text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Path } from 'object-path';
import { Component, Emit, Prop, Vue, Watch } from 'vue-property-decorator';
import { TableType } from '../../classes';
import { Column, IColumnDefinition } from '../../classes/column';
import { ESortDir, IDisplayHandlerParam, IDisplayHandlerResult } from '../../classes/handlers';
import { classValType, ensurePromise, mergeClassVals, namespaceEvent, TClassVal, TMaybePromise } from '../../utils';
import { VueDatatablePager } from '../vue-datatable-pager/vue-datatable-pager';
import template from './vue-datatable.html';
/**
* Parameters passed to the `data` function, to handle by custom logic.
*
* @tutorial ajax-data
*/
export interface IDataFnParams<TRow extends {}> {
filter: string | string[];
sortBy: Path | keyof TRow;
sortDir: ESortDir;
perPage: number;
page: number;
}
export interface ITableContentParam<TRow extends {}> {
rows: TRow[];
totalRowCount: number;
}
export type TDataFn<TRow extends {}> = ( ( search: IDataFnParams<TRow> ) => ITableContentParam<TRow> );
export type TColumnsDefinition<TRow extends {}> = Array<IColumnDefinition<TRow>>;
interface IPageRange {
/** Index of the first element of the page. 1-indexed */
from: number;
/** Index of the last element of the page. 1-indexed */
to: number;
/** The total number of items */
of: number;
}
/**
* The main component of the module, used to display a datatable.
*
* @vue-slot no-results Shown only if no rows are displayed
*
* @vue-slot default Used to render each row
* @vue-slot-param default row <TRow> - The current row to display.
* @vue-slot-param default index <number> - The current row index.
* @vue-slot-param default columns <Column[]> - The list of columns.
*
* @vue-slot footer Displayed at the bottom of the table.
* @vue-slot-param footer rows <TRow[]> - The current list of displayed rows.
* @vue-slot-param footer pagination <IPageRange> - The current pagination range of the table.
* @vue-slot-param footer columns <Column[]> - The list of columns.
*/
@Component( {
...template,
} )
export class VueDatatable<TRow extends {}, TSub extends VueDatatable<TRow, TSub>> extends Vue {
/**
* The name of the datatable. It should be unique per page.
*
* @vue-prop
*/
@Prop( { type: String, default: 'default' } ) public readonly name!: string;
/**
* Set to `true` to defer the initialization of the table after a pager has been attached. It may resolve issues related to double execution of data function.
*
* @vue-prop
*/
@Prop( { type: Boolean, default: false } ) public readonly waitForPager!: boolean;
/**
* List of columns definitions displayed by this datatable.
*
* @vue-prop
*/
@Prop( { type: Array, required: true } ) public readonly columns!: TColumnsDefinition<TRow>;
/**
* The list of items to display, or a getter function.
*
* @vue-prop
*/
@Prop( { required: true } ) public readonly data!: TRow[] | TDataFn<TRow> | unknown;
/**
* Value to match in rows for display filtering.
*
* @vue-prop
*/
@Prop( { type: [ String, Array ], default: null } ) public readonly filter!: string | string[];
/**
* Maximum number of rows displayed per page.
*
* @vue-prop
*/
@Prop( { type: Number, default: Infinity } ) public readonly perPage!: number;
/**
* Class(es) or getter function to get row classes.
*
* @vue-prop
*/
@Prop( { type: classValType.concat( [ Function ] ), default: null } ) public readonly rowClasses!: TClassVal | ( ( row: TRow ) => TClassVal ) | null;
/** Column used for data sorting. */
private sortBy: Column<TRow> | null = null;
/** Direction of the sort. A null value is equivalent to 'asc'. */
private sortDir: ESortDir | null = null;
// Pagination-related props & methods
/** Current page index. */
public page = 1;
/** Total number of rows contained by this data table. */
public totalRows = 0;
/** The total number of pages in the associated [[datatable]]. */
private get totalPages(): number | null {
if ( this.totalRows <= 0 || this.perPage <= 0 ) {
return 0;
} else if ( !isFinite( this.perPage ) ) {
return 1;
}
return Math.ceil( this.totalRows / this.perPage );
}
public get currentPageRange(): IPageRange {
if ( this.perPage === Infinity ) {
return {
from: 1,
of: this.totalRows,
to: this.totalRows + 1,
};
} else {
return {
from: Math.min( ( ( this.page - 1 ) * this.perPage ) + 1, Math.max( this.totalRows, 1 ) ),
of: this.totalRows,
to: Math.min( this.page * this.perPage, this.totalRows + 1 ),
};
}
}
/** Array of rows displayed by the table. */
public displayedRows: TRow[] = [];
/** Array of pagers that are linked to this table. */
public readonly pagers: Array<VueDatatablePager<any>> = [];
/** Array of columns definitions casted as [[Column]] objects. */
public get normalizedColumns() {
return this.columns.map( column => new Column( column ) );
}
/** Base CSS class to apply to the `<table>` element. */
public get tableClass() {
return mergeClassVals( this.tableType.setting( 'table.class' ), this.$attrs.class )
.join( ' ' );
}
protected readonly tableType!: TableType<any>;
public get handler() {
return this.tableType.handler;
}
public get identifier() {
return this.tableType.id;
}
/**
* Register the table in the global registry of tables.
* Additionnaly, it may wait for a pager before starting watch data properties.
*
* @vue-event vuejs-datatable::ready Emitted when the table has been initialized.
* @vue-event-param vuejs-datatable::ready tableName <string> - The table name.
*/
public created() {
this.$datatables[this.name] = this;
this.$root.$emit( namespaceEvent( 'ready' ), this.name );
// Defer to next tick, so a pager component created just after have the time to link itself with this table before start watching.
this.$nextTick( () => {
if ( this.waitForPager && this.pagers.length === 0 ) {
this.$on( namespaceEvent( 'pager-bound' ), () => this.initWatchCriterions() );
} else {
// tslint:disable-next-line: no-floating-promises
this.initWatchCriterions();
}
} );
}
/**
* Get the sort direction for a specific column.
*
* @param columnDefinition - The column to check sorting direction for.
* @returns the sort direction for the specified column.
*/
public getSortDirectionForColumn( columnDefinition: Column<TRow> ): ESortDir | null {
if ( this.sortBy !== columnDefinition ) {
return null;
}
return this.sortDir;
}
/**
* Defines the sort direction for a specific column.
*
* @param direction - The direction of the sort.
* @param column - The column to check sorting direction for.
* @returns nothing.
*/
public setSortDirectionForColumn( direction: ESortDir | null, column: Column<TRow> ): void {
this.sortBy = column;
this.sortDir = direction;
}
/**
* Internal function that retrieve data rows to display.
*
* @returns Promise resolved with total rows count and/or rows to display
*/
private processRowsIn(): TMaybePromise<IDisplayHandlerResult<TRow>> {
if ( typeof this.data === 'function' ) {
const params = {
filter: this.filter,
page: this.page,
perPage: this.perPage,
sortBy: this.sortBy ? this.sortBy.field : null,
sortDir: this.sortDir,
};
return this.data( params );
} else {
const outObj: Partial<IDisplayHandlerParam<TRow, any, any, any, any>> = { source: this.data };
return ensurePromise( this.handler.filterHandler( this.data as any, this.filter, this.normalizedColumns ) )
.then( filteredData => ensurePromise( this.handler.sortHandler( outObj.filtered = filteredData, this.sortBy, this.sortDir ) ) )
.then( sortedData => ensurePromise( this.handler.paginateHandler( outObj.sorted = sortedData, this.perPage, this.page ) ) )
.then( pagedData => ensurePromise( this.handler.displayHandler( { ...outObj, paged: pagedData } as IDisplayHandlerParam<TRow, any, any, any, any> ) ) );
}
}
/**
* Using data (or its return value if it is a function), filter, sort, paginate & display rows in the table.
*
* @returns a promise resolved once the processing is done, with nothing.
* @see DataFnParams Parameters provided to the `data` function.
* @tutorial ajax-data
*/
@Watch( 'data', { deep: true, immediate: false } )
@Watch( 'columns', { deep: true, immediate: false } )
public processRows(): Promise<void> {
return ensurePromise( this.processRowsIn() )
.then( tableContent => this.setTableContent( tableContent ) );
}
/**
* Defines the table content & total rows number. You can send none, a single, or both properties. Only non undefined prop will be set.
*
* @param content - The content to set.
* @returns nothing.
*/
private setTableContent( { rows, totalRowCount }: Partial<ITableContentParam<TRow>> = {} ): void {
if ( typeof rows === 'object' ) {
this.displayedRows = rows;
}
if ( typeof totalRowCount === 'number' ) {
this.totalRows = totalRowCount;
}
}
/**
* Propagate the `page-changed` event when the page data is changed.
*
* @vue-event vuejs-datatable::page-changed Emitted when the page has changed.
* @vue-event-param vuejs-datatable::page-changed newPage <number> - The index of the new page.
*/
@Watch( 'page', { immediate: true } )
@Emit( namespaceEvent( 'page-changed' ) )
public emitNewPage() {
return this.page;
}
/**
* Get the classes to add on the row
*
* @param row - The row to get classes for.
* @returns the classes string to set on the row.
*/
public getRowClasses( row: TRow ): string[] {
const rowClasses = typeof this.rowClasses === 'function' ? this.rowClasses( row ) : this.rowClasses;
const settingsClass = this.tableType.setting( 'table.row.class' );
return mergeClassVals( settingsClass, rowClasses );
}
/**
* Starts the watching of following properties: `filter`, `perPage`, `page`, `sortBy`, `sortDir`.
* When a change is detected, the component runs [[datatable#processRows]].
* Because the watch is immediate, [[datatable#processRows]] is run immediately when this method is called.
*
* @see datatable#processRows
* @see https://vuejs.org/v2/api/#vm-watch
* @returns nothing.
*/
private initWatchCriterions(): Promise<void> {
for ( const prop of [ 'filter', 'perPage', 'page', 'sortBy', 'sortDir' ] ) {
this.$watch( prop, this.processRows, { immediate: false, deep: true } );
}
return this.processRows();
}
/**
* Recalculates the new page count, and emit `page-count-changed` with the new count.
*
* @vue-event vuejs-datatable::page-count-changed Emitted when the page count has changed.
* @vue-event-param vuejs-datatable::page-count-changed newCount <number> - The new total number of pages.
*/
@Watch( 'totalRows' )
@Watch( 'perPage' )
@Emit( namespaceEvent( 'page-count-changed' ) )
public refreshPageCount() {
return this.totalPages;
}
/**
* Re-emit the current page.
*
* @vue-event vuejs-datatable::page-changed
*/
@Watch( 'page' )
@Emit( namespaceEvent( 'page-changed' ) )
public refreshPage() {
return this.page;
}
} | the_stack |
import test from 'japa'
import 'reflect-metadata'
import { ApplicationContract } from '@ioc:Adonis/Core/Application'
import { AuthManager } from '../src/AuthManager'
import { SessionGuard } from '../src/Guards/Session'
import { LucidProvider } from '../src/UserProviders/Lucid'
import { DatabaseProvider } from '../src/UserProviders/Database'
import { TokenRedisProvider } from '../src/TokenProviders/Redis'
import { TokenDatabaseProvider } from '../src/TokenProviders/Database'
import {
setup,
reset,
cleanup,
mockAction,
mockProperty,
getUserModel,
setupApplication,
getLucidProviderConfig,
getDatabaseProviderConfig,
} from '../test-helpers'
let app: ApplicationContract
test.group('Auth', (group) => {
group.before(async () => {
app = await setupApplication()
await setup(app)
})
group.after(async () => {
await cleanup(app)
})
group.afterEach(async () => {
await reset(app)
})
test('make and cache instance of the session guard', (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const manager = new AuthManager(app, {
guard: 'session',
guards: {
api: {
driver: 'oat',
tokenProvider: {
driver: 'database',
table: 'api_tokens',
},
provider: getLucidProviderConfig({ model: async () => User }),
},
basic: {
driver: 'basic',
provider: getLucidProviderConfig({ model: async () => User }),
},
session: {
driver: 'session',
provider: getLucidProviderConfig({ model: async () => User }),
},
sessionDb: {
driver: 'session',
provider: getDatabaseProviderConfig(),
},
},
})
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {})
const auth = manager.getAuthForRequest(ctx)
const mapping = auth.use('session')
mapping['isCached'] = true
assert.equal(auth.use('session')['isCached'], true)
assert.instanceOf(mapping, SessionGuard)
assert.instanceOf(mapping.provider, LucidProvider)
})
test('proxy all methods to the default driver', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const manager = new AuthManager(app, {
guard: 'custom',
guards: {
custom: {
driver: 'custom',
provider: getLucidProviderConfig({ model: async () => User }),
},
session: {
driver: 'session',
provider: getLucidProviderConfig({ model: async () => User }),
},
sessionDb: {
driver: 'session',
provider: getDatabaseProviderConfig(),
},
},
} as any)
class CustomGuard {}
const guardInstance = new CustomGuard()
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {})
const auth = manager.getAuthForRequest(ctx)
manager.extend('guard', 'custom', () => {
return guardInstance as any
})
/**
* Test attempt
*/
mockAction(
guardInstance,
'attempt',
function (uid: string, secret: string, rememberMe: boolean) {
assert.equal(uid, 'foo')
assert.equal(secret, 'secret')
assert.equal(rememberMe, true)
}
)
await auth.attempt('foo', 'secret', true)
/**
* Test verify credentails
*/
mockAction(guardInstance, 'verifyCredentials', function (uid: string, secret: string) {
assert.equal(uid, 'foo')
assert.equal(secret, 'secret')
})
await auth.verifyCredentials('foo', 'secret')
/**
* Test login
*/
mockAction(guardInstance, 'login', function (user: any, rememberMe: boolean) {
assert.deepEqual(user, { id: 1 })
assert.equal(rememberMe, true)
})
await auth.login({ id: 1 }, true)
/**
* Test loginViaId
*/
mockAction(guardInstance, 'loginViaId', function (id: number, rememberMe: boolean) {
assert.deepEqual(id, 1)
assert.equal(rememberMe, true)
})
await auth.loginViaId(1, true)
/**
* Test logout
*/
mockAction(guardInstance, 'logout', function (renewToken: boolean) {
assert.equal(renewToken, true)
})
await auth.logout(true)
/**
* Test authenticate
*/
mockAction(guardInstance, 'authenticate', function () {
assert.isTrue(true)
})
await auth.authenticate()
/**
* Test check
*/
mockAction(guardInstance, 'check', function () {
assert.isTrue(true)
})
await auth.check()
/**
* Test isGuest
*/
mockProperty(guardInstance, 'isGuest', false)
assert.isFalse(auth.isGuest)
/**
* Test user
*/
mockProperty(guardInstance, 'user', { id: 1 })
assert.deepEqual(auth.user, { id: 1 })
/**
* Test isLoggedIn
*/
mockProperty(guardInstance, 'isLoggedIn', true)
assert.isTrue(auth.isLoggedIn)
/**
* Test isLoggedOut
*/
mockProperty(guardInstance, 'isLoggedOut', true)
assert.isTrue(auth.isLoggedOut)
/**
* Test authenticationAttempted
*/
mockProperty(guardInstance, 'authenticationAttempted', true)
assert.isTrue(auth.authenticationAttempted)
})
test('update default guard', (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const manager = new AuthManager(app, {
guard: 'session',
guards: {
session: {
driver: 'session',
provider: getLucidProviderConfig({ model: async () => User }),
},
basic: {
driver: 'basic',
provider: getLucidProviderConfig({ model: async () => User }),
},
api: {
driver: 'oat',
tokenProvider: {
driver: 'database',
table: 'api_tokens',
},
provider: getLucidProviderConfig({ model: async () => User }),
},
sessionDb: {
driver: 'session',
provider: getDatabaseProviderConfig(),
},
},
})
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {})
const auth = manager.getAuthForRequest(ctx)
auth.defaultGuard = 'sessionDb'
assert.equal(auth.name, 'sessionDb')
assert.instanceOf(auth.provider, DatabaseProvider)
})
test('serialize toJSON', (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const manager = new AuthManager(app, {
guard: 'session',
guards: {
session: {
driver: 'session',
provider: getLucidProviderConfig({ model: async () => User }),
},
api: {
driver: 'oat',
tokenProvider: {
driver: 'database',
table: 'api_tokens',
},
provider: getLucidProviderConfig({ model: async () => User }),
},
basic: {
driver: 'basic',
provider: getLucidProviderConfig({ model: async () => User }),
},
sessionDb: {
driver: 'session',
provider: getDatabaseProviderConfig(),
},
},
})
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {})
const auth = manager.getAuthForRequest(ctx)
auth.defaultGuard = 'sessionDb'
auth.use()
assert.deepEqual(auth.toJSON(), {
defaultGuard: 'sessionDb',
guards: {
sessionDb: {
isLoggedIn: false,
isGuest: true,
viaRemember: false,
user: undefined,
authenticationAttempted: false,
isAuthenticated: false,
},
},
})
})
test('make oat guard', (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const manager = new AuthManager(app, {
guard: 'api',
guards: {
api: {
driver: 'oat',
tokenProvider: {
driver: 'database',
table: 'api_tokens',
},
provider: getLucidProviderConfig({ model: async () => User }),
},
basic: {
driver: 'basic',
provider: getLucidProviderConfig({ model: async () => User }),
},
session: {
driver: 'session',
provider: getLucidProviderConfig({ model: async () => User }),
},
sessionDb: {
driver: 'session',
provider: getDatabaseProviderConfig(),
},
},
})
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {})
const auth = manager.getAuthForRequest(ctx).use('api')
assert.equal(auth.name, 'api')
assert.instanceOf(auth.provider, LucidProvider)
assert.instanceOf(auth.tokenProvider, TokenDatabaseProvider)
})
test('make oat guard with redis driver', (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const manager = new AuthManager(app, {
guard: 'api',
guards: {
api: {
driver: 'oat',
tokenProvider: {
driver: 'redis',
redisConnection: 'local',
},
provider: getLucidProviderConfig({ model: async () => User }),
},
basic: {
driver: 'basic',
provider: getLucidProviderConfig({ model: async () => User }),
},
session: {
driver: 'session',
provider: getLucidProviderConfig({ model: async () => User }),
},
sessionDb: {
driver: 'session',
provider: getDatabaseProviderConfig(),
},
},
})
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {})
const auth = manager.getAuthForRequest(ctx).use('api')
assert.equal(auth.name, 'api')
assert.instanceOf(auth.provider, LucidProvider)
assert.instanceOf(auth.tokenProvider, TokenRedisProvider)
})
test('return user_id when foreignKey is missing', (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const manager = new AuthManager(app, {
guard: 'api',
guards: {
api: {
driver: 'oat',
tokenProvider: {
driver: 'database',
table: 'api_tokens',
},
provider: getLucidProviderConfig({ model: async () => User }),
},
basic: {
driver: 'basic',
provider: getLucidProviderConfig({ model: async () => User }),
},
session: {
driver: 'session',
provider: getLucidProviderConfig({ model: async () => User }),
},
sessionDb: {
driver: 'session',
provider: getDatabaseProviderConfig(),
},
},
})
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {})
const auth = manager.getAuthForRequest(ctx).use('api')
assert.instanceOf(auth.tokenProvider, TokenDatabaseProvider)
assert.equal(auth.tokenProvider.foreignKey, 'user_id')
})
test('return the foreignKey when not missing', (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const manager = new AuthManager(app, {
guard: 'api',
guards: {
api: {
driver: 'oat',
tokenProvider: {
driver: 'database',
table: 'api_tokens',
foreignKey: 'account_id',
},
provider: getLucidProviderConfig({ model: async () => User }),
},
basic: {
driver: 'basic',
provider: getLucidProviderConfig({ model: async () => User }),
},
session: {
driver: 'session',
provider: getLucidProviderConfig({ model: async () => User }),
},
sessionDb: {
driver: 'session',
provider: getDatabaseProviderConfig(),
},
},
})
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {})
const auth = manager.getAuthForRequest(ctx).use('api')
assert.instanceOf(auth.tokenProvider, TokenDatabaseProvider)
assert.equal(auth.tokenProvider.foreignKey, 'account_id')
})
}) | the_stack |
import {CrA11yAnnouncerElement} from 'chrome://resources/cr_elements/cr_a11y_announcer/cr_a11y_announcer.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {afterNextRender, html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {ReadLaterApiProxy, ReadLaterApiProxyImpl} from '../read_later_api_proxy.js';
import {BookmarkFolderElement, FOLDER_OPEN_CHANGED_EVENT, getBookmarkFromElement, isBookmarkFolderElement} from './bookmark_folder.js';
import {BookmarksApiProxy, BookmarksApiProxyImpl} from './bookmarks_api_proxy.js';
import {BookmarksDragManager} from './bookmarks_drag_manager.js';
// Key for localStorage object that refers to all the open folders.
export const LOCAL_STORAGE_OPEN_FOLDERS_KEY = 'openFolders';
function getBookmarkName(bookmark: chrome.bookmarks.BookmarkTreeNode): string {
return bookmark.title || bookmark.url || '';
}
export class BookmarksListElement extends PolymerElement {
static get is() {
return 'bookmarks-list';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
folders_: {
type: Array,
value: () => [],
},
hoverVisible: {
reflectToAttribute: true,
value: false,
},
openFolders_: {
type: Array,
value: () => [],
},
};
}
private bookmarksApi_: BookmarksApiProxy =
BookmarksApiProxyImpl.getInstance();
private bookmarksDragManager_: BookmarksDragManager =
new BookmarksDragManager(this);
private readLaterApi_: ReadLaterApiProxy =
ReadLaterApiProxyImpl.getInstance();
private listeners_ = new Map<string, Function>();
private folders_: chrome.bookmarks.BookmarkTreeNode[];
hoverVisible: boolean;
private openFolders_: string[];
ready() {
super.ready();
this.addEventListener(
FOLDER_OPEN_CHANGED_EVENT,
e => this.onFolderOpenChanged_(
e as CustomEvent<{id: string, open: boolean}>));
this.addEventListener('keydown', e => this.onKeydown_(e));
this.addEventListener('pointermove', () => this.hoverVisible = true);
this.addEventListener('pointerleave', () => this.hoverVisible = false);
}
connectedCallback() {
super.connectedCallback();
this.setAttribute('role', 'tree');
this.bookmarksApi_.getFolders().then(folders => {
this.folders_ = folders;
this.addListener_(
'onChildrenReordered',
(id: string, reorderedInfo: chrome.bookmarks.ReorderInfo) =>
this.onChildrenReordered_(id, reorderedInfo));
this.addListener_(
'onChanged',
(id: string, changedInfo: chrome.bookmarks.ChangeInfo) =>
this.onChanged_(id, changedInfo));
this.addListener_(
'onCreated',
(_id: string, node: chrome.bookmarks.BookmarkTreeNode) =>
this.onCreated_(node));
this.addListener_(
'onMoved',
(_id: string, movedInfo: chrome.bookmarks.MoveInfo) =>
this.onMoved_(movedInfo));
this.addListener_('onRemoved', (id: string) => this.onRemoved_(id));
try {
const openFolders = window.localStorage[LOCAL_STORAGE_OPEN_FOLDERS_KEY];
this.openFolders_ = JSON.parse(openFolders);
} catch (error) {
this.openFolders_ = [this.folders_[0]!.id];
window.localStorage[LOCAL_STORAGE_OPEN_FOLDERS_KEY] =
JSON.stringify(this.openFolders_);
}
this.bookmarksDragManager_.startObserving();
});
if (loadTimeData.getBoolean('unifiedSidePanel')) {
// Show the UI as soon as the app is connected.
this.readLaterApi_.showUI();
}
}
disconnectedCallback() {
for (const [eventName, callback] of this.listeners_.entries()) {
this.bookmarksApi_.callbackRouter[eventName]!.removeListener(callback);
}
this.bookmarksDragManager_.stopObserving();
}
/** BookmarksDragDelegate */
getAscendants(bookmarkId: string): string[] {
const path = this.findPathToId_(bookmarkId);
return path.map(bookmark => bookmark.id);
}
/** BookmarksDragDelegate */
getIndex(bookmark: chrome.bookmarks.BookmarkTreeNode): number {
const path = this.findPathToId_(bookmark.id);
const parent = path[path.length - 2];
if (!parent || !parent.children) {
return -1;
}
return parent.children.findIndex((child) => child.id === bookmark.id);
}
/** BookmarksDragDelegate */
isFolderOpen(bookmark: chrome.bookmarks.BookmarkTreeNode): boolean {
return this.openFolders_.some(id => bookmark.id === id);
}
/** BookmarksDragDelegate */
onFinishDrop(bookmarks: chrome.bookmarks.BookmarkTreeNode[]): void {
if (bookmarks.length === 0 || bookmarks[0]!.id === undefined) {
return;
}
this.focusBookmark_(bookmarks[0]!.id);
this.hoverVisible = false;
}
/** BookmarksDragDelegate */
openFolder(folderId: string) {
this.changeFolderOpenStatus_(folderId, true);
}
private addListener_(eventName: string, callback: Function): void {
this.bookmarksApi_.callbackRouter[eventName]!.addListener(callback);
this.listeners_.set(eventName, callback);
}
/**
* Finds the node within the nested array of folders and returns the path to
* the node in the tree.
*/
private findPathToId_(id: string): chrome.bookmarks.BookmarkTreeNode[] {
const path: chrome.bookmarks.BookmarkTreeNode[] = [];
function findPathByIdInternal_(
id: string, node: chrome.bookmarks.BookmarkTreeNode) {
if (node.id === id) {
path.push(node);
return true;
}
if (!node.children) {
return false;
}
path.push(node);
const foundInChildren =
node.children.some(child => findPathByIdInternal_(id, child));
if (!foundInChildren) {
path.pop();
}
return foundInChildren;
}
this.folders_.some(folder => findPathByIdInternal_(id, folder));
return path;
}
/**
* Reduces an array of nodes to a string to notify Polymer of changes to the
* nested array.
*/
private getPathString_(path: chrome.bookmarks.BookmarkTreeNode[]): string {
return path.reduce((reducedString, pathItem, index) => {
if (index === 0) {
return `folders_.${this.folders_.indexOf(pathItem)}`;
}
const parent = path[index - 1];
return `${reducedString}.children.${parent!.children!.indexOf(pathItem)}`;
}, '');
}
private onChanged_(id: string, changedInfo: chrome.bookmarks.ChangeInfo) {
const path = this.findPathToId_(id);
Object.assign(path[path.length - 1], changedInfo);
const pathString = this.getPathString_(path);
Object.keys(changedInfo)
.forEach(key => this.notifyPath(`${pathString}.${key}`));
}
private onChildrenReordered_(
id: string, reorderedInfo: chrome.bookmarks.ReorderInfo) {
const path = this.findPathToId_(id);
const parent = path[path.length - 1];
const childById = parent!.children!.reduce((map, node) => {
map.set(node.id, node);
return map;
}, new Map());
parent!.children = reorderedInfo.childIds.map(id => childById.get(id));
const pathString = this.getPathString_(path);
this.notifyPath(`${pathString}.children`);
}
private onCreated_(node: chrome.bookmarks.BookmarkTreeNode) {
const pathToParent = this.findPathToId_(node.parentId as string);
const pathToParentString = this.getPathString_(pathToParent);
const parent = pathToParent[pathToParent.length - 1];
if (parent && !parent.children) {
// Newly created folders in this session may not have an array of
// children yet, so create an empty one.
parent.children = [];
}
this.splice(`${pathToParentString}.children`, node.index!, 0, node);
afterNextRender(this, () => {
this.focusBookmark_(node.id);
CrA11yAnnouncerElement.getInstance().announce(
loadTimeData.getStringF('bookmarkCreated', getBookmarkName(node)));
});
}
private changeFolderOpenStatus_(id: string, open: boolean) {
const alreadyOpenIndex = this.openFolders_.indexOf(id);
if (open && alreadyOpenIndex === -1) {
this.openFolders_.push(id);
} else if (!open) {
this.openFolders_.splice(alreadyOpenIndex, 1);
}
// Assign to a new array so that listeners are triggered.
this.openFolders_ = [...this.openFolders_];
window.localStorage[LOCAL_STORAGE_OPEN_FOLDERS_KEY] =
JSON.stringify(this.openFolders_);
}
private onFolderOpenChanged_(event: CustomEvent) {
const {id, open} = event.detail;
this.changeFolderOpenStatus_(id, open);
}
private onKeydown_(event: KeyboardEvent) {
if (['ArrowDown', 'ArrowUp'].includes(event.key)) {
this.handleArrowKeyNavigation_(event);
return;
}
if (!event.ctrlKey && !event.metaKey) {
return;
}
event.preventDefault();
const eventTarget = event.composedPath()[0] as HTMLElement;
const bookmarkData = getBookmarkFromElement(eventTarget);
if (!bookmarkData) {
return;
}
if (event.key === 'x') {
this.bookmarksApi_.cutBookmark(bookmarkData.id);
} else if (event.key === 'c') {
this.bookmarksApi_.copyBookmark(bookmarkData.id);
CrA11yAnnouncerElement.getInstance().announce(loadTimeData.getStringF(
'bookmarkCopied', getBookmarkName(bookmarkData)));
} else if (event.key === 'v') {
if (isBookmarkFolderElement(eventTarget)) {
this.bookmarksApi_.pasteToBookmark(bookmarkData.id);
} else {
this.bookmarksApi_.pasteToBookmark(
bookmarkData.parentId!, bookmarkData.id);
}
}
}
private handleArrowKeyNavigation_(event: KeyboardEvent) {
if (!(this.shadowRoot!.activeElement instanceof BookmarkFolderElement)) {
// If the key event did not happen within a BookmarkFolderElement, do
// not do anything.
return;
}
// Prevent arrow keys from causing scroll.
event.preventDefault();
const allFolderElements: BookmarkFolderElement[] =
Array.from(this.shadowRoot!.querySelectorAll('bookmark-folder'));
const delta = event.key === 'ArrowUp' ? -1 : 1;
let currentIndex =
allFolderElements.indexOf(this.shadowRoot!.activeElement);
let focusHasMoved = false;
while (!focusHasMoved) {
focusHasMoved = allFolderElements[currentIndex]!.moveFocus(delta);
currentIndex = (currentIndex + delta + allFolderElements.length) %
allFolderElements.length;
}
}
private onMoved_(movedInfo: chrome.bookmarks.MoveInfo) {
// Get old path and remove node from oldParent at oldIndex.
const oldParentPath = this.findPathToId_(movedInfo.oldParentId);
const oldParentPathString = this.getPathString_(oldParentPath);
const oldParent = oldParentPath[oldParentPath.length - 1];
const movedNode = oldParent!.children![movedInfo.oldIndex]!;
Object.assign(
movedNode, {index: movedInfo.index, parentId: movedInfo.parentId});
this.splice(`${oldParentPathString}.children`, movedInfo.oldIndex, 1);
// Get new parent's path and add the node to the new parent at index.
const newParentPath = this.findPathToId_(movedInfo.parentId);
const newParentPathString = this.getPathString_(newParentPath);
const newParent = newParentPath[newParentPath.length - 1];
if (newParent && !newParent.children) {
newParent.children = [];
}
this.splice(
`${newParentPathString}.children`, movedInfo.index, 0, movedNode);
if (movedInfo.oldParentId === movedInfo.parentId) {
CrA11yAnnouncerElement.getInstance().announce(loadTimeData.getStringF(
'bookmarkReordered', getBookmarkName(movedNode)));
} else {
CrA11yAnnouncerElement.getInstance().announce(loadTimeData.getStringF(
'bookmarkMoved', getBookmarkName(movedNode),
getBookmarkName(newParent!)));
}
}
private onRemoved_(id: string) {
const oldPath = this.findPathToId_(id);
const removedNode = oldPath.pop()!;
const oldParent = oldPath[oldPath.length - 1]!;
const oldParentPathString = this.getPathString_(oldPath);
this.splice(
`${oldParentPathString}.children`,
oldParent.children!.indexOf(removedNode), 1);
CrA11yAnnouncerElement.getInstance().announce(loadTimeData.getStringF(
'bookmarkDeleted', getBookmarkName(removedNode)));
}
private focusBookmark_(id: string) {
const path = this.findPathToId_(id);
if (path.length === 0) {
// Could not find bookmark.
return;
}
const rootBookmark = path.shift();
const rootBookmarkElement =
this.shadowRoot!.querySelector(`#bookmark-${rootBookmark!.id}`) as
BookmarkFolderElement;
if (!rootBookmarkElement) {
return;
}
const bookmarkElement = rootBookmarkElement.getFocusableElement(path);
if (bookmarkElement) {
bookmarkElement.focus();
}
}
}
declare global {
interface HTMLElementTagNameMap {
'bookmarks-list': BookmarksListElement;
}
}
customElements.define(BookmarksListElement.is, BookmarksListElement); | the_stack |
* @fileoverview Implements utilities for notations for menclose elements
*
* @author dpvc@mathjax.org (Davide Cervone)
*/
import {AnyWrapper} from './Wrapper.js';
import {CommonMenclose} from './Wrappers/menclose.js';
/*****************************************************************/
export const ARROWX = 4, ARROWDX = 1, ARROWY = 2; // default relative arrowhead values
export const THICKNESS = .067; // default rule thickness
export const PADDING = .2; // default padding
export const SOLID = THICKNESS + 'em solid'; // a solid border
/*****************************************************************/
/**
* Shorthand for CommonMenclose
*/
export type Menclose = CommonMenclose<any, any, any>;
/**
* Top, right, bottom, left padding data
*/
export type PaddingData = [number, number, number, number];
/**
* The functions used for notation definitions
*
* @templare N The DOM node class
*/
export type Renderer<W extends AnyWrapper, N> = (node: W, child: N) => void;
export type BBoxExtender<W extends AnyWrapper> = (node: W) => PaddingData;
export type BBoxBorder<W extends AnyWrapper> = (node: W) => PaddingData;
export type Initializer<W extends AnyWrapper> = (node: W) => void;
/**
* The definition of a notation
*
* @template W The menclose wrapper class
* @templare N The DOM node class
*/
export type NotationDef<W extends AnyWrapper, N> = {
renderer: Renderer<W, N>; // renders the DOM nodes for the notation
bbox: BBoxExtender<W>; // gives the offsets to the child bounding box: [top, right, bottom, left]
border?: BBoxBorder<W>; // gives the amount of the bbox offset that is due to borders on the child
renderChild?: boolean; // true if the notation is used to render the child directly (e.g., radical)
init?: Initializer<W>; // function to be called during wrapper construction
remove?: string; // list of notations that are suppressed by this one
};
/**
* For defining notation maps
*
* @template W The menclose wrapper class
* @templare N The DOM node class
*/
export type DefPair<W extends AnyWrapper, N> = [string, NotationDef<W, N>];
export type DefList<W extends AnyWrapper, N> = Map<string, NotationDef<W, N>>;
export type DefPairF<T, W extends AnyWrapper, N> = (name: T) => DefPair<W, N>;
/**
* The list of notations for an menclose element
*
* @template W The menclose wrapper class
* @templare N The DOM node class
*/
export type List<W extends AnyWrapper, N> = {[notation: string]: NotationDef<W, N>};
/*****************************************************************/
/**
* The names and indices of sides for borders, padding, etc.
*/
export const sideIndex = {top: 0, right: 1, bottom: 2, left: 3};
export type Side = keyof typeof sideIndex;
export const sideNames = Object.keys(sideIndex) as Side[];
/**
* Common BBox and Border functions
*/
export const fullBBox = ((node) => new Array(4).fill(node.thickness + node.padding)) as BBoxExtender<Menclose>;
export const fullPadding = ((node) => new Array(4).fill(node.padding)) as BBoxExtender<Menclose>;
export const fullBorder = ((node) => new Array(4).fill(node.thickness)) as BBoxBorder<Menclose>;
/*****************************************************************/
/**
* The length of an arrowhead
*/
export const arrowHead = (node: Menclose) => {
return Math.max(node.padding, node.thickness * (node.arrowhead.x + node.arrowhead.dx + 1));
};
/**
* Adjust short bbox for tall arrow heads
*/
export const arrowBBoxHD = (node: Menclose, TRBL: PaddingData) => {
if (node.childNodes[0]) {
const {h, d} = node.childNodes[0].getBBox();
TRBL[0] = TRBL[2] = Math.max(0, node.thickness * node.arrowhead.y - (h + d) / 2);
}
return TRBL;
};
/**
* Adjust thin bbox for wide arrow heads
*/
export const arrowBBoxW = (node: Menclose, TRBL: PaddingData) => {
if (node.childNodes[0]) {
const {w} = node.childNodes[0].getBBox();
TRBL[1] = TRBL[3] = Math.max(0, node.thickness * node.arrowhead.y - w / 2);
}
return TRBL;
};
/**
* The data for horizontal and vertical arrow notations
* [angle, double, isVertical, remove]
*/
export const arrowDef = {
up: [-Math.PI / 2, false, true, 'verticalstrike'],
down: [ Math.PI / 2, false, true, 'verticakstrike'],
right: [ 0, false, false, 'horizontalstrike'],
left: [ Math.PI, false, false, 'horizontalstrike'],
updown: [ Math.PI / 2, true, true, 'verticalstrike uparrow downarrow'],
leftright: [ 0, true, false, 'horizontalstrike leftarrow rightarrow']
} as {[name: string]: [number, boolean, boolean, string]};
/**
* The data for diagonal arrow notations
* [c, pi, double, remove]
*/
export const diagonalArrowDef = {
updiagonal: [-1, 0, false, 'updiagonalstrike northeastarrow'],
northeast: [-1, 0, false, 'updiagonalstrike updiagonalarrow'],
southeast: [ 1, 0, false, 'downdiagonalstrike'],
northwest: [ 1, Math.PI, false, 'downdiagonalstrike'],
southwest: [-1, Math.PI, false, 'updiagonalstrike'],
northeastsouthwest: [-1, 0, true, 'updiagonalstrike northeastarrow updiagonalarrow southwestarrow'],
northwestsoutheast: [ 1, 0, true, 'downdiagonalstrike northwestarrow southeastarrow']
} as {[name: string]: [number, number, boolean, string]};
/**
* The BBox functions for horizontal and vertical arrows
*/
export const arrowBBox = {
up: (node) => arrowBBoxW(node, [arrowHead(node), 0, node.padding, 0]),
down: (node) => arrowBBoxW(node, [node.padding, 0, arrowHead(node), 0]),
right: (node) => arrowBBoxHD(node, [0, arrowHead(node), 0, node.padding]),
left: (node) => arrowBBoxHD(node, [0, node.padding, 0, arrowHead(node)]),
updown: (node) => arrowBBoxW(node, [arrowHead(node), 0, arrowHead(node), 0]),
leftright: (node) => arrowBBoxHD(node, [0, arrowHead(node), 0, arrowHead(node)])
} as {[name: string]: BBoxExtender<Menclose>};
/*****************************************************************/
/**
* @param {Renderer} render The function for adding the border to the node
* @return {string => DefPair} The function returingn the notation definition
* for the notation having a line on the given side
*/
export const CommonBorder = function<W extends Menclose, N>(render: Renderer<W, N>): DefPairF<Side, W, N> {
/**
* @param {string} side The side on which a border should appear
* @return {DefPair} The notation definition for the notation having a line on the given side
*/
return (side: Side) => {
const i = sideIndex[side];
return [side, {
//
// Add the border to the main child object
//
renderer: render,
//
// Indicate the extra space on the given side
//
bbox: (node) => {
const bbox = [0, 0, 0, 0] as PaddingData;
bbox[i] = node.thickness + node.padding;
return bbox;
},
//
// Indicate the border on the given side
//
border: (node) => {
const bbox = [0, 0, 0, 0] as PaddingData;
bbox[i] = node.thickness;
return bbox;
}
}];
};
};
/**
* @param {Renderer} render The function for adding the borders to the node
* @return {(sring, Side, Side) => DefPair} The function returning the notation definition
* for the notation having lines on two sides
*/
export const CommonBorder2 = function<W extends Menclose, N>(render: Renderer<W, N>):
(name: string, side1: Side, side2: Side) => DefPair<W, N> {
/**
* @param {string} name The name of the notation to define
* @param {Side} side1 The first side to get a border
* @param {Side} side2 The second side to get a border
* @return {DefPair} The notation definition for the notation having lines on two sides
*/
return (name: string, side1: Side, side2: Side) => {
const i1 = sideIndex[side1];
const i2 = sideIndex[side2];
return [name, {
//
// Add the border along the given sides
//
renderer: render,
//
// Mark the extra space along the two sides
//
bbox: (node) => {
const t = node.thickness + node.padding;
const bbox = [0, 0, 0, 0] as PaddingData;
bbox[i1] = bbox[i2] = t;
return bbox;
},
//
// Indicate the border on the two sides
//
border: (node) => {
const bbox = [0, 0, 0, 0] as PaddingData;
bbox[i1] = bbox[i2] = node.thickness;
return bbox;
},
//
// Remove the single side notations, if present
//
remove: side1 + ' ' + side2
}];
};
};
/*****************************************************************/
/**
* @param {string => Renderer} render The function for adding the strike to the node
* @return {string => DefPair} The function returning the notation definition for the diagonal strike
*/
export const CommonDiagonalStrike = function<W extends Menclose, N>(render: (sname: string) => Renderer<W, N>):
DefPairF<string, W, N> {
/**
* @param {string} name The name of the diagonal strike to define
* @return {DefPair} The notation definition for the diagonal strike
*/
return (name: string) => {
const cname = 'mjx-' + name.charAt(0) + 'strike';
return [name + 'diagonalstrike', {
//
// Find the angle and width from the bounding box size and create the diagonal line
//
renderer: render(cname),
//
// Add padding all around
//
bbox: fullBBox
}];
};
};
/*****************************************************************/
/**
* @param {Renderer} render The function to add the arrow to the node
* @return {string => DefPair} The funciton returning the notation definition for the diagonal arrow
*/
export const CommonDiagonalArrow = function<W extends Menclose, N>(render: Renderer<W, N>): DefPairF<string, W, N> {
/**
* @param {string} name The name of the diagonal arrow to define
* @return {DefPair} The notation definition for the diagonal arrow
*/
return (name: string) => {
const [c, pi, double, remove] = diagonalArrowDef[name];
return [name + 'arrow', {
//
// Find the angle and width from the bounding box size and create
// the arrow from them and the other arrow data
//
renderer: (node, _child) => {
const [a, W] = node.arrowAW();
const arrow = node.arrow(W, c * (a - pi), double);
render(node, arrow);
},
//
// Add space for the arrowhead all around
//
bbox: (node) => {
const {a, x, y} = node.arrowData();
const [ax, ay, adx] = [node.arrowhead.x, node.arrowhead.y, node.arrowhead.dx];
const [b, ar] = node.getArgMod(ax + adx, ay);
const dy = y + (b > a ? node.thickness * ar * Math.sin(b - a) : 0);
const dx = x + (b > Math.PI / 2 - a ? node.thickness * ar * Math.sin(b + a - Math.PI / 2) : 0);
return [dy, dx, dy, dx];
},
//
// Remove redundant notations
//
remove: remove
}];
};
};
/**
* @param {Renderer} render The function to add the arrow to the node
* @return {string => DefPair} The function returning the notation definition for the arrow
*/
export const CommonArrow = function<W extends Menclose, N>(render: Renderer<W, N>): DefPairF<string, W, N> {
/**
* @param {string} name The name of the horizontal or vertical arrow to define
* @return {DefPair} The notation definition for the arrow
*/
return (name: string) => {
const [angle, double, isVertical, remove] = arrowDef[name];
return [name + 'arrow', {
//
// Get the arrow height and depth from the bounding box and the arrow direction
// then create the arrow from that and the other data
//
renderer: (node, _child) => {
const {w, h, d} = node.getBBox();
const [W, offset] = (isVertical ? [h + d, 'X'] : [w, 'Y']);
const dd = node.getOffset(offset);
const arrow = node.arrow(W, angle, double, offset, dd);
render(node, arrow);
},
//
// Add the padding to the proper sides
//
bbox: arrowBBox[name],
//
// Remove redundant notations
//
remove: remove
}];
};
}; | the_stack |
import {ControllerClass} from '@loopback/core';
import {model, property} from '@loopback/repository';
import {
Client,
createRestAppClient,
expect,
givenHttpServerConfig,
} from '@loopback/testlab';
import {
api,
getJsonSchema,
jsonToSchemaObject,
post,
requestBody,
RestApplication,
RestBindings,
SchemaObject,
ValidationOptions,
} from '../../..';
import {aBodySpec} from '../../helpers';
describe('Validation at REST level', () => {
let app: RestApplication;
let client: Client;
@model()
class Product {
@property()
id: number;
@property({required: true})
name: string;
// NOTE(rfeng): We have to add `type: 'string'` to `@property` as
// `string | null` removes TypeScript design:type reflection
@property({required: false, type: 'string', jsonSchema: {nullable: true}})
description?: string | null;
@property({
required: true,
jsonSchema: {
range: [0, 100],
errorMessage: {range: 'price must be in range 0 to 100'},
},
})
price: number;
constructor(data: Partial<Product>) {
Object.assign(this, data);
}
}
const PRODUCT_SPEC: SchemaObject = jsonToSchemaObject(getJsonSchema(Product));
// Add a schema that requires `description`
const PRODUCT_SPEC_WITH_DESCRIPTION: SchemaObject = {
...PRODUCT_SPEC,
};
PRODUCT_SPEC_WITH_DESCRIPTION.required =
PRODUCT_SPEC.required!.concat('description');
context('with properties excluded from schema', () => {
before(() => {
const schema: SchemaObject = jsonToSchemaObject(
getJsonSchema(Product, {exclude: ['id']}),
);
class ProductController {
@post('/products')
async create(
@requestBody(aBodySpec(schema))
data: object,
): Promise<Product> {
return new Product(data);
}
}
return givenAnAppAndAClient(ProductController);
});
after(() => app.stop());
it('rejects request bodies containing excluded properties', async () => {
const {body} = await client
.post('/products')
.type('json')
.send({id: 1, name: 'a-product-name', price: 1})
.expect(422);
expect(body.error).to.containEql({
code: 'VALIDATION_FAILED',
details: [
{
path: '',
code: 'additionalProperties',
message: 'must NOT have additional properties',
info: {additionalProperty: 'id'},
},
],
});
});
});
// This is the standard use case that most LB4 applications should use.
// The request body specification is inferred from a decorated model class.
context('for request body specified via model definition', () => {
class ProductController {
@post('/products')
async create(
@requestBody({required: true}) data: Product,
): Promise<Product> {
return new Product(data);
}
}
before(() => givenAnAppAndAClient(ProductController));
after(() => app.stop());
it('accepts valid values', () => serverAcceptsValidRequestBody());
it('rejects missing required properties', () =>
serverRejectsRequestWithMissingRequiredValues());
it('rejects requests with no body', async () => {
// An empty body is now parsed as `undefined`
await client.post('/products').type('json').expect(400);
});
it('rejects requests with empty json body', async () => {
await client.post('/products').type('json').send('{}').expect(422);
});
it('rejects requests with empty string body', async () => {
await client.post('/products').type('json').send('""').expect(422);
});
it('rejects requests with string body', async () => {
await client.post('/products').type('json').send('"pencils"').expect(422);
});
it('rejects requests with null body', async () => {
await client.post('/products').type('json').send('null').expect(400);
});
});
context('with request body validation options', () => {
class ProductController {
@post('/products')
async create(
@requestBody({required: true}) data: Product,
): Promise<Product> {
return new Product(data);
}
}
before(() =>
givenAnAppAndAClient(ProductController, {
compiledSchemaCache: new WeakMap(),
ajvKeywords: ['range'],
}),
);
after(() => app.stop());
it('rejects requests with price out of range', async () => {
const DATA = {
name: 'iPhone',
description: 'iPhone',
price: 200,
};
const res = await client.post('/products').send(DATA).expect(422);
expect(res.body).to.eql({
error: {
statusCode: 422,
name: 'UnprocessableEntityError',
message:
'The request body is invalid. See error object `details` property for more info.',
code: 'VALIDATION_FAILED',
details: [
{
path: '/price',
code: 'maximum',
message: 'must be <= 100',
info: {comparison: '<=', limit: 100},
},
{
path: '/price',
code: 'errorMessage',
message: 'price must be in range 0 to 100',
info: {
errors: [
{
keyword: 'range',
instancePath: '/price',
schemaPath:
'#/components/schemas/Product/properties/price/range',
params: {},
message: 'must pass "range" keyword validation',
emUsed: true,
},
],
},
},
],
},
});
});
});
context('with request body validation options - {ajvKeywords: true}', () => {
class ProductController {
@post('/products')
async create(
@requestBody({required: true}) data: Product,
): Promise<Product> {
return new Product(data);
}
}
before(() =>
givenAnAppAndAClient(ProductController, {
compiledSchemaCache: new WeakMap(),
$data: true,
}),
);
after(() => app.stop());
it('rejects requests with price out of range', async () => {
const DATA = {
name: 'iPhone',
description: 'iPhone',
price: 200,
};
const res = await client.post('/products').send(DATA).expect(422);
expect(res.body).to.eql({
error: {
statusCode: 422,
name: 'UnprocessableEntityError',
message:
'The request body is invalid. See error object `details` property for more info.',
code: 'VALIDATION_FAILED',
details: [
{
path: '/price',
code: 'maximum',
message: 'must be <= 100',
info: {comparison: '<=', limit: 100},
},
{
path: '/price',
code: 'errorMessage',
message: 'price must be in range 0 to 100',
info: {
errors: [
{
keyword: 'range',
instancePath: '/price',
schemaPath:
'#/components/schemas/Product/properties/price/range',
params: {},
message: 'must pass "range" keyword validation',
emUsed: true,
},
],
},
},
],
},
});
});
});
context(
'with request body validation options - {ajvErrorTransformer: [Function]}',
() => {
class ProductController {
@post('/products')
async create(
@requestBody({required: true}) data: Product,
): Promise<Product> {
return new Product(data);
}
}
before(() =>
givenAnAppAndAClient(ProductController, {
compiledSchemaCache: new WeakMap(),
$data: true,
ajvErrorTransformer: errors => {
return errors.map(e => ({
...e,
message: `(translated) ${e.message}`,
}));
},
}),
);
after(() => app.stop());
it('transforms error messages provided by AJV', async () => {
const DATA = {
name: 'iPhone',
description: 'iPhone',
};
const res = await client.post('/products').send(DATA).expect(422);
expect(res.body).to.eql({
error: {
statusCode: 422,
name: 'UnprocessableEntityError',
message:
'The request body is invalid. See error object `details` property for more info.',
code: 'VALIDATION_FAILED',
details: [
{
path: '',
code: 'required',
message: "(translated) must have required property 'price'",
info: {missingProperty: 'price'},
},
],
},
});
});
},
);
context('with request body validation options - {ajvErrors: true}', () => {
class ProductController {
@post('/products')
async create(
@requestBody({required: true}) data: Product,
): Promise<Product> {
return new Product(data);
}
}
before(() =>
givenAnAppAndAClient(ProductController, {
compiledSchemaCache: new WeakMap(),
$data: true,
}),
);
after(() => app.stop());
it('adds custom error message provided with jsonSchema', async () => {
const DATA = {
name: 'iPhone',
description: 'iPhone',
price: 200,
};
const res = await client.post('/products').send(DATA).expect(422);
expect(res.body).to.eql({
error: {
statusCode: 422,
name: 'UnprocessableEntityError',
message:
'The request body is invalid. See error object `details` property for more info.',
code: 'VALIDATION_FAILED',
details: [
{
path: '/price',
code: 'maximum',
message: 'must be <= 100',
info: {comparison: '<=', limit: 100},
},
{
path: '/price',
code: 'errorMessage',
message: 'price must be in range 0 to 100',
info: {
errors: [
{
keyword: 'range',
instancePath: '/price',
schemaPath:
'#/components/schemas/Product/properties/price/range',
params: {},
message: 'must pass "range" keyword validation',
emUsed: true,
},
],
},
},
],
},
});
});
});
context(
'with request body validation options - {ajvErrors: {keepErrors: true}}',
() => {
class ProductController {
@post('/products')
async create(
@requestBody({required: true}) data: Product,
): Promise<Product> {
return new Product(data);
}
}
before(() =>
givenAnAppAndAClient(ProductController, {
compiledSchemaCache: new WeakMap(),
$data: true,
ajvErrors: {
singleError: true,
},
}),
);
after(() => app.stop());
it('adds custom error message provided with jsonSchema', async () => {
const DATA = {
name: 'iPhone',
description: 'iPhone',
price: 200,
};
const res = await client.post('/products').send(DATA).expect(422);
expect(res.body).to.eql({
error: {
statusCode: 422,
name: 'UnprocessableEntityError',
message:
'The request body is invalid. See error object `details` property for more info.',
code: 'VALIDATION_FAILED',
details: [
{
path: '/price',
code: 'maximum',
message: 'must be <= 100',
info: {comparison: '<=', limit: 100},
},
{
path: '/price',
code: 'errorMessage',
message: 'price must be in range 0 to 100',
info: {
errors: [
{
keyword: 'range',
instancePath: '/price',
schemaPath:
'#/components/schemas/Product/properties/price/range',
params: {},
message: 'must pass "range" keyword validation',
emUsed: true,
},
],
},
},
],
},
});
});
},
);
context('with request body validation options - custom keywords', () => {
@model()
class ProductWithName {
@property()
id: number;
@property({required: true, jsonSchema: {validProductName: true}})
name: string;
constructor(data: Partial<ProductWithName>) {
Object.assign(this, data);
}
}
class ProductController {
@post('/products')
async create(
@requestBody({required: true}) data: ProductWithName,
): Promise<ProductWithName> {
return new ProductWithName({id: 1, name: 'prod-1'});
}
}
before(() => givenAnAppAndAClient(ProductController));
after(() => app.stop());
it('allows async custom keyword', async () => {
app.bind(RestBindings.REQUEST_BODY_PARSER_OPTIONS).to({
validation: {
logger: false, // Disable log warning - meta-schema not available
compiledSchemaCache: new WeakMap(),
$data: true,
ajvErrors: {
singleError: true,
},
keywords: [
{
keyword: 'validProductName',
async: true,
type: 'string',
validate: async (schema: unknown, data: string) => {
return data.startsWith('prod-');
},
},
],
},
});
const DATA = {
name: 'iPhone',
};
const res = await client.post('/products').send(DATA).expect(422);
expect(res.body).to.eql({
error: {
statusCode: 422,
name: 'UnprocessableEntityError',
message:
'The request body is invalid. See error object `details` property for more info.',
code: 'VALIDATION_FAILED',
details: [
{
path: '/name',
code: 'validProductName',
message: 'must pass "validProductName" keyword validation',
info: {},
},
],
},
});
});
it('allows sync custom keyword', async () => {
app.bind(RestBindings.REQUEST_BODY_PARSER_OPTIONS).to({
validation: {
logger: false, // Disable log warning - meta-schema not available
compiledSchemaCache: new WeakMap(),
$data: true,
ajvErrors: {
singleError: true,
},
keywords: [
{
keyword: 'validProductName',
async: false,
type: 'string',
validate: (schema: unknown, data: string) => {
return data.startsWith('prod-');
},
},
],
},
});
const DATA = {
name: 'iPhone',
};
const res = await client.post('/products').send(DATA).expect(422);
expect(res.body).to.eql({
error: {
statusCode: 422,
name: 'UnprocessableEntityError',
message:
'The request body is invalid. See error object `details` property for more info.',
code: 'VALIDATION_FAILED',
details: [
{
path: '/name',
code: 'validProductName',
message: 'must pass "validProductName" keyword validation',
info: {},
},
],
},
});
});
});
context(
'for request body specified via model definition with strict false',
() => {
@model({settings: {strict: false}})
class ProductNotStrict {
@property()
id: number;
@property({required: true})
name: string;
constructor(data: Partial<ProductNotStrict>) {
Object.assign(this, data);
}
}
class ProductController {
@post('products')
async create(
@requestBody({required: true}) data: ProductNotStrict,
): Promise<ProductNotStrict> {
return new ProductNotStrict(data);
}
}
before(() => givenAnAppAndAClient(ProductController));
after(() => app.stop());
it('rejects requests with empty string body', async () => {
await client.post('/products').type('json').send('""').expect(422);
});
it('rejects requests with string body', async () => {
await client
.post('/products')
.type('json')
.send('"pencil"')
.expect(422);
});
it('rejects requests with null body', async () => {
await client.post('/products').type('json').send('null').expect(400);
});
},
);
// A request body schema can be provided explicitly by the user
// as an inlined content[type].schema property.
context('for fully-specified request body', () => {
class ProductControllerWithFullSchema {
@post('/products')
async create(
@requestBody(aBodySpec(PRODUCT_SPEC)) data: object,
// ^^^^^^
// use "object" instead of "Product" to verify the situation when
// body schema cannot be inferred from the argument type
): Promise<Product> {
return new Product(data);
}
}
before(() => givenAnAppAndAClient(ProductControllerWithFullSchema));
after(() => app.stop());
it('accepts valid values', () => serverAcceptsValidRequestBody());
it('rejects missing required properties', () =>
serverRejectsRequestWithMissingRequiredValues());
});
context('for different schemas per media type', () => {
let spec = aBodySpec(PRODUCT_SPEC, {}, 'application/json');
spec = aBodySpec(
PRODUCT_SPEC_WITH_DESCRIPTION,
spec,
'application/x-www-form-urlencoded',
);
class ProductControllerWithFullSchema {
@post('/products')
async create(
@requestBody(spec) data: object,
// ^^^^^^
// use "object" instead of "Product" to verify the situation when
// body schema cannot be inferred from the argument type
): Promise<Product> {
return new Product(data);
}
}
before(() => givenAnAppAndAClient(ProductControllerWithFullSchema));
after(() => app.stop());
it('accepts valid values for json', () => serverAcceptsValidRequestBody());
it('accepts valid values for json with nullable properties', () =>
serverAcceptsValidRequestBodyWithNull());
it('accepts valid values for urlencoded', () =>
serverAcceptsValidRequestBodyForUrlencoded());
it('rejects missing required properties for urlencoded', () =>
serverRejectsMissingDescriptionForUrlencoded());
});
// A request body schema can be provided explicitly by the user as a reference
// to a schema shared in the global `components.schemas` object.
context('for request body specified via a reference', () => {
@api({
paths: {},
components: {
schemas: {
Product: PRODUCT_SPEC,
},
},
})
class ProductControllerReferencingComponents {
@post('/products')
async create(
@requestBody(aBodySpec({$ref: '#/components/schemas/Product'}))
data: object,
// ^^^^^^
// use "object" instead of "Product" to verify the situation when
// body schema cannot be inferred from the argument type
): Promise<Product> {
return new Product(data);
}
}
before(() => givenAnAppAndAClient(ProductControllerReferencingComponents));
after(() => app.stop());
it('accepts valid values', () => serverAcceptsValidRequestBody());
it('rejects missing required properties', () =>
serverRejectsRequestWithMissingRequiredValues());
});
async function serverAcceptsValidRequestBody() {
const DATA = {
name: 'Pencil',
description: 'An optional description of a pencil',
price: 10,
};
await client.post('/products').send(DATA).expect(200, DATA);
}
async function serverAcceptsValidRequestBodyWithNull() {
const DATA = {
name: 'Pencil',
description: null,
price: 10,
};
await client.post('/products').send(DATA).expect(200, DATA);
}
async function serverAcceptsValidRequestBodyForUrlencoded() {
const DATA =
'name=Pencil&price=10&description=An optional description of a pencil';
await client
.post('/products')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(DATA)
.expect(200, {
name: 'Pencil',
description: 'An optional description of a pencil',
price: 10,
});
}
async function serverRejectsMissingDescriptionForUrlencoded() {
const DATA = 'name=Pencil&price=10';
await client
.post('/products')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(DATA)
.expect(422);
}
async function serverRejectsRequestWithMissingRequiredValues() {
await client
.post('/products')
.send({
description: 'A product missing required name and price',
})
.expect(422);
}
async function givenAnAppAndAClient(
controller: ControllerClass,
validationOptions?: ValidationOptions,
) {
app = new RestApplication({rest: givenHttpServerConfig()});
if (validationOptions)
app
.bind(RestBindings.REQUEST_BODY_PARSER_OPTIONS)
.to({validation: validationOptions});
app.controller(controller);
await app.start();
client = createRestAppClient(app);
}
}); | the_stack |
import ReactDOM from "react-dom";
import {
render,
fireEvent,
mockBoundingClientRect,
restoreOriginalGetBoundingClientRect,
GlobalTestState,
screen,
queryByText,
queryAllByText,
waitFor,
} from "./test-utils";
import ExcalidrawApp from "../excalidraw-app";
import * as Renderer from "../renderer/renderScene";
import { reseed } from "../random";
import { UI, Pointer, Keyboard } from "./helpers/ui";
import { CODES } from "../keys";
import { ShortcutName } from "../actions/shortcuts";
import { copiedStyles } from "../actions/actionStyles";
import { API } from "./helpers/api";
import { setDateTimeForTests } from "../utils";
import { t } from "../i18n";
const checkpoint = (name: string) => {
expect(renderScene.mock.calls.length).toMatchSnapshot(
`[${name}] number of renders`,
);
expect(h.state).toMatchSnapshot(`[${name}] appState`);
expect(h.history.getSnapshotForTest()).toMatchSnapshot(`[${name}] history`);
expect(h.elements.length).toMatchSnapshot(`[${name}] number of elements`);
h.elements.forEach((element, i) =>
expect(element).toMatchSnapshot(`[${name}] element ${i}`),
);
};
const mouse = new Pointer("mouse");
const queryContextMenu = () => {
return GlobalTestState.renderResult.container.querySelector(".context-menu");
};
const clickLabeledElement = (label: string) => {
const element = document.querySelector(`[aria-label='${label}']`);
if (!element) {
throw new Error(`No labeled element found: ${label}`);
}
fireEvent.click(element);
};
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
const renderScene = jest.spyOn(Renderer, "renderScene");
beforeEach(() => {
localStorage.clear();
renderScene.mockClear();
reseed(7);
});
const { h } = window;
describe("contextMenu element", () => {
beforeEach(async () => {
localStorage.clear();
renderScene.mockClear();
reseed(7);
setDateTimeForTests("201933152653");
await render(<ExcalidrawApp />);
});
beforeAll(() => {
mockBoundingClientRect();
});
afterAll(() => {
restoreOriginalGetBoundingClientRect();
});
afterEach(() => {
checkpoint("end of test");
mouse.reset();
mouse.down(0, 0);
});
it("shows context menu for canvas", () => {
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 1,
clientY: 1,
});
const contextMenu = queryContextMenu();
const contextMenuOptions = contextMenu?.querySelectorAll(
".context-menu li",
);
const expectedShortcutNames: ShortcutName[] = [
"selectAll",
"gridMode",
"zenMode",
"viewMode",
"stats",
];
expect(contextMenu).not.toBeNull();
expect(contextMenuOptions?.length).toBe(expectedShortcutNames.length);
expectedShortcutNames.forEach((shortcutName) => {
expect(
contextMenu?.querySelector(`li[data-testid="${shortcutName}"]`),
).not.toBeNull();
});
});
it("shows context menu for element", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 1,
clientY: 1,
});
const contextMenu = queryContextMenu();
const contextMenuOptions = contextMenu?.querySelectorAll(
".context-menu li",
);
const expectedShortcutNames: ShortcutName[] = [
"copyStyles",
"pasteStyles",
"deleteSelectedElements",
"addToLibrary",
"flipHorizontal",
"flipVertical",
"sendBackward",
"bringForward",
"sendToBack",
"bringToFront",
"duplicateSelection",
];
expect(contextMenu).not.toBeNull();
expect(contextMenuOptions?.length).toBe(expectedShortcutNames.length);
expectedShortcutNames.forEach((shortcutName) => {
expect(
contextMenu?.querySelector(`li[data-testid="${shortcutName}"]`),
).not.toBeNull();
});
});
it("shows context menu for element", () => {
const rect1 = API.createElement({
type: "rectangle",
x: 0,
y: 0,
height: 200,
width: 200,
backgroundColor: "red",
});
const rect2 = API.createElement({
type: "rectangle",
x: 0,
y: 0,
height: 200,
width: 200,
backgroundColor: "red",
});
h.elements = [rect1, rect2];
API.setSelectedElements([rect1]);
// lower z-index
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 100,
clientY: 100,
});
expect(queryContextMenu()).not.toBeNull();
expect(API.getSelectedElement().id).toBe(rect1.id);
// higher z-index
API.setSelectedElements([rect2]);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 100,
clientY: 100,
});
expect(queryContextMenu()).not.toBeNull();
expect(API.getSelectedElement().id).toBe(rect2.id);
});
it("shows 'Group selection' in context menu for multiple selected elements", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
UI.clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
mouse.reset();
mouse.click(10, 10);
Keyboard.withModifierKeys({ shift: true }, () => {
mouse.click(20, 0);
});
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 1,
clientY: 1,
});
const contextMenu = queryContextMenu();
const contextMenuOptions = contextMenu?.querySelectorAll(
".context-menu li",
);
const expectedShortcutNames: ShortcutName[] = [
"copyStyles",
"pasteStyles",
"deleteSelectedElements",
"group",
"addToLibrary",
"sendBackward",
"bringForward",
"sendToBack",
"bringToFront",
"duplicateSelection",
];
expect(contextMenu).not.toBeNull();
expect(contextMenuOptions?.length).toBe(expectedShortcutNames.length);
expectedShortcutNames.forEach((shortcutName) => {
expect(
contextMenu?.querySelector(`li[data-testid="${shortcutName}"]`),
).not.toBeNull();
});
});
it("shows 'Ungroup selection' in context menu for group inside selected elements", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(10, 10);
UI.clickTool("rectangle");
mouse.down(10, -10);
mouse.up(10, 10);
mouse.reset();
mouse.click(10, 10);
Keyboard.withModifierKeys({ shift: true }, () => {
mouse.click(20, 0);
});
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.codePress(CODES.G);
});
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 1,
clientY: 1,
});
const contextMenu = queryContextMenu();
const contextMenuOptions = contextMenu?.querySelectorAll(
".context-menu li",
);
const expectedShortcutNames: ShortcutName[] = [
"copyStyles",
"pasteStyles",
"deleteSelectedElements",
"ungroup",
"addToLibrary",
"sendBackward",
"bringForward",
"sendToBack",
"bringToFront",
"duplicateSelection",
];
expect(contextMenu).not.toBeNull();
expect(contextMenuOptions?.length).toBe(expectedShortcutNames.length);
expectedShortcutNames.forEach((shortcutName) => {
expect(
contextMenu?.querySelector(`li[data-testid="${shortcutName}"]`),
).not.toBeNull();
});
});
it("selecting 'Copy styles' in context menu copies styles", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 1,
clientY: 1,
});
const contextMenu = queryContextMenu();
expect(copiedStyles).toBe("{}");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Copy styles")!);
expect(copiedStyles).not.toBe("{}");
const element = JSON.parse(copiedStyles);
expect(element).toEqual(API.getSelectedElement());
});
it("selecting 'Paste styles' in context menu pastes styles", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
// Change some styles of second rectangle
clickLabeledElement("Stroke");
clickLabeledElement(t("colors.c92a2a"));
clickLabeledElement("Background");
clickLabeledElement(t("colors.e64980"));
// Fill style
fireEvent.click(screen.getByTitle("Cross-hatch"));
// Stroke width
fireEvent.click(screen.getByTitle("Bold"));
// Stroke style
fireEvent.click(screen.getByTitle("Dotted"));
// Roughness
fireEvent.click(screen.getByTitle("Cartoonist"));
// Opacity
fireEvent.change(screen.getByLabelText("Opacity"), {
target: { value: "60" },
});
mouse.reset();
// Copy styles of second rectangle
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 40,
clientY: 40,
});
let contextMenu = queryContextMenu();
fireEvent.click(queryByText(contextMenu as HTMLElement, "Copy styles")!);
const secondRect = JSON.parse(copiedStyles);
expect(secondRect.id).toBe(h.elements[1].id);
mouse.reset();
// Paste styles to first rectangle
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 10,
clientY: 10,
});
contextMenu = queryContextMenu();
fireEvent.click(queryByText(contextMenu as HTMLElement, "Paste styles")!);
const firstRect = API.getSelectedElement();
expect(firstRect.id).toBe(h.elements[0].id);
expect(firstRect.strokeColor).toBe("#c92a2a");
expect(firstRect.backgroundColor).toBe("#e64980");
expect(firstRect.fillStyle).toBe("cross-hatch");
expect(firstRect.strokeWidth).toBe(2); // Bold: 2
expect(firstRect.strokeStyle).toBe("dotted");
expect(firstRect.roughness).toBe(2); // Cartoonist: 2
expect(firstRect.opacity).toBe(60);
});
it("selecting 'Delete' in context menu deletes element", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 1,
clientY: 1,
});
const contextMenu = queryContextMenu();
fireEvent.click(queryAllByText(contextMenu as HTMLElement, "Delete")[0]);
expect(API.getSelectedElements()).toHaveLength(0);
expect(h.elements[0].isDeleted).toBe(true);
});
it("selecting 'Add to library' in context menu adds element to library", async () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 1,
clientY: 1,
});
const contextMenu = queryContextMenu();
fireEvent.click(queryByText(contextMenu as HTMLElement, "Add to library")!);
await waitFor(() => {
const library = localStorage.getItem("excalidraw-library");
expect(library).not.toBeNull();
const addedElement = JSON.parse(library!)[0][0];
expect(addedElement).toEqual(h.elements[0]);
});
});
it("selecting 'Duplicate' in context menu duplicates element", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 1,
clientY: 1,
});
const contextMenu = queryContextMenu();
fireEvent.click(queryByText(contextMenu as HTMLElement, "Duplicate")!);
expect(h.elements).toHaveLength(2);
const { id: _id0, seed: _seed0, x: _x0, y: _y0, ...rect1 } = h.elements[0];
const { id: _id1, seed: _seed1, x: _x1, y: _y1, ...rect2 } = h.elements[1];
expect(rect1).toEqual(rect2);
});
it("selecting 'Send backward' in context menu sends element backward", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 40,
clientY: 40,
});
const contextMenu = queryContextMenu();
const elementsBefore = h.elements;
fireEvent.click(queryByText(contextMenu as HTMLElement, "Send backward")!);
expect(elementsBefore[0].id).toEqual(h.elements[1].id);
expect(elementsBefore[1].id).toEqual(h.elements[0].id);
});
it("selecting 'Bring forward' in context menu brings element forward", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 10,
clientY: 10,
});
const contextMenu = queryContextMenu();
const elementsBefore = h.elements;
fireEvent.click(queryByText(contextMenu as HTMLElement, "Bring forward")!);
expect(elementsBefore[0].id).toEqual(h.elements[1].id);
expect(elementsBefore[1].id).toEqual(h.elements[0].id);
});
it("selecting 'Send to back' in context menu sends element to back", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 40,
clientY: 40,
});
const contextMenu = queryContextMenu();
const elementsBefore = h.elements;
fireEvent.click(queryByText(contextMenu as HTMLElement, "Send to back")!);
expect(elementsBefore[1].id).toEqual(h.elements[0].id);
});
it("selecting 'Bring to front' in context menu brings element to front", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 10,
clientY: 10,
});
const contextMenu = queryContextMenu();
const elementsBefore = h.elements;
fireEvent.click(queryByText(contextMenu as HTMLElement, "Bring to front")!);
expect(elementsBefore[0].id).toEqual(h.elements[1].id);
});
it("selecting 'Group selection' in context menu groups selected elements", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
Keyboard.withModifierKeys({ shift: true }, () => {
mouse.click(10, 10);
});
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 1,
clientY: 1,
});
const contextMenu = queryContextMenu();
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Group selection")!,
);
const selectedGroupIds = Object.keys(h.state.selectedGroupIds);
expect(h.elements[0].groupIds).toEqual(selectedGroupIds);
expect(h.elements[1].groupIds).toEqual(selectedGroupIds);
});
it("selecting 'Ungroup selection' in context menu ungroups selected group", () => {
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
UI.clickTool("rectangle");
mouse.down(10, 10);
mouse.up(20, 20);
mouse.reset();
Keyboard.withModifierKeys({ shift: true }, () => {
mouse.click(10, 10);
});
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.codePress(CODES.G);
});
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 1,
clientY: 1,
});
const contextMenu = queryContextMenu();
expect(contextMenu).not.toBeNull();
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Ungroup selection")!,
);
const selectedGroupIds = Object.keys(h.state.selectedGroupIds);
expect(selectedGroupIds).toHaveLength(0);
expect(h.elements[0].groupIds).toHaveLength(0);
expect(h.elements[1].groupIds).toHaveLength(0);
});
}); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [s3-outposts](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazons3onoutposts.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class S3Outposts extends PolicyStatement {
public servicePrefix = 's3-outposts';
/**
* Statement provider for service [s3-outposts](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazons3onoutposts.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to abort a multipart upload
*
* Access Level: Write
*
* Possible conditions:
* - .ifDataAccessPointArn()
* - .ifDataAccessPointAccount()
* - .ifAccessPointNetworkOrigin()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_AbortMultipartUpload.html
*/
public toAbortMultipartUpload() {
return this.to('AbortMultipartUpload');
}
/**
* Grants permission to create a new access point
*
* Access Level: Write
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_CreateAccessPoint.html
*/
public toCreateAccessPoint() {
return this.to('CreateAccessPoint');
}
/**
* Grants permission to create a new bucket
*
* Access Level: Write
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_CreateBucket.html
*/
public toCreateBucket() {
return this.to('CreateBucket');
}
/**
* Grants permission to create a new endpoint
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_s3outposts_CreateEndpoint.html
*/
public toCreateEndpoint() {
return this.to('CreateEndpoint');
}
/**
* Grants permission to delete the access point named in the URI
*
* Access Level: Write
*
* Possible conditions:
* - .ifDataAccessPointArn()
* - .ifDataAccessPointAccount()
* - .ifAccessPointNetworkOrigin()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_DeleteAccessPoint.html
*/
public toDeleteAccessPoint() {
return this.to('DeleteAccessPoint');
}
/**
* Grants permission to delete the policy on a specified access point
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifDataAccessPointArn()
* - .ifDataAccessPointAccount()
* - .ifAccessPointNetworkOrigin()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_DeleteAccessPointPolicy.html
*/
public toDeleteAccessPointPolicy() {
return this.to('DeleteAccessPointPolicy');
}
/**
* Grants permission to delete the bucket named in the URI
*
* Access Level: Write
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_DeleteBucket.html
*/
public toDeleteBucket() {
return this.to('DeleteBucket');
}
/**
* Grants permission to delete the policy on a specified bucket
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_DeleteBucketPolicy.html
*/
public toDeleteBucketPolicy() {
return this.to('DeleteBucketPolicy');
}
/**
* Grants permission to delete the endpoint named in the URI
*
* Access Level: Write
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_s3outposts_DeleteEndpoint.html
*/
public toDeleteEndpoint() {
return this.to('DeleteEndpoint');
}
/**
* Grants permission to remove the null version of an object and insert a delete marker, which becomes the current version of the object
*
* Access Level: Write
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html
*/
public toDeleteObject() {
return this.to('DeleteObject');
}
/**
* Grants permission to use the tagging subresource to remove the entire tag set from the specified object
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifExistingObjectTag()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObjectTagging.html
*/
public toDeleteObjectTagging() {
return this.to('DeleteObjectTagging');
}
/**
* Grants permission to return configuration information about the specified access point
*
* Access Level: Read
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_GetAccessPoint.html
*/
public toGetAccessPoint() {
return this.to('GetAccessPoint');
}
/**
* Grants permission to returns the access point policy associated with the specified access point
*
* Access Level: Read
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_GetAccessPointPolicy.html
*/
public toGetAccessPointPolicy() {
return this.to('GetAccessPointPolicy');
}
/**
* Grants permission to return the bucket configuration associated with an Amazon S3 bucket
*
* Access Level: Read
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_GetBucket.html
*/
public toGetBucket() {
return this.to('GetBucket');
}
/**
* Grants permission to return the policy of the specified bucket
*
* Access Level: Read
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_GetBucketPolicy.html
*/
public toGetBucketPolicy() {
return this.to('GetBucketPolicy');
}
/**
* Grants permission to return the tag set associated with an Amazon S3 bucket
*
* Access Level: Read
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_GetBucketTagging.html
*/
public toGetBucketTagging() {
return this.to('GetBucketTagging');
}
/**
* Grants permission to return the lifecycle configuration information set on an Amazon S3 bucket
*
* Access Level: Read
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_GetBucketLifecycleConfiguration.html
*/
public toGetLifecycleConfiguration() {
return this.to('GetLifecycleConfiguration');
}
/**
* Grants permission to retrieve objects from Amazon S3
*
* Access Level: Read
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifExistingObjectTag()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html
*/
public toGetObject() {
return this.to('GetObject');
}
/**
* Grants permission to return the tag set of an object
*
* Access Level: Read
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifExistingObjectTag()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjectTagging.html
*/
public toGetObjectTagging() {
return this.to('GetObjectTagging');
}
/**
* Grants permission to list access points
*
* Access Level: List
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_ListAccessPoints.html
*/
public toListAccessPoints() {
return this.to('ListAccessPoints');
}
/**
* Grants permission to list some or all of the objects in an Amazon S3 bucket (up to 1000)
*
* Access Level: List
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifAuthType()
* - .ifDelimiter()
* - .ifMaxKeys()
* - .ifPrefix()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
*/
public toListBucket() {
return this.to('ListBucket');
}
/**
* Grants permission to list in-progress multipart uploads
*
* Access Level: List
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html
*/
public toListBucketMultipartUploads() {
return this.to('ListBucketMultipartUploads');
}
/**
* Grants permission to list endpoints
*
* Access Level: List
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_s3outposts_ListEndpoints.html
*/
public toListEndpoints() {
return this.to('ListEndpoints');
}
/**
* Grants permission to list the parts that have been uploaded for a specific multipart upload
*
* Access Level: List
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html
*/
public toListMultipartUploadParts() {
return this.to('ListMultipartUploadParts');
}
/**
* Grants permission to list all buckets owned by the authenticated sender of the request
*
* Access Level: List
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_ListRegionalBuckets.html
*/
public toListRegionalBuckets() {
return this.to('ListRegionalBuckets');
}
/**
* Grants permission to associate an access policy with a specified access point
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_PutAccessPointPolicy.html
*/
public toPutAccessPointPolicy() {
return this.to('PutAccessPointPolicy');
}
/**
* Grants permission to add or replace a bucket policy on a bucket
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_PutBucketPolicy.html
*/
public toPutBucketPolicy() {
return this.to('PutBucketPolicy');
}
/**
* Grants permission to add a set of tags to an existing Amazon S3 bucket
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_PutBucketTagging.html
*/
public toPutBucketTagging() {
return this.to('PutBucketTagging');
}
/**
* Grants permission to create a new lifecycle configuration for the bucket or replace an existing lifecycle configuration
*
* Access Level: Write
*
* Possible conditions:
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_PutBucketLifecycleConfiguration.html
*/
public toPutLifecycleConfiguration() {
return this.to('PutLifecycleConfiguration');
}
/**
* Grants permission to add an object to a bucket
*
* Access Level: Write
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifRequestObjectTag()
* - .ifRequestObjectTagKeys()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzAcl()
* - .ifXAmzContentSha256()
* - .ifXAmzCopySource()
* - .ifXAmzMetadataDirective()
* - .ifXAmzServerSideEncryption()
* - .ifXAmzStorageClass()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html
*/
public toPutObject() {
return this.to('PutObject');
}
/**
* Grants permission to set the access control list (ACL) permissions for an object that already exists in a bucket
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifExistingObjectTag()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzAcl()
* - .ifXAmzContentSha256()
* - .ifXAmzStorageClass()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjectAcl.html
*/
public toPutObjectAcl() {
return this.to('PutObjectAcl');
}
/**
* Grants permission to set the supplied tag-set to an object that already exists in a bucket
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifDataAccessPointAccount()
* - .ifDataAccessPointArn()
* - .ifAccessPointNetworkOrigin()
* - .ifExistingObjectTag()
* - .ifRequestObjectTag()
* - .ifRequestObjectTagKeys()
* - .ifAuthType()
* - .ifSignatureAge()
* - .ifSignatureversion()
* - .ifXAmzContentSha256()
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjectTagging.html
*/
public toPutObjectTagging() {
return this.to('PutObjectTagging');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AbortMultipartUpload",
"CreateAccessPoint",
"CreateBucket",
"CreateEndpoint",
"DeleteAccessPoint",
"DeleteBucket",
"DeleteEndpoint",
"DeleteObject",
"PutLifecycleConfiguration",
"PutObject"
],
"Permissions management": [
"DeleteAccessPointPolicy",
"DeleteBucketPolicy",
"PutAccessPointPolicy",
"PutBucketPolicy",
"PutObjectAcl"
],
"Tagging": [
"DeleteObjectTagging",
"PutBucketTagging",
"PutObjectTagging"
],
"Read": [
"GetAccessPoint",
"GetAccessPointPolicy",
"GetBucket",
"GetBucketPolicy",
"GetBucketTagging",
"GetLifecycleConfiguration",
"GetObject",
"GetObjectTagging"
],
"List": [
"ListAccessPoints",
"ListBucket",
"ListBucketMultipartUploads",
"ListEndpoints",
"ListMultipartUploadParts",
"ListRegionalBuckets"
]
};
/**
* Adds a resource of type accesspoint to the statement
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/access-points.html
*
* @param outpostId - Identifier for the outpostId.
* @param accessPointName - Identifier for the accessPointName.
* @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 onAccesspoint(outpostId: string, accessPointName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:s3-outposts:${Region}:${Account}:outpost/${OutpostId}/accesspoint/${AccessPointName}';
arn = arn.replace('${OutpostId}', outpostId);
arn = arn.replace('${AccessPointName}', accessPointName);
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 bucket to the statement
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html
*
* @param outpostId - Identifier for the outpostId.
* @param bucketName - Identifier for the bucketName.
* @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 onBucket(outpostId: string, bucketName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:s3-outposts:${Region}:${Account}:outpost/${OutpostId}/bucket/${BucketName}';
arn = arn.replace('${OutpostId}', outpostId);
arn = arn.replace('${BucketName}', bucketName);
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 endpoint to the statement
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/outposts-endpoints.html
*
* @param outpostId - Identifier for the outpostId.
* @param endpointId - Identifier for the endpointId.
* @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 onEndpoint(outpostId: string, endpointId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:s3-outposts:${Region}:${Account}:outpost/${OutpostId}/endpoint/${EndpointId}';
arn = arn.replace('${OutpostId}', outpostId);
arn = arn.replace('${EndpointId}', endpointId);
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 object to the statement
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingObjects.html
*
* @param outpostId - Identifier for the outpostId.
* @param bucketName - Identifier for the bucketName.
* @param objectName - Identifier for the objectName.
* @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 onObject(outpostId: string, bucketName: string, objectName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:s3-outposts:${Region}:${Account}:outpost/${OutpostId}/bucket/${BucketName}/object/${ObjectName}';
arn = arn.replace('${OutpostId}', outpostId);
arn = arn.replace('${BucketName}', bucketName);
arn = arn.replace('${ObjectName}', objectName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters access by the network origin (Internet or VPC)
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/creating-access-points.html#access-points-policies
*
* Applies to actions:
* - .toAbortMultipartUpload()
* - .toCreateAccessPoint()
* - .toDeleteAccessPoint()
* - .toDeleteAccessPointPolicy()
* - .toDeleteObject()
* - .toDeleteObjectTagging()
* - .toGetAccessPoint()
* - .toGetAccessPointPolicy()
* - .toGetObject()
* - .toGetObjectTagging()
* - .toListBucket()
* - .toListBucketMultipartUploads()
* - .toListMultipartUploadParts()
* - .toPutAccessPointPolicy()
* - .toPutObject()
* - .toPutObjectAcl()
* - .toPutObjectTagging()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifAccessPointNetworkOrigin(value: string | string[], operator?: Operator | string) {
return this.if(`AccessPointNetworkOrigin`, value, operator || 'StringLike');
}
/**
* Filters access by the AWS Account ID that owns the access point
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/creating-access-points.html#access-points-policies
*
* Applies to actions:
* - .toAbortMultipartUpload()
* - .toCreateAccessPoint()
* - .toDeleteAccessPoint()
* - .toDeleteAccessPointPolicy()
* - .toDeleteObject()
* - .toDeleteObjectTagging()
* - .toGetAccessPoint()
* - .toGetAccessPointPolicy()
* - .toGetObject()
* - .toGetObjectTagging()
* - .toListBucket()
* - .toListBucketMultipartUploads()
* - .toListMultipartUploadParts()
* - .toPutAccessPointPolicy()
* - .toPutObject()
* - .toPutObjectAcl()
* - .toPutObjectTagging()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifDataAccessPointAccount(value: string | string[], operator?: Operator | string) {
return this.if(`DataAccessPointAccount`, value, operator || 'StringLike');
}
/**
* Filters access by an access point Amazon Resource Name (ARN)
*
* Applies to actions:
* - .toAbortMultipartUpload()
* - .toCreateAccessPoint()
* - .toDeleteAccessPoint()
* - .toDeleteAccessPointPolicy()
* - .toDeleteObject()
* - .toDeleteObjectTagging()
* - .toGetAccessPoint()
* - .toGetAccessPointPolicy()
* - .toGetObject()
* - .toGetObjectTagging()
* - .toListBucket()
* - .toListBucketMultipartUploads()
* - .toListMultipartUploadParts()
* - .toPutAccessPointPolicy()
* - .toPutObject()
* - .toPutObjectAcl()
* - .toPutObjectTagging()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifDataAccessPointArn(value: string | string[], operator?: Operator | string) {
return this.if(`DataAccessPointArn`, value, operator || 'StringLike');
}
/**
* Filters access by requiring that an existing object tag has a specific tag key and value
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/object-tagging.html#tagging-and-policies
*
* Applies to actions:
* - .toDeleteObjectTagging()
* - .toGetObject()
* - .toGetObjectTagging()
* - .toPutObjectAcl()
* - .toPutObjectTagging()
*
* @param key The tag key to check
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifExistingObjectTag(key: string, value: string | string[], operator?: Operator | string) {
return this.if(`ExistingObjectTag/${ key }`, value, operator || 'StringLike');
}
/**
* Filters access by restricting the tag keys and values allowed on objects
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/object-tagging.html#tagging-and-policies
*
* Applies to actions:
* - .toPutObject()
* - .toPutObjectTagging()
*
* @param key The tag key to check
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestObjectTag(key: string, value: string | string[], operator?: Operator | string) {
return this.if(`RequestObjectTag/${ key }`, value, operator || 'StringLike');
}
/**
* Filters access by restricting the tag keys allowed on objects
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/object-tagging.html#tagging-and-policies
*
* Applies to actions:
* - .toPutObject()
* - .toPutObjectTagging()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRequestObjectTagKeys(value: string | string[], operator?: Operator | string) {
return this.if(`RequestObjectTagKeys`, value, operator || 'StringLike');
}
/**
* Filters access by restricting incoming requests to a specific authentication method
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/bucket-policy-s3-sigv4-conditions.html
*
* Applies to actions:
* - .toAbortMultipartUpload()
* - .toCreateAccessPoint()
* - .toCreateBucket()
* - .toDeleteAccessPoint()
* - .toDeleteAccessPointPolicy()
* - .toDeleteBucket()
* - .toDeleteBucketPolicy()
* - .toDeleteObject()
* - .toDeleteObjectTagging()
* - .toGetAccessPoint()
* - .toGetAccessPointPolicy()
* - .toGetBucket()
* - .toGetBucketPolicy()
* - .toGetBucketTagging()
* - .toGetLifecycleConfiguration()
* - .toGetObject()
* - .toGetObjectTagging()
* - .toListAccessPoints()
* - .toListBucket()
* - .toListBucketMultipartUploads()
* - .toListMultipartUploadParts()
* - .toListRegionalBuckets()
* - .toPutAccessPointPolicy()
* - .toPutBucketPolicy()
* - .toPutBucketTagging()
* - .toPutLifecycleConfiguration()
* - .toPutObject()
* - .toPutObjectAcl()
* - .toPutObjectTagging()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifAuthType(value: string | string[], operator?: Operator | string) {
return this.if(`authType`, value, operator || 'StringLike');
}
/**
* Filters access by requiring the delimiter parameter
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/walkthrough1.html
*
* Applies to actions:
* - .toListBucket()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifDelimiter(value: string | string[], operator?: Operator | string) {
return this.if(`delimiter`, value, operator || 'StringLike');
}
/**
* Filters access by limiting the maximum number of keys returned in a ListBucket request
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/amazon-s3-policy-keys.html#example-numeric-condition-operators
*
* Applies to actions:
* - .toListBucket()
*
* @param value The value(s) to check
* @param operator Works with [numeric operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Numeric). **Default:** `NumericEquals`
*/
public ifMaxKeys(value: number | number[], operator?: Operator | string) {
return this.if(`max-keys`, value, operator || 'NumericEquals');
}
/**
* Filters access by key name prefix
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/amazon-s3-policy-keys.html#condition-key-bucket-ops-2
*
* Applies to actions:
* - .toListBucket()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifPrefix(value: string | string[], operator?: Operator | string) {
return this.if(`prefix`, value, operator || 'StringLike');
}
/**
* Filters access by identifying the length of time, in milliseconds, that a signature is valid in an authenticated request
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/bucket-policy-s3-sigv4-conditions.html
*
* Applies to actions:
* - .toAbortMultipartUpload()
* - .toCreateAccessPoint()
* - .toCreateBucket()
* - .toDeleteAccessPoint()
* - .toDeleteAccessPointPolicy()
* - .toDeleteBucket()
* - .toDeleteBucketPolicy()
* - .toDeleteObject()
* - .toDeleteObjectTagging()
* - .toGetAccessPoint()
* - .toGetAccessPointPolicy()
* - .toGetBucket()
* - .toGetBucketPolicy()
* - .toGetBucketTagging()
* - .toGetLifecycleConfiguration()
* - .toGetObject()
* - .toGetObjectTagging()
* - .toListAccessPoints()
* - .toListBucket()
* - .toListBucketMultipartUploads()
* - .toListMultipartUploadParts()
* - .toListRegionalBuckets()
* - .toPutAccessPointPolicy()
* - .toPutBucketPolicy()
* - .toPutBucketTagging()
* - .toPutLifecycleConfiguration()
* - .toPutObject()
* - .toPutObjectAcl()
* - .toPutObjectTagging()
*
* @param value The value(s) to check
* @param operator Works with [numeric operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Numeric). **Default:** `NumericEquals`
*/
public ifSignatureAge(value: number | number[], operator?: Operator | string) {
return this.if(`signatureAge`, value, operator || 'NumericEquals');
}
/**
* Filters access by identifying the version of AWS Signature that is supported for authenticated requests
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/bucket-policy-s3-sigv4-conditions.html
*
* Applies to actions:
* - .toAbortMultipartUpload()
* - .toCreateAccessPoint()
* - .toCreateBucket()
* - .toDeleteAccessPoint()
* - .toDeleteAccessPointPolicy()
* - .toDeleteBucket()
* - .toDeleteBucketPolicy()
* - .toDeleteObject()
* - .toDeleteObjectTagging()
* - .toGetAccessPoint()
* - .toGetAccessPointPolicy()
* - .toGetBucket()
* - .toGetBucketPolicy()
* - .toGetBucketTagging()
* - .toGetLifecycleConfiguration()
* - .toGetObject()
* - .toGetObjectTagging()
* - .toListAccessPoints()
* - .toListBucket()
* - .toListBucketMultipartUploads()
* - .toListMultipartUploadParts()
* - .toListRegionalBuckets()
* - .toPutAccessPointPolicy()
* - .toPutBucketPolicy()
* - .toPutBucketTagging()
* - .toPutLifecycleConfiguration()
* - .toPutObject()
* - .toPutObjectAcl()
* - .toPutObjectTagging()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifSignatureversion(value: string | string[], operator?: Operator | string) {
return this.if(`signatureversion`, value, operator || 'StringLike');
}
/**
* Filters access by requiring the x-amz-acl header with a specific canned ACL in a request
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#permissions
*
* Applies to actions:
* - .toPutObject()
* - .toPutObjectAcl()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifXAmzAcl(value: string | string[], operator?: Operator | string) {
return this.if(`x-amz-acl`, value, operator || 'StringLike');
}
/**
* Filters access by disallowing unsigned content in your bucket
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/bucket-policy-s3-sigv4-conditions.html
*
* Applies to actions:
* - .toAbortMultipartUpload()
* - .toCreateAccessPoint()
* - .toCreateBucket()
* - .toDeleteAccessPoint()
* - .toDeleteAccessPointPolicy()
* - .toDeleteBucket()
* - .toDeleteBucketPolicy()
* - .toDeleteObject()
* - .toDeleteObjectTagging()
* - .toGetAccessPoint()
* - .toGetAccessPointPolicy()
* - .toGetBucket()
* - .toGetBucketPolicy()
* - .toGetBucketTagging()
* - .toGetLifecycleConfiguration()
* - .toGetObject()
* - .toGetObjectTagging()
* - .toListAccessPoints()
* - .toListBucket()
* - .toListBucketMultipartUploads()
* - .toListMultipartUploadParts()
* - .toListRegionalBuckets()
* - .toPutAccessPointPolicy()
* - .toPutBucketPolicy()
* - .toPutBucketTagging()
* - .toPutLifecycleConfiguration()
* - .toPutObject()
* - .toPutObjectAcl()
* - .toPutObjectTagging()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifXAmzContentSha256(value: string | string[], operator?: Operator | string) {
return this.if(`x-amz-content-sha256`, value, operator || 'StringLike');
}
/**
* Filters access by restricting the copy source to a specific bucket, prefix, or object
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/amazon-s3-policy-keys.html#putobject-limit-copy-source-3
*
* Applies to actions:
* - .toPutObject()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifXAmzCopySource(value: string | string[], operator?: Operator | string) {
return this.if(`x-amz-copy-source`, value, operator || 'StringLike');
}
/**
* Filters access by enabling enforcement of object metadata behavior (COPY or REPLACE) when objects are copied
*
* https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html
*
* Applies to actions:
* - .toPutObject()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifXAmzMetadataDirective(value: string | string[], operator?: Operator | string) {
return this.if(`x-amz-metadata-directive`, value, operator || 'StringLike');
}
/**
* Filters access by requiring server-side encryption
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html
*
* Applies to actions:
* - .toPutObject()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifXAmzServerSideEncryption(value: string | string[], operator?: Operator | string) {
return this.if(`x-amz-server-side-encryption`, value, operator || 'StringLike');
}
/**
* Filters access by storage class
*
* https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html#sc-howtoset
*
* Applies to actions:
* - .toPutObject()
* - .toPutObjectAcl()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifXAmzStorageClass(value: string | string[], operator?: Operator | string) {
return this.if(`x-amz-storage-class`, value, operator || 'StringLike');
}
} | the_stack |
import { assert, expect } from '@open-wc/testing';
import { LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';
import sinon from 'sinon';
// API to test
import { Binder, BinderConfiguration } from '../src';
import { Employee, EmployeeModel, Order, OrderModel, TestEntity, TestModel } from './TestModels.js';
@customElement('lit-order-view')
class LitOrderView extends LitElement {}
@customElement('lit-employee-view')
class LitEmployeeView extends LitElement {}
describe('form/Binder', () => {
const litOrderView = document.createElement('lit-order-view') as LitOrderView;
const requestUpdateStub = sinon.stub(litOrderView, 'requestUpdate').resolves();
afterEach(() => {
requestUpdateStub.reset();
});
it('should instantiate without type arguments', () => {
const binder = new Binder(litOrderView, OrderModel);
assert.isDefined(binder);
assert.isDefined(binder.value.notes);
assert.isDefined(binder.value.idString);
assert.isDefined(binder.value.customer.fullName);
assert.isDefined(binder.value.customer.idString);
});
it('should instantiate model', () => {
const binder = new Binder(litOrderView, OrderModel);
assert.instanceOf(binder.model, OrderModel);
});
it('should be able to create a binder with a default onchange listener', () => {
const binder = new Binder(litOrderView, OrderModel);
binder.for(binder.model.notes).value = 'foo';
expect(requestUpdateStub).to.be.calledTwice;
});
it('should be able to create a binder with a custom onchange listener', () => {
let foo = 'bar';
const config: BinderConfiguration<Order> = {
onChange: () => {
foo = 'baz';
},
};
const binder = new Binder(litOrderView, OrderModel, config);
binder.for(binder.model.notes).value = 'foo';
assert.equal(foo, 'baz');
});
describe('name value', () => {
let binder: Binder<Order, OrderModel>;
const expectedEmptyOrder: Order = {
idString: '',
customer: {
idString: '',
fullName: '',
nickName: '',
},
notes: '',
priority: 0,
products: [],
};
beforeEach(() => {
binder = new Binder(litOrderView, OrderModel);
requestUpdateStub.reset();
});
it('should have name for models', () => {
assert.equal(binder.for(binder.model.notes).name, 'notes');
assert.equal(binder.for(binder.model.customer.fullName).name, 'customer.fullName');
});
it('should have initial defaultValue', () => {
assert.deepEqual(binder.defaultValue, expectedEmptyOrder);
});
it('should have valueOf', () => {
assert.equal(binder.model.notes.valueOf(), '');
assert.equal(binder.model.priority.valueOf(), 0);
});
it('should have toString', () => {
assert.equal(binder.model.notes.valueOf(), '');
assert.equal(binder.model.priority.toString(), '0');
});
it('should have initial value', () => {
assert.equal(binder.value, binder.defaultValue);
assert.equal(binder.for(binder.model).value, binder.value);
assert.equal(binder.for(binder.model.notes).value, '');
assert.equal(binder.for(binder.model.customer.fullName).value, '');
assert.equal(binder.model.valueOf(), binder.value);
assert.equal(binder.model.notes.valueOf(), '');
assert.equal(binder.model.customer.fullName.valueOf(), '');
});
it('should change value on setValue', () => {
// Sanity check: requestUpdate should not be called
expect(requestUpdateStub).to.not.be.called;
binder.for(binder.model.notes).value = 'foo';
assert.equal(binder.value.notes, 'foo');
expect(requestUpdateStub).to.be.calledOnce;
});
it('should change value on deep setValue', () => {
expect(requestUpdateStub).to.not.be.called;
binder.for(binder.model.customer.fullName).value = 'foo';
assert.equal(binder.value.customer.fullName, 'foo');
expect(requestUpdateStub).to.be.calledOnce;
});
it('should not change defaultValue on setValue', () => {
binder.for(binder.model.notes).value = 'foo';
binder.for(binder.model.customer.fullName).value = 'foo';
assert.equal(binder.defaultValue.notes, '');
assert.equal(binder.defaultValue.customer.fullName, '');
});
it('should reset to default value', () => {
binder.for(binder.model.notes).value = 'foo';
binder.for(binder.model.customer.fullName).value = 'foo';
requestUpdateStub.reset();
binder.reset();
assert.equal(binder.value.notes, '');
assert.equal(binder.value.customer.fullName, '');
expect(requestUpdateStub).to.be.calledOnce;
});
it('should reset to provided value', () => {
binder.for(binder.model.notes).value = 'foo';
binder.for(binder.model.customer.fullName).value = 'foo';
requestUpdateStub.reset();
binder.read({
...expectedEmptyOrder,
notes: 'bar',
customer: {
...expectedEmptyOrder.customer,
fullName: 'bar',
},
});
assert.equal(binder.value.notes, 'bar');
assert.equal(binder.value.customer.fullName, 'bar');
expect(requestUpdateStub).to.be.calledOnce;
});
it('should clear value and default value', () => {
binder.read({
...expectedEmptyOrder,
notes: 'bar',
customer: {
...expectedEmptyOrder.customer,
fullName: 'bar',
},
});
requestUpdateStub.reset();
assert.notDeepEqual(binder.value, expectedEmptyOrder);
assert.notDeepEqual(binder.defaultValue, expectedEmptyOrder);
binder.clear();
assert.deepEqual(binder.value, expectedEmptyOrder);
assert.deepEqual(binder.defaultValue, expectedEmptyOrder);
expect(requestUpdateStub).to.be.calledOnce;
});
it('should update when clearing validation', async () => {
binder.clear();
const binderNode = binder.for(binder.model.customer.fullName);
await binderNode.validate();
assert.isTrue(binderNode.invalid);
requestUpdateStub.reset();
binder.clear();
assert.isFalse(binderNode.invalid);
expect(requestUpdateStub).to.be.calledOnce;
});
it('should not update excessively when nothing to clear', async () => {
binder.clear();
const binderNode = binder.for(binder.model.customer.fullName);
await binderNode.validate();
assert.isTrue(binderNode.invalid);
binder.clear();
requestUpdateStub.reset();
binder.clear();
expect(requestUpdateStub).to.not.be.called;
});
it('should forget visits on clear', () => {
const binderNode = binder.for(binder.model.customer.fullName);
binderNode.visited = true;
binder.clear();
assert.isFalse(binderNode.visited);
});
it('should be able to set null to object type property', () => {
const myBinder: Binder<TestEntity, TestModel<TestEntity>> = new Binder(document.createElement('div'), TestModel);
myBinder.for(myBinder.model.fieldAny).value = null;
myBinder.for(myBinder.model.fieldAny).validate();
assert.isFalse(myBinder.invalid);
});
it('should be able to set undefined to object type property', () => {
const myBinder: Binder<TestEntity, TestModel<TestEntity>> = new Binder(document.createElement('div'), TestModel);
myBinder.for(myBinder.model.fieldAny).value = undefined;
myBinder.for(myBinder.model.fieldAny).validate();
assert.isFalse(myBinder.invalid);
});
});
describe('optional', () => {
let binder: Binder<Employee, EmployeeModel<Employee>>;
const litEmployeeView = document.createElement('lit-employee-view') as LitEmployeeView;
const expectedEmptyEmployee: Employee = {
idString: '',
fullName: '',
supervisor: undefined,
colleagues: undefined,
};
beforeEach(() => {
binder = new Binder(litEmployeeView, EmployeeModel);
});
function getOnlyEmployeeData(e: Employee) {
const { idString, fullName } = e;
return { idString, fullName };
}
it('should not initialize optional in empty value', () => {
const emptyValue = EmployeeModel.createEmptyValue();
assert.isUndefined(emptyValue.supervisor);
});
it('should not initialize optional in binder value and default value', () => {
assert.isUndefined(binder.defaultValue.supervisor);
assert.deepEqual(binder.defaultValue, expectedEmptyEmployee);
// Ensure the key is present in the object
assert.isTrue('supervisor' in binder.defaultValue);
assert.isUndefined(binder.value.supervisor);
assert.deepEqual(binder.value, expectedEmptyEmployee);
assert.isTrue('supervisor' in binder.value);
});
it('should not initialize optional on binderNode access', () => {
binder.for(binder.model.supervisor);
assert.isUndefined(binder.defaultValue.supervisor);
assert.deepEqual(binder.defaultValue, expectedEmptyEmployee);
assert.isTrue('supervisor' in binder.defaultValue);
assert.isUndefined(binder.value.supervisor);
assert.deepEqual(binder.value, expectedEmptyEmployee);
assert.isTrue('supervisor' in binder.value);
});
it('should initialize parent optional on child binderNode access', () => {
binder.for(binder.model.supervisor.supervisor);
assert.isDefined(binder.defaultValue.supervisor);
assert.deepEqual(binder.defaultValue.supervisor, expectedEmptyEmployee);
assert.deepEqual(getOnlyEmployeeData(binder.defaultValue), getOnlyEmployeeData(expectedEmptyEmployee));
assert.isDefined(binder.value.supervisor);
assert.deepEqual(binder.value.supervisor, expectedEmptyEmployee);
assert.deepEqual(getOnlyEmployeeData(binder.value), getOnlyEmployeeData(expectedEmptyEmployee));
});
it('should not become dirty on binderNode access', () => {
assert.isFalse(binder.dirty);
binder.for(binder.model.supervisor);
assert.isFalse(binder.dirty);
binder.for(binder.model.supervisor.supervisor);
assert.isFalse(binder.dirty);
});
it('should not fail validation for non-initialised object or array', async () => {
await binder.validate();
assert.isFalse(binder.invalid);
// Populate non-initialised optional field with data
binder.value = { ...binder.value, supervisor: expectedEmptyEmployee };
await binder.validate();
assert.isFalse(binder.invalid);
// Populate non-initialised optional field with deep optional data
binder.value = {
...binder.value,
supervisor: {
...expectedEmptyEmployee,
supervisor: expectedEmptyEmployee,
},
};
await binder.validate();
assert.isFalse(binder.invalid);
});
it('should allow to reset optional object or array', async () => {
// Start from fields with optional data
binder.read({
...binder.value,
supervisor: expectedEmptyEmployee,
colleagues: [expectedEmptyEmployee],
});
await binder.validate();
assert.isFalse(binder.invalid);
// Reset optionals back to undefined
binder.value = expectedEmptyEmployee;
await binder.validate();
assert.isFalse(binder.invalid);
});
// https://github.com/vaadin/hilla/issues/43
it('should be able to bind to a nested property of an optional parent', async () => {
const superNameNode = binder.for(binder.model.supervisor.fullName);
binder.read({
...expectedEmptyEmployee,
});
assert.equal('', superNameNode.value);
});
// https://github.com/vaadin/hilla/issues/43
it('should be able to read a nested property of an optional parent after clear', async () => {
const superNameNode = binder.for(binder.model.supervisor.fullName);
binder.clear();
assert.equal('', superNameNode.value);
});
});
}); | the_stack |
import {
computed,
defineComponent,
inject,
nextTick,
onBeforeUnmount,
onMounted,
provide,
reactive,
ref,
toRefs,
VNode,
watch,
} from 'vue';
import { CheckCircleFilledIcon, CloseCircleFilledIcon, ErrorCircleFilledIcon } from 'tdesign-icons-vue-next';
import cloneDeep from 'lodash/cloneDeep';
import lodashGet from 'lodash/get';
import lodashSet from 'lodash/set';
import isNil from 'lodash/isNil';
import lodashTemplate from 'lodash/template';
import { validate } from './form-model';
import {
AllValidateResult,
Data,
FormErrorMessage,
FormItemValidateMessage,
ValidateTriggerType,
ValueType,
} from './type';
import props from './form-item-props';
import {
ErrorListType,
FormInjectionKey,
FormItemContext,
FormItemInjectionKey,
SuccessListType,
useCLASSNAMES,
} from './const';
import { useConfig, usePrefixClass, useTNodeJSX } from '../hooks';
type IconConstructor = typeof ErrorCircleFilledIcon;
export type FormItemValidateResult<T extends Data = Data> = { [key in keyof T]: boolean | AllValidateResult[] };
export const enum ValidateStatus {
TO_BE_VALIDATED = 'not',
SUCCESS = 'success',
FAIL = 'fail',
}
export default defineComponent({
name: 'TFormItem',
props: { ...props },
setup(props) {
const renderContent = useTNodeJSX();
const CLASS_NAMES = useCLASSNAMES();
const { global } = useConfig('form');
const form = inject(FormInjectionKey, undefined);
const FORM_ITEM_CLASS_PREFIX = usePrefixClass('form-item__');
const needRequiredMark = computed(() => {
const { requiredMark } = props;
if (typeof requiredMark === 'boolean') return requiredMark;
const parentRequiredMark = form?.requiredMark === undefined ? global.value.requiredMark : form?.requiredMark;
const isRequired = innerRules.value.filter((rule) => rule.required).length > 0;
return Boolean(parentRequiredMark && isRequired);
});
const hasColon = computed(() => !!(form?.colon && renderContent('label')));
const FROM_LABEL = usePrefixClass('form__label');
const labelAlign = computed(() => (isNil(props.labelAlign) ? form?.labelAlign : props.labelAlign));
const labelWidth = computed(() => (isNil(props.labelWidth) ? form?.labelWidth : props.labelWidth));
const labelClasses = computed(() => [
CLASS_NAMES.value.label,
{
[`${FROM_LABEL.value}--required`]: needRequiredMark.value,
[`${FROM_LABEL.value}--colon`]: hasColon.value,
[`${FROM_LABEL.value}--top`]: labelAlign.value === 'top' || !labelWidth.value,
[`${FROM_LABEL.value}--left`]: labelAlign.value === 'left' && labelWidth.value,
[`${FROM_LABEL.value}--right`]: labelAlign.value === 'right' && labelWidth.value,
},
]);
const renderLabel = () => {
if (Number(labelWidth.value) === 0) return;
let labelStyle = {};
if (labelWidth.value && labelAlign.value !== 'top') {
if (typeof labelWidth.value === 'number') {
labelStyle = { width: `${labelWidth.value}px` };
} else {
labelStyle = { width: labelWidth.value };
}
}
return (
<div class={labelClasses.value} style={labelStyle}>
<label for={props.for}>{renderContent('label')}</label>
</div>
);
};
/** Suffix Icon */
const getDefaultIcon = (): VNode => {
const resultIcon = (Icon: IconConstructor) => (
<span class={CLASS_NAMES.value.status}>
<Icon />
</span>
);
const list = errorList.value;
if (verifyStatus.value === ValidateStatus.SUCCESS) {
return resultIcon(CheckCircleFilledIcon);
}
if (list?.[0]) {
const type = list[0].type || 'error';
const icon =
{
error: CloseCircleFilledIcon,
warning: ErrorCircleFilledIcon,
}[type] || CheckCircleFilledIcon;
return resultIcon(icon as IconConstructor);
}
return null;
};
const renderSuffixIcon = () => {
const { statusIcon } = props;
if (statusIcon === false) return;
let resultIcon = renderContent('statusIcon', {
defaultNode: getDefaultIcon(),
});
if (resultIcon) return <span className={CLASS_NAMES.value.status}>{resultIcon}</span>;
if (resultIcon === false) return;
resultIcon = form?.renderContent('statusIcon', { defaultNode: getDefaultIcon() });
if (resultIcon) return resultIcon;
};
/** Suffix Icon END */
/** Content Style */
const errorClasses = computed(() => {
if (!showErrorMessage.value) return '';
if (verifyStatus.value === ValidateStatus.SUCCESS) {
return props.successBorder
? [CLASS_NAMES.value.success, CLASS_NAMES.value.successBorder].join(' ')
: CLASS_NAMES.value.success;
}
if (!errorList.value.length) return;
const type = errorList.value[0].type || 'error';
return type === 'error' ? CLASS_NAMES.value.error : CLASS_NAMES.value.warning;
});
const contentClasses = computed(() => [CLASS_NAMES.value.controls, errorClasses.value]);
const contentStyle = computed(() => {
let contentStyle = {};
if (labelWidth.value && labelAlign.value !== 'top') {
if (typeof labelWidth.value === 'number') {
contentStyle = { marginLeft: `${labelWidth.value}px` };
} else {
contentStyle = { marginLeft: labelWidth.value };
}
}
return contentStyle;
});
/** Content Style END */
const errorList = ref<ErrorListType[]>([]);
const successList = ref<SuccessListType[]>([]);
const verifyStatus = ref(ValidateStatus.TO_BE_VALIDATED);
const resetValidating = ref(false);
const needResetField = ref(false);
const resetHandler = () => {
needResetField.value = false;
errorList.value = [];
successList.value = [];
verifyStatus.value = ValidateStatus.TO_BE_VALIDATED;
};
const getEmptyValue = (): ValueType => {
const type = Object.prototype.toString.call(lodashGet(form?.data, props.name));
let emptyValue: ValueType;
if (type === '[object String]') {
emptyValue = '';
}
if (type === '[object Array]') {
emptyValue = [];
}
if (type === '[object Object]') {
emptyValue = {};
}
return emptyValue;
};
const resetField = async (resetType?: 'initial' | 'empty') => {
if (!props.name) return;
if (resetType !== undefined) {
resetType === 'empty' && lodashSet(form?.data, props.name, getEmptyValue());
resetType === 'initial' && lodashSet(form?.data, props.name, initialValue.value);
} else {
form?.resetType === 'empty' && lodashSet(form?.data, props.name, getEmptyValue());
form?.resetType === 'initial' && lodashSet(form?.data, props.name, initialValue.value);
}
await nextTick();
if (resetValidating.value) {
needResetField.value = true;
} else {
resetHandler();
}
};
const errorMessages = computed<FormErrorMessage>(() => form?.errorMessage ?? global.value.errorMessage);
const innerRules = computed(() => {
if (props.rules?.length) return props.rules;
if (!props.name) return [];
const index = props.name.lastIndexOf('.') || -1;
const pRuleName = props.name.slice(index + 1);
return lodashGet(form?.rules, props.name) || lodashGet(form?.rules, pRuleName) || [];
});
async function validateHandler<T>(trigger: ValidateTriggerType): Promise<FormItemValidateResult<T>> {
resetValidating.value = true;
const rules =
trigger === 'all'
? innerRules.value
: innerRules.value.filter((item) => (item.trigger || 'change') === trigger);
if (!rules?.length) {
resetValidating.value = false;
return;
}
const res = await validate(value.value, rules);
errorList.value = res
.filter((item) => item.result !== true)
.map((item: ErrorListType) => {
Object.keys(item).forEach((key) => {
if (!item.message && errorMessages.value[key]) {
const compiled = lodashTemplate(errorMessages.value[key]);
item.message = compiled({
name: props.label,
validate: item[key],
});
}
});
return item;
});
// 仅有自定义校验方法才会存在 successList
successList.value = res.filter(
(item) => item.result === true && item.message && item.type === 'success',
) as SuccessListType[];
// 根据校验结果设置校验状态
if (rules.length) {
verifyStatus.value = errorList.value.length ? ValidateStatus.FAIL : ValidateStatus.SUCCESS;
} else {
verifyStatus.value = ValidateStatus.TO_BE_VALIDATED;
}
// 重置处理
if (needResetField.value) {
resetHandler();
}
resetValidating.value = false;
return {
[props.name]: errorList.value.length === 0 ? true : res,
} as FormItemValidateResult<T>;
}
const setValidateMessage = (validateMessage: FormItemValidateMessage[]) => {
if (!validateMessage && !Array.isArray(validateMessage)) return;
if (validateMessage.length === 0) {
errorList.value = [];
verifyStatus.value = ValidateStatus.SUCCESS;
}
errorList.value = validateMessage.map((item) => ({ ...item, result: false }));
verifyStatus.value = ValidateStatus.FAIL;
};
const value = computed<ValueType>(() => form?.data && lodashGet(form?.data, props.name));
const initialValue = ref<ValueType>(undefined);
const { name } = toRefs(props);
const context: FormItemContext = reactive({
name,
resetHandler,
resetField,
validate: validateHandler,
setValidateMessage,
});
onMounted(() => {
initialValue.value = cloneDeep(value.value);
form?.children.push(context);
});
onBeforeUnmount(() => {
if (form) form.children = form?.children.filter((ctx) => ctx !== context);
});
watch(
value,
async () => {
await validateHandler('change');
},
{ deep: true },
);
const showErrorMessage = computed(() => {
if (typeof props.showErrorMessage === 'boolean') return props.showErrorMessage;
return form?.showErrorMessage;
});
const classes = computed(() => [
CLASS_NAMES.value.formItem,
FORM_ITEM_CLASS_PREFIX.value + props.name,
{
[CLASS_NAMES.value.formItemWithHelp]: helpNode.value,
[CLASS_NAMES.value.formItemWithExtra]: extraNode.value,
},
]);
const helpNode = computed<VNode>(() => {
if (props.help) {
return <div class={CLASS_NAMES.value.help}>{props.help}</div>;
}
return null;
});
const extraNode = computed<VNode>(() => {
const getExtraNode = (content: string) => <div class={CLASS_NAMES.value.extra}>{content}</div>;
const list = errorList.value;
if (showErrorMessage.value && list?.[0]?.message) {
return getExtraNode(list[0].message);
}
if (successList.value.length) {
return getExtraNode(successList.value[0].message);
}
return null;
});
const handleBlur = async () => {
await validateHandler('blur');
};
provide(FormItemInjectionKey, {
handleBlur,
});
return () => (
<div class={classes.value}>
{renderLabel()}
<div class={contentClasses.value} style={contentStyle.value}>
<div class={CLASS_NAMES.value.controlsContent}>
{renderContent('default')}
{renderSuffixIcon()}
</div>
{[helpNode.value, extraNode.value]}
</div>
</div>
);
},
}); | the_stack |
import { Maps } from '../../index';
import { BubbleSettingsModel, ColorMapping, IBubbleRenderingEventArgs, bubbleRendering } from '../index';
import { IBubbleClickEventArgs, bubbleClick, LayerSettings, IBubbleMoveEventArgs, bubbleMouseMove } from '../index';
import { isNullOrUndefined } from '@syncfusion/ej2-base';
import { CircleOption, MapLocation, findMidPointOfPolygon, Point, drawCircle, elementAnimate, getTranslate } from '../utils/helper';
import { RectOption, Rect, drawRectangle, checkPropertyPath, getZoomTranslate, getRatioOfBubble, maintainSelection,
getValueFromObject } from '../utils/helper';
import { BorderModel } from '../model/base-model';
/**
* Bubble module class
*/
export class Bubble {
private maps: Maps;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public bubbleCollection: any[];
/**
* Bubble Id for current layer
*/
public id: string = '';
constructor(maps: Maps) {
this.maps = maps;
this.bubbleCollection = [];
}
// eslint-disable-next-line valid-jsdoc
/**
* To render bubble
*
* @private
*/
public renderBubble(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
bubbleSettings: BubbleSettingsModel, shapeData: any, color: string, range: { min: number, max: number },
bubbleIndex: number, dataIndex: number, layerIndex: number, layer: LayerSettings, group: Element, bubbleID? : string
): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const layerData: any[] = layer.layerData; const colorValuePath: string = bubbleSettings.colorValuePath;
const equalValue: string = (!isNullOrUndefined(colorValuePath)) ? ((colorValuePath.indexOf('.') > -1) ?
(getValueFromObject(shapeData, bubbleSettings.colorValuePath)) : shapeData[colorValuePath]) : shapeData[colorValuePath];
const colorValue: number = (!isNullOrUndefined(colorValuePath)) ? ((colorValuePath.indexOf('.') > -1) ?
Number(getValueFromObject(shapeData, bubbleSettings.colorValuePath)) : Number(shapeData[colorValuePath])) :
Number(shapeData[colorValuePath]);
const bubbleValue: number = (!isNullOrUndefined(bubbleSettings.valuePath)) ? ((bubbleSettings.valuePath.indexOf('.') > -1) ?
Number(getValueFromObject(shapeData, bubbleSettings.valuePath)) : Number(shapeData[bubbleSettings.valuePath])) :
Number(shapeData[bubbleSettings.valuePath]);
let opacity: number; let bubbleColor: string;
if (isNaN(bubbleValue) && isNaN(colorValue) && isNullOrUndefined(equalValue)) {
return null;
}
let radius: number = getRatioOfBubble(bubbleSettings.minRadius, bubbleSettings.maxRadius, bubbleValue, range.min, range.max);
const colorMapping: ColorMapping = new ColorMapping(this.maps);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const shapeColor: any = colorMapping.getColorByValue(bubbleSettings.colorMapping, colorValue, equalValue);
// eslint-disable-next-line prefer-const
bubbleColor = (Object.prototype.toString.call(shapeColor) === '[object Object]' &&
!isNullOrUndefined(shapeColor['fill'])) ? shapeColor['fill'] : color;
// eslint-disable-next-line prefer-const
opacity = (Object.prototype.toString.call(shapeColor) === '[object Object]' &&
!isNullOrUndefined(shapeColor['opacity'])) ? shapeColor['opacity'] : bubbleSettings.opacity;
const shapePoints: [MapLocation[]] = [[]]; this.maps.translateType = 'bubble';
let midIndex: number = 0; let pointsLength: number = 0; let currentLength: number = 0;
for (let i: number = 0, len: number = layerData.length; i < len; i++) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let shape: any = layerData[i];
shape = shape['property'];
const shapePath: string = checkPropertyPath(shapeData[layer.shapeDataPath], layer.shapePropertyPath, shape);
const shapeDataLayerPathValue : string = !isNullOrUndefined(shapeData[layer.shapeDataPath]) &&
isNaN(shapeData[layer.shapeDataPath]) ? shapeData[layer.shapeDataPath].toLowerCase() : shapeData[layer.shapeDataPath];
const shapePathValue : string = !isNullOrUndefined(shape[shapePath]) && isNaN(shape[shapePath])
? shape[shapePath].toLowerCase() : shape[shapePath];
if (shapeDataLayerPathValue === shapePathValue && layerData[i].type !== 'LineString') {
if (layerData[i]['type'] === 'Point') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
shapePoints.push(this.getPoints(<any[]>layerData[i], []));
} else if (!layerData[i]['_isMultiPolygon']) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
shapePoints.push(this.getPoints(layerData[i] as any[], []));
currentLength = shapePoints[shapePoints.length - 1].length;
if (pointsLength < currentLength) {
pointsLength = currentLength;
midIndex = shapePoints.length - 1;
}
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const layer: any[] = <any[]>layerData[i];
for (let j: number = 0; j < layer.length; j++) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
shapePoints.push(this.getPoints(layer[j] as any[], []));
currentLength = shapePoints[shapePoints.length - 1].length;
if (pointsLength < currentLength) {
pointsLength = currentLength;
midIndex = shapePoints.length - 1;
}
}
}
}
}
const projectionType: string = this.maps.projectionType;
let centerY: number; let eventArgs: IBubbleRenderingEventArgs;
const bubbleBorder: BorderModel = {
color: bubbleSettings.border.color, opacity: bubbleSettings.border.opacity,
width: bubbleSettings.border.width
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const center: any = findMidPointOfPolygon(shapePoints[midIndex], projectionType, layer.geometryType);
if (bubbleSettings.visible) {
if (!isNullOrUndefined(center)) {
centerY = this.maps.projectionType === 'Mercator' ? center['y'] : (-center['y']);
eventArgs = {
cancel: false, name: bubbleRendering, border: bubbleBorder,
cx: center['x'], cy: centerY, data: shapeData, fill: bubbleColor,
maps: this.maps, radius: radius
};
} else {
const shapePointsLength: number = shapePoints.length - 1;
if (shapePoints[shapePointsLength]['x'] && shapePoints[shapePointsLength]['y']) {
eventArgs = {
cancel: false, name: bubbleRendering, border: bubbleBorder,
cx: shapePoints[shapePointsLength]['x'], cy: shapePoints[shapePointsLength]['y'],
data: shapeData, fill: bubbleColor, maps: this.maps,
radius: radius
};
} else {
return;
}
}
this.maps.trigger('bubbleRendering', eventArgs, (bubbleArgs: IBubbleRenderingEventArgs) => {
if (eventArgs.cancel) {
return;
}
let bubbleElement: Element;
eventArgs.border.opacity = isNullOrUndefined(eventArgs.border.opacity) ? opacity : eventArgs.border.opacity;
if (bubbleSettings.bubbleType === 'Circle') {
const circle: CircleOption = new CircleOption(
bubbleID, eventArgs.fill, eventArgs.border, opacity,
0, 0, eventArgs.radius, null
);
bubbleElement = drawCircle(this.maps, circle, group);
} else {
const y: number = this.maps.projectionType === 'Mercator' ? (eventArgs.cy - radius) : (eventArgs.cy + radius);
const rectangle: RectOption = new RectOption(
bubbleID, eventArgs.fill, eventArgs.border, opacity,
new Rect(0, 0, radius * 2, radius * 2), 2, 2
);
eventArgs.cx -= radius; eventArgs.cy = y;
bubbleElement = drawRectangle(this.maps, rectangle, group);
}
maintainSelection(this.maps.selectedBubbleElementId, this.maps.bubbleSelectionClass, bubbleElement,
'BubbleselectionMapStyle');
this.bubbleCollection.push({
LayerIndex: layerIndex,
BubbleIndex: bubbleIndex,
DataIndex: dataIndex,
element: bubbleElement,
center: { x: eventArgs.cx, y: eventArgs.cy }
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let translate: any;
const animate: boolean = layer.animationDuration !== 0 || isNullOrUndefined(this.maps.zoomModule);
if (this.maps.zoomSettings.zoomFactor > 1 && !isNullOrUndefined(this.maps.zoomModule)) {
translate = getZoomTranslate(this.maps, layer, animate);
} else {
translate = getTranslate(this.maps, layer, animate);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const bubbleDataSource: any[] = bubbleSettings.dataSource as any[];
const scale: number = translate['scale']; const transPoint: Point = translate['location'] as Point;
const position: MapLocation = new MapLocation(
(this.maps.isTileMap ? (eventArgs.cx) : ((eventArgs.cx + transPoint.x) * scale)),
(this.maps.isTileMap ? (eventArgs.cy) : ((eventArgs.cy + transPoint.y) * scale)));
bubbleElement.setAttribute('transform', 'translate( ' + (position.x) + ' ' + (position.y) + ' )');
const bubble: string = (bubbleDataSource.length - 1) === dataIndex ? 'bubble' : null;
if (bubbleSettings.bubbleType === 'Square') {
position.x += radius;
position.y += radius * (this.maps.projectionType === 'Mercator' ? 1 : -1);
} else {
radius = 0;
}
if (bubbleSettings.animationDuration > 0) {
elementAnimate(
bubbleElement, bubbleSettings.animationDelay, bubbleSettings.animationDuration, position, this.maps, bubble, radius
);
}
});
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getPoints(shape: any[], points: MapLocation[]): MapLocation[] {
if (isNullOrUndefined(shape.map)) {
points = shape['point'];
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
shape.map((current: any, index: number) => {
points.push(new Point(current['point']['x'], current['point']['y']));
});
}
return points;
}
// eslint-disable-next-line valid-jsdoc
/**
* To check and trigger bubble click event
*
* @private
*/
public bubbleClick(e: PointerEvent): void {
const target: string = (e.target as Element).id;
if (target.indexOf('_LayerIndex_') === -1) {
return;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data: any = this.getbubble(target);
if (isNullOrUndefined(data)) {
return;
}
const eventArgs: IBubbleClickEventArgs = {
cancel: false, name: bubbleClick, data: data, maps: this.maps,
target: target, x: e.clientX, y: e.clientY
};
this.maps.trigger(bubbleClick, eventArgs);
}
/**
* To get bubble from target id
*
* @param {string} target - Specifies the target
* @returns {object} - Returns the object
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private getbubble(target: string): any {
const id: string[] = target.split('_LayerIndex_');
const index: number = parseInt(id[1].split('_')[0], 10);
const layer: LayerSettings = <LayerSettings>this.maps.layers[index];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let data: any;
if (target.indexOf('_BubbleIndex_') > -1) {
const bubbleIndex: number = parseInt(id[1].split('_BubbleIndex_')[1], 10);
const dataIndex: number = parseInt(id[1].split('_BubbleIndex_')[1].split('_dataIndex_')[1], 10);
if (!isNaN(bubbleIndex)) {
data = layer.bubbleSettings[bubbleIndex].dataSource[dataIndex];
return data;
}
}
return null;
}
// eslint-disable-next-line valid-jsdoc
/**
* To check and trigger bubble move event
*
* @private
*/
public bubbleMove(e: PointerEvent): void {
const target: string = (e.target as Element).id;
if (target.indexOf('_LayerIndex_') === -1) {
return;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data: any = this.getbubble(target);
if (isNullOrUndefined(data)) {
return;
}
const eventArgs: IBubbleMoveEventArgs = {
cancel: false, name: bubbleMouseMove, data: data, maps: this.maps,
target: target, x: e.clientX, y: e.clientY
};
this.maps.trigger(bubbleMouseMove, eventArgs);
}
/**
* Get module name.
*
* @returns {string} - Returns the module name.
*/
protected getModuleName(): string {
return 'Bubble';
}
/**
* To destroy the bubble.
*
* @param {Maps} maps - Specifies the instance of the maps.
* @returns {void}
* @private
*/
public destroy(maps: Maps): void {
/**
* Destroy method performed here
*/
}
} | the_stack |
import * as ethers from 'ethers'
import { AbstractContract, RevertError, expect, BigNumber } from './utils'
import * as utils from './utils'
import {
ERC1155MetaMintBurnPackedBalanceMock,
ERC1155ReceiverMock
} from 'src/gen/typechain'
// init test wallets from package.json mnemonic
import { web3 } from 'hardhat'
const { wallet: ownerWallet, provider: ownerProvider, signer: ownerSigner } = utils.createTestWallet(web3, 1)
const { wallet: receiverWallet, provider: receiverProvider, signer: receiverSigner } = utils.createTestWallet(web3, 2)
const { wallet: anyoneWallet, provider: anyoneProvider, signer: anyoneSigner } = utils.createTestWallet(web3, 3)
const { wallet: operatorWallet, provider: operatorProvider, signer: operatorSigner } = utils.createTestWallet(web3, 4)
describe('ERC1155MintBurnPackedBalance', () => {
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
let ownerAddress: string
let receiverAddress: string
let anyoneAddress: string
let operatorAddress: string
let erc1155MintBurnContract: ERC1155MetaMintBurnPackedBalanceMock
let anyoneERC1155MintBurnContract: ERC1155MetaMintBurnPackedBalanceMock
let receiverContract: ERC1155ReceiverMock
context('When ERC1155MintBurn contract is deployed', () => {
before(async () => {
ownerAddress = await ownerWallet.getAddress()
receiverAddress = await receiverWallet.getAddress()
anyoneAddress = await anyoneWallet.getAddress()
operatorAddress = await operatorWallet.getAddress()
})
beforeEach(async () => {
const abstractReceiver = await AbstractContract.fromArtifactName('ERC1155ReceiverMock')
receiverContract = (await abstractReceiver.deploy(ownerWallet)) as ERC1155ReceiverMock
const abstract = await AbstractContract.fromArtifactName('ERC1155MetaMintBurnPackedBalanceMock')
erc1155MintBurnContract = (await abstract.deploy(ownerWallet)) as ERC1155MetaMintBurnPackedBalanceMock
anyoneERC1155MintBurnContract = (await erc1155MintBurnContract.connect(
anyoneSigner
)) as ERC1155MetaMintBurnPackedBalanceMock
})
describe('_mint() function', () => {
const tokenID = 666
const amount = 11
it('should ALLOW inheriting contract to call mint()', async () => {
const tx = erc1155MintBurnContract.mintMock(receiverAddress, tokenID, amount, [])
await expect(tx).to.be.fulfilled
})
it('should NOT allow anyone to call _mint()', async () => {
const transaction = {
to: erc1155MintBurnContract.address,
data:
'0x7776afa0000000000000000000000000b87213121fb89cbd8b877cb1bb3ff84dd2869cfa' +
'000000000000000000000000000000000000000000000000000000000000029a0000000000000000' +
'00000000000000000000000000000000000000000000000b'
}
const tx = anyoneWallet.sendTransaction(transaction)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155MetaMintBurnPackedBalanceMock: INVALID_METHOD'))
})
it('should increase the balance of receiver by the right amount', async () => {
const recipientBalanceA = await erc1155MintBurnContract.balanceOf(receiverAddress, tokenID)
await erc1155MintBurnContract.mintMock(receiverAddress, tokenID, amount, [])
const recipientBalanceB = await erc1155MintBurnContract.balanceOf(receiverAddress, tokenID)
expect(recipientBalanceB).to.be.eql(recipientBalanceA.add(amount))
})
it('should REVERT if amount is larger than limit (overflow 1)', async () => {
await erc1155MintBurnContract.mintMock(receiverAddress, tokenID, amount, [])
const maxVal0 = BigNumber.from(2)
.pow(32)
.sub(amount)
const tx0 = erc1155MintBurnContract.mintMock(receiverAddress, tokenID, maxVal0, [])
await expect(tx0).to.be.rejectedWith(RevertError('ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW'))
})
it('should REVERT if amount is larger than limit (invalid amount by 1)', async () => {
const maxVal = BigNumber.from(2).pow(32)
const tx = erc1155MintBurnContract.mintMock(anyoneWallet.address, 0, maxVal, [])
await expect(tx).to.be.rejectedWith(RevertError('ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW'))
})
it('should REVERT if amount is larger than limit(invalid amount min overflow)', async () => {
const maxVal = BigNumber.from(2).pow(32)
// Set balance to max acceptable value
await erc1155MintBurnContract.mintMock(anyoneWallet.address, 0, maxVal.sub(1), [])
const balance = await erc1155MintBurnContract.balanceOf(anyoneWallet.address, 0)
await expect(balance).to.be.eql(maxVal.sub(1))
// Value that overflows solidity, but result is < maxVal
// Minimum overflow
const maxVal2 = BigNumber.from(2)
.pow(256)
.sub(maxVal.sub(1))
const tx = erc1155MintBurnContract.mintMock(anyoneWallet.address, 0, maxVal2, [])
await expect(tx).to.be.rejectedWith(RevertError('ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW'))
})
it('should REVERT if amount is larger than limit (invalid amount max overflow)', async () => {
// Maximum overflow
const maxVal = BigNumber.from(2)
.pow(256)
.sub(1)
const tx = erc1155MintBurnContract.mintMock(anyoneWallet.address, 0, maxVal, [])
await expect(tx).to.be.rejectedWith(RevertError('ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW'))
})
it('should REVERT when sending to non-receiver contract', async () => {
const tx = erc1155MintBurnContract.mintMock(erc1155MintBurnContract.address, tokenID, amount, [])
await expect(tx).to.be.rejectedWith(RevertError('ERC1155MetaMintBurnPackedBalanceMock: INVALID_METHOD'))
})
it('should REVERT if invalid response from receiver contract', async () => {
await receiverContract.setShouldReject(true)
const tx = erc1155MintBurnContract.mintMock(receiverContract.address, tokenID, amount, [])
await expect(tx).to.be.rejectedWith(
RevertError('ERC1155PackedBalance#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE')
)
})
it('should pass if valid response from receiver contract', async () => {
const tx = erc1155MintBurnContract.mintMock(receiverContract.address, tokenID, amount, [])
await expect(tx).to.be.fulfilled
})
it('should pass if data is not null to receiver contract', async () => {
const data = ethers.utils.toUtf8Bytes('Hello from the other side')
// NOTE: typechain generates the wrong type for `bytes` type at this time
// see https://github.com/ethereum-ts/TypeChain/issues/123
// @ts-ignore
const tx = erc1155MintBurnContract.mintMock(receiverContract.address, tokenID, amount, data)
await expect(tx).to.be.fulfilled
})
it('should have balances updated before onERC1155Received is called', async () => {
const toPreBalance = await erc1155MintBurnContract.balanceOf(receiverContract.address, tokenID)
// Get event filter to get internal tx event
const filterFromReceiverContract = receiverContract.filters.TransferSingleReceiver(null, null, null, null)
await erc1155MintBurnContract.mintMock(receiverContract.address, tokenID, amount, [])
// Get logs from internal transaction event
// @ts-ignore (https://github.com/ethers-io/ethers.js/issues/204#issuecomment-427059031)
filterFromReceiverContract.fromBlock = 0
const logs = await ownerProvider.getLogs(filterFromReceiverContract)
const args = receiverContract.interface.decodeEventLog(
receiverContract.interface.events['TransferSingleReceiver(address,address,uint256,uint256)'],
logs[0].data,
logs[0].topics
)
expect(args._from).to.be.eql(ZERO_ADDRESS)
expect(args._to).to.be.eql(receiverContract.address)
expect(args._toBalance).to.be.eql(toPreBalance.add(amount))
})
it('should have TransferSingle event emitted before onERC1155Received is called', async () => {
// Get event filter to get internal tx event
const tx = await erc1155MintBurnContract.mintMock(receiverContract.address, tokenID, amount, [])
const receipt = await tx.wait(1)
const firstEventTopic = receipt.logs![0].topics[0]
const secondEventTopic = receipt.logs![1].topics[0]
expect(firstEventTopic).to.be.equal(
erc1155MintBurnContract.interface.getEventTopic(
erc1155MintBurnContract.interface.events['TransferSingle(address,address,address,uint256,uint256)']
)
)
expect(secondEventTopic).to.be.equal(
receiverContract.interface.getEventTopic(
receiverContract.interface.events['TransferSingleReceiver(address,address,uint256,uint256)']
)
)
})
it('should emit a Transfer event', async () => {
const tx = await erc1155MintBurnContract.mintMock(receiverAddress, tokenID, amount, [])
const receipt = await tx.wait(1)
const ev = receipt.events![0]
expect(ev.event).to.be.eql('TransferSingle')
})
it('should have 0x0 as `from` argument in Transfer event', async () => {
const tx = await erc1155MintBurnContract.mintMock(receiverAddress, tokenID, amount, [])
const receipt = await tx.wait(1)
// TODO: this form can be improved eventually as ethers improves its api
// or we write a wrapper function to parse the tx
const ev = receipt.events![0]
const args = ev.args! as any
expect(args._from).to.be.eql(ZERO_ADDRESS)
})
})
describe('_batchMint() function', () => {
const Ntypes = 123
const amountToMint = 10
const typesArray = Array.apply(null, { length: Ntypes }).map(Number.call, Number)
const amountArray = Array.apply(null, Array(Ntypes)).map(Number.prototype.valueOf, amountToMint)
it('should ALLOW inheriting contract to call _batchMint()', async () => {
const req = erc1155MintBurnContract.batchMintMock(receiverAddress, typesArray, amountArray, [])
;(await expect(req).to.be.fulfilled) as ethers.ContractTransaction
})
it('should PASS if arrays are empty', async () => {
const tx = erc1155MintBurnContract.batchMintMock(receiverAddress, [], [], [])
await expect(tx).to.be.fulfilled
})
it('should NOT allow anyone to call _batchMint()', async () => {
const transaction = {
to: erc1155MintBurnContract.address,
data:
'0x2589aeae00000000000000000000000035ef07393b57464e93deb59175ff72e6499450cf' +
'00000000000000000000000000000000000000000000000000000000000000600000000000000000' +
'0000000000000000000000000000000000000000000000c000000000000000000000000000000000' +
'00000000000000000000000000000002000000000000000000000000000000000000000000000000' +
'00000000000000010000000000000000000000000000000000000000000000000000000000000002' +
'00000000000000000000000000000000000000000000000000000000000000020000000000000000' +
'00000000000000000000000000000000000000000000000a00000000000000000000000000000000' +
'0000000000000000000000000000000a'
}
const tx = anyoneWallet.sendTransaction(transaction)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155MetaMintBurnPackedBalanceMock: INVALID_METHOD'))
})
it('should increase the balances of receiver by the right amounts', async () => {
await erc1155MintBurnContract.batchMintMock(receiverAddress, typesArray, amountArray, [])
for (let i = 0; i < typesArray.length; i++) {
const balanceTo = await erc1155MintBurnContract.balanceOf(receiverAddress, typesArray[i])
expect(balanceTo).to.be.eql(BigNumber.from(amountArray[i]))
}
})
it('should REVERT when sending to non-receiver contract', async () => {
const tx = erc1155MintBurnContract.batchMintMock(erc1155MintBurnContract.address, typesArray, amountArray, [], {
gasLimit: 2000000
})
await expect(tx).to.be.rejectedWith(RevertError('ERC1155MetaMintBurnPackedBalanceMock: INVALID_METHOD'))
})
it('should REVERT if invalid response from receiver contract', async () => {
await receiverContract.setShouldReject(true)
const tx = erc1155MintBurnContract.batchMintMock(receiverContract.address, typesArray, amountArray, [], {
gasLimit: 2000000
})
await expect(tx).to.be.rejectedWith(
RevertError('ERC1155PackedBalance#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE')
)
})
it('should REVERT if amount is larger than limit (overflow 1)', async () => {
await erc1155MintBurnContract.batchMintMock(receiverAddress, typesArray, amountArray, [], { gasLimit: 2000000 })
// Overflow by 1
const maxVal0 = BigNumber.from(2)
.pow(32)
.sub(amountToMint)
const tx0 = erc1155MintBurnContract.batchMintMock(
receiverAddress,
[typesArray[0], typesArray[1]],
[maxVal0, amountArray[1]],
[]
)
await expect(tx0).to.be.rejectedWith(RevertError('ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW'))
})
it('should REVERT if amount is larger than limit (invalid amount 1)', async () => {
const maxVal = BigNumber.from(2).pow(32)
const tx2 = erc1155MintBurnContract.batchMintMock(anyoneWallet.address, [0, 1], [maxVal, 1], [])
await expect(tx2).to.be.rejectedWith(RevertError('ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW'))
})
it('should REVERT if amount is larger than limit (invalid amount min overflow', async () => {
const maxVal = BigNumber.from(2).pow(32)
// Set balance to max acceptable value
await erc1155MintBurnContract.batchMintMock(anyoneWallet.address, [0], [maxVal.sub(1)], [])
const balance = await erc1155MintBurnContract.balanceOf(anyoneWallet.address, 0)
await expect(balance).to.be.eql(maxVal.sub(1))
// Value that overflows solidity, but result is < maxVal
const maxVal2 = BigNumber.from(2)
.pow(256)
.sub(maxVal.sub(1))
const tx3 = erc1155MintBurnContract.batchMintMock(anyoneWallet.address, [0], [maxVal2], [])
await expect(tx3).to.be.rejectedWith(RevertError('ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW'))
})
it('should REVERT if amount is larger than limit (invalid amount max overflow)', async () => {
const maxVal = BigNumber.from(2).pow(32)
// Set balance to max acceptable value
await erc1155MintBurnContract.batchMintMock(anyoneWallet.address, [0], [maxVal.sub(1)], [])
const balance = await erc1155MintBurnContract.balanceOf(anyoneWallet.address, 0)
await expect(balance).to.be.eql(maxVal.sub(1))
const maxVal3 = BigNumber.from(2)
.pow(256)
.sub(1)
const tx4 = erc1155MintBurnContract.batchMintMock(anyoneWallet.address, [0], [maxVal3], [])
await expect(tx4).to.be.rejectedWith(RevertError('ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW'))
})
it('should pass if valid response from receiver contract', async () => {
const tx = erc1155MintBurnContract.batchMintMock(receiverContract.address, typesArray, amountArray, [], {
gasLimit: 6000000
})
await expect(tx).to.be.fulfilled
})
it('should pass if data is not null from receiver contract', async () => {
const data = ethers.utils.toUtf8Bytes('Hello from the other side')
// TODO: remove ts-ignore when contract declaration is fixed
// @ts-ignore
const tx = erc1155MintBurnContract.batchMintMock(receiverContract.address, typesArray, amountArray, data, {
gasLimit: 2000000
})
await expect(tx).to.be.fulfilled
})
it('should have balances updated before onERC1155BatchReceived is called', async () => {
const toAddresses = Array(typesArray.length).fill(receiverContract.address)
const toPreBalances = await erc1155MintBurnContract.balanceOfBatch(toAddresses, typesArray)
// Get event filter to get internal tx event
const filterFromReceiverContract = receiverContract.filters.TransferBatchReceiver(null, null, null, null)
await erc1155MintBurnContract.batchMintMock(receiverContract.address, typesArray, amountArray, [], { gasLimit: 2000000 })
// Get logs from internal transaction event
// @ts-ignore (https://github.com/ethers-io/ethers.js/issues/204#issuecomment-427059031)
filterFromReceiverContract.fromBlock = 0
const logs = await ownerProvider.getLogs(filterFromReceiverContract)
const args = receiverContract.interface.decodeEventLog(
receiverContract.interface.events['TransferBatchReceiver(address,address,uint256[],uint256[])'],
logs[0].data,
logs[0].topics
)
expect(args._from).to.be.eql(ZERO_ADDRESS)
expect(args._to).to.be.eql(receiverContract.address)
for (let i = 0; i < typesArray.length; i++) {
expect(args._toBalances[i]).to.be.eql(toPreBalances[i].add(amountArray[i]))
}
})
it('should have TransferBatch event emitted before onERC1155BatchReceived is called', async () => {
// Get event filter to get internal tx event
const tx = await erc1155MintBurnContract.batchMintMock(receiverContract.address, typesArray, amountArray, [], {
gasLimit: 2000000
})
const receipt = await tx.wait(1)
const firstEventTopic = receipt.logs![0].topics[0]
const secondEventTopic = receipt.logs![1].topics[0]
expect(firstEventTopic).to.be.equal(
erc1155MintBurnContract.interface.getEventTopic(
erc1155MintBurnContract.interface.events['TransferBatch(address,address,address,uint256[],uint256[])']
)
)
expect(secondEventTopic).to.be.equal(
erc1155MintBurnContract.interface.getEventTopic(
receiverContract.interface.events['TransferBatchReceiver(address,address,uint256[],uint256[])']
)
)
})
it('should emit 1 Transfer events of N transfers', async () => {
const tx = await erc1155MintBurnContract.batchMintMock(receiverAddress, typesArray, amountArray, [])
const receipt = await tx.wait()
const ev = receipt.events![0]
expect(ev.event).to.be.eql('TransferBatch')
const args = ev.args! as any
expect(args._ids.length).to.be.eql(typesArray.length)
})
it('should have 0x0 as `from` argument in Transfer events', async () => {
const tx = await erc1155MintBurnContract.batchMintMock(receiverAddress, typesArray, amountArray, [])
const receipt = await tx.wait()
const args = receipt.events![0].args! as any
expect(args._from).to.be.eql(ZERO_ADDRESS)
})
})
describe('_burn() function', () => {
const tokenID = 666
const initBalance = 100
const amountToBurn = 10
beforeEach(async () => {
await erc1155MintBurnContract.mintMock(receiverAddress, tokenID, initBalance, [])
})
it('should ALLOW inheriting contract to call _burn()', async () => {
const tx = erc1155MintBurnContract.burnMock(receiverAddress, tokenID, amountToBurn)
await expect(tx).to.be.fulfilled
})
it('should NOT allow anyone to call _burn()', async () => {
const transaction = {
to: erc1155MintBurnContract.address,
data:
'0x464a5ffb00000000000000000000000008970fed061e7747cd9a38d680a601510cb659fb' +
'000000000000000000000000000000000000000000000000000000000000029a0000000000000000' +
'00000000000000000000000000000000000000000000000a'
}
const tx = anyoneWallet.sendTransaction(transaction)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155MetaMintBurnPackedBalanceMock: INVALID_METHOD'))
})
it('should decrease the balance of receiver by the right amount', async () => {
const recipientBalanceA = await erc1155MintBurnContract.balanceOf(receiverAddress, tokenID)
await erc1155MintBurnContract.burnMock(receiverAddress, tokenID, amountToBurn)
const recipientBalanceB = await erc1155MintBurnContract.balanceOf(receiverAddress, tokenID)
expect(recipientBalanceB).to.be.eql(recipientBalanceA.sub(amountToBurn))
})
it('should REVERT if amount is hgher than balance', async () => {
// Sanity check
const balance = await erc1155MintBurnContract.balanceOf(receiverAddress, tokenID)
expect(balance).to.be.eql(BigNumber.from(initBalance))
// Invalid amount to burn that would cause underflow
const invalidVal = initBalance + 1
const tx = erc1155MintBurnContract.burnMock(receiverAddress, tokenID, invalidVal)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155PackedBalance#_viewUpdateBinValue: UNDERFLOW'))
})
it('should emit a Transfer event', async () => {
const tx = await erc1155MintBurnContract.burnMock(receiverAddress, tokenID, amountToBurn)
const receipt = await tx.wait(1)
const ev = receipt.events![0]
expect(ev.event).to.be.eql('TransferSingle')
})
it('should have 0x0 as `to` argument in Transfer event', async () => {
const tx = await erc1155MintBurnContract.burnMock(receiverAddress, tokenID, amountToBurn)
const receipt = await tx.wait(1)
// TODO: this form can be improved eventually as ethers improves its api
// or we write a wrapper function to parse the tx
const ev = receipt.events![0]
const args = ev.args! as any
expect(args._to).to.be.eql(ZERO_ADDRESS)
})
})
describe('_batchBurn() function', () => {
const Ntypes = 32
const initBalance = 100
const amountToBurn = 30
const typesArray = Array.apply(null, { length: Ntypes }).map(Number.call, Number)
const burnAmountArray = Array.apply(null, Array(Ntypes)).map(Number.prototype.valueOf, amountToBurn)
const initBalanceArray = Array.apply(null, Array(Ntypes)).map(Number.prototype.valueOf, initBalance)
beforeEach(async () => {
await erc1155MintBurnContract.batchMintMock(receiverAddress, typesArray, initBalanceArray, [])
})
it('should ALLOW inheriting contract to call _batchBurn()', async () => {
const req = erc1155MintBurnContract.batchBurnMock(receiverAddress, typesArray, burnAmountArray)
const tx = (await expect(req).to.be.fulfilled) as ethers.ContractTransaction
// const receipt = await tx.wait()
// console.log('Batch mint :' + receipt.gasUsed)
})
// Should call mock's fallback function
it('should NOT allow anyone to call _batchBurn()', async () => {
const transaction = {
to: erc1155MintBurnContract.address,
data:
'0xb389c3bb000000000000000000000000dc04977a2078c8ffdf086d618d1f961b6c546222' +
'00000000000000000000000000000000000000000000000000000000000000600000000000000000' +
'0000000000000000000000000000000000000000000000c000000000000000000000000000000000' +
'00000000000000000000000000000002000000000000000000000000000000000000000000000000' +
'00000000000000010000000000000000000000000000000000000000000000000000000000000003' +
'00000000000000000000000000000000000000000000000000000000000000020000000000000000' +
'00000000000000000000000000000000000000000000001e00000000000000000000000000000000' +
'0000000000000000000000000000001e'
}
const tx = anyoneWallet.sendTransaction(transaction)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155MetaMintBurnPackedBalanceMock: INVALID_METHOD'))
})
it('should decrease the balances of receiver by the right amounts', async () => {
await erc1155MintBurnContract.batchBurnMock(receiverAddress, typesArray, burnAmountArray)
for (let i = 0; i < typesArray.length; i++) {
const balanceTo = await erc1155MintBurnContract.balanceOf(receiverAddress, typesArray[i])
expect(balanceTo).to.be.eql(BigNumber.from(initBalance - burnAmountArray[i]))
}
})
it('should REVERT if amount is higher than balance', async () => {
// Sanity check
const balance = await erc1155MintBurnContract.balanceOf(receiverAddress, typesArray[0])
expect(balance).to.be.eql(BigNumber.from(initBalance))
// Invalid amount to burn that would cause underflow
const invalidVal = initBalance + 1
const tx = erc1155MintBurnContract.batchBurnMock(receiverAddress, [typesArray[0]], [invalidVal])
await expect(tx).to.be.rejectedWith(RevertError('ERC1155PackedBalance#_viewUpdateBinValue: UNDERFLOW'))
})
it('should emit 1 Transfer events of N transfers', async () => {
const tx = await erc1155MintBurnContract.batchBurnMock(receiverAddress, typesArray, burnAmountArray)
const receipt = await tx.wait()
const ev = receipt.events![0]
expect(ev.event).to.be.eql('TransferBatch')
const args = ev.args! as any
expect(args._ids.length).to.be.eql(typesArray.length)
})
it('should have 0x0 as `to` argument in Transfer events', async () => {
const tx = await erc1155MintBurnContract.batchBurnMock(receiverAddress, typesArray, burnAmountArray)
const receipt = await tx.wait()
const args = receipt.events![0].args! as any
expect(args._to).to.be.eql(ZERO_ADDRESS)
})
})
})
}) | the_stack |
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { AbstractClient } from "../../../common/abstract_client"
import { ClientConfig } from "../../../common/interface"
import {
TextWaybill,
RecognizeOnlineTaxiItineraryOCRResponse,
BankSlipOCRRequest,
BusinessCardOCRResponse,
TextArithmetic,
HKIDCardOCRRequest,
CarInvoiceOCRRequest,
MixedInvoiceItem,
TrainTicketOCRRequest,
EstateCertOCRResponse,
FlightInvoiceOCRRequest,
MLIDPassportOCRRequest,
TextDetectResponse,
TollInvoiceOCRResponse,
VerifyBizLicenseResponse,
FinanBillSliceOCRResponse,
DriverLicenseOCRResponse,
Words,
VerifyBizLicenseRequest,
TextDetectionEn,
PermitOCRResponse,
InvoiceGeneralOCRRequest,
Rect,
WaybillOCRResponse,
SingleInvoiceInfo,
TextFormula,
MLIDCardOCRRequest,
VatInvoiceItem,
VehicleRegCertInfo,
VehicleLicenseOCRRequest,
EnterpriseLicenseOCRResponse,
InvoiceGeneralInfo,
WordCoordPoint,
InstitutionOCRResponse,
VehicleInvoiceInfo,
DriverLicenseOCRRequest,
BizLicenseVerifyResult,
TextDetection,
RecognizeTableOCRResponse,
TextEduPaper,
QrcodeOCRResponse,
WaybillObj,
InvoiceDetectInfo,
MainlandPermitOCRRequest,
EnterpriseLicenseOCRRequest,
BankCardOCRRequest,
StructuralItem,
OnlineTaxiItineraryInfo,
PropOwnerCertOCRResponse,
FinanBillInfo,
TrainTicketOCRResponse,
TollInvoiceInfo,
BankSlipInfo,
ArithmeticOCRResponse,
FormulaOCRResponse,
BusInvoiceInfo,
SmartStructuralOCRRequest,
TextVatInvoice,
GeneralHandwritingOCRRequest,
BizLicenseOCRRequest,
MixedInvoiceDetectResponse,
VatInvoiceUserInfo,
InsuranceBillOCRResponse,
GeneralAccurateOCRResponse,
HmtResidentPermitOCRRequest,
QrcodeOCRRequest,
TaxiInvoiceOCRResponse,
GeneralBasicOCRResponse,
RecognizeThaiIDCardOCRResponse,
CellContent,
MixedInvoiceOCRResponse,
ClassifyDetectOCRResponse,
VehicleLicenseOCRResponse,
VatInvoiceOCRRequest,
IDCardOCRResponse,
ClassifyDetectOCRRequest,
DutyPaidProofOCRResponse,
TollInvoiceOCRRequest,
LicensePlateOCRResponse,
HKIDCardOCRResponse,
VatInvoiceGoodsInfo,
PermitOCRRequest,
InvoiceGeneralOCRResponse,
TaxiInvoiceOCRRequest,
PropOwnerCertOCRRequest,
TextDetectRequest,
VatRollInvoiceOCRResponse,
VatInvoiceVerifyRequest,
EduPaperOCRResponse,
RecognizeThaiIDCardOCRRequest,
BusinessCardInfo,
TextGeneralHandwriting,
TableOCRRequest,
UsedVehicleInvoiceInfo,
QrcodeImgSize,
PassportOCRResponse,
VerifyBasicBizLicenseResponse,
VehicleRegCertOCRRequest,
WaybillOCRRequest,
ProductDataRecord,
LicensePlateOCRRequest,
GeneralBasicOCRRequest,
TextVehicleBack,
GeneralEfficientOCRRequest,
AdvertiseOCRRequest,
RideHailingDriverLicenseOCRResponse,
Detail,
EnglishOCRRequest,
VatInvoiceVerifyResponse,
SmartStructuralOCRResponse,
DetectedWords,
VerifyEnterpriseFourFactorsRequest,
ShipInvoiceInfo,
GeneralAccurateOCRRequest,
OrgCodeCertOCRRequest,
FlightInvoiceOCRResponse,
InstitutionOCRRequest,
CarInvoiceInfo,
FlightInvoiceInfo,
TextVehicleFront,
AdvertiseTextDetection,
FinanBillSliceInfo,
QueryBarCodeResponse,
ArithmeticOCRRequest,
VerifyOfdVatInvoiceOCRRequest,
FinanBillSliceOCRRequest,
MLIDPassportOCRResponse,
VatRollInvoiceOCRRequest,
TableTitle,
Coord,
SealOCRResponse,
DutyPaidProofInfo,
FinanBillOCRResponse,
ShipInvoiceOCRRequest,
BankSlipOCRResponse,
QuestionObj,
VinOCRResponse,
EduPaperOCRRequest,
FormulaOCRRequest,
PassportOCRRequest,
DutyPaidProofOCRRequest,
RideHailingDriverLicenseOCRRequest,
QueryBarCodeRequest,
ItemCoord,
OrgCodeCertOCRResponse,
MixedInvoiceOCRRequest,
TableDetectInfo,
ResidenceBookletOCRResponse,
CarInvoiceOCRResponse,
GeneralFastOCRRequest,
Polygon,
ShipInvoiceOCRResponse,
InsuranceBillInfo,
VehicleRegCertOCRResponse,
ClassifyDetectInfo,
GeneralEfficientOCRResponse,
SealOCRRequest,
VerifyOfdVatInvoiceOCRResponse,
TextTable,
ResidenceBookletOCRRequest,
BusInvoiceOCRResponse,
QrcodeResultsInfo,
MainlandPermitOCRResponse,
VatInvoice,
HmtResidentPermitOCRResponse,
EnglishOCRResponse,
BusInvoiceOCRRequest,
QuotaInvoiceOCRResponse,
RideHailingTransportLicenseOCRResponse,
CandWord,
EnterpriseLicenseInfo,
InsuranceBillOCRRequest,
GeneralHandwritingOCRResponse,
TableCell,
TableOCRResponse,
DetectedWordCoordPoint,
QuestionBlockObj,
AdvertiseOCRResponse,
VatRollInvoiceInfo,
RecognizeOnlineTaxiItineraryOCRRequest,
IDCardOCRRequest,
MixedInvoiceDetectRequest,
VinOCRRequest,
RideHailingTransportLicenseOCRRequest,
MLIDCardOCRResponse,
RecognizeTableOCRRequest,
EstateCertOCRRequest,
VerifyBasicBizLicenseRequest,
BizLicenseOCRResponse,
VatInvoiceOCRResponse,
QuotaInvoiceOCRRequest,
BankCardOCRResponse,
BusinessCardOCRRequest,
FinanBillOCRRequest,
VerifyEnterpriseFourFactorsResponse,
GeneralFastOCRResponse,
QrcodePositionObj,
} from "./ocr_models"
/**
* ocr client
* @class
*/
export class Client extends AbstractClient {
constructor(clientConfig: ClientConfig) {
super("ocr.tencentcloudapi.com", "2018-11-19", clientConfig)
}
/**
* 本接口支持病案首页、费用清单、结算单、医疗发票四种保险理赔单据的文本识别和结构化输出。
*/
async InsuranceBillOCR(
req: InsuranceBillOCRRequest,
cb?: (error: string, rep: InsuranceBillOCRResponse) => void
): Promise<InsuranceBillOCRResponse> {
return this.request("InsuranceBillOCR", req, cb)
}
/**
* 本接口支持营业执照信息的识别与准确性核验。
您可以通过输入营业执照注册号或营业执照图片(若两者都输入则只用注册号做查询)进行核验,接口返回查询到的工商照面信息,并比对要校验的字段与查询结果的一致性。查询到工商信息包括:统一社会信用代码、经营期限、法人姓名、经营状态、经营业务范围、注册资本等。
*/
async VerifyBasicBizLicense(
req: VerifyBasicBizLicenseRequest,
cb?: (error: string, rep: VerifyBasicBizLicenseResponse) => void
): Promise<VerifyBasicBizLicenseResponse> {
return this.request("VerifyBasicBizLicense", req, cb)
}
/**
* 本接口支持增值税发票的准确性核验,您可以通过输入增值税发票的关键字段提供所需的验证信息,接口返回真实的票面相关信息,包括发票代码、发票号码、开票日期、金额、消费类型、购方名称、购方税号、销方名称、销方税号等多个常用字段。支持多种发票类型核验,包括增值税专用发票、增值税普通发票(含电子普通发票、卷式发票、通行费发票)、机动车销售统一发票、货物运输业增值税专用发票、二手车销售统一发票。
*/
async VatInvoiceVerify(
req: VatInvoiceVerifyRequest,
cb?: (error: string, rep: VatInvoiceVerifyResponse) => void
): Promise<VatInvoiceVerifyResponse> {
return this.request("VatInvoiceVerify", req, cb)
}
/**
* 本接口支持条形码备案信息查询,返回条形码查询结果的相关信息,包括产品名称、产品英文名称、品牌名称、规格型号、宽度、高度、深度、关键字、产品描述、厂家名称、厂家地址、企业社会信用代码13个字段信息。
产品优势:直联中国物品编码中心,查询结果更加准确、可靠。
*/
async QueryBarCode(
req: QueryBarCodeRequest,
cb?: (error: string, rep: QueryBarCodeResponse) => void
): Promise<QueryBarCodeResponse> {
return this.request("QueryBarCode", req, cb)
}
/**
* 本接口支持智能化识别各类企业登记证书、许可证书、企业执照、三证合一类证书,结构化输出统一社会信用代码、公司名称、法定代表人、公司地址、注册资金、企业类型、经营范围等关键字段。
*/
async EnterpriseLicenseOCR(
req: EnterpriseLicenseOCRRequest,
cb?: (error: string, rep: EnterpriseLicenseOCRResponse) => void
): Promise<EnterpriseLicenseOCRResponse> {
return this.request("EnterpriseLicenseOCR", req, cb)
}
/**
* 本接口支持名片各字段的自动定位与识别,包含姓名、电话、手机号、邮箱、公司、部门、职位、网址、地址、QQ、微信、MSN等。
*/
async BusinessCardOCR(
req: BusinessCardOCRRequest,
cb?: (error: string, rep: BusinessCardOCRResponse) => void
): Promise<BusinessCardOCRResponse> {
return this.request("BusinessCardOCR", req, cb)
}
/**
* 本接口支持中国大陆居民二代身份证正反面所有字段的识别,包括姓名、性别、民族、出生日期、住址、公民身份证号、签发机关、有效期限,识别准确度达到99%以上。
另外,本接口还支持多种增值能力,满足不同场景的需求。如身份证照片、人像照片的裁剪功能,同时具备9种告警功能,如下表所示。
<table style="width:650px">
<thead>
<tr>
<th width="150">增值能力</th>
<th width="500">能力项</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">裁剪功能</td>
<td>身份证照片裁剪(去掉证件外多余的边缘、自动矫正拍摄角度)</td>
</tr>
<tr>
<td>人像照片裁剪(自动抠取身份证头像区域)</td>
</tr>
<tr>
<td rowspan="9">告警功能</td>
<td>身份证有效日期不合法告警</td>
</tr>
<tr>
<td>身份证边框不完整告警</td>
</tr>
<tr>
<td>身份证复印件告警</td>
</tr>
<tr>
<td>身份证翻拍告警</td>
</tr>
<tr>
<td>身份证框内遮挡告警</td>
</tr>
<tr>
<td>临时身份证告警</td>
</tr>
<tr>
<td>身份证 PS 告警</td>
</tr>
<tr>
<td>图片模糊告警(可根据图片质量分数判断)</td>
</tr>
</tbody>
</table>
*/
async IDCardOCR(
req: IDCardOCRRequest,
cb?: (error: string, rep: IDCardOCRResponse) => void
): Promise<IDCardOCRResponse> {
return this.request("IDCardOCR", req, cb)
}
/**
* 本接口支持对过路过桥费发票的发票代码、发票号码、日期、小写金额等关键字段的识别。
*/
async TollInvoiceOCR(
req: TollInvoiceOCRRequest,
cb?: (error: string, rep: TollInvoiceOCRResponse) => void
): Promise<TollInvoiceOCRResponse> {
return this.request("TollInvoiceOCR", req, cb)
}
/**
* 本接口支持马来西亚身份证识别,识别字段包括身份证号、姓名、性别、地址;具备身份证人像照片的裁剪功能和翻拍、复印件告警功能。
本接口暂未完全对外开放,如需咨询,请[联系商务](https://cloud.tencent.com/about/connect)
*/
async MLIDCardOCR(
req: MLIDCardOCRRequest,
cb?: (error: string, rep: MLIDCardOCRResponse) => void
): Promise<MLIDCardOCRResponse> {
return this.request("MLIDCardOCR", req, cb)
}
/**
* 本接口支持条形码和二维码的识别(包括 DataMatrix 和 PDF417)。
*/
async QrcodeOCR(
req: QrcodeOCRRequest,
cb?: (error: string, rep: QrcodeOCRResponse) => void
): Promise<QrcodeOCRResponse> {
return this.request("QrcodeOCR", req, cb)
}
/**
* 本接口支持图像整体文字的检测和识别。支持中文、英文、中英文、数字和特殊字符号的识别,并返回文字框位置和文字内容。
适用于文字较多、版式复杂、对识别准召率要求较高的场景,如试卷试题、网络图片、街景店招牌、法律卷宗等场景。
产品优势:与通用印刷体识别相比,提供更高精度的文字识别服务,在文字较多、长串数字、小字、模糊字、倾斜文本等困难场景下,高精度版的准确率和召回率更高。
通用印刷体识别不同版本的差异如下:
<table style="width:715px">
<thead>
<tr>
<th style="width:150px"></th>
<th >【荐】通用印刷体识别(高精度版)</th>
<th style="width:200px"><a href="https://cloud.tencent.com/document/product/866/33526">【荐】通用印刷体识别</a></th>
<th><a href="https://cloud.tencent.com/document/product/866/37831">通用印刷体识别(精简版)</a></th>
</tr>
</thead>
<tbody>
<tr>
<td> 适用场景</td>
<td>适用于文字较多、长串数字、小字、模糊字、倾斜文本等困难场景</td>
<td>适用于所有通用场景的印刷体识别</td>
<td>适用于快速文本识别场景,准召率有一定损失,价格更优惠</td>
</tr>
<tr>
<td>识别准确率</td>
<td>99%</td>
<td>96%</td>
<td>91%</td>
</tr>
<tr>
<td>价格</td>
<td>高</td>
<td>中</td>
<td>低</td>
</tr>
<tr>
<td>支持的语言</td>
<td>中文、英文、中英文</td>
<td>中文、英文、中英文、日语、韩语、西班牙语、法语、德语、葡萄牙语、越南语、马来语、俄语、意大利语、荷兰语、瑞典语、芬兰语、丹麦语、挪威语、匈牙利语、泰语</td>
<td>中文、英文、中英文</td>
</tr>
<tr>
<td>自动语言检测</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
</tr>
<tr>
<td>返回文本行坐标</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
</tr>
<tr>
<td>自动旋转纠正</td>
<td>支持旋转识别,返回角度信息</td>
<td>支持旋转识别,返回角度信息</td>
<td>支持旋转识别,返回角度信息</td>
</tr>
</tbody>
</table>
*/
async GeneralAccurateOCR(
req: GeneralAccurateOCRRequest,
cb?: (error: string, rep: GeneralAccurateOCRResponse) => void
): Promise<GeneralAccurateOCRResponse> {
return this.request("GeneralAccurateOCR", req, cb)
}
/**
* 本接口支持机票行程单关键字段的识别,包括旅客姓名、有效身份证件号码、电子客票号码、验证码、填开单位、其他税费、燃油附加费、民航发展基金、保险费、销售单位代号、始发地、目的地、航班号、时间、日期、座位等级、承运人、发票消费类型、票价、合计金额、填开日期、国内国际标签、印刷序号、客票级别/类别、客票生效日期、有效期截止日期、免费行李等字段,支持航班信息多行明细输出。
*/
async FlightInvoiceOCR(
req: FlightInvoiceOCRRequest,
cb?: (error: string, rep: FlightInvoiceOCRResponse) => void
): Promise<FlightInvoiceOCRResponse> {
return this.request("FlightInvoiceOCR", req, cb)
}
/**
* 本接口支持多张、多类型票据的混合检测和自动分类,返回对应票据类型。目前已支持增值税发票、增值税发票(卷票)、定额发票、通用机打发票、购车发票、火车票、出租车发票、机票行程单、汽车票、轮船票、过路过桥费发票、酒店账单、客运限额发票、购物小票、完税证明共15种票据。
*/
async MixedInvoiceDetect(
req: MixedInvoiceDetectRequest,
cb?: (error: string, rep: MixedInvoiceDetectResponse) => void
): Promise<MixedInvoiceDetectResponse> {
return this.request("MixedInvoiceDetect", req, cb)
}
/**
* 本接口支持识别轮船票的发票代码、发票号码、日期、姓名、票价、始发地、目的地、姓名、时间、发票消费类型、省、市、币种字段。
*/
async ShipInvoiceOCR(
req: ShipInvoiceOCRRequest,
cb?: (error: string, rep: ShipInvoiceOCRResponse) => void
): Promise<ShipInvoiceOCRResponse> {
return this.request("ShipInvoiceOCR", req, cb)
}
/**
* 本接口支持中国港澳台地区以及其他国家、地区的护照识别。识别字段包括护照ID、姓名、出生日期、性别、有效期、发行国、国籍,具备护照人像照片的裁剪功能和翻拍、复印件告警功能。
*/
async MLIDPassportOCR(
req: MLIDPassportOCRRequest,
cb?: (error: string, rep: MLIDPassportOCRResponse) => void
): Promise<MLIDPassportOCRResponse> {
return this.request("MLIDPassportOCR", req, cb)
}
/**
* 本接口支持对增值税发票(卷票)的发票代码、发票号码、日期、校验码、合计金额(小写)等关键字段的识别。
*/
async VatRollInvoiceOCR(
req: VatRollInvoiceOCRRequest,
cb?: (error: string, rep: VatRollInvoiceOCRResponse) => void
): Promise<VatRollInvoiceOCRResponse> {
return this.request("VatRollInvoiceOCR", req, cb)
}
/**
* 本接口支持定额发票的发票号码、发票代码、金额(大小写)、发票消费类型、地区及是否有公司印章等关键字段的识别。
*/
async QuotaInvoiceOCR(
req: QuotaInvoiceOCRRequest,
cb?: (error: string, rep: QuotaInvoiceOCRResponse) => void
): Promise<QuotaInvoiceOCRResponse> {
return this.request("QuotaInvoiceOCR", req, cb)
}
/**
* 本接口支持图片内车辆识别代号(VIN)的检测和识别。
*/
async VinOCR(
req: VinOCRRequest,
cb?: (error: string, rep: VinOCRResponse) => void
): Promise<VinOCRResponse> {
return this.request("VinOCR", req, cb)
}
/**
* 本接口支持图片中整体文字的检测和识别,返回文字框位置与文字内容。相比通用印刷体识别接口,识别速度更快、支持的 QPS 更高。
*/
async GeneralFastOCR(
req: GeneralFastOCRRequest,
cb?: (error: string, rep: GeneralFastOCRResponse) => void
): Promise<GeneralFastOCRResponse> {
return this.request("GeneralFastOCR", req, cb)
}
/**
* 本接口支持房产证关键字段的识别,包括房地产权利人、共有情况、登记时间、规划用途、房屋性质、房屋坐落等。
目前接口对合肥、成都、佛山三个城市的房产证版式识别较好。
*/
async PropOwnerCertOCR(
req: PropOwnerCertOCRRequest,
cb?: (error: string, rep: PropOwnerCertOCRResponse) => void
): Promise<PropOwnerCertOCRResponse> {
return this.request("PropOwnerCertOCR", req, cb)
}
/**
* 本接口支持快速精准识别营业执照上的字段,包括统一社会信用代码、公司名称、经营场所、主体类型、法定代表人、注册资金、组成形式、成立日期、营业期限和经营范围等字段。
*/
async BizLicenseOCR(
req: BizLicenseOCRRequest,
cb?: (error: string, rep: BizLicenseOCRResponse) => void
): Promise<BizLicenseOCRResponse> {
return this.request("BizLicenseOCR", req, cb)
}
/**
* 本接口支持图片内手写体文字的检测和识别,针对手写字体无规则、字迹潦草、模糊等特点进行了识别能力的增强。
*/
async GeneralHandwritingOCR(
req: GeneralHandwritingOCRRequest,
cb?: (error: string, rep: GeneralHandwritingOCRResponse) => void
): Promise<GeneralHandwritingOCRResponse> {
return this.request("GeneralHandwritingOCR", req, cb)
}
/**
* 本接口支持市面上主流版式电子运单的识别,包括收件人和寄件人的姓名、电话、地址以及运单号等字段。
*/
async WaybillOCR(
req: WaybillOCRRequest,
cb?: (error: string, rep: WaybillOCRResponse) => void
): Promise<WaybillOCRResponse> {
return this.request("WaybillOCR", req, cb)
}
/**
* 本接口支持出租车发票关键字段的识别,包括发票号码、发票代码、金额、日期、上下车时间、里程、车牌号、发票类型及所属地区等字段。
*/
async TaxiInvoiceOCR(
req: TaxiInvoiceOCRRequest,
cb?: (error: string, rep: TaxiInvoiceOCRResponse) => void
): Promise<TaxiInvoiceOCRResponse> {
return this.request("TaxiInvoiceOCR", req, cb)
}
/**
* 本接口支持对通用机打发票的发票代码、发票号码、日期、购买方识别号、销售方识别号、校验码、小写金额等关键字段的识别。
*/
async InvoiceGeneralOCR(
req: InvoiceGeneralOCRRequest,
cb?: (error: string, rep: InvoiceGeneralOCRResponse) => void
): Promise<InvoiceGeneralOCRResponse> {
return this.request("InvoiceGeneralOCR", req, cb)
}
/**
* 本接口支持网约车行程单关键字段的识别,包括行程起止日期、上车时间、起点、终点、里程、金额等字段。
*/
async RecognizeOnlineTaxiItineraryOCR(
req: RecognizeOnlineTaxiItineraryOCRRequest,
cb?: (error: string, rep: RecognizeOnlineTaxiItineraryOCRResponse) => void
): Promise<RecognizeOnlineTaxiItineraryOCRResponse> {
return this.request("RecognizeOnlineTaxiItineraryOCR", req, cb)
}
/**
* 本接口支持中国香港身份证人像面中关键字段的识别,包括中文姓名、英文姓名、姓名电码、出生日期、性别、证件符号、首次签发日期、最近领用日期、身份证号、是否是永久性居民身份证;具备防伪识别、人像照片裁剪等扩展功能。
本接口暂未完全对外开放,如需咨询,请[联系商务](https://cloud.tencent.com/about/connect)
*/
async HKIDCardOCR(
req: HKIDCardOCRRequest,
cb?: (error: string, rep: HKIDCardOCRResponse) => void
): Promise<HKIDCardOCRResponse> {
return this.request("HKIDCardOCR", req, cb)
}
/**
* 本接口支持中英文图片/ PDF内常规表格、无线表格、多表格的检测和识别,支持日文有线表格识别,返回每个单元格的文字内容,支持旋转的表格图片识别,且支持将识别结果保存为 Excel 格式。
*/
async RecognizeTableOCR(
req: RecognizeTableOCRRequest,
cb?: (error: string, rep: RecognizeTableOCRResponse) => void
): Promise<RecognizeTableOCRResponse> {
return this.request("RecognizeTableOCR", req, cb)
}
/**
* 本接口支持营业执照信息的识别与准确性核验,返回的真实工商照面信息比营业执照识别及核验(基础版)接口更详细。
您可以输入营业执照注册号或营业执照图片(若两者都输入则只用注册号做查询),接口返回查询到的工商照面信息,并比对要校验的字段与查询结果的一致性。
查询到工商信息包括:统一社会信用代码、组织机构代码、经营期限、法人姓名、经营状态、经营业务范围及方式、注册资金、注册币种、登记机关、开业日期、企业(机构)类型、注销日期、吊销日期、许可经营项目、一般经营项目、核准时间、省、地级市、区/县、住所所在行政区划代码、行业门类代码、行业门类名称、国民经济行业代码、国民经济行业名称、经营(业务)范围等。
*/
async VerifyBizLicense(
req: VerifyBizLicenseRequest,
cb?: (error: string, rep: VerifyBizLicenseResponse) => void
): Promise<VerifyBizLicenseResponse> {
return this.request("VerifyBizLicense", req, cb)
}
/**
* 本接口支持对完税证明的税号、纳税人识别号、纳税人名称、金额合计大写、金额合计小写、填发日期、税务机关、填票人等关键字段的识别。
*/
async DutyPaidProofOCR(
req: DutyPaidProofOCRRequest,
cb?: (error: string, rep: DutyPaidProofOCRResponse) => void
): Promise<DutyPaidProofOCRResponse> {
return this.request("DutyPaidProofOCR", req, cb)
}
/**
* 本接口支持图像整体文字的检测和识别。可以识别中文、英文、中英文、日语、韩语、西班牙语、法语、德语、葡萄牙语、越南语、马来语、俄语、意大利语、荷兰语、瑞典语、芬兰语、丹麦语、挪威语、匈牙利语、泰语,阿拉伯语20种语言,且各种语言均支持与英文混合的文字识别。
适用于印刷文档识别、网络图片识别、广告图文字识别、街景店招牌识别、菜单识别、视频标题识别、头像文字识别等场景。
产品优势:支持自动识别语言类型,可返回文本框坐标信息,对于倾斜文本支持自动旋转纠正。
通用印刷体识别不同版本的差异如下:
<table style="width:715px">
<thead>
<tr>
<th style="width:150px"></th>
<th style="width:200px">【荐】通用印刷体识别</th>
<th ><a href="https://cloud.tencent.com/document/product/866/34937">【荐】通用印刷体识别(高精度版)</a></th>
<th><a href="https://cloud.tencent.com/document/product/866/37831">通用印刷体识别(精简版)</a></th>
</tr>
</thead>
<tbody>
<tr>
<td> 适用场景</td>
<td>适用于所有通用场景的印刷体识别</td>
<td>适用于文字较多、长串数字、小字、模糊字、倾斜文本等困难场景</td>
<td>适用于快速文本识别场景,准召率有一定损失,价格更优惠</td>
</tr>
<tr>
<td>识别准确率</td>
<td>96%</td>
<td>99%</td>
<td>91%</td>
</tr>
<tr>
<td>价格</td>
<td>中</td>
<td>高</td>
<td>低</td>
</tr>
<tr>
<td>支持的语言</td>
<td>中文、英文、中英文、日语、韩语、西班牙语、法语、德语、葡萄牙语、越南语、马来语、俄语、意大利语、荷兰语、瑞典语、芬兰语、丹麦语、挪威语、匈牙利语、泰语</td>
<td>中文、英文、中英文</td>
<td>中文、英文、中英文</td>
</tr>
<tr>
<td>自动语言检测</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
</tr>
<tr>
<td>返回文本行坐标</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
</tr>
<tr>
<td>自动旋转纠正</td>
<td>支持旋转识别,返回角度信息</td>
<td>支持旋转识别,返回角度信息</td>
<td>支持旋转识别,返回角度信息</td>
</tr>
</tbody>
</table>
*/
async GeneralBasicOCR(
req: GeneralBasicOCRRequest,
cb?: (error: string, rep: GeneralBasicOCRResponse) => void
): Promise<GeneralBasicOCRResponse> {
return this.request("GeneralBasicOCR", req, cb)
}
/**
* 本接口支持对卡式港澳台通行证的识别,包括签发地点、签发机关、有效期限、性别、出生日期、英文姓名、姓名、证件号等字段。
*/
async PermitOCR(
req: PermitOCRRequest,
cb?: (error: string, rep: PermitOCRResponse) => void
): Promise<PermitOCRResponse> {
return this.request("PermitOCR", req, cb)
}
/**
* 本接口支持组织机构代码证关键字段的识别,包括代码、有效期、地址、机构名称等。
*/
async OrgCodeCertOCR(
req: OrgCodeCertOCRRequest,
cb?: (error: string, rep: OrgCodeCertOCRResponse) => void
): Promise<OrgCodeCertOCRResponse> {
return this.request("OrgCodeCertOCR", req, cb)
}
/**
* 本接口通过检测图片中的文字信息特征,快速判断图片中有无文字并返回判断结果,帮助用户过滤无文字的图片。
*/
async TextDetect(
req: TextDetectRequest,
cb?: (error: string, rep: TextDetectResponse) => void
): Promise<TextDetectResponse> {
return this.request("TextDetect", req, cb)
}
/**
* 本接口支持常见银行票据的自动分类和识别。切片识别包括金融行业常见票据的重要切片字段识别,包括金额、账号、日期、凭证号码等。(金融票据切片:金融票据中待识别字段及其周围局部区域的裁剪图像。)
*/
async FinanBillSliceOCR(
req: FinanBillSliceOCRRequest,
cb?: (error: string, rep: FinanBillSliceOCRResponse) => void
): Promise<FinanBillSliceOCRResponse> {
return this.request("FinanBillSliceOCR", req, cb)
}
/**
* 此接口基于企业四要素授权“姓名、证件号码、企业标识、企业全称”,验证企业信息是否一致。
*/
async VerifyEnterpriseFourFactors(
req: VerifyEnterpriseFourFactorsRequest,
cb?: (error: string, rep: VerifyEnterpriseFourFactorsResponse) => void
): Promise<VerifyEnterpriseFourFactorsResponse> {
return this.request("VerifyEnterpriseFourFactors", req, cb)
}
/**
* 本接口支持识别公路汽车客票的发票代码、发票号码、日期、姓名、票价等字段。
*/
async BusInvoiceOCR(
req: BusInvoiceOCRRequest,
cb?: (error: string, rep: BusInvoiceOCRResponse) => void
): Promise<BusInvoiceOCRResponse> {
return this.request("BusInvoiceOCR", req, cb)
}
/**
* 本接口支持增值税专用发票、增值税普通发票、增值税电子发票全字段的内容检测和识别,包括发票代码、发票号码、打印发票代码、打印发票号码、开票日期、合计金额、校验码、税率、合计税额、价税合计、购买方识别号、复核、销售方识别号、开票人、密码区1、密码区2、密码区3、密码区4、发票名称、购买方名称、销售方名称、服务名称、备注、规格型号、数量、单价、金额、税额、收款人等字段。
*/
async VatInvoiceOCR(
req: VatInvoiceOCRRequest,
cb?: (error: string, rep: VatInvoiceOCRResponse) => void
): Promise<VatInvoiceOCRResponse> {
return this.request("VatInvoiceOCR", req, cb)
}
/**
* <b>此接口为表格识别的旧版本服务,不再进行服务升级,建议您使用识别能力更强、服务性能更优的<a href="https://cloud.tencent.com/document/product/866/49525">新版表格识别</a>。</b>
本接口支持图片内表格文档的检测和识别,返回每个单元格的文字内容,支持将识别结果保存为 Excel 格式。
*/
async TableOCR(
req: TableOCRRequest,
cb?: (error: string, rep: TableOCRResponse) => void
): Promise<TableOCRResponse> {
return this.request("TableOCR", req, cb)
}
/**
* 本接口支持网约车驾驶证关键字段的识别,包括姓名、证号、起始日期、截止日期、发证日期。
*/
async RideHailingDriverLicenseOCR(
req: RideHailingDriverLicenseOCRRequest,
cb?: (error: string, rep: RideHailingDriverLicenseOCRResponse) => void
): Promise<RideHailingDriverLicenseOCRResponse> {
return this.request("RideHailingDriverLicenseOCR", req, cb)
}
/**
* 港澳台居住证OCR支持港澳台居住证正反面全字段内容检测识别功能,包括姓名、性别、出生日期、地址、身份证ID、签发机关、有效期限、签发次数、通行证号码关键字段识别。可以应用于港澳台居住证信息有效性校验场景,例如银行开户、用户注册等场景。
*/
async HmtResidentPermitOCR(
req: HmtResidentPermitOCRRequest,
cb?: (error: string, rep: HmtResidentPermitOCRResponse) => void
): Promise<HmtResidentPermitOCRResponse> {
return this.request("HmtResidentPermitOCR", req, cb)
}
/**
* 本接口支持识别并提取各类证照、票据、表单、合同等结构化场景的字段信息。无需任何配置,灵活高效。适用于各类结构化信息录入场景。
*/
async SmartStructuralOCR(
req: SmartStructuralOCRRequest,
cb?: (error: string, rep: SmartStructuralOCRResponse) => void
): Promise<SmartStructuralOCRResponse> {
return this.request("SmartStructuralOCR", req, cb)
}
/**
* 本接口支持作业算式题目的自动识别和判分,目前覆盖 K12 学力范围内的 11 种题型,包括加减乘除四则、加减乘除已知结果求运算因子、判断大小、约等于估算、带余数除法、分数四则运算、单位换算、竖式加减法、竖式乘除法、脱式计算和解方程,平均识别精度达到93%以上。
*/
async ArithmeticOCR(
req: ArithmeticOCRRequest,
cb?: (error: string, rep: ArithmeticOCRResponse) => void
): Promise<ArithmeticOCRResponse> {
return this.request("ArithmeticOCR", req, cb)
}
/**
* 本接口支持对中国大陆机动车车牌的自动定位和识别,返回地域编号和车牌号信息。
*/
async LicensePlateOCR(
req: LicensePlateOCRRequest,
cb?: (error: string, rep: LicensePlateOCRResponse) => void
): Promise<LicensePlateOCRResponse> {
return this.request("LicensePlateOCR", req, cb)
}
/**
* 本接口支持不动产权证关键字段的识别,包括使用期限、面积、用途、权利性质、权利类型、坐落、共有情况、权利人、权利其他状况等。
*/
async EstateCertOCR(
req: EstateCertOCRRequest,
cb?: (error: string, rep: EstateCertOCRResponse) => void
): Promise<EstateCertOCRResponse> {
return this.request("EstateCertOCR", req, cb)
}
/**
* 支持身份证、护照、名片、银行卡、行驶证、驾驶证、港澳台通行证、户口本、港澳台来往内地通行证、港澳台居住证、不动产证、营业执照的智能分类。
*/
async ClassifyDetectOCR(
req: ClassifyDetectOCRRequest,
cb?: (error: string, rep: ClassifyDetectOCRResponse) => void
): Promise<ClassifyDetectOCRResponse> {
return this.request("ClassifyDetectOCR", req, cb)
}
/**
* 印章识别已支持各类印章,包括发票章,财务章等,适用于公文,票据等场景。
*/
async SealOCR(
req: SealOCRRequest,
cb?: (error: string, rep: SealOCRResponse) => void
): Promise<SealOCRResponse> {
return this.request("SealOCR", req, cb)
}
/**
* 本接口支持火车票全字段的识别,包括编号、票价、姓名、座位号、出发时间、出发站、到达站、车次、席别、发票类型及序列号等。
*/
async TrainTicketOCR(
req: TrainTicketOCRRequest,
cb?: (error: string, rep: TrainTicketOCRResponse) => void
): Promise<TrainTicketOCRResponse> {
return this.request("TrainTicketOCR", req, cb)
}
/**
* 本接口支持银行回单全字段的识别,包括付款开户行、收款开户行、付款账号、收款账号、回单类型、回单编号、币种、流水号、凭证号码、交易机构、交易金额、手续费、日期等字段信息。
*/
async BankSlipOCR(
req: BankSlipOCRRequest,
cb?: (error: string, rep: BankSlipOCRResponse) => void
): Promise<BankSlipOCRResponse> {
return this.request("BankSlipOCR", req, cb)
}
/**
* 本接口支持图像整体文字的检测和识别。支持中文、英文、中英文、数字和特殊字符号的识别,并返回文字框位置和文字内容。
适用于快速文本识别场景。
产品优势:与通用印刷体识别接口相比,精简版虽然在准确率和召回率上有一定损失,但价格更加优惠。
通用印刷体识别不同版本的差异如下:
<table style="width:715px">
<thead>
<tr>
<th style="width:150px"></th>
<th >通用印刷体识别(精简版)</th>
<th style="width:200px"><a href="https://cloud.tencent.com/document/product/866/33526">【荐】通用印刷体识别</a></th>
<th><a href="https://cloud.tencent.com/document/product/866/34937">【荐】通用印刷体识别(高精度版)</a></th>
</tr>
</thead>
<tbody>
<tr>
<td> 适用场景</td>
<td>适用于快速文本识别场景,准召率有一定损失,价格更优惠</td>
<td>适用于所有通用场景的印刷体识别</td>
<td>适用于文字较多、长串数字、小字、模糊字、倾斜文本等困难场景</td>
</tr>
<tr>
<td>识别准确率</td>
<td>91%</td>
<td>96%</td>
<td>99%</td>
</tr>
<tr>
<td>价格</td>
<td>低</td>
<td>中</td>
<td>高</td>
</tr>
<tr>
<td>支持的语言</td>
<td>中文、英文、中英文</td>
<td>中文、英文、中英文、日语、韩语、西班牙语、法语、德语、葡萄牙语、越南语、马来语、俄语、意大利语、荷兰语、瑞典语、芬兰语、丹麦语、挪威语、匈牙利语、泰语</td>
<td>中文、英文、中英文</td>
</tr>
<tr>
<td>自动语言检测</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
</tr>
<tr>
<td>返回文本行坐标</td>
<td>支持</td>
<td>支持</td>
<td>支持</td>
</tr>
<tr>
<td>自动旋转纠正</td>
<td>支持旋转识别,返回角度信息</td>
<td>支持旋转识别,返回角度信息</td>
<td>支持旋转识别,返回角度信息</td>
</tr>
</tbody>
</table>
*/
async GeneralEfficientOCR(
req: GeneralEfficientOCRRequest,
cb?: (error: string, rep: GeneralEfficientOCRResponse) => void
): Promise<GeneralEfficientOCRResponse> {
return this.request("GeneralEfficientOCR", req, cb)
}
/**
* 本接口支持广告商品图片内文字的检测和识别,返回文本框位置与文字内容。
产品优势:针对广告商品图片普遍存在较多繁体字、艺术字的特点,进行了识别能力的增强。支持中英文、横排、竖排以及倾斜场景文字识别。文字识别的召回率和准确率能达到96%以上。
*/
async AdvertiseOCR(
req: AdvertiseOCRRequest,
cb?: (error: string, rep: AdvertiseOCRResponse) => void
): Promise<AdvertiseOCRResponse> {
return this.request("AdvertiseOCR", req, cb)
}
/**
* 本接口支持国内机动车登记证书主要字段的结构化识别,包括机动车所有人、身份证明名称、号码、车辆型号、车辆识别代号、发动机号、制造厂名称等。
*/
async VehicleRegCertOCR(
req: VehicleRegCertOCRRequest,
cb?: (error: string, rep: VehicleRegCertOCRResponse) => void
): Promise<VehicleRegCertOCRResponse> {
return this.request("VehicleRegCertOCR", req, cb)
}
/**
* 本接口支持事业单位法人证书关键字段识别,包括注册号、有效期、住所、名称、法定代表人等。
*/
async InstitutionOCR(
req: InstitutionOCRRequest,
cb?: (error: string, rep: InstitutionOCRResponse) => void
): Promise<InstitutionOCRResponse> {
return this.request("InstitutionOCR", req, cb)
}
/**
* 本接口支持图像英文文字的检测和识别,返回文字框位置与文字内容。支持多场景、任意版面下的英文、字母、数字和常见字符的识别,同时覆盖英文印刷体和英文手写体识别。
*/
async EnglishOCR(
req: EnglishOCRRequest,
cb?: (error: string, rep: EnglishOCRResponse) => void
): Promise<EnglishOCRResponse> {
return this.request("EnglishOCR", req, cb)
}
/**
* 本接口支持居民户口簿户主页及成员页关键字段的识别,包括姓名、户别、地址、籍贯、身份证号码等。
*/
async ResidenceBookletOCR(
req: ResidenceBookletOCRRequest,
cb?: (error: string, rep: ResidenceBookletOCRResponse) => void
): Promise<ResidenceBookletOCRResponse> {
return this.request("ResidenceBookletOCR", req, cb)
}
/**
* 本接口支持对中国大陆主流银行卡正反面关键字段的检测与识别,包括卡号、卡类型、卡名字、银行信息、有效期。支持竖排异形卡识别、多角度旋转图片识别。支持对复印件、翻拍件、边框遮挡的银行卡进行告警,可应用于各种银行卡信息有效性校验场景,如金融行业身份认证、第三方支付绑卡等场景。
*/
async BankCardOCR(
req: BankCardOCRRequest,
cb?: (error: string, rep: BankCardOCRResponse) => void
): Promise<BankCardOCRResponse> {
return this.request("BankCardOCR", req, cb)
}
/**
* 本接口支持机动车销售统一发票和二手车销售统一发票的识别,包括发票号码、发票代码、合计金额、合计税额等二十多个字段。
*/
async CarInvoiceOCR(
req: CarInvoiceOCRRequest,
cb?: (error: string, rep: CarInvoiceOCRResponse) => void
): Promise<CarInvoiceOCRResponse> {
return this.request("CarInvoiceOCR", req, cb)
}
/**
* 本接口支持驾驶证主页和副页所有字段的自动定位与识别,重点字段的识别准确度达到99%以上。
驾驶证主页:包括证号、姓名、性别、国籍、住址、出生日期、初次领证日期、准驾车型、有效期限、发证单位
驾驶证副页:包括证号、姓名、档案编号、记录。
另外,本接口还支持复印件、翻拍和PS告警功能。
*/
async DriverLicenseOCR(
req: DriverLicenseOCRRequest,
cb?: (error: string, rep: DriverLicenseOCRResponse) => void
): Promise<DriverLicenseOCRResponse> {
return this.request("DriverLicenseOCR", req, cb)
}
/**
* 智能识别并结构化港澳台居民来往内地通行证正面全部字段,包含中文姓名、英文姓名、性别、出生日期、签发机关、有效期限、证件号、签发地点、签发次数、证件类别。
*/
async MainlandPermitOCR(
req: MainlandPermitOCRRequest,
cb?: (error: string, rep: MainlandPermitOCRResponse) => void
): Promise<MainlandPermitOCRResponse> {
return this.request("MainlandPermitOCR", req, cb)
}
/**
* 本接口支持识别主流初高中数学符号和公式,返回公式的 Latex 格式文本。
*/
async FormulaOCR(
req: FormulaOCRRequest,
cb?: (error: string, rep: FormulaOCRResponse) => void
): Promise<FormulaOCRResponse> {
return this.request("FormulaOCR", req, cb)
}
/**
* 本接口支持中国大陆地区护照个人资料页多个字段的检测与识别。已支持字段包括英文姓名、中文姓名、国家码、护照号、出生地、出生日期、国籍英文、性别英文、有效期、签发地点英文、签发日期、持证人签名、护照机读码(MRZ码)等。
*/
async PassportOCR(
req: PassportOCRRequest,
cb?: (error: string, rep: PassportOCRResponse) => void
): Promise<PassportOCRResponse> {
return this.request("PassportOCR", req, cb)
}
/**
* 本接口支持常见银行票据的自动分类和识别。整单识别包括支票(含现金支票、普通支票、转账支票),承兑汇票(含银行承兑汇票、商业承兑汇票)以及进账单等,适用于中国人民银行印发的 2010 版银行票据凭证版式(银发[2010]299 号)。
*/
async FinanBillOCR(
req: FinanBillOCRRequest,
cb?: (error: string, rep: FinanBillOCRResponse) => void
): Promise<FinanBillOCRResponse> {
return this.request("FinanBillOCR", req, cb)
}
/**
* 本接口支持OFD格式的增值税电子普通发票和增值税电子专用发票的识别,返回发票代码、发票号码、开票日期、验证码、机器编号、密码区,购买方和销售方信息,包括名称、纳税人识别号、地址电话、开户行及账号,以及价税合计、开票人、收款人、复核人、税额、不含税金额等字段信息。
*/
async VerifyOfdVatInvoiceOCR(
req: VerifyOfdVatInvoiceOCRRequest,
cb?: (error: string, rep: VerifyOfdVatInvoiceOCRResponse) => void
): Promise<VerifyOfdVatInvoiceOCRResponse> {
return this.request("VerifyOfdVatInvoiceOCR", req, cb)
}
/**
* 本接口支持多张、多类型票据的混合识别,系统自动实现分割、分类和识别,同时支持自选需要识别的票据类型。目前已支持增值税发票、增值税发票(卷票)、定额发票、通用机打发票、购车发票、火车票、出租车发票、机票行程单、汽车票、轮船票、过路过桥费发票共11种票据。
*/
async MixedInvoiceOCR(
req: MixedInvoiceOCRRequest,
cb?: (error: string, rep: MixedInvoiceOCRResponse) => void
): Promise<MixedInvoiceOCRResponse> {
return this.request("MixedInvoiceOCR", req, cb)
}
/**
* 本接口支持数学试题内容的识别和结构化输出,包括通用文本解析和小学/初中/高中数学公式解析能力(包括91种题型,180种符号),公式返回格式为 Latex 格式文本。
*/
async EduPaperOCR(
req: EduPaperOCRRequest,
cb?: (error: string, rep: EduPaperOCRResponse) => void
): Promise<EduPaperOCRResponse> {
return this.request("EduPaperOCR", req, cb)
}
/**
* 本接口支持网约车运输证关键字段的识别,包括交运管许可字号、车辆所有人、车辆号牌、起始日期、截止日期、发证日期。
*/
async RideHailingTransportLicenseOCR(
req: RideHailingTransportLicenseOCRRequest,
cb?: (error: string, rep: RideHailingTransportLicenseOCRResponse) => void
): Promise<RideHailingTransportLicenseOCRResponse> {
return this.request("RideHailingTransportLicenseOCR", req, cb)
}
/**
* 本接口支持泰国身份证识别,识别字段包括泰文姓名、英文姓名、地址、出生日期、身份证号码。
本接口暂未完全对外开放,如需咨询,请[联系商务](https://cloud.tencent.com/about/connect)
*/
async RecognizeThaiIDCardOCR(
req: RecognizeThaiIDCardOCRRequest,
cb?: (error: string, rep: RecognizeThaiIDCardOCRResponse) => void
): Promise<RecognizeThaiIDCardOCRResponse> {
return this.request("RecognizeThaiIDCardOCR", req, cb)
}
/**
* 本接口支持行驶证主页和副页所有字段的自动定位与识别。
行驶证主页:车牌号码、车辆类型、所有人、住址、使用性质、品牌型号、识别代码、发动机号、注册日期、发证日期、发证单位。
行驶证副页:号牌号码、档案编号、核定载人数、总质量、整备质量、核定载质量、外廓尺寸、准牵引总质量、备注、检验记录。
另外,本接口还支持复印件、翻拍和PS告警功能。
*/
async VehicleLicenseOCR(
req: VehicleLicenseOCRRequest,
cb?: (error: string, rep: VehicleLicenseOCRResponse) => void
): Promise<VehicleLicenseOCRResponse> {
return this.request("VehicleLicenseOCR", req, cb)
}
} | the_stack |
import {
Attribute,
PrimaryIdentifierAttribute,
SecondaryIdentifierAttribute,
Method,
createAttributeDecorator,
createMethodDecorator,
isComponentClassOrInstance,
isComponentInstance
} from '@layr/component';
import {StorableComponent, SortDirection} from './storable';
import {
StorablePropertyFinder,
StorableAttribute,
StorableAttributeOptions,
StorablePrimaryIdentifierAttribute,
StorableSecondaryIdentifierAttribute,
StorableAttributeLoader,
StorableMethod,
StorableMethodOptions
} from './properties';
import type {IndexAttributes} from './index-class';
import {isStorableClass, isStorableInstance, isStorableClassOrInstance} from './utilities';
type StorableAttributeDecoratorOptions = Omit<StorableAttributeOptions, 'value' | 'default'>;
/**
* Decorates an attribute of a storable component so it can be combined with a [`Loader`](https://layrjs.com/docs/v2/reference/storable-attribute#loader-type), a [`Finder`](https://layrjs.com/docs/v2/reference/storable-property#finder-type), or any kind of [`Hook`](https://layrjs.com/docs/v2/reference/storable-attribute#hook-type).
*
* @param [valueType] A string specifying the [type of values](https://layrjs.com/docs/v2/reference/value-type#supported-types) that can be stored in the attribute (default: `'any'`).
* @param [options] The options to create the [`StorableAttribute`](https://layrjs.com/docs/v2/reference/storable-attribute#constructor).
*
* @examplelink See an example of use in the [`StorableAttribute`](https://layrjs.com/docs/v2/reference/storable-attribute) class.
*
* @category Decorators
* @decorator
*/
export function attribute(
valueType?: string,
options?: StorableAttributeDecoratorOptions
): PropertyDecorator;
export function attribute(options?: StorableAttributeDecoratorOptions): PropertyDecorator;
export function attribute(
valueType?: string | StorableAttributeDecoratorOptions,
options?: StorableAttributeDecoratorOptions
) {
return createAttributeDecorator(
new Map([
[isStorableClassOrInstance, StorableAttribute],
[isComponentClassOrInstance, Attribute]
]),
'attribute',
valueType,
options
);
}
/**
* Decorates an attribute of a component as a [storable primary identifier attribute](https://layrjs.com/docs/v2/reference/storable-primary-identifier-attribute).
*
* @param [valueType] A string specifying the type of values the attribute can store. It can be either `'string'` or `'number'` (default: `'string'`).
* @param [options] The options to create the [`StorablePrimaryIdentifierAttribute`](https://layrjs.com/docs/v2/reference/storable-primary-identifier-attribute#constructor).
*
* @category Decorators
* @decorator
*/
export function primaryIdentifier(
valueType?: string,
options?: StorableAttributeDecoratorOptions
): PropertyDecorator;
export function primaryIdentifier(options?: StorableAttributeDecoratorOptions): PropertyDecorator;
export function primaryIdentifier(
valueType?: string | StorableAttributeDecoratorOptions,
options?: StorableAttributeDecoratorOptions
) {
return createAttributeDecorator(
new Map([
[isStorableInstance, StorablePrimaryIdentifierAttribute],
[isComponentInstance, PrimaryIdentifierAttribute]
]),
'primaryIdentifier',
valueType,
options
);
}
/**
* Decorates an attribute of a component as a [storable secondary identifier attribute](https://layrjs.com/docs/v2/reference/storable-secondary-identifier-attribute).
*
* @param [valueType] A string specifying the type of values the attribute can store. It can be either `'string'` or `'number'` (default: `'string'`).
* @param [options] The options to create the [`StorableSecondaryIdentifierAttribute`](https://layrjs.com/docs/v2/reference/storable-secondary-identifier-attribute#constructor).
*
* @category Decorators
* @decorator
*/
export function secondaryIdentifier(
valueType?: string,
options?: StorableAttributeDecoratorOptions
): PropertyDecorator;
export function secondaryIdentifier(options?: StorableAttributeDecoratorOptions): PropertyDecorator;
export function secondaryIdentifier(
valueType?: string | StorableAttributeDecoratorOptions,
options?: StorableAttributeDecoratorOptions
) {
return createAttributeDecorator(
new Map([
[isStorableInstance, StorableSecondaryIdentifierAttribute],
[isComponentInstance, SecondaryIdentifierAttribute]
]),
'secondaryIdentifier',
valueType,
options
);
}
/**
* Decorates a method of a storable component so it can be combined with a [`Finder`](https://layrjs.com/docs/v2/reference/storable-property#finder-type).
*
* @param [options] The options to create the [`StorableMethod`](https://layrjs.com/docs/v2/reference/storable-method#constructor).
*
* @examplelink See an example of use in the [`StorableMethod`](https://layrjs.com/docs/v2/reference/storable-method) class.
*
* @category Decorators
* @decorator
*/
export function method(options: StorableMethodOptions = {}) {
return createMethodDecorator(
new Map([
[isStorableClassOrInstance, StorableMethod],
[isComponentClassOrInstance, Method]
]),
'method',
options
);
}
/**
* Decorates a storable attribute with a [`Loader`](https://layrjs.com/docs/v2/reference/storable-attribute#loader-type).
*
* @param loader A function representing the [`Loader`](https://layrjs.com/docs/v2/reference/storable-attribute#loader-type) of the storable attribute.
*
* @examplelink See an example of use in the [`StorableAttribute`](https://layrjs.com/docs/v2/reference/storable-attribute) class.
*
* @category Decorators
* @decorator
*/
export function loader(loader: StorableAttributeLoader) {
return function (target: typeof StorableComponent | StorableComponent, name: string) {
if (!isStorableClassOrInstance(target)) {
throw new Error(
`@loader() must be used as a storable component attribute decorator (property: '${name}')`
);
}
if (
!target.hasStorableAttribute(name) ||
target.getStorableAttribute(name, {autoFork: false}).getParent() !== target
) {
throw new Error(
`@loader() must be used in combination with @attribute() (property: '${name}')`
);
}
target.getStorableAttribute(name).setLoader(loader);
};
}
/**
* Decorates a storable attribute or method with a [`Finder`](https://layrjs.com/docs/v2/reference/storable-property#finder-type).
*
* @param finder A function representing the [`Finder`](https://layrjs.com/docs/v2/reference/storable-property#finder-type) of the storable attribute or method.
*
* @examplelink See an example of use in the [`StorableAttribute`](https://layrjs.com/docs/v2/reference/storable-attribute) and [`StorableMethod`](https://layrjs.com/docs/v2/reference/storable-method) classes.
*
* @category Decorators
* @decorator
*/
export function finder(finder: StorablePropertyFinder) {
return function (target: StorableComponent, name: string) {
if (!isStorableInstance(target)) {
throw new Error(
`@finder() must be used as a storable component property decorator (property: '${name}')`
);
}
if (
!target.hasStorableProperty(name) ||
target.getStorableProperty(name, {autoFork: false}).getParent() !== target
) {
throw new Error(
`@finder() must be used in combination with @attribute() or @method() (property: '${name}')`
);
}
target.getStorableProperty(name).setFinder(finder);
};
}
type ClassIndexParam = IndexAttributes;
type ClassIndexOptions = {isUnique?: boolean};
type AttributeIndexParam = {direction?: SortDirection; isUnique?: boolean};
/**
* Defines an [index](https://layrjs.com/docs/v2/reference/index) for an attribute or a set of attributes.
*
* This decorator is commonly placed before a storable component attribute to define a [single attribute index](https://layrjs.com/docs/v2/reference/index#single-attribute-indexes), but it can also be placed before a storable component class to define a [compound attribute index](https://layrjs.com/docs/v2/reference/index#compound-attribute-indexes).
*
* @param [optionsOrAttributes] Depends on the type of index you want to define (see below).
* @param [options] An object specifying some options in the case of compound attribute index (see below).
*
* @details
* ###### Single Attribute Indexes
*
* You can define an index for a single attribute by placing the `@index()` decorator before an attribute definition. In this case, you can specify the following parameters:
*
* - `options`:
* - `direction`: A string representing the sort direction of the index. The possible values are `'asc'` (ascending) or `'desc'` (descending) and the default value is `'asc'`.
* - `isUnique`: A boolean specifying whether the index should hold unique values or not (default: `false`). When set to `true`, the underlying database will prevent you to store an attribute with the same value in multiple storable components.
*
* ###### Compound Attribute Indexes
*
* You can define an index that combines multiple attributes by placing the `@index()` decorator before a storable component class definition. In this case, you can specify the following parameters:
*
* - `attributes`: An object specifying the attributes to be indexed. The shape of the object should be `{attributeName: direction, ...}` where `attributeName` is a string representing the name of an attribute and `direction` is a string representing the sort direction (possible values: `'asc'` or `'desc'`).
* - `options`:
* - `isUnique`: A boolean specifying whether the index should hold unique values or not (default: `false`). When set to `true`, the underlying database will prevent you to store an attribute with the same value in multiple storable components.
*
* @example
* ```
* // JS
*
* import {Component} from '@layr/component';
* import {Storable, attribute, index} from '@layr/storable';
*
* // An index that combines the `year` and `title` attributes:
* ﹫index({year: 'desc', title: 'asc'})
* export class Movie extends Storable(Component) {
* // An index for the `title` attribute with the `isUnique` option:
* @index({isUnique: true}) @attribute('string') title;
*
* // An index for the `year` attribute with the `'desc'` sort direction:
* @index({direction: 'desc'}) @attribute('number') year;
* }
* ```
*
* @example
* ```
* // TS
*
* import {Component} from '@layr/component';
* import {Storable, attribute, index} from '@layr/storable';
*
* // An index that combines the `year` and `title` attributes:
* ﹫index({year: 'desc', title: 'asc'})
* export class Movie extends Storable(Component) {
* // An index for the `title` attribute with the `isUnique` option:
* @index({isUnique: true}) @attribute('string') title!: string;
*
* // An index for the `year` attribute with the `'desc'` sort direction:
* @index({direction: 'desc'}) @attribute('number') year!: string;
* }
* ```
*
* @category Decorators
* @decorator
*/
export function index(
param?: AttributeIndexParam
): (target: StorableComponent, name: string) => void;
export function index(
param: ClassIndexParam,
options?: ClassIndexOptions
): (target: typeof StorableComponent) => void;
export function index(
param: ClassIndexParam | AttributeIndexParam = {},
options: ClassIndexOptions = {}
) {
return function (target: typeof StorableComponent | StorableComponent, name?: string) {
if (name === undefined) {
// Class decorator
if (!isStorableClass(target)) {
throw new Error(
`@index() must be used as a storable component class decorator or a storable component attribute decorator`
);
}
target.prototype.setIndex(param as ClassIndexParam, options);
return;
}
// Attribute decorator
if (!isStorableInstance(target)) {
throw new Error(
`@index() must be used as a storable component class decorator or a storable component attribute decorator (property: '${name}')`
);
}
if (
!target.hasProperty(name) ||
target.getProperty(name, {autoFork: false}).getParent() !== target
) {
throw new Error(
`@index() must be used in combination with @attribute() (property: '${name}')`
);
}
const {direction = 'asc', isUnique} = param as AttributeIndexParam;
target.setIndex({[name]: direction}, {isUnique});
};
} | the_stack |
import EventsList from '../interfaces/events-list';
import Level from '../interfaces/level';
import Source from '../interfaces/source';
import { DVR_THRESHOLD, EVENT_OPTIONS, SUPPORTS_HLS } from '../utils/constants';
import { addEvent } from '../utils/events';
import { loadScript } from '../utils/general';
import { isHlsSource } from '../utils/media';
import Native from './native';
declare const Hls: any;
/**
* HLS Media.
*
* @description Class that handles M3U8 files using hls.js within the player
* @see https://github.com/video-dev/hls.js/
* @class HlsMedia
*/
class HlsMedia extends Native {
/**
* Instance of hls.js player.
*
* @type Hls
* @memberof HlsMedia
*/
#player: any;
/**
* Hls events that will be triggered in Player.
*
* @see https://github.com/video-dev/hls.js/blob/master/src/events.js
* @type EventsList
* @memberof HlsMedia
*/
#events: EventsList = {};
/**
* Time in milliseconds to attempt to recover media after an error.
*
* @type number
* @memberof HlsMedia
*/
#recoverDecodingErrorDate = 0;
/**
* Time in milliseconds to attempt to swap audio codec after an error.
*
* @type number
* @memberof HlsMedia
*/
#recoverSwapAudioCodecDate = 0;
/**
* Hls options to be passed to the Hls instance.
*
* @see https://github.com/video-dev/hls.js/blob/master/docs/API.md#fine-tuning
* @private
* @type object
* @memberof HlsMedia
*/
#options?: unknown;
/**
* Flag to indicate if `autoplay` attribute was set
*
* @private
* @type boolean
* @memberof HlsMedia
*/
#autoplay: boolean;
/**
* Creates an instance of HlsMedia.
*
* @param {HTMLMediaElement} element
* @param {Source} mediaSource
* @memberof HlsMedia
*/
constructor(element: HTMLMediaElement, mediaSource: Source, autoplay = false, options?: unknown) {
super(element, mediaSource);
this.#options = options || {};
this.element = element;
this.media = mediaSource;
this.#autoplay = autoplay;
this.promise = (typeof Hls === 'undefined')
// Ever-green script
? loadScript('https://cdn.jsdelivr.net/npm/hls.js@latest/dist/hls.min.js')
: new Promise(resolve => {
resolve({});
});
this._create = this._create.bind(this);
this._revoke = this._revoke.bind(this);
this._play = this._play.bind(this);
this._pause = this._pause.bind(this);
this.promise.then(this._create);
return this;
}
/**
* Provide support via hls.js if browser does not have native support for HLS
*
* @inheritDoc
* @memberof HlsMedia
*/
public canPlayType(mimeType: string): boolean {
return SUPPORTS_HLS() && mimeType === 'application/x-mpegURL';
}
/**
*
* @inheritDoc
* @memberof HlsMedia
*/
public load(): void {
if (this.#player) {
this.#player.detachMedia();
this.#player.loadSource(this.media.src);
this.#player.attachMedia(this.element);
}
const e = addEvent('loadedmetadata');
this.element.dispatchEvent(e);
if (!this.#events) {
this.#events = Hls.Events;
Object.keys(this.#events).forEach(event => {
this.#player.on(this.#events[event], (...args: Array<Record<string, unknown>>) => this._assign(this.#events[event], args));
});
}
}
/**
*
* @inheritDoc
* @memberof HlsMedia
*/
public destroy(): void {
this._revoke();
}
/**
*
* @inheritDoc
* @memberof HlsMedia
*/
set src(media: Source) {
if (isHlsSource(media)) {
this._revoke();
this.#player = new Hls(this.#options);
this.#player.loadSource(media.src);
this.#player.attachMedia(this.element);
this.#events = Hls.Events;
Object.keys(this.#events).forEach(event => {
this.#player.on(this.#events[event], (...args: Array<Record<string, unknown>>) => this._assign(this.#events[event], args));
});
}
}
get levels(): Level[] {
const levels: Level[] = [];
if (this.#player && this.#player.levels && this.#player.levels.length) {
Object.keys(this.#player.levels).forEach(item => {
const { height, name } = this.#player.levels[item];
const level = {
height,
id: item,
label: name || null,
};
levels.push(level);
});
}
return levels;
}
set level(level: number) {
this.#player.currentLevel = level;
}
get level(): number {
return this.#player ? this.#player.currentLevel : -1;
}
/**
* Setup Hls player with options.
*
* Some of the options/events will be overridden to improve performance and user's experience.
*
* @private
* @memberof HlsMedia
*/
private _create() {
const autoplay = !!(this.element.preload === 'auto' || this.#autoplay);
(this.#options as Record<string, unknown>).autoStartLoad = autoplay;
this.#player = new Hls(this.#options);
this.instance = this.#player;
this.#events = Hls.Events;
Object.keys(this.#events).forEach(event => {
this.#player.on(this.#events[event], (...args: Array<Record<string, unknown>>) => this._assign(this.#events[event], args));
});
if (!autoplay) {
this.element.addEventListener('play', this._play, EVENT_OPTIONS);
this.element.addEventListener('pause', this._pause, EVENT_OPTIONS);
}
}
/**
* Custom HLS events
*
* These events can be attached to the original node using addEventListener and the name of the event,
* using or not Hls.Events object
* @see https://github.com/video-dev/hls.js/blob/master/src/events.js
* @see https://github.com/video-dev/hls.js/blob/master/src/errors.js
* @see https://github.com/video-dev/hls.js/blob/master/docs/API.md#runtime-events
* @see https://github.com/video-dev/hls.js/blob/master/docs/API.md#errors
* @param {string} event The name of the HLS event
* @param {any} data The data passed to the event, could be an object or an array
* @memberof HlsMedia
*/
private _assign(event: string, data: Array<Record<string, unknown>>): void {
if (event === 'hlsError') {
const errorDetails = {
detail: {
data,
message: data[1].details,
type: 'HLS',
},
};
const errorEvent = addEvent('playererror', errorDetails);
this.element.dispatchEvent(errorEvent);
// borrowed from https://video-dev.github.io/hls.js/demo
const type = data[1].type as string;
const fatal = data[1].fatal;
const details = data[1];
if (fatal) {
switch (type) {
case 'mediaError':
const now = new Date().getTime();
if (!this.#recoverDecodingErrorDate || (now - this.#recoverDecodingErrorDate) > 3000) {
this.#recoverDecodingErrorDate = new Date().getTime();
this.#player.recoverMediaError();
} else if (!this.#recoverSwapAudioCodecDate || (now - this.#recoverSwapAudioCodecDate) > 3000) {
this.#recoverSwapAudioCodecDate = new Date().getTime();
console.warn('Attempting to swap Audio Codec and recover from media error');
this.#player.swapAudioCodec();
this.#player.recoverMediaError();
} else {
const msg = 'Cannot recover, last media error recovery failed';
console.error(msg);
const mediaEvent = addEvent(type, { detail: { data: details }});
this.element.dispatchEvent(mediaEvent);
}
break;
case 'networkError':
const message = 'Network error';
console.error(message);
const networkEvent = addEvent(type, { detail: { data: details }});
this.element.dispatchEvent(networkEvent);
break;
default:
this.#player.destroy();
const fatalEvent = addEvent(type, { detail: { data: details }});
this.element.dispatchEvent(fatalEvent);
break;
}
} else {
const err = addEvent(type, { detail: { data: details }});
this.element.dispatchEvent(err);
}
} else {
const details: Record<string, unknown> = data[1] as Record<string, unknown>;
if (event === 'hlsLevelLoaded' && details.live === true) {
this.element.setAttribute('op-live__enabled', 'true');
const timeEvent = addEvent('timeupdate');
this.element.dispatchEvent(timeEvent);
} else if (event === 'hlsLevelUpdated' && details.live === true && (details.totalduration as number) > DVR_THRESHOLD) {
this.element.setAttribute('op-dvr__enabled', 'true');
const timeEvent = addEvent('timeupdate');
this.element.dispatchEvent(timeEvent);
} else if (event === 'hlsFragParsingMetadata') {
const metaEvent = addEvent('metadataready', { detail: { data: data[1] } });
this.element.dispatchEvent(metaEvent);
}
const e = addEvent(event, { detail: { data: data[1] } });
this.element.dispatchEvent(e);
}
}
/**
* Remove all hls.js events and destroy hls.js player instance.
*
* @memberof HlsMedia
*/
private _revoke(): void {
if (this.#player) {
this.#player.stopLoad();
}
if (this.#events) {
Object.keys(this.#events).forEach(event => {
this.#player.off(this.#events[event], (...args: Array<Record<string, unknown>>) => this._assign(this.#events[event], args));
});
}
this.element.removeEventListener('play', this._play);
this.element.removeEventListener('pause', this._pause);
if (this.#player) {
this.#player.destroy();
this.#player = null;
}
}
private _play(): void {
if (this.#player) {
this.#player.startLoad();
}
}
private _pause(): void {
if (this.#player) {
this.#player.stopLoad();
}
}
}
export default HlsMedia; | the_stack |
import * as fs from 'fs';
import { inspect, promisify } from 'util';
import * as xml2js from 'xml2js';
import { AbstractRunnable, RunnableReloadResult } from '../AbstractRunnable';
import { AbstractTest, AbstractTestEvent } from '../AbstractTest';
import { Suite } from '../Suite';
import { DOCTest } from './DOCTest';
import { SharedVariables } from '../SharedVariables';
import { RunningRunnable, ProcessResult } from '../RunningRunnable';
import { RunnableProperties } from '../RunnableProperties';
import { CancellationFlag, Version } from '../Util';
import { TestGrouping } from '../TestGroupingInterface';
import { RootSuite } from '../RootSuite';
interface XmlObject {
[prop: string]: any; //eslint-disable-line
}
export class DOCRunnable extends AbstractRunnable {
public constructor(
shared: SharedVariables,
rootSuite: RootSuite,
execInfo: RunnableProperties,
docVersion: Version | undefined,
) {
super(shared, rootSuite, execInfo, 'doctest', Promise.resolve(docVersion));
}
private getTestGrouping(): TestGrouping {
if (this.properties.testGrouping) {
return this.properties.testGrouping;
} else {
const grouping = { groupByExecutable: this._getGroupByExecutable() };
return grouping;
}
}
private async _reloadFromString(
testListOutput: string,
cancellationFlag: CancellationFlag,
): Promise<RunnableReloadResult> {
const testGrouping = this.getTestGrouping();
let res: XmlObject = {};
new xml2js.Parser({ explicitArray: true }).parseString(testListOutput, (err: Error, result: XmlObject) => {
if (err) {
throw err;
} else {
res = result;
}
});
const reloadResult = new RunnableReloadResult();
for (let i = 0; i < res.doctest.TestCase.length; ++i) {
if (cancellationFlag.isCancellationRequested) return reloadResult;
const testCase = res.doctest.TestCase[i].$;
const testName = testCase.name;
const filePath: string | undefined = testCase.filename
? await this._resolveSourceFilePath(testCase.filename)
: undefined;
const line: number | undefined = testCase.line !== undefined ? Number(testCase.line) - 1 : undefined;
const skippedOpt: boolean | undefined = testCase.skipped !== undefined ? testCase.skipped === 'true' : undefined;
const suite: string | undefined = testCase.testsuite !== undefined ? testCase.testsuite : undefined;
const description: string | undefined = testCase.description;
const tags = suite !== undefined ? [`${suite}`] : [];
const skipped = skippedOpt !== undefined ? skippedOpt : false;
reloadResult.add(
...(await this._createSubtreeAndAddTest(
testGrouping,
testName,
testName,
filePath,
tags,
(parent: Suite) =>
new DOCTest(this._shared, this, parent, testName, skipped, filePath, line, tags, description),
(old: AbstractTest): boolean => (old as DOCTest).update(filePath, line, tags, skipped),
)),
);
}
return reloadResult;
}
protected async _reloadChildren(cancellationFlag: CancellationFlag): Promise<RunnableReloadResult> {
const cacheFile = this.properties.path + '.TestMate.testListCache.txt';
if (this._shared.enabledTestListCaching) {
try {
const cacheStat = await promisify(fs.stat)(cacheFile);
const execStat = await promisify(fs.stat)(this.properties.path);
if (cacheStat.size > 0 && cacheStat.mtime > execStat.mtime) {
this._shared.log.info('loading from cache: ', cacheFile);
const content = await promisify(fs.readFile)(cacheFile, 'utf8');
return await this._reloadFromString(content, cancellationFlag);
}
} catch (e) {
this._shared.log.warn('coudnt use cache', e);
}
}
const args = this.properties.prependTestListingArgs.concat([
'--list-test-cases',
'--reporters=xml',
'--no-skip=true',
'--no-color=true',
]);
this._shared.log.info('discovering tests', this.properties.path, args, this.properties.options.cwd);
const docTestListOutput = await this.properties.spawner.spawnAsync(
this.properties.path,
args,
this.properties.options,
30000,
);
if (docTestListOutput.stderr && !this.properties.ignoreTestEnumerationStdErr) {
this._shared.log.warn(
'reloadChildren -> docTestListOutput.stderr',
docTestListOutput.stdout,
docTestListOutput.stderr,
docTestListOutput.error,
docTestListOutput.status,
);
return await this._createAndAddUnexpectedStdError(docTestListOutput.stdout, docTestListOutput.stderr);
}
const result = await this._reloadFromString(docTestListOutput.stdout, cancellationFlag);
if (this._shared.enabledTestListCaching) {
promisify(fs.writeFile)(cacheFile, docTestListOutput.stdout).catch(err =>
this._shared.log.warn('couldnt write cache file:', err),
);
}
return result;
}
private _getRunParamsCommon(childrenToRun: readonly Readonly<DOCTest>[]): string[] {
const execParams: string[] = [];
const testNames = childrenToRun.map(c => c.getEscapedTestName());
execParams.push('--test-case=' + testNames.join(','));
execParams.push('--no-skip=true');
execParams.push('--case-sensitive=true');
execParams.push('--duration=true');
if (this._shared.isNoThrow) execParams.push('--no-throw=true');
if (this._shared.rngSeed !== null) {
execParams.push('--order-by=rand');
execParams.push('--rand-seed=' + this._shared.rngSeed.toString());
}
return execParams;
}
protected _getRunParamsInner(childrenToRun: readonly Readonly<DOCTest>[]): string[] {
const execParams: string[] = this._getRunParamsCommon(childrenToRun);
execParams.push('--reporters=xml');
return execParams;
}
// eslint-disable-next-line
protected _getDebugParamsInner(childrenToRun: readonly Readonly<DOCTest>[], breakOnFailure: boolean): string[] {
const execParams: string[] = this._getRunParamsCommon(childrenToRun);
execParams.push('--reporters=console');
execParams.push('--no-breaks=' + (breakOnFailure ? 'false' : 'true'));
return execParams;
}
protected _handleProcess(testRunId: string, runInfo: RunningRunnable): Promise<void> {
const data = new (class {
public stdoutBuffer = '';
public stderrBuffer = '';
public inTestCase = false;
public currentChild: AbstractTest | undefined = undefined;
public route: Suite[] = [];
public beforeFirstTestCase = true;
public rngSeed: number | undefined = undefined;
public unprocessedXmlTestCases: [string, string][] = [];
public processedTestCases: AbstractTest[] = [];
})();
const testCaseTagRe = /<TestCase(\s+[^\n\r]+)[^\/](\/)?>/;
return new Promise<ProcessResult>(resolve => {
const chunks: string[] = [];
const processChunk = (chunk: string): void => {
chunks.push(chunk);
data.stdoutBuffer = data.stdoutBuffer + chunk;
let invariant = 99999;
do {
if (runInfo.cancellationToken.isCancellationRequested) return;
if (!data.inTestCase) {
if (data.beforeFirstTestCase && data.rngSeed === undefined) {
const ri = data.stdoutBuffer.match(/<Options\s+[^>\n]*rand_seed="([0-9]+)"/);
if (ri != null && ri.length == 2) {
data.rngSeed = Number(ri[1]);
}
}
const m = data.stdoutBuffer.match(testCaseTagRe);
if (m == null) return;
const skipped = m[2] === '/';
data.inTestCase = true;
let name = '';
if (skipped) {
new xml2js.Parser({ explicitArray: true }).parseString(m[0], (err: Error, result: XmlObject) => {
if (err) {
this._shared.log.exceptionS(err);
throw err;
} else {
name = result.TestCase.$.name;
}
});
} else {
new xml2js.Parser({ explicitArray: true }).parseString(
m[0] + '</TestCase>',
(err: Error, result: XmlObject) => {
if (err) {
this._shared.log.exceptionS(err);
throw err;
} else {
name = result.TestCase.$.name;
}
},
);
}
data.beforeFirstTestCase = false;
const test = this._findTest(v => v.compare(name));
if (test) {
const route = [...test.route()];
this.sendMinimalEventsIfNeeded(testRunId, data.route, route);
data.route = route;
data.currentChild = test;
this._shared.log.info('Test', data.currentChild.testNameAsId, 'has started.');
if (!skipped) {
this._shared.sendTestRunEvent(data.currentChild.getStartEvent(testRunId));
data.stdoutBuffer = data.stdoutBuffer.substr(m.index!);
} else {
this._shared.log.info('Test ', data.currentChild.testNameAsId, 'has skipped.');
// this always comes so we skip it
//const testCaseXml = m[0];
//this._shared.sendTestEvent(data.currentChild.getStartEvent());
// try {
// const ev: TestEvent = data.currentChild.parseAndProcessTestCase(testCaseXml, data.rngSeed, runInfo);
// data.processedTestCases.push(data.currentChild);
// this._shared.sendTestEvent(ev);
// } catch (e) {
// this._shared.log.error('parsing and processing test', e, data, testCaseXml);
// this._shared.sendTestEvent({
// type: 'test',
// test: data.currentChild,
// state: 'errored',
// message: '😱 Unexpected error under parsing output !! Error: ' + inspect(e) + '\n',
// });
// }
data.inTestCase = false;
data.currentChild = undefined;
data.stdoutBuffer = data.stdoutBuffer.substr(m.index! + m[0].length);
}
} else {
this._shared.log.info('TestCase not found in children', name);
}
} else {
const endTestCase = '</TestCase>';
const b = data.stdoutBuffer.indexOf(endTestCase);
if (b == -1) return;
const testCaseXml = data.stdoutBuffer.substring(0, b + endTestCase.length);
if (data.currentChild !== undefined) {
this._shared.log.info('Test ', data.currentChild.testNameAsId, 'has finished.');
try {
const ev = data.currentChild.parseAndProcessTestCase(
testRunId,
testCaseXml,
data.rngSeed,
runInfo.timeout,
data.stderrBuffer,
);
this._shared.sendTestRunEvent(ev);
data.processedTestCases.push(data.currentChild);
} catch (e) {
this._shared.log.error('parsing and processing test', e, data, chunks, testCaseXml);
this._shared.sendTestRunEvent({
type: 'test',
test: data.currentChild,
state: 'errored',
message: [
'😱 Unexpected error under parsing output !! Error: ' + inspect(e),
'Consider opening an issue: https://github.com/matepek/vscode-catch2-test-adapter/issues/new/choose',
`Please attach the output of: "${runInfo.process.spawnfile} ${runInfo.process.spawnargs}"`,
'',
'⬇ std::cout:',
runInfo.process.stdout,
'⬆ std::cout',
'⬇ stdoutBuffer:',
data.stdoutBuffer,
'⬆ stdoutBuffer',
'⬇ std::cerr:',
runInfo.process.stderr,
'⬆ std::cerr',
'⬇ stderrBuffer:',
data.stderrBuffer,
'⬆ stderrBuffer',
].join('\n'),
});
}
} else {
this._shared.log.info('<TestCase> found without TestInfo: ', this, '; ', testCaseXml);
data.unprocessedXmlTestCases.push([testCaseXml, data.stderrBuffer]);
}
data.inTestCase = false;
data.currentChild = undefined;
// do not clear data.route
data.stdoutBuffer = data.stdoutBuffer.substr(b + endTestCase.length);
data.stderrBuffer = '';
}
} while (data.stdoutBuffer.length > 0 && --invariant > 0);
if (invariant == 0) {
this._shared.log.error('invariant==0', this, runInfo, data, chunks);
resolve(ProcessResult.error('Possible infinite loop of this extension'));
runInfo.killProcess();
}
};
runInfo.process.stdout.on('data', (chunk: Uint8Array) => processChunk(chunk.toLocaleString()));
runInfo.process.stderr.on('data', (chunk: Uint8Array) => (data.stderrBuffer += chunk.toLocaleString()));
runInfo.process.once('close', (code: number | null, signal: string | null) => {
if (runInfo.cancellationToken.isCancellationRequested) {
resolve(ProcessResult.ok());
} else {
if (code !== null && code !== undefined) resolve(ProcessResult.createFromErrorCode(code));
else if (signal !== null && signal !== undefined) resolve(ProcessResult.createFromSignal(signal));
else resolve(ProcessResult.error('unknown sfngvdlfkxdvgn'));
}
});
})
.catch((reason: Error) => {
// eslint-disable-next-line
if ((reason as any).code === undefined) this._shared.log.exceptionS(reason);
return new ProcessResult(reason);
})
.then((result: ProcessResult) => {
result.error && this._shared.log.info(result.error.toString(), result, runInfo, this, data);
if (data.inTestCase) {
if (data.currentChild !== undefined) {
this._shared.log.info('data.currentChild !== undefined: ', data);
let ev: AbstractTestEvent;
if (runInfo.cancellationToken.isCancellationRequested) {
ev = data.currentChild.getCancelledEvent(testRunId, data.stdoutBuffer);
} else if (runInfo.timeout !== null) {
ev = data.currentChild.getTimeoutEvent(testRunId, runInfo.timeout);
} else {
ev = data.currentChild.getFailedEventBase(testRunId);
ev.message = '😱 Unexpected error !!';
if (result.error) {
ev.state = 'errored';
ev.message += '\n' + result.error.message;
}
ev.message += [
'',
'⬇ std::cout:',
data.stdoutBuffer,
'⬆ std::cout',
'⬇ std::cerr:',
data.stderrBuffer,
'⬆ std::cerr',
].join('\n');
}
data.currentChild.lastRunEvent = ev;
this._shared.sendTestRunEvent(ev);
} else {
this._shared.log.warn('data.inTestCase: ', data);
}
}
this.sendMinimalEventsIfNeeded(testRunId, data.route, []);
data.route = [];
const isTestRemoved =
runInfo.timeout === null &&
!runInfo.cancellationToken.isCancellationRequested &&
result.error === undefined &&
data.processedTestCases.length < runInfo.childrenToRun.length;
if (data.unprocessedXmlTestCases.length > 0 || isTestRemoved) {
this.reloadTests(this._shared.taskPool, runInfo.cancellationToken).then(
() => {
// we have test results for the newly detected tests
// after reload we can set the results
const events: AbstractTestEvent[] = [];
for (let i = 0; i < data.unprocessedXmlTestCases.length; i++) {
const [testCaseXml, stderr] = data.unprocessedXmlTestCases[i];
const m = testCaseXml.match(testCaseTagRe);
if (m == null || m.length != 1) break;
let name: string | undefined = undefined;
new xml2js.Parser({ explicitArray: true }).parseString(
m[0] + '</TestCase>',
(err: Error, result: XmlObject) => {
if (err) {
this._shared.log.exceptionS(err);
} else {
name = result.TestCase.$.name;
}
},
);
if (name === undefined) break;
// xml output trimmes the name of the test
const currentChild = this._findTest(v => v.compare(name!));
if (currentChild === undefined) break;
try {
const ev = currentChild.parseAndProcessTestCase(
testRunId,
testCaseXml,
data.rngSeed,
runInfo.timeout,
stderr,
);
events.push(ev);
} catch (e) {
this._shared.log.error('parsing and processing test', e, testCaseXml);
}
}
events.length && this._shared.sendTestEvents(events);
},
(reason: Error) => {
// Suite possibly deleted: It is a dead suite.
this._shared.log.error('reloading-error: ', reason);
},
);
}
});
}
} | the_stack |
export class Endpoints {
static readonly CHANNEL
= (channelId) => [ 'channels', channelId ]
static readonly CHANNEL_BULK_DELETE
= (channelId) => [ 'channels', channelId, 'messages', 'bulk-delete' ]
static readonly CHANNEL_CALL_RING
= (channelId) => [ 'channels', channelId, 'call', 'ring' ]
static readonly CHANNEL_CROSSPOST
= (channelId, msgId) => [ 'channels', channelId, 'messages', msgId, 'crosspost' ]
static readonly CHANNEL_FOLLOW
= (channelId) => [ 'channels', channelId, 'followers' ]
static readonly CHANNEL_INVITES
= (channelId) => [ 'channels', channelId, 'invites' ]
static readonly CHANNEL_MESSAGE_REACTION
= (channelId, msgId, reaction) => [ 'channels', channelId, 'messages', msgId, 'reactions', reaction ]
static readonly CHANNEL_MESSAGE_REACTION_USER
= (channelId, msgId, reaction, userId) => [ 'channels', channelId, 'messages', msgId, 'reactions', reaction, userId ]
static readonly CHANNEL_MESSAGE_REACTIONS
= (channelId, msgId) => [ 'channels', channelId, 'messages', msgId, 'reactions' ]
static readonly CHANNEL_MESSAGE
= (channelId, msgId) => [ 'channels', channelId, 'messages', msgId ]
static readonly CHANNEL_MESSAGES
= (channelId) => [ 'channels', channelId, 'messages' ]
static readonly CHANNEL_MESSAGES_SEARCH
= (channelId) => [ 'channels', channelId, 'messages', 'search' ]
static readonly CHANNEL_PERMISSION
= (channelId, overId) => [ 'channels', channelId, 'permissions', overId ]
static readonly CHANNEL_PERMISSIONS
= (channelId) => [ 'channels', channelId, 'permissions' ]
static readonly CHANNEL_PIN
= (channelId, msgId) => [ 'channels', channelId, 'pins', msgId ]
static readonly CHANNEL_PINS
= (channelId) => [ 'channels', channelId, 'pins' ]
static readonly CHANNEL_RECIPIENT
= (groupId, userId) => [ 'channels', groupId, 'recipients', userId ]
static readonly CHANNEL_TYPING
= (channelId) => [ 'channels', channelId, 'typing' ]
static readonly CHANNEL_WEBHOOKS
= (channelId) => [ 'channels', channelId, 'webhooks' ]
static readonly CHANNELS
= () => [ 'channels' ]
static readonly CUSTOM_EMOJI_GUILD
= (emojiId) => [ 'emojis', emojiId, 'guild' ]
static readonly DISCOVERY_CATEGORIES
= () => [ 'discovery', 'categories' ]
static readonly DISCOVERY_VALIDATION
= () => [ 'discovery', 'valid-term' ]
static readonly GATEWAY
= () => [ 'gateway' ]
static readonly GATEWAY_BOT
= () => [ 'gateway', 'bot' ]
static readonly GUILD
= (guildId) => [ 'guilds', guildId ]
static readonly GUILD_AUDIT_LOGS
= (guildId) => [ 'guilds', guildId, 'audit-logs' ]
static readonly GUILD_BAN
= (guildId, memberId) => [ 'guilds', guildId, 'bans', memberId ]
static readonly GUILD_BANS
= (guildId) => [ 'guilds', guildId, 'bans' ]
static readonly GUILD_CHANNELS
= (guildId) => [ 'guilds', guildId, 'channels' ]
static readonly GUILD_DISCOVERY
= (guildId) => [ 'guilds', guildId, 'discovery-metadata' ]
static readonly GUILD_DISCOVERY_CATEGORY
= (guildId, categoryId) => [ 'guilds', guildId, 'discovery-categories', categoryId ]
static readonly GUILD_EMBED
= (guildId) => [ 'guilds', guildId, 'embed' ]
static readonly GUILD_EMOJI
= (guildId, emojiId) => [ 'guilds', guildId, 'emojis', emojiId ]
static readonly GUILD_EMOJIS
= (guildId) => [ 'guilds', guildId, 'emojis' ]
static readonly GUILD_INTEGRATION
= (guildId, integrationId) => [ 'guilds', guildId, 'integrations', integrationId ]
static readonly GUILD_INTEGRATION_SYNC
= (guildId, integrationId) => [ 'guilds', guildId, 'integrations', integrationId, 'sync' ]
static readonly GUILD_INTEGRATIONS
= (guildId) => [ 'guilds', guildId, 'integrations' ]
static readonly GUILD_INVITES
= (guildId) => [ 'guilds', guildId, 'invites' ]
static readonly GUILD_VANITY_URL
= (guildId) => [ 'guilds', guildId, 'vanity-url' ]
static readonly GUILD_MEMBER
= (guildId, memberId) => [ 'guilds', guildId, 'members', memberId ]
static readonly GUILD_MEMBER_NICK
= (guildId, memberId) => [ 'guilds', guildId, 'members', memberId, 'nick' ]
static readonly GUILD_MEMBER_ROLE
= (guildId, memberId, roleId) => [ 'guilds', guildId, 'members', memberId, 'roles', roleId ]
static readonly GUILD_MEMBERS
= (guildId) => [ 'guilds', guildId, 'members' ]
static readonly GUILD_MEMBERS_SEARCH
= (guildId) => [ 'guilds', guildId, 'members', 'search' ]
static readonly GUILD_MESSAGES_SEARCH
= (guildId) => [ 'guilds', guildId, 'messages', 'search' ]
static readonly GUILD_PREVIEW
= (guildId) => [ 'guilds', guildId, 'preview' ]
static readonly GUILD_PRUNE
= (guildId) => [ 'guilds', guildId, 'prune' ]
static readonly GUILD_ROLE
= (guildId, roleId) => [ 'guilds', guildId, 'roles', roleId ]
static readonly GUILD_ROLES
= (guildId) => [ 'guilds', guildId, 'roles' ]
static readonly GUILD_TEMPLATE
= (code) => [ 'guilds', 'templates', code ]
static readonly GUILD_TEMPLATES
= (guildId) => [ 'guilds', guildId, 'templates' ]
static readonly GUILD_TEMPLATE_GUILD
= (guildId, code) => [ 'guilds', guildId, 'templates', code ]
static readonly GUILD_VOICE_REGIONS
= (guildId) => [ 'guilds', guildId, 'regions' ]
static readonly GUILD_WEBHOOKS
= (guildId) => [ 'guilds', guildId, 'webhooks' ]
static readonly GUILD_WELCOME_SCREEN
= (guildId) => [ 'guilds', guildId, 'welcome-screen' ]
static readonly GUILD_WIDGET_SETTINGS
= (guildId) => [ 'guilds', guildId, 'widget' ]
static readonly GUILD_WIDGET
= (guildId) => [ 'guilds', guildId, 'widget.json' ]
static readonly GUILD_VOICE_STATE
= (guildId, user) => [ 'guilds', guildId, 'voice-states', user ]
static readonly GUILDS
= () => [ 'guilds' ]
static readonly INVITE
= (inviteId) => [ 'invites', inviteId ]
static readonly OAUTH2_APPLICATION
= (appId) => [ 'oauth2', 'applications', appId ]
static readonly STAGE_INSTANCE
= (channelId) => [ 'stage-instances', channelId ]
static readonly STAGE_INSTANCES
= () => [ 'stage-instances' ]
static readonly STICKER
= (stickerId) => [ 'stickers', stickerId ]
static readonly NITRO_STICKERS
= () => [ 'sticker-packs' ]
static readonly GUILD_STICKER
= (guildId, stickerId) => [ 'guilds', guildId, 'stickers', stickerId ]
static readonly GUILD_STICKERS
= (guildId) => [ 'guilds', guildId, 'stickers' ]
static readonly CHANNEL_THREAD_MEMBER
= (channelId, memberId) => [ 'channels', channelId, 'thread-members', memberId ]
static readonly CHANNEL_MESSAGE_THREADS
= (channelId, messageId) => [ 'channels', channelId, 'messages', messageId, 'threads' ]
static readonly CHANNEL_THREADS
= (channelId) => [ 'channels', channelId, 'threads' ]
static readonly CHANNEL_ACTIVE_THREADS
= (channelId) => [ 'channels', channelId, 'threads', 'active' ]
static readonly CHANNEL_ARCHIVE_THREADS
= (channelId, type) => [ 'channels', channelId, 'threads', 'archived', type ]
static readonly CHANNEL_ARCHIVED_JOINED_THREADS
= (channelId) => [ 'channels', channelId, 'users', '@me', 'threads', 'archived', 'private' ]
static readonly GUILD_ACTIVE_THREADS
= (guildId) => [ 'guilds', guildId, 'threads', 'active' ]
static readonly USER
= (userId) => [ 'users', userId ]
static readonly USER_BILLING
= (userId) => [ 'users', userId, 'billing' ]
static readonly USER_BILLING_PAYMENTS
= (userId) => [ 'users', userId, 'billing', 'payments' ]
static readonly USER_BILLING_PREMIUM_SUBSCRIPTION
= (userId) => [ 'users', userId, 'billing', 'premium-subscription' ]
static readonly USER_CHANNELS
= (userId) => [ 'users', userId, 'channels' ]
static readonly USER_CONNECTIONS
= (userId) => [ 'users', userId, 'connections' ]
static readonly USER_CONNECTION_PLATFORM
= (userId, platform, id) => [ 'users', userId, 'connections', platform, id ]
static readonly USER_GUILD
= (userId, guildId) => [ 'users', userId, 'guilds', guildId ]
static readonly USER_GUILDS
= (userId) => [ 'users', userId, 'guilds' ]
static readonly USER_MFA_CODES
= (userId) => [ 'users', userId, 'mfa', 'codes' ]
static readonly USER_MFA_TOTP_DISABLE
= (userId) => [ 'users', userId, 'mfa', 'totp', 'disable' ]
static readonly USER_MFA_TOTP_ENABLE
= (userId) => [ 'users', userId, 'mfa', 'totp', 'enable' ]
static readonly USER_NOTE
= (userId, targetId) => [ 'users', userId, 'note', targetId ]
static readonly USER_PROFILE
= (userId) => [ 'users', userId, 'profile' ]
static readonly USER_RELATIONSHIP
= (userId, relId) => [ 'users', userId, 'relationships', relId ]
static readonly USER_SETTINGS
= (userId) => [ 'users', userId, 'settings' ]
static readonly USERS
= () => [ 'users' ]
static readonly VOICE_REGIONS
= () => [ 'voice', 'regions' ]
static readonly WEBHOOK
= (hookId) => [ 'webhooks', hookId ]
static readonly WEBHOOK_MESSAGE
= (hookId, token, msgId) => [ 'webhooks', hookId, token, 'messages', msgId ]
static readonly WEBHOOK_SLACK
= (hookId) => [ 'webhooks', hookId, 'slack' ]
static readonly WEBHOOK_TOKEN
= (hookId, token) => [ 'webhooks', hookId, token ]
static readonly WEBHOOK_TOKEN_SLACK
= (hookId, token) => [ 'webhooks', hookId, token, 'slack' ]
// CDN Endpoints
static readonly ACHIEVEMENT_ICON
= (applicationId, achievementId, icon) => [ 'app-assets', applicationId, 'achievements', achievementId, 'icons', icon ]
static readonly APPLICATION_ASSET
= (applicationId, asset) => [ 'app-assets', applicationId, asset ]
static readonly APPLICATION_ICON
= (applicationId, icon) => [ 'app-icons', applicationId, icon ]
static readonly CHANNEL_ICON
= (channelId, channelIcon) => [ 'channel-icons', channelId, channelIcon ]
static readonly CUSTOM_EMOJI
= (emojiId) => [ 'emojis', emojiId ]
static readonly DEFAULT_USER_AVATAR
= (userDiscriminator) => [ 'embed', 'avatars', userDiscriminator ]
static readonly GUILD_BANNER
= (guildId, guildBanner) => [ 'banners', guildId, guildBanner ]
static readonly GUILD_DISCOVERY_SPLASH
= (guildId, guildDiscoverySplash) => [ 'discovery-splashes', guildId, guildDiscoverySplash ]
static readonly GUILD_ICON
= (guildId, guildIcon) => [ 'icons', guildId, guildIcon ]
static readonly GUILD_SPLASH
= (guildId, guildSplash) => [ 'splashes', guildId, guildSplash ]
static readonly TEAM_ICON
= (teamId, teamIcon) => [ 'team-icons', teamId, teamIcon ]
static readonly USER_AVATAR
= (userId, userAvatar) => [ 'avatars', userId, userAvatar ]
} | the_stack |
import './styles.js';
import {FilePath} from 'chrome://resources/mojo/mojo/public/mojom/base/file_path.mojom-webui.js';
import {Url} from 'chrome://resources/mojo/url/mojom/url.mojom-webui.js';
import {afterNextRender, html} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {kMaximumGooglePhotosPreviews, kMaximumLocalImagePreviews} from '../../common/constants.js';
import {isNonEmptyArray, isNullOrArray, isNullOrNumber, promisifyOnload} from '../../common/utils.js';
import {sendCollections, sendGooglePhotosCount, sendGooglePhotosPhotos, sendImageCounts, sendLocalImageData, sendLocalImages, sendVisible} from '../iframe_api.js';
import {WallpaperCollection, WallpaperImage, WallpaperProviderInterface} from '../personalization_app.mojom-webui.js';
import {WithPersonalizationStore} from '../personalization_store.js';
import {initializeBackdropData} from './wallpaper_controller.js';
import {getWallpaperProvider} from './wallpaper_interface_provider.js';
let sendCollectionsFunction = sendCollections;
let sendGooglePhotosCountFunction = sendGooglePhotosCount;
let sendGooglePhotosPhotosFunction = sendGooglePhotosPhotos;
let sendImageCountsFunction = sendImageCounts;
let sendLocalImagesFunction = sendLocalImages;
let sendLocalImageDataFunction = sendLocalImageData;
/**
* Mock out the iframe api functions for testing. Return promises that are
* resolved when the function is called by |WallpaperCollectionsElement|.
*/
interface PromisifyResult {
sendCollections: Promise<unknown>;
sendGooglePhotosCount: Promise<unknown>;
sendGooglePhotosPhotos: Promise<unknown>;
sendImageCounts: Promise<unknown>;
sendLocalImages: Promise<unknown>;
sendLocalImageData: Promise<unknown>;
}
export function promisifyIframeFunctionsForTesting(): PromisifyResult {
const resolvers = {} as
{[key in keyof PromisifyResult]: (_: unknown) => void};
const promises = ([
'sendCollections',
'sendGooglePhotosCount',
'sendGooglePhotosPhotos',
'sendImageCounts',
'sendLocalImages',
'sendLocalImageData',
] as (keyof PromisifyResult)[])
.reduce((result, next) => {
result[next] =
new Promise(resolve => resolvers[next] = resolve);
return result;
}, {} as PromisifyResult);
sendCollectionsFunction = (...args) => resolvers['sendCollections'](args);
sendGooglePhotosCountFunction = (...args) =>
resolvers['sendGooglePhotosCount'](args);
sendGooglePhotosPhotosFunction = (...args) =>
resolvers['sendGooglePhotosPhotos'](args);
sendImageCountsFunction = (...args) => resolvers['sendImageCounts'](args);
sendLocalImagesFunction = (...args) => resolvers['sendLocalImages'](args);
sendLocalImageDataFunction = (...args) =>
resolvers['sendLocalImageData'](args);
return promises;
}
export class WallpaperCollections extends WithPersonalizationStore {
static get is() {
return 'wallpaper-collections';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* Hidden state of this element. Used to notify iframe of visibility
* changes.
*/
hidden: {
type: Boolean,
reflectToAttribute: true,
observer: 'onHiddenChanged_',
},
collections_: Array,
collectionsLoading_: Boolean,
/**
* The list of Google Photos photos.
*/
googlePhotos_: Array,
/**
* Whether the list of Google Photos photos is currently loading.
*/
googlePhotosLoading_: Boolean,
/**
* The count of Google Photos photos.
*/
googlePhotosCount_: Number,
/**
* Whether the count of Google Photos photos is currently loading.
*/
googlePhotosCountLoading_: Boolean,
/**
* Contains a mapping of collection id to an array of images.
*/
images_: Object,
/**
* Contains a mapping of collection id to loading boolean.
*/
imagesLoading_: Object,
localImages_: Array,
/**
* Whether the local image list is currently loading.
*/
localImagesLoading_: Boolean,
/**
* Stores a mapping of local image id to loading status.
*/
localImageDataLoading_: Object,
/**
* Stores a mapping of local image id to thumbnail data.
*/
localImageData_: Object,
hasError_: {
type: Boolean,
// Call computed functions with their dependencies as arguments so that
// polymer knows when to re-run the computation.
computed:
'computeHasError_(collections_, collectionsLoading_, localImages_, localImagesLoading_)',
},
};
}
hidden: boolean;
private collections_: WallpaperCollection[];
private collectionsLoading_: boolean;
private googlePhotos_: unknown[]|null;
private googlePhotosLoading_: boolean;
private googlePhotosCount_: number|null;
private googlePhotosCountLoading_: boolean;
private images_: Record<string, WallpaperImage[]>;
private imagesLoading_: Record<string, boolean>;
private localImages_: FilePath[];
private localImagesLoading_: boolean;
private localImageData_: Record<string, string>;
private localImageDataLoading_: Record<string, boolean>;
private hasError_: boolean;
private wallpaperProvider_: WallpaperProviderInterface;
private iframePromise_: Promise<HTMLIFrameElement>;
private didSendLocalImageData_: boolean;
static get observers() {
return [
'onCollectionsChanged_(collections_, collectionsLoading_)',
'onCollectionImagesChanged_(images_, imagesLoading_)',
'onGooglePhotosChanged_(googlePhotos_, googlePhotosLoading_)',
'onGooglePhotosCountChanged_(googlePhotosCount_, googlePhotosCountLoading_)',
'onLocalImagesChanged_(localImages_, localImagesLoading_)',
'onLocalImageDataChanged_(localImages_, localImageData_, localImageDataLoading_)',
];
}
constructor() {
super();
this.wallpaperProvider_ = getWallpaperProvider();
this.iframePromise_ =
promisifyOnload(this, 'collections-iframe', afterNextRender) as
Promise<HTMLIFrameElement>;
this.didSendLocalImageData_ = false;
}
connectedCallback() {
super.connectedCallback();
this.watch('collections_', state => state.wallpaper.backdrop.collections);
this.watch(
'collectionsLoading_', state => state.wallpaper.loading.collections);
this.watch('googlePhotos_', state => state.wallpaper.googlePhotos.photos);
this.watch(
'googlePhotosLoading_',
state => state.wallpaper.loading.googlePhotos.photos);
this.watch(
'googlePhotosCount_', state => state.wallpaper.googlePhotos.count);
this.watch(
'googlePhotosCountLoading_',
state => state.wallpaper.loading.googlePhotos.count);
this.watch('images_', state => state.wallpaper.backdrop.images);
this.watch('imagesLoading_', state => state.wallpaper.loading.images);
this.watch('localImages_', state => state.wallpaper.local.images);
this.watch(
'localImagesLoading_', state => state.wallpaper.loading.local.images);
this.watch('localImageData_', state => state.wallpaper.local.data);
this.watch(
'localImageDataLoading_', state => state.wallpaper.loading.local.data);
this.updateFromStore();
initializeBackdropData(this.wallpaperProvider_, this.getStore());
}
/**
* Notify iframe that this element visibility has changed.
*/
private async onHiddenChanged_(hidden: boolean) {
if (!hidden) {
document.title = this.i18n('title');
}
const iframe = await this.iframePromise_;
sendVisible(iframe.contentWindow!, !hidden);
}
private computeHasError_(
collections: WallpaperCollection[], collectionsLoading: boolean,
localImages: FilePath[], localImagesLoading: boolean): boolean {
return this.localImagesError_(localImages, localImagesLoading) &&
this.collectionsError_(collections, collectionsLoading);
}
private collectionsError_(
collections: WallpaperCollection[],
collectionsLoading: boolean): boolean {
return !collectionsLoading && !isNonEmptyArray(collections);
}
private localImagesError_(
localImages: FilePath[], localImagesLoading: boolean): boolean {
return !localImagesLoading && !isNonEmptyArray(localImages);
}
private async onCollectionsChanged_(
collections: WallpaperCollection[], collectionsLoading: boolean) {
// Check whether collections are loaded before sending to
// the iframe. Collections could be null/empty array.
if (!collectionsLoading) {
const iframe = await this.iframePromise_;
sendCollectionsFunction(iframe.contentWindow!, collections);
}
}
/**
* Send count of image units in each collection when a new collection is
* fetched. D/L variants of the same image represent a count of 1.
*/
private async onCollectionImagesChanged_(
images: Record<string, WallpaperImage[]>,
imagesLoading: Record<string, boolean>) {
if (!images || !imagesLoading) {
return;
}
const counts = Object.entries(images)
.filter(([collectionId]) => {
return imagesLoading[collectionId] === false;
})
.map(([key, value]) => {
// Collection has completed loading. If no images were
// retrieved, set count value to null to indicate
// failure.
if (Array.isArray(value)) {
const unitIds = new Set();
value.forEach(image => {
unitIds.add(image.unitId);
});
return [key, unitIds.size] as [string, number];
} else {
return [key, null] as [string, null];
}
})
.reduce((result, [key, value]) => {
result[key!] = value;
return result;
}, {} as Record<string, number|null>);
const iframe = await this.iframePromise_;
sendImageCountsFunction(iframe.contentWindow!, counts);
}
/** Invoked on changes to the list of Google Photos photos. */
private async onGooglePhotosChanged_(
googlePhotos: Url[]|null, googlePhotosLoading: boolean) {
if (googlePhotosLoading || !isNullOrArray(googlePhotos)) {
return;
}
const iframe = await this.iframePromise_;
sendGooglePhotosPhotosFunction(
iframe.contentWindow!,
googlePhotos?.slice(0, kMaximumGooglePhotosPreviews) ?? null);
}
/** Invoked on changes to the count of Google Photos photos. */
private async onGooglePhotosCountChanged_(
googlePhotosCount: number|null, googlePhotosCountLoading: boolean) {
if (googlePhotosCountLoading || !isNullOrNumber(googlePhotosCount)) {
return;
}
const iframe = await this.iframePromise_;
sendGooglePhotosCountFunction(iframe.contentWindow!, googlePhotosCount);
}
/**
* Send updated local images list to the iframe.
*/
private async onLocalImagesChanged_(
localImages: FilePath[]|null, localImagesLoading: boolean) {
this.didSendLocalImageData_ = false;
if (!localImagesLoading && Array.isArray(localImages)) {
const iframe = await this.iframePromise_;
sendLocalImagesFunction(iframe.contentWindow!, localImages);
}
}
/**
* Send up to |maximumImageThumbnailsCount| image thumbnails to untrusted.
*/
private async onLocalImageDataChanged_(
images: FilePath[]|null, imageData: Record<string, string>,
imageDataLoading: Record<string, boolean>) {
if (!Array.isArray(images) || !imageData || !imageDataLoading ||
this.didSendLocalImageData_) {
return;
}
const successfullyLoaded: string[] =
images.map(image => image.path).filter(key => {
const doneLoading = imageDataLoading[key] === false;
const success = !!imageData[key];
return success && doneLoading;
});
function shouldSendImageData() {
if (!Array.isArray(images)) {
return false;
}
// All images (up to |kMaximumLocalImagePreviews|) have loaded.
const didLoadMaximum = successfullyLoaded.length >=
Math.min(kMaximumLocalImagePreviews, images.length);
return didLoadMaximum ||
// No more images to load so send now even if some failed.
images.every(image => imageDataLoading[image.path] === false);
}
if (shouldSendImageData()) {
// Also send information about which images failed to load. This is
// necessary to decide whether to show loading animation or failure svg
// while updating local images.
const failures = images.map(image => image.path)
.filter(key => {
const doneLoading =
imageDataLoading[key] === false;
const failure = imageData[key] === '';
return failure && doneLoading;
})
.reduce((result, key) => {
// Empty string means that this image failed to
// load.
result[key] = '';
return result;
}, {} as Record<string, string>);
const data =
successfullyLoaded.filter((_, i) => i < kMaximumLocalImagePreviews)
.reduce((result, key) => {
result[key] = imageData[key];
return result;
}, failures);
this.didSendLocalImageData_ = true;
const iframe = await this.iframePromise_;
sendLocalImageDataFunction(iframe.contentWindow!, data);
}
}
}
customElements.define(WallpaperCollections.is, WallpaperCollections); | the_stack |
import React from "react"
import { observer } from "mobx-react"
import { action, observable, computed, reaction } from "mobx"
import {
GrapherInterface,
GrapherQueryParams,
} from "../grapher/core/GrapherInterface"
import {
ExplorerControlPanel,
ExplorerControlBar,
} from "../explorer/ExplorerControls"
import ReactDOM from "react-dom"
import { ExplorerProgram } from "../explorer/ExplorerProgram"
import { ColumnSlug, SerializedGridProgram } from "../clientUtils/owidTypes"
import {
Grapher,
GrapherManager,
GrapherProgrammaticInterface,
} from "../grapher/core/Grapher"
import {
debounce,
excludeUndefined,
exposeInstanceOnWindow,
flatten,
isInIFrame,
keyMap,
omitUndefinedValues,
throttle,
uniqBy,
} from "../clientUtils/Util"
import {
SlideShowController,
SlideShowManager,
} from "../grapher/slideshowController/SlideShowController"
import {
ExplorerChoiceParams,
ExplorerContainerId,
ExplorerFullQueryParams,
EXPLORERS_PREVIEW_ROUTE,
EXPLORERS_ROUTE_FOLDER,
UNSAVED_EXPLORER_DRAFT,
UNSAVED_EXPLORER_PREVIEW_QUERYPARAMS,
} from "./ExplorerConstants"
import { EntityPickerManager } from "../grapher/controls/entityPicker/EntityPickerConstants"
import { SelectionArray } from "../grapher/selection/SelectionArray"
import { SortOrder, TableSlug } from "../coreTable/CoreTableConstants"
import { isNotErrorValue } from "../coreTable/ErrorValues"
import { Bounds, DEFAULT_BOUNDS } from "../clientUtils/Bounds"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faChartLine } from "@fortawesome/free-solid-svg-icons/faChartLine"
import { EntityPicker } from "../grapher/controls/entityPicker/EntityPicker"
import classNames from "classnames"
import { ColumnTypeNames, CoreColumnDef } from "../coreTable/CoreColumnDef"
import { BlankOwidTable, OwidTable } from "../coreTable/OwidTable"
import { BAKED_BASE_URL } from "../settings/clientSettings"
import {
explorerUrlMigrationsById,
migrateExplorerUrl,
} from "./urlMigrations/ExplorerUrlMigrations"
import { setWindowUrl, Url } from "../clientUtils/urls/Url"
import { ExplorerPageUrlMigrationSpec } from "./urlMigrations/ExplorerPageUrlMigrationSpec"
import { setSelectedEntityNamesParam } from "../grapher/core/EntityUrlBuilder"
import { PromiseCache } from "../clientUtils/PromiseCache"
import { PromiseSwitcher } from "../clientUtils/PromiseSwitcher"
export interface ExplorerProps extends SerializedGridProgram {
grapherConfigs?: GrapherInterface[]
queryStr?: string
isEmbeddedInAnOwidPage?: boolean
isInStandalonePage?: boolean
isPreview?: boolean
canonicalUrl?: string
selection?: SelectionArray
}
const renderLivePreviewVersion = (props: ExplorerProps) => {
let renderedVersion: string
setInterval(() => {
const versionToRender =
localStorage.getItem(UNSAVED_EXPLORER_DRAFT + props.slug) ??
props.program
if (versionToRender === renderedVersion) return
const newProps = { ...props, program: versionToRender }
ReactDOM.render(
<Explorer
{...newProps}
queryStr={window.location.search}
key={Date.now()}
isPreview={true}
/>,
document.getElementById(ExplorerContainerId)
)
renderedVersion = versionToRender
}, 1000)
}
const isNarrow = () =>
window.screen.width < 450 || document.documentElement.clientWidth <= 800
@observer
export class Explorer
extends React.Component<ExplorerProps>
implements
SlideShowManager<ExplorerChoiceParams>,
EntityPickerManager,
GrapherManager
{
// caution: do a ctrl+f to find untyped usages
static renderSingleExplorerOnExplorerPage(
program: ExplorerProps,
grapherConfigs: GrapherInterface[],
urlMigrationSpec?: ExplorerPageUrlMigrationSpec
) {
const props: ExplorerProps = {
...program,
grapherConfigs,
isEmbeddedInAnOwidPage: false,
isInStandalonePage: true,
}
if (window.location.href.includes(EXPLORERS_PREVIEW_ROUTE)) {
renderLivePreviewVersion(props)
return
}
let url = Url.fromURL(window.location.href)
// Handle redirect spec that's baked on the page.
// e.g. the old COVID Grapher to Explorer redirects are implemented this way.
if (urlMigrationSpec) {
const { explorerUrlMigrationId, baseQueryStr } = urlMigrationSpec
const migration = explorerUrlMigrationsById[explorerUrlMigrationId]
if (migration) {
url = migration.migrateUrl(url, baseQueryStr)
} else {
console.error(
`No explorer URL migration with id ${explorerUrlMigrationId}`
)
}
}
// Handle explorer-specific migrations.
// This is how we migrate the old CO2 explorer to the new CO2 explorer.
// Because they are on the same path, we can't handle it like we handle
// the COVID explorer redirects above.
url = migrateExplorerUrl(url)
// Update the window URL
setWindowUrl(url)
ReactDOM.render(
<Explorer {...props} queryStr={url.queryStr} />,
document.getElementById(ExplorerContainerId)
)
}
private initialQueryParams = Url.fromQueryStr(this.props.queryStr ?? "")
.queryParams as ExplorerFullQueryParams
explorerProgram = ExplorerProgram.fromJson(this.props).initDecisionMatrix(
this.initialQueryParams
)
// only used for the checkbox at the bottom of the embed dialog
@observable embedDialogHideControls = true
selection =
this.props.selection ??
new SelectionArray(
this.explorerProgram.selection,
undefined,
this.explorerProgram.entityType
)
@observable.ref grapher?: Grapher
@action.bound setGrapher(grapher: Grapher) {
this.grapher = grapher
}
@computed get grapherConfigs() {
const arr = this.props.grapherConfigs || []
const grapherConfigsMap: Map<number, GrapherInterface> = new Map()
arr.forEach((config) => grapherConfigsMap.set(config.id!, config))
return grapherConfigsMap
}
componentDidMount() {
this.setGrapher(this.grapherRef!.current!)
this.updateGrapherFromExplorer()
this.updateEntityPickerTable()
let url = Url.fromQueryParams(this.initialQueryParams)
if (this.props.selection?.hasSelection) {
url = setSelectedEntityNamesParam(
url,
this.props.selection.selectedEntityNames
)
}
this.grapher?.populateFromQueryParams(url.queryParams)
exposeInstanceOnWindow(this, "explorer")
this.onResizeThrottled = throttle(this.onResize, 100)
window.addEventListener("resize", this.onResizeThrottled)
this.onResize() // call resize for the first time to initialize chart
if (this.props.isInStandalonePage) this.bindToWindow()
}
componentWillUnmount() {
if (this.onResizeThrottled)
window.removeEventListener("resize", this.onResizeThrottled)
}
private initSlideshow() {
const grapher = this.grapher
if (!grapher || grapher.slideShow) return
grapher.slideShow = new SlideShowController(
this.explorerProgram.decisionMatrix.allDecisionsAsQueryParams(),
0,
this
)
}
private persistedGrapherQueryParamsBySelectedRow: Map<
number,
Partial<GrapherQueryParams>
> = new Map()
// todo: break this method up and unit test more. this is pretty ugly right now.
@action.bound private reactToUserChangingSelection(oldSelectedRow: number) {
if (!this.grapher || !this.explorerProgram.currentlySelectedGrapherRow)
return // todo: can we remove this?
this.initSlideshow()
const oldGrapherParams = this.grapher.changedParams
this.persistedGrapherQueryParamsBySelectedRow.set(
oldSelectedRow,
oldGrapherParams
)
const newGrapherParams = {
...this.persistedGrapherQueryParamsBySelectedRow.get(
this.explorerProgram.currentlySelectedGrapherRow
),
region: oldGrapherParams.region,
time: this.grapher.timeParam,
}
const previousTab = this.grapher.tab
this.updateGrapherFromExplorer()
// preserve the previous tab if that's still available in the new view;
// and use the first tab otherwise
newGrapherParams.tab = this.grapher.availableTabs.includes(previousTab)
? previousTab
: this.grapher.availableTabs[0]
this.grapher.populateFromQueryParams(newGrapherParams)
}
@action.bound private setGrapherTable(table: OwidTable) {
if (this.grapher) {
this.grapher.inputTable = table
this.grapher.appendNewEntitySelectionOptions()
}
}
private futureGrapherTable = new PromiseSwitcher<OwidTable>({
onResolve: (table) => this.setGrapherTable(table),
onReject: (error) => this.grapher?.setError(error),
})
tableLoader = new PromiseCache((slug: TableSlug | undefined) =>
this.explorerProgram.constructTable(slug)
)
@action.bound updateGrapherFromExplorer() {
const grapher = this.grapher
if (!grapher) return
const grapherConfigFromExplorer = this.explorerProgram.grapherConfig
const { grapherId, tableSlug, yScaleToggle, yAxisMin, facetYDomain } =
grapherConfigFromExplorer
const hasGrapherId = grapherId && isNotErrorValue(grapherId)
const grapherConfig = hasGrapherId
? this.grapherConfigs.get(grapherId!) ?? {}
: {}
const config: GrapherProgrammaticInterface = {
...grapherConfig,
...grapherConfigFromExplorer,
hideEntityControls: this.showExplorerControls,
manuallyProvideData: tableSlug ? true : false,
}
grapher.setAuthoredVersion(config)
grapher.reset()
grapher.yAxis.canChangeScaleType = yScaleToggle
grapher.yAxis.min = yAxisMin
if (facetYDomain) {
grapher.yAxis.facetDomain = facetYDomain
}
grapher.updateFromObject(config)
if (!hasGrapherId) {
// Clear any error messages, they are likely to be related to dataset loading.
this.grapher?.clearErrors()
// Set a table immediately. A BlankTable shows a loading animation.
this.setGrapherTable(
BlankOwidTable(tableSlug, `Loading table '${tableSlug}'`)
)
this.futureGrapherTable.set(this.tableLoader.get(tableSlug))
grapher.id = 0
}
// Download data if this is a Grapher ID inside the Explorer specification
grapher.downloadData()
grapher.slug = this.explorerProgram.slug
if (this.downloadDataLink)
grapher.externalCsvLink = this.downloadDataLink
}
@action.bound setSlide(choiceParams: ExplorerFullQueryParams) {
this.explorerProgram.decisionMatrix.setValuesFromChoiceParams(
choiceParams
)
}
@computed private get currentChoiceParams(): ExplorerChoiceParams {
const { decisionMatrix } = this.explorerProgram
return decisionMatrix.currentParams
}
@computed get queryParams(): ExplorerFullQueryParams {
if (!this.grapher) return {}
if (window.location.href.includes(EXPLORERS_PREVIEW_ROUTE))
localStorage.setItem(
UNSAVED_EXPLORER_PREVIEW_QUERYPARAMS +
this.explorerProgram.slug,
JSON.stringify(this.currentChoiceParams)
)
let url = Url.fromQueryParams(
omitUndefinedValues({
...this.grapher.changedParams,
pickerSort: this.entityPickerSort,
pickerMetric: this.entityPickerMetric,
hideControls: this.initialQueryParams.hideControls || undefined,
...this.currentChoiceParams,
})
)
url = setSelectedEntityNamesParam(
url,
this.selection.hasSelection
? this.selection.selectedEntityNames
: undefined
)
return url.queryParams as ExplorerFullQueryParams
}
@computed get currentUrl(): Url {
if (this.props.isPreview) return Url.fromQueryParams(this.queryParams)
return Url.fromURL(this.baseUrl).setQueryParams(this.queryParams)
}
private bindToWindow() {
// There is a surprisingly considerable performance overhead to updating the url
// while animating, so we debounce to allow e.g. smoother timelines
const pushParams = () => setWindowUrl(this.currentUrl)
const debouncedPushParams = debounce(pushParams, 100)
reaction(
() => this.queryParams,
() =>
this.grapher?.debounceMode
? debouncedPushParams()
: pushParams()
)
}
private get panels() {
return this.explorerProgram.decisionMatrix.choicesWithAvailability.map(
(choice) => (
<ExplorerControlPanel
key={choice.title}
explorerSlug={this.explorerProgram.slug}
choice={choice}
onChange={this.onChangeChoice(choice.title)}
isMobile={this.isNarrow}
/>
)
)
}
onChangeChoice = (choiceTitle: string) => (value: string) => {
const { currentlySelectedGrapherRow } = this.explorerProgram
this.explorerProgram.decisionMatrix.setValueCommand(choiceTitle, value)
if (currentlySelectedGrapherRow)
this.reactToUserChangingSelection(currentlySelectedGrapherRow)
}
private renderHeaderElement() {
return (
<div className="ExplorerHeaderBox">
<div></div>
<div className="ExplorerTitle">
{this.explorerProgram.explorerTitle}
</div>
<div
className="ExplorerSubtitle"
dangerouslySetInnerHTML={{
__html: this.explorerProgram.explorerSubtitle || "",
}}
></div>
</div>
)
}
@observable private isNarrow = isNarrow()
@computed private get isInIFrame() {
return isInIFrame()
}
@computed private get showExplorerControls() {
if (!this.props.isEmbeddedInAnOwidPage && !this.isInIFrame) return true
// Only allow hiding controls on embedded pages
return !(
this.explorerProgram.hideControls ||
this.initialQueryParams.hideControls === "true"
)
}
@computed private get downloadDataLink(): string | undefined {
return this.explorerProgram.downloadDataLink
}
@observable
private grapherContainerRef: React.RefObject<HTMLDivElement> =
React.createRef()
@observable.ref private grapherBounds = DEFAULT_BOUNDS
@observable.ref
private grapherRef: React.RefObject<Grapher> = React.createRef()
private renderControlBar() {
return (
<ExplorerControlBar
isMobile={this.isNarrow}
showControls={this.showMobileControlsPopup}
closeControls={this.closeControls}
>
{this.panels}
</ExplorerControlBar>
)
}
private renderEntityPicker() {
return (
<EntityPicker
key="entityPicker"
manager={this}
isDropdownMenu={this.isNarrow}
/>
)
}
private onResizeThrottled?: () => void
@action.bound private toggleMobileControls() {
this.showMobileControlsPopup = !this.showMobileControlsPopup
}
@action.bound private onResize() {
this.isNarrow = isNarrow()
this.grapherBounds = this.getGrapherBounds() || this.grapherBounds
}
// Todo: add better logic to maximize the size of the Grapher
private getGrapherBounds() {
const grapherContainer = this.grapherContainerRef.current
return grapherContainer
? new Bounds(
0,
0,
grapherContainer.clientWidth,
grapherContainer.clientHeight
)
: undefined
}
@observable private showMobileControlsPopup = false
private get mobileCustomizeButton() {
return (
<a
className="btn btn-primary mobile-button"
onClick={this.toggleMobileControls}
data-track-note="covid-customize-chart"
>
<FontAwesomeIcon icon={faChartLine} /> Customize chart
</a>
)
}
@action.bound private closeControls() {
this.showMobileControlsPopup = false
}
// todo: add tests for this and better tests for this class in general
@computed private get showHeaderElement() {
return (
this.showExplorerControls &&
this.explorerProgram.explorerTitle &&
this.panels.length > 0
)
}
render() {
const { showExplorerControls, showHeaderElement } = this
return (
<div
className={classNames({
Explorer: true,
"mobile-explorer": this.isNarrow,
HideControls: !showExplorerControls,
"is-embed": this.props.isEmbeddedInAnOwidPage,
})}
>
{showHeaderElement && this.renderHeaderElement()}
{showHeaderElement && this.renderControlBar()}
{showExplorerControls && this.renderEntityPicker()}
{showExplorerControls &&
this.isNarrow &&
this.mobileCustomizeButton}
<div className="ExplorerFigure" ref={this.grapherContainerRef}>
<Grapher
bounds={this.grapherBounds}
enableKeyboardShortcuts={true}
manager={this}
ref={this.grapherRef}
/>
</div>
</div>
)
}
@computed get editUrl() {
return `${EXPLORERS_ROUTE_FOLDER}/${this.props.slug}`
}
@computed get baseUrl() {
return `${BAKED_BASE_URL}/${EXPLORERS_ROUTE_FOLDER}/${this.props.slug}`
}
@computed get canonicalUrl() {
return this.props.canonicalUrl ?? this.currentUrl.fullUrl
}
@computed get embedDialogUrl() {
return this.currentUrl.updateQueryParams({
hideControls: this.embedDialogHideControls.toString(),
}).fullUrl
}
@action.bound embedDialogToggleHideControls() {
this.embedDialogHideControls = !this.embedDialogHideControls
}
@computed get embedDialogAdditionalElements() {
return (
<div style={{ marginTop: ".5rem" }}>
<label>
<input
type="checkbox"
checked={this.embedDialogHideControls}
onChange={this.embedDialogToggleHideControls}
/>{" "}
Hide controls
</label>
</div>
)
}
@computed get grapherTable() {
return this.grapher?.tableAfterAuthorTimelineFilter
}
@observable entityPickerMetric? = this.initialQueryParams.pickerMetric
@observable entityPickerSort? = this.initialQueryParams.pickerSort
@observable.ref entityPickerTable?: OwidTable
@observable.ref entityPickerTableIsLoading: boolean = false
private futureEntityPickerTable = new PromiseSwitcher<OwidTable>({
onResolve: (table) => {
this.entityPickerTable = table
this.entityPickerTableIsLoading = false
},
onReject: () => {
this.entityPickerTableIsLoading = false
},
})
private updateEntityPickerTable(): void {
if (this.entityPickerMetric) {
this.entityPickerTableIsLoading = true
this.futureEntityPickerTable.set(
this.tableLoader.get(
this.getTableSlugOfColumnSlug(this.entityPickerMetric)
)
)
}
}
setEntityPicker({
metric,
sort,
}: { metric?: string; sort?: SortOrder } = {}) {
if (metric) this.entityPickerMetric = metric
if (sort) this.entityPickerSort = sort
this.updateEntityPickerTable()
}
private tableSlugHasColumnSlug(
tableSlug: TableSlug | undefined,
columnSlug: ColumnSlug
) {
const columnDefsByTableSlug = this.explorerProgram.columnDefsByTableSlug
return !!columnDefsByTableSlug
.get(tableSlug)
?.find((def) => def.slug === columnSlug)
}
private getTableSlugOfColumnSlug(
columnSlug: ColumnSlug
): TableSlug | undefined {
// In most cases, column slugs will be duplicated in the tables, e.g. entityName.
// Prefer the current Grapher table if it contains the column slug.
const grapherTableSlug = this.explorerProgram.grapherConfig.tableSlug
if (this.tableSlugHasColumnSlug(grapherTableSlug, columnSlug)) {
return grapherTableSlug
}
// ...otherwise, search all tables for the column slug
return this.explorerProgram.tableSlugs.find((tableSlug) =>
this.tableSlugHasColumnSlug(tableSlug, columnSlug)
)
}
@computed get entityPickerColumnDefs(): CoreColumnDef[] {
const allColumnDefs = uniqBy(
flatten(
Array.from(this.explorerProgram.columnDefsByTableSlug.values())
),
(def) => def.slug
)
if (this.explorerProgram.pickerColumnSlugs) {
const columnDefsBySlug = keyMap(allColumnDefs, (def) => def.slug)
// Preserve the order of columns in the Explorer `pickerColumnSlugs`
return excludeUndefined(
this.explorerProgram.pickerColumnSlugs.map((slug) =>
columnDefsBySlug.get(slug)
)
)
} else {
const discardColumnTypes = new Set([
ColumnTypeNames.Year,
ColumnTypeNames.Date,
ColumnTypeNames.Day,
ColumnTypeNames.EntityId,
ColumnTypeNames.EntityCode,
])
return allColumnDefs.filter(
(def) =>
def.type === undefined || !discardColumnTypes.has(def.type)
)
}
}
@computed get requiredColumnSlugs() {
return this.grapher?.newSlugs ?? []
}
} | the_stack |
import { default as axios } from 'axios';
import BigNumber from 'bignumber.js';
import {
ApiAccount,
ApiFundingRates,
ApiHistoricalFundingRates,
ApiIndexPrice,
ApiMarketMessage,
ApiMarketName,
ApiOptions,
ApiOrder,
ApiOrderOnOrderbook,
ApiSide,
BigNumberable,
Fee,
Order,
Price,
SignedOrder,
SigningMethod,
address,
RequestMethod,
} from '../lib/types';
import { Orders } from './Orders';
const FOUR_WEEKS_IN_SECONDS = 60 * 60 * 24 * 28;
const DEFAULT_API_ENDPOINT = 'https://api.dydx.exchange';
const DEFAULT_API_TIMEOUT = 10000;
export class Api {
private endpoint: String;
private perpetualOrders: Orders;
private timeout: number;
constructor(
perpetualOrders: Orders,
apiOptions: ApiOptions = {},
) {
this.endpoint = apiOptions.endpoint || DEFAULT_API_ENDPOINT;
this.timeout = apiOptions.timeout || DEFAULT_API_TIMEOUT;
this.perpetualOrders = perpetualOrders;
}
// ============ Managing Orders ============
public async placePerpetualOrder({
order: {
side,
amount,
price,
maker,
taker,
expiration = new BigNumber(FOUR_WEEKS_IN_SECONDS),
limitFee,
salt,
},
market,
fillOrKill,
postOnly,
clientId,
cancelId,
cancelAmountOnRevert,
}: {
order: {
side: ApiSide,
amount: BigNumberable,
price: BigNumberable,
maker: address,
taker: address,
expiration: BigNumberable,
limitFee?: BigNumberable,
salt?: BigNumberable,
},
market: ApiMarketName,
fillOrKill?: boolean,
postOnly?: boolean,
clientId?: string,
cancelId?: string,
cancelAmountOnRevert?: boolean,
}): Promise<{ order: ApiOrder }> {
const order: SignedOrder = await this.createPerpetualOrder({
market,
side,
amount,
price,
maker,
taker,
expiration,
postOnly,
limitFee,
salt,
});
return this.submitPerpetualOrder({
order,
market,
fillOrKill,
postOnly,
cancelId,
clientId,
cancelAmountOnRevert,
});
}
/**
* Creates but does not place a signed perpetualOrder
*/
async createPerpetualOrder({
market,
side,
amount,
price,
maker,
taker,
expiration,
postOnly,
limitFee,
salt,
}: {
market: ApiMarketName,
side: ApiSide,
amount: BigNumberable,
price: BigNumberable,
maker: address,
taker: address,
expiration: BigNumberable,
postOnly: boolean,
limitFee?: BigNumberable,
salt?: BigNumberable,
}): Promise<SignedOrder> {
if (!Object.values(ApiMarketName).includes(market)) {
throw new Error(`market: ${market} is invalid`);
}
if (!Object.values(ApiSide).includes(side)) {
throw new Error(`side: ${side} is invalid`);
}
const amountNumber: BigNumber = new BigNumber(amount);
const perpetualLimitFee: Fee = limitFee
? new Fee(limitFee)
: this.perpetualOrders.getFeeForOrder(amountNumber, !postOnly);
const realExpiration: BigNumber = getRealExpiration(expiration);
const order: Order = {
maker,
taker,
limitFee: perpetualLimitFee,
isBuy: side === ApiSide.BUY,
isDecreaseOnly: false,
amount: amountNumber,
limitPrice: new Price(price),
triggerPrice: new Price('0'),
expiration: realExpiration,
salt: salt ? new BigNumber(salt) : generatePseudoRandom256BitNumber(),
};
const typedSignature: string = await this.perpetualOrders.signOrder(
order,
SigningMethod.Hash,
);
return {
...order,
typedSignature,
};
}
/**
* Submits an already signed perpetualOrder
*/
public async submitPerpetualOrder({
order,
market,
fillOrKill = false,
postOnly = false,
cancelId,
clientId,
cancelAmountOnRevert,
}: {
order: SignedOrder,
market: ApiMarketName,
fillOrKill?: boolean,
postOnly?: boolean,
cancelId?: string,
clientId?: string,
cancelAmountOnRevert?: boolean,
}): Promise<{ order: ApiOrder }> {
const jsonOrder = jsonifyPerpetualOrder(order);
const data: any = {
fillOrKill,
postOnly,
clientId,
cancelId,
cancelAmountOnRevert,
market,
order: jsonOrder,
};
return this.axiosRequest({
data,
method: RequestMethod.POST,
url: `${this.endpoint}/v2/orders`,
});
}
public async cancelOrder({
orderId,
maker,
}: {
orderId: string,
maker: address,
}): Promise<{ order: ApiOrder }> {
const signature = await this.perpetualOrders.signCancelOrderByHash(
orderId,
maker,
SigningMethod.Hash,
);
return this.axiosRequest({
url: `${this.endpoint}/v2/orders/${orderId}`,
method: RequestMethod.DELETE,
headers: {
authorization: `Bearer ${signature}`,
},
});
}
// ============ Getters ============
public async getMarkets():
Promise<{ markets: ApiMarketMessage[] }> {
return this.axiosRequest({
url: `${this.endpoint}/v1/perpetual-markets`,
method: RequestMethod.GET,
});
}
public async getAccountBalances({
accountOwner,
}: {
accountOwner: address,
}): Promise<ApiAccount> {
return this.axiosRequest({
url: `${this.endpoint}/v1/perpetual-accounts/${accountOwner}`,
method: RequestMethod.GET,
});
}
public async getOrderbook({
market,
}: {
market: ApiMarketName,
}): Promise<{ bids: ApiOrderOnOrderbook[], asks: ApiOrderOnOrderbook[] }> {
return this.axiosRequest({
url: `${this.endpoint}/v1/orderbook/${market}`,
method: RequestMethod.GET,
});
}
// ============ Funding Getters ============
/**
* Get the current and predicted funding rates.
*
* IMPORTANT: The `current` value returned by this function is not active until it has been mined
* on-chain, which may not happen for some period of time after the start of the hour. To get the
* funding rate that is currently active on-chain, use the getMarkets() function.
*
* The `current` rate is updated each hour, on the hour. The `predicted` rate is updated each
* minute, on the minute, and may be null if no premiums have been calculated since the last
* funding rate update.
*
* Params:
* - markets (optional): Limit results to the specified markets.
*/
public async getFundingRates({
markets,
}: {
markets?: ApiMarketName[],
} = {}): Promise<{ [market: string]: ApiFundingRates }> {
return this.axiosRequest({
url: `${this.endpoint}/v1/funding-rates`,
method: RequestMethod.GET,
params: { markets },
});
}
/**
* Get historical funding rates. The most recent funding rates are returned first.
*
* Params:
* - markets (optional): Limit results to the specified markets.
* - limit (optional): The maximum number of funding rates. The default, and maximum, is 100.
* - startingBefore (optional): Return funding rates effective before this date.
*/
public async getHistoricalFundingRates({
markets,
limit,
startingBefore,
}: {
markets?: ApiMarketName[],
limit?: number,
startingBefore?: Date,
} = {}): Promise<{ [market: string]: ApiHistoricalFundingRates }> {
return this.axiosRequest({
url: `${this.endpoint}/v1/historical-funding-rates`,
method: RequestMethod.GET,
params: {
markets,
limit,
startingBefore: startingBefore && startingBefore.toISOString(),
},
});
}
/**
* Get the index price used in the funding rate calculation.
*
* Params:
* - markets (optional): Limit results to the specified markets.
*/
public async getFundingIndexPrice({
markets,
}: {
markets?: ApiMarketName[],
} = {}): Promise<{ [market: string]: ApiIndexPrice }> {
return this.axiosRequest({
url: `${this.endpoint}/v1/index-price`,
method: RequestMethod.GET,
params: { markets },
});
}
private async axiosRequest(
{
url,
method,
headers,
data,
params,
}: {
url: string,
method: RequestMethod,
headers?: any,
data?: any,
params?: any,
}): Promise<any> {
try {
const response = await axios({
url,
method,
headers,
data,
params,
timeout: this.timeout,
});
return response.data;
} catch (error) {
if (error.response) {
throw new Error(error.response.data.errors[0].msg);
} else {
const newError = new Error(error.message);
newError.stack = error.stack;
throw new Error;
}
}
}
}
function generatePseudoRandom256BitNumber(): BigNumber {
const MAX_DIGITS_IN_UNSIGNED_256_INT = 78;
// BigNumber.random returns a pseudo-random number between 0 & 1 with a passed in number of
// decimal places.
// Source: https://mikemcl.github.io/bignumber.js/#random
const randomNumber = BigNumber.random(MAX_DIGITS_IN_UNSIGNED_256_INT);
const factor = new BigNumber(10).pow(MAX_DIGITS_IN_UNSIGNED_256_INT - 1);
const randomNumberScaledTo256Bits = randomNumber.times(factor).integerValue();
return randomNumberScaledTo256Bits;
}
function jsonifyPerpetualOrder(order: SignedOrder) {
return {
isBuy: order.isBuy,
isDecreaseOnly: order.isDecreaseOnly,
amount: order.amount.toFixed(0),
limitPrice: order.limitPrice.value.toString(),
triggerPrice: order.triggerPrice.value.toString(),
limitFee: order.limitFee.value.toString(),
maker: order.maker,
taker: order.taker,
expiration: order.expiration.toFixed(0),
typedSignature: order.typedSignature,
salt: order.salt.toFixed(0),
};
}
function getRealExpiration(expiration: BigNumberable): BigNumber {
return new BigNumber(expiration).eq(0) ?
new BigNumber(0)
: new BigNumber(Math.round(new Date().getTime() / 1000)).plus(
new BigNumber(expiration),
);
} | the_stack |
import addSemivoicedMarks from './fn/addSemivoicedMarks';
import addVoicedMarks from './fn/addVoicedMarks';
import byteSize from './fn/byteSize';
import charAt from './fn/charAt';
import charCodeAt from './fn/charCodeAt';
import combinateSoundMarks from './fn/combinateSoundMarks';
import concat from './fn/concat';
import convertIterationMarks from './fn/convertIterationMarks';
import convertProlongedSoundMarks from './fn/convertProlongedSoundMarks';
import endWith from './fn/endWith';
import has from './fn/has';
import hasSmallLetter from './fn/hasSmallLetter';
import hasSurrogatePair from './fn/hasSurrogatePair';
import hasUnpairedSurrogate from './fn/hasUnpairedSurrogate';
import includes from './fn/includes';
import indexOf from './fn/indexOf';
import is from './fn/is';
import isEmpty from './fn/isEmpty';
import isNumeric from './fn/isNumeric';
import isOnly from './fn/isOnly';
import isOnlyHiragana from './fn/isOnlyHiragana';
import isOnlyKatakana from './fn/isOnlyKatakana';
import lastIndexOf from './fn/lastIndexOf';
import matches from './fn/matches';
import padEnd from './fn/padEnd';
import padStart from './fn/padStart';
import remove from './fn/remove';
import removeUnpairedSurrogate from './fn/removeUnpairedSurrogate';
import removeVoicedMarks from './fn/removeVoicedMarks';
import repeat from './fn/repeat';
import replace from './fn/replace';
import replaceFromMap from './fn/replaceFromMap';
import search from './fn/search';
import slice from './fn/slice';
import split from './fn/split';
import startsWith from './fn/startsWith';
import substr from './fn/substr';
import substring from './fn/substring';
import test from './fn/test';
import toBasicLetter from './fn/toBasicLetter';
import toHiragana from './fn/toHiragana';
import toKatakana from './fn/toKatakana';
import toNarrow from './fn/toNarrow';
import toNarrowAlphanumeric from './fn/toNarrowAlphanumeric';
import toNarrowJapanese from './fn/toNarrowJapanese';
import toNarrowKatakana from './fn/toNarrowKatakana';
import toNarrowSign from './fn/toNarrowSign';
import toNarrowSymbolForJapanese from './fn/toNarrowSymbolForJapanese';
import toNumeric from './fn/toNumeric';
import toPhoeticKana from './fn/toPhoeticKana';
import toWide from './fn/toWide';
import toWideAlphanumeric from './fn/toWideAlphanumeric';
import toWideJapanese from './fn/toWideJapanese';
import toWideKatakana from './fn/toWideKatakana';
import toWideSign from './fn/toWideSign';
import toWideSymbolForJapanese from './fn/toWideSymbolForJapanese';
import arrayize from './util/arrayize';
/**
* ## Jacoクラス
*
* 日本語やマルチバイト文字・ASCII文字を扱いやすくするためのラッパークラス
*
* 文字列クラスを継承してはいないがメソッドは同等のものが実装されている。
* ただし基本的にほとんどのメソッドが破壊的メソッドかつチェインナブルである。
*
* @version 2.0.0
* @since 0.1.0
*/
export default class Jaco {
/**
* 文字列長
*
* - サロゲートペアを考慮する
*
* @version 2.0.0
* @since 2.0.0
* @readonly
*/
public get length(): number {
return arrayize(this.$).length;
}
/**
* 保持する文字列
*
* @version 2.0.0
* @since 0.1.0
*/
private $: string;
/**
* コンストラクタ
*
* ```javascript
* var a = new Jaco("あああ");
* ```
*
* @version 2.0.0
* @since 0.1.0
* @param str 対象の文字列
*/
constructor(str: any) {
// tslint:disable-line:no-any
this.$ = `${str}`;
}
/**
* 半濁点を追加する
*
* @version 2.0.0
* @since 1.1.0
*/
public addSemivoicedMarks(): Jaco {
return new Jaco(addSemivoicedMarks(this.$));
}
/**
* 濁点を追加する
*
* @version 2.0.0
* @since 1.1.0
*/
public addVoicedMarks(): Jaco {
return new Jaco(addVoicedMarks(this.$));
}
/**
* 後方結合
*
* @version 2.0.0
* @since 0.2.0
* @param element 結合する文字列
*/
public append(element: { toString(): string }): Jaco {
return new Jaco(concat(this, element));
}
/**
* 文字列のバイトサイズを返す
*
* @version 0.2.0
* @since 0.2.0
*/
public byteSize(): number {
return byteSize(this.$);
}
/**
* 文字列から指定位置の文字を返す
*
* - サロゲートペアを考慮する
* - String.prototype.charAt とは非互換
*
* @version 2.0.0
* @since 2.0.0
* @param index 指定位置
*/
public charAt(index: number = 0): Jaco {
return new Jaco(charAt(this.$, index));
}
/**
* 指定位置のUnicodeコードポイントを返す
*
* - サロゲートペアを考慮する
* - String.prototype.charCodeAt とは非互換
*
* @version 2.0.0
* @since 2.0.0
* @param charCodeAt 指定位置
*/
public charCodeAt(index: number = 0): number {
return charCodeAt(this.$, index);
}
/**
* コピーを生成する
*
* @version 0.2.0
* @since 0.2.0
*/
public clone(): Jaco {
return new Jaco(this.$);
}
/**
* 濁点・半濁点とひらがな・かたかなを結合させる
*
* @version 2.0.0
* @since 2.0.0
* @param convertOnly ひらがな・かたかなと結合させずに、文字だけ結合文字に変換
*/
public combinateSoundMarks(convertOnly: boolean = false): Jaco {
return new Jaco(combinateSoundMarks(this.$, convertOnly));
}
/**
* 文字列連結をおこなう
*
* - String.prototype.concat とは非互換
*
* @version 2.0.0
* @since 0.2.0
* @param ...args 文字列もしくはJacoインスタンス
*/
public concat(...args: (Jaco | ({ toString(): string }))[]): Jaco {
return new Jaco(concat(this.$, args));
}
/**
* 繰り返し記号をかなに置き換える
*
* @version 2.0.0
* @since 1.1.0
*/
public convertIterationMarks(): Jaco {
return new Jaco(convertIterationMarks(this.$));
}
/**
* 長音符をかなに置き換える
*
* @version 2.0.0
* @since 1.1.0
*/
public convertProlongedSoundMarks(): Jaco {
return new Jaco(convertProlongedSoundMarks(this.$));
}
/**
* 引数に指定された文字列が末尾と合致するか
*
* - サロゲートペアを考慮する
* - String.prototype.endWith とは非互換
*
* @version 2.0.0
* @since 2.0.0
* @param search 合致対象文字列
* @param position 末尾の位置
*/
public endWith(search: { toString(): string }, position?: number): boolean {
return endWith(this.$, search, position);
}
/**
* 該当の文字のいずれかを含んでいるかどうか
*
* @version 2.0.0
* @since 2.0.0
* @param characters 文字セット
* @return 結果の真偽
*/
public has(characters: { toString(): string }): boolean {
return has(this.$, characters);
}
/**
* 小書き文字を含むかどうか
*
* @version 1.1.0
* @since 1.1.0
* @return 小書き文字を含むかどうか
*/
public hasSmallLetter(): boolean {
return hasSmallLetter(this.$);
}
/**
* サロゲートペア文字列を含んでいるかどうか
*
* @version 2.0.0
* @since 2.0.0
* @return 結果の真偽
*/
public hasSurrogatePair(): boolean {
return hasSurrogatePair(this.$);
}
/**
* ペアになっていないサロゲートコードポイントを含んでいるかどうか
*
* @version 2.0.0
* @since 2.0.0
* @return 結果の真偽
*/
public hasUnpairedSurrogate(): boolean {
return hasUnpairedSurrogate(this.$);
}
/**
* 引数に指定された文字列が部分合致するか
*
* @version 2.0.0
* @since 2.0.0
* @param search 合致対象文字列
* @param position 開始位置
* @return 合致したかどうか
*/
public includes(search: Jaco | string, position: number = 0): boolean {
return includes(this.$, search, position);
}
/**
* 指定された文字列が最初に現れるインデックスを返す
*
* - サロゲートペアを考慮する
* - String.prototype.indexOf とは非互換
*
* @version 2.0.0
* @since 2.0.0
* @param search 検索文字列
* @param fromIndex 検索位置
*/
public indexOf(
search: { toString(): string },
fromIndex: number = 0
): number {
return indexOf(this.$, search, fromIndex);
}
/**
* 完全マッチ
*
* @version 0.2.0
* @since 0.2.0
* @param target 比較する文字列
*/
public is(target: { toString(): string }): boolean {
return is(this.$, target);
}
/**
* 文字が空かどうか
*
* @version 0.2.0
* @since 0.2.0
*/
public isEmpty(): boolean {
return isEmpty(this.$);
}
/**
* 数字だけで構成されているかどうか
*
* @version 2.0.0
* @since 0.5.0
* @param negative 負の数値も含めてチェックするかどうか
* @param floatingPoint 小数としてチェックするかどうか
* @return 結果の真偽
*/
public isNumeric(
negative: boolean = true,
floatingPoint: boolean = true
): boolean {
return isNumeric(this.$, negative, floatingPoint);
}
/**
* 該当の文字だけで構成されているかどうか
*
* @version 2.0.0
* @since 0.2.0
* @param characters 文字セット
* @return 結果の真偽
*/
public isOnly(characters: { toString(): string }): boolean {
return isOnly(this.$, characters);
}
/**
* ひらがなだけで構成されているかどうか
*
* @version 0.2.0
* @since 0.2.0
* @return 結果の真偽
*/
public isOnlyHiragana(): boolean {
return isOnlyHiragana(this.$);
}
/**
* カタカナだけで構成されているかどうか
*
* @version 0.2.0
* @since 0.2.0
* @return 結果の真偽
*/
public isOnlyKatakana(): boolean {
return isOnlyKatakana(this.$);
}
/**
* 指定された文字列が最後に現れるインデックスを返す
*
* - サロゲートペアを考慮する
* - String.prototype.lastIndexOf とは非互換
*
* @version 2.0.0
* @since 2.0.0
* @param search 検索文字列
* @param [fromIndex] 検索位置
*
*/
public lastIndexOf(
search: { toString(): string },
fromIndex: number = Infinity
): number {
return lastIndexOf(this.$, search, fromIndex);
}
/**
* 正規表現に対する文字列 のマッチングの際に、そのマッチ結果を得る
*
* @version 2.0.0
* @since 2.0.0
* @param regexp パターン
*/
public match(regexp: RegExp): RegExpMatchArray | null {
return this.$.match(regexp);
}
/**
* 正規表現に対する文字列 のマッチングの際に、そのマッチ結果を純粋な配列で得る
*
* @version 2.0.0
* @since 2.0.0
* @param pattern パターン
*/
public matches(pattern: RegExp): string[] {
return matches(this.$, pattern);
}
/**
* 【未実装】Unicode 正規化形式を返す
*
* TODO: 日本語に関係する文字になるべく対応する
*
* - String.prototype.normalize とは非互換
*
* @version x.x.x
* @since x.x.x
* @param form 正規化形式の種類
*/
public normalize(form: 'NFC' | 'NFD' | 'NFKC' | 'NFKD' = 'NFC'): never {
throw Error(`No support method yet`);
}
/**
* 最終的な文字列が指定された長さに到達するように文字列で延長する
*
* - サロゲートペアを考慮する
* - String.prototype.padEnd とは非互換
*
* @version 2.0.0
* @since 2.0.0
* @param targetLength 最終的な長さ
* @param padString 延長する文字列
*/
public padEnd(
targetLength: number,
padString: { toString(): string } = ' '
): Jaco {
return new Jaco(padEnd(this.$, targetLength, padString));
}
/**
* 最終的な文字列が指定された長さに到達するように文字列を先頭に追加する
*
* - サロゲートペアを考慮する
* - String.prototype.padStart とは非互換
*
* @version 2.0.0
* @since 2.0.0
* @param targetLength 最終的な長さ
* @param padString 延長する文字列
*/
public padStart(
targetLength: number,
padString: { toString(): string } = ' '
): Jaco {
return new Jaco(padStart(this.$, targetLength, padString));
}
/**
* 前方結合
*
* ```javascript
* new Jaco("あああ").prepend("いいい").toString() // => "いいいあああ"
* ```
*
* @version 0.2.0
* @since 0.2.0
* @param element 結合する文字列
*/
public prepend(element: { toString(): string }): Jaco {
return new Jaco(concat(element, this));
}
/**
* 文字列を取り除く
*
* @version 2.0.0
* @since 0.2.0
* @param pattern 取り除く文字列
*/
public remove(pattern: RegExp | { toString(): string }): Jaco {
return new Jaco(remove(this.$, pattern));
}
/**
* ペアになっていないサロゲートコードポイントの削除
*
* @version 2.0.0
* @since 2.0.0
*/
public removeUnpairedSurrogate(): Jaco {
return new Jaco(removeUnpairedSurrogate(this.$));
}
/**
* 濁点・半濁点を取り除く
*
* @version 1.1.0
* @since 1.1.0
* @param ignoreSingleMark 単体の濁点・半濁点を除去するかどうか
*/
public removeVoicedMarks(ignoreSingleMark: boolean = false): Jaco {
return new Jaco(removeVoicedMarks(this.$, ignoreSingleMark));
}
/**
* 文字列を繰り返す
*
* - String.prototype.repeat とは非互換
*
* @version 2.0.0
* @since 2.0.0
* @param times 繰り返しの回数
*/
public repeat(times: number = 0): Jaco {
return new Jaco(repeat(this.$, times));
}
/**
* 文字列をパターンで置換する
*
* @version 2.0.0
* @since 0.2.0
* @param pattern 対象のパターン
* @param replacement 置換する文字列
*/
public replace(
pattern: RegExp | { toString(): string },
replacement: { toString(): string }
): Jaco {
return new Jaco(replace(this.$, pattern, replacement));
}
/**
* キーがパターン・値が置換文字列のハッシュマップによって置換する
*
* @version 2.0.0
* @since 0.1.0
* @param convMap キーがパターン・値が置換文字列のハッシュマップ
*/
public replaceFromMap(convMap: { [pattern: string]: string }): Jaco {
return new Jaco(replaceFromMap(this.$, convMap));
}
/**
* 正規表現にマッチしたインデックスを返す
*
* - サロゲートペアを考慮する
* - String.prototype.search とは非互換
*
* @version 2.0.0
* @since 2.0.0
* @param pattern パターン
*/
public search(pattern: RegExp | { toString(): string }): number {
return search(this.$, pattern);
}
/**
* 文字位置による抽出
*
* - サロゲートペアを考慮する
* - String.prototype.slice とは非互換
*
* @version 2.0.0
* @since 0.2.0
* @param start 開始インデックス
* @param end 終了インデックス 省略すると最後まで
*/
public slice(start: number, end?: number): Jaco {
return new Jaco(slice(this.$, start, end));
}
/**
* 文字列の配列に分割する
*
* - String.prototype.split とは非互換
*
* @version 2.0.0
* @since 2.0.0
* @param separator 区切り文字
* @param limit 配列の数を指定
*/
public split(
separator: RegExp | { toString(): string },
limit?: number
): string[] {
return split(this.$, separator, limit);
}
/**
* 引数に指定された文字列が先頭と合致するか
*
* - サロゲートペアを考慮する
* - String.prototype.startsWith とは非互換
*
* @version 2.0.0
* @since 2.0.0
* @param search 合致対象文字列
* @param position 先頭の位置
*/
public startsWith(
search: { toString(): string },
position: number = 0
): boolean {
return startsWith(this.$, search, position);
}
/**
* 指定した位置から指定した数だけ文字列を抽出
*
* - サロゲートペアを考慮する
* - String.prototype.substr とは非互換
*
* @version 2.0.0
* @since 0.2.0
* @param start 開始インデックス
* @param length 指定数
*/
public substr(start: number, length?: number): Jaco {
return new Jaco(substr(this.$, start, length));
}
/**
* 指定した位置の間の文字列を抽出
*
* - サロゲートペアを考慮する
* - String.prototype.substring とは非互換
*
* @version 2.0.0
* @since 0.2.0
* @param indexA インデックス
* @param indexB インデックス
*/
public substring(indexA: number, indexB: number): Jaco {
return new Jaco(substring(this.$, indexA, indexB));
}
/**
* パターンとマッチするかどうか
*
* @version 2.0.0
* @since 0.2.0
* @param pattern パターン
*/
public test(pattern: RegExp | { toString(): string }): boolean {
return test(this.$, pattern);
}
/**
* 小書き文字を基底文字に変換する
*
* @version 1.1.0
* @since 1.1.0
*/
public toBasicLetter(): Jaco {
return new Jaco(toBasicLetter(this.$));
}
/**
* ひらがなに変換する
*
* 第一引数に true を渡した場合、濁点・半濁点は基本的に結合される
* ヷヸヹヺは文字が存在しないため ひらがな + 結合文字でない濁点・半濁点 となる
*
* @version 0.2.0
* @since 0.1.0
* @param isCombinate 濁点・半濁点を結合文字にするかどうか
*/
public toHiragana(isCombinate: boolean = false): Jaco {
return new Jaco(toHiragana(this.$, isCombinate));
}
/**
* カタカナに変換する
*
* @version 0.2.0
* @since 0.1.0
* @param toWide 半角カタカナを全角カタカナへ変換するかどうか
*/
public toKatakana(toWide: boolean = true): Jaco {
return new Jaco(toKatakana(this.$, toWide));
}
/**
* 英字の大文字を小文字に変換する
*
* @version 0.2.0
* @since 0.2.0
* @return インスタンス自身
*/
public toLowerCase(): Jaco {
return new Jaco(this.$.toLowerCase());
}
/**
* 半角に変換
*
* @version 2.0.0
* @since 0.4.0
*/
public toNarrow(convertJapaneseChars: boolean = false): Jaco {
return new Jaco(toNarrow(this.$, convertJapaneseChars));
}
/**
* 英数字を半角に変換
*
* @version 2.0.0
* @since 1.3.0
*/
public toNarrowAlphanumeric(): Jaco {
return new Jaco(toNarrowAlphanumeric(this.$));
}
/**
* カタカナと日本語で使われる記号を半角に変換
*
* @version 0.4.0
* @since 0.4.0
*/
public toNarrowJapanese(): Jaco {
return new Jaco(toNarrowJapanese(this.$));
}
/**
* 半角カタカナに変換する
*
* @version 0.6.0
* @since 0.1.0
* @param fromHiragana ひらがなも変換する
*/
public toNarrowKatakana(fromHiragana: boolean = false): Jaco {
return new Jaco(toNarrowKatakana(this.$, fromHiragana));
}
/**
* 記号を半角に変換する
*
* @version 2.0.0
* @since 2.0.0
*/
public toNarrowSign(): Jaco {
return new Jaco(toNarrowSign(this.$));
}
/**
* 日本語で使われる記号を半角に変換
*
* @version 2.0.0
* @since 0.4.0
*/
public toNarrowSymbolForJapanese(): Jaco {
return new Jaco(toNarrowSymbolForJapanese(this.$));
}
/**
* 数値に変換する
*
* @version 0.2.0
* @since 0.2.0
* @return 数値
*/
public toNumber(): number {
return parseFloat(this.$);
}
/**
* 数字に変換する
*
* @version 0.5.0
* @since 0.5.0
* @param negative 負の値を許可してマイナスをつけるかどうか
* @param floatingPoint 小数を許可してドットをつけるかどうか
*/
public toNumeric(
negative: boolean = false,
floatingPoint: boolean = false
): Jaco {
return new Jaco(toNumeric(this.$, negative, floatingPoint));
}
/**
* よみの文字に変換する
* JIS X 4061 [日本語文字列照合順番](http://goo.gl/Mw8ja) に準ずる
*
* @version 1.1.0
* @since 1.1.0
*/
public toPhoeticKana(): Jaco {
return new Jaco(toPhoeticKana(this.$));
}
/**
* 明示もしくは暗黙の文字列変換メソッド
*
* @version 0.1.0
* @since 0.1.0
* @return インスタンス自身が保持する文字列
*/
public toString(): string {
return this.$;
}
/**
* 英字の小文字を大文字に変換する
*
* @version 0.2.0
* @since 0.2.0
* @return インスタンス自身
*/
public toUpperCase(): Jaco {
return new Jaco(this.$.toUpperCase());
}
/**
* 全角に変換
*
* @version 0.4.0
* @since 0.4.0
*/
public toWide(): Jaco {
return new Jaco(toWide(this.$));
}
/**
* 英数字を全角に変換
*
* @version 2.0.0
* @since 1.3.0
*/
public toWideAlphanumeric(): Jaco {
return new Jaco(toWideAlphanumeric(this.$));
}
/**
* カタカナと日本語で使われる記号を全角に変換
*
* @version 0.4.0
* @since 0.4.0
*/
public toWideJapanese(): Jaco {
return new Jaco(toWideJapanese(this.$));
}
/**
* 全角カタカナに変換する
*
* @version 0.2.0
* @since 0.1.0
*/
public toWideKatakana(): Jaco {
return new Jaco(toWideKatakana(this.$));
}
/**
* 記号を全角に変換する
*
* @version 2.0.0
* @since 2.0.0
*/
public toWideSign(): Jaco {
return new Jaco(toWideSign(this.$));
}
/**
* 日本語で使われる記号を全角に変換
*
* @version 2.0.0
* @since 0.4.0
*/
public toWideSymbolForJapanese(): Jaco {
return new Jaco(toWideSymbolForJapanese(this.$));
}
/**
* 先頭と末尾の空白を取り除く
*
* @version 2.0.0
* @since 0.2.0
*/
public trim(): Jaco {
return new Jaco(this.$.trim());
}
/**
* 先頭の空白を取り除く
*
* @version 2.0.0
* @since 2.0.0
*/
public trimLeft(): Jaco {
return new Jaco(remove(this.$, /^\s+/));
}
/**
* 末尾の空白を取り除く
*
* @version 2.0.0
* @since 2.0.0
*/
public trimRight(): Jaco {
return new Jaco(remove(this.$, /\s+$/));
}
/**
* 暗黙の値変換に呼び出されるメソッド
*
* @version 0.1.0
* @since 0.1.0
* @return インスタンス自身が保持する文字列
*/
public valueOf(): string {
return this.toString();
}
/**
* イテレータ
*
* 要素の型は `string` ではなく `Jaco`
*
* @version 2.0.0
* @since 2.0.0
* @return イテレータブル `<Jaco>`
*/
public [Symbol.iterator](): Iterator<Jaco> {
let counter = 0;
const iterator: Iterator<Jaco> = {
next: () => {
const count = counter++;
const item: string = arrayize(this.$)[count];
const result: IteratorResult<Jaco> = {
value: new Jaco(item),
done: this.length <= count
};
return result;
}
};
return iterator;
}
} | the_stack |
import {CompositionTypeEnum} from '../../foundation/definitions/CompositionType';
import {ProcessApproach} from '../../foundation/definitions/ProcessApproach';
import {ShaderAttributeOrSemanticsOrString} from '../../foundation/materials/core/AbstractMaterialNode';
import {ShaderSemanticsClass} from '../../foundation/definitions/ShaderSemantics';
import {
VertexAttributeEnum,
VertexAttributeClass,
} from '../../foundation/definitions/VertexAttribute';
import WebGLResourceRepository from '../WebGLResourceRepository';
import {WellKnownComponentTIDs} from '../../foundation/components/WellKnownComponentTIDs';
import SystemState from '../../foundation/system/SystemState';
import MemoryManager from '../../foundation/core/MemoryManager';
export type AttributeNames = Array<string>;
export default abstract class GLSLShader {
static __instance: GLSLShader;
__webglResourceRepository?: WebGLResourceRepository = WebGLResourceRepository.getInstance();
constructor() {}
get glsl_rt0() {
const repo = this.__webglResourceRepository!;
if (repo.currentWebGLContextWrapper!.isWebGL2) {
return 'layout(location = 0) out vec4 rt0;\n';
} else {
return 'vec4 rt0;\n';
}
}
get glsl_fragColor() {
const repo = this.__webglResourceRepository!;
if (
repo.currentWebGLContextWrapper != null &&
repo.currentWebGLContextWrapper!.isWebGL2
) {
return '';
} else {
return 'gl_FragColor = rt0;\n';
}
}
get glsl_vertex_in() {
const repo = this.__webglResourceRepository!;
if (repo.currentWebGLContextWrapper!.isWebGL2) {
return 'in';
} else {
return 'attribute';
}
}
get glsl_fragment_in() {
const repo = this.__webglResourceRepository!;
if (repo.currentWebGLContextWrapper!.isWebGL2) {
return 'in';
} else {
return 'varying';
}
}
get glsl_vertex_out() {
const repo = this.__webglResourceRepository!;
if (repo.currentWebGLContextWrapper!.isWebGL2) {
return 'out';
} else {
return 'varying';
}
}
get glsl_vertex_centroid_out() {
const repo = this.__webglResourceRepository!;
if (repo.currentWebGLContextWrapper!.isWebGL2) {
return 'centroid out';
} else {
return 'varying';
}
}
get glsl_texture() {
const repo = this.__webglResourceRepository!;
if (repo.currentWebGLContextWrapper!.isWebGL2) {
return 'texture';
} else {
return 'texture2D';
}
}
get glsl_textureCube() {
const repo = this.__webglResourceRepository!;
if (repo.currentWebGLContextWrapper!.isWebGL2) {
return 'texture';
} else {
return 'textureCube';
}
}
get glsl_textureProj() {
const repo = this.__webglResourceRepository!;
if (repo.currentWebGLContextWrapper!.isWebGL2) {
return 'textureProj';
} else {
return 'texture2DProj';
}
}
get glsl_versionText() {
const repo = this.__webglResourceRepository!;
if (
repo.currentWebGLContextWrapper != null &&
repo.currentWebGLContextWrapper!.isWebGL2
) {
return '';
// return '#version 300 es\n'
} else {
return '';
}
}
get glslPrecision() {
return `precision highp float;
precision highp int;
`;
}
static get glslMainBegin() {
return `
void main() {
`;
}
static get glslMainEnd() {
return `
}
`;
}
getGlslVertexShaderProperies(str = '') {
return str;
}
get glsl1ShaderTextureLodExt() {
const ext = WebGLResourceRepository.getInstance()
.currentWebGLContextWrapper!.webgl1ExtSTL;
return ext != null ? '#extension GL_EXT_shader_texture_lod : require' : '';
}
get glsl1ShaderDerivativeExt() {
const ext = WebGLResourceRepository.getInstance()
.currentWebGLContextWrapper!.webgl1ExtDRV;
return ext != null
? '#extension GL_OES_standard_derivatives : require'
: '';
}
get toNormalMatrix() {
return `
mat3 toNormalMatrix(mat4 m) {
float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],
a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],
a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],
a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
float b00 = a00 * a11 - a01 * a10,
b01 = a00 * a12 - a02 * a10,
b02 = a00 * a13 - a03 * a10,
b03 = a01 * a12 - a02 * a11,
b04 = a01 * a13 - a03 * a11,
b05 = a02 * a13 - a03 * a12,
b06 = a20 * a31 - a21 * a30,
b07 = a20 * a32 - a22 * a30,
b08 = a20 * a33 - a23 * a30,
b09 = a21 * a32 - a22 * a31,
b10 = a21 * a33 - a23 * a31,
b11 = a22 * a33 - a23 * a32;
float determinantVal = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
return mat3(
a11 * b11 - a12 * b10 + a13 * b09, a12 * b08 - a10 * b11 - a13 * b07, a10 * b10 - a11 * b08 + a13 * b06,
a02 * b10 - a01 * b11 - a03 * b09, a00 * b11 - a02 * b08 + a03 * b07, a01 * b08 - a00 * b10 - a03 * b06,
a31 * b05 - a32 * b04 + a33 * b03, a32 * b02 - a30 * b05 - a33 * b01, a30 * b04 - a31 * b02 + a33 * b00) / determinantVal;
}`;
}
get getSkinMatrix() {
return `
#ifdef RN_IS_SKINNING
highp mat4 createMatrixFromQuaternionTranslationScale( highp vec4 quaternion, highp vec3 translation, highp vec3 scale ) {
highp vec4 q = quaternion;
highp vec3 t = translation;
highp float sx = q.x * q.x;
highp float sy = q.y * q.y;
highp float sz = q.z * q.z;
highp float cx = q.y * q.z;
highp float cy = q.x * q.z;
highp float cz = q.x * q.y;
highp float wx = q.w * q.x;
highp float wy = q.w * q.y;
highp float wz = q.w * q.z;
highp mat4 mat = mat4(
1.0 - 2.0 * (sy + sz), 2.0 * (cz + wz), 2.0 * (cy - wy), 0.0,
2.0 * (cz - wz), 1.0 - 2.0 * (sx + sz), 2.0 * (cx + wx), 0.0,
2.0 * (cy + wy), 2.0 * (cx - wx), 1.0 - 2.0 * (sx + sy), 0.0,
t.x, t.y, t.z, 1.0
);
highp mat4 uniformScaleMat = mat4(
scale.x, 0.0, 0.0, 0.0,
0.0, scale.y, 0.0, 0.0,
0.0, 0.0, scale.z, 0.0,
0.0, 0.0, 0.0, 1.0
);
return mat*uniformScaleMat;
}
highp vec4 unpackedVec2ToNormalizedVec4(highp vec2 vec_xy, highp float criteria){
highp float r;
highp float g;
highp float b;
highp float a;
highp float ix = floor(vec_xy.x * criteria);
highp float v1x = ix / criteria;
highp float v1y = ix - floor(v1x) * criteria;
r = ( v1x + 1.0 ) / (criteria-1.0);
g = ( v1y + 1.0 ) / (criteria-1.0);
highp float iy = floor( vec_xy.y * criteria);
highp float v2x = iy / criteria;
highp float v2y = iy - floor(v2x) * criteria;
b = ( v2x + 1.0 ) / (criteria-1.0);
a = ( v2y + 1.0 ) / (criteria-1.0);
r -= 1.0/criteria;
g -= 1.0/criteria;
b -= 1.0/criteria;
a -= 1.0/criteria;
r = r*2.0-1.0;
g = g*2.0-1.0;
b = b*2.0-1.0;
a = a*2.0-1.0;
return vec4(r, g, b, a);
}
mat4 getSkinMatrix(float skeletalComponentSID) {
#ifdef RN_BONE_DATA_TYPE_Mat44x1
mat4 skinMat = a_weight.x * get_boneMatrix(skeletalComponentSID, int(a_joint.x));
skinMat += a_weight.y * get_boneMatrix(skeletalComponentSID, int(a_joint.y));
skinMat += a_weight.z * get_boneMatrix(skeletalComponentSID, int(a_joint.z));
skinMat += a_weight.w * get_boneMatrix(skeletalComponentSID, int(a_joint.w));
#elif defined(RN_BONE_DATA_TYPE_VEC4X2)
vec2 criteria = vec2(4096.0, 4096.0);
vec4 tq_x = get_boneTranslatePackedQuat(skeletalComponentSID, int(a_joint.x));
vec4 sq_x = get_boneScalePackedQuat(skeletalComponentSID, int(a_joint.x));
vec4 quat = unpackedVec2ToNormalizedVec4(vec2(tq_x.w, sq_x.w), criteria.x);
mat4 skinMat = a_weight.x * createMatrixFromQuaternionTranslationScale(quat, tq_x.xyz, sq_x.xyz);
vec4 tq_y = get_boneTranslatePackedQuat(skeletalComponentSID, int(a_joint.y));
vec4 sq_y = get_boneScalePackedQuat(skeletalComponentSID, int(a_joint.y));
quat = unpackedVec2ToNormalizedVec4(vec2(tq_y.w, sq_y.w), criteria.x);
skinMat += a_weight.y * createMatrixFromQuaternionTranslationScale(quat, tq_y.xyz, sq_y.xyz);
vec4 tq_z = get_boneTranslatePackedQuat(skeletalComponentSID, int(a_joint.z));
vec4 sq_z = get_boneScalePackedQuat(skeletalComponentSID, int(a_joint.z));
quat = unpackedVec2ToNormalizedVec4(vec2(tq_z.w, sq_z.w), criteria.x);
skinMat += a_weight.z * createMatrixFromQuaternionTranslationScale(quat, tq_z.xyz, sq_z.xyz);
vec4 tq_w = get_boneTranslatePackedQuat(skeletalComponentSID, int(a_joint.w));
vec4 sq_w = get_boneScalePackedQuat(skeletalComponentSID, int(a_joint.w));
quat = unpackedVec2ToNormalizedVec4(vec2(tq_w.w, sq_w.w), criteria.x);
skinMat += a_weight.w * createMatrixFromQuaternionTranslationScale(quat, tq_w.xyz, sq_w.xyz);
#elif defined(RN_BONE_DATA_TYPE_VEC4X2_OLD)
vec4 ts_x = get_boneTranslateScale(skeletalComponentSID, int(a_joint.x));
mat4 skinMat = a_weight.x * createMatrixFromQuaternionTranslationScale(
get_boneQuaternion(skeletalComponentSID, int(a_joint.x)), ts_x.xyz, vec3(ts_x.w));
vec4 ts_y = get_boneTranslateScale(skeletalComponentSID, int(a_joint.y));
skinMat += a_weight.y * createMatrixFromQuaternionTranslationScale(
get_boneQuaternion(skeletalComponentSID, int(a_joint.y)), ts_y.xyz, vec3(ts_y.w));
vec4 ts_z = get_boneTranslateScale(skeletalComponentSID, int(a_joint.z));
skinMat += a_weight.z * createMatrixFromQuaternionTranslationScale(
get_boneQuaternion(skeletalComponentSID, int(a_joint.z)), ts_z.xyz, vec3(ts_z.w));
vec4 ts_w = get_boneTranslateScale(skeletalComponentSID, int(a_joint.w));
skinMat += a_weight.w * createMatrixFromQuaternionTranslationScale(
get_boneQuaternion(skeletalComponentSID, int(a_joint.w)), ts_w.xyz, vec3(ts_w.w));
#elif defined(RN_BONE_DATA_TYPE_VEC4X1)
vec4 boneCompressedChunksX = get_boneCompressedChunk(skeletalComponentSID, int(a_joint.x));
vec4 boneCompressedChunksY = get_boneCompressedChunk(skeletalComponentSID, int(a_joint.y));
vec4 boneCompressedChunksZ = get_boneCompressedChunk(skeletalComponentSID, int(a_joint.z));
vec4 boneCompressedChunksW = get_boneCompressedChunk(skeletalComponentSID, int(a_joint.w));
vec2 criteria = vec2(4096.0, 4096.0);
vec4 boneCompressedInfo = get_boneCompressedInfo(0.0, 0);
vec4 ts_x = unpackedVec2ToNormalizedVec4(boneCompressedChunksX.zw, criteria.y)*boneCompressedInfo;
mat4 skinMat = a_weight.x * createMatrixFromQuaternionTranslationScale(
unpackedVec2ToNormalizedVec4(boneCompressedChunksX.xy, criteria.x), ts_x.xyz, vec3(ts_x.w));
vec4 ts_y = unpackedVec2ToNormalizedVec4(boneCompressedChunksY.zw, criteria.y)*boneCompressedInfo;
skinMat += a_weight.y * createMatrixFromQuaternionTranslationScale(
unpackedVec2ToNormalizedVec4(boneCompressedChunksY.xy, criteria.x), ts_y.xyz, vec3(ts_y.w));
vec4 ts_z = unpackedVec2ToNormalizedVec4(boneCompressedChunksZ.zw, criteria.y)*boneCompressedInfo;
skinMat += a_weight.z * createMatrixFromQuaternionTranslationScale(
unpackedVec2ToNormalizedVec4(boneCompressedChunksZ.xy, criteria.x), ts_z.xyz, vec3(ts_z.w));
vec4 ts_w = unpackedVec2ToNormalizedVec4(boneCompressedChunksW.zw, criteria.y)*boneCompressedInfo;
skinMat += a_weight.w * createMatrixFromQuaternionTranslationScale(
unpackedVec2ToNormalizedVec4(boneCompressedChunksW.xy, criteria.x), ts_w.xyz, vec3(ts_w.w));
#endif
return skinMat;
}
#endif
`;
}
get packing() {
return `
const vec4 bitEnc = vec4(1.,255.,65025.,16581375.);
const vec4 bitDec = 1./bitEnc;
vec4 encodeFloatRGBA(float v) {
float val = v;
float r = mod(val, 255.0);
val -= r;
float g = mod(val, 65025.0);
val -= g;
float b = mod(val, 16581375.0);
return vec4(r/255.0, g/65025.0, b/16581375.0, 1.0);
}`;
}
get processGeometryWithSkinningOptionally() {
return `
#ifdef RN_IS_SKINNING
bool skinning(
float skeletalComponentSID,
in mat3 inNormalMatrix,
out mat3 outNormalMatrix,
in vec3 inPosition_inLocal,
out vec4 outPosition_inWorld,
in vec3 inNormal_inLocal,
out vec3 outNormal_inWorld
)
{
mat4 skinMat = getSkinMatrix(skeletalComponentSID);
outPosition_inWorld = skinMat * vec4(inPosition_inLocal, 1.0);
outNormalMatrix = toNormalMatrix(skinMat);
outNormal_inWorld = normalize(outNormalMatrix * inNormal_inLocal);
return true;
}
#endif
bool processGeometryWithMorphingAndSkinning(
float skeletalComponentSID,
in mat4 worldMatrix,
in mat3 inNormalMatrix,
out mat3 outNormalMatrix,
in vec3 inPosition_inLocal,
out vec4 outPosition_inWorld,
in vec3 inNormal_inLocal,
out vec3 outNormal_inWorld
) {
bool isSkinning = false;
vec3 position_inLocal;
#ifdef RN_IS_MORPHING
if (u_morphTargetNumber == 0) {
#endif
position_inLocal = inPosition_inLocal;
#ifdef RN_IS_MORPHING
} else {
float vertexIdx = a_baryCentricCoord.w;
position_inLocal = get_position(vertexIdx, inPosition_inLocal);
}
#endif
#ifdef RN_IS_SKINNING
if (skeletalComponentSID >= 0.0) {
isSkinning = skinning(skeletalComponentSID, inNormalMatrix, outNormalMatrix, position_inLocal, outPosition_inWorld, inNormal_inLocal, outNormal_inWorld);
} else {
#endif
outNormalMatrix = inNormalMatrix;
outPosition_inWorld = worldMatrix * vec4(position_inLocal, 1.0);
outNormal_inWorld = normalize(inNormalMatrix * inNormal_inLocal);
#ifdef RN_IS_SKINNING
}
#endif
return isSkinning;
}`;
}
get prerequisites() {
const webGLResourceRepository = WebGLResourceRepository.getInstance();
const dataUboDefinition = webGLResourceRepository.getGlslDataUBODefinitionString();
const dataUBOVec4SizeStr = webGLResourceRepository.getGlslDataUBOVec4SizeString();
return `uniform float u_materialSID;
uniform sampler2D u_dataTexture;
const int widthOfDataTexture = ${MemoryManager.bufferWidthLength};
const int heightOfDataTexture = ${MemoryManager.bufferHeightLength};
#if defined(GLSL_ES3) && defined(RN_IS_FASTEST_MODE) && defined(RN_IS_UBO_ENABLED)
${dataUBOVec4SizeStr}
${dataUboDefinition}
#endif
highp vec4 fetchElement(highp sampler2D tex, int vec4_idx, int texWidth, int texHeight) {
#if defined(GLSL_ES3) && defined(RN_IS_FASTEST_MODE) && defined(RN_IS_UBO_ENABLED)
if (vec4_idx < dataUBOVec4Size) {
return fetchVec4FromVec4Block(vec4_idx);
} else {
int idxOnDataTex = vec4_idx - dataUBOVec4Size;
highp ivec2 uv = ivec2(idxOnDataTex % texWidth, idxOnDataTex / texWidth);
return texelFetch( tex, uv, 0 );
}
#elif defined(GLSL_ES3)
highp ivec2 uv = ivec2(vec4_idx % texWidth, vec4_idx / texWidth);
return texelFetch( tex, uv, 0 );
#else
// This idea from https://qiita.com/YVT/items/c695ab4b3cf7faa93885
highp vec2 invSize = vec2(1.0/float(texWidth), 1.0/float(texHeight));
highp float t = (float(vec4_idx) + 0.5) * invSize.x;
highp float x = fract(t);
highp float y = (floor(t) + 0.5) * invSize.y;
#ifdef GLSL_ES3
return texture( tex, vec2(x, y));
#else
return texture2D( tex, vec2(x, y));
#endif
#endif
}
vec2 fetchVec2No16BytesAligned(highp sampler2D tex, int scalar_idx, int texWidth, int texHeight) {
#ifdef GLSL_ES3
int posIn4bytes = scalar_idx % 4;
#else
int posIn4bytes = int(mod(float(scalar_idx), 4.0));
#endif
int basePosIn16bytes = scalar_idx*4 - posIn4bytes;
if (posIn4bytes == 0) {
vec4 val = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
return val.xy;
} else if (posIn4bytes == 1) {
vec4 val0 = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
return vec2(val0.yz);
} else if (posIn4bytes == 2) {
vec4 val0 = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
vec4 val1 = fetchElement(u_dataTexture, basePosIn16bytes+1, texWidth, texHeight);
return vec2(val0.zw);
} else if (posIn4bytes == 3) {
vec4 val0 = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
vec4 val1 = fetchElement(u_dataTexture, basePosIn16bytes+1, texWidth, texHeight);
return vec2(val0.w, val1.x);
}
}
vec3 fetchVec3No16BytesAligned(highp sampler2D tex, int scalar_idx, int texWidth, int texHeight) {
#ifdef GLSL_ES3
int posIn4bytes = scalar_idx % 4;
#else
int posIn4bytes = int(mod(float(scalar_idx), 4.0));
#endif
int basePosIn16bytes = scalar_idx*4 - posIn4bytes;
if (posIn4bytes == 0) {
vec4 val = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
return val.xyz;
} else if (posIn4bytes == 1) {
vec4 val0 = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
return vec3(val0.yzw);
} else if (posIn4bytes == 2) {
vec4 val0 = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
vec4 val1 = fetchElement(u_dataTexture, basePosIn16bytes+1, texWidth, texHeight);
return vec3(val0.zw, val1.x);
} else if (posIn4bytes == 3) {
vec4 val0 = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
vec4 val1 = fetchElement(u_dataTexture, basePosIn16bytes+1, texWidth, texHeight);
return vec3(val0.w, val1.xy);
}
}
vec4 fetchVec4(highp sampler2D tex, int vec4_idx, int texWidth, int texHeight) {
return fetchElement(u_dataTexture, vec4_idx, texWidth, texHeight);
}
float fetchScalarNo16BytesAligned(highp sampler2D tex, int scalar_idx, int texWidth, int texHeight) {
vec4 val = fetchElement(u_dataTexture, scalar_idx, texWidth, texHeight);
return val.x;
}
mat2 fetchMat2No16BytesAligned(highp sampler2D tex, int scalar_idx, int texWidth, int texHeight) {
int vec4_idx = scalar_idx*4;
vec4 col0 = fetchElement(u_dataTexture, vec4_idx, texWidth, texHeight);
mat2 val = mat2(
col0.x, col0.y,
col0.z, col0.w
);
return val;
}
mat2 fetchMat2(highp sampler2D tex, int vec4_idx, int texWidth, int texHeight) {
vec4 col0 = fetchElement(u_dataTexture, vec4_idx, texWidth, texHeight);
mat2 val = mat2(
col0.x, col0.y,
col0.z, col0.w
);
return val;
}
mat3 fetchMat3No16BytesAligned(highp sampler2D tex, int scalar_idx, int texWidth, int texHeight) {
#ifdef GLSL_ES3
int posIn4bytes = scalar_idx % 4;
#else
int posIn4bytes = int(mod(float(scalar_idx), 4.0));
#endif
int basePosIn16bytes = scalar_idx*4 - posIn4bytes;
if (posIn4bytes == 0) {
vec4 col0 = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
vec4 col1 = fetchElement(u_dataTexture, basePosIn16bytes + 1, texWidth, texHeight);
vec4 col2 = fetchElement(u_dataTexture, basePosIn16bytes + 2, texWidth, texHeight);
mat3 val = mat3(
col0.x, col0.y, col0.z,
col0.w, col1.x, col1.y,
col1.z, col1.w, col2.x
);
return val;
} else if (posIn4bytes == 1) {
vec4 col0 = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
vec4 col1 = fetchElement(u_dataTexture, basePosIn16bytes + 1, texWidth, texHeight);
vec4 col2 = fetchElement(u_dataTexture, basePosIn16bytes + 2, texWidth, texHeight);
mat3 val = mat3(
col0.y, col0.z, col0.w,
col1.x, col1.y, col1.z,
col1.w, col2.x, col2.y
);
return val;
} else if (posIn4bytes == 2) {
vec4 col0 = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
vec4 col1 = fetchElement(u_dataTexture, basePosIn16bytes + 1, texWidth, texHeight);
vec4 col2 = fetchElement(u_dataTexture, basePosIn16bytes + 2, texWidth, texHeight);
mat3 val = mat3(
col0.z, col0.w, col1.x,
col1.y, col1.z, col1.w,
col2.x, col2.y, col2.z
);
return val;
} else { // posIn4bytes == 3
vec4 col0 = fetchElement(u_dataTexture, basePosIn16bytes, texWidth, texHeight);
vec4 col1 = fetchElement(u_dataTexture, basePosIn16bytes + 1, texWidth, texHeight);
vec4 col2 = fetchElement(u_dataTexture, basePosIn16bytes + 2, texWidth, texHeight);
mat3 val = mat3(
col0.w, col1.x, col1.y,
col1.z, col1.w, col2.x,
col2.y, col2.z, col2.w
);
return val;
}
}
mat3 fetchMat3(highp sampler2D tex, int vec4_idx, int texWidth, int texHeight) {
vec4 col0 = fetchElement(u_dataTexture, vec4_idx, texWidth, texHeight);
vec4 col1 = fetchElement(u_dataTexture, vec4_idx + 1, texWidth, texHeight);
vec4 col2 = fetchElement(u_dataTexture, vec4_idx + 2, texWidth, texHeight);
mat3 val = mat3(
col0.x, col0.y, col0.z,
col0.w, col1.x, col1.y,
col1.z, col1.w, col2.x
);
return val;
}
mat4 fetchMat4(highp sampler2D tex, int vec4_idx, int texWidth, int texHeight) {
vec4 col0 = fetchElement(u_dataTexture, vec4_idx, texWidth, texHeight);
vec4 col1 = fetchElement(u_dataTexture, vec4_idx + 1, texWidth, texHeight);
vec4 col2 = fetchElement(u_dataTexture, vec4_idx + 2, texWidth, texHeight);
vec4 col3 = fetchElement(u_dataTexture, vec4_idx + 3, texWidth, texHeight);
mat4 val = mat4(
col0.x, col0.y, col0.z, col0.w,
col1.x, col1.y, col1.z, col1.w,
col2.x, col2.y, col2.z, col2.w,
col3.x, col3.y, col3.z, col3.w
);
return val;
}
float rand(const vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
vec3 descramble(vec3 v) {
float seed = 0.0;
v.x -= sin(fract(v.y*20.0));
v.z -= cos(fract(-v.y*10.0));
return v;
}
`;
}
get mainPrerequisites() {
const processApproach = SystemState.currentProcessApproach;
if (ProcessApproach.isFastestApproach(processApproach)) {
return `
float materialSID = u_currentComponentSIDs[0]; // index 0 data is the materialSID
int lightNumber = 0;
#ifdef RN_IS_LIGHTING
lightNumber = int(u_currentComponentSIDs[${WellKnownComponentTIDs.LightComponentTID}]);
#endif
float skeletalComponentSID = -1.0;
#ifdef RN_IS_SKINNING
skeletalComponentSID = u_currentComponentSIDs[${WellKnownComponentTIDs.SkeletalComponentTID}];
#endif
`;
} else {
return `
float materialSID = u_materialSID;
int lightNumber = 0;
#ifdef RN_IS_LIGHTING
lightNumber = get_lightNumber(0.0, 0);
#endif
float skeletalComponentSID = -1.0;
#ifdef RN_IS_SKINNING
skeletalComponentSID = float(get_skinningMode(0.0, 0));
#endif
`;
}
}
get pointSprite() {
return ` vec4 position_inWorld = worldMatrix * vec4(a_position, 1.0);
vec3 viewPosition = get_viewPosition(cameraSID, 0);
float distanceFromCamera = length(position_inWorld.xyz - viewPosition);
vec3 pointDistanceAttenuation = get_pointDistanceAttenuation(materialSID, 0);
float distanceAttenuationFactor = sqrt(1.0/(pointDistanceAttenuation.x + pointDistanceAttenuation.y * distanceFromCamera + pointDistanceAttenuation.z * distanceFromCamera * distanceFromCamera));
float maxPointSize = get_pointSize(materialSID, 0);
gl_PointSize = clamp(distanceAttenuationFactor * maxPointSize, 0.0, maxPointSize);`;
}
get pbrUniformDefinition() {
let shaderText = '';
shaderText += 'uniform vec2 uMetallicRoughnessFactors;\n';
shaderText += 'uniform vec3 uBaseColorFactor;\n';
shaderText += 'uniform vec2 uOcclusionFactors;';
shaderText += 'uniform vec3 uEmissiveFactor;';
shaderText += 'uniform sampler2D uMetallicRoughnessTexture;\n';
const occlusionTexture = true; //material.getTextureFromPurpose(GLBoost.TEXTURE_PURPOSE_OCCLUSION);
if (occlusionTexture) {
shaderText += 'uniform sampler2D uOcclusionTexture;\n';
}
const emissiveTexture = true; //material.getTextureFromPurpose(GLBoost.TEXTURE_PURPOSE_EMISSIVE);
if (emissiveTexture) {
shaderText += 'uniform sampler2D uEmissiveTexture;\n';
}
const diffuseEnvCubeTexture = true; //material.getTextureFromPurpose(GLBoost.TEXTURE_PURPOSE_IBL_DIFFUSE_ENV_CUBE);
if (diffuseEnvCubeTexture) {
shaderText += 'uniform sampler2D u_brdfLutTexture;\n';
shaderText += 'uniform samplerCube uDiffuseEnvTexture;\n';
shaderText += 'uniform samplerCube uSpecularEnvTexture;\n';
shaderText += 'uniform vec4 uIBLParameters;\n'; // Ka * amount of ambient lights
}
shaderText += 'uniform vec4 ambient;\n'; // Ka * amount of ambient lights
return shaderText;
}
get mipmapLevel() {
return `
// https://stackoverflow.com/questions/24388346/how-to-access-automatic-mipmap-level-in-glsl-fragment-shader-texture
float mipmapLevel(vec3 uv_as_texel)
{
vec3 dx_vtc = dFdx(uv_as_texel);
vec3 dy_vtc = dFdy(uv_as_texel);
float delta_max_sqr = max(dot(dx_vtc, dx_vtc), dot(dy_vtc, dy_vtc));
float mml = 0.5 * log2(delta_max_sqr);
return max( 0.0, mml );
}`;
}
get pbrMethodDefinition() {
return `
const float M_PI = 3.141592653589793;
const float c_MinRoughness = 0.04;
float angular_n_h(float NH) {
return acos(NH);
}
float sqr(float x) {
return x*x;
}
float d_phong(float NH, float c1) {
return pow(
cos(acos(NH))
, c1
);
}
// this is from https://www.unrealengine.com/blog/physically-based-shading-on-mobile
vec3 envBRDFApprox( vec3 F0, float Roughness, float NoV ) {
const vec4 c0 = vec4(-1, -0.0275, -0.572, 0.022 );
const vec4 c1 = vec4(1, 0.0425, 1.04, -0.04 );
vec4 r = Roughness * c0 + c1;
float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;
vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;
return F0 * AB.x + AB.y;
}
// GGX NDF
float d_ggx(float NH, float alphaRoughness) {
float roughnessSqr = alphaRoughness * alphaRoughness;
float f = (roughnessSqr - 1.0) * NH * NH + 1.0;
return roughnessSqr / (M_PI * f * f);
}
float d_torrance_reiz(float NH, float c3) {
float CosSquared = NH*NH;
float TanSquared = (1.0 - CosSquared)/CosSquared;
//return (1.0/M_PI) * sqr(c3/(CosSquared * (c3*c3 + TanSquared))); // gamma = 2, aka GGX
return (1.0/sqrt(M_PI)) * (sqr(c3)/(CosSquared * (c3*c3 + TanSquared))); // gamma = 1, D_Berry
}
float d_beckmann(float NH, float m) {
float co = 1.0 / (4.0 * m * m * NH * NH * NH * NH);
float expx = exp((NH * NH - 1.0) / (m * m * NH * NH));
return co * expx;
}
// the same as glTF WebGL sample
// https://github.com/KhronosGroup/glTF-WebGL-PBR/blob/88eda8c5358efe03128b72b6c5f5f6e5b6d023e1/shaders/pbr-frag.glsl#L188
// That is, Unreal Engine based approach, but modified to use alphaRoughness (squared artist's roughness parameter),
// and based on 'Separable Masking and Shadowing' approximation (propesed by Christophe Schlick)
// https://www.cs.virginia.edu/~jdl/bib/appearance/analytic%20models/schlick94b.pdf
float g_shielding(float NL, float NV, float alphaRoughness) {
float r = alphaRoughness;
// Local Shadowing using "Schlick-Smith" Masking Function
float localShadowing = 2.0 * NL / (NL + sqrt(r * r + (1.0 - r * r) * (NL * NL)));
// Local Masking using "Schlick-Smith" Masking Function
float localMasking = 2.0 * NV / (NV + sqrt(r * r + (1.0 - r * r) * (NV * NV)));
return localShadowing * localMasking;
}
// The code from https://google.github.io/filament/Filament.html#listing_approximatedspecularv
// The idea is from [Heitz14] Eric Heitz. 2014. Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs.
float v_SmithGGXCorrelated(float NL, float NV, float alphaRoughness) {
float a2 = alphaRoughness * alphaRoughness;
float GGXV = NL * sqrt(NV * NV * (1.0 - a2) + a2);
float GGXL = NV * sqrt(NL * NL * (1.0 - a2) + a2);
return 0.5 / (GGXV + GGXL);
}
float v_SmithGGXCorrelatedFast(float NL, float NV, float alphaRoughness) {
float a = alphaRoughness;
float GGXV = NL * (NV * (1.0 - a) + a);
float GGXL = NV * (NL * (1.0 - a) + a);
return 0.5 / (GGXV + GGXL);
}
// The Schlick Approximation to Fresnel
vec3 fresnel(vec3 f0, float VH) {
return vec3(f0) + (vec3(1.0) - f0) * pow(1.0 - VH, 5.0);
}
vec3 cook_torrance_specular_brdf(float NH, float NL, float NV, vec3 F, float alphaRoughness) {
float D = d_ggx(NH, alphaRoughness);
float V = v_SmithGGXCorrelated(NL, NV, alphaRoughness);
return vec3(D)*vec3(V)*F;
// float G = g_shielding(NL, NV, alphaRoughness);
// return vec3(D)*vec3(G)*F/vec3(4.0*NL*NV);
}
vec3 diffuse_brdf(vec3 albedo)
{
return albedo / M_PI;
}
vec3 srgbToLinear(vec3 srgbColor) {
return pow(srgbColor, vec3(2.2));
}
float srgbToLinear(float value) {
return pow(value, 2.2);
}
vec3 linearToSrgb(vec3 linearColor) {
return pow(linearColor, vec3(1.0/2.2));
}
float linearToSrgb(float value) {
return pow(value, 1.0/2.2);
}
vec3 fresnelSchlickRoughness(vec3 F0, float cosTheta, float roughness)
{
return F0 + (max(vec3(1.0 - roughness), F0) - F0) * pow(1.0 - cosTheta, 5.0);
}
vec3 normalBlendingUDN(sampler2D baseMap, sampler2D detailMap, vec2 baseUv, vec2 detailUv) {
vec3 t = ${this.glsl_texture}(baseMap, baseUv).xyz * 2.0 - 1.0;
vec3 u = ${this.glsl_texture}(detailMap, detailUv).xyz * 2.0 - 1.0;
vec3 r = normalize(vec3(t.xy + u.xy, t.z));
return r;
}
vec2 uvTransform(vec2 scale, vec2 offset, float rotation, vec2 uv) {
mat3 translationMat = mat3(1,0,0, 0,1,0, offset.x, offset.y, 1);
mat3 rotationMat = mat3(
cos(rotation), -sin(rotation), 0,
sin(rotation), cos(rotation), 0,
0, 0, 1
);
mat3 scaleMat = mat3(scale.x,0,0, 0,scale.y,0, 0,0,1);
mat3 matrix = translationMat * rotationMat * scaleMat;
vec2 uvTransformed = ( matrix * vec3(uv.xy, 1) ).xy;
return uvTransformed;
}
`;
}
get hash() {
return `
vec2 hash(vec2 p) {
return fract(sin(p * mat2(127.1, 311.7, 269.5, 183.3))*43758.5453123);
}
`;
}
get returnToOriginalColorSpace() {
return `
// Decorrelated color space vectors and origin
uniform vec3 u_colorSpaceVector1;
uniform vec3 u_colorSpaceVector2;
uniform vec3 u_colorSpaceVector3;
uniform vec3 u_colorSpaceOrigin;
vec3 ReturnToOriginalColorSpace(vec3 color)
{
vec3 result =
u_colorSpaceOrigin +
u_colorSpaceVector1 * color.r +
u_colorSpaceVector2 * color.g +
u_colorSpaceVector3 * color.b;
return result;
}`;
}
get triangleGrid() {
return `
void TriangleGrid(vec2 uv,
out float w1, out float w2, out float w3,
out ivec2 vertex1, out ivec2 vertex2, out ivec2 vertex3)
{
// Scaling of the input
uv *= 3.464; // 2 * sqrt(3)
// Skew input space into simplex triangle grid
const mat2 gridToSkewedGrid = mat2(1.0, 0.0, -0.57735027, 1.15470054);
vec2 skewedCoord = gridToSkewedGrid * uv;
// Compute local triangle vertex IDs and local barycentric coordinates
ivec2 baseId = ivec2(floor(skewedCoord));
vec3 temp = vec3(fract(skewedCoord), 0);
temp.z = 1.0 - temp.x - temp.y;
if (temp.z > 0.0)
{
w1 = temp.z;
w2 = temp.y;
w3 = temp.x;
vertex1 = baseId;
vertex2 = baseId + ivec2(0, 1);
vertex3 = baseId + ivec2(1, 0);
}
else
{
w1 = -temp.z;
w2 = 1.0 - temp.y;
w3 = 1.0 - temp.x;
vertex1 = baseId + ivec2(1, 1);
vertex2 = baseId + ivec2(1, 0);
vertex3 = baseId + ivec2(0, 1);
}
}`;
}
get mipmap_level() {
return `
// https://stackoverflow.com/questions/24388346/how-to-access-automatic-mipmap-level-in-glsl-fragment-shader-texture
float mipmapLevel(in vec2 uv_as_texel)
{
vec2 dx_vtc = dFdx(uv_as_texel);
vec2 dy_vtc = dFdy(uv_as_texel);
float delta_max_sqr = max(dot(dx_vtc, dx_vtc), dot(dy_vtc, dy_vtc));
float mml = 0.5 * log2(delta_max_sqr);
return max( 0, mml );
}
`;
}
// These codes are from https://eheitzresearch.wordpress.com/738-2/
// "Procedural Stochastic Textures by Tiling and Blending"
// Thanks to the authors for permission to use.
// A little modified to work on WebGL 1
byExampleProceduralNoise() {
return `
uniform sampler2D u_Tinput; // Gaussian input T(I)
uniform sampler2D u_invT; // Inverse histogram transformation T^{-1}
// By-Example procedural noise at uv
vec3 byExampleProceduralNoise(vec2 uv, vec2 textureSizeOfTinput, vec2 textureSizeOfInvT)
{
// Get triangle info
float w1, w2, w3;
ivec2 vertex1, vertex2, vertex3;
TriangleGrid(uv, w1, w2, w3, vertex1, vertex2, vertex3);
// Assign random offset to each triangle vertex
vec2 uv1 = uv + hash(vertex1);
vec2 uv2 = uv + hash(vertex2);
vec2 uv3 = uv + hash(vertex3);
// Precompute UV derivatives
vec2 duvdx = dFdx(uv);
vec2 duvdy = dFdy(uv);
// Fetch Gaussian input
vec3 G1 = textureGrad(u_Tinput, uv1, duvdx, duvdy).rgb;
vec3 G2 = textureGrad(u_Tinput, uv2, duvdx, duvdy).rgb;
vec3 G3 = textureGrad(u_Tinput, uv3, duvdx, duvdy).rgb;
// Variance-preserving blending
vec3 G = w1*G1 + w2*G2 + w3*G3;
G = G - vec3(0.5);
G = G * inversesqrt(w1*w1 + w2*w2 + w3*w3);
G = G + vec3(0.5);
// Compute LOD level to fetch the prefiltered look-up table invT
float LOD = mipmapLevel(uv * textureSizeOfTinput).y / textureSizeOfInvT.y);
// Fetch prefiltered LUT (T^{-1})
vec3 color;
color.r = texture(u_invT, vec2(G.r, LOD)).r;
color.g = texture(u_invT, vec2(G.g, LOD)).g;
color.b = texture(u_invT, vec2(G.b, LOD)).b;
// Original color space
color = returnToOriginalColorSpace(color);
return color;
}`;
}
get texture2DSeamless() {
return `
vec4 texture2DSeamless(vec2 uv, vec4 scaleTranslate) {
color = vec4(byExampleProceduralNoise(uv * scaleTranslate.xy + scaleTranslate.zw), 1);
}
`;
}
get simpleMVPPosition() {
return `
float cameraSID = u_currentComponentSIDs[${WellKnownComponentTIDs.CameraComponentTID}];
mat4 worldMatrix = get_worldMatrix(a_instanceID);
mat4 viewMatrix = get_viewMatrix(cameraSID, 0);
mat4 projectionMatrix = get_projectionMatrix(cameraSID, 0);
gl_Position = projectionMatrix * viewMatrix * worldMatrix * vec4(a_position, 1.0);
`;
}
get perturbedNormal() {
return `
#ifdef RN_USE_TANGENT_ATTRIBUTE
vec3 perturb_normal(vec3 normal_inWorld, vec3 viewVector, vec2 texcoord) {
vec3 tangent_inWorld = normalize(v_tangent_inWorld);
vec3 binormal_inWorld = normalize(v_binormal_inWorld);
mat3 tbnMat_tangent_to_world = mat3(tangent_inWorld, binormal_inWorld, normal_inWorld);
vec3 normal = ${this.glsl_texture}(u_normalTexture, texcoord).xyz * 2.0 - 1.0;
return normalize(tbnMat_tangent_to_world * normal);
}
#else
#ifdef RN_IS_SUPPORTING_STANDARD_DERIVATIVES
// This is based on http://www.thetenthplanet.de/archives/1180
mat3 cotangent_frame(vec3 normal, vec3 position, vec2 uv) {
uv = gl_FrontFacing ? uv : -uv;
// get edge vectors of the pixel triangle
vec3 dp1 = dFdx(position);
vec3 dp2 = dFdy(position);
vec2 duv1 = dFdx(uv);
vec2 duv2 = dFdy(uv);
// solve the linear system
vec3 dp2perp = cross(dp2, normal);
vec3 dp1perp = cross(normal, dp1);
vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;
vec3 bitangent = dp2perp * duv1.y + dp1perp * duv2.y;
// construct a scale-invariant frame
float invMat = inversesqrt(max(dot(tangent, tangent), dot(bitangent, bitangent)));
return mat3(tangent * invMat, bitangent * invMat, normal);
}
vec3 perturb_normal(vec3 normal, vec3 viewVector, vec2 texcoord) {
vec3 normalTex = ${this.glsl_texture}(u_normalTexture, texcoord).xyz * 2.0 - 1.0;
mat3 tbnMat_tangent_to_world = cotangent_frame(normal, -viewVector, texcoord);
return normalize(tbnMat_tangent_to_world * normalTex);
}
#else
vec3 perturb_normal(vec3 normal, vec3 viewVector, vec2 texcoord) {
return normal;
}
#endif
#endif
`;
}
static getStringFromShaderAnyDataType(
data: ShaderAttributeOrSemanticsOrString
): string {
if (data instanceof ShaderSemanticsClass) {
return 'u_' + data.str;
} else if (data instanceof VertexAttributeClass) {
return data.shaderStr;
} else {
return data as string;
}
}
abstract get attributeNames(): AttributeNames;
abstract get attributeSemantics(): Array<VertexAttributeEnum>;
abstract get attributeCompositions(): Array<CompositionTypeEnum>;
} | the_stack |
import { Datetime } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { BodyDateTimeClient } from "../bodyDateTimeClient";
import {
DatetimeGetNullOptionalParams,
DatetimeGetNullResponse,
DatetimeGetInvalidOptionalParams,
DatetimeGetInvalidResponse,
DatetimeGetOverflowOptionalParams,
DatetimeGetOverflowResponse,
DatetimeGetUnderflowOptionalParams,
DatetimeGetUnderflowResponse,
DatetimePutUtcMaxDateTimeOptionalParams,
DatetimePutUtcMaxDateTime7DigitsOptionalParams,
DatetimeGetUtcLowercaseMaxDateTimeOptionalParams,
DatetimeGetUtcLowercaseMaxDateTimeResponse,
DatetimeGetUtcUppercaseMaxDateTimeOptionalParams,
DatetimeGetUtcUppercaseMaxDateTimeResponse,
DatetimeGetUtcUppercaseMaxDateTime7DigitsOptionalParams,
DatetimeGetUtcUppercaseMaxDateTime7DigitsResponse,
DatetimePutLocalPositiveOffsetMaxDateTimeOptionalParams,
DatetimeGetLocalPositiveOffsetLowercaseMaxDateTimeOptionalParams,
DatetimeGetLocalPositiveOffsetLowercaseMaxDateTimeResponse,
DatetimeGetLocalPositiveOffsetUppercaseMaxDateTimeOptionalParams,
DatetimeGetLocalPositiveOffsetUppercaseMaxDateTimeResponse,
DatetimePutLocalNegativeOffsetMaxDateTimeOptionalParams,
DatetimeGetLocalNegativeOffsetUppercaseMaxDateTimeOptionalParams,
DatetimeGetLocalNegativeOffsetUppercaseMaxDateTimeResponse,
DatetimeGetLocalNegativeOffsetLowercaseMaxDateTimeOptionalParams,
DatetimeGetLocalNegativeOffsetLowercaseMaxDateTimeResponse,
DatetimePutUtcMinDateTimeOptionalParams,
DatetimeGetUtcMinDateTimeOptionalParams,
DatetimeGetUtcMinDateTimeResponse,
DatetimePutLocalPositiveOffsetMinDateTimeOptionalParams,
DatetimeGetLocalPositiveOffsetMinDateTimeOptionalParams,
DatetimeGetLocalPositiveOffsetMinDateTimeResponse,
DatetimePutLocalNegativeOffsetMinDateTimeOptionalParams,
DatetimeGetLocalNegativeOffsetMinDateTimeOptionalParams,
DatetimeGetLocalNegativeOffsetMinDateTimeResponse,
DatetimeGetLocalNoOffsetMinDateTimeOptionalParams,
DatetimeGetLocalNoOffsetMinDateTimeResponse
} from "../models";
/** Class containing Datetime operations. */
export class DatetimeImpl implements Datetime {
private readonly client: BodyDateTimeClient;
/**
* Initialize a new instance of the class Datetime class.
* @param client Reference to the service client
*/
constructor(client: BodyDateTimeClient) {
this.client = client;
}
/**
* Get null datetime value
* @param options The options parameters.
*/
getNull(
options?: DatetimeGetNullOptionalParams
): Promise<DatetimeGetNullResponse> {
return this.client.sendOperationRequest({ options }, getNullOperationSpec);
}
/**
* Get invalid datetime value
* @param options The options parameters.
*/
getInvalid(
options?: DatetimeGetInvalidOptionalParams
): Promise<DatetimeGetInvalidResponse> {
return this.client.sendOperationRequest(
{ options },
getInvalidOperationSpec
);
}
/**
* Get overflow datetime value
* @param options The options parameters.
*/
getOverflow(
options?: DatetimeGetOverflowOptionalParams
): Promise<DatetimeGetOverflowResponse> {
return this.client.sendOperationRequest(
{ options },
getOverflowOperationSpec
);
}
/**
* Get underflow datetime value
* @param options The options parameters.
*/
getUnderflow(
options?: DatetimeGetUnderflowOptionalParams
): Promise<DatetimeGetUnderflowResponse> {
return this.client.sendOperationRequest(
{ options },
getUnderflowOperationSpec
);
}
/**
* Put max datetime value 9999-12-31T23:59:59.999Z
* @param datetimeBody datetime body
* @param options The options parameters.
*/
putUtcMaxDateTime(
datetimeBody: Date,
options?: DatetimePutUtcMaxDateTimeOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ datetimeBody, options },
putUtcMaxDateTimeOperationSpec
);
}
/**
* This is against the recommendation that asks for 3 digits, but allow to test what happens in that
* scenario
* @param datetimeBody datetime body
* @param options The options parameters.
*/
putUtcMaxDateTime7Digits(
datetimeBody: Date,
options?: DatetimePutUtcMaxDateTime7DigitsOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ datetimeBody, options },
putUtcMaxDateTime7DigitsOperationSpec
);
}
/**
* Get max datetime value 9999-12-31t23:59:59.999z
* @param options The options parameters.
*/
getUtcLowercaseMaxDateTime(
options?: DatetimeGetUtcLowercaseMaxDateTimeOptionalParams
): Promise<DatetimeGetUtcLowercaseMaxDateTimeResponse> {
return this.client.sendOperationRequest(
{ options },
getUtcLowercaseMaxDateTimeOperationSpec
);
}
/**
* Get max datetime value 9999-12-31T23:59:59.999Z
* @param options The options parameters.
*/
getUtcUppercaseMaxDateTime(
options?: DatetimeGetUtcUppercaseMaxDateTimeOptionalParams
): Promise<DatetimeGetUtcUppercaseMaxDateTimeResponse> {
return this.client.sendOperationRequest(
{ options },
getUtcUppercaseMaxDateTimeOperationSpec
);
}
/**
* This is against the recommendation that asks for 3 digits, but allow to test what happens in that
* scenario
* @param options The options parameters.
*/
getUtcUppercaseMaxDateTime7Digits(
options?: DatetimeGetUtcUppercaseMaxDateTime7DigitsOptionalParams
): Promise<DatetimeGetUtcUppercaseMaxDateTime7DigitsResponse> {
return this.client.sendOperationRequest(
{ options },
getUtcUppercaseMaxDateTime7DigitsOperationSpec
);
}
/**
* Put max datetime value with positive numoffset 9999-12-31t23:59:59.999+14:00
* @param datetimeBody datetime body
* @param options The options parameters.
*/
putLocalPositiveOffsetMaxDateTime(
datetimeBody: Date,
options?: DatetimePutLocalPositiveOffsetMaxDateTimeOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ datetimeBody, options },
putLocalPositiveOffsetMaxDateTimeOperationSpec
);
}
/**
* Get max datetime value with positive num offset 9999-12-31t23:59:59.999+14:00
* @param options The options parameters.
*/
getLocalPositiveOffsetLowercaseMaxDateTime(
options?: DatetimeGetLocalPositiveOffsetLowercaseMaxDateTimeOptionalParams
): Promise<DatetimeGetLocalPositiveOffsetLowercaseMaxDateTimeResponse> {
return this.client.sendOperationRequest(
{ options },
getLocalPositiveOffsetLowercaseMaxDateTimeOperationSpec
);
}
/**
* Get max datetime value with positive num offset 9999-12-31T23:59:59.999+14:00
* @param options The options parameters.
*/
getLocalPositiveOffsetUppercaseMaxDateTime(
options?: DatetimeGetLocalPositiveOffsetUppercaseMaxDateTimeOptionalParams
): Promise<DatetimeGetLocalPositiveOffsetUppercaseMaxDateTimeResponse> {
return this.client.sendOperationRequest(
{ options },
getLocalPositiveOffsetUppercaseMaxDateTimeOperationSpec
);
}
/**
* Put max datetime value with positive numoffset 9999-12-31t23:59:59.999-14:00
* @param datetimeBody datetime body
* @param options The options parameters.
*/
putLocalNegativeOffsetMaxDateTime(
datetimeBody: Date,
options?: DatetimePutLocalNegativeOffsetMaxDateTimeOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ datetimeBody, options },
putLocalNegativeOffsetMaxDateTimeOperationSpec
);
}
/**
* Get max datetime value with positive num offset 9999-12-31T23:59:59.999-14:00
* @param options The options parameters.
*/
getLocalNegativeOffsetUppercaseMaxDateTime(
options?: DatetimeGetLocalNegativeOffsetUppercaseMaxDateTimeOptionalParams
): Promise<DatetimeGetLocalNegativeOffsetUppercaseMaxDateTimeResponse> {
return this.client.sendOperationRequest(
{ options },
getLocalNegativeOffsetUppercaseMaxDateTimeOperationSpec
);
}
/**
* Get max datetime value with positive num offset 9999-12-31t23:59:59.999-14:00
* @param options The options parameters.
*/
getLocalNegativeOffsetLowercaseMaxDateTime(
options?: DatetimeGetLocalNegativeOffsetLowercaseMaxDateTimeOptionalParams
): Promise<DatetimeGetLocalNegativeOffsetLowercaseMaxDateTimeResponse> {
return this.client.sendOperationRequest(
{ options },
getLocalNegativeOffsetLowercaseMaxDateTimeOperationSpec
);
}
/**
* Put min datetime value 0001-01-01T00:00:00Z
* @param datetimeBody datetime body
* @param options The options parameters.
*/
putUtcMinDateTime(
datetimeBody: Date,
options?: DatetimePutUtcMinDateTimeOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ datetimeBody, options },
putUtcMinDateTimeOperationSpec
);
}
/**
* Get min datetime value 0001-01-01T00:00:00Z
* @param options The options parameters.
*/
getUtcMinDateTime(
options?: DatetimeGetUtcMinDateTimeOptionalParams
): Promise<DatetimeGetUtcMinDateTimeResponse> {
return this.client.sendOperationRequest(
{ options },
getUtcMinDateTimeOperationSpec
);
}
/**
* Put min datetime value 0001-01-01T00:00:00+14:00
* @param datetimeBody datetime body
* @param options The options parameters.
*/
putLocalPositiveOffsetMinDateTime(
datetimeBody: Date,
options?: DatetimePutLocalPositiveOffsetMinDateTimeOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ datetimeBody, options },
putLocalPositiveOffsetMinDateTimeOperationSpec
);
}
/**
* Get min datetime value 0001-01-01T00:00:00+14:00
* @param options The options parameters.
*/
getLocalPositiveOffsetMinDateTime(
options?: DatetimeGetLocalPositiveOffsetMinDateTimeOptionalParams
): Promise<DatetimeGetLocalPositiveOffsetMinDateTimeResponse> {
return this.client.sendOperationRequest(
{ options },
getLocalPositiveOffsetMinDateTimeOperationSpec
);
}
/**
* Put min datetime value 0001-01-01T00:00:00-14:00
* @param datetimeBody datetime body
* @param options The options parameters.
*/
putLocalNegativeOffsetMinDateTime(
datetimeBody: Date,
options?: DatetimePutLocalNegativeOffsetMinDateTimeOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ datetimeBody, options },
putLocalNegativeOffsetMinDateTimeOperationSpec
);
}
/**
* Get min datetime value 0001-01-01T00:00:00-14:00
* @param options The options parameters.
*/
getLocalNegativeOffsetMinDateTime(
options?: DatetimeGetLocalNegativeOffsetMinDateTimeOptionalParams
): Promise<DatetimeGetLocalNegativeOffsetMinDateTimeResponse> {
return this.client.sendOperationRequest(
{ options },
getLocalNegativeOffsetMinDateTimeOperationSpec
);
}
/**
* Get min datetime value 0001-01-01T00:00:00
* @param options The options parameters.
*/
getLocalNoOffsetMinDateTime(
options?: DatetimeGetLocalNoOffsetMinDateTimeOptionalParams
): Promise<DatetimeGetLocalNoOffsetMinDateTimeResponse> {
return this.client.sendOperationRequest(
{ options },
getLocalNoOffsetMinDateTimeOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const getNullOperationSpec: coreClient.OperationSpec = {
path: "/datetime/null",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getInvalidOperationSpec: coreClient.OperationSpec = {
path: "/datetime/invalid",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getOverflowOperationSpec: coreClient.OperationSpec = {
path: "/datetime/overflow",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getUnderflowOperationSpec: coreClient.OperationSpec = {
path: "/datetime/underflow",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const putUtcMaxDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/max/utc",
httpMethod: "PUT",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.datetimeBody,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const putUtcMaxDateTime7DigitsOperationSpec: coreClient.OperationSpec = {
path: "/datetime/max/utc7ms",
httpMethod: "PUT",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.datetimeBody,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getUtcLowercaseMaxDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/max/utc/lowercase",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getUtcUppercaseMaxDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/max/utc/uppercase",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getUtcUppercaseMaxDateTime7DigitsOperationSpec: coreClient.OperationSpec = {
path: "/datetime/max/utc7ms/uppercase",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const putLocalPositiveOffsetMaxDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/max/localpositiveoffset",
httpMethod: "PUT",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.datetimeBody,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getLocalPositiveOffsetLowercaseMaxDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/max/localpositiveoffset/lowercase",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getLocalPositiveOffsetUppercaseMaxDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/max/localpositiveoffset/uppercase",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const putLocalNegativeOffsetMaxDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/max/localnegativeoffset",
httpMethod: "PUT",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.datetimeBody,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getLocalNegativeOffsetUppercaseMaxDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/max/localnegativeoffset/uppercase",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getLocalNegativeOffsetLowercaseMaxDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/max/localnegativeoffset/lowercase",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const putUtcMinDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/min/utc",
httpMethod: "PUT",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.datetimeBody,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getUtcMinDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/min/utc",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const putLocalPositiveOffsetMinDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/min/localpositiveoffset",
httpMethod: "PUT",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.datetimeBody,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getLocalPositiveOffsetMinDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/min/localpositiveoffset",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const putLocalNegativeOffsetMinDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/min/localnegativeoffset",
httpMethod: "PUT",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.datetimeBody,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getLocalNegativeOffsetMinDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/min/localnegativeoffset",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const getLocalNoOffsetMinDateTimeOperationSpec: coreClient.OperationSpec = {
path: "/datetime/min/localnooffset",
httpMethod: "GET",
responses: {
200: {
bodyMapper: { type: { name: "DateTime" } }
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import * as PIXI from 'pixi.js';
import PIXIHelper from '../class/pixi/helper/PIXIHelper';
import { PIXIGlobal } from '../class/pixi/init/PIXIGlobal';
import { GEDragHelper } from './GEDragHelper';
import { IGEResManager } from './IGEResManager';
import { EaselResManager } from './EaselResManager';
import { PIXIBrushAdaptor } from '../class/pixi/etc/PIXIBrushAdaptor';
import { PIXIScaleAdaptor } from '../class/pixi/atlas/PIXIScaleAdaptor';
const INITIAL_VIDEO_PARAMS = {
WIDTH: 480,
HEIGHT: 270,
X: -240,
Y: -135,
SCALE_X: 0.75,
SCALE_Y: 0.75,
ALPHA: 0.5,
};
const isFirefox = typeof InstallTrigger !== 'undefined';
declare let createjs: any;
interface IGraphicsEngineApplication {
render(): void;
stage: PIXI.Container | any;
destroy(destroyOption: any): void;
}
interface ITicker {
reset(): void;
setFPS(n: number): void;
}
class CreateJsApplication implements IGraphicsEngineApplication {
stage: any;
constructor(canvas: HTMLCanvasElement) {
const stage = new createjs.Stage(canvas.id);
createjs.Touch.enable(stage);
stage.enableMouseOver(10);
stage.mouseMoveOutside = true;
this.stage = stage;
}
render(): void {
this.stage.update();
}
destroy(destroyOption: any) {
this.stage = null;
}
}
export class GEHelperBase {
protected _isWebGL: boolean = false;
INIT(isWebGL: boolean) {
this._isWebGL = isWebGL;
}
}
const emptyFn = (...arg: any[]) => {};
class _GEHelper extends GEHelperBase {
get isWebGL(): boolean {
return this._isWebGL;
}
public resManager: IGEResManager;
public textHelper: _TextHelper;
public colorFilter: _ColorFilterHelper;
public brushHelper: _BrushHelper;
/** pixi 객체로부터 rotate를 읽을 때 사용할 값 */
public rotateRead: number = 1;
/** pixi 객체에 rotate를 할당 할 때 사용할 값 */
public rotateWrite: number = 1;
public Ticker: ITicker;
private _isInitialized: boolean;
/** pixi Graphics로 비디오 감지 표현하기 위한 PIXI.Graphics */
public poseIndicatorGraphic: PIXI.Graphics | createjs.Graphics;
public faceIndicatorGraphic: PIXI.Graphics | createjs.Graphics;
public objectIndicatorGraphic: PIXI.Graphics | createjs.Graphics;
/**
* issues/9422#issuecomment-2678582
* 최종 좌표 결정 단계에서 약간의 오차를 주어 이 현상을 막음.
*/
public rndPosition: () => number;
/**
* 비디오 블록용 컨테이너, index = 2 , 기존의 오브젝트 컨테이너 = index3;
*/
private videoContainer: PIXI.Container | createjs.Container;
INIT(isWebGL: boolean) {
super.INIT(isWebGL);
if (this._isInitialized) {
return;
}
this._isInitialized = true;
GEDragHelper.INIT(isWebGL);
(this.colorFilter = new _ColorFilterHelper()).INIT(isWebGL);
(this.textHelper = new _TextHelper()).INIT(isWebGL);
(this.brushHelper = new _BrushHelper()).INIT(isWebGL);
if (this._isWebGL) {
// this.rndPosition = ()=>{ return Math.random() * 0.8 - 0.4; };
this.rndPosition = () => 0;
this.rotateRead = 180 / Math.PI;
this.rotateWrite = Math.PI / 180;
PIXIGlobal.initOnce();
this.resManager = PIXIGlobal.atlasManager;
this.Ticker = {
reset: emptyFn,
setFPS: emptyFn,
};
} else {
this.rndPosition = () => 0;
this.resManager = new EaselResManager();
this.Ticker = {
reset: createjs.Ticker.reset,
setFPS: createjs.Ticker.setFPS,
};
}
this.resManager.INIT();
}
newApp(canvas: HTMLCanvasElement): IGraphicsEngineApplication {
let app: IGraphicsEngineApplication;
if (this._isWebGL) {
app = PIXIGlobal.getNewApp(canvas);
} else {
app = new CreateJsApplication(canvas);
}
return app;
}
cloneStamp(entity: any): any {
if (this._isWebGL) {
const orgObj = entity.object;
const orgTex = orgObj.internal_getOriginalTex && orgObj.internal_getOriginalTex();
const object = PIXIHelper.sprite('StampEntity', orgTex || orgObj.texture);
object.visible = orgObj.visible;
object.interactive = false;
object.interactiveChildren = false;
object.setTransform(
orgObj.x,
orgObj.y,
orgObj.scale.x,
orgObj.scale.y,
orgObj.rotation,
orgObj.skew.x,
orgObj.skew.y,
orgObj.pivot.x,
orgObj.pivot.y
);
return object;
} else {
const object = entity.object.clone();
object.mouseEnabled = false;
object.tickEnabled = false;
object.filters = null;
return object;
}
}
hitTestMouse(object: any): boolean {
if (this._isWebGL) {
const pixiApp: PIXI.Application = Entry.stage._app;
const im = pixiApp.renderer.plugins.interaction;
const hitObject = im.hitTest(im.mouse.global, object);
return !!hitObject;
} else {
if (object.alpha < 0.001) {
return false;
}
const stage = Entry.stage.canvas;
const pt = object.globalToLocal(stage.mouseX, stage.mouseY);
return object.hitTest(pt.x, pt.y);
}
}
tickByEngine() {
if (this._isWebGL) {
Entry.stage._app.ticker.start();
} else {
createjs.Ticker.addEventListener('tick', Entry.stage.canvas);
}
}
// for createJS ONLY issue, #12012
disableTickByEngine() {
if (this._isWebGL) {
return;
} else {
createjs.Ticker.removeEventListener('tick', Entry.stage.canvas);
}
}
getNewContainer(): any {
if (this._isWebGL) {
return new PIXI.Container();
} else {
return new createjs.Container();
}
}
// this function returns corresponding VideoElement,
getVideoElement(video: HTMLVideoElement): any {
console.log('getVideoElement');
let videoElement: any = null;
const { WIDTH, X, Y, SCALE_X, SCALE_Y, ALPHA } = INITIAL_VIDEO_PARAMS;
let HEIGHT = INITIAL_VIDEO_PARAMS.HEIGHT;
if (this._isWebGL) {
const videoTexture = PIXI.Texture.from(video);
videoElement = new PIXI.Sprite(videoTexture);
if (isFirefox) {
HEIGHT *= 1.33;
}
} else {
videoElement = new createjs.Bitmap(video);
}
videoElement.width = WIDTH;
videoElement.height = HEIGHT;
videoElement.x = X;
videoElement.y = Y;
videoElement.alpha = ALPHA;
if (this._isWebGL) {
videoElement.scale.x = SCALE_X;
videoElement.scale.y = SCALE_Y;
} else {
videoElement.scaleX = SCALE_X;
videoElement.scaleY = SCALE_Y;
videoElement.on('tick', () => {
if (videoElement.cacheCanvas) {
videoElement.updateCache();
}
});
}
return videoElement;
}
createNewIndicatorGraphic() {
const graphic = this.newGraphic();
graphic.width = 640;
graphic.height = 360;
graphic.x = INITIAL_VIDEO_PARAMS.X;
graphic.y = INITIAL_VIDEO_PARAMS.Y;
return graphic;
}
drawVideoElement(videoElement: PIXI.Sprite | createjs.Bitmap): any {
if (!this.videoContainer) {
this.videoContainer = Entry.stage.canvas.getChildAt(2);
}
this.videoContainer.addChild(videoElement);
this.tickByEngine();
}
drawDetectedGraphic() {
if (!this.poseIndicatorGraphic) {
this.poseIndicatorGraphic = this.createNewIndicatorGraphic();
Entry.stage.canvas.addChildAt(this.poseIndicatorGraphic, 4);
}
if (!this.faceIndicatorGraphic) {
this.faceIndicatorGraphic = this.createNewIndicatorGraphic();
Entry.stage.canvas.addChildAt(this.faceIndicatorGraphic, 4);
}
if (!this.objectIndicatorGraphic) {
this.objectIndicatorGraphic = this.createNewIndicatorGraphic();
Entry.stage.canvas.addChildAt(this.objectIndicatorGraphic, 4);
}
this.tickByEngine();
}
turnOffWebcam(canvasVideo: PIXI.Sprite | createjs.Bitmap) {
if (!canvasVideo) {
return;
}
const targetContainer = Entry.stage.canvas.getChildAt(2);
targetContainer.removeChild(canvasVideo);
}
hFlipVideoElement(canvasVideo: PIXI.Sprite | createjs.Bitmap): any {
const { x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY } = canvasVideo;
canvasVideo.setTransform(-x, y, -scaleX, scaleY, rotation, skewX, skewY, regX, regY);
}
vFlipVideoElement(canvasVideo: PIXI.Sprite | createjs.Bitmap): any {
const { x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY } = canvasVideo;
canvasVideo.setTransform(x, -y, scaleX, -scaleY, rotation, skewX, skewY, regX, regY);
}
setVideoAlpha(canvasVideo: PIXI.Sprite | createjs.Bitmap, value: number): any {
canvasVideo.alpha = (100 - value) / 100;
}
removeAllChildInHandler(handler: PIXI.Graphics | createjs.Graphics) {
while (handler.children.length > 0) {
const child = handler.getChildAt(0);
handler.removeChild(child);
}
}
resetHandlers() {
if (
!this.faceIndicatorGraphic ||
!this.poseIndicatorGraphic ||
!this.objectIndicatorGraphic
) {
return;
}
if (this.isWebGL) {
this.faceIndicatorGraphic.clear();
this.poseIndicatorGraphic.clear();
this.objectIndicatorGraphic.clear();
this.removeAllChildInHandler(this.objectIndicatorGraphic);
this.removeAllChildInHandler(this.poseIndicatorGraphic);
this.removeAllChildInHandler(this.faceIndicatorGraphic);
} else {
this.faceIndicatorGraphic.graphics.clear();
this.poseIndicatorGraphic.graphics.clear();
this.objectIndicatorGraphic.graphics.clear();
}
}
async drawHumanPoints(poses: Array<any>, flipStatus: any) {
const R = 5;
let handler = this.poseIndicatorGraphic;
if (this._isWebGL) {
while (handler.children.length > 0) {
const child = handler.getChildAt(0);
handler.removeChild(child);
}
} else {
handler = this.poseIndicatorGraphic.graphics;
}
handler.clear();
poses.map((pose: any, index: Number) => {
const { x, y } = pose.keypoints[3].position;
if (this._isWebGL) {
const text = PIXIHelper.text(
`${Lang.Blocks.video_human}-${index + 1}`,
'20px Nanum Gothic',
'',
'middle',
'center'
);
text.x = x - 20;
text.y = y - 20;
handler.addChild(text);
} else {
handler.append({
exec: (ctx: any) => {
ctx.font = '20px Nanum Gothic';
ctx.color = 'blue';
ctx.fillText(`${Lang.Blocks.video_human}-${index + 1}`, x - 20, y - 20);
},
});
}
pose.keypoints.map((item: any) => {
const { x, y } = item.position;
const recalculatedY = flipStatus.vertical ? INITIAL_VIDEO_PARAMS.HEIGHT - y : y;
handler.beginFill(0x0000ff);
handler.drawCircle(x, recalculatedY, R);
handler.endFill();
});
});
}
async drawHumanSkeletons(adjacents: Array<any>, flipStatus: any) {
const coordList: any = [];
let handler = this.poseIndicatorGraphic;
adjacents.forEach((adjacentList: any) => {
adjacentList.forEach((pair: any) => {
const start = pair[0].position;
const end = pair[1].position;
if (flipStatus.vertical) {
start.y = INITIAL_VIDEO_PARAMS.HEIGHT - start.y;
end.y = INITIAL_VIDEO_PARAMS.HEIGHT - end.y;
}
coordList.push({ start, end });
});
});
if (this._isWebGL) {
handler.lineStyle(5, 0x0000ff);
} else {
handler = handler.graphics;
handler.setStrokeStyle(8, 'round').beginStroke('blue');
}
coordList.forEach((coord: any) => {
const { start, end } = coord;
handler.moveTo(start.x, start.y).lineTo(end.x, end.y);
});
}
async drawFaceEdges(faces: any, flipStatus: any) {
let handler = this.faceIndicatorGraphic;
if (this._isWebGL) {
handler.clear();
while (handler.children.length > 0) {
const child = handler.getChildAt(0);
handler.removeChild(child);
}
handler.lineStyle(2, 0xff0000);
} else {
handler = handler.graphics;
handler.clear();
handler.setStrokeStyle(2, 'round').beginStroke('red');
}
faces.forEach((face: { landmarks: { _positions: any[] } }, index: Number) => {
const positions = face.landmarks._positions;
positions.forEach((item, i) => {
if (
i === 0 ||
i === 17 ||
i === 27 ||
i === 31 ||
i === 36 ||
i === 42 ||
i === 48
) {
return;
}
const prev = face.landmarks._positions[i - 1];
this.drawEdge(prev, item, handler, flipStatus);
});
// compensation for missing edges
this.drawEdge(positions[42], positions[47], handler, flipStatus);
this.drawEdge(positions[41], positions[36], handler, flipStatus);
this.drawEdge(positions[60], positions[67], handler, flipStatus);
this.drawEdge(positions[0], positions[17], handler, flipStatus);
this.drawEdge(positions[16], positions[26], handler, flipStatus);
this.drawEdge(positions[27], positions[31], handler, flipStatus);
this.drawEdge(positions[27], positions[35], handler, flipStatus);
this.drawEdge(positions[30], positions[31], handler, flipStatus);
this.drawEdge(positions[30], positions[35], handler, flipStatus);
const refPoint = positions[57];
let x = refPoint._x;
let y = refPoint._y;
const { WIDTH, HEIGHT } = INITIAL_VIDEO_PARAMS;
if (flipStatus.horizontal) {
x = WIDTH - x;
}
if (flipStatus.vertical) {
y = HEIGHT - y;
}
if (this._isWebGL) {
const text = PIXIHelper.text(
`${Lang.Blocks.video_face}-${index + 1}`,
'20px Nanum Gothic',
'',
'middle',
'center'
);
text.x = x;
text.y = y - 10;
handler.addChild(text);
} else {
handler.append({
exec: (ctx: any) => {
ctx.font = '20px Nanum Gothic';
ctx.color = '#0000ff';
ctx.fillText(`${Lang.Blocks.video_face}-${index + 1}`, x, y - 10);
},
});
}
});
}
drawEdge(
pos1: { _x: number; _y: number },
pos2: { _x: number; _y: number },
handler: PIXI.Graphics | createjs.Graphics,
flipStatus: any
) {
const { WIDTH, HEIGHT } = INITIAL_VIDEO_PARAMS;
let { _x, _y } = pos2;
let prevX = pos1._x;
let prevY = pos1._y;
if (flipStatus.horizontal) {
_x = WIDTH - _x;
prevX = WIDTH - prevX;
}
if (flipStatus.vertical) {
_y = HEIGHT - _y;
prevY = HEIGHT - prevY;
}
handler.moveTo(prevX, prevY).lineTo(_x, _y);
}
async drawObjectBox(objects: Array<any>, flipStatus: any) {
const objectsList: any = [];
objects.forEach((object: any) => {
const bbox = object.bbox;
const name = object.class
? `${Lang.Blocks.video_object}-${Lang.video_object_params[object.class]}`
: '';
let x = bbox[0];
let y = bbox[1];
const width = bbox[2];
const height = bbox[3];
if (flipStatus.horizontal) {
x = INITIAL_VIDEO_PARAMS.WIDTH - x - width;
}
if (flipStatus.vertical) {
y = INITIAL_VIDEO_PARAMS.HEIGHT - y - height;
}
const textpoint = { x: x + 20, y: y + 20 };
objectsList.push({ textpoint, name, x, y, width, height });
});
let handler = this.objectIndicatorGraphic;
if (this._isWebGL) {
handler.clear();
while (handler.children.length > 0) {
const child = handler.getChildAt(0);
handler.removeChild(child);
}
handler.lineStyle(5, 0xff0000);
objectsList.forEach((target: any, index: Number) => {
const { textpoint, name, x, y, width, height } = target;
if (name) {
const text = PIXIHelper.text(
`${name}-${index + 1}`,
'20px Nanum Gothic',
'',
'middle',
'center'
);
text.x = textpoint.x;
text.y = textpoint.y;
handler.addChild(text);
}
handler.drawRect(x, y, width, height);
});
} else {
handler = handler.graphics;
handler.clear();
objectsList.forEach((target: any, index: Number) => {
const { textpoint, name, x, y, width, height } = target;
if (name) {
handler.append({
exec: (ctx: any) => {
ctx.font = '20px Nanum Gothic';
ctx.fillText(`${name}-${index + 1}`, textpoint.x - 5, textpoint.y + 5);
},
});
}
handler
.setStrokeStyle(8, 'round')
.beginStroke('red')
.drawRect(x, y, width, height);
});
}
}
getTransformedBounds(sprite: PIXI.Sprite | any): PIXI.Rectangle | any {
if (this._isWebGL) {
return sprite.getBounds(false);
} else {
return sprite.getTransformedBounds();
}
}
calcParentBound(obj: any): any {
if (this._isWebGL) {
return PIXIHelper.getTransformBound(obj);
} else {
return obj.getTransformedBounds();
}
}
newContainer(debugName?: string): PIXI.Container | any {
if (this._isWebGL) {
return PIXIHelper.container(debugName);
} else {
return new createjs.Container();
}
}
/**
* stage wall 생성만을 위한 함수
* @param path
*/
newWallTexture(path: string): PIXI.Texture | HTMLImageElement {
if (this._isWebGL) {
return PIXI.Texture.from(path);
} else {
const img: HTMLImageElement = new Image();
img.src = path;
return img;
}
}
/**
* stage wall 생성만을 위한 함수
* @param tex
*/
newWallSprite(tex: any) {
if (this._isWebGL) {
return new PIXI.Sprite(tex);
} else {
return new createjs.Bitmap(tex);
}
}
newEmptySprite() {
if (this._isWebGL) {
return PIXIHelper.sprite();
} else {
return new createjs.Bitmap();
}
}
newSpriteWithCallback(url: string, callback?: () => void) {
const img = new Image();
if (callback) {
const handle = () => {
img.removeEventListener('load', handle);
callback();
};
img.addEventListener('load', handle);
}
img.src = url;
if (this._isWebGL) {
const texture = PIXI.Texture.from(img);
return PIXI.Sprite.from(texture);
} else {
return new createjs.Bitmap(img);
}
}
newGraphic() {
if (this._isWebGL) {
return new PIXI.Graphics();
} else {
return new createjs.Shape();
}
}
newAScaleAdaptor(target: any): any {
if (this._isWebGL) {
return PIXIScaleAdaptor.factory(target);
}
//createjs 는 사용하는 코드측에서 분기 처리.
return null;
}
}
export const GEHelper = new _GEHelper();
class _ColorFilterHelper extends GEHelperBase {
hue(value: number) {
if (this._isWebGL) {
const cmHue = new PIXI.filters.ColorMatrixFilter();
// @ts-ignore
return cmHue.hue(value);
} else {
const cmHue = new createjs.ColorMatrix();
cmHue.adjustColor(0, 0, 0, value);
const hueFilter = new createjs.ColorMatrixFilter(cmHue);
return hueFilter;
}
}
brightness(value: number) {
if (this._isWebGL) {
value /= 255;
}
// pixi 필터에 brightness 가 있지만, createjs 와 matrix 값이 달라 결과가 다르게 보임. 그래서 동일하게 구현함.
const matrix = [
1,
0,
0,
0,
value,
0,
1,
0,
0,
value,
0,
0,
1,
0,
value,
0,
0,
0,
1,
0,
0,
0,
0,
0,
1,
];
return this.newColorMatrixFilter(matrix);
}
/**
* @param matrixValue
*/
newColorMatrixFilter(matrixValue: number[]) {
if (this._isWebGL) {
matrixValue.length = 20; // pixi matrix 는 5 * 4
const m = new PIXI.filters.ColorMatrixFilter();
m._loadMatrix(matrixValue, false);
return m;
} else {
//createjs matrix 는 5*5
const cm = new createjs.ColorMatrix();
cm.copy(matrixValue);
return new createjs.ColorMatrixFilter(cm);
}
}
/**
*
* @param entity - EntityObject
* @param cache
*/
setCache(entity: any, cache: boolean) {
if (this._isWebGL) {
//do nothing
} else {
cache ? entity.cache() : entity.object.uncache();
}
}
}
class _TextHelper extends GEHelperBase {
setColor(target: PIXI.Text | any, color: string) {
if (this._isWebGL) {
target.style.fill = color;
} else {
target.color = color;
}
}
/**
* @param str
* @param font size & fontface - 10pt NanumGothic
* @param color css style color - #ffffff
* @param textBaseline
* @param textAlign
* @
*/
newText(
str: string,
font: string,
color: string,
textBaseline?: string,
textAlign?: string
): PIXI.Text | any {
if (this._isWebGL) {
return PIXIHelper.text(str, font, color, textBaseline, textAlign);
} else {
const text = new createjs.Text(str, font, color);
textBaseline ? (text.textBaseline = textBaseline) : 0;
textAlign ? (text.textAlign = textAlign) : 0;
return text;
}
}
}
class _BrushHelper extends GEHelperBase {
newBrush() {
if (this._isWebGL) {
return new PIXIBrushAdaptor();
} else {
return new createjs.Graphics();
}
}
newShape(brush: PIXIBrushAdaptor | any) {
if (this._isWebGL) {
const shape = PIXIHelper.newPIXIGraphics();
brush.internal_setShape(shape);
return shape;
} else {
return new createjs.Shape(brush);
}
}
} | the_stack |
import {PbEcdsaParams, PbEcdsaPublicKey, PbEcdsaSignatureEncoding, PbEllipticCurveType, PbHashType, PbKeyData} from '../internal/proto';
import * as Registry from '../internal/registry';
import * as Util from '../internal/util';
import * as Bytes from '../subtle/bytes';
import * as EllipticCurves from '../subtle/elliptic_curves';
import {assertExists} from '../testing/internal/test_utils';
import {EcdsaPublicKeyManager} from './ecdsa_public_key_manager';
import {PublicKeyVerify} from './internal/public_key_verify';
const KEY_TYPE = 'type.googleapis.com/google.crypto.tink.EcdsaPublicKey';
const VERSION = 0;
const PRIMITIVE = PublicKeyVerify;
describe('ecdsa public key manager test', function() {
beforeEach(function() {
// Use a generous promise timeout for running continuously.
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 1000; // 1000s
});
afterEach(function() {
Registry.reset();
// Reset the promise timeout to default value.
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; // 1s
});
it('new key', function() {
const manager = new EcdsaPublicKeyManager();
try {
manager.getKeyFactory().newKey(new Uint8Array(0));
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.notSupported());
}
});
it('new key data', function() {
const manager = new EcdsaPublicKeyManager();
try {
manager.getKeyFactory().newKeyData(new Uint8Array(0));
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.notSupported());
}
});
it('get primitive, unsupported key data type', async function() {
const manager = new EcdsaPublicKeyManager();
const keyData =
(await createKeyData()).setTypeUrl('unsupported_key_type_url');
try {
await manager.getPrimitive(PRIMITIVE, keyData);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString())
.toBe(ExceptionText.unsupportedKeyType(keyData.getTypeUrl()));
}
});
it('get primitive, unsupported key type', async function() {
const manager = new EcdsaPublicKeyManager();
const key = new PbEcdsaParams();
try {
await manager.getPrimitive(PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.unsupportedKeyType());
}
});
it('get primitive, high version', async function() {
const version = 1;
const manager = new EcdsaPublicKeyManager();
const key = (await createKey()).setVersion(version);
try {
await manager.getPrimitive(PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.versionOutOfBounds());
}
});
it('get primitive, missing params', async function() {
const manager = new EcdsaPublicKeyManager();
const key = (await createKey()).setParams(null);
try {
await manager.getPrimitive(PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.missingParams());
}
});
it('get primitive, invalid params', async function() {
const manager = new EcdsaPublicKeyManager();
const key = await createKey();
// Unknown encoding.
key.getParams()?.setEncoding(PbEcdsaSignatureEncoding.UNKNOWN_ENCODING);
try {
await manager.getPrimitive(PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.unknownEncoding());
}
key.getParams()?.setEncoding(PbEcdsaSignatureEncoding.DER);
// Unknown hash.
key.getParams()?.setHashType(PbHashType.UNKNOWN_HASH);
try {
await manager.getPrimitive(PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.unknownHash());
}
key.getParams()?.setHashType(PbHashType.SHA256);
// Unknown curve.
key.getParams()?.setCurve(PbEllipticCurveType.UNKNOWN_CURVE);
try {
await manager.getPrimitive(PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString()).toBe(ExceptionText.unknownCurve());
}
// Bad hash + curve combinations.
key.getParams()?.setCurve(PbEllipticCurveType.NIST_P384);
try {
await manager.getPrimitive(PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString())
.toBe(
'SecurityException: expected SHA-384 or SHA-512 (because curve is P-384) but got SHA-256');
}
key.getParams()?.setCurve(PbEllipticCurveType.NIST_P521);
try {
await manager.getPrimitive(PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(e.toString())
.toBe(
'SecurityException: expected SHA-512 (because curve is P-521) but got SHA-256');
}
});
it('get primitive, invalid key', async function() {
const manager = new EcdsaPublicKeyManager();
const key = await createKey();
const x = key.getX();
key.setX(new Uint8Array(0));
try {
await manager.getPrimitive(PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(ExceptionText.webCryptoErrors()).toContain(e.toString());
}
key.setX(x);
key.setY(new Uint8Array(0));
try {
await manager.getPrimitive(PRIMITIVE, key);
fail('An exception should be thrown.');
} catch (e) {
expect(ExceptionText.webCryptoErrors()).toContain(e.toString());
}
});
it('get primitive, invalid serialized key', async function() {
const manager = new EcdsaPublicKeyManager();
const keyData = await createKeyData();
for (let i = 0; i < 2; ++i) {
// Set the value of keyData to something which is not a serialization of a
// proper key.
keyData.setValue(new Uint8Array(i));
try {
await manager.getPrimitive(PRIMITIVE, keyData);
fail('An exception should be thrown ' + i.toString());
} catch (e) {
expect(e.toString()).toBe(ExceptionText.invalidSerializedKey());
}
}
});
// tests for getting primitive from valid key/keyData
it('get primitive, from key', async function() {
const manager = new EcdsaPublicKeyManager();
const keys = await createTestSetOfKeys();
for (const key of keys) {
await manager.getPrimitive(PRIMITIVE, key);
}
});
it('get primitive, from key data', async function() {
const manager = new EcdsaPublicKeyManager();
const keyDatas = await createTestSetOfKeyDatas();
for (const key of keyDatas) {
await manager.getPrimitive(PRIMITIVE, key);
}
});
it('does support', function() {
const manager = new EcdsaPublicKeyManager();
expect(manager.doesSupport(KEY_TYPE)).toBe(true);
});
it('get key type', function() {
const manager = new EcdsaPublicKeyManager();
expect(manager.getKeyType()).toBe(KEY_TYPE);
});
it('get primitive type', function() {
const manager = new EcdsaPublicKeyManager();
expect(manager.getPrimitiveType()).toBe(PRIMITIVE);
});
it('get version', function() {
const manager = new EcdsaPublicKeyManager();
expect(manager.getVersion()).toBe(VERSION);
});
});
// Helper classes and functions
class ExceptionText {
static notSupported(): string {
return 'SecurityException: This operation is not supported for public keys. ' +
'Use EcdsaPrivateKeyManager to generate new keys.';
}
static unsupportedPrimitive(): string {
return 'SecurityException: Requested primitive type which is not supported by ' +
'this key manager.';
}
static unsupportedKeyType(opt_requestedKeyType?: string): string {
const prefix = 'SecurityException: Key type';
const suffix =
'is not supported. This key manager supports ' + KEY_TYPE + '.';
if (opt_requestedKeyType) {
return prefix + ' ' + opt_requestedKeyType + ' ' + suffix;
} else {
return prefix + ' ' + suffix;
}
}
static versionOutOfBounds(): string {
return 'SecurityException: Version is out of bound, must be between 0 and ' +
VERSION + '.';
}
static unknownEncoding(): string {
return 'SecurityException: Invalid public key - missing signature encoding.';
}
static unknownHash(): string {
return 'SecurityException: Unknown hash type.';
}
static unknownCurve(): string {
return 'SecurityException: Unknown curve type.';
}
static missingParams(): string {
return 'SecurityException: Invalid public key - missing params.';
}
static missingXY(): string {
return 'SecurityException: Invalid public key - missing value of X or Y.';
}
static invalidSerializedKey(): string {
return 'SecurityException: Input cannot be parsed as ' + KEY_TYPE +
' key-proto.';
}
static webCryptoErrors(): string[] {
return [
'DataError',
// Firefox
'DataError: Data provided to an operation does not meet requirements',
];
}
}
function createParams(
curveType: PbEllipticCurveType, hashType: PbHashType,
encoding: PbEcdsaSignatureEncoding): PbEcdsaParams {
const params = (new PbEcdsaParams())
.setCurve(curveType)
.setHashType(hashType)
.setEncoding(encoding);
return params;
}
async function createKey(
opt_curveType: PbEllipticCurveType = PbEllipticCurveType.NIST_P256,
opt_hashType: PbHashType = PbHashType.SHA256,
opt_encoding: PbEcdsaSignatureEncoding =
PbEcdsaSignatureEncoding.DER): Promise<PbEcdsaPublicKey> {
const curveSubtleType = Util.curveTypeProtoToSubtle(opt_curveType);
const curveName = EllipticCurves.curveToString(curveSubtleType);
const key =
(new PbEcdsaPublicKey())
.setVersion(0)
.setParams(createParams(opt_curveType, opt_hashType, opt_encoding));
const keyPair = await EllipticCurves.generateKeyPair('ECDSA', curveName);
const publicKey = await EllipticCurves.exportCryptoKey(keyPair.publicKey);
key.setX(
Bytes.fromBase64(assertExists(publicKey['x']), /* opt_webSafe = */ true));
key.setY(
Bytes.fromBase64(assertExists(publicKey['y']), /* opt_webSafe = */ true));
return key;
}
function createKeyDataFromKey(key: PbEcdsaPublicKey): PbKeyData {
const keyData =
new PbKeyData()
.setTypeUrl(KEY_TYPE)
.setValue(key.serializeBinary())
.setKeyMaterialType(PbKeyData.KeyMaterialType.ASYMMETRIC_PUBLIC);
return keyData;
}
async function createKeyData(
opt_curveType?: PbEllipticCurveType, opt_hashType?: PbHashType,
opt_encoding?: PbEcdsaSignatureEncoding): Promise<PbKeyData> {
const key = await createKey(opt_curveType, opt_hashType, opt_encoding);
return createKeyDataFromKey(key);
}
// Create set of keys with all possible predefined/supported parameters.
async function createTestSetOfKeys(): Promise<PbEcdsaPublicKey[]> {
const keys: PbEcdsaPublicKey[] = [];
keys.push(await createKey(
PbEllipticCurveType.NIST_P256, PbHashType.SHA256,
PbEcdsaSignatureEncoding.DER));
keys.push(await createKey(
PbEllipticCurveType.NIST_P256, PbHashType.SHA256,
PbEcdsaSignatureEncoding.IEEE_P1363));
keys.push(await createKey(
PbEllipticCurveType.NIST_P384, PbHashType.SHA512,
PbEcdsaSignatureEncoding.DER));
keys.push(await createKey(
PbEllipticCurveType.NIST_P384, PbHashType.SHA512,
PbEcdsaSignatureEncoding.IEEE_P1363));
keys.push(await createKey(
PbEllipticCurveType.NIST_P521, PbHashType.SHA512,
PbEcdsaSignatureEncoding.DER));
keys.push(await createKey(
PbEllipticCurveType.NIST_P521, PbHashType.SHA512,
PbEcdsaSignatureEncoding.IEEE_P1363));
return keys;
}
// Create set of keyData protos with keys of all possible predefined/supported
// parameters.
async function createTestSetOfKeyDatas(): Promise<PbKeyData[]> {
const keys = await createTestSetOfKeys();
const keyDatas: PbKeyData[] = [];
for (const key of keys) {
const keyData = await createKeyDataFromKey(key);
keyDatas.push(keyData);
}
return keyDatas;
} | the_stack |
import { IPackage } from '../interfaces/IPackage';
import { IPackageExplorer } from '../interfaces/IPackageExplorer';
import { NpmService } from '../services/NpmService';
import { IPackageDetail } from '../interfaces/IPackageDetail';
import { BowerService } from '../services/BowerService';
import { IPackageCommand } from '../interfaces/IPackageCommand';
import { StatusHelpers } from './StatusHelpers';
const compareVersions = require('compare-versions');
const getPackageReadme = require('get-package-readme');
const mdToHtml = require('showdown');
const fs = require('fs');
const q = require('q');
let _command = '';
export class PackageHelpers {
scope: any;
constructor(scope: any) {
this.scope = scope;
}
//Reset packages
resetPackages() {
this.scope.$root.packages = {}
}
//Install package
install(packageNames: string[], isDevDependency: boolean = false, callback: any) {
const activeItem: IPackageExplorer = <IPackageExplorer>this.scope.$root.activePackageExplorerItem;
const path: string = this.scope.$root.activePackageExplorerItem.path;
new StatusHelpers().setTextForPackageProcess(packageNames.join(', '), _command, 'start');
if (activeItem.packageManager === 'npm') {
const npmPacksWithVersion = (packageName: string) => {
let deferred = q.defer();
if (packageName !== undefined && packageName.indexOf('||') === -1) {
new NpmService().getLatestVersion(packageName, (result: any) => {
deferred.resolve(`${packageName}@${result}`);
});
} else {
deferred.resolve(packageName.replace('||', '@'));
}
return deferred.promise;
}
q.all(packageNames.map(npmPacksWithVersion)).done((result: any) => {
const packs: IPackageCommand = {
packages: result,
isDevDependency: isDevDependency,
packagePath: path,
isGlobal: path === null || path === undefined
}
new NpmService().install(packs, (result: any) => {
packs.packages.forEach((val: any, i: number) => {
const packName = val.substring(0, val.lastIndexOf('@'));
const packVersion = val.substring(val.lastIndexOf('@') + 1, val.length);
this.addToInstalledPackages(packName, packVersion, false, false);
});
new StatusHelpers().setTextForPackageProcess(packageNames.join(', '), _command, 'end');
setTimeout(callback(result), 250);
});
});
}
else if (activeItem.packageManager === 'bower') {
const bowerPacksWithVersion = (packageName: string) => {
let deferred = q.defer();
if (packageName !== undefined && packageName.indexOf('||') === -1) {
new BowerService().getLatestVersion(packageName, (result: any) => {
deferred.resolve(`${packageName}#${result}`);
});
} else {
deferred.resolve(packageName.replace('||', '#'));
}
return deferred.promise;
}
q.all(packageNames.map(bowerPacksWithVersion)).done((result: any) => {
const packs: IPackageCommand = {
packages: result,
isDevDependency: false,
packagePath: path
}
new BowerService().install(packs, (result: any) => {
$.each(result, (key: string, val: any) => {
new StatusHelpers().setTextForPackageProcess(packageNames.join(', '), _command, 'end');
this.addToInstalledPackages(key, val.pkgMeta.version, false, false);
});
setTimeout(callback(result), 250);
});
});
}
}
//Uninstall package
uninstall(packageNames: string[], forUpgradeOrDowngrade: boolean = false, callback: any) {
const activeItem: IPackageExplorer = <IPackageExplorer>this.scope.$root.activePackageExplorerItem;
new StatusHelpers().setTextForPackageProcess(packageNames.join(', '), _command, 'start');
const pack: IPackageCommand = {
packages: packageNames.map((item) => {
return item.indexOf('||') !== -1 ? item.split('||')[0] : item;
}),
packagePath: activeItem.path,
isGlobal: activeItem.path === null || activeItem.path === undefined
};
if (activeItem.packageManager === 'npm') {
new NpmService().uninstall(pack, (result: any) => {
packageNames.forEach((val: any, i: number) => {
this.removeFromInstalledPackages(val, forUpgradeOrDowngrade);
});
new StatusHelpers().setTextForPackageProcess(packageNames.join(', '), _command, 'end');
setTimeout(callback(result), 250);
});
}
else if (activeItem.packageManager === 'bower') {
new BowerService().uninstall(pack, (result: any) => {
$.each(result, (key: string, val: any) => {
this.removeFromInstalledPackages(key, forUpgradeOrDowngrade);
});
new StatusHelpers().setTextForPackageProcess(packageNames.join(', '), _command, 'end');
setTimeout(callback(result), 250);
});
}
}
//Update the package
update(packageNames: string[], isDevDependency: boolean = false, callback: any) {
this.uninstall(packageNames, true, () => {
this.install(packageNames, isDevDependency, callback);
});
}
//Downgrade package version
downgrade(packageNames: string[], isDevDependency: boolean = false, callback: any) {
this.uninstall(packageNames, true, () => {
this.install(packageNames, isDevDependency, callback);
});
}
//Add a package to list of installed package
private addToInstalledPackages(packageName: string, version: string, fromInstalledPackage: boolean = false, isDevDependencies: boolean = false) {
if (this.scope.$root.packages[packageName] === undefined) {
let packInfo: IPackage = {
alreadyInstalled: true,
name: packageName,
version: version,
selectedVersion: version,
isDevDependencies: isDevDependencies,
listItemControl: {
downgrade: false,
install: false,
loader: fromInstalledPackage ? true : false,
reload: fromInstalledPackage ? false : true,
uninstall: true,
update: false,
},
detailControl: {
downgrade: false,
install: false,
loader: fromInstalledPackage ? true : false,
reload: fromInstalledPackage ? false : true,
uninstall: true,
update: false
}
}
this.scope.$root.packages[packageName] = packInfo;
} else {
this.scope.$root.packages[packageName].alreadyInstalled = true;
this.scope.$root.packages[packageName].version = version;
this.scope.$root.packages[packageName].selectedVersion = version;
}
}
//Remove package from list of installed
removeFromInstalledPackages(packageName: string, forUpgradeOrDowngrade: boolean = false) {
if (packageName.indexOf('||') !== -1) packageName = packageName.split('||')[0];
let packInfo: IPackage = <IPackage>this.scope.$root.packages[packageName];
packInfo.alreadyInstalled = false;
packInfo.listItemControl.downgrade = false;
packInfo.listItemControl.loader = false;
packInfo.listItemControl.reload = true;
packInfo.listItemControl.update = false;
packInfo.detailControl.downgrade = false;
packInfo.detailControl.loader = false;
packInfo.detailControl.reload = true;
packInfo.detailControl.update = false;
if (!forUpgradeOrDowngrade) {
packInfo.listItemControl.install = true;
packInfo.listItemControl.uninstall = false;
packInfo.detailControl.install = true;
packInfo.detailControl.uninstall = false;
}
this.scope.$root.packages[packageName] = packInfo;
}
//Get all installed packages list without read a file
getAllInstalledPackages(): IPackage[] {
const allPackages: IPackage[] = <IPackage[]>this.scope.$root.packages;
let installedPackages: IPackage[] = [];
$.each(allPackages, (key, val) => {
if (val.alreadyInstalled) installedPackages.push(val);
});
return _.sortBy(installedPackages, 'name');
}
setAllAsInstalled(packages: IPackage[]) {
$.each(packages, (i, key) => {
let packInfo: IPackage = <IPackage>this.scope.$root.packages[key.name];
packInfo.alreadyInstalled = true;
packInfo.listItemControl.downgrade = false;
packInfo.listItemControl.install = false;
packInfo.listItemControl.loader = true;
packInfo.listItemControl.reload = false;
packInfo.listItemControl.uninstall = true;
packInfo.listItemControl.update = false;
packInfo.detailControl.downgrade = false;
packInfo.detailControl.install = false;
packInfo.detailControl.loader = false;
packInfo.detailControl.reload = false;
packInfo.detailControl.uninstall = false;
packInfo.detailControl.update = false;
this.scope.$root.packages[key.name] = packInfo;
});
}
//Get installed packages from package/bower.json file
getInstalledPackagesFromFile(packageManager: string, filePath: string, callback: any): void {
if (packageManager === 'npm') {
if (filePath === null) { //Global packages
new NpmService().getGlobalPackages((result: any) => {
$.each(result, (i, key) => {
this.addToInstalledPackages(key.name, key.version, true, false);
});
setTimeout(() => {
callback(this.getAllInstalledPackages());
}, 250);
});
} else {
new NpmService().getInstalledPackagesFromFile(filePath, (result: any) => {
if (result !== undefined && result !== null) {
$.each(result.dependencies, (key: string, val: any) => {
this.addToInstalledPackages(key, val.version, true, false);
});
}
setTimeout(() => {
callback(this.getAllInstalledPackages());
}, 250);
});
}
}
else if (packageManager === 'bower') {
new BowerService().getInstalledPackagesFromFile(filePath, (result: any) => {
if (result !== undefined && result !== null) {
$.each(result.dependencies, (key: string, val: any) => {
this.addToInstalledPackages(key, val.pkgMeta.version, true, false);
//Depends on packages
$.each(val.dependencies, (subKey: string, subVal: any) => {
if (subVal.pkgMeta !== undefined) this.addToInstalledPackages(subKey, subVal.pkgMeta.version, true, false);
});
});
}
setTimeout(() => {
callback(this.getAllInstalledPackages());
}, 250);
});
}
}
//Get&set a package latest version
setLatestVersion(packageName: string, version: string, callback: any) {
const pack: IPackageExplorer = <IPackageExplorer>this.scope.$root.activePackageExplorerItem;
if (pack.packageManager === 'npm') {
new NpmService().getLatestVersion(packageName, (result: string) => {
let packInfo: IPackage = <IPackage>this.scope.$root.packages[packageName];
if (packInfo !== undefined) {
packInfo.listItemControl.loader = false;
packInfo.listItemControl.update = packInfo.alreadyInstalled && compareVersions(result, version) > 0;
packInfo.latestVersion = result;
packInfo.selectedVersion = result;
packInfo.detailControl.loader = false;
packInfo.detailControl.update = packInfo.alreadyInstalled && compareVersions(result, version) > 0;
this.scope.$root.$apply(() => {
this.scope.$root.packages[packageName] = packInfo;
callback();
});
}
});
} else if (pack.packageManager === 'bower') {
new BowerService().getLatestVersion(packageName, (result: string) => {
let packInfo: IPackage = <IPackage>this.scope.$root.packages[packageName];
if (packInfo !== undefined) {
packInfo.listItemControl.loader = false;
packInfo.listItemControl.update = packInfo.alreadyInstalled && compareVersions(result, version) > 0;
packInfo.latestVersion = result;
packInfo.selectedVersion = result;
packInfo.detailControl.loader = false;
packInfo.detailControl.update = packInfo.alreadyInstalled && compareVersions(result, version) > 0;
this.scope.$root.$apply(() => {
this.scope.$root.packages[packageName] = packInfo;
callback();
});
}
});
}
}
getSearchResult(query: string, callback: any) {
const pack: IPackageExplorer = <IPackageExplorer>this.scope.$root.activePackageExplorerItem;
let searchResults: IPackage[] = [];
if (pack.packageManager === 'npm') {
new NpmService().getSearchResult(query, (result: any) => {
$.each(result, (i: number, val: any) => {
const shownBefore: boolean = this.scope.$root.packages[val.name] !== undefined;
let resultItem: IPackage;
if (!shownBefore) {
resultItem = {
alreadyInstalled: false,
name: val.name,
version: val.version,
selectedVersion: val.version,
listItemControl: {
downgrade: false,
install: true,
loader: false,
reload: false,
uninstall: false,
update: false,
},
detailControl: {
downgrade: false,
install: true,
loader: false,
reload: false,
uninstall: false,
update: false
}
}
this.scope.$root.packages[val.name] = resultItem;
} else {
resultItem = <IPackage>this.scope.$root.packages[val.name];
}
searchResults.push(resultItem);
});
callback(searchResults);
});
} else if (pack.packageManager === 'bower') {
new BowerService().getSearchResult(query, (result: any) => {
$.each(result, (i: number, val: any) => {
const shownBefore: boolean = this.scope.$root.packages[val.name] !== undefined;
let resultItem: IPackage;
if (!shownBefore) {
resultItem = {
alreadyInstalled: false,
name: val.name,
version: null,
selectedVersion: null,
listItemControl: {
downgrade: false,
install: true,
loader: false,
reload: false,
uninstall: false,
update: false,
},
detailControl: {
downgrade: false,
install: true,
loader: false,
reload: false,
uninstall: false,
update: false
}
}
this.scope.$root.packages[val.name] = resultItem;
} else {
resultItem = <IPackage>this.scope.$root.packages[val.name];
}
searchResults.push(resultItem);
});
callback(searchResults);
});
}
}
getPackageDetailInfo(packageName: string, callback: any) {
const pack: IPackageExplorer = <IPackageExplorer>this.scope.$root.activePackageExplorerItem;
if (pack.packageManager === 'npm') {
new NpmService().getPackageDetailInfo(packageName, (result: any) => {
const packDetail: IPackageDetail = {
name: result.name,
versions: result.versions.reverse()
}
callback(packDetail);
})
}
else if (pack.packageManager === 'bower') {
new BowerService().getPackageDetailInfo(packageName, (result: any) => {
const packDetail: IPackageDetail = {
name: result.name,
versions: result.versions
}
callback(packDetail);
});
}
}
//Get readme content
// getReadMeContent(packageName: string, version: string, callback: any) {
// const pack: IPackageExplorer = <IPackageExplorer>this.scope.$root.activePackageExplorerItem;
// // if (pack.packageManager === 'npm' || pack.packageManager === 'bower') {
// // getPackageReadme(packageName, (err: any, readMe: any) => {
// // if (err || readMe == undefined) {
// // callback('__empty__');
// // } else {
// // callback(new mdToHtml.Converter().makeHtml(readMe));
// // }
// // });
// // }
// if (pack.packageManager === 'bower') {
// new BowerService().getReadMeContent(packageName, version, (result: any) => {
// if (result !== undefined) {
// callback(new mdToHtml.Converter().makeHtml(result));
// } else {
// callback('__empty__');
// }
// });
// }
// }
getPackageDetailByVersion(packageName: string, version: string, callback: any) {
const pack: IPackageExplorer = <IPackageExplorer>this.scope.$root.activePackageExplorerItem;
if (pack.packageManager === 'npm') {
new NpmService().getPackageDetailInfoByVersion(packageName, version, (log: any, readMe: any) => {
const packDetail: IPackageDetail = {
name: packageName,
version: version,
author: log.author,
contributors: log.contributors,
dependencies: log.dependencies,
devDependencies: log.devDependencies,
description: log.description,
license: log.license
};
if (readMe !== undefined) {
callback(packDetail, new mdToHtml.Converter().makeHtml(readMe));
} else {
callback(packDetail, '__empty__');
}
});
} else if (pack.packageManager === 'bower') {
new BowerService().getPackageDetailByVersion(packageName, version, (log: any, readMe: any) => {
let packDetail: IPackageDetail = {
name: packageName,
version: version
};
if (log.data.pkgMeta !== undefined && log.data.pkgMeta !== null) {
packDetail.author = log.data.pkgMeta.author;
packDetail.contributors = log.data.pkgMeta.contributors;
packDetail.dependencies = log.data.pkgMeta.dependencies;
packDetail.devDependencies = log.data.pkgMeta.devDependencies;
packDetail.description = log.data.pkgMeta.description;
packDetail.license = typeof log.data.pkgMeta.license === 'object' ? log.data.pkgMeta.license.type : log.data.pkgMeta.license;
packDetail.author = log.data.pkgMeta.author;
}
if (readMe !== undefined) {
callback(packDetail, new mdToHtml.Converter().makeHtml(readMe));
} else {
callback(packDetail, '__empty__');
}
})
}
}
runCommand(command: string, pack: IPackage, callback: any) {
let packageName: string = pack.name;
const version: string = pack.selectedVersion;
const isDevDependencies: boolean = pack.isDevDependencies;
_command = command;
if (command === 'reload') this.scope.$root.reloadPackageList();
if (command === 'install') {
if (version !== undefined && version !== null && version !== '') packageName += `||${version}`;
this.install([packageName], isDevDependencies, callback);
} else if (command === 'uninstall') {
this.uninstall([packageName], false, callback);
} else if (command === 'installAsDev') {
if (version !== undefined && version !== null && version !== '') packageName += `||${version}`;
this.install([packageName], true, callback);
} else if (command === 'update' || command === 'downgrade') {
if (version !== undefined && version !== null && version !== '') packageName += `||${version}`;
this.update([packageName], isDevDependencies, callback);
}
}
} | the_stack |
import { testTokenization } from '../test/testRunner';
testTokenization('pug', [
// Tags [Pug]
[
{
line: 'p 5',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 1, type: '' }
]
}
],
[
{
line: 'div#container.stuff',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 3, type: 'tag.id.pug' },
{ startIndex: 13, type: 'tag.class.pug' }
]
}
],
[
{
line: 'div.container#stuff',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 3, type: 'tag.class.pug' },
{ startIndex: 13, type: 'tag.id.pug' }
]
}
],
[
{
line: 'div.container#stuff .container',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 3, type: 'tag.class.pug' },
{ startIndex: 13, type: 'tag.id.pug' },
{ startIndex: 19, type: '' }
]
}
],
[
{
line: '#tag-id-1',
tokens: [{ startIndex: 0, type: 'tag.id.pug' }]
}
],
[
{
line: '.tag-id-1',
tokens: [{ startIndex: 0, type: 'tag.class.pug' }]
}
],
// Attributes - Single Line [Pug]
[
{
line: 'input(type="checkbox")',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 5, type: 'delimiter.parenthesis.pug' },
{ startIndex: 6, type: 'attribute.name.pug' },
{ startIndex: 10, type: 'delimiter.pug' },
{ startIndex: 11, type: 'attribute.value.pug' },
{ startIndex: 21, type: 'delimiter.parenthesis.pug' }
]
}
],
[
{
line: 'input (type="checkbox")',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 5, type: '' }
]
}
],
[
{
line: 'input(type="checkbox",name="agreement",checked)',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 5, type: 'delimiter.parenthesis.pug' },
{ startIndex: 6, type: 'attribute.name.pug' },
{ startIndex: 10, type: 'delimiter.pug' },
{ startIndex: 11, type: 'attribute.value.pug' },
{ startIndex: 21, type: 'attribute.delimiter.pug' },
{ startIndex: 22, type: 'attribute.name.pug' },
{ startIndex: 26, type: 'delimiter.pug' },
{ startIndex: 27, type: 'attribute.value.pug' },
{ startIndex: 38, type: 'attribute.delimiter.pug' },
{ startIndex: 39, type: 'attribute.name.pug' },
{ startIndex: 46, type: 'delimiter.parenthesis.pug' }
]
}
],
[
{
line: 'input(type="checkbox"',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 5, type: 'delimiter.parenthesis.pug' },
{ startIndex: 6, type: 'attribute.name.pug' },
{ startIndex: 10, type: 'delimiter.pug' },
{ startIndex: 11, type: 'attribute.value.pug' }
]
},
{
line: 'name="agreement"',
tokens: [
{ startIndex: 0, type: 'attribute.name.pug' },
{ startIndex: 4, type: 'delimiter.pug' },
{ startIndex: 5, type: 'attribute.value.pug' }
]
},
{
line: 'checked)',
tokens: [
{ startIndex: 0, type: 'attribute.name.pug' },
{ startIndex: 7, type: 'delimiter.parenthesis.pug' }
]
},
{
line: 'body',
tokens: [{ startIndex: 0, type: 'tag.pug' }]
}
],
// Attributes - MultiLine [Pug]
[
{
line: 'input(type="checkbox"',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 5, type: 'delimiter.parenthesis.pug' },
{ startIndex: 6, type: 'attribute.name.pug' },
{ startIndex: 10, type: 'delimiter.pug' },
{ startIndex: 11, type: 'attribute.value.pug' }
]
},
{
line: 'disabled',
tokens: [{ startIndex: 0, type: 'attribute.name.pug' }]
},
{
line: 'checked)',
tokens: [
{ startIndex: 0, type: 'attribute.name.pug' },
{ startIndex: 7, type: 'delimiter.parenthesis.pug' }
]
},
{
line: 'body',
tokens: [{ startIndex: 0, type: 'tag.pug' }]
}
],
// Interpolation [Pug]
[
{
line: 'p print #{count} lines',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 1, type: '' },
{ startIndex: 8, type: 'interpolation.delimiter.pug' },
{ startIndex: 10, type: 'interpolation.pug' },
{ startIndex: 15, type: 'interpolation.delimiter.pug' },
{ startIndex: 16, type: '' }
]
}
],
[
{
line: 'p print "#{count}" lines',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 1, type: '' },
{ startIndex: 9, type: 'interpolation.delimiter.pug' },
{ startIndex: 11, type: 'interpolation.pug' },
{ startIndex: 16, type: 'interpolation.delimiter.pug' },
{ startIndex: 17, type: '' }
]
}
],
[
{
line: '{ key: 123 }',
tokens: [
{ startIndex: 0, type: 'delimiter.curly.pug' },
{ startIndex: 1, type: '' },
{ startIndex: 5, type: 'delimiter.pug' },
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'number.pug' },
{ startIndex: 10, type: '' },
{ startIndex: 11, type: 'delimiter.curly.pug' }
]
}
],
// Comments - Single Line [Pug]
[
{
line: '// html#id1.class1',
tokens: [{ startIndex: 0, type: 'comment.pug' }]
}
],
[
{
line: 'body hello // not a comment 123',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 4, type: '' }
]
}
],
// Comments - MultiLine [Pug]
[
{
line: '//',
tokens: [{ startIndex: 0, type: 'comment.pug' }]
},
{
line: ' should be a comment',
tokens: [{ startIndex: 0, type: 'comment.pug' }]
},
{
line: ' should still be a comment',
tokens: [{ startIndex: 0, type: 'comment.pug' }]
},
{
line: 'div should not be a comment',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 3, type: '' }
]
}
],
// Code [Pug]
[
{
line: '- var a = 1',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 2, type: 'keyword.var.pug' },
{ startIndex: 5, type: '' },
{ startIndex: 8, type: 'delimiter.pug' },
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'number.pug' }
]
}
],
[
{
line: 'each item in items',
tokens: [
{ startIndex: 0, type: 'keyword.each.pug' },
{ startIndex: 4, type: '' },
{ startIndex: 10, type: 'keyword.in.pug' },
{ startIndex: 12, type: '' }
]
}
],
[
{
line: '- var html = "<script></script>"',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 2, type: 'keyword.var.pug' },
{ startIndex: 5, type: '' },
{ startIndex: 11, type: 'delimiter.pug' },
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'string.pug' }
]
}
],
// Generated from sample
[
{
line: 'doctype 5',
tokens: [
{ startIndex: 0, type: 'keyword.doctype.pug' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'number.pug' }
]
},
{
line: 'html(lang="en")',
tokens: [
{ startIndex: 0, type: 'tag.pug' },
{ startIndex: 4, type: 'delimiter.parenthesis.pug' },
{ startIndex: 5, type: 'attribute.name.pug' },
{ startIndex: 9, type: 'delimiter.pug' },
{ startIndex: 10, type: 'attribute.value.pug' },
{ startIndex: 14, type: 'delimiter.parenthesis.pug' }
]
},
{
line: ' head',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 4, type: 'tag.pug' }
]
},
{
line: ' title= pageTitle',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 8, type: 'tag.pug' },
{ startIndex: 13, type: '' }
]
},
{
line: " script(type='text/javascript')",
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 8, type: 'tag.pug' },
{ startIndex: 14, type: 'delimiter.parenthesis.pug' },
{ startIndex: 15, type: 'attribute.name.pug' },
{ startIndex: 19, type: 'delimiter.pug' },
{ startIndex: 20, type: 'attribute.value.pug' },
{ startIndex: 37, type: 'delimiter.parenthesis.pug' }
]
},
{
line: ' if (foo) {',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 12, type: 'keyword.if.pug' },
{ startIndex: 14, type: '' },
{ startIndex: 15, type: 'delimiter.parenthesis.pug' },
{ startIndex: 16, type: '' },
{ startIndex: 19, type: 'delimiter.parenthesis.pug' },
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'delimiter.curly.pug' }
]
},
{
line: ' bar()',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 19, type: 'delimiter.parenthesis.pug' }
]
},
{
line: ' }',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 12, type: 'delimiter.curly.pug' }
]
},
{
line: ' body',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 4, type: 'tag.pug' }
]
},
{
line: ' // Disclaimer: You will need to turn insertSpaces to true in order for the',
tokens: [{ startIndex: 0, type: 'comment.pug' }]
},
{
line: ' syntax highlighting to kick in properly (especially for comments)',
tokens: [{ startIndex: 0, type: 'comment.pug' }]
},
{
line: ' Enjoy :)',
tokens: [{ startIndex: 0, type: 'comment.pug' }]
},
{
line: ' h1 Pug - node template engine if in',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 8, type: 'tag.pug' },
{ startIndex: 10, type: '' }
]
},
{
line: ' p.',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 8, type: 'tag.pug' },
{ startIndex: 9, type: 'delimiter.pug' }
]
},
{
line: ' text ',
tokens: [{ startIndex: 0, type: '' }]
},
{
line: ' text',
tokens: [{ startIndex: 0, type: '' }]
},
{
line: ' #container',
tokens: [{ startIndex: 0, type: '' }]
},
{
line: ' #container',
tokens: [{ startIndex: 0, type: '' }]
},
{
line: ' #container',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 8, type: 'tag.id.pug' }
]
},
{
line: ' if youAreUsingPug',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 10, type: 'keyword.if.pug' },
{ startIndex: 12, type: '' }
]
},
{
line: ' p You are amazing',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 12, type: 'tag.pug' },
{ startIndex: 13, type: '' }
]
},
{
line: ' else',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 10, type: 'keyword.else.pug' }
]
},
{
line: ' p Get on it!',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 12, type: 'tag.pug' },
{ startIndex: 13, type: '' }
]
},
{
line: ' p Text can be included in a number of different ways.',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 5, type: 'tag.pug' },
{ startIndex: 6, type: '' }
]
}
]
]); | the_stack |
declare namespace AMap {
namespace Map {
type Feature = 'bg' | 'point' | 'road' | 'building';
type ViewMode = '2D' | '3D';
interface Options {
/**
* 地图视口,用于控制影响地图静态显示的属性
*/
view?: View2D | undefined;
/**
* 地图图层数组,数组可以是图层 中的一个或多个,默认为普通二维地图
*/
layers?: Layer[] | undefined;
/**
* 地图显示的缩放级别
*/
zoom?: number | undefined;
/**
* 地图中心点坐标值
*/
center?: LocationValue | undefined;
/**
* 地图标注显示顺序
*/
labelzIndex?: number | undefined;
/**
* 地图显示的缩放级别范围
*/
zooms?: [number, number] | undefined;
/**
* 地图语言类型
*/
lang?: Lang | undefined;
/**
* 地图默认鼠标样式
*/
defaultCursor?: string | undefined;
/**
* 地图显示的参考坐标系
*/
crs?: 'EPSG3857' | 'EPSG3395' | 'EPSG4326' | undefined;
/**
* 地图平移过程中是否使用动画
*/
animateEnable?: boolean | undefined;
/**
* 是否开启地图热点和标注的hover效果
*/
isHotspot?: boolean | undefined;
/**
* 当前地图中默认显示的图层
*/
defaultLayer?: TileLayer | undefined;
/**
* 地图是否可旋转
*/
rotateEnable?: boolean | undefined;
/**
* 是否监控地图容器尺寸变化
*/
resizeEnable?: boolean | undefined;
/**
* 是否在有矢量底图的时候自动展示室内地图
*/
showIndoorMap?: boolean | undefined;
/**
* 在展示矢量图的时候自动展示室内地图图层
*/
// indoorMap?: IndorMap
/**
* 是否支持可以扩展最大缩放级别
*/
expandZoomRange?: boolean | undefined;
/**
* 地图是否可通过鼠标拖拽平移
*/
dragEnable?: boolean | undefined;
/**
* 地图是否可缩放
*/
zoomEnable?: boolean | undefined;
/**
* 地图是否可通过双击鼠标放大地图
*/
doubleClickZoom?: boolean | undefined;
/**
* 地图是否可通过键盘控制
*/
keyboardEnable?: boolean | undefined;
/**
* 地图是否使用缓动效果
*/
jogEnable?: boolean | undefined;
/**
* 地图是否可通过鼠标滚轮缩放浏览
*/
scrollWheel?: boolean | undefined;
/**
* 地图在移动终端上是否可通过多点触控缩放浏览地图
*/
touchZoom?: boolean | undefined;
/**
* 当touchZoomCenter=1的时候,手机端双指缩放的以地图中心为中心,否则默认以双指中间点为中心
*/
touchZoomCenter?: number | undefined;
/**
* 设置地图的显示样式
*/
mapStyle?: string | undefined;
/**
* 设置地图上显示的元素种类
*/
features?: Feature[] | 'all' | Feature | undefined;
/**
* 设置地图显示3D楼块效果
*/
showBuildingBlock?: boolean | undefined;
/**
* 视图模式
*/
viewMode?: ViewMode | undefined;
/**
* 俯仰角度
*/
pitch?: number | undefined;
/**
* 是否允许设置俯仰角度
*/
pitchEnable?: boolean | undefined;
/**
* 楼块出现和消失的时候是否显示动画过程
*/
buildingAnimation?: boolean | undefined;
/**
* 调整天空颜色
*/
skyColor?: string | undefined;
/**
* 设置地图的预加载模式
*/
preloadMode?: boolean | undefined;
/**
* 为 Map 实例指定掩模的路径,各图层将只显示路径范围内图像
*/
mask?: Array<[number, number]> | Array<Array<[number, number]>> | Array<Array<Array<[number, number]>>> | undefined;
maxPitch?: number | undefined;
rotation?: number | undefined;
forceVector?: boolean | undefined;
// internal
baseRender?: 'vw' | 'd' | 'dv' | 'v' | undefined;
overlayRender?: 'c' | 'd' | undefined;
showLabel?: boolean | undefined;
gridMapForeign?: boolean | undefined;
logoUrl?: string | undefined;
logoUrlRetina?: string | undefined;
copyright?: string | undefined;
turboMode?: boolean | undefined;
workerMode?: boolean | undefined;
// continuousZoomEnable?: boolean;
// showFog: boolean;
// yaw: number;
// scale: number;
// detectRetina: number;
}
interface Status {
/**
* 是否开启动画
*/
animateEnable: boolean;
/**
* 是否双击缩放
*/
doubleClickZoom: boolean;
/**
* 是否支持拖拽
*/
dragEnable: boolean;
isHotspot: boolean;
/**
* 是否开启缓动效果
*/
jogEnable: boolean;
/**
* 是否支持键盘
*/
keyboardEnable: boolean;
/**
* 是否支持调整俯仰角
*/
pitchEnable: boolean;
resizeEnable: boolean;
/**
* 是否支持旋转
*/
rotateEnable: boolean;
/**
* 是否支持滚轮缩放
*/
scrollWheel: boolean;
/**
* 是否支持触摸缩放
*/
touchZoom: boolean;
/**
* 是否支持缩放
*/
zoomEnable: boolean;
}
type HotspotEvent<N extends string> = Event<N, {
/**
* 经纬度坐标
*/
lnglat: LngLat;
/**
* 热点名称
*/
name: string;
/**
* 热点id
*/
id: string;
// internal
/**
* 是否室内热点
*/
isIndoorPOI: boolean;
}>;
interface EventMap {
click: MapsEvent<'click', Map>;
dblclick: MapsEvent<'dblclick', Map>;
rightclick: MapsEvent<'rightclick', Map>;
rdblclick: MapsEvent<'rdblclick', Map>;
mouseup: MapsEvent<'mouseup', Map>;
mousedown: MapsEvent<'mousedown', Map>;
mousemove: MapsEvent<'mousemove', Map>;
mousewheel: MapsEvent<'mousewheel', Map>;
mouseover: MapsEvent<'mouseover', Map>;
mouseout: MapsEvent<'mouseout', Map>;
touchstart: MapsEvent<'touchstart', Map>;
touchmove: MapsEvent<'touchmove', Map>;
touchend: MapsEvent<'touchend', Map>;
contextmenu: MapsEvent<'contextmenu', Map>;
hotspotclick: HotspotEvent<'hotspotclick'>;
hotspotover: HotspotEvent<'hotspotover'>;
hotspotout: HotspotEvent<'hotspotout'>;
complete: Event<'complete'>;
mapmove: Event<'mapmove'>;
movestart: Event<'movestart'>;
moveend: Event<'moveend'>;
zoomchange: Event<'zoomchange'>;
zoomstart: Event<'zoomstart'>;
zoomend: Event<'zoomend'>;
dragstart: Event<'dragstart'>;
dragging: Event<'dragging'>;
dragend: Event<'dragend'>;
resize: Event<'resize'>;
}
}
class Map extends EventEmitter {
/**
* 构造一个地图对象
* @param container 地图容器的id或者是DOM元素
* @param opts 选项
*/
constructor(container: string | HTMLElement, opts?: Map.Options);
/**
* 唤起高德地图客户端marker页
* @param obj 唤起参数
*/
poiOnAMAP(obj: { id: string; location?: LocationValue | undefined; name?: string | undefined }): void;
/**
* 唤起高德地图客户端marker详情页
* @param obj 唤起参数
*/
detailOnAMAP(obj: { id: string; location?: LocationValue | undefined; name?: string | undefined }): void;
/**
* 获取当前地图缩放级别
*/
getZoom(): number;
/**
* 获取地图图层数组
*/
getLayers(): Layer[];
/**
* 获取地图中心点经纬度坐标值
*/
getCenter(): LngLat;
/**
* 返回地图对象的容器
*/
getContainer(): HTMLElement | null;
/**
* 获取地图中心点所在区域
*/
getCity(callback: (cityData: {
/**
* 市名称
*/
city: string;
/**
* 市代码
*/
citycode: string;
/**
* 区名称
*/
district: string;
/**
* 省
*/
province: string | never[]; // province is empty array when getCity fail
}) => void): void;
/**
* 获取当前地图视图范围,获取当前可视区域
*/
getBounds(): Bounds;
/**
* 获取当前地图标注的显示顺序
*/
getLabelzIndex(): number;
/**
* 获取Map的限制区域
*/
getLimitBounds(): Bounds;
/**
* 获取地图语言类型
*/
getLang(): Lang;
/**
* 获取地图容器像素大小
*/
getSize(): Size;
/**
* 获取地图顺时针旋转角度
*/
getRotation(): number;
/**
* 获取当前地图状态信息
*/
getStatus(): Map.Status;
/**
* 获取地图默认鼠标指针样式
*/
getDefaultCursor(): string;
/**
* 获取指定位置的地图分辨率
* @param point 指定经纬度
*/
getResolution(point?: LocationValue): number;
/**
* 获取当前地图比例尺
* @param dpi dpi
*/
getScale(dpi?: number): number;
/**
* 设置地图显示的缩放级别
* @param level 缩放级别
*/
setZoom(level: number): void;
/**
* 设置地图标注显示的顺序
* @param index 显示顺序
*/
setLabelzIndex(index: number): void;
/**
* 设置地图图层数组
* @param layers 图层数组
*/
setLayers(layers: Layer[]): void;
/**
* 添加覆盖物/图层
* @param overlay 覆盖物/图层
*/
add(overlay: Overlay | Overlay[]): void;
/**
* 删除覆盖物/图层
* @param overlay 覆盖物/图层
*/
remove(overlay: Overlay | Overlay[]): void;
/**
* 返回添加的覆盖物对象
* @param type 覆盖物类型
*/
getAllOverlays(type?: 'marker' | 'circle' | 'polyline' | 'polygon'): Overlay[];
/**
* 设置地图显示的中心点
* @param center 中心点经纬度
*/
setCenter(center: LocationValue): void;
/**
* 地图缩放至指定级别并以指定点为地图显示中心点
* @param zoomLevel 缩放等级
* @param center 缩放中心
*/
setZoomAndCenter(zoomLevel: number, center: LocationValue): void;
/**
* 按照行政区名称或adcode来设置地图显示的中心点。
* @param city 城市名称或城市编码
* @param callback 回调
*/
setCity(city: string, callback: (this: this, coord: [string, string], zoom: number) => void): void;
/**
* 指定当前地图显示范围
* @param bound 显示范围
*/
setBounds(bound: Bounds): Bounds;
/**
* 设置Map的限制区域
* @param bound 限制区域
*/
setLimitBounds(bound: Bounds): void;
/**
* 清除限制区域
*/
clearLimitBounds(): void;
/**
* 设置地图语言类型
* @param lang 语言类型
*/
setLang(lang: Lang): void;
/**
* 设置地图顺时针旋转角度,旋转原点为地图容器中心点
* @param rotation 旋转角度
*/
setRotation(rotation: number): void;
/**
* 设置当前地图显示状态
* @param status 状态
*/
setStatus(status: Partial<Map.Status>): void;
/**
* 设置鼠标指针默认样式
* @param cursor 指针样式
*/
setDefaultCursor(cursor: string): void;
/**
* 地图放大一级显示
*/
zoomIn(): void;
/**
* 地图缩小一级显示
*/
zoomOut(): void;
/**
* 地图中心点平移至指定点位置
* @param position 目标位置经纬度
*/
panTo(position: LocationValue): void;
/**
* 以像素为单位,沿x方向和y方向移动地图
* @param x 横向移动像素,向右为正
* @param y 纵向移动像素,向下为正
*/
panBy(x: number, y: number): void;
/**
* 根据地图上添加的覆盖物分布情况,自动缩放地图到合适的视野级别
* @param overlayList 覆盖物数组
* @param immediately 是否需要动画过程
* @param avoid 上下左右的像素避让宽度
* @param maxZoom 最大缩放级别
*/
setFitView(
overlayList?: Overlay | Overlay[],
immediately?: boolean,
avoid?: [number, number, number, number],
maxZoom?: number
): Bounds | false | undefined;
/**
* 删除地图上所有的覆盖物
*/
clearMap(): void;
/**
* 注销地图对象,并清空地图容器
*/
destroy(): void;
/**
* 加载插件,
* tips: 插件的类型定义不在本类型定义中给出,需要另行安装例如
* 3d地图:@types/amap-js-api-map3d
* 地区搜索:@types/amap-js-api-place-search
* @param name 插件名称
* @param callback 插件加载完成后的回调函数
*/
plugin(name: string | string[], callback: () => void): this;
/**
* 添加控件
* @param control 控件
*/
addControl(control: {}): void; // TODO
/**
* 移除控件
* @param control 控件
*/
removeControl(control: {}): void; // TODO
/**
* 清除地图上的信息窗体。
*/
clearInfoWindow(): void;
/**
* 平面地图像素坐标转换为地图经纬度坐标
* @param pixel 像素坐标
* @param level 缩放等级
*/
pixelToLngLat(pixel: Pixel, level?: number): LngLat;
/**
* 地图经纬度坐标转换为平面地图像素坐标
* @param lnglat 经纬度坐标
* @param level 缩放等级
*/
lnglatToPixel(lnglat: LocationValue, level?: number): Pixel;
/**
* 地图容器像素坐标转为地图经纬度坐标
* @param pixel 地图像素坐标
*/
containerToLngLat(pixel: Pixel): LngLat;
/**
* 地图经纬度坐标转为地图容器像素坐标
* @param lnglat 经纬度坐标
*/
lngLatToContainer(lnglat: LocationValue): Pixel;
/**
* 地图经纬度坐标转为地图容器像素坐标
* @param lnglat 经纬度坐标
*/
lnglatTocontainer(lnglat: LocationValue): Pixel;
/**
* 设置地图的显示样式
* @param style 地图样式
*/
setMapStyle(style: string): void;
/**
* 获取地图显示样式
*/
getMapStyle(): string;
/**
* 设置地图上显示的元素种类
* @param feature 元素
*/
setFeatures(feature: Map.Feature | Map.Feature[] | 'all'): void;
/**
* 获取地图显示元素种类
*/
getFeatures(): Map.Feature | Map.Feature[] | 'all';
/**
* 修改底图图层
* @param layer 图层
*/
setDefaultLayer(layer: TileLayer): void;
/**
* 设置俯仰角
* @param pitch 俯仰角
*/
setPitch(pitch: number): void;
/**
* 获取俯仰角
*/
getPitch(): number;
getViewMode_(): Map.ViewMode;
lngLatToGeodeticCoord(lnglat: LocationValue): Pixel;
geodeticCoordToLngLat(pixel: Pixel): LngLat;
}
} | the_stack |
import type { DidCommService, ConnectionRecord } from '../modules/connections'
import type { OutboundTransport } from '../transport/OutboundTransport'
import type { OutboundMessage, OutboundPackage, EncryptedMessage } from '../types'
import type { AgentMessage } from './AgentMessage'
import type { EnvelopeKeys } from './EnvelopeService'
import type { TransportSession } from './TransportService'
import { inject, Lifecycle, scoped } from 'tsyringe'
import { DID_COMM_TRANSPORT_QUEUE, InjectionSymbols } from '../constants'
import { ReturnRouteTypes } from '../decorators/transport/TransportDecorator'
import { AriesFrameworkError } from '../error'
import { Logger } from '../logger'
import { MessageRepository } from '../storage/MessageRepository'
import { MessageValidator } from '../utils/MessageValidator'
import { EnvelopeService } from './EnvelopeService'
import { TransportService } from './TransportService'
export interface TransportPriorityOptions {
schemes: string[]
restrictive?: boolean
}
@scoped(Lifecycle.ContainerScoped)
export class MessageSender {
private envelopeService: EnvelopeService
private transportService: TransportService
private messageRepository: MessageRepository
private logger: Logger
public readonly outboundTransports: OutboundTransport[] = []
public constructor(
envelopeService: EnvelopeService,
transportService: TransportService,
@inject(InjectionSymbols.MessageRepository) messageRepository: MessageRepository,
@inject(InjectionSymbols.Logger) logger: Logger
) {
this.envelopeService = envelopeService
this.transportService = transportService
this.messageRepository = messageRepository
this.logger = logger
this.outboundTransports = []
}
public registerOutboundTransport(outboundTransport: OutboundTransport) {
this.outboundTransports.push(outboundTransport)
}
public async packMessage({
keys,
message,
endpoint,
}: {
keys: EnvelopeKeys
message: AgentMessage
endpoint: string
}): Promise<OutboundPackage> {
const encryptedMessage = await this.envelopeService.packMessage(message, keys)
return {
payload: encryptedMessage,
responseRequested: message.hasAnyReturnRoute(),
endpoint,
}
}
private async sendMessageToSession(session: TransportSession, message: AgentMessage) {
this.logger.debug(`Existing ${session.type} transport session has been found.`, {
keys: session.keys,
})
if (!session.keys) {
throw new AriesFrameworkError(`There are no keys for the given ${session.type} transport session.`)
}
const encryptedMessage = await this.envelopeService.packMessage(message, session.keys)
await session.send(encryptedMessage)
}
public async sendPackage({
connection,
encryptedMessage,
options,
}: {
connection: ConnectionRecord
encryptedMessage: EncryptedMessage
options?: { transportPriority?: TransportPriorityOptions }
}) {
const errors: Error[] = []
// Try to send to already open session
const session = this.transportService.findSessionByConnectionId(connection.id)
if (session?.inboundMessage?.hasReturnRouting()) {
try {
await session.send(encryptedMessage)
return
} catch (error) {
errors.push(error)
this.logger.debug(`Sending packed message via session failed with error: ${error.message}.`, error)
}
}
// Retrieve DIDComm services
const { services, queueService } = await this.retrieveServicesByConnection(connection, options?.transportPriority)
if (this.outboundTransports.length === 0 && !queueService) {
throw new AriesFrameworkError('Agent has no outbound transport!')
}
// Loop trough all available services and try to send the message
for await (const service of services) {
this.logger.debug(`Sending outbound message to service:`, { service })
try {
for (const transport of this.outboundTransports) {
if (transport.supportedSchemes.includes(service.protocolScheme)) {
await transport.sendMessage({
payload: encryptedMessage,
endpoint: service.serviceEndpoint,
connectionId: connection.id,
})
break
}
}
return
} catch (error) {
this.logger.debug(
`Sending outbound message to service with id ${service.id} failed with the following error:`,
{
message: error.message,
error: error,
}
)
}
}
// We didn't succeed to send the message over open session, or directly to serviceEndpoint
// If the other party shared a queue service endpoint in their did doc we queue the message
if (queueService) {
this.logger.debug(`Queue packed message for connection ${connection.id} (${connection.theirLabel})`)
this.messageRepository.add(connection.id, encryptedMessage)
return
}
// Message is undeliverable
this.logger.error(`Message is undeliverable to connection ${connection.id} (${connection.theirLabel})`, {
message: encryptedMessage,
errors,
connection,
})
throw new AriesFrameworkError(`Message is undeliverable to connection ${connection.id} (${connection.theirLabel})`)
}
public async sendMessage(
outboundMessage: OutboundMessage,
options?: {
transportPriority?: TransportPriorityOptions
}
) {
const { connection, payload } = outboundMessage
const errors: Error[] = []
this.logger.debug('Send outbound message', {
message: payload,
connectionId: connection.id,
})
// Try to send to already open session
const session = this.transportService.findSessionByConnectionId(connection.id)
if (session?.inboundMessage?.hasReturnRouting(payload.threadId)) {
this.logger.debug(`Found session with return routing for message '${payload.id}' (connection '${connection.id}'`)
try {
await this.sendMessageToSession(session, payload)
return
} catch (error) {
errors.push(error)
this.logger.debug(`Sending an outbound message via session failed with error: ${error.message}.`, error)
}
}
// Retrieve DIDComm services
const { services, queueService } = await this.retrieveServicesByConnection(connection, options?.transportPriority)
// Loop trough all available services and try to send the message
for await (const service of services) {
try {
// Enable return routing if the
const shouldUseReturnRoute = !this.transportService.hasInboundEndpoint(connection.didDoc)
await this.sendMessageToService({
message: payload,
service,
senderKey: connection.verkey,
returnRoute: shouldUseReturnRoute,
connectionId: connection.id,
})
return
} catch (error) {
errors.push(error)
this.logger.debug(
`Sending outbound message to service with id ${service.id} failed with the following error:`,
{
message: error.message,
error: error,
}
)
}
}
// We didn't succeed to send the message over open session, or directly to serviceEndpoint
// If the other party shared a queue service endpoint in their did doc we queue the message
if (queueService) {
this.logger.debug(`Queue message for connection ${connection.id} (${connection.theirLabel})`)
const keys = {
recipientKeys: queueService.recipientKeys,
routingKeys: queueService.routingKeys || [],
senderKey: connection.verkey,
}
const encryptedMessage = await this.envelopeService.packMessage(payload, keys)
this.messageRepository.add(connection.id, encryptedMessage)
return
}
// Message is undeliverable
this.logger.error(`Message is undeliverable to connection ${connection.id} (${connection.theirLabel})`, {
message: payload,
errors,
connection,
})
throw new AriesFrameworkError(`Message is undeliverable to connection ${connection.id} (${connection.theirLabel})`)
}
public async sendMessageToService({
message,
service,
senderKey,
returnRoute,
connectionId,
}: {
message: AgentMessage
service: DidCommService
senderKey: string
returnRoute?: boolean
connectionId?: string
}) {
if (this.outboundTransports.length === 0) {
throw new AriesFrameworkError('Agent has no outbound transport!')
}
this.logger.debug(`Sending outbound message to service:`, { messageId: message.id, service })
const keys = {
recipientKeys: service.recipientKeys,
routingKeys: service.routingKeys || [],
senderKey,
}
// Set return routing for message if requested
if (returnRoute) {
message.setReturnRouting(ReturnRouteTypes.all)
}
try {
await MessageValidator.validate(message)
} catch (error) {
this.logger.error(
`Aborting sending outbound message ${message.type} to ${service.serviceEndpoint}. Message validation failed`,
{
errors: error,
message: message.toJSON(),
}
)
throw error
}
const outboundPackage = await this.packMessage({ message, keys, endpoint: service.serviceEndpoint })
outboundPackage.endpoint = service.serviceEndpoint
outboundPackage.connectionId = connectionId
for (const transport of this.outboundTransports) {
if (transport.supportedSchemes.includes(service.protocolScheme)) {
await transport.sendMessage(outboundPackage)
break
}
}
}
private async retrieveServicesByConnection(
connection: ConnectionRecord,
transportPriority?: TransportPriorityOptions
) {
this.logger.debug(`Retrieving services for connection '${connection.id}' (${connection.theirLabel})`, {
transportPriority,
})
// Retrieve DIDComm services
const allServices = this.transportService.findDidCommServices(connection)
//Separate queue service out
let services = allServices.filter((s) => !isDidCommTransportQueue(s.serviceEndpoint))
const queueService = allServices.find((s) => isDidCommTransportQueue(s.serviceEndpoint))
//If restrictive will remove services not listed in schemes list
if (transportPriority?.restrictive) {
services = services.filter((service) => {
const serviceSchema = service.protocolScheme
return transportPriority.schemes.includes(serviceSchema)
})
}
//If transport priority is set we will sort services by our priority
if (transportPriority?.schemes) {
services = services.sort(function (a, b) {
const aScheme = a.protocolScheme
const bScheme = b.protocolScheme
return transportPriority?.schemes.indexOf(aScheme) - transportPriority?.schemes.indexOf(bScheme)
})
}
this.logger.debug(
`Retrieved ${services.length} services for message to connection '${connection.id}'(${connection.theirLabel})'`
)
return { services, queueService }
}
}
export function isDidCommTransportQueue(serviceEndpoint: string): serviceEndpoint is typeof DID_COMM_TRANSPORT_QUEUE {
return serviceEndpoint === DID_COMM_TRANSPORT_QUEUE
} | the_stack |
import _ from "lodash";
import m from "mithril";
import Stream from "mithril/stream";
import {TaskJSON, Template} from "models/admin_templates/templates";
import {EnvironmentVariableJSON} from "models/environment_variables/types";
import {PipelineStructure} from "models/internal_pipeline_structure/pipeline_structure";
import {ArtifactJSON} from "models/pipeline_configs/artifact";
import {JobJSON} from "models/pipeline_configs/job";
import {StageJSON} from "models/pipeline_configs/stage";
import {TabJSON} from "models/pipeline_configs/tab";
import {ModelWithNameIdentifierValidator} from "models/shared/name_validation";
import {PluginInfos} from "models/shared/plugin_infos_new/plugin_info";
import * as Buttons from "views/components/buttons";
import {FlashMessage, MessageType} from "views/components/flash_message";
import {CheckboxField, SelectField, SelectFieldOptions, TextField} from "views/components/forms/input_fields";
import {Tree} from "views/components/hierarchy/tree";
import {KeyValuePair} from "views/components/key_value_pair";
import {Link} from "views/components/link";
import {Modal, Size} from "views/components/modal";
import {Tabs} from "views/components/tab";
import {Table} from "views/components/table";
import styles from "views/pages/admin_templates/modals.scss";
import {TaskWidget} from "views/pages/admin_templates/task_widget";
const inflection = require("lodash-inflection");
export class CreateTemplateModal extends Modal {
private readonly callback: (newTemplateName: string, basedOnPipeline?: string) => void;
private readonly template: ModelWithNameIdentifierValidator;
private readonly basedOnPipelineCheckbox: Stream<boolean>;
private readonly selectedPipeline: Stream<string>;
private readonly pipelines: string[];
constructor(pipelineStructure: PipelineStructure,
callback: (newTemplateName: string, basedOnPipeline?: string) => void) {
super();
this.callback = callback;
this.template = new ModelWithNameIdentifierValidator();
this.basedOnPipelineCheckbox = Stream<boolean>(false);
this.selectedPipeline = Stream<string>();
this.pipelines = pipelineStructure.getAllConfigPipelinesNotUsingTemplates().sort((a, b) => {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
}
body() {
return (
<div>
<TextField property={this.template.name}
errorText={this.template.errors().errorsForDisplay("name")}
onchange={() => this.template.validate("name")}
required={true}
label={"Template name"}/>
<CheckboxField property={this.basedOnPipelineCheckbox}
label={"Extract from pipeline"}
helpText={"If a pipeline is not selected, a template with a default stage and default job will be created. If a pipeline is selected, the template will use the stages from the pipeline and the pipeline itself will be modified to use this template."}/>
{this.maybeShowPipelines()}
</div>
);
}
buttons() {
const disabled = _.isEmpty(this.template.name()) ||
this.template.errors().hasErrors() ||
(this.basedOnPipelineCheckbox() && _.isEmpty(this.selectedPipeline()));
return [<Buttons.Primary data-test-id="button-create"
disabled={disabled}
onclick={this.create.bind(this)}>Create</Buttons.Primary>];
}
title(): string {
return "Create a new template";
}
private create() {
this.callback(this.template.name(), this.basedOnPipelineCheckbox() ? this.selectedPipeline() : undefined);
super.close();
}
private maybeShowPipelines() {
if (this.basedOnPipelineCheckbox()) {
return (
<SelectField property={this.selectedPipeline}
label={"Pipeline"}
helpText={"This pipeline will be modified to use the newly created template."}>
<SelectFieldOptions items={this.pipelines} selected={this.selectedPipeline()}/>
</SelectField>
);
}
}
}
export class ShowTemplateModal extends Modal {
private readonly template: string;
private readonly templateConfig: Stream<Template>;
private readonly pluginInfos: PluginInfos;
private selectedStage?: StageJSON;
private selectedJob?: JobJSON;
constructor(template: string, templateConfig: Stream<Template>, pluginInfos: PluginInfos) {
super(Size.large);
this.fixedHeight = true;
this.template = template;
this.templateConfig = templateConfig;
this.pluginInfos = pluginInfos;
this.templateConfig();
}
body() {
if (this.isLoading()) {
return undefined;
}
return (
<div class={styles.parent}>
<div data-test-id="stage-job-tree" class={styles.stageJobTree}>
{this.templateConfig().stages.map((eachStage) => {
const stageLink = (
<Link href="#" onclick={() => {
this.selectStage(eachStage);
return false;
}}>{eachStage.name}</Link>
);
return (
<Tree datum={stageLink}>
{eachStage.jobs.map((eachJob) => {
const jobLink = (
<Link href="#" onclick={() => {
this.selectJob(eachStage, eachJob);
return false;
}}>{eachJob.name}</Link>
);
return (
<Tree datum={jobLink}/>
);
})}
</Tree>);
})}
</div>
{this.showSelection()}
</div>
);
}
title(): string {
return `Showing template ${this.template}`;
}
private selectStage(eachStage: StageJSON) {
this.selectedStage = eachStage;
this.selectedJob = undefined;
}
private selectJob(eachStage: StageJSON, eachJob: JobJSON) {
this.selectedStage = eachStage;
this.selectedJob = eachJob;
}
private showSelection() {
if (!this.selectedJob && !this.selectedStage) {
this.selectStage(this.templateConfig().stages[0]);
}
if (this.selectedJob) {
return this.showJob(this.selectedStage!, this.selectedJob!);
}
return this.showStage(this.selectedStage!);
}
private showStage(stage: StageJSON) {
const stageProperties = new Map([
["Stage Type", stage.approval.type === "success" ? "On success" : "Manual"],
["Fetch Materials", this.yesOrNo(stage.fetch_materials)],
["Never Cleanup Artifacts", this.yesOrNo(stage.never_cleanup_artifacts)],
["Clean Working Directory", this.yesOrNo(stage.clean_working_directory)],
]);
return (
<div data-test-id={`selected-stage-${stage.name}`} class={styles.stageOrJob}>
Showing stage <em>{stage.name}</em>
<hr/>
<div class={styles.propertiesWrapper}>
<KeyValuePair data={stageProperties}/>
</div>
<Tabs
tabs={["Environment Variables", "Permissions"]}
contents={
[this.environmentVariables(stage.environment_variables), this.stagePermissions(stage)]}/>
</div>
);
}
private showJob(stage: StageJSON, job: JobJSON) {
const jobProperties = new Map<string, any>([
["Resources", _.isEmpty(job.resources) ? null : job.resources.join(", ")],
["Elastic Profile ID", job.elastic_profile_id],
["Job Timeout", (this.jobTimeout(job))],
["Run type", this.jobRunType(job)],
]);
return (
<div data-test-id={`selected-job-${stage.name}-${job.name}`} class={styles.stageOrJob}>
Showing job <em>{stage.name}</em> > <em>{job.name}</em>
<hr/>
<div className={styles.propertiesWrapper}>
<KeyValuePair data={jobProperties}/>
</div>
<Tabs
tabs={["Tasks", "Artifacts", "Environment Variables", "Custom Tabs"]}
contents={[this.tasks(job.tasks), this.artifacts(job.artifacts), this.environmentVariables(job.environment_variables), this.tabs(
job.tabs)]}/>
</div>
);
}
private jobTimeout(job: JobJSON) {
let timeout: any;
if (_.isNil(job.timeout)) {
timeout = "Use server default";
} else if (job.timeout === 0) {
timeout = "Never timeout";
} else {
timeout = `Cancel after ${job.timeout} ${inflection.pluralize("minute", job.timeout)} of inactivity`;
}
return timeout;
}
private jobRunType(job: JobJSON) {
if (job.run_instance_count === "all") {
return "Run on all agents";
} else if (job.run_instance_count === 0) {
return `Run on ${job.run_instance_count} agents`;
} else {
return `Run on 1 agent`;
}
}
private yesOrNo(b: boolean) {
return b ? "Yes" : "No";
}
private environmentVariables(variables: EnvironmentVariableJSON[]) {
if (_.isEmpty(variables)) {
return <FlashMessage message="No environment variables have been configured." type={MessageType.info}/>;
}
const data = new Map(variables.map((eachVar) => {
return [eachVar.name, eachVar.secure ? "******" : eachVar.value];
}));
return <KeyValuePair data={data}/>;
}
private stagePermissions(stage: StageJSON) {
const authorization = stage.approval.authorization;
const data = new Map<string, m.Children>();
if (authorization) {
if (authorization.users.length >= 1) {
data.set("Users", authorization.users.join(", "));
}
if (authorization.roles.length >= 1) {
data.set("Roles", authorization.roles.join(", "));
}
}
if (data.size === 0) {
return (
<FlashMessage
message="There is no authorization configured for this stage nor its pipeline group. Only GoCD administrators can operate this stage."
type={MessageType.info}/>
);
} else {
return <KeyValuePair data={data}/>;
}
}
private artifacts(artifacts: ArtifactJSON[]) {
if (_.isEmpty(artifacts)) {
return (<FlashMessage message="No artifacts have been configured" type={MessageType.info}/>);
}
const artifactsGroupedByType = _.groupBy(artifacts,
(eachArtifact) => eachArtifact.type);
return [
this.buildArtifacts(artifactsGroupedByType.build),
this.testArtifacts(artifactsGroupedByType.test),
this.externalArtifacts(artifactsGroupedByType.external),
];
}
private tabs(tabs: TabJSON[]) {
if (_.isEmpty(tabs)) {
return (<FlashMessage message="No custom tabs have been configured" type={MessageType.info}/>);
}
const data = tabs.map((eachTab) => {
return [eachTab.name, eachTab.path];
});
return <Table headers={["Tab Name", "Path"]} data={data}/>;
}
private tasks(tasks: TaskJSON[]) {
if (_.isEmpty(tasks)) {
return (<FlashMessage message="No tasks have been configured" type={MessageType.info}/>);
}
return (
<div class={styles.taskList}>
{tasks.map((eachTask, index) => {
return (
<div data-test-id={`task-${index}`} class={styles.taskRow}>
<div class={styles.taskDescription}>
<TaskWidget pluginInfos={this.pluginInfos} task={eachTask}/>
</div>
<div class={styles.taskRunIf}>
Run if {eachTask.attributes.run_if.join(", ")}
</div>
</div>
);
})}
</div>
);
}
private buildArtifacts(artifacts: ArtifactJSON[]) {
if (_.isEmpty(artifacts)) {
return <FlashMessage message="No build artifacts have been configured" type={MessageType.info}/>;
}
const data = artifacts.map((eachArtifact) => {
return [eachArtifact.source, eachArtifact.destination];
});
return <Table caption="Build Artifacts" headers={["Source", "Destination"]} data={data}/>;
}
private testArtifacts(artifacts: ArtifactJSON[]) {
if (_.isEmpty(artifacts)) {
return <FlashMessage message="No test artifacts have been configured" type={MessageType.info}/>;
}
const data = artifacts.map((eachArtifact) => {
return [eachArtifact.source, eachArtifact.destination];
});
return <Table caption="Test Artifacts" headers={["Source", "Destination"]} data={data}/>;
}
private externalArtifacts(artifacts: ArtifactJSON[]) {
if (_.isEmpty(artifacts)) {
return <FlashMessage message="No external artifacts have been configured" type={MessageType.info}/>;
}
return [
<div>External Artifacts</div>,
artifacts.map((eachArtifact) => {
return this.externalArtifact(eachArtifact);
})
];
}
private externalArtifact(artifact: ArtifactJSON) {
const artifactInfo = new Map([["Artifact ID", artifact.artifact_id], ["Store ID", artifact.store_id]]);
const artifactConfig = new Map(artifact.configuration!.map((eachConfig) => {
return [eachConfig.key, eachConfig.value || "******"];
}));
return (
<div>
<KeyValuePair data={artifactInfo}/>
Configuration:
<div style="padding-left: 15px;">
<KeyValuePair data={artifactConfig}/>
</div>
</div>
);
}
} | the_stack |
import { animate, style, transition, trigger } from '@angular/animations'
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'
import { DOCUMENT } from '@angular/common'
import { Component, ElementRef, EventEmitter, Inject, Input, OnChanges, OnInit, Output, QueryList, SimpleChanges, ViewChild, ViewChildren } from '@angular/core'
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'
import { DomSanitizer } from '@angular/platform-browser'
import { first } from 'rxjs/operators'
import { EventService, FilterService, LocalStorageService, MapService, ObservationService, UserService } from 'src/app/upgrade/ajs-upgraded-providers'
import { ObservationEditFormPickerComponent } from './observation-edit-form-picker.component'
import * as moment from 'moment';
import { ObservationEditDiscardComponent } from './observation-edit-discard/observation-edit-discard.component'
import { MatSnackBar, MatSnackBarRef, SimpleSnackBar } from '@angular/material/snack-bar'
import { MatIconRegistry } from '@angular/material/icon'
import { MatDialog } from '@angular/material/dialog'
import { MatBottomSheet } from '@angular/material/bottom-sheet'
import { AttachmentService, AttachmentUploadEvent, AttachmentUploadStatus } from '../attachment/attachment.service'
import { FileUpload } from '../attachment/attachment-upload/attachment-upload.component'
import { AttachmentAction } from './observation-edit-attachment/observation-edit-attachment-action'
export type ObservationFormControl = FormControl & { definition: any }
@Component({
selector: 'observation-edit',
templateUrl: './observation-edit.component.html',
styleUrls: ['./observation-edit.component.scss'],
animations: [
trigger('error', [
transition(':enter', [
style({ height: 0, opacity: 0 }),
animate('250ms', style({ height: '*', opacity: 1 })),
]),
transition(':leave', [
animate('250ms', style({ height: 0, opacity: 0 }))
])
]),
trigger('mask', [
transition(':enter', [
style({ opacity: 0 }),
animate('250ms', style({ opacity: .2 })),
]),
transition(':leave', [
animate('250ms', style({ opacity: 0 }))
])
])
]
})
export class ObservationEditComponent implements OnInit, OnChanges {
@Input() preview: boolean
@Input() observation: any
attachments =[]
@Output() close = new EventEmitter<any>()
@ViewChild('editContent', { static: true }) editContent: ElementRef
@ViewChild('dragHandle', { static: true }) dragHandle: ElementRef
@ViewChildren('form') formElements: QueryList<ElementRef>
event: any
formGroup: FormGroup
formDefinitions: any
timestampDefinition = {
title: '',
type: 'date',
name: 'timestamp',
required: true
}
geometryDefinition = {
title: 'Location',
type: 'geometry',
name: 'geometry',
required: true
}
mask = false
saving = false
error: any
uploads: FileUpload[] = []
attachmentUrl: string
isNewObservation: boolean
canDeleteObservation: boolean
observationForm = {}
formOptions = { expand: false }
initialObservation: any
geometryStyle: any
primaryField: any
primaryFieldValue: string
secondaryField: any
secondaryFieldValue: string
formRemoveSnackbar: MatSnackBarRef<SimpleSnackBar>
constructor(
sanitizer: DomSanitizer,
matIconRegistry: MatIconRegistry,
public dialog: MatDialog,
private formBuilder: FormBuilder,
private bottomSheet: MatBottomSheet,
private snackBar: MatSnackBar,
private attachmentService: AttachmentService,
@Inject(DOCUMENT) private document: Document,
@Inject(MapService) private mapService: any,
@Inject(UserService) private userService: any,
@Inject(FilterService) private filterService: any,
@Inject(EventService) private eventService: any,
@Inject(ObservationService) private observationService: any,
@Inject(LocalStorageService) private localStorageService: any) {
matIconRegistry.addSvgIcon('handle', sanitizer.bypassSecurityTrustResourceUrl('assets/images/handle-24px.svg'));
}
ngOnInit(): void {
if (this.observation.id === 'new') {
this.formOptions.expand = true
}
this.canDeleteObservation = this.observation.id !== 'new' &&
(this.hasEventUpdatePermission() || this.isCurrentUsersObservation() || this.hasUpdatePermissionsInEventAcl())
this.attachmentService.upload$.subscribe(event => this.onAttachmentUpload(event))
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.observation && changes.observation.currentValue) {
this.event = this.eventService.getEventById(this.observation.eventId)
this.formDefinitions = this.eventService.getFormsForEvent(this.event).reduce((map, form) => {
map[form.id] = form
return map
}, {})
this.isNewObservation = this.observation.id === 'new'
this.initialObservation = JSON.parse(JSON.stringify(this.observation))
if (this.observation.style) {
this.geometryStyle = JSON.parse(JSON.stringify(this.observation.style))
}
if (this.isNewObservation) {
this.mapService.addFeaturesToLayer([this.observation], 'Observations')
}
this.toFormGroup(this.observation)
this.updatePrimarySecondary()
}
}
hasEventUpdatePermission(): boolean {
return this.userService.myself.role.permissions.includes('DELETE_OBSERVATION')
}
isCurrentUsersObservation(): boolean {
return this.observation.userId === this.userService.myself.id
}
hasUpdatePermissionsInEventAcl(): boolean {
const myAccess = this.filterService.getEvent().acl[this.userService.myself.id] || {}
const aclPermissions = myAccess.permissions || []
return aclPermissions.includes('update')
}
token(): string {
return this.localStorageService.getToken()
}
// TODO multi-form build out validators here as well for each form control
toFormGroup(observation: any): void {
const timestampControl = new FormControl(moment(observation.properties.timestamp).toDate(), Validators.required);
const geometryControl = new FormControl(observation.geometry, Validators.required);
const formArray = new FormArray([])
const observationForms = observation.properties.forms || []
observationForms.forEach(observationForm => {
const formDefinition = this.formDefinitions[observationForm.formId]
const fieldGroup = new FormGroup({
id: new FormControl(observationForm.id),
formId: new FormControl(formDefinition.id)
})
formDefinition.fields
.filter(field => !field.archived)
.sort((a, b) => a.id - b.id)
.forEach(field => {
const value = this.isNewObservation ? field.value : observationForm[field.name]
const fieldControl = new FormControl(value, field.required ? Validators.required : null)
fieldGroup.addControl(field.name, fieldControl)
})
formArray.push(fieldGroup)
})
this.formGroup = this.formBuilder.group({
id: observation.id,
eventId: new FormControl(observation.eventId),
type: new FormControl(observation.type),
geometry: geometryControl,
properties: new FormGroup({
timestamp: timestampControl,
forms: formArray
})
})
if (observation.properties.forms.length === 0 && this.hasForms() && observation.id === 'new') {
this.pickForm()
}
}
updatePrimarySecondary(): void {
const forms = this.formGroup.get('properties').get('forms') as FormArray
if (forms.length) {
const primaryFormGroup = forms.at(0) as FormGroup
const definition = this.formDefinitions[primaryFormGroup.get('formId').value]
let primaryFieldValue
if (primaryFormGroup.contains(definition.primaryFeedField)) {
this.primaryField = definition.fields.find(field => field.name === definition.primaryFeedField)
primaryFieldValue = primaryFormGroup.get(definition.primaryFeedField).value
}
let secondaryFieldValue
if (primaryFormGroup.contains(definition.secondaryFeedField)) {
this.secondaryField = definition.fields.find(field => field.name === definition.secondaryFeedField)
secondaryFieldValue = primaryFormGroup.get(definition.secondaryFeedField).value
}
if ((this.primaryField && primaryFieldValue !== this.primaryFieldValue) ||
((this.secondaryField && secondaryFieldValue !== this.secondaryFieldValue))) {
this.primaryFieldValue = this.primaryField ? primaryFieldValue : null
this.secondaryFieldValue = this.secondaryField ? secondaryFieldValue : null
const observation = this.formGroup.value
const style = this.observationService.getObservationStyleForForm(observation, this.event, definition)
observation.style = style
this.geometryStyle = style
this.mapService.updateFeatureForLayer(observation, 'Observations')
}
}
}
save(): void {
if (this.formRemoveSnackbar) {
this.formRemoveSnackbar.dismiss()
}
this.saving = true
this.uploads = []
// TODO look at this: this is a hack that will be corrected when we pull ids from the server
const form = this.formGroup.getRawValue()
const id = form.id;
if (form.id === 'new') {
delete form.id
}
this.eventService.saveObservation(form).then(observation => {
// If this feature was added to the map as a new observation, remove it
// as the event service will add it back to the map based on it new id
// if it passes the current filter.
if (id === 'new') {
this.mapService.removeFeatureFromLayer({ id: id }, 'Observations')
}
this.error = null
this.observation = observation
this.formGroup.get('id').setValue(observation.id)
form.properties.forms.forEach(form => {
const formDefinition = this.formDefinitions[form.formId];
Object.keys(form).forEach(fieldName => {
const fieldDefinition = formDefinition.fields.find(field => field.name === fieldName);
const value = form[fieldName];
if (fieldDefinition && fieldDefinition.type === 'attachment' && Array.isArray(value)) {
value.forEach(fieldAttachment => {
const attachment = observation.attachments.find(attachment => {
return !attachment.url &&
attachment.name === fieldAttachment.name &&
attachment.contentType == fieldAttachment.contentType
});
if (fieldAttachment.file && fieldAttachment.action === AttachmentAction.ADD && attachment) {
fieldAttachment.attachmentId = attachment.id
this.uploads.push(attachment)
}
})
}
})
})
if (this.uploads.length) {
this.attachmentUrl = observation.url
} else {
this.close.emit(this.observation)
}
}, err => {
this.formGroup.markAllAsTouched()
if (id === 'new') {
this.observation.id = 'new'
}
this.saving = false;
this.error = {
message: err.data.message
}
})
}
cancel(): void {
this.observation.geometry = this.initialObservation.geometry;
if (this.observation.id !== 'new') {
this.mapService.updateFeatureForLayer(this.observation, 'Observations')
} else {
this.mapService.removeFeatureFromLayer(this.observation, 'Observations')
}
if (this.formRemoveSnackbar) {
this.formRemoveSnackbar.dismiss()
}
this.dialog.open(ObservationEditDiscardComponent, {
width: '300px',
autoFocus: false,
position: { left: '75px' }
}).afterClosed().subscribe(result => {
if (result === 'discard') {
this.close.emit()
}
})
}
hasForms(): boolean {
const definitions = this.formDefinitions || {}
return Object.keys(definitions).length > 0
}
onGeometryEdit(event): void {
this.mask = event.action === 'edit';
if (this.mask) {
const elementBounds = event.source.nativeElement.getBoundingClientRect();
const parentBounds = this.editContent.nativeElement.getBoundingClientRect();
if (elementBounds.top < parentBounds.top || elementBounds.bottom > parentBounds.bottom) {
event.source.nativeElement.scrollIntoView({ behavior: "smooth", block: "nearest" });
}
}
}
pickForm(): void {
this.formOptions.expand = true
this.bottomSheet.open(ObservationEditFormPickerComponent, {
panelClass: 'feed-panel'
}).afterDismissed().subscribe(form => {
if (!form) return
const fieldsGroup = new FormGroup({
formId: new FormControl(form.id)
});
form.fields
.filter(field => !field.archived)
.sort((a, b) => a.id - b.id)
.forEach(field => {
const fieldControl = new FormControl(field.value, field.required ? Validators.required : null)
fieldsGroup.addControl(field.name, fieldControl)
});
(this.formGroup.get('properties').get('forms') as FormArray).push(fieldsGroup);
this.formElements.changes.pipe(first()).subscribe((queryList: QueryList<ElementRef>) => {
queryList.last.nativeElement.scrollIntoView({ behavior: 'smooth' })
})
})
}
removeForm(formGroup: FormGroup): void {
const formArray = this.formGroup.get('properties').get('forms') as FormArray
const index = formArray.controls.indexOf(formGroup)
formArray.removeAt(index)
this.formRemoveSnackbar = this.snackBar.open('Form Deleted', 'UNDO', {
duration: 5000,
panelClass: 'form-remove-snackbar',
})
this.formRemoveSnackbar.onAction().subscribe(() => {
formArray.insert(index, formGroup)
})
}
reorderForm(event: CdkDragDrop<any, any>): void {
if (event.currentIndex === event.previousIndex) return
const forms = (this.formGroup.get('properties').get('forms') as FormArray).controls
moveItemInArray(forms, event.previousIndex, event.currentIndex)
// re-calculate primary/secondary based new first form
if (event.currentIndex === 0 || event.previousIndex === 0) {
this.updatePrimarySecondary()
}
}
dragStart(event: DragEvent): void {
this.document.body.classList.add('item-drag')
}
dragEnd(event: DragEvent): void {
this.document.body.classList.remove('item-drag')
}
private onAttachmentUpload(event: AttachmentUploadEvent): void {
switch (event.status) {
case AttachmentUploadStatus.COMPLETE: {
this.eventService.addAttachmentToObservation(this.observation, event.response)
this.uploads = this.uploads.filter(attachment => attachment.id !== event.upload.attachmentId)
if (this.uploads.length === 0) {
this.saving = false
this.close.emit(this.observation)
}
break;
}
case AttachmentUploadStatus.ERROR: {
this.snackBar.open(event.response?.error, null, { duration: 4000 })
const formArray = this.formGroup.get('properties').get('forms') as FormArray
formArray.controls.forEach((formGroup: FormGroup) => {
const formId = formGroup.get('formId').value
const formDefinition = this.formDefinitions[formId];
Object.keys(formGroup.controls).forEach(fieldName => {
const fieldDefinition = formDefinition.fields.find(field => field.name === fieldName);
if (fieldDefinition && fieldDefinition.type === 'attachment') {
let attachments = formGroup.get(fieldName).value || []
attachments = attachments.filter(attachment => attachment.attachmentId !== event.upload.attachmentId)
formGroup.get(fieldName).setValue(attachments)
}
})
})
this.saving = false;
break;
}
}
}
} | the_stack |
import os = require("os");
import TelemetryClient = require("../Library/TelemetryClient");
import Constants = require("../Declarations/Constants");
class AutoCollectPerformance {
public static INSTANCE: AutoCollectPerformance;
private static _totalRequestCount: number = 0;
private static _totalFailedRequestCount: number = 0;
private static _totalDependencyCount: number = 0;
private static _totalFailedDependencyCount: number = 0;
private static _totalExceptionCount: number = 0;
private static _intervalDependencyExecutionTime: number = 0;
private static _intervalRequestExecutionTime: number = 0;
private _lastIntervalRequestExecutionTime: number = 0; // the sum of durations which took place during from app start until last interval
private _lastIntervalDependencyExecutionTime: number = 0;
private _enableLiveMetricsCounters: boolean;
private _collectionInterval: number;
private _client: TelemetryClient;
private _handle: NodeJS.Timer;
private _isEnabled: boolean;
private _isInitialized: boolean;
private _lastAppCpuUsage: { user: number, system: number };
private _lastHrtime: number[];
private _lastCpus: { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[];
private _lastDependencies: { totalDependencyCount: number; totalFailedDependencyCount: number; time: number; };
private _lastRequests: { totalRequestCount: number; totalFailedRequestCount: number; time: number; };
private _lastExceptions: { totalExceptionCount: number, time: number };
/**
* @param enableLiveMetricsCounters - enable sending additional live metrics information (dependency metrics, exception metrics, committed memory)
*/
constructor(client: TelemetryClient, collectionInterval = 60000, enableLiveMetricsCounters = false) {
if (!AutoCollectPerformance.INSTANCE) {
AutoCollectPerformance.INSTANCE = this;
}
this._lastRequests = { totalRequestCount: 0, totalFailedRequestCount: 0, time: 0 };
this._lastDependencies = { totalDependencyCount: 0, totalFailedDependencyCount: 0, time: 0 };
this._lastExceptions = { totalExceptionCount: 0,time: 0 };
this._isInitialized = false;
this._client = client;
this._collectionInterval = collectionInterval;
this._enableLiveMetricsCounters = enableLiveMetricsCounters;
}
public enable(isEnabled: boolean, collectionInterval?: number) {
this._isEnabled = isEnabled;
if (this._isEnabled && !this._isInitialized) {
this._isInitialized = true;
}
if (isEnabled) {
if (!this._handle) {
this._lastCpus = os.cpus();
this._lastRequests = {
totalRequestCount: AutoCollectPerformance._totalRequestCount,
totalFailedRequestCount: AutoCollectPerformance._totalFailedRequestCount,
time: +new Date
};
this._lastDependencies = {
totalDependencyCount: AutoCollectPerformance._totalDependencyCount,
totalFailedDependencyCount: AutoCollectPerformance._totalFailedDependencyCount,
time: +new Date
};
this._lastExceptions = {
totalExceptionCount: AutoCollectPerformance._totalExceptionCount,
time: +new Date
};
if (typeof (process as any).cpuUsage === 'function') {
this._lastAppCpuUsage = (process as any).cpuUsage();
}
this._lastHrtime = process.hrtime();
this._collectionInterval = collectionInterval || this._collectionInterval;
this._handle = setInterval(() => this.trackPerformance(), this._collectionInterval);
this._handle.unref(); // Allow the app to terminate even while this loop is going on
}
} else {
if (this._handle) {
clearInterval(this._handle);
this._handle = undefined;
}
}
}
public static countRequest(duration: number | string, success: boolean) {
let durationMs: number;
if (!AutoCollectPerformance.isEnabled()) {
return;
}
if (typeof duration === 'string') {
// dependency duration is passed in as "00:00:00.123" by autocollectors
durationMs = +new Date('1970-01-01T' + duration + 'Z'); // convert to num ms, returns NaN if wrong
} else if (typeof duration === 'number') {
durationMs = duration;
} else {
return;
}
AutoCollectPerformance._intervalRequestExecutionTime += durationMs;
if (success === false) {
AutoCollectPerformance._totalFailedRequestCount++;
}
AutoCollectPerformance._totalRequestCount++;
}
public static countException() {
AutoCollectPerformance._totalExceptionCount++;
}
public static countDependency(duration: number | string, success: boolean) {
let durationMs: number;
if (!AutoCollectPerformance.isEnabled()) {
return;
}
if (typeof duration === 'string') {
// dependency duration is passed in as "00:00:00.123" by autocollectors
durationMs = +new Date('1970-01-01T' + duration + 'Z'); // convert to num ms, returns NaN if wrong
} else if (typeof duration === 'number') {
durationMs = duration;
} else {
return;
}
AutoCollectPerformance._intervalDependencyExecutionTime += durationMs;
if (success === false) {
AutoCollectPerformance._totalFailedDependencyCount++;
}
AutoCollectPerformance._totalDependencyCount++;
}
public isInitialized() {
return this._isInitialized;
}
public static isEnabled() {
return AutoCollectPerformance.INSTANCE && AutoCollectPerformance.INSTANCE._isEnabled;
}
public trackPerformance() {
this._trackCpu();
this._trackMemory();
this._trackNetwork();
this._trackDependencyRate();
this._trackExceptionRate();
}
private _trackCpu() {
// this reports total ms spent in each category since the OS was booted, to calculate percent it is necessary
// to find the delta since the last measurement
var cpus = os.cpus();
if (cpus && cpus.length && this._lastCpus && cpus.length === this._lastCpus.length) {
var totalUser = 0;
var totalSys = 0;
var totalNice = 0;
var totalIdle = 0;
var totalIrq = 0;
for (var i = 0; !!cpus && i < cpus.length; i++) {
var cpu = cpus[i];
var lastCpu = this._lastCpus[i];
var name = "% cpu(" + i + ") ";
var model = cpu.model;
var speed = cpu.speed;
var times = cpu.times;
var lastTimes = lastCpu.times;
// user cpu time (or) % CPU time spent in user space
var user = (times.user - lastTimes.user) || 0;
totalUser += user;
// system cpu time (or) % CPU time spent in kernel space
var sys = (times.sys - lastTimes.sys) || 0;
totalSys += sys;
// user nice cpu time (or) % CPU time spent on low priority processes
var nice = (times.nice - lastTimes.nice) || 0;
totalNice += nice;
// idle cpu time (or) % CPU time spent idle
var idle = (times.idle - lastTimes.idle) || 0;
totalIdle += idle;
// irq (or) % CPU time spent servicing/handling hardware interrupts
var irq = (times.irq - lastTimes.irq) || 0;
totalIrq += irq;
}
// Calculate % of total cpu time (user + system) this App Process used (Only supported by node v6.1.0+)
let appCpuPercent: number = undefined;
if (typeof (process as any).cpuUsage === 'function') {
const appCpuUsage = (process as any).cpuUsage();
const hrtime = process.hrtime();
const totalApp = ((appCpuUsage.user - this._lastAppCpuUsage.user) + (appCpuUsage.system - this._lastAppCpuUsage.system)) || 0;
if (typeof this._lastHrtime !== 'undefined' && this._lastHrtime.length === 2) {
const elapsedTime = ((hrtime[0] - this._lastHrtime[0]) * 1e6 + (hrtime[1] - this._lastHrtime[1]) / 1e3) || 0; // convert to microseconds
appCpuPercent = 100 * totalApp / (elapsedTime * cpus.length);
}
// Set previous
this._lastAppCpuUsage = appCpuUsage;
this._lastHrtime = hrtime;
}
var combinedTotal = (totalUser + totalSys + totalNice + totalIdle + totalIrq) || 1;
this._client.trackMetric({ name: Constants.PerformanceCounter.PROCESSOR_TIME, value: ((combinedTotal - totalIdle) / combinedTotal) * 100 });
this._client.trackMetric({ name: Constants.PerformanceCounter.PROCESS_TIME, value: appCpuPercent || ((totalUser / combinedTotal) * 100) });
}
this._lastCpus = cpus;
}
private _trackMemory() {
var freeMem = os.freemem();
var usedMem = process.memoryUsage().rss;
var committedMemory = os.totalmem() - freeMem;
this._client.trackMetric({ name: Constants.PerformanceCounter.PRIVATE_BYTES, value: usedMem });
this._client.trackMetric({ name: Constants.PerformanceCounter.AVAILABLE_BYTES, value: freeMem });
// Only supported by quickpulse service
if (this._enableLiveMetricsCounters) {
this._client.trackMetric({ name: Constants.QuickPulseCounter.COMMITTED_BYTES, value: committedMemory });
}
}
private _trackNetwork() {
// track total request counters
var lastRequests = this._lastRequests;
var requests = {
totalRequestCount: AutoCollectPerformance._totalRequestCount,
totalFailedRequestCount: AutoCollectPerformance._totalFailedRequestCount,
time: +new Date
};
var intervalRequests = (requests.totalRequestCount - lastRequests.totalRequestCount) || 0;
var intervalFailedRequests = (requests.totalFailedRequestCount - lastRequests.totalFailedRequestCount) || 0;
var elapsedMs = requests.time - lastRequests.time;
var elapsedSeconds = elapsedMs / 1000;
var averageRequestExecutionTime = ((AutoCollectPerformance._intervalRequestExecutionTime - this._lastIntervalRequestExecutionTime) / intervalRequests) || 0; // default to 0 in case no requests in this interval
this._lastIntervalRequestExecutionTime = AutoCollectPerformance._intervalRequestExecutionTime // reset
if (elapsedMs > 0) {
var requestsPerSec = intervalRequests / elapsedSeconds;
var failedRequestsPerSec = intervalFailedRequests / elapsedSeconds;
this._client.trackMetric({ name: Constants.PerformanceCounter.REQUEST_RATE, value: requestsPerSec });
// Only send duration to live metrics if it has been updated!
if (!this._enableLiveMetricsCounters || intervalRequests > 0) {
this._client.trackMetric({ name: Constants.PerformanceCounter.REQUEST_DURATION, value: averageRequestExecutionTime });
}
// Only supported by quickpulse service
if (this._enableLiveMetricsCounters) {
this._client.trackMetric({ name: Constants.QuickPulseCounter.REQUEST_FAILURE_RATE, value: failedRequestsPerSec });
}
}
this._lastRequests = requests;
}
// Static counter is accumulated externally. Report the rate to client here
// Note: This is currently only used with QuickPulse client
private _trackDependencyRate() {
if (this._enableLiveMetricsCounters) {
var lastDependencies = this._lastDependencies;
var dependencies = {
totalDependencyCount: AutoCollectPerformance._totalDependencyCount,
totalFailedDependencyCount: AutoCollectPerformance._totalFailedDependencyCount,
time: +new Date
};
var intervalDependencies = (dependencies.totalDependencyCount - lastDependencies.totalDependencyCount) || 0;
var intervalFailedDependencies = (dependencies.totalFailedDependencyCount - lastDependencies.totalFailedDependencyCount) || 0;
var elapsedMs = dependencies.time - lastDependencies.time;
var elapsedSeconds = elapsedMs / 1000;
var averageDependencyExecutionTime = ((AutoCollectPerformance._intervalDependencyExecutionTime - this._lastIntervalDependencyExecutionTime) / intervalDependencies) || 0;
this._lastIntervalDependencyExecutionTime = AutoCollectPerformance._intervalDependencyExecutionTime // reset
if (elapsedMs > 0) {
var dependenciesPerSec = intervalDependencies / elapsedSeconds;
var failedDependenciesPerSec = intervalFailedDependencies / elapsedSeconds;
this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_RATE, value: dependenciesPerSec });
this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_FAILURE_RATE, value: failedDependenciesPerSec });
// redundant check for livemetrics, but kept for consistency w/ requests
// Only send duration to live metrics if it has been updated!
if (!this._enableLiveMetricsCounters || intervalDependencies > 0) {
this._client.trackMetric({ name: Constants.QuickPulseCounter.DEPENDENCY_DURATION, value: averageDependencyExecutionTime });
}
}
this._lastDependencies = dependencies;
}
}
// Static counter is accumulated externally. Report the rate to client here
// Note: This is currently only used with QuickPulse client
private _trackExceptionRate() {
if (this._enableLiveMetricsCounters) {
var lastExceptions = this._lastExceptions;
var exceptions = {
totalExceptionCount: AutoCollectPerformance._totalExceptionCount,
time: +new Date
};
var intervalExceptions = (exceptions.totalExceptionCount - lastExceptions.totalExceptionCount) || 0;
var elapsedMs = exceptions.time - lastExceptions.time;
var elapsedSeconds = elapsedMs / 1000;
if (elapsedMs > 0) {
var exceptionsPerSec = intervalExceptions / elapsedSeconds;
this._client.trackMetric({ name: Constants.QuickPulseCounter.EXCEPTION_RATE, value: exceptionsPerSec });
}
this._lastExceptions = exceptions;
}
}
public dispose() {
AutoCollectPerformance.INSTANCE = null;
this.enable(false);
this._isInitialized = false;
}
}
export = AutoCollectPerformance; | the_stack |
import { IQuestionsFilter, IQuestionItem, IPagedItems, ICurrentUser, IReplyItem, IPostItem } from "models";
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { DisplayMode } from "@microsoft/sp-core-library";
import { StandardFields, SortOption, PostFields, FormMode, Parameters, DiscussionType, MentionUtility, ApplicationPages} from "utilities";
import { IApplicationState } from "../reducers/appReducer";
import { HttpRequestError } from "@pnp/odata";
import { IEmailProperties } from '@pnp/sp/sputilities';
import { IPeoplePickerEntity } from '@pnp/sp/profiles';
import * as strings from 'QuestionsWebPartStrings';
import { ISiteUserProps } from "@pnp/sp/presets/all";
export enum IServiceCallState {
Warning = "Warning",
Error = "Error",
Information = "Information",
Success = "Success"
}
export interface IServiceCallStatus {
state: IServiceCallState;
display: boolean;
message: string;
}
// types of actions that can be performed
export enum ActionTypes {
UPDATE_THEMEVARIANT = 'UPDATE_THEMEVARIANT',
UPDATE_WEBPARTPROPERTY = 'UPDATE_WEBPARTPROPERTY',
UPDATE_WEBPARTCONTEXT = 'UPDATE_WEBPARTCONTEXT',
UPDATE_WEBPARTDISPLAYMODE = 'UPDATE_WEBPARTDISPLAYMODE',
UPDATE_SEARCHTEXT = 'UPDATE_SEARCHTEXT',
UPDATE_SHOWQUESTIONSOPTION = 'UPDATE_SHOWQUESTIONSOPTION',
GET_CURRENTUSER_START = 'GET_CURRENTUSER_START',
GET_CURRENTUSER_SUCCESSFUL = 'GET_CURRENTUSER_SUCCESSFUL',
UPDATE_CURRENTUSER = 'UPDATE_CURRENTUSER',
UPDATE_PAGED_QUESTIONS = 'UPDATE_PAGED_QUESTIONS',
LIKE_QUESTION_START = 'LIKE_QUESTION_START',
LIKE_QUESTION_SUCCESSFUL = 'LIKE_QUESTION_SUCCESSFUL',
FOLLOW_QUESTION_START = 'FOLLOW_QUESTION_START',
FOLLOW_QUESTION_SUCCESSFUL = 'FOLLOW_QUESTION_SUCCESSFUL',
LIKE_REPLY_START = 'LIKE_REPLY_START',
LIKE_REPLY_SUCCESSFUL = 'LIKE_REPLY_SUCCESSFUL',
HELPFUL_REPLY_START = 'HELPFUL_REPLY_START',
HELPFUL_REPLY_SUCCESSFUL = 'HELPFUL_REPLY_SUCCESSFUL',
CHANGE_DISCUSSION_TYPE_START = 'CHANGE_DISCUSSION_TYPE_START',
CHANGE_DISCUSSION_TYPE_SUCCESSFUL = 'CHANGE_DISCUSSION_TYPE_SUCCESSFUL',
GET_QUESTIONS_START = 'GET_QUESTIONS_START',
GET_QUESTIONS_FINISHED = 'GET_QUESTIONS_FINISHED',
GET_QUESTION_START = 'GET_QUESTION_START',
GET_QUESTION_FINISHED = 'GET_QUESTION_FINISHED',
UPDATE_SELECTED_QUESTION = 'UPDATE_SELECTED_QUESTION',
SELECTED_QUESTION_CHANGED = 'SELECTED_QUESTION_CHANGED',
DELETE_QUESTION_START = 'DELETE_QUESTION_START',
DELETE_QUESTION_SUCCESSFUL = 'DELETE_QUESTION_SUCCESSFUL',
SAVE_QUESTION_START = 'SAVE_QUESTION_START',
SAVE_QUESTION_SUCCESSFUL = 'SAVE_QUESTION_SUCCESSFUL',
GET_REPLY_START = 'GET_REPLY_START',
GET_REPLY_FINISHED = 'GET_REPLY_FINISHED',
DELETE_REPLY_START = 'DELETE_REPLY_START',
DELETE_REPLY_SUCCESSFUL = 'DELETE_REPLY_SUCCESSFUL',
SAVE_REPLY_START = 'SAVE_REPLY_START',
SAVE_REPLY_SUCCESSFUL = 'SAVE_REPLY_SUCCESSFUL',
REPLY_ANSWER_START = 'REPLY_ANSWER_START',
REPLY_ANSWER_SUCCESSFUL = 'REPLY_ANSWER_SUCCESSFUL',
UPDATE_APPLICATION_ERROR_MESSAGE = 'UPDATE_APPLICATION_ERROR_MESSAGE',
UPDATE_APPLICATION_SERVICE_CALL_STATUS = 'UPDATE_APPLICATION_SERVICE_CALL_STATUS',
UPLOAD_IMAGE_START = 'UPLOAD_IMAGE_START',
UPLOAD_IMAGE_SUCCESSFUL = 'UPLOAD_IMAGE_SUCCESSFUL',
SEARCH_PEOPLE_START = 'SEARCH_PEOPLE_START',
SEARCH_PEOPLE_SUCCESSFUL = 'SEARCH_PEOPLE_SUCCESSFUL',
UPDATE_PERSONAS_LIST = 'UPDATE_PERSONAS_LIST'
}
// contracts for those actions
export type Action =
{ type: ActionTypes.UPDATE_THEMEVARIANT, themeVariant: IReadonlyTheme | undefined } |
{ type: ActionTypes.UPDATE_WEBPARTPROPERTY, propertyName: string, propertyValue: any } |
{ type: ActionTypes.UPDATE_WEBPARTCONTEXT, webPartContext: WebPartContext } |
{ type: ActionTypes.UPDATE_WEBPARTDISPLAYMODE, displayMode: DisplayMode } |
{ type: ActionTypes.UPDATE_SEARCHTEXT, searchText: string } |
{ type: ActionTypes.UPDATE_SHOWQUESTIONSOPTION, option: string } |
{ type: ActionTypes.UPDATE_CURRENTUSER, currentUser: ICurrentUser } |
{ type: ActionTypes.UPDATE_APPLICATION_ERROR_MESSAGE, errorMessage: string } |
{ type: ActionTypes.UPDATE_APPLICATION_SERVICE_CALL_STATUS, serviceStatus: IServiceCallStatus } |
{ type: ActionTypes.GET_QUESTIONS_START } |
{
type: ActionTypes.UPDATE_PAGED_QUESTIONS,
currentPagedQuestions: IPagedItems<IQuestionItem> | null,
previousPagedQuestions: IPagedItems<IQuestionItem>[]
} |
{
type: ActionTypes.UPDATE_SELECTED_QUESTION,
selectedQuestion: IQuestionItem | null,
formMode: FormMode,
} |
{
type: ActionTypes.SELECTED_QUESTION_CHANGED,
selectedQuestionChanged: boolean
} |
{ type: ActionTypes.UPDATE_PERSONAS_LIST, people: IPeoplePickerEntity[] }
;
// functions for those actions
const simpleAction = (actionType: ActionTypes) => ({
type: actionType
});
export const updateThemeVariant = (themeVariant: IReadonlyTheme | undefined): Action => ({
type: ActionTypes.UPDATE_THEMEVARIANT,
themeVariant
});
export const updateWebPartProperty = (propertyName: string, propertyValue: any): Action => ({
type: ActionTypes.UPDATE_WEBPARTPROPERTY,
propertyName,
propertyValue
});
export const updateWebPartDisplayMode = (displayMode: DisplayMode): Action => ({
type: ActionTypes.UPDATE_WEBPARTDISPLAYMODE,
displayMode
});
export const updateWebPartContext = (webPartContext: WebPartContext): Action => ({
type: ActionTypes.UPDATE_WEBPARTCONTEXT,
webPartContext
});
const updateCurrentUser = (currentUser: ICurrentUser): Action => ({
type: ActionTypes.UPDATE_CURRENTUSER,
currentUser
});
const updateSearchText = (searchText: string): Action => ({
type: ActionTypes.UPDATE_SEARCHTEXT,
searchText
});
export const updateShowQuestionsOption = (option: string): Action => ({
type: ActionTypes.UPDATE_SHOWQUESTIONSOPTION,
option: option
});
const updateApplicationErrorMessage = (errorMessage: string): Action => ({
type: ActionTypes.UPDATE_APPLICATION_ERROR_MESSAGE,
errorMessage
});
const updateApplicationServiceCallStatus = (serviceStatus: IServiceCallStatus): Action => ({
type: ActionTypes.UPDATE_APPLICATION_SERVICE_CALL_STATUS,
serviceStatus
});
export function flashServiceStatus(message: string, state: IServiceCallState) {
return (dispatch) => {
dispatch(updateApplicationServiceCallStatus({ display: true, message: message, state: state }));
setTimeout(() => { dispatch(updateApplicationServiceCallStatus({ display: false, message: message, state: state })); }, 5000);
};
}
const updatePagedQuestions = (currentPagedQuestions: IPagedItems<IQuestionItem> | null,
previousPagedQuestions: IPagedItems<IQuestionItem>[]): Action => ({
type: ActionTypes.UPDATE_PAGED_QUESTIONS,
currentPagedQuestions,
previousPagedQuestions
});
export function searchPeople(input: string, maxCount: number) {
return async (dispatch, getState, { userService }) => {
let peopleFound: ISiteUserProps[];
dispatch(simpleAction(ActionTypes.SEARCH_PEOPLE_START));
peopleFound = await userService.searchPeople(input, maxCount)
.catch(e => {
let message = handleHttpError(e);
dispatch(updateApplicationErrorMessage(message));
});
dispatch(simpleAction(ActionTypes.SEARCH_PEOPLE_SUCCESSFUL));
return peopleFound;
};
}
export function searchPeoplePicker(input: string, maxCount: number) {
return async (dispatch, getState, { userService }) => {
let peopleFound: IPeoplePickerEntity[];
dispatch(simpleAction(ActionTypes.SEARCH_PEOPLE_START));
peopleFound = await userService.searchPeoplePicker(input, maxCount)
.catch(e => {
let message = handleHttpError(e);
dispatch(updateApplicationErrorMessage(message));
});
dispatch(simpleAction(ActionTypes.SEARCH_PEOPLE_SUCCESSFUL));
return peopleFound;
};
}
export function ensureUserInSite(email: string) {
return async (dispatch, getState, { userService }) => {
let response: boolean = await userService.ensureUserInSite(email)
.catch(e => {
let message = handleHttpError(e);
dispatch(updateApplicationErrorMessage(message));
});
return response;
};
}
export function searchQuestions(searchText: string, categoryFilter: string | null) {
return (dispatch) => {
dispatch(updateSearchText(searchText));
dispatch(updatePagedQuestions(null, []));
dispatch(getPagedQuestions(false, categoryFilter));
};
}
export function changeShowQuestionsOption(option: string, categoryFilter: string | null) {
return (dispatch) => {
dispatch(updateShowQuestionsOption(option));
dispatch(updatePagedQuestions(null, []));
dispatch(getPagedQuestions(false, categoryFilter));
};
}
const updateSelectedQuestion = (selectedQuestion: IQuestionItem | null, formMode: FormMode): Action => ({
type: ActionTypes.UPDATE_SELECTED_QUESTION,
selectedQuestion,
formMode
});
const selectedQuestionUpdated = (selectedQuestionChanged: boolean): Action => ({
type: ActionTypes.SELECTED_QUESTION_CHANGED,
selectedQuestionChanged
});
export function getPagedQuestions(goingToNextPage: boolean, categoryFilter: string | null) {
return async (dispatch, getState, { questionService }) => {
let currentUser = await dispatch(getCurrentUser());
const { pageSize, searchText, sortOption, selectedShowQuestionsOption, loadInitialPage, currentPagedQuestions, previousPagedQuestions, discussionType, selectedQuestionChanged } = getState();
if (loadInitialPage === true || (searchText && searchText.length > 2)) {
let orderByColumn: string = StandardFields.TITLE;
let orderByAscending: boolean = true;
switch (sortOption) {
case SortOption.MostRecent:
orderByColumn = StandardFields.CREATED;
orderByAscending = false;
break;
case SortOption.MostLiked:
orderByColumn = PostFields.LIKE_COUNT;
orderByAscending = false;
break;
}
let filter: IQuestionsFilter = {
pageSize: pageSize,
searchText: searchText,
orderByColumnName: orderByColumn,
orderByAscending: orderByAscending,
selectedShowQuestionsOption: selectedShowQuestionsOption,
category: categoryFilter,
discussionType: discussionType
};
if (currentPagedQuestions !== null && goingToNextPage === true) {
previousPagedQuestions.push(currentPagedQuestions);
}
dispatch(simpleAction(ActionTypes.GET_QUESTIONS_START));
let questions: any;
if(selectedQuestionChanged === true) {
filter.searchText = '';
questions = await questionService.getPagedQuestions(currentUser, filter, null)
.catch(e => {
let message = handleHttpError(e);
dispatch(updateApplicationErrorMessage(message));
});
dispatch(updatePagedQuestions(questions, []));
dispatch(updateSearchText(filter.searchText as string));
dispatch(selectedQuestionUpdated(false));
}
else {
questions = await questionService.getPagedQuestions(currentUser, filter, currentPagedQuestions)
.catch(e => {
let message = handleHttpError(e);
dispatch(updateApplicationErrorMessage(message));
});
dispatch(updatePagedQuestions(questions, previousPagedQuestions));
}
dispatch(simpleAction(ActionTypes.GET_QUESTIONS_FINISHED));
}
else {
// reset state of paged items
dispatch(updatePagedQuestions(null, []));
}
};
}
export function navigateToViewAll(categoryFilter: string | null) {
return (dispatch, getState) => {
const { webPartContext, applicationPage, useApplicationPage }: IApplicationState = getState();
if (useApplicationPage === true
&& webPartContext
&& applicationPage
&& applicationPage.endsWith('.aspx')) {
window.open(`${webPartContext.pageContext.web.absoluteUrl}/SitePages/${applicationPage}${(!(categoryFilter === null || categoryFilter ==='') ? '?Category=' + encodeURIComponent(categoryFilter) : '' )}`, '_blank');
}
else {
dispatch(updateWebPartProperty('loadInitialPage', true));
dispatch(updatePagedQuestions(null, []));
dispatch(updateSearchText(''));
dispatch(getPagedQuestions(false, categoryFilter));
}
};
}
export function getPrevPagedQuestions() {
return (dispatch, getState) => {
const { previousPagedQuestions } = getState();
let questions = previousPagedQuestions.pop();
dispatch(updatePagedQuestions(questions, previousPagedQuestions));
};
}
export function launchNewQuestion(initialTitle: string, category: string, type: DiscussionType) {
return (dispatch, getState) => {
const { webPartContext, applicationPage, useApplicationPage }: IApplicationState = getState();
if(webPartContext && applicationPage) {
const questionUrl = `${webPartContext.pageContext.web.absoluteUrl}/SitePages/${applicationPage}?${Parameters.QUESTIONID}=0&${Parameters.CATEGORY}=${encodeURIComponent(category)}&${Parameters.TYPE}=${encodeURIComponent(type)}`;
if (useApplicationPage === true
&& webPartContext
&& applicationPage
&& applicationPage.endsWith('.aspx')) {
window.open(questionUrl, '_blank');
}
else {
dispatch(inializeNewQuestion(initialTitle, category, type));
if(window.location.pathname.length > 0 &&
(window.location.pathname.toLowerCase().endsWith(ApplicationPages.QUESTIONS.toLowerCase()) ||
window.location.pathname.toLowerCase().endsWith(ApplicationPages.CONVERSATIONS.toLowerCase()))) {
window.history.replaceState({}, "", questionUrl);
}
}
}
};
}
export function launchQuestion(questionId?: number) {
return (dispatch, getState) => {
const { webPartContext, applicationPage, useApplicationPage }: IApplicationState = getState();
if(webPartContext && applicationPage) {
let questionUrl = `${webPartContext.pageContext.web.absoluteUrl}/SitePages/${applicationPage}?${Parameters.QUESTIONID}=${questionId}`;
//if the route contains a category, keep it in the URL
let queryParms = new URLSearchParams(window.location.search);
if (queryParms.has(Parameters.CATEGORY)) {
questionUrl = `${questionUrl}&${Parameters.CATEGORY}=${String(queryParms.get(Parameters.CATEGORY))}`;
}
if (useApplicationPage === true && applicationPage.endsWith('.aspx')) {
window.open(questionUrl, '_blank');
}
else {
dispatch(getSelectedQuestion(questionId));
// only attempt to update the url if we are on one of our application pages
if(window.location.pathname.length > 0 &&
(window.location.pathname.toLowerCase().endsWith(ApplicationPages.QUESTIONS.toLowerCase()) ||
window.location.pathname.toLowerCase().endsWith(ApplicationPages.CONVERSATIONS.toLowerCase()))) {
window.history.replaceState({}, "", questionUrl);
}
}
}
};
}
export function inializeNewQuestion(initialTitle: string, category: string, type: DiscussionType) {
return (dispatch, getState) => {
let newQuestion: IQuestionItem = {
id: 0,
title: initialTitle,
details: '',
detailsText: '',
likeCount: 0,
likeIds: [],
likedByCurrentUser: false,
followEmails: [],
followedByCurrentUser: false,
isAnswered: false,
totalReplyCount: 0,
canDelete: false,
canEdit: false,
canReact: false,
canReply: false,
replies: [],
category: category,
discussionType: type,
page: '',
attachments: [],
newAttachments: [],
removedAttachments: []
};
dispatch(updateSelectedQuestion(newQuestion, FormMode.New));
};
}
export function getSelectedQuestion(questionId?: number) {
return async (dispatch, getState, { questionService }) => {
let currentUser = await dispatch(getCurrentUser());
if (questionId && questionId > 0) {
dispatch(simpleAction(ActionTypes.GET_QUESTION_START));
let question = await questionService.getQuestionById(currentUser, questionId)
.catch(e => {
let message = handleHttpError(e);
if (e.status === 404) {
message = strings.ErrorMessage_HTTP_ItemNotFound;
}
dispatch(updateApplicationErrorMessage(message));
});
dispatch(updateSelectedQuestion(question, FormMode.View));
dispatch(simpleAction(ActionTypes.GET_QUESTION_FINISHED));
}
else {
dispatch(updateSelectedQuestion(null, FormMode.View));
const { webPartContext, applicationPage }: IApplicationState = getState();
if(webPartContext && applicationPage) {
/*
The risk in the below url is if a user launches to the Questions.aspx on a question with a category or see all for a web part with category we won't
preserve that, so new questions after below wouldn't keep it.
In testing we could try to utilize the category from the 'last question', however that also has risks when you see all with no category you
see all questions regardless of category so your last viewed question would impact what category is used on the next new category
*/
let questionUrl = `${webPartContext.pageContext.web.absoluteUrl}/SitePages/${applicationPage}`;
// check if category is in the URL and preserve it
let queryParms = new URLSearchParams(window.location.search);
if(queryParms.has(Parameters.CATEGORY)) {
questionUrl = `${questionUrl}?${Parameters.CATEGORY}=${String(queryParms.get(Parameters.CATEGORY))}`;
}
// only attempt to update the url if we are on one of our application pages
// this should only be invoked when the questions.tsx is closed, cancel edit or cancel on new
if(window.location.pathname.length > 0 &&
(window.location.pathname.toLowerCase().endsWith(ApplicationPages.QUESTIONS.toLowerCase()) ||
window.location.pathname.toLowerCase().endsWith(ApplicationPages.CONVERSATIONS.toLowerCase()))) {
window.history.replaceState({}, "", questionUrl);
}
}
}
};
}
// Delete question actions
export function deleteQuestion(question: IQuestionItem) {
return async (dispatch, getState, { questionService }) => {
if (question && question.id && question.id > 0) {
dispatch(simpleAction(ActionTypes.DELETE_QUESTION_START));
await questionService.deleteQuestion(question)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(simpleAction(ActionTypes.DELETE_QUESTION_SUCCESSFUL));
dispatch(selectedQuestionUpdated(true)); // so question list will know to refresh
dispatch(updateSelectedQuestion(null, FormMode.View));
}
};
}
export function likeQuestion(question: IQuestionItem) {
return async (dispatch, getState, { questionService }) => {
let currentUser = await dispatch(getCurrentUser());
if (question && question.id && question.id > 0) {
updateLiked(currentUser, question);
dispatch(simpleAction(ActionTypes.LIKE_QUESTION_START));
await questionService.updateLiked(question)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(getSelectedQuestion(question.id));
dispatch(simpleAction(ActionTypes.LIKE_QUESTION_SUCCESSFUL));
}
};
}
export function followQuestion(question: IQuestionItem) {
return async (dispatch, getState, { questionService }) => {
let currentUser = await dispatch(getCurrentUser());
if (question && question.id && question.id > 0) {
updateFollowed(currentUser, question);
dispatch(simpleAction(ActionTypes.FOLLOW_QUESTION_START));
await questionService.updateFollowed(question)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(getSelectedQuestion(question.id));
dispatch(simpleAction(ActionTypes.FOLLOW_QUESTION_SUCCESSFUL));
}
};
}
export function updateDiscussionType(question: IQuestionItem) {
return async (dispatch, getState, { questionService }) => {
if (question && question.id && question.id > 0) {
dispatch(simpleAction(ActionTypes.CHANGE_DISCUSSION_TYPE_START));
await questionService.updateDiscussionType(question)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(getSelectedQuestion(question.id));
dispatch(selectedQuestionUpdated(true)); // so question list will know to refresh
dispatch(simpleAction(ActionTypes.CHANGE_DISCUSSION_TYPE_SUCCESSFUL));
dispatch(flashServiceStatus("Discussion Type successfully updated.", IServiceCallState.Success));
}
};
}
// Save question action
export function isDuplicateQuestion(question: IQuestionItem) {
return async (dispatch, getState, { questionService }) => {
if (question) {
let isDuplicate = await questionService.isDuplicateQuestion(question)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
return isDuplicate;
}
};
}
export function saveQuestion(question: IQuestionItem) {
return async (dispatch, getState, { questionService }) => {
if (question) {
let currentUser = await dispatch(getCurrentUser());
dispatch(simpleAction(ActionTypes.SAVE_QUESTION_START));
// make sure user asking question is following by default for new questions
let isNewQuestion: boolean = false;
if (!question.id || question.id <= 0) {
question.followEmails.push(currentUser.email);
isNewQuestion = true;
//Special logic for page tracking on New Questions
//Essentially, if we are on the full page part, then store the referrer, unless it's null, undefined, empty or was the login page
//Otherwise, store the current page
var page = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
let trackCurrentPage: boolean = true;
const { applicationPage }: IApplicationState = getState();
if (page === applicationPage) {
trackCurrentPage = false;
}
if (trackCurrentPage === false) {
if (document.referrer !== null && document.referrer !== undefined && document.referrer.length > 0 && (document.referrer.search(/login.microsoftonline.com\//gi) === -1) ) {
question.page = document.referrer;
}
else {
// our application page should always be in site pages so lest split and just use the site url
question.page = window.location.href.search(/\/sitepages\//gi) !== -1 ? window.location.href.split(/\/sitepages\//gi)[0] : window.location.href;
}
}
else {
question.page = window.location.href.indexOf('?') !== -1 ? window.location.href.split('?')[0]: window.location.href;
}
}
let id = await questionService.saveQuestion(question)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(simpleAction(ActionTypes.SAVE_QUESTION_SUCCESSFUL));
dispatch(getSelectedQuestion(id));
dispatch(selectedQuestionUpdated(true)); // so question list will know to refresh
// TODO send notification to all follows and moderators on update
// TODO send notification to moderators for new
if (isNewQuestion === true) {
dispatch(createAndSendNewQuestionEmail(question, id));
//Send out mention notifications
const mentions = MentionUtility.parse(question.details);
if (mentions.length > 0) {
dispatch(createAndSendMentionReceiptEmail(question, id, mentions));
}
}
return id;
}
};
}
// REPLY actions
export function getReply(replyId: number) {
return async (dispatch, getState, { questionService }) => {
let currentUser = await dispatch(getCurrentUser());
if (replyId && replyId > 0) {
dispatch(simpleAction(ActionTypes.GET_REPLY_START));
let reply = await questionService.getReplyById(currentUser, replyId)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(simpleAction(ActionTypes.GET_REPLY_FINISHED));
return reply;
}
else {
dispatch(updateSelectedQuestion(null, FormMode.View));
}
};
}
export function deleteReply(reply: IReplyItem) {
return async (dispatch, getState, { questionService }) => {
if (reply && reply.id && reply.id > 0) {
dispatch(simpleAction(ActionTypes.DELETE_REPLY_START));
// Bug 16315 - if we are deleting a reply that has been marked as the answer then let's unmark it
// Bug 16328 - if we are deleting a reply and a child reply is the answer then let's unmark it
await dispatch(tryUnMarkAnswerOnDelete(reply));
await questionService.deleteReply(reply)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(simpleAction(ActionTypes.DELETE_REPLY_SUCCESSFUL));
if (reply.parentQuestionId) {
dispatch(getSelectedQuestion(reply.parentQuestionId));
}
}
};
}
export function saveReply(reply: IReplyItem) {
return async (dispatch, getState, { questionService, notificationService }) => {
if (reply) {
dispatch(simpleAction(ActionTypes.SAVE_REPLY_START));
let id = await questionService.saveReply(reply)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(simpleAction(ActionTypes.SAVE_REPLY_SUCCESSFUL));
if (reply.parentQuestionId) {
dispatch(getSelectedQuestion(reply.parentQuestionId));
}
dispatch(createAndSendReplyEmail(reply));
return id;
}
};
}
export function helpfulReply(reply: IReplyItem) {
return async (dispatch, getState, { questionService }) => {
let currentUser = await dispatch(getCurrentUser());
if (reply && reply.id && reply.id > 0) {
updateHelpful(currentUser, reply);
dispatch(simpleAction(ActionTypes.HELPFUL_REPLY_START));
await questionService.updateHelpful(reply)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(simpleAction(ActionTypes.HELPFUL_REPLY_SUCCESSFUL));
}
};
}
export function likeReply(reply: IReplyItem) {
return async (dispatch, getState, { questionService }) => {
let currentUser = await dispatch(getCurrentUser());
if (reply && reply.id && reply.id > 0) {
updateLiked(currentUser, reply);
dispatch(simpleAction(ActionTypes.LIKE_REPLY_START));
await questionService.updateLiked(reply)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(simpleAction(ActionTypes.LIKE_REPLY_SUCCESSFUL));
}
};
}
export function markAnswer(reply: IReplyItem) {
return async (dispatch, getState, { questionService }) => {
if (reply && reply.id && reply.id > 0) {
reply.isAnswer = !reply.isAnswer;
dispatch(simpleAction(ActionTypes.REPLY_ANSWER_START));
await questionService.markAnswer(reply)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(simpleAction(ActionTypes.REPLY_ANSWER_SUCCESSFUL));
if (reply.parentQuestionId) {
dispatch(getSelectedQuestion(reply.parentQuestionId));
dispatch(selectedQuestionUpdated(true)); // so question list will know to refresh
}
if (reply.isAnswer === true) {
dispatch(createAndSendMarkedAnswerEmail(reply));
}
}
};
}
export function tryUnMarkAnswerOnDelete(reply: IReplyItem) {
return async (dispatch, getState, { questionService }) => {
if (reply.isAnswer) {
await dispatch(markAnswer(reply));
}
else {
if (reply.replies) {
for (let childReply of reply.replies) {
await dispatch(tryUnMarkAnswerOnDelete(childReply));
}
}
}
};
}
function updateFollowed(currentUser: ICurrentUser, question: IQuestionItem) {
question.followedByCurrentUser = !question.followedByCurrentUser;
const index = question.followEmails.indexOf(currentUser.email);
if (question.followedByCurrentUser === true) {
if (index === -1) {
question.followEmails.push(currentUser.email);
}
}
else {
if (index > -1) {
question.followEmails.splice(index, 1);
}
}
}
function updateLiked(currentUser: ICurrentUser, post: IPostItem) {
post.likedByCurrentUser = !post.likedByCurrentUser;
let currentUserId = `${currentUser.id}`;
const index = post.likeIds.indexOf(currentUserId);
if (post.likedByCurrentUser === true) {
if (index === -1) {
post.likeIds.push(currentUserId);
}
}
else {
if (index > -1) {
post.likeIds.splice(index, 1);
}
}
}
function updateHelpful(currentUser: ICurrentUser, reply: IReplyItem) {
reply.helpfulByCurrentUser = !reply.helpfulByCurrentUser;
let currentUserId = `${currentUser.id}`;
const index = reply.helpfulIds.indexOf(currentUserId);
if (reply.helpfulByCurrentUser === true) {
if (index === -1) {
reply.helpfulIds.push(currentUserId);
}
}
else {
if (index > -1) {
reply.helpfulIds.splice(index, 1);
}
}
}
function createAndSendNewQuestionEmail(question: IQuestionItem, questionId: number) {
return async (dispatch, getState, { userService, notificationService }) => {
if (question) {
let currentUser = await dispatch(getCurrentUser());
let notifyEmails = await userService.getNotificationGroupUserEmails();
if (notifyEmails && notifyEmails.length > 0) {
const { webPartContext, applicationPage, discussionType } = getState();
let subjectPrefix = discussionType === DiscussionType.Question ? strings.EmailMessage_Subject_NewQuestion : strings.EmailMessage_Subject_NewConversation;
let actionMessage = discussionType === DiscussionType.Question ? strings.EmailMessage_Body_HasNewQuestion : strings.EmailMessage_Body_HasNewConversation;
let pageDetailsLabel = discussionType === DiscussionType.Question ? strings.EmailMessage_Body_PageDetails_Question : strings.EmailMessage_Body_PageDetails_Conversation;
let categoryDetails: string = '';
if(question.category && question.category.length > 0) {
categoryDetails = `<p><b>${strings.EmailMessage_Body_CategoryDetails}</b> ${question.category}</p>`;
}
let pageDetails: string = '';
if(question.page && question.page.length > 0) {
pageDetails = `<p><b>${pageDetailsLabel}</b> <a href='${question.page}'>${question.page}</a></p>`;
}
let email: IEmailProperties = {
Subject: `${subjectPrefix} ${question.title}`,
To: notifyEmails,
Body: `
${getTroubleViewingHtml(webPartContext, applicationPage, questionId, question.title, currentUser, actionMessage)}
<p>
<a href='mailto:${currentUser.email}' >${currentUser.displayName}</a>
${actionMessage}
<a href='${webPartContext.pageContext.web.absoluteUrl}/SitePages/${applicationPage}?${Parameters.QUESTIONID}=${questionId}'>
${question.title}
</a>
</p>
${categoryDetails}
${pageDetails}
<p><b>${(discussionType === DiscussionType.Question ? strings.EmailMessage_Body_QuestionDetails : strings.EmailMessage_Body_ConversationDetails)}</b></p>
<p><hr>${question.details}</p>
`
};
notificationService.sendEmail(email);
}
}
};
}
function createAndSendReplyEmail(reply: IReplyItem) {
return async (dispatch, getState, { notificationService }) => {
if (reply) {
let currentUser = await dispatch(getCurrentUser());
const { selectedQuestion, webPartContext, applicationPage, discussionType } = getState();
let subjectPrefix = strings.EmailMessage_Subject_NewReply;
let actionMessage = discussionType === DiscussionType.Question ? strings.EmailMessage_Body_HasNewRepliedToQuestion : strings.EmailMessage_Body_HasNewRepliedToConversation;
if (reply.id && reply.id > 0) {
subjectPrefix = strings.EmailMessage_Subject_UpdatedReply;
actionMessage = discussionType === DiscussionType.Question ? strings.EmailMessage_Body_HasUpdatedRepliedToQuestion : strings.EmailMessage_Body_HasUpdatedRepliedToConversation;
}
let categoryDetails: string = '';
if(selectedQuestion.category && selectedQuestion.category.length > 0) {
categoryDetails = `<p><b>${strings.EmailMessage_Body_CategoryDetails}</b> ${selectedQuestion.category}</p>`;
}
let email: IEmailProperties = {
Subject: `${subjectPrefix} ${selectedQuestion.title}`,
To: selectedQuestion.followEmails,
Body: `
${getTroubleViewingHtml(webPartContext, applicationPage, selectedQuestion.id, selectedQuestion.title, currentUser, actionMessage)}
<p>
<a href='mailto:${currentUser.email}' >${currentUser.displayName}</a>
${actionMessage}
<a href='${webPartContext.pageContext.web.absoluteUrl}/SitePages/${applicationPage}?${Parameters.QUESTIONID}=${selectedQuestion.id}'>
${selectedQuestion.title}
</a>
</p>
${categoryDetails}
<p><b>${strings.EmailMessage_Body_ReplyDetails}</b></p>
<p><hr>${reply.details}</p>
`
};
notificationService.sendEmail(email);
}
};
}
function createAndSendMentionReceiptEmail(post: IPostItem, postId: number, mentionEmails: string[]) {
return async (dispatch, getState, { notificationService }) => {
if (post) {
let currentUser = await dispatch(getCurrentUser());
if (mentionEmails && mentionEmails.length > 0) {
const { webPartContext, applicationPage } = getState();
let subjectSuffix = strings.EmailMessage_Subject_MentionNotification;
let preamble = strings.EmailMessage_Body_MentionNotification;
let email: IEmailProperties = {
Subject: `${currentUser.displayName} ${subjectSuffix}`,
To: mentionEmails,
Body: `
${getTroubleViewingHtml(webPartContext, applicationPage, postId, post.title, undefined, preamble)}
<p>
${preamble}
</p>
<p>
<a href='${webPartContext.pageContext.web.absoluteUrl}/SitePages/${applicationPage}?${Parameters.QUESTIONID}=${postId}'>
${post.title}
</a>
</p>
<p><hr>${post.details}</p>
<p>
By <a href='mailto:${currentUser.email}' >${currentUser.displayName}</a>
</p>
`
};
notificationService.sendEmail(email);
}
}
};
}
function createAndSendMarkedAnswerEmail(reply: IReplyItem) {
return async (dispatch, getState, { notificationService }) => {
if (reply) {
let currentUser = await dispatch(getCurrentUser());
let subjectPrefix = strings.EmailMessage_Subject_ReplyMarkedAnswer;
let actionMessage = strings.EmailMessage_Body_HasMarkedAnswerTo;
if (reply.id && reply.id > 0) {
if (reply.isAnswer === false) {
subjectPrefix = strings.EmailMessage_Subject_ReplyUnMarkedAnswer;
actionMessage = strings.EmailMessage_Body_HasUnmarkedAnswerTo;
}
}
const { selectedQuestion, webPartContext, applicationPage } = getState();
let categoryDetails: string = '';
if(selectedQuestion.category && selectedQuestion.category.length > 0) {
categoryDetails = `<p><b>${strings.EmailMessage_Body_CategoryDetails}</b> ${selectedQuestion.category}</p>`;
}
let email: IEmailProperties = {
Subject: `${subjectPrefix} ${selectedQuestion.title}`,
To: selectedQuestion.followEmails,
Body: `
${getTroubleViewingHtml(webPartContext, applicationPage, selectedQuestion.id, selectedQuestion.title, currentUser, actionMessage)}
<p>
<a href='mailto:${currentUser.email}' >${currentUser.displayName}</a>
${actionMessage}
<a href='${webPartContext.pageContext.web.absoluteUrl}/SitePages/${applicationPage}?${Parameters.QUESTIONID}=${selectedQuestion.id}'>
${selectedQuestion.title}
</a>
</p>
${categoryDetails}
<p><b>${strings.EmailMessage_Body_ReplyDetails}</b></p>
<p><hr>${reply.details}</p>
`
};
notificationService.sendEmail(email);
}
};
}
export function getTroubleViewingHtml(webPartContext, applicationPage, questionId, title, currentUser, actionMessage) {
return `
<div style='display:none' >${currentUser ? currentUser.displayName : ''} ${actionMessage} ${title}</div>
<p>
<a style='text-decoration: none;font-size: 12px;color: #a19f9d;'
href='${webPartContext.pageContext.web.absoluteUrl}/SitePages/${applicationPage}?${Parameters.QUESTIONID}=${questionId}'>
${strings.EmailMessage_Body_ProblemViewing}
</a>
</p>`;
}
export function getCurrentUser() {
return async (dispatch, getState, { userService }) => {
let { currentUser } = getState();
if (!currentUser) {
dispatch(simpleAction(ActionTypes.GET_CURRENTUSER_START));
currentUser = await userService.getCurrentUser();
dispatch(simpleAction(ActionTypes.GET_CURRENTUSER_SUCCESSFUL));
dispatch(updateCurrentUser(currentUser));
}
return currentUser;
};
}
export function uploadImageToQuestionsAssets(questionTile: string, blobInfo: any, progress) {
return async (dispatch, getState, { questionsAssetsService }) => {
dispatch(simpleAction(ActionTypes.UPLOAD_IMAGE_START));
let imageUrl = await questionsAssetsService.uploadImageToQuestionsAssets(questionTile, blobInfo, progress)
.catch(e => {
let message = handleHttpError(e);
throw new Error(message);
});
dispatch(simpleAction(ActionTypes.UPLOAD_IMAGE_SUCCESSFUL));
return imageUrl;
};
}
export function handleHttpError(error: HttpRequestError): string {
switch (error.status) {
case 400:
return strings.ErrorMessage_HTTP_BadRequest;
case 403:
return strings.ErrorMessage_HTTP_AccessDenied;
case 404:
return strings.ErrorMessage_HTTP_NotFound;
case undefined:
return error.message;
default:
return strings.ErrorMessage_HTTP_Generic;
}
} | the_stack |
import { getRealURL } from "../utils/url";
import { ArConnectEvent } from "../views/Popup/routes/Settings";
import { connect, disconnect } from "../background/api/connection";
import {
activeAddress,
allAddresses,
publicKey
} from "../background/api/address";
import { addToken, walletNames } from "../background/api/utility";
import { signTransaction } from "../background/api/transaction";
import {
MessageFormat,
MessageType,
validateMessage
} from "../utils/messenger";
import {
checkPermissions,
getActiveTab,
getArweaveConfig,
getPermissions,
getStoreData,
walletsStored,
checkCommunityContract
} from "../utils/background";
import { decrypt, encrypt, signature } from "../background/api/encryption";
import {
handleTabUpdate,
handleArweaveTabOpened,
handleArweaveTabClosed,
handleArweaveTabActivated,
handleBrowserLostFocus,
handleBrowserGainedFocus,
getArweaveActiveTab
} from "../background/tab_update";
import { browser, Runtime } from "webextension-polyfill-ts";
import { fixupPasswords } from "../utils/auth";
import { SignatureOptions } from "arweave/web/lib/crypto/crypto-interface";
import { Chunk } from "../utils/chunks";
import Transaction, { Tag } from "arweave/web/lib/transaction";
// stored transactions and their chunks
let transactions: {
chunkCollectionID: string; // unique ID for this collection
transaction: Transaction;
signatureOptions: SignatureOptions;
origin: string; // tabID for verification
rawChunks: Chunk[]; // raw chunks to be reconstructed
}[] = [];
// open the welcome page
browser.runtime.onInstalled.addListener(async () => {
if (!(await walletsStored()))
browser.tabs.create({ url: browser.runtime.getURL("/welcome.html") });
else await fixupPasswords();
});
browser.windows.onFocusChanged.addListener(async (windowId) => {
if (!(await walletsStored())) return;
if (windowId === browser.windows.WINDOW_ID_NONE) {
handleBrowserLostFocus();
} else {
const activeTab = await getActiveTab();
const txId = await checkCommunityContract(activeTab.url!);
if (txId) handleBrowserGainedFocus(activeTab.id!, txId);
}
});
// Create listeners for the icon utilities and context menu item updates.
browser.tabs.onActivated.addListener(async (activeInfo) => {
if (!(await walletsStored())) return;
handleArweaveTabActivated(activeInfo.tabId);
handleTabUpdate();
});
browser.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (!(await walletsStored())) return;
if (changeInfo.status === "complete") {
const txId = await checkCommunityContract(tab.url!);
if (txId) {
handleArweaveTabOpened(tabId, txId);
} else {
if (tabId === (await getArweaveActiveTab())) {
// It looks like user just entered or opened another web site on the same tab,
// where Arweave resource was loaded previously. Hence it needs to be closed.
handleArweaveTabClosed(tabId);
}
}
}
handleTabUpdate();
});
browser.tabs.onRemoved.addListener(async (tabId, removeInfo) => {
if (!(await walletsStored())) return;
const activeTab = await getActiveTab();
if (await checkCommunityContract(activeTab.url!))
handleArweaveTabClosed(tabId);
});
browser.runtime.onConnect.addListener((connection) => {
if (connection.name !== "backgroundConnection") return;
connection.onMessage.addListener(async (msg, port) => {
if (!validateMessage(msg, { sender: "api" })) return;
const res = await handleApiCalls(msg, port);
connection.postMessage({ ...res, ext: "arconnect" });
});
});
// listen for messages from the content script
const handleApiCalls = async (
message: MessageFormat,
port: Runtime.Port
): Promise<MessageFormat> => {
try {
const eventsStore = localStorage.getItem("arweave_events"),
events: ArConnectEvent[] = eventsStore
? JSON.parse(eventsStore)?.val
: [],
activeTab = await getActiveTab(
message.type === "sign_transaction" ||
message.type === "sign_transaction_chunk" ||
message.type === "sign_transaction_end" ||
false
),
tabURL = activeTab.url as string,
faviconUrl = activeTab.favIconUrl,
blockedSites = (await getStoreData())?.["blockedSites"];
// check if site is blocked
if (blockedSites) {
if (
blockedSites.includes(getRealURL(tabURL)) ||
blockedSites.includes(tabURL)
)
return {
type: `${message.type}_result` as MessageType,
ext: "arconnect",
res: false,
message: "Site is blocked",
sender: "background",
id: message.id
};
}
// if no wallets are stored, return and open the login page
if (!(await walletsStored())) {
browser.tabs.create({ url: browser.runtime.getURL("/welcome.html") });
return {
type: "connect_result",
ext: "arconnect",
res: false,
message: "No wallets added",
sender: "background",
id: message.id
};
}
// update events
localStorage.setItem(
"arweave_events",
JSON.stringify({
val: [
// max 100 events
...events.filter((_, i) => i < 98),
{ event: message.type, url: tabURL, date: Date.now() }
]
})
);
switch (message.type) {
// connect to arconnect
case "connect":
return {
type: "connect_result",
ext: "arconnect",
sender: "background",
id: message.id,
...(await connect(message, tabURL, faviconUrl))
};
// disconnect from arconnect
case "disconnect":
return {
type: "disconnect_result",
ext: "arconnect",
sender: "background",
id: message.id,
...(await disconnect(tabURL))
};
// get the active/selected address
case "get_active_address":
if (!(await checkPermissions(["ACCESS_ADDRESS"], tabURL)))
return {
type: "get_active_address_result",
ext: "arconnect",
res: false,
id: message.id,
message:
"The site does not have the required permissions for this action",
sender: "background"
};
return {
type: "get_active_address_result",
ext: "arconnect",
sender: "background",
id: message.id,
...(await activeAddress())
};
// get the public key of the active/selected address
case "get_active_public_key":
if (!(await checkPermissions(["ACCESS_PUBLIC_KEY"], tabURL)))
return {
type: "get_active_public_key_result",
ext: "arconnect",
res: false,
id: message.id,
message:
"The site does not have the required permissions for this action",
sender: "background"
};
return {
type: "get_active_public_key_result",
ext: "arconnect",
sender: "background",
id: message.id,
...(await publicKey())
};
// get all addresses added to ArConnect
case "get_all_addresses":
if (!(await checkPermissions(["ACCESS_ALL_ADDRESSES"], tabURL)))
return {
type: "get_all_addresses_result",
ext: "arconnect",
res: false,
id: message.id,
message:
"The site does not have the required permissions for this action",
sender: "background"
};
return {
type: "get_all_addresses_result",
ext: "arconnect",
sender: "background",
id: message.id,
...(await allAddresses())
};
// get names of wallets added to ArConnect
case "get_wallet_names":
if (!(await checkPermissions(["ACCESS_ALL_ADDRESSES"], tabURL)))
return {
type: "get_wallet_names_result",
ext: "arconnect",
res: false,
id: message.id,
message:
"The site does not have the required permissions for this action",
sender: "background"
};
return {
type: "get_wallet_names_result",
ext: "arconnect",
id: message.id,
sender: "background",
...(await walletNames())
};
// return permissions for the current url
case "get_permissions":
return {
type: "get_permissions_result",
ext: "arconnect",
res: true,
permissions: await getPermissions(tabURL),
id: message.id,
sender: "background"
};
// get the user's custom arweave config
case "get_arweave_config":
if (!(await checkPermissions(["ACCESS_ARWEAVE_CONFIG"], tabURL)))
return {
type: "get_arweave_config_result",
ext: "arconnect",
res: false,
id: message.id,
message:
"The site does not have the required permissions for this action",
sender: "background"
};
return {
type: "get_arweave_config_result",
ext: "arconnect",
res: true,
id: message.id,
config: await getArweaveConfig(),
sender: "background"
};
// add a custom token
case "add_token":
return {
type: "add_token_result",
ext: "arconnect",
sender: "background",
id: message.id,
...(await addToken(message))
};
// sign a transaction
case "sign_transaction":
if (!(await checkPermissions(["SIGN_TRANSACTION"], tabURL)))
return {
type: "sign_transaction_result",
ext: "arconnect",
res: false,
id: message.id,
message:
"The site does not have the required permissions for this action",
sender: "background"
};
// Begin listening for chunks
// this initializes a new array element
// with all the data for a future signing
// the content of the chunks will get pushed
// here
transactions.push({
chunkCollectionID: message.chunkCollectionID,
transaction: {
...message.transaction,
// add an empty tag array and data array to start,
data: new Uint8Array(),
tags: []
},
signatureOptions: message.signatureOptions,
// @ts-ignore
origin: port.sender.origin,
rawChunks: []
});
// tell the injected script that the background
// script is ready to receive the chunks
return {
type: "sign_transaction_result",
ext: "arconnect",
sender: "background",
id: message.id,
res: true
};
// receive and reconstruct a chunk
case "sign_transaction_chunk":
// get the chunk from the message
const chunk: Chunk = message.chunk;
// find the key of the transaction that the
// chunk belongs to
// also check if the origin of the chunk matches
// the origin of the tx creation
const txArrayID = transactions.findIndex(
({ chunkCollectionID, origin }) =>
chunkCollectionID === chunk.collectionID &&
// @ts-expect-error
origin === port.sender.origin
);
// throw error if the owner tx of this chunk is not present
if (txArrayID < 0)
return {
type: "sign_transaction_chunk_result",
ext: "arconnect",
res: false,
message: "Invalid origin for chunk",
id: message.id,
sender: "background"
};
// push valid chunk for evaluation in the future
transactions[txArrayID].rawChunks.push(chunk);
// let the injected script know that it can send the next chunk
return {
type: "sign_transaction_chunk_result",
ext: "arconnect",
res: true,
id: message.id,
sender: "background"
};
case "sign_transaction_end":
// find the the transaction whose chunk
// stream is ending
// also check if the origin matches
// the origin of the tx creation
const reconstructTx = transactions.find(
({ chunkCollectionID, origin }) =>
chunkCollectionID === message.chunkCollectionID &&
// @ts-expect-error
origin === port.sender.origin
);
// throw error if the owner tx of this tx is not present
if (!reconstructTx)
return {
type: "sign_transaction_end_result",
ext: "arconnect",
res: false,
id: message.id,
message: "Invalid origin for end request",
sender: "background"
};
// sort the chunks by their indexes to make sure
// that we are not loading them in the wrong order
reconstructTx.rawChunks.sort((a, b) => a.index - b.index);
// create a Uint8Array to reconstruct the data to
const reconstructedData = new Uint8Array(
parseFloat(reconstructTx.transaction.data_size ?? "0")
);
let previousLength = 0;
// loop through the raw chunks and reconstruct
// the transaction fields: data and tags
for (const chunk of reconstructTx.rawChunks) {
if (chunk.type === "data") {
// handle data chunks
// create a Uint8Array from the chunk value
const chunkBuffer = new Uint8Array(chunk.value as Uint8Array);
// append the value of the chunk after the
// previous array (using the currently filled
// indexes with "previousLength")
reconstructedData.set(chunkBuffer, previousLength);
previousLength += chunkBuffer.length; // increase the previous length by the buffer size
} else if (chunk.type === "tag") {
// handle tag chunks by simply pushing them
reconstructTx.transaction.tags.push(chunk.value as Tag);
}
}
// update the tx data with the reconstructed data
reconstructTx.transaction.data = reconstructedData;
// clean up the raw chunks
reconstructTx.rawChunks = [];
const signResult = await signTransaction(
Object.assign({}, reconstructTx.transaction),
tabURL,
message.signatureOptions
);
// remove tx from the global chunk storage
transactions = transactions.filter(
({ chunkCollectionID }) =>
chunkCollectionID !== message.chunkCollectionID
);
// now the tx is ready for signing, the injected
// script can request the background script to sign
return {
type: "sign_transaction_end_result",
ext: "arconnect",
sender: "background",
id: message.id,
chunkCollectionID: message.chunkCollectionID,
...signResult
};
case "encrypt":
if (!(await checkPermissions(["ENCRYPT"], tabURL)))
return {
type: "encrypt_result",
ext: "arconnect",
res: false,
id: message.id,
message:
"The site does not have the required permissions for this action",
sender: "background"
};
return {
type: "encrypt_result",
ext: "arconnect",
sender: "background",
id: message.id,
...(await encrypt(message, tabURL))
};
case "decrypt":
if (!(await checkPermissions(["DECRYPT"], tabURL)))
return {
type: "decrypt_result",
ext: "arconnect",
res: false,
id: message.id,
message:
"The site does not have the required permissions for this action",
sender: "background"
};
return {
type: "decrypt_result",
ext: "arconnect",
sender: "background",
id: message.id,
...(await decrypt(message, tabURL))
};
case "signature":
if (!(await checkPermissions(["SIGNATURE"], tabURL)))
return {
type: "signature_result",
ext: "arconnect",
res: false,
id: message.id,
message:
"The site does not have the required permissions for this action",
sender: "background"
};
return {
type: "signature_result",
ext: "arconnect",
sender: "background",
id: message.id,
...(await signature(message, tabURL))
};
default:
break;
}
return {
type: `${message.type}_result` as MessageType,
ext: "arconnect",
res: false,
id: message.id,
message: "Unknown error",
sender: "background"
};
} catch (e) {
return {
type: `${message.type}_result` as MessageType,
ext: "arconnect",
res: false,
id: message.id,
message: `Internal error: \n${e}`,
sender: "background"
};
}
};
// listen for messages from the popup
// right now the only message from there
// is for the wallet switch event
browser.runtime.onMessage.addListener(async (message: MessageFormat) => {
const activeTab = await getActiveTab();
if (!validateMessage(message, { sender: "popup" })) return;
if (!(await walletsStored())) return;
switch (message.type) {
case "archive_page":
const response: MessageFormat = await browser.tabs.sendMessage(
activeTab.id as number,
message
);
return { ...response, url: activeTab.url };
case "switch_wallet_event":
if (
!(await checkPermissions(
["ACCESS_ALL_ADDRESSES", "ACCESS_ADDRESS"],
activeTab.url as string
))
)
return;
browser.tabs.sendMessage(activeTab.id as number, {
...message,
type: "switch_wallet_event_forward"
});
break;
}
});
export {}; | the_stack |
/**
* @license Copyright © 2013 onwards, Andrew Whewell
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Portions Copyright (c) 2009, CodePlex Foundation
* All rights reserved.
*
* CodePlex license:
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* * Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview String utility methods.
*/
namespace VRS
{
/**
* Methods for working with strings.
*
* The format() code was copied from http://stackoverflow.com/questions/2534803/string-format-in-javascript
* which in turn was extracted from MicrosoftAjax.js by Sky Sanders on 28th March 2010.
*/
export class StringUtility
{
/**
* Returns true if the text contains the hasText string.
*/
contains(text: string, hasText: string, ignoreCase: boolean = false) : boolean
{
var result = !!(text && hasText);
if(result) {
if(!ignoreCase) result = text.indexOf(hasText) !== -1;
else result = text.toUpperCase().indexOf(hasText.toUpperCase()) !== -1;
}
return result;
}
/**
* Returns true if the lhs is equals to the rhs.
*/
equals(lhs: string, rhs: string, ignoreCase: boolean = false) : boolean
{
var result = false;
if(!lhs) result = !rhs;
else result = rhs && (!ignoreCase ? lhs === rhs : lhs.toUpperCase() === rhs.toUpperCase());
return result;
}
/**
* Calls the allowCharacter callback for each character in the text and returns the string formed from those
* characters that the callback returns true for.
*/
filter(text: string, allowCharacter: (ch: string) => boolean) : string
{
return this.filterReplace(text, function(ch) {
return allowCharacter(ch) ? ch : null;
});
}
/**
* Calls the replaceCharacter callback for each character in the text and returns the string formed from the
* strings that the callback returns.
*/
filterReplace(text: string, replaceCharacter: (ch: string) => string) : string
{
let result = text;
if(result) {
result = '';
let length = text.length;
let start = 0;
let useChunk = function(end) {
result += text.substring(start, end);
start = end + 1;
};
for(let i = 0;i < length;++i) {
let ch = text[i];
let replaceWith = replaceCharacter(ch);
if(ch !== replaceWith) {
useChunk(i);
if(replaceWith) result += replaceWith;
}
}
useChunk(length);
}
return result;
}
/**
* Returns the text with chevrons and ampersands escaped out for display in HTML.
*
* The aim of this function is to make the text HTML-safe in one pass - it is not to convert
* every possible HTML character to escape codes.
*/
htmlEscape(text: string, newlineToLineBreak: boolean = false) : string
{
return this.filterReplace(text, function(ch) {
switch(ch) {
case '&': return '&';
case '<': return '<';
case '>': return '>';
case '\n': return newlineToLineBreak ? '<br />' : ch;
default: return ch;
}
});
}
/**
* Formats a .NET style format string and arguments.
* @param {string} text The formatting string.
* @param {...} args The arguments to the formatting string.
* @returns {string} The formatted string.
*/
format(text: string, ...args: any[]) : string
{
return this.toFormattedString(false, arguments);
}
/**
* Replaces .NET style substitution markers with the arguments passed across.
* This was copied from http://stackoverflow.com/questions/2534803/string-format-in-javascript
* which in turn was extracted from MicrosoftAjax.js.
*/
private toFormattedString(useLocale: boolean, args: IArguments) : string
{
var result = '';
var format = <string>args[0];
for(var i = 0;;) {
// Find the next opening or closing brace
var open = format.indexOf('{', i);
var close = format.indexOf('}', i);
if((open < 0) && (close < 0)) {
// Not found: copy the end of the string and break
result += format.slice(i);
break;
}
if((close > 0) && ((close < open) || (open < 0))) {
if(format.charAt(close + 1) !== '}') throw new Error('format stringFormatBraceMismatch');
result += format.slice(i, close + 1);
i = close + 2;
continue;
}
// Copy the string before the brace
result += format.slice(i, open);
i = open + 1;
// Check for double braces (which display as one and are not arguments)
if (format.charAt(i) === '{') {
result += '{';
i++;
continue;
}
if (close < 0) throw new Error('format stringFormatBraceMismatch');
// Find the closing brace
// Get the string between the braces, and split it around the ':' (if any)
var brace = format.substring(i, close);
var colonIndex = brace.indexOf(':');
var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1;
if (isNaN(argNumber)) throw new Error('format stringFormatInvalid');
var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1);
/** @type {VRS_FORMAT_ARG} */
var arg = args[argNumber];
if (typeof (arg) === "undefined" || arg === null) {
arg = '';
}
// If it has a toFormattedString method, call it. Otherwise, call toString()
if (arg.toFormattedString) result += arg.toFormattedString(argFormat);
else if (useLocale && arg.localeFormat) result += arg.localeFormat(argFormat);
else if (arg.format) result += arg.format(argFormat);
else if (arg.toFixed) result += this.formatNumber(<number>arg, argFormat);
else result += arg.toString();
i = close + 1;
}
return result;
}
/**
* Formats a number with an optional .NET-style format parameter.
*
* This does not try to ape every .NET number format, just those that VRS needs.
*/
formatNumber(value: number, format?: number) : string;
formatNumber(value: number, format?: string) : string;
formatNumber(value: number, format?) : string
{
if(isNaN(value)) value = 0;
var result: string;
// Test for the most common case where only simple (or no) formatting is required.
if(value >= 0) {
if(format === undefined || format === null) return value.toString();
if(typeof format === 'number') {
result = value.toString();
if(result.length < format) {
while(result.length < format) result = '0' + result; // This is ugly but very quick.
}
return result;
}
}
var culture = Globalize.culture();
var leadingZeros = 0;
var decimalPlaces = -1; // -1 indicates that we just display the natural decimals from a toString() call
var showSeparators = false;
var decimalPosn = 0;
if(format) {
if(typeof format === 'number') format = this.repeatedSequence('0', format);
if(format[0] === 'n' || format[0] === 'N') {
decimalPlaces = Number(format.substr(1));
showSeparators = true;
} else {
decimalPosn = format.indexOf('.');
var integerFormat = decimalPosn === -1 ? format : format.substr(0, decimalPosn);
var decimalFormat = decimalPosn === -1 ? null : format.substr(decimalPosn + 1);
if(integerFormat == '0,000') {
showSeparators = true;
decimalPlaces = 0;
} else {
if(this.indexNotOf(integerFormat, '0') !== -1) throw 'Invalid format ' + format;
leadingZeros = integerFormat.length;
}
if(!decimalFormat) decimalPlaces = 0;
else {
if(this.indexNotOf(decimalFormat, '0') !== -1) throw 'Invalid format ' + format;
decimalPlaces = decimalFormat.length;
}
}
}
var isNegative = value < 0;
var numberText = decimalPlaces === -1 ? Math.abs(value).toString() : Math.abs(value).toFixed(decimalPlaces);
decimalPosn = numberText.indexOf('.');
var integerText = decimalPosn === -1 ? numberText : numberText.substr(0, decimalPosn);
var decimalText = decimalPosn === -1 || decimalPlaces === 0 ? '' : numberText.substr(decimalPosn + 1);
if(isNegative && integerText === '0' && this.indexNotOf(decimalText, '0') === -1) isNegative = false;
if(leadingZeros) {
var zerosRequired = leadingZeros - integerText.length;
if(zerosRequired > 0) integerText = this.repeatedSequence('0', zerosRequired) + integerText;
}
if(showSeparators) {
var groupSizes = culture.numberFormat.groupSizes;
var groupSizeIndex = 0;
var groupSize = groupSizes[groupSizeIndex];
var stringIndex = integerText.length - 1;
var separator = culture.numberFormat[','];
var withSeparators = '';
while(stringIndex >= 0) {
if(groupSize === 0 || groupSize > stringIndex) {
withSeparators = integerText.slice(0, stringIndex + 1) + (withSeparators.length ? (separator + withSeparators) : '');
break;
}
withSeparators = integerText.slice(stringIndex - groupSize + 1, stringIndex + 1) + (withSeparators.length ? (separator + withSeparators) : '');
stringIndex -= groupSize;
if(groupSizeIndex < groupSizes.length) groupSize = groupSizes[groupSizeIndex++];
}
integerText = withSeparators;
}
result = integerText;
if(decimalText) {
result += culture.numberFormat['.'];
result += decimalText;
}
if(isNegative) {
var pattern = culture.numberFormat.pattern[0];
var indexOfN = pattern.indexOf('n');
if(indexOfN === -1) throw 'Invalid negative pattern ' + pattern + ' for culture ' + culture.name;
result = pattern.substr(0, indexOfN) + result + pattern.substr(indexOfN + 1);
}
return result || '';
}
/**
* Returns the index of the first character that is not the character passed across.
*/
indexNotOf(text: string, character: string) : number
{
if(!character || character.length !== 1) throw 'A single character must be supplied';
var result = -1;
if(text) {
var length = text.length;
for(var i = 0;i < length;++i) {
if(text[i] !== character) {
result = i;
break;
}
}
}
return result;
}
/**
* Returns true if the text is in upper-case.
*/
isUpperCase(text: string) : boolean
{
return text && text.toUpperCase() == text;
}
/**
* Returns a string consisting of the sequence repeated count times.
*/
repeatedSequence(sequence: string, count: number) : string
{
// As ugly as this looks it's a lot quicker than other methods like new Array(count+1).join(sequence)
var result = '';
for(var i = 0;i < count;++i) {
result += sequence;
}
return result;
}
/**
* Returns the text padded with a string for length characters.
*/
padLeft(text: string, ch: string, length: number) : string
{
return this.doPad(text, ch, length, false);
}
/**
* Returns the text padded with a string for length characters.
*/
padRight(text: string, ch: string, length: number) : string
{
return this.doPad(text, ch, length, true);
}
/**
* Does the work for padLeft and padRight.
*/
private doPad(text: string, ch: string, length: number, toRight: boolean) : string
{
if(text === null || text === undefined) text = '';
var requiredCount = Math.ceil((length - text.length) / ch.length);
return requiredCount <= 0 ? text :
toRight ? text + this.repeatedSequence(ch, requiredCount)
: this.repeatedSequence(ch, requiredCount) + text;
}
/**
* Returns true if the text begins with the withText string.
*/
startsWith(text: string, withText: string, ignoreCase: boolean = false) : boolean
{
return this.startsOrEndsWith(text, withText, ignoreCase, true);
}
/**
* Returns true if the text ends with the withText string.
*/
endsWith(text: string, withText: string, ignoreCase: boolean = false) : boolean
{
return this.startsOrEndsWith(text, withText, ignoreCase, false);
};
/**
* Returns true if the text starts or ends with the withText string.
*/
private startsOrEndsWith(text: string, withText: string, ignoreCase: boolean, fromStart: boolean) : boolean
{
var length = withText ? withText.length : 0;
var result = !!(text && length && text.length >= length);
if(result) {
var chunk = fromStart ? text.substr(0, length) : text.slice(-length);
if(ignoreCase) {
chunk = chunk.toUpperCase();
withText = withText.toUpperCase();
}
result = chunk === withText;
}
return result;
}
/**
* Encodes the string in Base64 without incurring the 'failed to be encoded' error that Chrome throws when you
* pass it characters that need more than one byte to encode. Based on snippet from MDN here:
* https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_.232_.E2.80.93_rewriting_atob()_and_btoa()_using_TypedArrays_and_UTF-8
* @param text
*/
safeBtoa(text: string)
{
return btoa(encodeURIComponent(text).replace(/%([0-9A-F]{2})/g, function(match: any, p1: string) {
return String.fromCharCode(Number('0x' + p1));
}));
}
}
/**
* Pre-built instances of StringUtility. The code historically expects to be able to use these,
* can't replace them with static methods.
*/
export var stringUtility = new VRS.StringUtility();
} | the_stack |
import { message, Spin } from 'antd';
import ChartDrillContextMenu from 'app/components/ChartDrill/ChartDrillContextMenu';
import ChartDrillPaths from 'app/components/ChartDrill/ChartDrillPaths';
import { ChartIFrameContainer } from 'app/components/ChartIFrameContainer';
import { VizHeader } from 'app/components/VizHeader';
import { ChartDataViewFieldCategory } from 'app/constants';
import { useCacheWidthHeight } from 'app/hooks/useCacheWidthHeight';
import useI18NPrefix from 'app/hooks/useI18NPrefix';
import { ChartDataRequestBuilder } from 'app/models/ChartDataRequestBuilder';
import ChartManager from 'app/models/ChartManager';
import ChartDrillContext from 'app/pages/ChartWorkbenchPage/contexts/ChartDrillContext';
import { useWorkbenchSlice } from 'app/pages/ChartWorkbenchPage/slice';
import { selectAvailableSourceFunctions } from 'app/pages/ChartWorkbenchPage/slice/selectors';
import { fetchAvailableSourceFunctions } from 'app/pages/ChartWorkbenchPage/slice/thunks';
import { useMainSlice } from 'app/pages/MainPage/slice';
import { IChart } from 'app/types/Chart';
import { IChartDrillOption } from 'app/types/ChartDrillOption';
import {
getRuntimeComputedFields,
getRuntimeDateLevelFields,
} from 'app/utils/chartHelper';
import { generateShareLinkAsync, makeDownloadDataTask } from 'app/utils/fetch';
import { getChartDrillOption } from 'app/utils/internalChartHelper';
import { FC, memo, useCallback, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
import styled from 'styled-components/macro';
import { BORDER_RADIUS, SPACE_LG } from 'styles/StyleConstants';
import { useSaveAsViz } from '../hooks/useSaveAsViz';
import { useVizSlice } from '../slice';
import {
selectPreviewCharts,
selectPublishLoading,
selectVizs,
} from '../slice/selectors';
import {
deleteViz,
fetchDataSetByPreviewChartAction,
initChartPreviewData,
publishViz,
removeTab,
updateFilterAndFetchDataset,
updateGroupAndFetchDataset,
} from '../slice/thunks';
import { ChartPreview } from '../slice/types';
import { urlSearchTransfer } from '../utils';
import ControllerPanel from './components/ControllerPanel';
const ChartPreviewBoard: FC<{
backendChartId: string;
orgId: string;
filterSearchUrl?: string;
allowDownload?: boolean;
allowShare?: boolean;
allowManage?: boolean;
}> = memo(
({
backendChartId,
orgId,
filterSearchUrl,
allowDownload,
allowShare,
allowManage,
}) => {
// NOTE: avoid initialize width or height is zero that cause echart sampling calculation issue.
const defaultChartContainerWH = 1;
const {
cacheWhRef: ref,
cacheW,
cacheH,
} = useCacheWidthHeight(defaultChartContainerWH, defaultChartContainerWH);
useWorkbenchSlice();
const { actions: vizAction } = useVizSlice();
const { actions } = useMainSlice();
const chartManager = ChartManager.instance();
const dispatch = useDispatch();
const [version, setVersion] = useState<string>();
const previewCharts = useSelector(selectPreviewCharts);
const publishLoading = useSelector(selectPublishLoading);
const availableSourceFunctions = useSelector(
selectAvailableSourceFunctions,
);
const [chartPreview, setChartPreview] = useState<ChartPreview>();
const [chart, setChart] = useState<IChart>();
const [loadingStatus, setLoadingStatus] = useState<boolean>(false);
const drillOptionRef = useRef<IChartDrillOption>();
const t = useI18NPrefix('viz.main');
const tg = useI18NPrefix('global');
const saveAsViz = useSaveAsViz();
const history = useHistory();
const vizs = useSelector(selectVizs);
useEffect(() => {
const filterSearchParams = filterSearchUrl
? urlSearchTransfer.toParams(filterSearchUrl)
: undefined;
dispatch(
initChartPreviewData({
backendChartId,
orgId,
filterSearchParams,
}),
);
}, [dispatch, orgId, backendChartId, filterSearchUrl]);
useEffect(() => {
const sourceId = chartPreview?.backendChart?.view.sourceId;
if (sourceId) {
dispatch(
fetchAvailableSourceFunctions({
sourceId: sourceId,
}),
);
}
}, [chartPreview?.backendChart?.view.sourceId, dispatch]);
useEffect(() => {
const newChartPreview = previewCharts.find(
c => c.backendChartId === backendChartId,
);
if (newChartPreview && newChartPreview.version !== version) {
setVersion(newChartPreview.version);
setChartPreview(newChartPreview);
drillOptionRef.current = getChartDrillOption(
newChartPreview?.chartConfig?.datas,
drillOptionRef?.current,
);
if (
!chart ||
chart?.meta?.id !==
newChartPreview?.backendChart?.config?.chartGraphId
) {
const newChart = chartManager.getById(
newChartPreview?.backendChart?.config?.chartGraphId,
);
registerChartEvents(newChart, backendChartId);
setChart(newChart);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
backendChartId,
chart,
chartManager,
chartPreview?.backendChart?.id,
previewCharts,
version,
]);
const registerChartEvents = (chart, backendChartId) => {
chart?.registerMouseEvents([
{
name: 'click',
callback: param => {
if (
drillOptionRef.current?.isSelectedDrill &&
!drillOptionRef.current.isBottomLevel
) {
const option = drillOptionRef.current;
option.drillDown(param.data.rowData);
drillOptionRef.current = option;
handleDrillOptionChange(option);
return;
}
if (
param.componentType === 'table' &&
param.seriesType === 'paging-sort-filter'
) {
dispatch(
fetchDataSetByPreviewChartAction({
backendChartId,
sorter: {
column: param?.seriesName!,
operator: param?.value?.direction,
aggOperator: param?.value?.aggOperator,
},
pageInfo: {
pageNo: param?.value?.pageNo,
},
}),
);
return;
}
},
},
]);
};
const handleGotoWorkbenchPage = () => {
history.push({
pathname: `/organizations/${orgId}/vizs/chartEditor`,
search: `dataChartId=${backendChartId}&chartType=dataChart&container=dataChart`,
});
};
const handleFilterChange = (type, payload) => {
dispatch(
updateFilterAndFetchDataset({
backendChartId,
chartPreview,
payload,
drillOption: drillOptionRef?.current,
}),
);
};
const handleGenerateShareLink = async ({
expiryDate,
authenticationMode,
roles,
users,
rowPermissionBy,
}: {
expiryDate: string;
authenticationMode: string;
roles: string[];
users: string[];
rowPermissionBy: string;
}) => {
const result = await generateShareLinkAsync({
expiryDate,
authenticationMode,
roles,
users,
rowPermissionBy,
vizId: backendChartId,
vizType: 'DATACHART',
});
return result;
};
const handleCreateDownloadDataTask = async downloadType => {
if (!chartPreview) {
return;
}
const builder = new ChartDataRequestBuilder(
{
id: chartPreview?.backendChart?.view?.id || '',
config: chartPreview?.backendChart?.view.config || {},
computedFields:
chartPreview?.backendChart?.config.computedFields || [],
},
chartPreview?.chartConfig?.datas,
chartPreview?.chartConfig?.settings,
{},
false,
chartPreview?.backendChart?.config?.aggregation,
);
const folderId = vizs.filter(
v => v.relId === chartPreview?.backendChart?.id,
)[0].id;
dispatch(
makeDownloadDataTask({
downloadParams: [
{
...builder.build(),
...{
vizId:
downloadType === 'EXCEL'
? chartPreview?.backendChart?.id
: folderId,
vizName: chartPreview?.backendChart?.name,
analytics: false,
vizType: 'dataChart',
},
},
],
imageWidth: cacheW,
downloadType,
fileName: chartPreview?.backendChart?.name || 'chart',
resolve: () => {
dispatch(actions.setDownloadPolling(true));
},
}),
);
};
const handlePublish = useCallback(() => {
if (chartPreview?.backendChart) {
dispatch(
publishViz({
id: chartPreview.backendChart.id,
vizType: 'DATACHART',
publish: chartPreview.backendChart.status === 1 ? true : false,
resolve: () => {
message.success(
chartPreview.backendChart?.status === 2
? t('unpublishSuccess')
: t('publishSuccess'),
);
},
}),
);
}
}, [dispatch, chartPreview?.backendChart, t]);
const handleSaveAsVizs = useCallback(() => {
saveAsViz(chartPreview?.backendChartId as string, 'DATACHART');
}, [saveAsViz, chartPreview?.backendChartId]);
const handleReloadData = useCallback(async () => {
setLoadingStatus(true);
await dispatch(
fetchDataSetByPreviewChartAction({
backendChartId,
}),
);
setLoadingStatus(false);
}, [dispatch, backendChartId]);
const handleAddToDashBoard = useCallback(
(dashboardId, dashboardType) => {
const currentChartPreview = previewCharts.find(
c => c.backendChartId === backendChartId,
);
try {
history.push({
pathname: `/organizations/${orgId}/vizs/${dashboardId}/boardEditor`,
state: {
widgetInfo: JSON.stringify({
chartType: '',
dataChart: currentChartPreview?.backendChart,
dataview: currentChartPreview?.backendChart?.view,
dashboardType,
}),
},
});
} catch (error) {
throw error;
}
},
[previewCharts, history, backendChartId, orgId],
);
const redirect = useCallback(
tabKey => {
if (tabKey) {
history.push(`/organizations/${orgId}/vizs/${tabKey}`);
} else {
history.push(`/organizations/${orgId}/vizs`);
}
},
[history, orgId],
);
const handleRecycleViz = useCallback(() => {
dispatch(
deleteViz({
params: { id: backendChartId, archive: true },
type: 'DATACHART',
resolve: () => {
message.success(tg('operation.archiveSuccess'));
dispatch(removeTab({ id: backendChartId, resolve: redirect }));
},
}),
);
}, [backendChartId, dispatch, redirect, tg]);
const handleDrillOptionChange = (option: IChartDrillOption) => {
drillOptionRef.current = option;
dispatch(
updateFilterAndFetchDataset({
backendChartId,
chartPreview,
payload: null,
drillOption: drillOptionRef?.current,
}),
);
};
const handleDateLevelChange = (type, payload) => {
const rows = getRuntimeDateLevelFields(payload.value?.rows);
const dateLevelComputedFields = rows.filter(
v => v.category === ChartDataViewFieldCategory.DateLevelComputedField,
);
const replacedColName = payload.value.replacedColName;
const computedFields = getRuntimeComputedFields(
dateLevelComputedFields,
replacedColName,
chartPreview?.backendChart?.config?.computedFields,
chartPreview?.chartConfig,
);
dispatch(
vizAction.updateComputedFields({
backendChartId,
computedFields,
}),
);
dispatch(
updateGroupAndFetchDataset({
backendChartId,
payload: payload,
drillOption: drillOptionRef?.current,
}),
);
};
return (
<StyledChartPreviewBoard>
<VizHeader
chartName={chartPreview?.backendChart?.name}
status={chartPreview?.backendChart?.status}
publishLoading={publishLoading}
onGotoEdit={handleGotoWorkbenchPage}
onPublish={handlePublish}
onGenerateShareLink={handleGenerateShareLink}
onDownloadData={handleCreateDownloadDataTask}
onSaveAsVizs={handleSaveAsVizs}
onReloadData={handleReloadData}
onAddToDashBoard={handleAddToDashBoard}
onRecycleViz={handleRecycleViz}
allowDownload={allowDownload}
allowShare={allowShare}
allowManage={allowManage}
orgId={orgId}
backendChartId={backendChartId}
/>
<PreviewBlock>
<ChartDrillContext.Provider
value={{
drillOption: drillOptionRef.current,
onDrillOptionChange: handleDrillOptionChange,
availableSourceFunctions,
onDateLevelChange: handleDateLevelChange,
}}
>
<div>
<ControllerPanel
viewId={chartPreview?.backendChart?.viewId}
view={chartPreview?.backendChart?.view}
chartConfig={chartPreview?.chartConfig}
onChange={handleFilterChange}
/>
</div>
<ChartWrapper ref={ref}>
<Spin wrapperClassName="spinWrapper" spinning={loadingStatus}>
<ChartDrillContextMenu chartConfig={chartPreview?.chartConfig!}>
<ChartIFrameContainer
key={backendChartId}
containerId={backendChartId}
dataset={chartPreview?.dataset}
chart={chart!}
config={chartPreview?.chartConfig!}
drillOption={drillOptionRef.current}
width={cacheW}
height={cacheH}
/>
</ChartDrillContextMenu>
</Spin>
</ChartWrapper>
<StyledChartDrillPathsContainer>
<ChartDrillPaths />
</StyledChartDrillPathsContainer>
<StyledChartDrillPathsContainer />
</ChartDrillContext.Provider>
</PreviewBlock>
</StyledChartPreviewBoard>
);
},
);
export default ChartPreviewBoard;
const StyledChartPreviewBoard = styled.div`
display: flex;
flex: 1;
flex-flow: column;
height: 100%;
iframe {
flex-grow: 1000;
}
`;
const PreviewBlock = styled.div`
display: flex;
flex: 1;
flex-direction: column;
height: 100%;
padding: ${SPACE_LG};
overflow: hidden;
box-shadow: ${p => p.theme.shadowBlock};
`;
const ChartWrapper = styled.div`
position: relative;
display: flex;
flex: 1;
background-color: ${p => p.theme.componentBackground};
border-radius: ${BORDER_RADIUS};
.chart-drill-menu-container {
height: 100%;
}
.spinWrapper {
width: 100%;
height: 100%;
.ant-spin-container {
width: 100%;
height: 100%;
}
}
`;
const StyledChartDrillPathsContainer = styled.div`
background-color: ${p => p.theme.componentBackground};
`; | the_stack |
import difference from "lodash-es/difference";
import each from "lodash-es/each";
import flatten from "lodash-es/flatten";
import flow from "lodash-es/flow";
import intersection from "lodash-es/intersection";
import isEqual from "lodash-es/isEqual";
import isNumber from "lodash-es/isNumber";
import keys from "lodash-es/keys";
import map from "lodash-es/map";
import { default as pr } from "lodash-es/partialRight";
import pick from "lodash-es/pick";
import takeRight from "lodash-es/takeRight";
import union from "lodash-es/union";
import uniq from "lodash-es/uniq";
import values from "lodash-es/values";
import {glslFloatRepr, noop} from "../utils";
import * as Ast from "./Ast";
import CodeInstance from "./CodeInstance";
import { parse } from "./ExprGrammar.pegjs";
export interface ICompileResult {
codeInst: CodeInstance;
glslCode: string;
}
export default function compileExpr(
codeSrc: {[name: string]: string | string[]},
jsFuncs: string[] = [],
glslFuncs: string[] = [],
nonUniforms: string[] = [],
): ICompileResult {
const codeStrings: {[name: string]: string} = {};
for (const name in codeSrc) {
if (!codeSrc.hasOwnProperty(name)) {
continue;
}
let codeString = codeSrc[name];
if (Array.isArray(codeString)) {
codeString = codeString.join("\n");
}
codeString.trim();
if (codeString.length === 0) {
continue;
}
codeStrings[name] = codeString;
}
// 1) Parse the code
const codeAst = parseCode(codeStrings);
// 2) Process the AST
const tables = processAst(codeAst, jsFuncs, glslFuncs, nonUniforms);
// 3) Generate code
const codeInst = generateJs(codeAst, tables, jsFuncs);
const glslCode = generateGlsl(codeAst, tables, glslFuncs);
return {codeInst, glslCode};
}
interface ICodeAst {[name: string]: Ast.Program; }
function parseCode(codeSrc: {[name: string]: string}): ICodeAst {
const codeAst: ICodeAst = {}; // abstract syntax tree
for (const name in codeSrc) {
if (!codeSrc.hasOwnProperty(name)) {
continue;
}
try {
codeAst[name] = parse(codeSrc[name]) as Ast.Program;
} catch (e) {
throw new Error("Error parsing " + name + " (" + e.line + ":" + e.column + ")" + " : " + e);
}
}
return codeAst;
}
function isStaticExprList(exprs: Ast.Expression[]): exprs is Ast.PrimaryExpr[] {
return exprs.every((expr) => {
return expr instanceof Ast.PrimaryExpr;
});
}
interface ISymbolTables {
register: {[name: string]: string[]};
preCompute: {[uniformName: string]: string[]};
jsVars: string[];
glslVars: string[];
nonUniforms: string[];
uniforms: string[];
glslUsedFuncs: string[];
glslRegisters: string[];
}
function processAst(
codeAst: ICodeAst,
jsFuncs: string[],
glslFuncs: string[],
extraNonUniforms: string[],
): ISymbolTables {
const funcCall: {[name: string]: string[]} = {};
const variable: {[name: string]: string[]} = {};
const register: {[name: string]: string[]} = {};
const preCompute: {[uniformName: string]: string[]} = {};
let preComputeCounter = 0;
const processNode = (ast, name) => {
if (ast instanceof Ast.Program) {
for (const statement of ast.statements) {
processNode(statement, name);
}
} else if (ast instanceof Ast.BinaryExpr) {
processNode(ast.leftOperand, name);
processNode(ast.rightOperand, name);
} else if (ast instanceof Ast.UnaryExpr) {
processNode(ast.operand, name);
} else if (ast instanceof Ast.FuncCall) {
checkFunc(ast);
// if its a precomputable function to be generated in glsl
// then build a table entry
if (glslFuncs.indexOf(name) >= 0 && glslPreComputeFuncs.indexOf(ast.funcName) >= 0) {
const args = ast.args;
if (!isStaticExprList(args)) {
throw new Error(
`Non Pre-Computable arguments for ${ast.funcName} in shader code, use variables or constants`,
);
}
const entry = [ast.funcName].concat(map(args, (arg) => arg.value));
let uniformName;
for (const key in preCompute) {
if (isEqual(preCompute[key], entry)) {
uniformName = key;
break;
}
}
if (!uniformName) {
uniformName = "__PC_" + ast.funcName + "_" + preComputeCounter++;
preCompute[uniformName] = entry;
}
ast.preComputeUniformName = uniformName;
}
funcCall[name].push(ast.funcName);
for (const arg of ast.args) {
processNode(arg, name);
}
} else if (ast instanceof Ast.Assignment) {
processNode(ast.lhs, name);
processNode(ast.expr, name);
} else if (ast instanceof Ast.PrimaryExpr && ast.type === "ID") {
variable[name].push(ast.value);
} else if (ast instanceof Ast.PrimaryExpr && ast.type === "REG") {
register[name].push(ast.value);
}
};
for (const name in codeAst) {
if (!codeAst.hasOwnProperty(name)) {
continue;
}
funcCall[name] = [];
variable[name] = [];
register[name] = [];
processNode(codeAst[name], name);
funcCall[name] = uniq(funcCall[name]);
variable[name] = uniq(variable[name]);
register[name] = uniq(register[name]);
}
const jsVars: string[] = flow([pr(pick, jsFuncs), values, flatten, uniq])(variable);
const glslVars: string[] = flow([pr(pick, glslFuncs), values, flatten, uniq])(variable);
const nonUniforms: string[] = flow([pr(difference, jsVars), pr(union, extraNonUniforms), uniq])(glslVars);
const uniforms: string[] = intersection(glslVars, jsVars);
const glslUsedFuncs: string[] = flow([pr(pick, glslFuncs), values, flatten, uniq])(funcCall);
const glslRegisters: string[] = flow([pr(pick, glslFuncs), values, flatten, uniq])(register);
return {
glslRegisters, glslUsedFuncs, glslVars, jsVars, nonUniforms, preCompute, register, uniforms,
};
}
function generateJs(codeAst: ICodeAst, tables: ISymbolTables, jsFuncs: string[]): CodeInstance {
const generateNode = (ast) => {
if (ast instanceof Ast.BinaryExpr) {
return "(" + generateNode(ast.leftOperand) + ast.operator + generateNode(ast.rightOperand) + ")";
}
if (ast instanceof Ast.UnaryExpr) {
return "(" + ast.operator + generateNode(ast.operand) + ")";
}
if (ast instanceof Ast.FuncCall) {
switch (ast.funcName) {
case "above":
return [
"(",
generateNode(ast.args[0]),
">",
generateNode(ast.args[1]),
"?1:0)",
].join("");
case "below":
return [
"(",
generateNode(ast.args[0]),
"<",
generateNode(ast.args[1]),
"?1:0)",
].join("");
case "equal":
return [
"(",
generateNode(ast.args[0]),
"==",
generateNode(ast.args[1]),
"?1:0)",
].join("");
case "if":
return [
"(",
generateNode(ast.args[0]),
"!==0?",
generateNode(ast.args[1]),
":",
generateNode(ast.args[2]),
")",
].join("");
case "select":
const code = ["((function() {"];
code.push("switch(" + generateNode(ast.args[0]) + ") {");
each(takeRight(ast.args, ast.args.length - 1), (arg, i) => {
code.push("case " + i + ": return " + generateNode(arg) + ";");
});
code.push("default : throw new Error('Unknown selector value in select');");
code.push("}}).call(this))");
return code.join("");
case "sqr":
return "(Math.pow((" + generateNode(ast.args[0]) + "),2))";
case "band":
return "(((" + generateNode(ast.args[0]) + ")&&(" + generateNode(ast.args[1]) + "))?1:0)";
case "bor":
return "(((" + generateNode(ast.args[0]) + ")||(" + generateNode(ast.args[1]) + "))?1:0)";
case "bnot":
return "((!(" + generateNode(ast.args[0]) + "))?1:0)";
case "invsqrt":
return "(1/Math.sqrt(" + generateNode(ast.args[0]) + "))";
case "atan2":
return "(Math.atan((" + generateNode(ast.args[0]) + ")/(" + generateNode(ast.args[1]) + ")))";
default:
let prefix;
const args = map(ast.args, (arg) => generateNode(arg)).join(",");
if (jsMathFuncs.indexOf(ast.funcName) >= 0) {
prefix = "Math.";
} else {
prefix = "this.";
}
return "(" + prefix + ast.funcName + "(" + args + "))";
}
}
if (ast instanceof Ast.Assignment) {
return generateNode(ast.lhs) + "=" + generateNode(ast.expr);
}
if (ast instanceof Ast.Program) {
const stmts = map(ast.statements, (stmt) => generateNode(stmt));
return stmts.join(";\n");
}
if (ast instanceof Ast.PrimaryExpr && ast.type === "VALUE") {
return ast.value.toString();
}
if (ast instanceof Ast.PrimaryExpr && ast.type === "CONST") {
return translateConstants(ast.value).toString();
}
if (ast instanceof Ast.PrimaryExpr && ast.type === "ID") {
return "this." + ast.value;
}
if (ast instanceof Ast.PrimaryExpr && ast.type === "REG") {
return "this.registerBank[\"" + ast.value + "\"]";
}
};
const registerUsages = flow([values, flatten, uniq])(tables.register);
const hasRandom = tables.glslUsedFuncs.indexOf("rand") >= 0;
const codeInst = new CodeInstance(
registerUsages,
tables.glslRegisters,
hasRandom,
tables.uniforms,
tables.preCompute,
);
// clear all variables
for (const jsVar of tables.jsVars) {
codeInst[jsVar] = 0;
}
// generate code
for (const name of jsFuncs) {
const ast = codeAst[name];
if (ast) {
const jsCodeString = generateNode(ast);
codeInst[name] = new Function(jsCodeString);
} else {
codeInst[name] = noop;
}
}
return codeInst;
}
function generateGlsl(codeAst: ICodeAst, tables: ISymbolTables, glslFuncs: string[]): string {
const generateNode = (ast) => {
if (ast instanceof Ast.BinaryExpr) {
return "(" + generateNode(ast.leftOperand) + ast.operator + generateNode(ast.rightOperand) + ")";
}
if (ast instanceof Ast.UnaryExpr) {
return "(" + ast.operator + generateNode(ast.operand) + ")";
}
if (ast instanceof Ast.FuncCall) {
if (ast.preComputeUniformName) {
return "(" + ast.preComputeUniformName + ")";
}
switch (ast.funcName) {
case "above":
return [
"(",
generateNode(ast.args[0]),
">",
generateNode(ast.args[1]),
"?1.0:0.0)",
].join("");
case "below":
return [
"(",
generateNode(ast.args[0]),
"<",
generateNode(ast.args[1]),
"?1.0:0.0)",
].join("");
case "equal":
return [
"(",
generateNode(ast.args[0]),
"==",
generateNode(ast.args[1]),
"?1.0:0.0)",
].join("");
case "if":
return [
"(",
generateNode(ast.args[0]),
"!=0.0?",
generateNode(ast.args[1]),
":",
generateNode(ast.args[2]),
")",
].join("");
case "select": {
const selectExpr = generateNode(ast.args[0]);
const generateSelect = (args, i) => {
if (args.length === 1) {
return generateNode(args[0]);
} else {
return [
"((" + selectExpr + " === " + i + ")?",
"(" + generateNode(args[0]) + "):",
"(" + generateSelect(takeRight(args, args.length - 1), i + 1) + "))",
].join("");
}
};
return generateSelect(takeRight(ast.args, ast.args.length - 1), 0);
}
case "sqr":
return "(pow((" + generateNode(ast.args[0]) + "), 2))";
case "band":
return "(float((" + generateNode(ast.args[0]) + ")&&(" + generateNode(ast.args[1]) + ")))";
case "bor":
return "(float((" + generateNode(ast.args[0]) + ")||(" + generateNode(ast.args[1]) + ")))";
case "bnot":
return "(float(!(" + generateNode(ast.args[0]) + ")))";
case "invsqrt":
return "(inversesqrt(" + generateNode(ast.args[0]) + "))";
case "atan2":
return "(atan((" + generateNode(ast.args[0]) + "),(" + generateNode(ast.args[1]) + "))";
default: {
const args = map(ast.args, (arg) => generateNode(arg)).join(",");
return "(" + ast.funcName + "(" + args + "))";
}
}
}
if (ast instanceof Ast.Assignment) {
return generateNode(ast.lhs) + "=" + generateNode(ast.expr);
}
if (ast instanceof Ast.Program) {
const stmts = map(ast.statements, (stmt) => generateNode(stmt));
return stmts.join(";\n") + ";";
}
if (ast instanceof Ast.PrimaryExpr && ast.type === "VALUE") {
return glslFloatRepr(ast.value);
}
if (ast instanceof Ast.PrimaryExpr && ast.type === "CONST") {
return translateConstants(ast.value).toString();
}
if (ast instanceof Ast.PrimaryExpr && (ast.type === "ID" || ast.type === "REG")) {
return ast.value;
}
};
let glslCode = [];
// glsl variable declarations
glslCode = glslCode.concat(map(tables.nonUniforms, (name) => {
return "float " + name + " = 0.0;";
}));
glslCode = glslCode.concat(map(tables.uniforms, (name) => {
return "uniform float " + name + ";";
}));
// include required functions in glsl
glslCode = glslCode.concat(flow([
pr(map, (name) => {
return ((name in glslFuncCode) ? (glslFuncCode[name]) : []);
}),
flatten,
])(tables.glslUsedFuncs));
// declarations for precomputed functions
glslCode = glslCode.concat(flow([
keys,
pr(map, (name) => {
return "uniform float " + name + ";";
}),
])(tables.preCompute));
// add the functions
for (const name of glslFuncs) {
const ast = codeAst[name];
if (ast) {
const codeString = generateNode(ast);
glslCode.push("void " + name + "() {");
glslCode.push(codeString);
glslCode.push("}");
} else {
glslCode.push("void " + name + "() {}");
}
}
return glslCode.join("\n");
}
type ArgLength = number | {min: number};
const funcArgLengths: {[funcName: string]: ArgLength} = {
above: 2,
abs: 1,
acos: 1,
asin: 1,
atan: 1,
atan2: 2,
band: 2,
below: 2,
bnot: 1,
bor: 2,
ceil: 1,
cos: 1,
equal: 2,
floor: 1,
getosc: 3,
gettime: 1,
if: 3,
invsqrt: 1,
log: 1,
max: 2,
min: 2,
pow: 2,
rand: 1,
select: {
min: 2,
},
sin: 1,
sqr: 1,
sqrt: 1,
tan: 1,
};
const jsMathFuncs = [
"min", "max", "sin", "cos", "abs", "tan", "asin", "acos",
"atan", "log", "pow", "sqrt", "floor", "ceil",
];
const glslPreComputeFuncs = ["getosc", "gettime"];
const glslFuncCode = {
rand: [
"uniform vec2 __randStep;",
"vec2 __randSeed;",
"float rand(float max) {",
" __randSeed += __randStep;",
" float val = fract(sin(dot(__randSeed.xy ,vec2(12.9898,78.233))) * 43758.5453);",
" return (floor(val*max)+1);",
"}",
].join("\n"),
};
function checkFunc(ast: Ast.FuncCall) {
const requiredArgLength = funcArgLengths[ast.funcName];
if (requiredArgLength === undefined) {
throw Error("Unknown function " + ast.funcName);
}
if (isNumber(requiredArgLength)) {
if (ast.args.length !== requiredArgLength) {
throw Error(ast.funcName + " accepts " + requiredArgLength + " arguments");
}
} else if (requiredArgLength.min) {
if (ast.args.length < requiredArgLength.min) {
throw Error(ast.funcName + " accepts atleast " + requiredArgLength.min + " arguments");
}
}
}
function translateConstants(value: string): number {
switch (value) {
case "pi": return Math.PI;
case "e": return Math.E;
case "phi": return 1.6180339887;
default: throw new Error("Unknown constant " + value);
}
} | the_stack |
module Cats.OS.File {
export var PATH:NodeJS.Path = require("path");
var fs = require("fs");
var exec = require("child_process").exec;
var glob = require("glob");
/**
* Very lightweight watcher for files and directories, used to inform the user of changes
* in the underlying file system.
*/
export class Watcher extends qx.event.Emitter {
// Keeps track of the files and directories that are being watched
private watches:Map<any> = {};
constructor() {
super();
}
/**
* Add a new file or directory to the watch list. If it already exists it is being ignored
*
*/
add(name:string) {
if (this.watches[name]) return;
var w = fs.watch(name, (event:any,filename:string) => {
console.info("Node changed " + name + " event " + event + " fileName " + filename);
this.emit("change", name);
});
this.watches[name] = w;
}
/**
* Add a new directory to the watch list. If it already exists it is being ignored.
* Only rename type of events are being propgated (so new files or deletes).
*
* Files within a directory changing size etc are not propagated.
*
*/
addDir(name:string) {
if (this.watches[name]) return;
var w = fs.watch(name, (event:any,filename:string) => {
console.info("Node changed " + name + " event " + event + " fileName " + filename);
if (event === "rename") this.emit("change", name);
});
this.watches[name] = w;
}
/**
* Remove an entry from the watch list (file or directory)
*
* @param name The filepath that no longer should be watched
*
*/
remove(name:string) {
var w = this.watches[name];
if (w) {
w.close();
delete this.watches[name];
}
}
}
/**
* Create recursively directories if they don't exist yet
*
* @param path The directory path to create
*
*/
export function mkdirRecursiveSync(path: string) {
if (!fs.existsSync(path)) {
mkdirRecursiveSync(PATH.dirname(path));
fs.mkdirSync(path,509); //, 0775);
}
}
/**
* Create a file watcher
*/
export function getWatcher() {
var watcher = new Watcher();
return watcher;
}
/**
* Get the stat of a file and return them as a set of properties
*
*/
export function getProperties(fileName:string) {
if (! fileName) return [];
var stat:NodeJS.fs.Stats = fs.statSync(fileName);
var baseName = PATH.basename(fileName);
var result = [
{ key: "fileName", value: baseName},
{ key: "filePath", value: fileName}
];
for (var key in stat) {
if (stat.hasOwnProperty(key)) {
result.push({
key: key,
value : stat[key]
});
}
}
return result;
}
/**
* Run an external command like a build tool and log the output
*
*/
export function runCommand(cmd:string, options:any, logger=IDE.console) {
if (! options.env) {
options.env = process.env;
}
var child = exec(cmd, options, () => {
/* ignore the buffers */
});
var id = child.pid;
IDE.processTable.addProcess(child, cmd);
child.stdout.on("data", function (data:string) {
logger.log("" + data);
});
child.stderr.on("data", function (data:string) {
logger.error("" + data);
});
child.on("close", function (code:number) {
logger.log("Done");
});
}
/**
* Remove a file or an empty directory
*
* @param path the path of the file or directory to be removed
*
*/
export function remove(path:string) {
var isFile = fs.statSync(path).isFile();
if (isFile)
fs.unlinkSync(path);
else
fs.rmdirSync(path);
}
/**
* Is this instance running on the OSX platform
*/
export function isOSX() {
return process.platform === "darwin";
}
export function isWindows() {
return process.platform === "win32";
}
/**
* Join two paths together and return the result.
*/
export function join(a:string,b:string, native=false) : string{
var result = PATH.join(a,b);
if (!native) result = switchToForwardSlashes(result);
return result;
}
/**
* Find a file matching a certain patterns and in the certain directory
*/
export function find(pattern:string, rootDir:string, cb:Function) {
var files:Array<string> = glob.sync(pattern, {cwd:rootDir, mark:true}) ;
files = files.filter((name) => {return name.slice(-1) !== "/"; });
cb(null,files);
}
/**
* Rename a file or directory
*
* @param oldName the old name of the file or directory
* @param newName the new name of the file or directory
*/
export function rename(oldName:string,newName: string) {
fs.renameSync(oldName, newName);
}
/**
* Determine the newLine character that should be used.
*
* @return Returned value is either the dos or unix newline character
*/
function determineNewLineChar(): string {
return "\n";
/*
try {
var char = IDE.project.config.codeFormat.NewLineCharacter;
if (char) return char;
} catch (exp) {}
if (isWindows()) return "\r\n";
return "\n";
*/
}
/**
* Write text content to a file. If a directory doesn't exist, create it
*
* @param name The full name of the file
* @param value The content of the file
* @param stat Indicate if we should return the stat values of the newly written file
*
*/
export function writeTextFile(name: string, value: string, stat=false):any {
var newLineChar = determineNewLineChar();
if (newLineChar !== "\n") {
value = value.replace(/\n/g, newLineChar);
}
var fileName = name;
//fileName = PATH.resolve(IDE.project.projectDir, fileName);
mkdirRecursiveSync(PATH.dirname(fileName));
fs.writeFileSync(fileName, value, "utf8");
if (stat) return fs.statSync(fileName);
return null;
}
/**
* Convert backward slashes (DOS) to forward slashes (UNIX)
*
*/
export function switchToForwardSlashes(path:string):string {
if (! path) return path;
return path.replace(/\\/g, "/");
}
/**
* Sort two file entries. First sort on directory versus file and then on alphabet.
* This is similar how most file explorers do it.
*/
function sort(a: Cats.FileEntry, b: Cats.FileEntry) {
if ((!a.isDirectory) && b.isDirectory) return 1;
if (a.isDirectory && (!b.isDirectory)) return -1;
if (a.name > b.name) return 1;
if (b.name > a.name) return -1;
return 0;
}
/**
* Read all the files from a directory
*
* @param directory The directory name that should be read
* @param sorted Should be result be sorted or not
*
*/
export function readDir(directory:string, sorted=false) {
var files:string[] = fs.readdirSync(directory);
var result:Cats.FileEntry[] = [];
files.forEach((file) => {
var fullName = OS.File.join(directory, file);
var stats = fs.statSync(fullName);
result.push({
name:file,
fullName: fullName,
isFile: stats.isFile() ,
isDirectory: stats.isDirectory()
});
});
if (sorted) result.sort(sort);
return result;
}
/**
* Read the content from a text file.
*
* @param name The full name/path of the file
*
*/
export function readTextFile(name: string): string {
if (name == null ) return "";
var data = fs.readFileSync(name, "utf8");
// Use single character line returns
data = data.replace(/\r\n?/g, "\n");
// Remove the BOM (only MS uses BOM for UTF8)
data = data.replace(/^\uFEFF/, '');
return data;
}
} | the_stack |
/// <reference path="node_modules/@types/snapsvg/index.d.ts"/>
/// <reference path="node_modules/@types/knockout/index.d.ts"/>
/// <reference path="node_modules/@types/jquery/index.d.ts"/>
var COLOR_PRIMARY = ko.observable<Snap.RGB>(Snap.getRGB("#2C3E50"));
var COLOR_SUCCESS = ko.observable<Snap.RGB>(Snap.getRGB("#18BC9C"));
var COLOR_INFO = ko.observable<Snap.RGB>(Snap.getRGB("#3498DB"));
var COLOR_WARNING = ko.observable<Snap.RGB>(Snap.getRGB("#F39C12"));
var COLOR_DANGER = ko.observable<Snap.RGB>(Snap.getRGB("#E74C3C"));
var BACKGROUND_COLOR = ko.observable<Snap.RGB>(Snap.getRGB("rgb(200, 200, 200)"));
var CAM_BACKGROUND_COLOR = ko.observable<Snap.RGB>(Snap.getRGB("rgb(255, 255, 255)"));
var CAM_OUTLINE = COLOR_PRIMARY;
class Vec2 {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
toString() {
return `(${this.x}, ${this.y})`;
}
clone() {
return new Vec2(this.x, this.y);
}
}
function add(a: Vec2, b: Vec2) {
return new Vec2(a.x + b.x, a.y + b.y);
}
function sub(a: Vec2, b: Vec2) {
return new Vec2(a.x - b.x, a.y - b.y);
}
function mulV(a: Vec2, b: Vec2) {
return new Vec2(a.x * b.x, a.y * b.y);
}
function mul(a: Vec2, b: number) {
return new Vec2(a.x * b, a.y * b);
}
function dot(a: Vec2, b: Vec2) {
return a.x * b.x + a.y * b.y;
}
function vlength(a: Vec2) {
return Math.sqrt(dot(a, a));
}
function normalize(a: Vec2) {
var len = vlength(a);
return new Vec2(a.x / len, a.y / len);
}
function reflect(i: Vec2, n: Vec2) {
i = mul(i, 1);
return sub(i, mul(n, 2.0 * dot(n, i)));
}
function refract(i: Vec2, n: Vec2, eta: number) {
var NdotI = dot(n, i);
var k = 1.0 - eta * eta * (1.0 - NdotI * NdotI);
if (k < 0.0)
return new Vec2(0, 0);
else
return sub(mul(i, eta), mul(n, eta * NdotI + Math.sqrt(k) ));
}
function cross(a: Vec2, b: Vec2) {
return a.x * b.y - a.y * b.x;
}
function perp(a: Vec2) {
return new Vec2(-a.y, a.x);
}
function uniformSampleHemisphere(n: Vec2) {
var Xi1 = Math.random();
var Xi2 = Math.random();
var theta = Xi1;
var phi = 2.0 * Math.PI * Xi2;
var f = Math.sqrt(1 - theta * theta);
var x = f * Math.cos(phi);
var y = theta;
var dir = new Vec2(x, y);
dir = mul(dir, sign(dot(dir, n)));
return dir;
}
function cosineSampleHemisphere(n: Vec2) {
var Xi1 = Math.random();
var Xi2 = Math.random();
var theta = Xi1;
var phi = 2.0 * Math.PI * Xi2;
var f = Math.sqrt(1 - theta);
var x = f * Math.cos(phi);
var y = Math.sqrt(theta);
var xDir = perp(n);
return add(mul(xDir, x), mul(n,y));
}
function sampleCircle(pos: Vec2, rad: number) {
var angle = Math.random() * 2 * Math.PI;
var dir = new Vec2(Math.sin(angle), Math.cos(angle));
return add(pos, mul(dir, rad));
}
class Ray {
o: Vec2;
d: Vec2;
constructor(o: Vec2, d: Vec2) {
this.o = o;
this.d = d;
}
clone() {
return new Ray(this.o.clone(), this.d.clone());
}
}
function sign(f : number) {
return f < 0 ? -1 : 1;
}
function intersectRayLinesegment(r:Ray, a:Vec2, b:Vec2, result:Intersection) {
var v1 = sub(r.o, a);
var v2 = sub(b, a);
var v3 = perp(r.d);
var t1 = cross(v2, v1) / dot(v2, v3);
var t2 = dot(v1, v3) / dot(v2, v3);
if (t1 < 0 || t2 < 0 || t2 > 1) return false;
result.p = add(r.o, mul(r.d, t1));
result.n = perp(v2);
result.n = mul(result.n, -sign(dot(result.n, r.d)));
return true;
}
class Intersection {
p: Vec2;
n: Vec2;
shape: Shape;
}
function transformPoint(a: Vec2, mat: Snap.Matrix) {
return new Vec2(mat.x(a.x, a.y), mat.y(a.x, a.y));
}
function transpose(mat: Snap.Matrix) {
return Snap.matrix(mat.d, mat.c, mat.b, mat.a, 0, 0);
}
function transformDir(a: Vec2, mat: Snap.Matrix) {
var dirTrans = transpose(mat.invert());
return normalize(transformPoint(a, dirTrans));
}
function transformRay(ray: Ray, mat: Snap.Matrix) {
return new Ray(transformPoint(ray.o, mat), transformDir(ray.d, mat));
}
class Material {
static MATERIAL_MAP: any = {};
outlineColor: KnockoutObservable<Snap.RGB>;
fillColor: KnockoutObservable<Snap.RGB>;
outlineOpacity: number;
fillOpacity: number;
outlineWidth: number;
linkedElements: KnockoutObservableArray<Snap.Element>;
isLight: KnockoutObservable<boolean>;
name: KnockoutObservable<string>;
constructor(name: string, outlineColor: Snap.RGB, fillColor: Snap.RGB, outlineOpacity: number, fillOpacity: number, outlineWidth: number) {
this.outlineColor = ko.observable<Snap.RGB>(outlineColor);
this.fillColor = ko.observable<Snap.RGB>(fillColor);;
this.outlineOpacity = outlineOpacity;
this.fillOpacity = fillOpacity;
this.outlineWidth = outlineWidth;
this.linkedElements = ko.observableArray<Snap.Element>([]);
this.isLight = ko.observable<boolean>(false);
this.name = ko.observable<string>(name);
this.outlineColor.subscribe((newValue) => { this.update() }, this);
this.fillColor.subscribe((newValue) => { this.update() }, this);
}
update() {
for (var el of this.linkedElements()) {
el.attr({
fill: this.fillOpacity > 0.01 ? this.fillColor().hex : "none",
stroke: this.outlineColor().hex,
strokeWidth: this.outlineWidth / (el.transform().localMatrix ? el.transform().localMatrix.split().scalex : 1),
"fill-opacity": this.fillOpacity,
"stroke-opacity": this.outlineOpacity,
//"vector-effect": "non-scaling-stroke",
});
}
}
apply(el: Snap.Element) {
var elMat = <Material>(<any>el).mat;
if (elMat != this) {
if (elMat) {
elMat.linkedElements.remove(el);
}
(<any>el).mat = this;
this.linkedElements.push(el);
}
el.attr({
fill: this.fillOpacity > 0.01 ? this.fillColor().hex : "none",
stroke: this.outlineColor().hex,
strokeWidth: this.outlineWidth / (el.transform().localMatrix ? el.transform().localMatrix.split().scalex : 1),
"fill-opacity": this.fillOpacity,
"stroke-opacity": this.outlineOpacity,
//"vector-effect": "non-scaling-stroke",
});
for (var child of el.children()) {
this.apply(child);
}
}
applyTo(el: Thing) {
this.apply(el.svgElement());
}
}
var DEFAULT_MATERIAL: KnockoutObservable<Material> = ko.observable<Material>(new Material("Default", COLOR_DANGER(), BACKGROUND_COLOR(), 1.0, 0.25, 2));
var CAM_MATERIAL: KnockoutObservable<Material> = ko.observable<Material>(new Material("Camera", CAM_OUTLINE(), CAM_BACKGROUND_COLOR(), 1.0, 0.75, 2));
var PATH_MATERIAL: KnockoutObservable<Material> = ko.observable<Material>(new Material("Path", COLOR_SUCCESS(), BACKGROUND_COLOR(), 1.0, 0.0, 2));
var LIGHT_MATERIAL: KnockoutObservable<Material> = ko.observable<Material>(new Material("Light", COLOR_WARNING(), BACKGROUND_COLOR(), 1.0, 0.25, 0.5));
class Thing {
paper: Snap.Paper;
svgElement: KnockoutObservable<Snap.Element>;
material: KnockoutObservable<Material>;
pos: KnockoutComputed<Vec2>;
scale: KnockoutComputed<Vec2>;
rot: KnockoutComputed<number>;
transform: KnockoutComputed<Snap.Matrix>;
svgObserver: MutationObserver;
cachedTransform: Snap.Matrix;
cachedTransformInv: Snap.Matrix;
constructor(s: Snap.Paper) {
this.paper = s;
this.cachedTransform = Snap.matrix();
this.svgObserver = new MutationObserver((recs: MutationRecord[], inst: MutationObserver) => {
var transformMutated: boolean = false;
for (var rec of recs) {
if (rec.attributeName == "transform") {
transformMutated = true;
break;
}
}
if (transformMutated) {
this.svgElement.valueHasMutated();
}
});
this.svgElement = ko.observable<Snap.Element>();
this.material = ko.observable<Material>(DEFAULT_MATERIAL());
this.transform = ko.computed<Snap.Matrix>({
read: () => {
if (!this.svgElement()) return Snap.matrix();
this.cachedTransform = this.svgElement().transform().globalMatrix;
this.cachedTransformInv = this.cachedTransform.invert();
return this.cachedTransform;
},
write: (val: Snap.Matrix) => {
if (!this.svgElement()) return;
this.cachedTransform = val;
this.cachedTransformInv = this.cachedTransform.invert();
this.svgElement().attr({ transform: val });
this.material().apply(this.svgElement());
},
owner: this
});
this.pos = ko.computed<Vec2>({
read: () => {
var trans = this.transform();
var split = trans.split();
return new Vec2(split.dx, split.dy);
},
write: (val: Vec2) => {
var trans = this.transform();
var split = trans.split();
trans.translate(-split.dx + val.x, -split.dy + val.y);
this.transform(trans);
},
owner: this
});
this.scale = ko.computed<Vec2>({
read: () => {
var trans = this.transform();
var split = trans.split();
return new Vec2(split.scalex, split.scaley);
},
write: (val: Vec2) => {
var trans = this.transform();
var split = trans.split();
trans.scale(val.x / split.scalex, val.y / split.scaley);
this.transform(trans);
},
owner: this
});
this.rot = ko.computed<number>({
read: () => {
var trans = this.transform();
var split = trans.split();
return split.rotate;
},
write: (val: number) => {
var trans = this.transform();
var split = trans.split();
trans.rotate(-split.rotate + val);
this.transform(trans);
},
owner: this
});
}
private destroySvg(el: Snap.Element) {
this.material().linkedElements.remove(el);
for (var child of el.children()) {
this.destroySvg(child);
}
}
destroy() {
this.destroySvg(this.svgElement());
this.svgElement().remove();
}
setup() {
this.svgElement(this.makeSvg(this.paper));
this.material.subscribe((newValue) => { newValue.applyTo(this); }, this);
this.svgObserver.observe(this.svgElement().node, { attributes: true, subtree: true });
this.svgElement().node.addEventListener("mousewheel", (ev: WheelEvent) => {
if (ev.shiftKey) {
this.scale( add(this.scale(), mul(new Vec2(1, 1), ev.wheelDelta * 0.02)));
} else {
this.rot(this.rot() + ev.wheelDelta * 0.1);
}
ev.preventDefault();
ev.stopPropagation();
});
this.svgElement.valueHasMutated();
}
makeSvg(s: Snap.Paper): Snap.Element {
return null;
}
}
class Shape extends Thing {
constructor(s: Snap.Paper) {
super(s);
}
intersect(ray: Ray, result: Intersection): boolean { return false }
sampleShape(): Vec2 {
return this.pos();
}
}
class Light extends Shape {
constructor(pos: Vec2, rad: number, s: Snap.Paper) {
super(s);
this.setup();
this.pos(pos);
this.scale(new Vec2(rad, rad));
this.material( LIGHT_MATERIAL());
}
intersect(ray: Ray, result: Intersection) {
ray = transformRay(ray, this.cachedTransformInv);
var t0: number;
var t1: number; // solutions for t if the ray intersects
var L = mul(ray.o, -1);
var tca = dot(L, ray.d);
var d2 = dot(L, L) - tca * tca;
if (d2 > 1) return false;
var thc = Math.sqrt(1 - d2);
t0 = tca - thc;
t1 = tca + thc;
if (t0 > t1) {
var tmp = t0;
t0 = t1;
t1 = tmp;
}
if (t0 < 0) {
t0 = t1; // if t0 is negative, let's use t1 instead
if (t0 < 0) return false; // both t0 and t1 are negative
}
result.p = add(ray.o, mul(ray.d, t0));
result.n = normalize(result.p);
result.p = transformPoint(result.p, this.cachedTransform);
result.n = transformDir(result.n, this.cachedTransform);
return true;
}
makeSvg(s: Snap.Paper) {
var g = s.group();
var circle = s.circle(0, 0, 1);
this.material().apply(circle);
g.add(circle);
var mat = Snap.matrix();
var xAxis = new Vec2(1, 0);
var count = 10;
for (var i = 0; i < count; i++) {
mat.rotate(360 / count);
var angle = 360 / count * i;
var p = mul(transformPoint(xAxis, mat), 5);
var line = s.line(0, 0, p.x, p.y);
this.material().apply(line);
g.add(line);
}
this.material().apply(g);
g.data("thing", this);
return g;
}
sampleShape() {
return sampleCircle(this.pos(), this.scale().x);
}
}
class Circle extends Shape {
constructor(pos: Vec2, rad: number, s: Snap.Paper) {
super(s);
this.setup();
this.pos(pos);
this.scale(new Vec2(rad, rad));
}
intersect(ray: Ray, result: Intersection) {
ray = transformRay(ray, this.cachedTransformInv);
var t0: number;
var t1: number; // solutions for t if the ray intersects
var L = mul(ray.o, -1);
var tca = dot(L, ray.d);
var d2 = dot(L, L) - tca * tca;
if (d2 > 1) return false;
var thc = Math.sqrt(1 - d2);
t0 = tca - thc;
t1 = tca + thc;
if (t0 > t1) {
var tmp = t0;
t0 = t1;
t1 = tmp;
}
if (t0 < 0) {
t0 = t1; // if t0 is negative, let's use t1 instead
if (t0 < 0) return false; // both t0 and t1 are negative
}
result.p = add(ray.o, mul(ray.d, t0));
result.n = normalize(result.p);
result.p = transformPoint(result.p, this.cachedTransform);
result.n = transformDir(result.n, this.cachedTransform);
return true;
}
makeSvg(s: Snap.Paper) {
var el = s.circle(0, 0, 1);
el.data("thing", this);
return el;
}
sampleShape() {
return sampleCircle(this.pos(), this.scale().x);
}
}
var BOX_CORNERS = [
new Vec2(0, 0),
new Vec2(1, 0),
new Vec2(1, 1),
new Vec2(0, 1)
];
class Box extends Shape {
constructor(pos: Vec2, size: Vec2, s: Snap.Paper) {
super(s);
this.setup();
this.pos(pos);
this.scale(size);
}
intersect(ray: Ray, result: Intersection) {
ray = transformRay(ray, this.cachedTransformInv);
var minDist = 20000000;
var hitSomething = false;
for (var i = 0; i < 4; i++) {
var curr = BOX_CORNERS[i];
var next = BOX_CORNERS[(i + 1) % 4];
var intersect = new Intersection();
if (intersectRayLinesegment(ray, curr, next, intersect)) {
hitSomething = true;
var dist = vlength(sub(intersect.p, ray.o));
if (dist < minDist) {
minDist = dist;
result.p = intersect.p;
result.n = intersect.n;
}
}
}
if (!hitSomething) return false;
result.p = transformPoint(result.p, this.cachedTransform);
result.n = transformDir(result.n, this.cachedTransform);
return true;
}
makeSvg(s: Snap.Paper) {
var el = s.rect(0, 0, 1, 1);
el.data("thing", this);
return el;
}
}
class Polygon extends Shape {
points: Vec2[];
constructor(points: Vec2[], s: Snap.Paper) {
super(s);
this.points = points;
this.setup();
}
intersect(ray: Ray, result: Intersection) {
ray = transformRay(ray, this.cachedTransformInv);
var minDist = 20000000;
var hitSomething = false;
for (var i = 0; i < this.points.length; i++) {
var curr = this.points[i];
var next = this.points[(i + 1) % this.points.length];
var intersect = new Intersection();
if (intersectRayLinesegment(ray, curr, next, intersect)) {
hitSomething = true;
var dist = vlength(sub(intersect.p, ray.o));
if (dist < minDist) {
minDist = dist;
result.p = intersect.p;
result.n = intersect.n;
}
}
}
if (!hitSomething) return false;
result.p = transformPoint(result.p, this.cachedTransform);
result.n = transformDir(result.n, this.cachedTransform);
return true;
}
makeSvg(s: Snap.Paper) {
var posArray: number[] = [];
for (var p of this.points) {
posArray.push(p.x, p.y );
}
var el = s.polygon(posArray);
el.data("thing", this);
return el;
}
}
class Camera extends Thing {
fov: KnockoutObservable<number>;
constructor(pos: Vec2, rot: number, s: Snap.Paper) {
super(s);
this.fov = ko.observable<number>(60);
this.setup();
this.pos(pos);
this.rot(rot);
this.material( CAM_MATERIAL());
}
forward() {
return this.sampleDir(0.5);
}
sampleDir(psp: number) {
var mat = Snap.matrix();
setRotation(mat, -this.fov() / 2 + this.fov() * psp);
var dir = transformDir(new Vec2(1, 0), mat);
return transformDir(dir, this.cachedTransform);
}
lookAt(target: Vec2, pos?: Vec2) {
if (!pos) {
pos = this.pos();
} else {
this.pos(pos);
}
var dir = normalize(sub(target, pos));
var angle = Snap.angle(1, 0, dir.x, dir.y);
this.rot(angle);
}
makeSvg(s: Snap.Paper) {
var g = s.group();
var mat = Snap.matrix();
mat.rotate(-this.fov() / 2);
var dir = transformDir(new Vec2(1, 0), mat);
var eyeRadDir = mul(dir, 25);
var el = s.path(`M 0,0 ${eyeRadDir.x}, ${eyeRadDir.y} A 40, 40 1 0, 1 ${eyeRadDir.x}, ${-eyeRadDir.y} Z`);
this.material().apply(el);
g.add(el);
dir = mul(dir, 32);
{
var line = s.line(0, 0, dir.x, dir.y);
this.material().apply(line);
g.add(line);
}
{
var line = s.line(0, 0, dir.x, -dir.y);
this.material().apply(line);
g.add(line);
}
var circle = s.ellipse(19, 0, 2, 4);
this.material().apply(circle);
g.add(circle);
g.data("thing", this);
return g;
}
}
interface Set<T> {
add(value: T): Set<T>;
clear(): void;
delete(value: T): boolean;
entries(): Array<[T, T]>;
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): Array<T>;
size: number;
}
interface SetConstructor {
new <T>(): Set<T>;
new <T>(iterable: Array<T>): Set<T>;
prototype: Set<any>;
}
declare var Set: SetConstructor;
class PathData {
points: Intersection[];
properties: Set<string>;
}
class Path extends Thing {
data: PathData;
constructor(data: PathData, s: Snap.Paper) {
super(s);
this.data = data;
this.setup();
this.material(PATH_MATERIAL());
}
makeSvg(s: Snap.Paper) {
var posArray: number[] = [];
var g = s.group();
for (var i of this.data.points) {
posArray.push(i.p.x, i.p.y);
var normTarget = add(i.p, mul(i.n, 10));
//var norm = s.line(i.p.x, i.p.y, normTarget.x, normTarget.y);
//DEFAULT_MATERIAL().apply(norm);
//g.add(norm);
}
var line = s.polyline(posArray);
this.material().apply(line);
g.add(line);
g.data("thing", this);
g.attr({ "z-index": -1 });
return g;
}
}
interface Sampler {
name: string;
tracePath(ray: Ray, depth: number, scene: Scene): PathData[];
}
function setRotation(mat: Snap.Matrix, r: number) {
var cosr = Math.cos(Snap.rad(r));
var sinr = Math.sin(Snap.rad(r));
mat.a = cosr;
mat.b = sinr;
mat.c = -sinr;
mat.d = cosr;
}
class SampleSpaceVisualization {
canvas: CanvasRenderingContext2D;
selectedCoordinates: KnockoutObservable<Vec2>;
drawLabels: KnockoutObservable<boolean>;
constructor(canvas: CanvasRenderingContext2D) {
this.canvas = canvas;
this.selectedCoordinates = ko.observable<Vec2>(new Vec2(0.5, 0.5));
this.drawLabels = ko.observable<boolean>(true);
}
getPath(scene: Scene, cam: Camera, coord: Vec2) {
var path: PathData = new PathData();
path.points = [];
path.properties = new Set<string>();
var dir = cam.sampleDir(coord.x);
var primaryRay: Ray = new Ray(add(cam.pos(), mul(dir, 21)), dir);
path.points.push({ p: primaryRay.o, n: primaryRay.d, shape: null });
var primaryHit = new Intersection();
var didHitPrimary = scene.intersect(primaryRay, primaryHit);
if (!didHitPrimary) {
path.points.push({ p: add(primaryRay.o, mul(primaryRay.d, 20000)), n: primaryRay.d, shape: null });
return path;
}
path.points.push(primaryHit);
var secondaryDir = primaryHit.n;
var mat = Snap.matrix();
setRotation(mat, -90 + 180 * coord.y);
secondaryDir = transformDir(secondaryDir, mat);
var secondaryRay: Ray = new Ray(add(primaryHit.p, mul(secondaryDir, 1)), secondaryDir);
var secondaryHit = new Intersection();
var didHitSecondary = scene.intersect(secondaryRay, secondaryHit);
if (!didHitSecondary) {
path.points.push({ p: add(secondaryRay.o, mul(secondaryRay.d, 20000)), n: secondaryRay.d, shape: null });
return path;
}
path.points.push(secondaryHit);
return path;
}
update(scene: Scene, cam: Camera) {
var width = this.canvas.canvas.width;
var height = this.canvas.canvas.width;
var newDataObj = this.canvas.createImageData(width, height);
var newData = newDataObj.data;
var mat = Snap.matrix();
for (var x = 0; x < width; x++) {
var dir = cam.sampleDir(x / width);
var primaryRay: Ray = new Ray(cam.pos(), dir);
var primaryHit = new Intersection();
var didHitPrimary = scene.intersect(primaryRay, primaryHit);
for (var y = 0; y < height; y++) {
var pixelIndex = (x + width * y) * 4;
if (!didHitPrimary) {
newData[pixelIndex + 0] = 0;
newData[pixelIndex + 1] = 0;
newData[pixelIndex + 2] = 0;
newData[pixelIndex + 3] = 255;
continue;
}
var secondaryDir = primaryHit.n;
setRotation(mat, -90 + 180 * y / height);
secondaryDir = transformDir(secondaryDir, mat);
var secondaryRay: Ray = new Ray(add(primaryHit.p, mul(secondaryDir, 1)), secondaryDir);
var secondaryHit = new Intersection();
var didHitSecondary = scene.intersect(secondaryRay, secondaryHit);
var primHitCol = primaryHit.shape.material().outlineColor();
if (!didHitSecondary) {
newData[pixelIndex + 0] = primHitCol.r;
newData[pixelIndex + 1] = primHitCol.g;
newData[pixelIndex + 2] = primHitCol.b;
newData[pixelIndex + 3] = 255;
continue;
}
var secHitCol = secondaryHit.shape.material().outlineColor();
newData[pixelIndex + 0] = 255 * (secHitCol.r / 255 * primHitCol.r / 255);
newData[pixelIndex + 1] = 255 * (secHitCol.g / 255 * primHitCol.g / 255);
newData[pixelIndex + 2] = 255 * (secHitCol.b / 255 * primHitCol.b / 255);
newData[pixelIndex + 3] = 255;
}
}
this.canvas.putImageData(newDataObj, 0, 0);
if (this.drawLabels()) {
this.canvas.lineWidth = 2;
this.canvas.strokeStyle = COLOR_INFO().hex;
this.canvas.beginPath();
this.canvas.moveTo(this.selectedCoordinates().x * width, 0);
this.canvas.lineTo(this.selectedCoordinates().x * width, height);
this.canvas.stroke();
this.canvas.strokeStyle = COLOR_WARNING().hex;
this.canvas.beginPath();
this.canvas.arc(this.selectedCoordinates().x * width, this.selectedCoordinates().y * height, 2, 0, 360);
this.canvas.stroke();
}
}
}
declare class jscolor {
constructor(el: any, opt:any);
}
class Scene extends Shape {
renderPathDensity: KnockoutObservable<boolean>;
visualizePrimarySampleSpace: KnockoutObservable<boolean>;
densityFullResolution: KnockoutObservable<boolean>;
sampleSpaceVis: SampleSpaceVisualization;
shapes: KnockoutObservableArray<Shape>;
paths: Path[];
cameras: KnockoutObservableArray<Camera>;
materials: KnockoutObservableArray<Material>;
sampler: KnockoutObservable<Sampler>;
canvas: CanvasRenderingContext2D;
renderedPathsCount: KnockoutObservable<number>;
lights: KnockoutObservableArray<Shape>;
availableSamplers: KnockoutObservableArray<Sampler>;
maxDepth: KnockoutObservable<number>;
pathDensityMultiplier: KnockoutObservable<number>;
maxDensitySamples: KnockoutObservable<number>;
afterAddMaterial(element: HTMLElement[], data: Material) {
console.log(data);
var outlinePickEl = element[1].querySelector('#jscolor-outline');
var outlinePicker = new jscolor(outlinePickEl, {
valueElement: null,
value: data.outlineColor().hex,
});
outlinePickEl.textContent = "";
(<any>outlinePicker).onFineChange = () => { data.outlineColor(Snap.getRGB("#" + outlinePicker.toString())); };
var fillPickEl = element[1].querySelector('#jscolor-fill');
var fillPicker = new jscolor(fillPickEl, {
valueElement: null,
value: data.fillColor().hex,
});
(<any>fillPicker).onFineChange = () => { data.fillColor(Snap.getRGB("#" + fillPicker.toString())); };
fillPickEl.textContent = "";
}
constructor(sampler : Sampler, s: Snap.Paper) {
super(s);
this.maxDensitySamples = ko.observable<number>(50000);
this.pathDensityMultiplier = ko.observable<number>(1);
this.maxDepth = ko.observable<number>(3);
this.visualizePrimarySampleSpace = ko.observable<boolean>(false);
this.renderedPathsCount = ko.observable<number>(0);
this.renderPathDensity = ko.observable<boolean>(false);
this.densityFullResolution = ko.observable<boolean>(false);
this.sampler = ko.observable<Sampler>(sampler);
this.shapes = ko.observableArray<Shape>([]);
this.lights = ko.observableArray<Shape>([]);
this.paths = [];
this.cameras = ko.observableArray<Camera>([]);
this.materials = ko.observableArray<Material>([]);
this.setup();
$(this.svgElement().node).off("mouswheel");
s.undrag();
sampleDirFunc.subscribe((newVal) => this.recalculatePaths(), this);
this.svgElement.subscribe((newVal) => this.recalculatePaths(), this);
this.renderPathDensity.subscribe((newVal) => this.recalculatePaths(), this);
this.visualizePrimarySampleSpace.subscribe((newVal) => this.recalculatePaths(), this);
this.densityFullResolution.subscribe((newVal) => this.recalculatePaths(), this);
this.maxDepth.subscribe((newVal) => this.recalculatePaths(), this);
this.sampler.subscribe((newVal) => this.recalculatePaths(), this);
this.availableSamplers = ko.observableArray<Sampler>([this.sampler()]);
}
removeMaterial(mat: Material) {
this.materials.remove(mat);
}
sampleLight() {
var lightIndex = Math.floor(this.lights().length * Math.random());
var light = this.lights()[lightIndex];
return light.sampleShape();
}
recalculatePaths() {
for (var path of this.paths) {
path.destroy();
}
this.paths = [];
this.renderedPathsCount(0);
this.canvas.clearRect(0, 0, 10000, 10000);
if (this.renderPathDensity()) {
window.requestAnimationFrame(() => this.updateDensity());
} else if (!this.visualizePrimarySampleSpace()) {
for (var cam of this.cameras()) {
var fwd = cam.forward();
var startRay = new Ray(add(cam.pos(), mul(fwd, 21)), fwd);
var newPaths = this.sampler().tracePath(startRay, this.maxDepth(), this);
for (var p of newPaths) {
var path = new Path(p, this.paper);
this.paths.push(path);
}
}
}
if (this.visualizePrimarySampleSpace()) {
var sampleCanvas = this.sampleSpaceVis.canvas.canvas;
sampleCanvas.width = $(sampleCanvas).width() * (this.densityFullResolution() ? 1 : 0.5) ;
sampleCanvas.height = sampleCanvas.width;
this.sampleSpaceVis.update(this, this.cameras()[0]);
var p = this.sampleSpaceVis.getPath(this, this.cameras()[0], this.sampleSpaceVis.selectedCoordinates());
var path = new Path(p, this.paper);
this.paths.push(path);
}
}
updateDensity() {
if (!this.renderPathDensity()) return;
this.canvas.globalCompositeOperation = "soft-light";
for (var cam of this.cameras()) {
var fwd = cam.forward();
var startRay = new Ray(add(cam.pos(), mul(fwd, 21)), fwd);
var renderPaths: PathData[] = [];
for (var i = 0; i < 4; i++) {
var newPaths = this.sampler().tracePath(startRay.clone(), this.maxDepth(), this);
for (var p of newPaths) {
renderPaths.push(p);
}
}
this.renderedPathsCount(this.renderedPathsCount() + 4);
this.canvas.strokeStyle = PATH_MATERIAL().outlineColor().hex;
this.canvas.lineWidth = 0.4;
this.canvas.globalAlpha = 0.02 * this.pathDensityMultiplier();
for (var p of renderPaths) {
this.canvas.strokeStyle = p.properties.has("HitLight") ? COLOR_WARNING().hex : COLOR_INFO().hex;
this.canvas.beginPath();
this.canvas.moveTo(p.points[0].p.x, p.points[0].p.y);
for (var point of p.points) {
this.canvas.lineTo(point.p.x, point.p.y);
}
this.canvas.stroke();
}
}
if (this.renderedPathsCount() < this.maxDensitySamples()) {
window.requestAnimationFrame(() => this.updateDensity());
}
}
removeThing(thing: Thing) {
if (thing instanceof Camera) {
this.cameras.remove(<Camera>thing);
} else if (thing instanceof Shape) {
this.shapes.remove(<Shape>thing);
}
if (thing instanceof Light) {
this.lights.remove(<Light>thing);
}
thing.svgElement().remove();
this.recalculatePaths();
}
addCamera(cam: Camera) {
this.cameras.push(cam);
this.svgElement().add(cam.svgElement());
cam.svgElement().drag();
}
addShape(shape: Shape) {
this.shapes.push(shape);
if (shape instanceof Light) this.lights.push(shape);
this.svgElement().add(shape.svgElement());
shape.svgElement().drag();
}
intersect(ray: Ray, result: Intersection) {
var minDist: number = 2000000;
var hitSomething = false;
for (var shape of this.shapes()) {
var intersect: Intersection = new Intersection();
if (shape.intersect(ray, intersect)) {
hitSomething = true;
var dist = vlength(sub(ray.o, intersect.p));
if (dist < minDist) {
result.p = intersect.p;
result.n = intersect.n;
result.shape = shape;
minDist = dist;
}
}
}
return hitSomething;
}
test(a: Vec2, b: Vec2) {
var r: Ray = new Ray(a, normalize(sub(b, a)));
var res: Intersection = new Intersection();
if (!this.intersect(r, res)) {
return false;
}
var dist = vlength(sub(res.p, b));
if (dist > 2) return false;
return true;
}
makeSvg(s: Snap.Paper) {
var elements: Snap.Element[] = [];
var group = s.group();
group.data("thing", this);
return group;
}
}
class SinglePathSampler implements Sampler {
name: string = "Simple";
tracePath(ray: Ray, depth: number, scene: Scene): PathData[] {
var path: PathData = new PathData();
path.points = [];
path.properties = new Set<string>();
path.points.push({ p: ray.o, n: ray.d, shape: null});
for (var i = 0; i < depth; i++) {
var intersect: Intersection = new Intersection();
if (!scene.intersect(ray, intersect)) {
path.points.push({ p: add(ray.o, mul(ray.d, 20000)), n: ray.d, shape: null});
break;
}
path.points.push(intersect);
if (intersect.shape instanceof Light) {
path.properties.add("HitLight");
break;
}
ray.o = intersect.p;
ray.d = reflect(ray.d, intersect.n);
ray.o = add(ray.o, mul(ray.d, 0.1));
}
return [path];
}
}
class OffsetPathSampler implements Sampler {
name: string = "Offset";
tracePath(ray: Ray, depth: number, scene: Scene): PathData[] {
if (depth < 0) return [];
var mat = Snap.matrix();
setRotation(mat, -5);
var offsetRay: Ray = new Ray(ray.o.clone(), transformDir(ray.d, mat));
var basePath: PathData = new PathData();
var result: PathData[] = [];
basePath.properties = new Set<string>();
basePath.points = [];
basePath.points.push({ p: ray.o, n: ray.d, shape: null });
for (var i = 0; i < depth; i++) {
var intersect: Intersection = new Intersection();
if (!scene.intersect(ray, intersect)) {
basePath.points.push({ p: add(ray.o, mul(ray.d, 20000)), n: ray.d, shape: null });
break;
}
basePath.points.push(intersect);
if (intersect.shape instanceof Light) {
break;
}
ray.o = intersect.p;
ray.d = cosineSampleHemisphere(intersect.n);
ray.o = add(ray.o, mul(ray.d, 0.1));
}
var offsetPath: PathData = new PathData();
result.push(offsetPath);
ray = offsetRay;
offsetPath.properties = new Set<string>();
offsetPath.points = [];
offsetPath.points.push({ p: ray.o, n: ray.d, shape: null });
var intersect: Intersection = new Intersection();
if (!scene.intersect(ray, intersect)) {
offsetPath.points.push({ p: add(ray.o, mul(ray.d, 20000)), n: ray.d, shape: null });
} else {
offsetPath.points.push(intersect);
if (basePath.points.length > 2 && scene.test(add(intersect.p, mul(intersect.n, 1)), basePath.points[2].p)) {
for (var j = 2; j < basePath.points.length; j++) {
offsetPath.points.push(basePath.points[j]);
}
}
}
basePath.properties = new Set<string>();
basePath.points = [];
basePath.points.push({ p: ray.o, n: ray.d, shape: null });
for (var i = 0; i < depth; i++) {
var intersect: Intersection = new Intersection();
if (!scene.intersect(ray, intersect)) {
basePath.points.push({ p: add(ray.o, mul(ray.d, 20000)), n: ray.d, shape: null });
break;
}
basePath.points.push(intersect);
if (intersect.shape instanceof Light) {
break;
}
ray.o = intersect.p;
ray.d = cosineSampleHemisphere(intersect.n);
ray.o = add(ray.o, mul(ray.d, 0.1));
}
result.push(basePath);
offsetPath.properties.add("HitLight");
return result;
}
}
var sampleDirFunc = ko.observable<(intersect: Intersection, ray: Ray, scene: Scene) => Vec2[]>();
class ScriptedPathSampler implements Sampler {
name: string = "Scripted";
sampleDir: KnockoutObservable<(intersect: Intersection, ray: Ray, scene: Scene) => Vec2[]>;
tracePath(ray: Ray, depth: number, scene: Scene): PathData[] {
if (depth < 0) return [];
var sampleDir = this.sampleDir();
if (!sampleDir) {
return [];
}
var path: PathData = new PathData();
var result: PathData[] = [];
result.push(path);
path.properties = new Set<string>();
path.points = [];
path.points.push({ p: ray.o, n: ray.d, shape: null });
var intersect: Intersection = new Intersection();
if (!scene.intersect(ray, intersect)) {
path.points.push({ p: add(ray.o, mul(ray.d, 20000)), n: ray.d, shape: null });
return result;
}
path.points.push(intersect);
if (intersect.shape instanceof Light) {
path.properties.add("HitLight");
return result;
}
var dirs: Vec2[];
try {
dirs = sampleDir(intersect, ray, scene);
} catch (runtimeError) {
$("#code-footer").text("Sample Error:" + runtimeError.name + "-" + runtimeError.message);
return result;
}
if (!dirs) {
return result;
}
for (var dir of dirs) {
var r: Ray = new Ray(add(intersect.p, mul(dir, 1)), dir);
var newPaths: PathData[];
try {
newPaths = this.tracePath(r, depth - 1, scene);
} catch (runtimeError) {
$("#code-footer").text("Trace Path Error:" + runtimeError.name + "-" + runtimeError.message);
return result;
}
for (var newPath of newPaths) {
newPath.properties.forEach((value, index, set) => {
path.properties.add(value);
}, this);
result.push(newPath);
}
}
return result;
}
}
function makeRaySVG(s: Snap.Paper, r: Ray, length: number) {
var target = add(r.o, mul(r.d, length));
return s.line(r.o.x, r.o.y, target.x, target.y);
}
declare function unescape(s:string): string;
var s: Snap.Paper;
var scene: Scene;
function toDataUrl(e: Snap.Element, maxWidth: number, maxHeight: number) {
var bb = e.getBBox();
var x = Math.max(+bb.x.toFixed(3), 0) - 3;
var y = Math.max(+ bb.y.toFixed(3), 0) - 3;
var w = Math.min(+ bb.width.toFixed(3), maxWidth) + x + 3;
var h = Math.min(+ bb.height.toFixed(3), maxHeight) + y + 3;
var img: Snap.Element;
if (scene.renderPathDensity()) {
var canvas = <HTMLCanvasElement>document.getElementById("density");
var imageStrg = canvas.toDataURL();
img = s.image(imageStrg, 0, 0, maxWidth, maxHeight);
}
var svg = Snap.format('<svg version="1.2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{width}" height="{height}" viewBox="{x} {y} {width} {height}">{contents}</svg>', {
x: x,
y: y,
width: w,
height: h,
contents: e.outerSVG()
});
if (img) {
svg = svg.replace("href", "xlink:href");
img.remove();
}
return "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svg)));
}
window.onload = () => {
s = Snap("#svg-container");
var cam = new Camera(new Vec2(100, 100), 45, s);
CAM_MATERIAL().applyTo(cam);
var pathSampler = new ScriptedPathSampler();
pathSampler.sampleDir = sampleDirFunc;
scene = new Scene(pathSampler, s);
scene.materials.push(DEFAULT_MATERIAL());
scene.materials.push(CAM_MATERIAL());
scene.materials.push(PATH_MATERIAL());
scene.materials.push(LIGHT_MATERIAL());
var canvas = <HTMLCanvasElement>document.getElementById("density");
var svgEl = document.getElementById("svg-container");
var width = $(svgEl).width();
var height = $(svgEl).height();
window.addEventListener("resize", () => {
canvas.width = $(svgEl).width();
canvas.height = $(svgEl).height();
scene.recalculatePaths();
}, true);
var svgEl = document.getElementById("svg-container");
var width = $(svgEl).width();
var height = $(svgEl).height();
canvas.width = width;
canvas.height = height;
scene.canvas = <CanvasRenderingContext2D>canvas.getContext("2d");
var sampleCanvas = <HTMLCanvasElement>document.getElementById("sample-space");
sampleCanvas.width = $(sampleCanvas).width();
sampleCanvas.height = sampleCanvas.width;
scene.sampleSpaceVis = new SampleSpaceVisualization(<CanvasRenderingContext2D>sampleCanvas.getContext("2d"));
scene.sampleSpaceVis.drawLabels.subscribe((newVal) => scene.recalculatePaths(), scene);
scene.availableSamplers.push(new OffsetPathSampler(), new SinglePathSampler());
sampleCanvas.addEventListener("mousemove", (e: MouseEvent) => {
if (e.button == 0 && !e.shiftKey) return;
var x = (e.pageX - sampleCanvas.offsetLeft) / sampleCanvas.offsetWidth;
var y = (e.pageY - sampleCanvas.offsetTop) / sampleCanvas.offsetHeight;
console.log(new Vec2(x, y));
scene.sampleSpaceVis.selectedCoordinates(new Vec2(x, y));
scene.recalculatePaths();
}, this);
scene.addCamera(cam);
scene.addShape(new Circle(new Vec2(250, 280), 50, s));
scene.addShape(new Light(new Vec2(300, 200), 4, s));
var deformedCircle = new Circle(new Vec2(250, 150), 30, s);
deformedCircle.scale(new Vec2(30.0, 30.0));
deformedCircle.rot(0);
scene.addShape(deformedCircle);
scene.addShape(new Box(new Vec2(250, 50), new Vec2(20, 40), s));
var mat = Snap.matrix();
var points: Vec2[] = [];
var xAxis = new Vec2(1, 0);
var count = 40;
for (var i = 0; i < count; i++) {
mat.rotate(360 / count);
var angle = 360 / count * i;
var p = transformPoint(xAxis, mat);
points.push(mul(p, Math.sin(angle * 4) * 0.5 * Math.cos(angle + 10) + 2.0));
}
var poly = new Polygon(points, s);
poly.scale(new Vec2(40, 40));
scene.addShape(poly);
ko.applyBindings(scene);
}
function saveSvg() {
var svgEl = document.getElementById("svg-container");
var width = $(svgEl).width();
var height = $(svgEl).height();
var saveButton = document.getElementById("save-button");
saveButton.setAttribute("href", toDataUrl(s, width, height));
} | the_stack |
declare var describe: any, console: any;
import * as expect from 'expect';
import { findNodesByType, Nodes, PhaseFlags } from '../dist/compiler/nodes';
import { folderBasedTest, testParseToken, testParseTokenFailsafe, PhasesResult } from './TestHelpers';
import { ParsingContext } from '../dist/compiler/ParsingContext';
import { printNode } from '../dist/utils/nodePrinter';
import { printAST } from '../dist/utils/astPrinter';
import { nodeSystem } from '../dist/support/NodeSystem';
const parsingContext = new ParsingContext(nodeSystem);
parsingContext.paths.push(nodeSystem.resolvePath(__dirname, '../stdlib'));
describe('Semantic', function () {
const semanticPhases = function (txt: string, fileName: string): PhasesResult {
parsingContext.reset();
const moduleName = parsingContext.getModuleFQNForFile(fileName);
parsingContext.invalidateModule(moduleName);
parsingContext.getParsingPhaseForContent(fileName, moduleName, txt);
return { parsingContext, document: parsingContext.getPhase(moduleName, PhaseFlags.Semantic) };
};
const scopePhases = function (txt: string, fileName: string): PhasesResult {
parsingContext.reset();
const moduleName = parsingContext.getModuleFQNForFile(fileName);
parsingContext.invalidateModule(moduleName);
parsingContext.getParsingPhaseForContent(fileName, moduleName, txt);
return { parsingContext, document: parsingContext.getPhase(moduleName, PhaseFlags.Scope) };
};
describe('Files', () => {
folderBasedTest(
'test/fixtures/semantics/*.lys',
scopePhases,
async (result, err) => {
if (err) throw err;
if (!result) throw new Error('No result');
return printAST(result.document);
},
'.ast'
);
folderBasedTest(
'test/fixtures/semantics/*.lys',
semanticPhases,
async (result, err) => {
if (err) throw err;
if (!result) throw new Error('No result');
return printNode(result.document);
},
'.desugar'
);
describe('Compilation-execution-tests-desugar', () => {
folderBasedTest(
'**/execution/*.lys',
semanticPhases,
async (result, err) => {
if (err) throw err;
if (!result) throw new Error('No result');
return printNode(result.document);
},
'.desugar'
);
});
});
let semanticTestCount = 0;
function getFileName() {
return `tests/semantic_tests_${semanticTestCount++}.lys`;
}
function test(literals: any, ...placeholders: any[]) {
let result = '';
// interleave the literals with the placeholders
for (let i = 0; i < placeholders.length; i++) {
result += literals[i];
result += placeholders[i];
}
// add the last literal
result += literals[literals.length - 1];
testParseToken(
result,
getFileName(),
async (_, e) => {
if (e) throw e;
expect(parsingContext.messageCollector.hasErrors()).toEqual(false);
},
scopePhases
);
}
function testToFail(literals: any, ...placeholders: any) {
let result = '';
// interleave the literals with the placeholders
for (let i = 0; i < placeholders.length; i++) {
result += literals[i];
result += placeholders[i];
}
// add the last literal
result += literals[literals.length - 1];
testParseTokenFailsafe(
result,
'MUST_FAIL_' + getFileName(),
async (result, err) => {
const didFail = !!err || !result || parsingContext.messageCollector.hasErrors();
if (!didFail && result) {
console.log(result);
console.log(printAST(result.document));
console.log(result.document.scope!.inspect());
}
expect(didFail).toEqual(true);
},
scopePhases,
false
);
}
describe('Duplicated parameters', () => {
test`
fun test(a: i32, b: i32): i32 = 1
`;
testToFail`
fun test(a: i32, a: i32): i32 = 1
`;
});
describe('scope shadowing', () => {
test`
enum x {
Nila
}
fun f(x: x): x = ???
`;
test`
enum x {
Nila
}
fun f(x: x): x = ???
`;
testToFail`
enum N {
x
}
fun x(): void = ???
`;
testToFail`
enum x {
N
}
fun x(): void = ???
`;
testToFail`
struct x()
fun x(): void = ???
`;
});
describe('conditionals', () => {
test`
fun gcd(x: i32, y: i32): i32 =
if (x > y)
gcd(x - y, y)
else if (x < y)
gcd(x, y - x)
else
x
`;
testParseToken(
`
var x = 1
var b = false
fun a(): void = {
if (x < 3) a()
b
}`,
getFileName(),
async (result, e) => {
if (e) throw e;
if (!result) throw new Error('No result');
const refs = findNodesByType(result.document, Nodes.BlockNode);
const statements = refs[0].statements;
expect(statements.length).toBe(2);
},
scopePhases
);
testParseToken(
`
var x = 1
var b = false
fun a(): void = {
if (x < 3) { a() }
b
}`,
getFileName(),
async (result, e) => {
if (e) throw e;
if (!result) throw new Error('No result');
const refs = findNodesByType(result.document, Nodes.BlockNode);
const statements = refs[0].statements;
expect(statements.length).toBe(2);
},
scopePhases
);
});
describe('namespaces', () => {
test`
type BB = %injected
type AA = BB
impl BB {
fun gta(): i32 = 1
}
fun test(a: i32): boolean = BB.gta()
`;
testToFail`
type BB = %injected
type AA = BB
impl BB {
fun gtax(): i32 = 1
}
fun test(a: i32): i32 = gtax()
`;
test`
type BB = %injected
impl BB {
var x = 1
fun gtax(): i32 = x
}
fun test(a: i32): i32 = BB.gtax()
`;
test`
struct ExistentType()
impl ExistentType {
// stub
}
`;
test`
struct ExistentType()
impl ExistentType {
fun gtax(): i32 = 1
}
fun test(a: i32): i32 = ExistentType.gtax()
`;
});
describe('Pattern matching', () => {
test`
fun test(a: i32): boolean = match a {
case 1 -> true
else -> false
}
`;
testToFail`
fun test(a: i32): void = match a { }
`;
testToFail`
fun test(a: i32): i32 = match a { else -> 1 }
`;
});
describe('block', () => {
testParseToken(
`
fun map(a: i32,b: i32): i32 = a
fun a(): i32 = {
map(1,3)
}`,
getFileName(),
async (result, e) => {
if (e) throw e;
if (!result) throw new Error('No result');
const refs = findNodesByType(result.document, Nodes.BlockNode);
const statements = refs[0].statements;
expect(statements.length).toBe(1);
},
scopePhases
);
testParseToken(
`
fun main(): i32 = {
var a: i32 = 1
a = 2
a
}
`,
getFileName(),
async (result, e) => {
if (e) throw e;
if (!result) throw new Error('No result');
const refs = findNodesByType(result.document, Nodes.BlockNode);
const statements = refs[0].statements;
expect(statements.length).toBe(3);
},
scopePhases
);
testParseToken(
`
fun map(a: i32,b: i32): i32 = a
var b = false
fun a(): i32 = {
(1).map(3)
b
}`,
getFileName(),
async (result, e) => {
if (e) throw e;
if (!result) throw new Error('No result');
const refs = findNodesByType(result.document, Nodes.BlockNode);
const statements = refs[0].statements;
expect(statements.length).toBe(2);
},
scopePhases
);
});
describe('module resolution', () => {
testParseToken(
`
fun a(): void = {}
`,
getFileName(),
async (result, e) => {
if (e) throw e;
if (!result) throw new Error('No result');
expect(result.document.scope!.importedModules.has('system::core::native')).toEqual(true);
},
scopePhases
);
testParseToken(
`
import system::core
import system::random
fun a(): void = {}
`,
getFileName(),
async (result, e) => {
if (e) throw e;
if (!result) throw new Error('No result');
expect(result.document.scope!.importedModules.has('system::core')).toEqual(true);
expect(result.document.scope!.importedModules.has('system::random')).toEqual(true);
},
scopePhases
);
testParseToken(
`
fun a(): i32 = system::random::nextInt()
`,
getFileName(),
async (result, e) => {
if (e) throw e;
if (!result) throw new Error('No result');
expect(result.document.scope!.importedModules.has('system::core::i32')).toEqual(true);
},
scopePhases
);
testParseToken(
`
fun hash(): i32 = 1
`,
getFileName(),
async (result, e) => {
if (e) throw e;
if (!result) throw new Error('No result');
expect(result.document.scope!.importedModules.has('system::core::i32')).toEqual(true);
},
scopePhases
);
});
describe('Scopes', () => {
test`
val a = true
fun test(): boolean = a
`;
test`
val a = true
fun test(): boolean = a
`;
test`
val a = true
fun test(): boolean = a
`;
test`
fun test(): void = test
`;
test`
var a = 1
fun test(a: i32): i32 = a
`;
test`
import system::core::string
`;
testToFail`
import system::moduleThatDoesNotExist
`;
test`
type i32 = %stack { lowLevelType="i32" byteSize=4 }
var a: i32 = 1
`;
testToFail`var a: i32a = 1`;
testToFail`
type i32 = %stack { lowLevelType="i32" byteSize=4 }
var i32 = 1
`;
test`
var a = 1
var b = a
`;
testToFail`
fun test(a: i32): i32 = b
`;
});
}); | the_stack |
import { expect } from "chai";
import * as fs from "fs";
import { ClipPlane } from "../../clipping/ClipPlane";
import { ClipUtilities } from "../../clipping/ClipUtils";
import { ConvexClipPlaneSet } from "../../clipping/ConvexClipPlaneSet";
import { UnionOfConvexClipPlaneSets } from "../../clipping/UnionOfConvexClipPlaneSets";
import { Arc3d } from "../../curve/Arc3d";
import { GeometryQuery } from "../../curve/GeometryQuery";
import { LineSegment3d } from "../../curve/LineSegment3d";
import { LineString3d } from "../../curve/LineString3d";
import { StrokeOptions } from "../../curve/StrokeOptions";
import { Geometry } from "../../Geometry";
import { Angle } from "../../geometry3d/Angle";
import { GrowableXYZArray } from "../../geometry3d/GrowableXYZArray";
import { Matrix3d } from "../../geometry3d/Matrix3d";
import { Plane3dByOriginAndUnitNormal } from "../../geometry3d/Plane3dByOriginAndUnitNormal";
import { Point3d, Vector3d } from "../../geometry3d/Point3dVector3d";
import { IndexedXYZCollectionPolygonOps, PolygonOps } from "../../geometry3d/PolygonOps";
import { Range2d, Range3d } from "../../geometry3d/Range";
import { Transform } from "../../geometry3d/Transform";
import { IndexedPolyface, Polyface } from "../../polyface/Polyface";
import { PolyfaceBuilder } from "../../polyface/PolyfaceBuilder";
import { ClippedPolyfaceBuilders, PolyfaceClip } from "../../polyface/PolyfaceClip";
import { PolyfaceQuery } from "../../polyface/PolyfaceQuery";
import { Sample } from "../../serialization/GeometrySamples";
import { IModelJson } from "../../serialization/IModelJsonSchema";
import { Box } from "../../solid/Box";
import { LinearSweep } from "../../solid/LinearSweep";
import { SweepContour } from "../../solid/SweepContour";
import { Checker } from "../Checker";
import { GeometryCoreTestIO } from "../GeometryCoreTestIO";
import { RFunctions } from "../polyface/DrapeLinestring.test";
/* eslint-disable no-console */
describe("PolyfaceClip", () => {
it("ClipPlane", () => {
const ck = new Checker();
const polyface = Sample.createTriangularUnitGridPolyface(Point3d.create(0, 0, 0), Vector3d.unitX(), Vector3d.unitY(), 3, 4);
const clipper = ClipPlane.createNormalAndPointXYZXYZ(1, 1, 0, 1, 1, 1)!;
const leftClip = PolyfaceClip.clipPolyface(polyface, clipper)!;
const rightClip = PolyfaceClip.clipPolyfaceClipPlane(polyface, clipper, false)!;
const area = PolyfaceQuery.sumFacetAreas(polyface);
const areaLeft = PolyfaceQuery.sumFacetAreas(leftClip);
const areaRight = PolyfaceQuery.sumFacetAreas(rightClip);
const allGeometry: GeometryQuery[] = [];
GeometryCoreTestIO.captureGeometry(allGeometry, polyface, 0, 0, 0);
GeometryCoreTestIO.captureGeometry(allGeometry, leftClip, 0, 10, 0);
GeometryCoreTestIO.captureGeometry(allGeometry, rightClip, 0, 10, 0);
ck.testCoordinate(area, areaLeft + areaRight);
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "ClipPlane");
expect(ck.getNumErrors()).equals(0);
});
it("EdgeInClipPlane", () => {
const ck = new Checker();
const polyface = Sample.createTriangularUnitGridPolyface(Point3d.create(0, 0, 0), Vector3d.unitX(), Vector3d.unitY(), 3, 2);
const clipper = ClipPlane.createNormalAndPointXYZXYZ(1, 0, 0, 1, 0, 0)!;
const leftClip = PolyfaceClip.clipPolyface(polyface, clipper)!;
const rightClip = PolyfaceClip.clipPolyfaceClipPlane(polyface, clipper, false)!;
const area = PolyfaceQuery.sumFacetAreas(polyface);
const areaLeft = PolyfaceQuery.sumFacetAreas(leftClip);
const areaRight = PolyfaceQuery.sumFacetAreas(rightClip);
const allGeometry: GeometryQuery[] = [];
GeometryCoreTestIO.captureGeometry(allGeometry, polyface, 0, 0, 0);
GeometryCoreTestIO.captureGeometry(allGeometry, leftClip, 0, 10, 0);
GeometryCoreTestIO.captureGeometry(allGeometry, rightClip, 0, 10, 0);
ck.testCoordinate(area, areaLeft + areaRight);
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "EdgeInClipPlane");
expect(ck.getNumErrors()).equals(0);
});
it("ConvexClipPlaneSet", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const vectorU = Vector3d.create(1, -1, 0);
const vectorV = Vector3d.create(1, 2, 0);
const singleFacetArea = vectorU.crossProductMagnitude(vectorV);
const xEdges = 4;
const yEdges = 5;
const polyface = Sample.createTriangularUnitGridPolyface(Point3d.create(0, 0, 0.5), vectorU, vectorV, xEdges + 1, yEdges + 1);
const clipX0 = 2;
const clipY0 = 0.5;
const ax = 1.0;
const ay = 2.0;
const clipper = ConvexClipPlaneSet.createXYBox(clipX0, clipY0, clipX0 + ax, clipY0 + ay);
const displayRange = Range3d.createXYZXYZ(0, 0, -2, 10, 10, 2);
const clipperEdges = ClipUtilities.loopsOfConvexClipPlaneIntersectionWithRange(clipper, displayRange);
const x0 = 0;
const outputStep = 20.0;
const y0 = 0;
const y1 = y0 + outputStep;
const clippedOutput = PolyfaceClip.clipPolyface(polyface, clipper)!;
const area = PolyfaceQuery.sumFacetAreas(polyface);
ck.testCoordinate(xEdges * yEdges * singleFacetArea, area);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, polyface, x0, y0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clippedOutput, x0, y1, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clipperEdges, x0, y0);
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "ConvexClipPlaneSet");
expect(ck.getNumErrors()).equals(0);
});
it("UnionOfConvexClipPlaneSet.Disjoint", () => {
const doDisjointClipTest = false;
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const edgeLength = 2.0;
const vectorU = Vector3d.create(edgeLength, 0, 0);
const vectorV = Vector3d.create(0, edgeLength, 0);
let x0 = 0;
const y0 = 0;
const xEdges = 4;
const yEdges = 5;
const polyfaceP3 = Sample.createTriangularUnitGridPolyface(Point3d.create(0, 0, 0), vectorU, vectorV, xEdges + 1, yEdges + 1);
const polyfaceP4 = Sample.createTriangularUnitGridPolyface(Point3d.create(0, 0, 0), vectorU, vectorV, xEdges + 1, yEdges + 1, false, false, false, false);
const polyfaceQ3 = Sample.createTriangularUnitGridPolyface(Point3d.create(0, 0, 0), vectorU.scale(xEdges), vectorV.scale(yEdges), 2, 2);
const polyfaceQ4 = Sample.createTriangularUnitGridPolyface(Point3d.create(0, 0, 0), vectorU.scale(xEdges), vectorV.scale(yEdges), 2, 2, false, false, false, false);
for (const polyface of [polyfaceQ4, polyfaceP3, polyfaceQ3, polyfaceP4]) {
const range = polyface.range();
const dY = range.yLength() * 1.5;
const dX = range.xLength() * 2;
const dZ = 0.2;
const ax = 1.0;
const ay = 2.0;
const clipperX0 = 2;
const clipperY0 = 0.5;
const clipperX2 = clipperX0 + 2 * ax;
const clipPlane = ClipPlane.createNormalAndPointXYZXYZ(clipperX0, clipperY0, 0, 2, 1, 1)!;
const clipper0 = ConvexClipPlaneSet.createXYBox(clipperX0, clipperY0, clipperX0 + ax, clipperY0 + ay);
const clipper2 = ConvexClipPlaneSet.createXYBox(clipperX2, clipperY0 + 0.25, clipperX2 + ax, clipperY0 + ay + 0.5);
const clipper02 = UnionOfConvexClipPlaneSets.createConvexSets([clipper2, clipper0]);
// NEEDS WORK: clipper02 breaks tests !!!
const clippers: Array<ClipPlane | ConvexClipPlaneSet | UnionOfConvexClipPlaneSets> = [clipper0, clipper2, clipPlane];
if (doDisjointClipTest)
clippers.unshift(clipper02);
for (const clipper of clippers) {
const clipperEdges = ClipUtilities.loopsOfConvexClipPlaneIntersectionWithRange(clipper, range);
// The mesh should be big enough to completely contain the clip -- hence output area is known .....
for (const outputSelect of [1, 0]) {
const builders = ClippedPolyfaceBuilders.create(true, true);
PolyfaceClip.clipPolyfaceInsideOutside(polyface, clipper, builders, outputSelect);
const area = PolyfaceQuery.sumFacetAreas(polyface);
const polyfaceA = builders.claimPolyface(0, true);
const polyfaceB = builders.claimPolyface(1, true);
const areaA = PolyfaceQuery.sumFacetAreas(polyfaceA);
const areaB = PolyfaceQuery.sumFacetAreas(polyfaceB);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, polyface, x0, y0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clipperEdges, x0, y0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, polyfaceA, x0, y0 + dY, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, polyfaceB, x0, y0 + 2 * dY, 0);
const boundaryB = PolyfaceQuery.boundaryEdges(polyfaceB);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, boundaryB, x0, y0 + 2 * dY, dZ);
if (polyfaceB) {
const polyfaceB1 = PolyfaceQuery.cloneWithTVertexFixup(polyfaceB);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, polyfaceB1, x0, y0 + 3 * dY, 0);
const boundaryB1 = PolyfaceQuery.boundaryEdges(polyfaceB1);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, boundaryB1, x0, y0 + 3 * dY, dZ);
}
if (!ck.testCoordinate(area, areaA + areaB, " sum of inside and outside clip areas")) {
GeometryCoreTestIO.captureCloneGeometry(allGeometry, polyface, x0, y0 + 5 * dY, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clipperEdges, x0, y0 + 5 * dY, 0);
}
x0 += dX;
}
}
x0 += 2.0 * dX;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "UnionOfConvexClipPlaneSet.Disjoint");
expect(ck.getNumErrors()).equals(0);
});
/** Test PolyfaceBuilder.addPolygon variants with reverse normals. */
it("addPolygon", () => {
const ck = new Checker();
const points0 = [Point3d.create(0, 0), Point3d.create(1, 0), Point3d.create(0, 2)];
const points1 = [Point3d.create(0, 0, 1), Point3d.create(1, 0, 1), Point3d.create(0, 2, 1), Point3d.create(0, 0, 1)]; // with duplicate !
const growable0 = new GrowableXYZArray();
growable0.pushFrom(points0);
const growable1 = new GrowableXYZArray();
growable1.pushFrom(points1);
const singleFacetArea = PolygonOps.areaNormalGo(growable0)!.magnitude();
const builderG = PolyfaceBuilder.create();
builderG.addPolygonGrowableXYZArray(growable0);
// exercise reverse-order block of addPolygonGrowableXYZArray
builderG.toggleReversedFacetFlag();
builderG.addPolygonGrowableXYZArray(growable1);
const polyfaceG = builderG.claimPolyface(true);
const totalAreaG = PolyfaceQuery.sumFacetAreas(polyfaceG);
const builderP = PolyfaceBuilder.create();
builderP.addPolygon(points0);
// exercise reverse-order block of addPolygonGrowableXYZArray
builderP.toggleReversedFacetFlag();
builderP.addPolygon(points1);
const polyfaceP = builderP.claimPolyface(true);
const totalAreaP = PolyfaceQuery.sumFacetAreas(polyfaceG);
ck.testCoordinate(totalAreaG, totalAreaP);
ck.testCoordinate(2 * singleFacetArea, totalAreaP);
ck.testCoordinate(2 * singleFacetArea, totalAreaG);
const allGeometry: GeometryQuery[] = [];
GeometryCoreTestIO.captureGeometry(allGeometry, polyfaceG, 0, 0, 0);
GeometryCoreTestIO.captureGeometry(allGeometry, polyfaceP, 5, 0, 0);
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "addPolygon");
expect(ck.getNumErrors()).equals(0);
});
it("Section", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let x0 = 0.0;
const zShift = 0.01;
for (const multiplier of [1, 3]) {
x0 += multiplier * 10;
const polyface = Sample.createTriangularUnitGridPolyface(Point3d.create(0, 0, 0), Vector3d.unitX(), Vector3d.unitY(), 3 * multiplier, 4 * multiplier);
if (multiplier > 1)
polyface.data.point.mapComponent(2,
(x: number, y: number, _z: number) => {
return 1.0 * RFunctions.cosineOfMappedAngle(x, 0.0, 5.0) * RFunctions.cosineOfMappedAngle(y, -1.0, 8.0);
});
for (let q = 1; q <= multiplier + 1.5; q++) {
const clipper = ClipPlane.createNormalAndPointXYZXYZ(q, 1, 0, q, q, 1)!;
const section = PolyfaceClip.sectionPolyfaceClipPlane(polyface, clipper)!;
// save with zShift to separate cleanly from the background mesh . .
GeometryCoreTestIO.captureCloneGeometry(allGeometry, section, x0, 0, zShift);
GeometryCoreTestIO.captureGeometry(allGeometry, section, x0, 0, 0);
}
// !!! save this only at end so the x0 shift does not move the mesh for the clippers.
GeometryCoreTestIO.captureGeometry(allGeometry, polyface, x0, 0, 0);
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "Section");
expect(ck.getNumErrors()).equals(0);
});
it("ClosedSection", () => {
const ck = new Checker();
let x0 = 0.0;
const y0 = 0.0;
const y1 = 10.0;
const y2 = 20.0;
const y3 = 30.0;
const allGeometry: GeometryQuery[] = [];
const xyStar = Sample.createStar(0, 0, 0, 4, 2, 4, true);
// xyStar.reverse ();
const sweep = LinearSweep.createZSweep(xyStar, 0, 10, true)!;
const options = StrokeOptions.createForFacets();
options.maxEdgeLength = 4.0;
const builder = PolyfaceBuilder.create(options);
builder.addLinearSweep(sweep);
const facets = builder.claimPolyface(true);
const range = facets.range();
range.expandInPlace(0.5);
for (const clipPlane of [
ClipPlane.createNormalAndPointXYZXYZ(0, 0, 1, 1, 1, 3)!,
ClipPlane.createNormalAndPointXYZXYZ(1, 0.5, 0.2, 0, 1, 1)!,
ClipPlane.createNormalAndPointXYZXYZ(0, 1, 1, 1, 1, 2)!,
ClipPlane.createNormalAndPointXYZXYZ(0, 0, 1, 0, 0, 2)!]) {
for (const insideClip of [true, false]) {
const clipPlanePoints = clipPlane.intersectRange(range)!;
const frame = clipPlane.getFrame();
const section = PolyfaceClip.sectionPolyfaceClipPlane(facets, clipPlane);
const clippedPolyface = PolyfaceClip.clipPolyfaceClipPlaneWithClosureFace(facets, clipPlane, insideClip);
const cutPlane = PolyfaceBuilder.polygonToTriangulatedPolyface(clipPlanePoints.getPoint3dArray());
GeometryCoreTestIO.captureCloneGeometry(allGeometry, facets, x0, y0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutPlane, x0, y0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, section, x0, y1, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clippedPolyface, x0, y3, 0);
for (const s of section) {
if (s.isPhysicallyClosed) {
const region = PolyfaceBuilder.polygonToTriangulatedPolyface(s.packedPoints.getPoint3dArray(), frame);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, region, x0, y2, 0);
}
}
x0 += 10.0;
}
x0 += 30.0;
}
ck.testUndefined(PolyfaceBuilder.polygonToTriangulatedPolyface(
[Point3d.create(0, 0), Point3d.create(0, 1)]), "should fail triangulating less than 3 points");
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "ClosedSection");
expect(ck.getNumErrors()).equals(0);
});
it("Box", () => {
const ck = new Checker();
const builder = PolyfaceBuilder.create();
builder.addBox(Box.createRange(Range3d.create(Point3d.create(-1, -1, -1), Point3d.create(1, 1, 1)), true)!);
const facets = builder.claimPolyface();
const range = facets.range();
range.expandInPlace(0.5);
const allGeometry: GeometryQuery[] = [];
let x0 = 0;
const y0 = 0;
for (const clipPlane of [
ClipPlane.createNormalAndPointXYZXYZ(0, 0, 1, 0, 0, 0)!,
ClipPlane.createNormalAndPointXYZXYZ(0, 0, -1, 0, 0, 0)!,
ClipPlane.createNormalAndPointXYZXYZ(0, 2, 1, 0, 0, 0)!,
ClipPlane.createNormalAndPointXYZXYZ(0, 2, -1, 0, 0, 0)!]) {
const clipPlanePoints = clipPlane.intersectRange(range)!;
const frame = clipPlane.getFrame();
const dy = 2.0 * range.yLength();
const y1 = y0 + dy;
const y2 = y1 + dy;
const y3 = y2 + dy;
const y4 = y3 + dy;
const section = PolyfaceClip.sectionPolyfaceClipPlane(facets, clipPlane);
const insideClip = PolyfaceClip.clipPolyfaceClipPlaneWithClosureFace(facets, clipPlane, true, true);
const outsideClip = PolyfaceClip.clipPolyfaceClipPlaneWithClosureFace(facets, clipPlane, false, true);
const cutPlane = PolyfaceBuilder.polygonToTriangulatedPolyface(clipPlanePoints.getPoint3dArray());
GeometryCoreTestIO.captureCloneGeometry(allGeometry, facets, x0, y0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutPlane, x0, y0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, section, x0, y1, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, insideClip, x0, y3, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, outsideClip, x0, y4, 0);
for (const s of section) {
if (s.isPhysicallyClosed) {
const region = PolyfaceBuilder.polygonToTriangulatedPolyface(s.packedPoints.getPoint3dArray(), frame);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, region, x0, y2, 0);
}
}
x0 += 10.0;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "Box");
expect(ck.getNumErrors()).equals(0);
});
it("TwoComponentSection", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const meshJSON = {
indexedMesh: {
point: [
[-1314.6730196637218, -57.10471794754267, -5.490003639162751], [-1314.896312748082, -56.537848295643926, -5.510317207634216], [-1314.8979232803686, -56.533829868771136, -5.3803893105941825],
[-1314.6956910152803, -57.04815019853413, -3.662215652904706], [-1314.9189832430566, -56.48128271847963, -3.6825291425338946], [-1314.7091404076782, -57.0142579190433, -3.1975819905346725],
[-1314.9231749525643, -56.47075137402862, -3.478972522978438], [-1314.9421641827794, -56.42276875022799, -3.0638822874461766], [-1314.7390657665092, -56.93854473717511, -2.7227602402563207],
[-1314.976242534176, -56.336483863182366, -2.6424124827608466], [-1314.7866303779301, -56.81805418152362, -2.2439098892791662], [-1315.0262713459088, -56.209706934168935, -2.220409367873799],
[-1314.834356342326, -56.69708855636418, -1.88633862361894], [-1314.8925853258697, -56.549456998705864, -1.5336732444993686], [-1315.0927135171369, -56.04125931020826, -1.8044034888444003],
[-1314.961282182252, -56.37524692341685, -1.1892659660661593], [-1315.1755565702333, -55.831168909557164, -1.4013555171550252], [-1315.0402223932906, -56.17502646334469, -0.856507872173097],
[-1315.274262645049, -55.58079734817147, -1.0183311252039857], [-1315.1289869659813, -55.949857488274574, -0.5387295018008444], [-1315.3580743367784, -55.368176135234535, -0.7483150090265553],
[-1315.226965778158, -55.70128717646003, -0.2390975789166987], [-1315.4495686356095, -55.13604204170406, -0.4960487415373791], [-1315.333369733533, -55.431317169219255, 0.03948582641896792],
[-1315.5479536699713, -54.88640406168997, -0.2638915148272645], [-1315.652313624567, -54.621586034074426, -0.05384081805823371], [-1315.4472513569053, -55.142351396381855, 0.2944752340845298],
[-1319.4383521693526, -45.007064340636134, -5.923518669005716], [-1319.439963756071, -45.00304323993623, -5.793590867804596], [-1315.5675327406498, -54.83712511882186, 0.5237587880692445],
[-1315.7989962851861, -54.249344075098634, 0.18917484689154662], [-1319.6616452540038, -44.440194689668715, -5.9438322374771815], [-1315.6930391303613, -54.518619729205966, 0.7257155363040511],
[-1315.951936306432, -53.8611929519102, 0.3876608006248716], [-1315.8225359838107, -54.18996868748218, 0.8992497764993459], [-1316.1085139245843, -53.46378275100142, 0.5406269291997887],
[-1315.9547671198961, -53.854360677301884, 1.043801223830087], [-1316.266183029511, -53.063577332533896, 0.6485063915024512], [-1316.0884916253272, -53.5149458842352, 1.1593317580409348],
[-1316.4225866948836, -52.66656098328531, 0.7129976582655217], [-1319.4610235207947, -44.95049659349024, -4.095730682747671], [-1316.2225174400955, -53.17475076112896, 1.2462912875053007],
[-1316.5756449538749, -52.27801544778049, 0.7368380023690406], [-1319.6843166055623, -44.38362694066018, -4.1160442512482405], [-1319.4593420174788, -44.95498723257333, -3.6845272506179754],
[-1316.3997749281116, -52.72479889634997, 1.3193813897960354], [-1319.6824109015288, -44.388716329820454, -3.650013694772497], [-1319.4433784229914, -44.99574109353125, -3.2617125234392006],
[-1316.5732409551856, -52.284447288140655, 1.3464004472771194], [-1319.411973949289, -45.07569708675146, -2.8325225476583], [-1319.6643188276794, -44.43490403983742, -3.1708236702834256],
[-1317.2765918981167, -50.49853556416929, 0.6730709861731157], [-1319.3643031304819, -45.196947483345866, -2.4030360869364813], [-1319.6287270910107, -44.52552083041519, -2.6844083640899044],
[-1319.2999650278944, -45.36050648894161, -1.979977705545025], [-1319.5899691355298, -44.62411019485444, -2.3189694250759203], [-1319.2190551686217, -45.56612777058035, -1.5704381284012925],
[-1317.9176058679004, -48.871206316165626, 0.6147562326223124], [-1319.540610271506, -44.74960973486304, -1.9565164920932148], [-1319.1222068965435, -45.81219966430217, -1.1815293378895149],
[-1318.0697283439804, -48.48499567061663, 0.5631527817167807], [-1319.039797498146, -46.02155460137874, -0.9074735297763254], [-1319.4806025013677, -44.90213949885219, -1.6004006100120023],
[-1318.2241813773871, -48.09284638334066, 0.47038205052376725], [-1318.9497548320796, -46.250277870334685, -0.6514305796881672], [-1318.3788218617556, -47.70019774045795, 0.3340909504913725],
[-1318.8192631817656, -46.58171500824392, -0.34194668068084866], [-1319.4100858065067, -45.08134227246046, -1.2540460220188834], [-1318.5312560963794, -47.3131257770583, 0.1530131880135741],
[-1318.6789329773746, -46.93810682557523, -0.07282068848144263], [-1317.9351099316264, -48.82709795888513, 1.2225075878959615], [-1319.3293957076385, -45.286364460363984, -0.920851907460019],
[-1318.1075154047576, -48.38939256221056, 1.164023675955832], [-1319.2390624813852, -45.51585812214762, -0.6040887353592552], [-1318.282562176406, -47.944956701248884, 1.0588835139351431],
[-1319.139801532845, -45.76800546422601, -0.3067954441939946], [-1318.414131053025, -47.61089193448424, 0.9477621258411091], [-1319.032495127176, -46.040565280243754, -0.0316839705046732],
[-1318.5446913255146, -47.2793722813949, 0.8081888991291635], [-1318.9181664104108, -46.330938938073814, 0.2189426910772454], [-1318.6730424726848, -46.95344530697912, 0.6399315853777807],
[-1318.7979473226587, -46.63625187240541, 0.44325374250183813], [-1306.8970196380978, -54.03787715174258, -5.383082429820206], [-1307.1203127235058, -53.471007496118546, -5.403395998291671],
[-1307.123446831596, -53.46758996602148, -5.273489050625358], [-1306.9411242355127, -53.98976263590157, -3.5555891540134326], [-1307.164416463871, -53.42289515584707, -3.575902643526206],
[-1306.960030266142, -53.958022441715, -3.091030521376524], [-1307.1709969213116, -53.41330592986196, -3.372378869680688], [-1307.1948683849187, -53.36724884994328, -2.9573557656549383],
[-1306.9955491531873, -53.884515340439975, -2.6162856828595977], [-1307.2339197730762, -53.282925319857895, -2.535954341001343], [-1307.0487732768524, -53.76625688839704, -2.137513151013991],
[-1307.288944863947, -53.158118915744126, -2.1140199257060885], [-1307.100738369627, -53.64696316886693, -1.7800001740106381], [-1307.1631602107664, -53.50098526477814, -1.4273924473382067],
[-1307.3603305587312, -52.991621006280184, -1.6980820209137164], [-1307.2359643492382, -53.32839509379119, -1.0830416447133757], [-1307.4479828339536, -52.783427353948355, -1.2951001767651178],
[-1307.3188863100368, -53.129745027050376, -0.7503383005096111], [-1307.5512804948376, -52.53486670553684, -0.9121389198116958], [-1307.4114676423487, -52.90608137752861, -0.4326124111539684],
[-1307.6383442233782, -52.32352809049189, -0.6421675197198056], [-1307.5130604805308, -52.65893642697483, -0.133030181779759], [-1307.7328908390482, -52.092597825452685, -0.3899432220205199],
[-1307.6228408953757, -52.39029809460044, 0.1455067968054209], [-1307.834099994041, -51.84407367184758, -0.15782482747454196], [-1307.9410314990673, -51.58026986103505, 0.052190510177752],
[-1307.7398305887473, -52.10255813319236, 0.4004534680279903], [-1311.6623521425645, -41.94022354390472, -5.816597459604964], [-1311.665487305203, -41.9368033381179, -5.686690607864875],
[-1307.862925764406, -51.798441612161696, 0.6296983319043647], [-1308.090716930572, -51.209212188608944, 0.29516488648368977], [-1311.8856452268665, -41.373353890143335, -5.836911028047325],
[-1307.9909314328688, -51.48092193715274, 0.8316207147436216], [-1308.2461448091199, -50.82204227428883, 0.4936166317493189], [-1308.1225989012164, -51.1531269820407, 1.0051251085824333],
[-1308.4046809814172, -50.425404525361955, 0.6465558299678378], [-1308.2566640858422, -50.818242316134274, 1.1496513374440838], [-1308.5637816990493, -50.025763732381165, 0.7544156073709019],
[-1308.3918843068532, -50.47941743209958, 1.2651613053458277], [-1308.7211074174847, -49.62911103852093, 0.8188941958360374], [-1311.7064567398047, -41.89210902992636, -3.98910418379819],
[-1308.5270715028164, -50.13968035392463, 1.3521048656548373], [-1308.874608016049, -49.24073995836079, 0.8427284576755483], [-1311.9297498240485, -41.32523937523365, -4.009417752240552],
[-1311.7095899169217, -41.89849856868386, -3.5779669542971533], [-1308.7053739842377, -49.69014063291252, 1.4251805990934372], [-1308.8793413292733, -49.249986744485795, 1.452192763419589],
[-1311.6985617888859, -41.94119896925986, -3.1552200905571226], [-1311.933300757897, -41.3324808543548, -3.5434622254688293], [-1311.6721510011703, -42.023124465718865, -2.726098778686719],
[-1309.575554959767, -47.461260076612234, 0.7789614414214157], [-1311.920802212495, -41.38087464310229, -3.0643491127702873], [-1311.6294600100373, -42.14633889589459, -2.296680791361723],
[-1311.8908699883032, -41.473723533563316, -2.578011625824729], [-1311.5700086812722, -42.31182523816824, -1.873689603904495], [-1311.8563511604443, -41.57398480270058, -2.21263097555493],
[-1311.4938095906982, -42.51930443570018, -1.464214800595073], [-1310.2165689287358, -45.83393083047122, 0.7206466880161315], [-1311.8111851541325, -41.70113799907267, -1.8502356949611567],
[-1311.4014134522877, -42.76713224314153, -1.0753672275459394], [-1310.3682490662322, -45.447545723989606, 0.6690493192581926], [-1311.3221262866864, -42.97771858703345, -0.801354350609472],
[-1311.755284666433, -41.85528766736388, -1.494176288601011], [-1310.5217800466344, -45.05503278132528, 0.5762912663631141], [-1311.2349867338198, -43.207586833275855, -0.5453513188112993],
[-1310.6749889180646, -44.66181951202452, 0.44001985117211007], [-1311.1079810556257, -43.54039883520454, -0.23591535238665529], [-1310.8254645981942, -44.27397509943694, 0.2589690191671252],
[-1310.9706536214217, -43.89797494281083, 0.03316935116890818], [-1311.6887497214484, -42.03606083616614, -1.1478764503262937], [-1310.2412103049573, -45.79263741709292, 1.3282999040384311],
[-1311.6118763824343, -42.24258834775537, -0.814734816813143], [-1310.413114460418, -45.35473429784179, 1.2698228852823377], [-1311.5251571819535, -42.47350737452507, -0.4980213381059002],
[-1310.5871162380208, -44.90988629497588, 1.1646970921137836], [-1311.42927269364, -42.72698638681322, -0.200774473749334], [-1310.7175237335614, -44.575363480485976, 1.053591673146002],
[-1311.3250743568642, -43.00077202171087, 0.07429426346789114], [-1310.8465882905875, -44.24325392302126, 0.9140390128304716], [-1311.2135594324209, -43.29225543513894, 0.3248822349414695],
[-1310.9731053883443, -43.91660360060632, 0.7458069174608681], [-1311.0958396244678, -43.59855407383293, 0.5491589208832011]],
pointIndex: [84, 83, 1, 2, 0, 83, 86, 4, 1, 0, 86, 88, 6, 4, 0, 88, 91, 9, 6, 0, 91, 93, 11, 9, 0, 93, 95, 13, 11, 0, 95, 96, 14, 13, 0, 96, 98, 16, 14, 0, 98, 100, 18, 16, 0, 100, 102, 20, 18, 0,
102, 104, 22, 20, 0, 104, 106, 24, 22, 0, 106, 109, 27, 24, 0, 109, 112, 30, 27, 0, 112, 115, 33, 30, 0, 115, 117, 35, 33, 0, 117, 119, 37, 35, 0, 119, 121, 39, 37, 0, 121, 124, 42, 39, 0,
124, 128, 46, 42, 0, 128, 129, 49, 46, 0, 129, 153, 71, 49, 0, 153, 155, 73, 71, 0, 155, 157, 75, 73, 0, 157, 159, 77, 75, 0, 159, 161, 79, 77, 0, 161, 163, 81, 79, 0, 163, 164, 82, 81, 0,
164, 162, 80, 82, 0, 162, 160, 78, 80, 0, 160, 158, 76, 78, 0, 158, 156, 74, 76, 0, 156, 154, 72, 74, 0, 154, 152, 68, 72, 0, 152, 145, 63, 68, 0, 145, 141, 59, 63, 0, 141, 138, 56, 59, 0,
138, 136, 54, 56, 0, 136, 134, 51, 54, 0, 134, 131, 47, 51, 0, 131, 126, 44, 47, 0, 126, 114, 32, 44, 0, 114, 110, 28, 32, 0, 110, 111, 29, 28, 0, 111, 123, 41, 29, 0, 123, 127, 45, 41, 0,
127, 130, 48, 45, 0, 130, 132, 50, 48, 0, 132, 135, 53, 50, 0, 135, 137, 55, 53, 0, 137, 139, 57, 55, 0, 139, 142, 60, 57, 0, 142, 144, 62, 60, 0, 144, 147, 65, 62, 0, 147, 149, 67, 65, 0,
149, 151, 70, 67, 0, 151, 150, 69, 70, 0, 150, 148, 66, 69, 0, 148, 146, 64, 66, 0, 146, 143, 61, 64, 0, 143, 140, 58, 61, 0, 140, 133, 52, 58, 0, 133, 125, 43, 52, 0, 125, 122, 40, 43, 0,
122, 120, 38, 40, 0, 120, 118, 36, 38, 0, 118, 116, 34, 36, 0, 116, 113, 31, 34, 0, 113, 108, 26, 31, 0, 108, 107, 25, 26, 0, 107, 105, 23, 25, 0, 105, 103, 21, 23, 0, 103, 101, 19, 21, 0,
101, 99, 17, 19, 0, 99, 97, 15, 17, 0, 97, 94, 12, 15, 0, 94, 92, 10, 12, 0, 92, 90, 8, 10, 0, 90, 89, 7, 8, 0, 89, 87, 5, 7, 0, 87, 85, 3, 5, 0, 85, 84, 2, 3, 0,
2, 1, 4, 6, 9, 11, 13, 14, 16, 18, 20, 22, 24, 27, 30, 33, 35, 37, 39, 42, 46, 49, 71, 73, 75, 77, 79, 81, 82, 80, 78, 76, 74, 72, 68, 63, 59, 56, 54, 51, 47, 44, 32, 28, 29, 41, 45, 48, 50, 53, 55, 57, 60, 62, 65, 67, 70, 69, 66, 64, 61, 58, 52, 43, 40, 38, 36, 34, 31, 26, 25, 23, 21, 19, 17, 15, 12, 10, 8, 7, 5, 3, 0,
// start split face
// 73, 75, 77, 79, 81, 82, 80, 78, 76, 74, 72, 68, 63, 59, 56, 54, 51, 47, 44, 32, 28, 29, 41, 45, 48, 50, 53, 55, 57, 60, 62, 65, 67, 70, 69, 66, 64, 61, 58, 0,
// 58, 52, 43, 40, 38, 36, 34, 31, 26, 25, 23, 21, 19, 17, 15, 12, 10, 8, 7, 5, 3, 2, 1, 4, 6, 9, 11, 13, 14, 16, 18, 20, 22, 24, 27, 30, 33, 35, 37, 39, 42, 46, 49, 71, 73, 0,
// end split face
85, 83, 84, 0, 85, 86, 83, 0, 89, 88, 86, 0, 90, 91, 88, 0, 92, 93, 91, 0, 94, 95, 93, 0, 97, 96, 95, 0, 97, 98, 96, 0, 99, 100, 98, 0, 101, 102, 100, 0, 103, 104, 102, 0,
105, 106, 104, 0, 107, 109, 106, 0, 108, 112, 109, 0, 113, 115, 112, 0, 113, 117, 115, 0, 116, 119, 117, 0, 118, 121, 119, 0, 120, 124, 121, 0, 120, 128, 124, 0, 122, 129, 128, 0,
133, 153, 129, 0, 143, 155, 153, 0, 146, 157, 155, 0, 146, 159, 157, 0, 148, 161, 159, 0, 150, 163, 161, 0, 151, 164, 163, 0, 151, 162, 164, 0, 149, 160, 162, 0, 147, 158, 160, 0,
144, 156, 158, 0, 142, 154, 156, 0, 139, 152, 154, 0, 139, 145, 152, 0, 137, 141, 145, 0, 135, 138, 141, 0, 132, 136, 138, 0, 130, 134, 136, 0, 127, 131, 134, 0, 123, 126, 131, 0,
111, 114, 126, 0, 111, 110, 114, 0, 126, 123, 111, 0, 131, 127, 123, 0, 134, 130, 127, 0, 136, 132, 130, 0, 138, 135, 132, 0, 141, 137, 135, 0, 145, 139, 137, 0, 154, 142, 139, 0,
156, 144, 142, 0, 158, 147, 144, 0, 160, 149, 147, 0, 162, 151, 149, 0, 163, 150, 151, 0, 161, 148, 150, 0, 159, 146, 148, 0, 155, 143, 146, 0, 153, 140, 143, 0, 153, 133, 140, 0,
129, 125, 133, 0, 129, 122, 125, 0, 128, 120, 122, 0, 121, 118, 120, 0, 119, 116, 118, 0, 117, 113, 116, 0, 112, 108, 113, 0, 109, 107, 108, 0, 106, 105, 107, 0, 104, 103, 105, 0,
102, 101, 103, 0, 100, 99, 101, 0, 98, 97, 99, 0, 95, 94, 97, 0, 93, 92, 94, 0, 91, 90, 92, 0, 88, 89, 90, 0, 86, 87, 89, 0, 86, 85, 87, 0],
},
};
const clipPlane = ClipPlane.createNormalAndDistance(Vector3d.create(-0.012396820892038292, 0.030931559524568275, 0.9994446245076056), 13.05715711957438)!;
const polyface = IModelJson.Reader.parse(meshJSON);
if (ck.testDefined(polyface) && polyface instanceof Polyface) {
const point0 = polyface.data.point.getPoint3dAtUncheckedPointIndex(0);
const x0 = -point0.x;
let y0 = -point0.y;
const z0 = -point0.z;
const dy = Math.max(5.0, polyface.range().yLength() + 1);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, polyface, x0, y0, z0);
for (const inside of [true, false]) {
const clippedPolyface = PolyfaceClip.clipPolyfaceClipPlaneWithClosureFace(polyface, clipPlane, inside, true);
y0 += dy;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clippedPolyface, x0, y0, z0);
}
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "TwoComponentSection");
expect(ck.getNumErrors()).equals(0);
});
it("UnderAndOver", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let x0 = 0;
let y0 = 0;
for (const numX of [2, 5, 10]) {
for (const numY of [2, 4, 15]) {
for (const mapY of [false, true]) {
y0 = 0;
const yStep = numY + 1;
GeometryCoreTestIO.captureGeometry(allGeometry, LineSegment3d.create(Point3d.create(x0, y0), Point3d.create(x0, y0 + yStep)));
GeometryCoreTestIO.captureGeometry(allGeometry, LineSegment3d.create(Point3d.create(x0, y0 + yStep), Point3d.create(x0, y0 + 2 * yStep)));
const meshX = Sample.createTriangularUnitGridPolyface(Point3d.create(0.1, 0.2, -0.5), Vector3d.create(0.5, 0, 0.3), Vector3d.create(0, 0.6, 0), numX, numY);
if (mapY)
meshX.data.point.mapComponent(2,
(x: number, y: number, _z: number) => {
return 1.0 * RFunctions.cosineOfMappedAngle(x, 0.0, 5.0) * RFunctions.cosineOfMappedAngle(y, -1.0, 8.0);
});
const meshY = Sample.createTriangularUnitGridPolyface(Point3d.create(0, 0, 0), Vector3d.unitX(), Vector3d.unitY(), numX, numY);
/*
let z0 = 0.125;
const builderY = PolyfaceBuilder.create();
builderY.addPolygon([Point3d.create(0, 0, z0), Point3d.create(2, 0, z0), Point3d.create(2, 2, z0), Point3d.create(0, 2, z0)]);
const meshY = builderY.claimPolyface();
*/
if (mapY)
meshY.data.point.mapComponent(2,
(x: number, y: number, _z: number) => {
return 1.0 * RFunctions.cosineOfMappedAngle(x, 0.0, 3.0) * RFunctions.cosineOfMappedAngle(y, -1.0, 5.0);
});
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshX, x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshY, x0, y0);
const visitorX = meshX.createVisitor();
const visitorY = meshY.createVisitor();
const builderXUnderY = PolyfaceBuilder.create();
const builderXOverY = PolyfaceBuilder.create();
PolyfaceClip.clipPolyfaceUnderOverConvexPolyfaceIntoBuilders(visitorX, visitorY, builderXUnderY, builderXOverY);
const builderYUnderX = PolyfaceBuilder.create();
const builderYOverX = PolyfaceBuilder.create();
PolyfaceClip.clipPolyfaceUnderOverConvexPolyfaceIntoBuilders(visitorY, visitorX, builderYUnderX, builderYOverX);
y0 += yStep;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, builderXUnderY.claimPolyface(), x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, builderXOverY.claimPolyface(), x0, y0);
y0 += yStep;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, builderYUnderX.claimPolyface(), x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, builderYOverX.claimPolyface(), x0, y0);
y0 += yStep;
const cutFill = PolyfaceClip.computeCutFill(meshX, meshY);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutFill.meshAUnderB, x0, y0);
y0 += yStep;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutFill.meshAOverB, x0, y0);
y0 += 2 * yStep;
const fixA = PolyfaceQuery.cloneWithTVertexFixup(cutFill.meshAOverB);
const fixB = PolyfaceQuery.cloneWithTVertexFixup(cutFill.meshAUnderB);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, fixA, x0, y0);
y0 += yStep;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, fixB, x0, y0);
y0 += 2 * yStep;
const fixEdgeA = PolyfaceQuery.cloneWithColinearEdgeFixup(fixA);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, fixEdgeA, x0, y0);
y0 += yStep;
const fixEdgeB = PolyfaceQuery.cloneWithColinearEdgeFixup(fixB);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, fixEdgeB, x0, y0);
y0 += yStep;
x0 += numX * 2 + 4;
}
}
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "UnderAndOver");
expect(ck.getNumErrors()).equals(0);
});
it("NonConvexClip", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let x0 = 0;
let y0 = 0;
const deltaX = 10.0;
const gapDelta = 1.0;
// plane+polygon clip with at-vertex and nonconvex cases
const shape0 = GrowableXYZArray.create([[0, 0], [0, 6], [4, 4]]);
const shape1 = GrowableXYZArray.create([[0, 0], [0, 6], [4, 4], [2, 1]]);
const shape2 = GrowableXYZArray.create([[0, 0], [0, 6], [4, 6], [4, 0]]);
const shape3 = GrowableXYZArray.create([[0, 0], [0, 6], [4, 4], [4, 0], [3, 0], [3, 2], [1, 3], [1, 0]]);
const shape4 = GrowableXYZArray.create([[0, 0], [0, 6], [4, 4], [4, 0], [3, 0], [3, 2], [1, 2], [1, 0], [0.5, 0], [0.5, 2], [0.25, 2], [0.25, 0]]);
const shape5 = GrowableXYZArray.create(Sample.createSquareWave(Point3d.create(0, 0, 0), 0.5, 3, 0.75, 3, 4));
for (const points of [shape5, shape0, shape1, shape2, shape3, shape4, shape5]) {
const range = Range3d.createFromVariantData(points);
range.expandInPlace(1.5);
range.high.z = range.low.z;
const work = new GrowableXYZArray();
GeometryCoreTestIO.createAndCaptureLoop(allGeometry, points, x0, y0);
for (const y of [2, 0, 1, 2, 3, 4, 5, 6]) {
const plane = Plane3dByOriginAndUnitNormal.create(Point3d.create(0, y, 0), Vector3d.create(0, 1, 0))!;
GeometryCoreTestIO.captureGeometry(allGeometry, LineSegment3d.createXYXY(-2, y, 22, y), x0, y0);
x0 += deltaX;
const pointsA = points.clone();
const numCrossingsA = IndexedXYZCollectionPolygonOps.clipConvexPolygonInPlace(plane, pointsA, work, false);
const loopsA = IndexedXYZCollectionPolygonOps.gatherCutLoopsFromPlaneClip(plane, pointsA);
GeometryCoreTestIO.createAndCaptureLoop(allGeometry, pointsA, x0, y0);
for (const loop of loopsA.inputLoops)
GeometryCoreTestIO.createAndCaptureLoop(allGeometry, loop.xyz, x0 + 10.0, y0);
IndexedXYZCollectionPolygonOps.reorderCutLoops(loopsA);
for (const loop of loopsA.outputLoops)
GeometryCoreTestIO.createAndCaptureLoop(allGeometry, loop.xyz, x0 + 20.0, y0);
const pointsB = points.clone();
const numCrossingsB = IndexedXYZCollectionPolygonOps.clipConvexPolygonInPlace(plane, pointsB, work, true);
const loopsB = IndexedXYZCollectionPolygonOps.gatherCutLoopsFromPlaneClip(plane, pointsB);
GeometryCoreTestIO.createAndCaptureLoop(allGeometry, pointsB, x0, y0 + gapDelta);
for (const loop of loopsB.inputLoops)
GeometryCoreTestIO.createAndCaptureLoop(allGeometry, loop.xyz, x0 + 10, y0 + gapDelta);
IndexedXYZCollectionPolygonOps.reorderCutLoops(loopsB);
for (const loop of loopsB.outputLoops)
GeometryCoreTestIO.createAndCaptureLoop(allGeometry, loop.xyz, x0 + 20.0, y0 + gapDelta);
if (((numCrossingsB !== 0 && numCrossingsB !== 2)) || (numCrossingsA !== 0 && numCrossingsA !== 2))
GeometryCoreTestIO.captureRangeEdges(allGeometry, range, x0, y0);
ck.testExactNumber(numCrossingsA, numCrossingsB, "crossing counts with inside flip");
x0 += 40.0;
}
y0 += 25.0;
x0 = 0.0;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "NonConvexClip");
expect(ck.getNumErrors()).equals(0);
});
it("CutFillUndulating", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let x0 = 0;
let y0 = 0;
const numXA = 6;
const numYA = 5;
const numXB = 12;
const numYB = 12;
const meshA = Sample.createTriangularUnitGridPolyface(Point3d.create(2, 2, 0), Vector3d.unitX(), Vector3d.unitY(), numXA, numYA, false, false, false, true);
const amplitudeA = 0.45;
const amplitudeB = -0.35;
meshA.data.point.mapComponent(2,
(x: number, y: number, _z: number) => {
return amplitudeA * RFunctions.cosineOfMappedAngle(x, 0.0, numXA) * RFunctions.cosineOfMappedAngle(y, 0, numYA);
});
const meshB = Sample.createTriangularUnitGridPolyface(Point3d.create(0, 0, 0), Vector3d.unitX(0.7), Vector3d.unitY(0.8), numXB, numYB, false, false, false, true);
meshB.data.point.mapComponent(2,
(x: number, y: number, _z: number) => {
return amplitudeB * RFunctions.cosineOfMappedAngle(x, 0.0, 3.0) * RFunctions.cosineOfMappedAngle(y, 1, 5.0);
});
// spin meshB so its grids do not align with mesh A
const rangeB = meshB.range();
const centerB = rangeB.localXYZToWorld(0.5, 0.5, 0);
const transform = Transform.createFixedPointAndMatrix(centerB, Matrix3d.createRotationAroundAxisIndex(2, Angle.createDegrees(30)));
const rangeB1 = meshB.range();
meshB.tryTransformInPlace(transform);
for (const zShift of [0, 0.10, 0.10, 0.10, 0.10, 0.10]) {
y0 = 0;
meshB.tryTranslateInPlace(0, 0, zShift);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshA, x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshB, x0, y0);
const cutFill = PolyfaceClip.computeCutFill(meshA, meshB);
y0 -= rangeB1.yLength();
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutFill.meshAUnderB, x0, y0);
y0 -= rangeB1.yLength();
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutFill.meshAOverB, x0, y0);
x0 += 2 * rangeB1.xLength();
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "CutFillUndulating");
expect(ck.getNumErrors()).equals(0);
});
it("CutFillCoincident", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
let x0 = 0;
let y0 = 0;
const numXA = 14;
const numYA = 9;
const meshA = Sample.createTriangularUnitGridPolyface(Point3d.create(2, 2, 0), Vector3d.unitX(), Vector3d.unitY(), numXA, numYA, false, false, false, true);
const meshB = Sample.createTriangularUnitGridPolyface(Point3d.create(2, 2, 0), Vector3d.unitX(), Vector3d.unitY(), numXA, numYA, false, false, false, true);
const rangeB1 = meshB.range();
shiftZInXYFractionRange(meshA, 0.1, 0.1, 0.5, 0.3, 0.5);
shiftZInXYFractionRange(meshB, 0.3, 0.2, 0.6, 0.6, -0.5);
shiftZInXYFractionRange(meshB, 0.4, 0.5, 0.8, 0.9, 0.25);
shiftZInXYFractionRange(meshA, 0.7, 0.1, 1.8, 0.9, 0.20);
y0 = 0;
const dy = 1.1 * rangeB1.yLength();
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshA, x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshB, x0, y0);
const cutFill = PolyfaceClip.computeCutFill(meshA, meshB);
y0 -= dy;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutFill.meshAUnderB, x0, y0);
y0 -= dy;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutFill.meshAOverB, x0, y0);
x0 += 2 * rangeB1.xLength();
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "CutFillCoincident");
expect(ck.getNumErrors()).equals(0);
});
it("CutFillJonas", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const meshA = IModelJson.Reader.parse(JSON.parse(fs.readFileSync("./src/test/testInputs/CutFill/JonasJune2020A/existingPoly1.50.imjs", "utf8")));
const meshB = IModelJson.Reader.parse(JSON.parse(fs.readFileSync("./src/test/testInputs/CutFill/JonasJune2020A/proposedPoly1.50.imjs", "utf8")));
if (meshA instanceof IndexedPolyface && meshB instanceof IndexedPolyface) {
// meshA.triangulate();
// meshB.triangulate();
const rangeA = meshB.range();
const rangeB = meshB.range();
const rangeAB = rangeA.union(rangeB);
const x0 = -rangeAB.low.x;
let y0 = -rangeA.low.y;
const dy = 1.1 * rangeAB.yLength();
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshA, x0, y0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshB, x0, y0);
GeometryCoreTestIO.captureRangeEdges(allGeometry, rangeAB, x0, y0);
const cutFill = PolyfaceClip.computeCutFill(meshA, meshB);
y0 += dy;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutFill.meshAUnderB, x0, y0);
GeometryCoreTestIO.captureRangeEdges(allGeometry, rangeAB, x0, y0);
y0 += dy;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutFill.meshAOverB, x0, y0);
GeometryCoreTestIO.captureRangeEdges(allGeometry, rangeAB, x0, y0);
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "CutFillJonas");
expect(ck.getNumErrors()).equals(0);
});
// cspell:word Arnoldas
it("ArnoldasBox", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const meshData = {
indexedMesh: {
point: [
[0, 0, 0.4999999999723128],
[0, 0, 1], [2.3283064365386963e-10, 0.6889561647549272, 0.49999999998019096],
[0.8495529009960592, 9.313225746154785e-10, 0.5000000000207994],
[0.3110438375733793, 0.6889561647549272, 0.499999999997943],
[0.8495529009960592, 0.15044710040092468, 0.5000000000225198],
[4.656612873077393e-10, 0.6889561638236046, 1],
[0.8495529008796439, 9.313225746154785e-10, 1],
[0.8495529012288898, 0.6889561638236046, 0.5000000000286775],
[0.8495529012288898, 0.6889561638236046, 0.8908151873411514],
[0.8495529012288898, 0.6889561638236046, 1]],
pointIndex: [1, 4, 8, 2, 0, 3, 1, 2,
7, 0, 11, 7, 2, 8, 0, 3,
5, 6, 4, 1, 0, 6, 5, 9,
0,
9, 5, 10, 0, 5, 3, 7, 0,
7, 11, 10, 5, 0, 4, 6, 8,
0,
6, 9, 10, 0, 10, 11, 8, 0,
8, 6, 10, 0],
},
};
let x0 = 0;
let y0 = 0;
const yStep = 2.0;
const xStep = 5.0;
const polyface = IModelJson.Reader.parse(meshData);
const vectorA = Vector3d.create(-1, -1, -0.234);
vectorA.normalizeInPlace();
if (ck.testDefined(polyface) && ck.testTrue(polyface instanceof Polyface) && polyface instanceof Polyface) {
for (const transform of Sample.createRigidTransforms(1.0)) {
y0 = 0.0;
for (const clipPlane of [ClipPlane.createNormalAndDistance(Vector3d.create(0, 0, -1), -0.8221099398657934)!,
/* */ ClipPlane.createNormalAndDistance(Vector3d.create(0, -1, 0), -0.4221099398657934)!,
/* */ ClipPlane.createNormalAndDistance(Vector3d.create(-1, 0, 0), -0.8221099398657934)!,
/* */ ClipPlane.createNormalAndDistance(vectorA, -0.8221099398657934)!]) {
const clipPlaneA = clipPlane.clone();
clipPlaneA.transformInPlace(transform);
const polyfaceA = polyface.cloneTransformed(transform) as Polyface;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, polyfaceA, x0, y0);
for (const inside of [false, true]) {
const clip = PolyfaceClip.clipPolyfaceClipPlaneWithClosureFace(polyfaceA, clipPlaneA, inside, true);
if (ck.testDefined(clip) && clip) {
ck.testTrue(PolyfaceQuery.isPolyfaceClosedByEdgePairing(clip), " clip closure");
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clip, x0, y0 += yStep);
}
}
y0 += 5 * yStep;
}
x0 += xStep;
}
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "ArnoldasBox");
expect(ck.getNumErrors()).equals(0);
});
it("CutFill", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const sideAngle = Angle.createDegrees(0.001);
const meshA = IModelJson.Reader.parse(JSON.parse(fs.readFileSync("./src/test/iModelJsonSamples/polyface/ArnoldasEarthWorks/meshA.imjs", "utf8")));
if (ck.testTrue(meshA instanceof IndexedPolyface, "Expected one indexed polyface in meshA") && meshA instanceof IndexedPolyface) {
ck.testFalse(PolyfaceQuery.isPolyfaceClosedByEdgePairing(meshA), " expect this input to have boundary issue");
const boundaries = PolyfaceQuery.boundaryEdges(meshA, true, true, true);
const range = meshA.range();
const rv = raggedVolume(meshA);
console.log("Volume estimate", rv);
const dz = range.zLength() * 2.0;
const dzFront = 4 * dz;
const dzSide = 3 * dz;
const dzRear = 2 * dz;
const dx = 2.0 * range.xLength();
const x1 = dx;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshA, 0, 0);
GeometryCoreTestIO.captureRangeEdges(allGeometry, range, 0, 0, 0);
GeometryCoreTestIO.captureRangeEdges(allGeometry, range, 0, 0, dz);
GeometryCoreTestIO.captureRangeEdges(allGeometry, range, 0, 0, dzFront);
GeometryCoreTestIO.captureRangeEdges(allGeometry, range, 0, 0, dzSide);
GeometryCoreTestIO.captureRangeEdges(allGeometry, range, 0, 0, dzRear);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, boundaries, 0, 0, dz);
const partitionedIndices = PolyfaceQuery.partitionFacetIndicesByVisibilityVector(meshA, Vector3d.unitZ(), sideAngle);
const meshes = PolyfaceQuery.clonePartitions(meshA, partitionedIndices);
GeometryCoreTestIO.captureRangeEdges(allGeometry, range, 0, 0, dzFront);
PolyfaceQuery.markPairedEdgesInvisible(meshes[0] as IndexedPolyface, Angle.createDegrees(5));
PolyfaceQuery.markPairedEdgesInvisible(meshes[1] as IndexedPolyface, Angle.createDegrees(5));
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshes[0], 0, 0, dzFront);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshes[2], 0, 0, dzSide);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshes[1], 0, 0, dzRear);
const front = meshes[0] as IndexedPolyface;
const rear = meshes[1] as IndexedPolyface;
rear.reverseIndices();
const cutFill = PolyfaceClip.computeCutFill(front, rear);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutFill.meshAUnderB, x1, 0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, cutFill.meshAOverB, x1, 0, dz);
GeometryCoreTestIO.saveGeometry(allGeometry, "ArnoldasEarthWorks", "meshA");
}
expect(ck.getNumErrors()).equals(0);
});
it("BoxClosure", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const builder = PolyfaceBuilder.create();
builder.addBox(Box.createRange(Range3d.create(Point3d.create(-1, -1, -1), Point3d.create(1, 1, 1)), true)!);
const facets = builder.claimPolyface();
const planes = [];
planes.push(ClipPlane.createNormalAndPointXYZXYZ(1, 0, 0, 0.5, 0, 0)!);
planes.push(ClipPlane.createNormalAndPointXYZXYZ(2, 3, 2, 0.5, 0, 0)!);
planes.push(ClipPlane.createNormalAndPointXYZXYZ(-1, -0.5, -0.5, 1, 0.8, 0.8)!);
let x0 = 0;
for (const interior of [false, true]) {
const clipper = ConvexClipPlaneSet.createEmpty();
for (const p of planes) {
p.setFlags(interior, interior);
clipper.planes.push(p);
const clipBuilders = ClippedPolyfaceBuilders.create(true, true, true);
PolyfaceClip.clipPolyfaceInsideOutside(facets, clipper, clipBuilders);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, facets, x0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clipBuilders.claimPolyface(0, true), x0, 5);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clipBuilders.claimPolyface(1, true), x0, 10);
x0 += 10.0;
}
x0 += 10;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "BoxClosure");
expect(ck.getNumErrors()).equals(0);
});
it("BoxClosureNonConvex", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const builder = PolyfaceBuilder.create();
const boxZ0 = 0.01;
const boxZ1 = 0.3;
builder.addBox(Box.createRange(Range3d.create(Point3d.create(-1, -1, boxZ0), Point3d.create(1, 1, boxZ1)), true)!);
const facets = builder.claimPolyface();
const xA = 0.2;
const xB = 0.4;
const xC = 1.2;
const yA = -0.3;
const yB = -0.1;
const yC = 1.2;
const yD = 0.4;
const clipData = [];
const contourP0 = SweepContour.createForPolygon(
[Point3d.create(xA, yA), Point3d.create(xB, yA), Point3d.create(xA, yB), Point3d.create(xA, yA)])!;
const clipperP0 = contourP0.sweepToUnionOfConvexClipPlaneSets()!;
const contourP1 = SweepContour.createForPolygon(
[Point3d.create(xA, yA), Point3d.create(xC, yA), Point3d.create(xA, yC), Point3d.create(xA, yA)])!;
const clipperP1 = contourP1.sweepToUnionOfConvexClipPlaneSets()!;
const dxB = 0.3;
const contourQ0 = SweepContour.createForPolygon(
[Point3d.create(xA, yA), Point3d.create(xC, yA), Point3d.create(xC, yB), Point3d.create(xB + dxB, yB), Point3d.create(xB, yC), Point3d.create(xA, yC), Point3d.create(xA, yA)])!;
const clipperQ0 = contourQ0.sweepToUnionOfConvexClipPlaneSets()!;
const contourQ1 = SweepContour.createForPolygon(
[Point3d.create(xA, yA), Point3d.create(xC, yA), Point3d.create(xC, yB), Point3d.create(xB + dxB, yB), Point3d.create(xB, yD), Point3d.create(xA, yD), Point3d.create(xA, yA)])!;
const clipperQ1 = contourQ1.sweepToUnionOfConvexClipPlaneSets()!;
let x0 = 0;
clipData.push([contourP0, clipperP0]);
clipData.push([contourP1, clipperP1]);
clipData.push([contourQ0, clipperQ0]);
clipData.push([contourQ1, clipperQ1]);
for (const cd of clipData) {
const clipper = cd[1] as UnionOfConvexClipPlaneSets;
const sweepContour = cd[0] as SweepContour;
GeometryCoreTestIO.captureCloneGeometry(allGeometry, sweepContour.curves, x0, 0, boxZ1 + 0.01);
const clipBuilders = ClippedPolyfaceBuilders.create(true, true, true);
PolyfaceClip.clipPolyfaceInsideOutside(facets, clipper, clipBuilders);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, facets, x0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clipBuilders.claimPolyface(0, true), x0, 3);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clipBuilders.claimPolyface(1, true), x0, 6);
x0 += 5;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "BoxClosureNonConvex");
expect(ck.getNumErrors()).equals(0);
});
it("PolyfaceClip", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
expect(ck.getNumErrors()).equals(0);
const meshData = {
indexedMesh: {
point: [
[-47.37304994184524, -491.3657047697343, -0.320753981533926],
[-47.37675585504621, -491.3664080584422, -0.2828410894726403],
[-47.40868372656405, -487.70353786600754, -0.30898173157765996],
[-47.41238963953219, -487.7042411547154, -0.27106883950182237],
[-43.71249747485854, -491.3038417249918, -0.25523604593763594],
[-43.71620338782668, -491.3045450136997, -0.21732315386179835],
[-47.410502686863765, -486.3654011632316, -0.3046578628855059],
[-47.41420860006474, -486.36610445193946, -0.2667449708242202],
[-43.747635680483654, -487.6862194132991, -0.2442416615667753],
[-43.7513415934518, -487.686922702007, -0.20632876950548962],
[-43.7494085803628, -486.3643588316627, -0.24021521456597839],
[-43.75311449333094, -486.36506212037057, -0.2023023224901408],
[-47.364242404000834, -481.3650494045578, -0.2884034485759912],
[-47.36794831696898, -481.3657526932657, -0.25049055651470553],
[-47.35331786912866, -480.7779169315472, -0.2864855175430421],
[-47.3570237820968, -480.77862021978945, -0.2485726254672045],
[-43.70361571526155, -481.4248265787028, -0.22513469854311552],
[-43.70732162822969, -481.42552986741066, -0.18722180648182984],
[-47.25060150329955, -476.8523820149712, -0.2736169950949261],
[-47.25430741626769, -476.8530853036791, -0.23570410303364042],
[-43.692812270717695, -480.8448353074491, -0.2233610739640426],
[-43.69651818368584, -480.845538596157, -0.18544818190275691],
[-47.23427976411767, -476.36603803373873, -0.27201753927511163],
[-47.23798567708582, -476.3667413224466, -0.23410464719927404],
[-47.13739399355836, -473.8551799589768, -0.2637437052180758],
[-47.141099906526506, -473.8558832476847, -0.22583081314223818],
[-43.591263198526576, -476.96704542357475, -0.21149232835159637],
[-43.59496911172755, -476.9677487122826, -0.17357943627575878],
[-43.57535727042705, -476.48665985185653, -0.2076899910462089],
[-43.57906318339519, -476.4873631405644, -0.1697770989703713],
[-47.02064847340807, -471.3697551796213, -0.255529179572477],
[-47.02435438637622, -471.37045846832916, -0.21761628751119133],
[-43.48077054461464, -474.00656314985827, -0.18805605440866202],
[-43.48447645758279, -474.00726643856615, -0.15014316234737635],
[-46.890834543482995, -469.15438479636924, -0.248182242072877],
[-46.89454045644919, -469.15508808504393, -0.21026935000420527],
[-43.36655237781815, -471.5515877753496, -0.1686169594322564],
[-43.37025829101913, -471.5522910640575, -0.13070406735641882],
[-43.239302208178145, -469.36335787194645, -0.15128906038398932],
[-43.2430081212604, -469.36406116061477, -0.11337616830783828]],
pointIndex: [39, 40, 38, 37, 0, 40, 36, 32, 38, 0, 36, 35, 31, 32, 0, 35, 39, 37, 31, 0, 37, 38, 34, 33, 0,
38, 32, 26, 34, 0, 32, 31, 25, 26, 0, 31, 37, 33, 25, 0, 33, 34, 30, 29, 0, 34, 26, 24, 30, 0,
26, 25, 23, 24, 0, 25, 33, 29, 23, 0, 29, 30, 28, 27, 0, 30, 24, 20, 28, 0, 24, 23, 19, 20, 0,
23, 29, 27, 19, 0, 27, 28, 22, 21, 0, 28, 20, 16, 22, 0, 20, 19, 15, 16, 0, 19, 27, 21, 15, 0,
21, 22, 18, 17, 0, 22, 16, 14, 18, 0, 16, 15, 13, 14, 0, 15, 21, 17, 13, 0, 17, 18, 12, 11, 0,
18, 14, 8, 12, 0, 14, 13, 7, 8, 0, 13, 17, 11, 7, 0, 11, 12, 10, 9, 0, 12, 8, 4, 10, 0,
8, 7, 3, 4, 0, 7, 11, 9, 3, 0, 9, 10, 6, 5, 0, 10, 4, 2, 6, 0, 4, 3, 1, 2, 0,
3, 9, 5, 1, 0, 5, 6, 2, 1, 0, 35, 40, 39, 0, 35, 36, 40, 0],
},
};
if (Checker.noisy.isolateFacetsOnClipPlane) {
// trim out facets not contained in known problem range . . .
const edgeIndices = [33, 34, 25, 26];
const pointIndex1 = [];
const pointIndex = meshData.indexedMesh.pointIndex;
for (let i0 = 0; i0 < meshData.indexedMesh.pointIndex.length;) {
// i0 is first index of a new facet.
let i1;
let hits = 0;
for (i1 = i0; pointIndex[i1] > 0; i1++) {
if (edgeIndices.includes(pointIndex[i1]))
hits++;
}
if (hits > 0) {
for (let i = i0; i <= i1; i++) {
pointIndex1.push(pointIndex[i]);
}
}
i0 = i1 + 1;
}
meshData.indexedMesh.pointIndex = pointIndex1;
}
const polyface = IModelJson.Reader.parse(meshData) as Polyface;
if (ck.testDefined(polyface) && polyface) {
const pointA = polyface.data.point.getPoint3dAtUncheckedPointIndex(33);
const pointB = polyface.data.point.getPoint3dAtUncheckedPointIndex(25);
const edgeVector = Vector3d.createStartEnd(pointA, pointB);
const stepFactor = 2.0;
const basePoint = pointA.clone();
GeometryCoreTestIO.captureCloneGeometry(allGeometry, polyface, basePoint.x, basePoint.y, basePoint.z);
for (const shiftDistance of [0, 0.1, -0.01]) {
const plane = ClipPlane.createNormalAndDistance(Vector3d.create(0.040888310883825336, 0.998909753725443, 0.022526649667507826), -475.2718707964355 + shiftDistance);
if (ck.testDefined(plane) && plane) {
const inside = PolyfaceClip.clipPolyfaceClipPlaneWithClosureFace(polyface, plane, true, true);
const outside = PolyfaceClip.clipPolyfaceClipPlaneWithClosureFace(polyface, plane, false, true);
const plane1 = plane.getPlane3d();
basePoint.addScaledInPlace(edgeVector, stepFactor);
if (plane1) {
const centerA = plane1.projectPointToPlane(pointA);
const centerB = plane1.projectPointToPlane(pointB);
const arc1 = Arc3d.createCenterNormalRadius(centerA, plane1.getNormalRef(), 0.2);
const arc2 = Arc3d.createCenterNormalRadius(centerB, plane1.getNormalRef(), 0.2);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, arc1, basePoint.x, basePoint.y, basePoint.z);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, arc2, basePoint.x, basePoint.y, basePoint.z);
GeometryCoreTestIO.captureGeometry(allGeometry, LineString3d.create(arc1.fractionToPoint(0.8), arc2.fractionToPoint(0.2)), basePoint.x, basePoint.y, basePoint.z);
}
GeometryCoreTestIO.captureCloneGeometry(allGeometry, inside, basePoint.x, basePoint.y, basePoint.z);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, outside, basePoint.x, basePoint.y, basePoint.z);
}
}
GeometryCoreTestIO.saveGeometry(allGeometry, "PolyfaceClip", "CutOnEdge");
}
expect(ck.getNumErrors()).equals(0);
});
it("ArnoldasClip", () => {
const ck = new Checker();
for (const caseDirectory of ["case1", "case2"]) {
const allGeometry: GeometryQuery[] = [];
const meshFile = `./src/test/testInputs/clipping/arnoldasInOut/${caseDirectory}/source.json`;
const clipperFile = `./src/test/testInputs/clipping/arnoldasInOut/${caseDirectory}/clipper.json`;
const meshA = IModelJson.Reader.parse(JSON.parse(fs.readFileSync(meshFile, "utf8")));
const clipper = UnionOfConvexClipPlaneSets.fromJSON(JSON.parse(fs.readFileSync(clipperFile, "utf8")));
if (ck.testType(meshA as IndexedPolyface, IndexedPolyface, "Expect mesh") && meshA instanceof IndexedPolyface && ck.testType(clipper, UnionOfConvexClipPlaneSets, "expect clipper")) {
GeometryCoreTestIO.captureCloneGeometry(allGeometry, meshA, 0, 0);
const range = meshA.range();
const dx = 0.2 * range.xLength();
const dy = range.yLength();
const dz = 0.1 * range.zLength();
range.low.addXYZInPlace(-dx, -dy, -dz);
range.high.addXYZInPlace(dx, dy, dz);
const clipperLoopsA = ClipUtilities.loopsOfConvexClipPlaneIntersectionWithRange(clipper, range, true, false, true);
const clipperLoopsB = ClipUtilities.loopsOfConvexClipPlaneIntersectionWithRange(clipper, range, true, false, false);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clipperLoopsA, 0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clipperLoopsB, 0, - dy);
const builders = ClippedPolyfaceBuilders.create(true, true, true);
PolyfaceClip.clipPolyfaceInsideOutside(meshA, clipper, builders);
const inside = builders.builderA?.claimPolyface();
const outside = builders.builderB?.claimPolyface();
GeometryCoreTestIO.captureCloneGeometry(allGeometry, inside, 0, range.yLength());
GeometryCoreTestIO.captureCloneGeometry(allGeometry, outside, 0, 2 * range.yLength());
}
GeometryCoreTestIO.saveGeometry(allGeometry, "clipping", `arnoldas${caseDirectory}`);
}
expect(ck.getNumErrors()).equals(0);
});
it("ArnoldasSimpleClip", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
// make a rectangle clipper with interior planes ...
const clipRectangle = Sample.createRectangle(1, 0, 4, 8, 0, true);
const contour = SweepContour.createForPolygon(clipRectangle);
const clipper = contour?.sweepToUnionOfConvexClipPlaneSets();
const rectangleB = Sample.createRectangle(0, 1, 6, 2, 0, true);
const mesh = PolyfaceBuilder.polygonToTriangulatedPolyface(rectangleB);
const builders = ClippedPolyfaceBuilders.create(false, true, true);
PolyfaceClip.clipPolyfaceUnionOfConvexClipPlaneSetsToBuilders(mesh!, clipper!, builders, 0);
// const inside = builders.builderA?.claimPolyface();
const outside = builders.builderB?.claimPolyface();
if (ck.testType(outside, IndexedPolyface)) {
GeometryCoreTestIO.captureCloneGeometry(allGeometry, mesh, 0, 0);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, clipRectangle, 0, 0);
// GeometryCoreTestIO.captureCloneGeometry(allGeometry, inside, 0, 10);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, outside, 0, 20);
ck.testExactNumber(4, outside.facetCount);
ck.testExactNumber(10, outside.pointCount);
}
// make a single-face mesh that cuts all the way across . .
GeometryCoreTestIO.saveGeometry(allGeometry, "clipping", "arnoldasSimpleClip");
expect(ck.getNumErrors()).equals(0);
});
});
/** Estimate a volume for a mesh that may be missing side faces.
* * Compute volume "between" the mesh facets and the bottom plane of the mesh range
* * Compute volume "between" the mesh facets and the top plane of the mesh range.
* * The return structure contains
* * a volume estimate
* * a relative error estimate based on the difference between upper and lower volumes.
*
*/
function raggedVolume(mesh: Polyface): { volume: number, volumeDifferenceRelativeError: number } {
const range = mesh.range();
const xyPlane0 = Plane3dByOriginAndUnitNormal.createXYPlane(range.low);
const xyPlane1 = Plane3dByOriginAndUnitNormal.createXYPlane(range.high);
const volume0 = PolyfaceQuery.sumVolumeBetweenFacetsAndPlane(mesh, xyPlane0);
const volume1 = PolyfaceQuery.sumVolumeBetweenFacetsAndPlane(mesh, xyPlane1);
const volumeDifference = Math.abs(volume1.volume - volume0.volume);
return { volume: volume0.volume, volumeDifferenceRelativeError: Geometry.safeDivideFraction(volumeDifference, Math.abs(volume0.volume), 1000.0) };
}
function shiftZInXYFractionRange(mesh: Polyface, lowXFraction: number, lowYFraction: number, highXFraction: number, highYFraction: number, deltaZ: number) {
const points = mesh.data.point;
const rangeA = mesh.range();
const lowPoint = rangeA.localXYZToWorld(lowXFraction, lowYFraction, 0)!;
const highPoint = rangeA.localXYZToWorld(highXFraction, highYFraction, 0)!;
const rangeXY = Range2d.createXYXY(lowPoint?.x, lowPoint?.y, highPoint?.x, highPoint.y);
const p = Point3d.create();
for (let i = 0; i < points.length; i++) {
points.getPoint3dAtUncheckedPointIndex(i, p);
if (rangeXY.containsXY(p.x, p.y)) {
p.z += deltaZ;
points.setAtCheckedPointIndex(i, p);
}
}
} | the_stack |
'use strict';
import * as turfHelpers from '@turf/helpers';
import lineSliceAlong from '@turf/line-slice-along';
import along from '@turf/along';
import bearing from '@turf/bearing';
import distance from '@turf/distance';
import length from '@turf/length';
import nearestPointOnLine from '@turf/nearest-point-on-line';
import { rmse } from './util';
import { reverseLineString } from './geom';
import { TileIndex } from './tile_index';
import { TilePathParams, TileType } from './tiles';
import { Feature, LineString } from '@turf/buffer/node_modules/@turf/helpers';
import { RoadClass, SharedStreetsReference } from 'sharedstreets-types';
import { SharedStreetsGeometry } from 'sharedstreets-pbf/proto/sharedstreets';
import { forwardReference, backReference } from './index';
// import { start } from 'repl';
// import { normalize } from 'path';
const DEFAULT_SEARCH_RADIUS = 25;
const DEFAULT_LENGTH_TOLERANCE = 0.1;
const DEFUALT_CANDIDATES = 10;
const DEFAULT_BEARING_TOLERANCE = 15; // 360 +/- tolerance
const MAX_FEATURE_LENGTH = 15000; // 1km
const MAX_SEARCH_RADIUS = 100;
const MAX_LENGTH_TOLERANCE = 0.5;
const MAX_CANDIDATES = 10;
const MAX_BEARING_TOLERANCE = 180; // 360 +/- tolerance
const REFERNECE_GEOMETRY_OFFSET = 2;
const MAX_ROUTE_QUERIES = 16;
// TODO need to pull this from PBF enum defintion
// @property {number} Motorway=0 Motorway value
// * @property {number} Trunk=1 Trunk value
// * @property {number} Primary=2 Primary value
// * @property {number} Secondary=3 Secondary value
// * @property {number} Tertiary=4 Tertiary value
// * @property {number} Residential=5 Residential value
// * @property {number} Unclassified=6 Unclassified value
// * @property {number} Service=7 Service value
// * @property {number} Other=8 Other value
function roadClassConverter(roadClass:string):number {
if(roadClass === 'Motorway')
return 0;
else if(roadClass === 'Trunk')
return 1;
else if(roadClass === 'Primary')
return 2;
else if(roadClass === 'Secondary')
return 3;
else if(roadClass === 'Tertiary')
return 4;
else if(roadClass === 'Residential')
return 5;
else if(roadClass === 'Unclassified')
return 6;
else if(roadClass === 'Service')
return 7;
else
return null;
}
function angleDelta(a1, a2) {
var delta = 180 - Math.abs(Math.abs(a1 - a2) - 180);
return delta;
}
function normalizeAngle(a) {
if(a < 0)
return a + 360;
return a;
}
export enum ReferenceDirection {
FORWARD = "forward",
BACKWARD = "backward"
}
export enum ReferenceSideOfStreet {
RIGHT = "right",
LEFT = "left",
UNKNOWN = "unknown"
}
interface SortableCanddate {
score:number;
calcScore():number;
}
export class PointCandidate implements SortableCanddate {
score:number;
searchPoint:turfHelpers.Feature<turfHelpers.Point>;
pointOnLine:turfHelpers.Feature<turfHelpers.Point>;
snappedPoint:turfHelpers.Feature<turfHelpers.Point>;
geometryId:string;
referenceId:string;
roadClass:RoadClass;
direction:ReferenceDirection;
streetname:string;
referenceLength:number;
location:number;
bearing:number;
interceptAngle:number;
sideOfStreet:ReferenceSideOfStreet;
oneway:boolean;
calcScore():number {
if(!this.score) {
// score for snapped points are average of distance to point on line distance and distance to snapped ponit
if(this.snappedPoint)
this.score = (this.pointOnLine.properties.dist + distance(this.searchPoint, this.snappedPoint, {units: 'meters'})) / 2;
else
this.score = this.pointOnLine.properties.dist;
}
return this.score;
}
toFeature():turfHelpers.Feature<turfHelpers.Point> {
this.calcScore();
var feature:turfHelpers.Feature<turfHelpers.Point> = turfHelpers.feature(this.pointOnLine.geometry, {
score: this.score,
location: this.location,
referenceLength: this.referenceLength,
geometryId: this.geometryId,
referenceId: this.referenceId,
direction: this.direction,
bearing: this.bearing,
sideOfStreet: this.sideOfStreet,
interceptAngle: this.interceptAngle
});
return feature;
}
}
export class PointMatcher {
tileIndex:TileIndex;
searchRadius:number = DEFAULT_SEARCH_RADIUS;
bearingTolerance:number = DEFAULT_BEARING_TOLERANCE;
lengthTolerance:number = DEFAULT_LENGTH_TOLERANCE;
includeIntersections:boolean = false;
includeStreetnames:boolean = false;
ignoreDirection:boolean = false;
snapToIntersections:boolean = false;
snapTopology:boolean = false;
snapSideOfStreet:ReferenceSideOfStreet = ReferenceSideOfStreet.UNKNOWN;
tileParams:TilePathParams;
constructor(extent:turfHelpers.Feature<turfHelpers.Polygon>=null, params:TilePathParams, existingTileIndex:TileIndex=null) {
this.tileParams = params;
if(existingTileIndex)
this.tileIndex = existingTileIndex;
else
this.tileIndex = new TileIndex();
}
directionForRefId(refId:string):ReferenceDirection {
var ref = <SharedStreetsReference>this.tileIndex.objectIndex.get(refId);
if(ref) {
var geom:SharedStreetsGeometry = <SharedStreetsGeometry>this.tileIndex.objectIndex.get(ref['geometryId']);
if(geom) {
if(geom['forwardReferenceId'] === ref['id'])
return ReferenceDirection.FORWARD
else if(geom['backReferenceId'] === ref['id'])
return ReferenceDirection.BACKWARD
}
}
return null;
}
toIntersectionIdForRefId(refId:string):string {
var ref:SharedStreetsReference = <SharedStreetsReference>this.tileIndex.objectIndex.get(refId);
return ref.locationReferences[ref.locationReferences.length - 1].intersectionId;
}
fromIntersectionIdForRefId(refId:string):string {
var ref:SharedStreetsReference = <SharedStreetsReference>this.tileIndex.objectIndex.get(refId);
return ref.locationReferences[0].intersectionId;
}
async getPointCandidateFromRefId(searchPoint:turfHelpers.Feature<turfHelpers.Point>, refId:string, searchBearing:number):Promise<PointCandidate> {
var reference = <SharedStreetsReference>this.tileIndex.objectIndex.get(refId);
var geometry = <SharedStreetsGeometry>this.tileIndex.objectIndex.get(reference.geometryId);
var geometryFeature = <Feature<LineString>>this.tileIndex.featureIndex.get(reference.geometryId);
var direction = ReferenceDirection.FORWARD;
if(geometry.backReferenceId && geometry.backReferenceId === refId)
direction = ReferenceDirection.BACKWARD;
var pointOnLine = nearestPointOnLine(geometryFeature, searchPoint, {units:'meters'});
if(pointOnLine.properties.dist < this.searchRadius) {
var refLength = 0;
for(var lr of reference.locationReferences) {
if(lr.distanceToNextRef)
refLength = refLength + (lr.distanceToNextRef / 100);
}
var interceptBearing = normalizeAngle(bearing(pointOnLine, searchPoint));
var i = pointOnLine.properties.index;
if(geometryFeature.geometry.coordinates.length <= i + 1)
i = i - 1;
var lineBearing = bearing(geometryFeature.geometry.coordinates[i], geometryFeature.geometry.coordinates[i + 1]);
if(direction === ReferenceDirection.BACKWARD)
lineBearing += 180;
lineBearing = normalizeAngle(lineBearing);
var pointCandidate:PointCandidate = new PointCandidate();
pointCandidate.searchPoint = searchPoint;
pointCandidate.pointOnLine = pointOnLine;
pointCandidate.geometryId = geometryFeature.properties.id;
pointCandidate.referenceId = reference.id;
pointCandidate.roadClass = geometry.roadClass;
// if(this.includeStreetnames) {
// var metadata = await this.cache.metadataById(pointCandidate.geometryId);
// pointCandidate.streetname = metadata.name;
// }
pointCandidate.direction = direction;
pointCandidate.referenceLength = refLength;
if(direction === ReferenceDirection.FORWARD)
pointCandidate.location = pointOnLine.properties.location;
else
pointCandidate.location = refLength - pointOnLine.properties.location;
pointCandidate.bearing = normalizeAngle(lineBearing);
pointCandidate.interceptAngle = normalizeAngle(interceptBearing - lineBearing);
pointCandidate.sideOfStreet = ReferenceSideOfStreet.UNKNOWN;
if(pointCandidate.interceptAngle < 180) {
pointCandidate.sideOfStreet = ReferenceSideOfStreet.RIGHT;
}
if(pointCandidate.interceptAngle > 180) {
pointCandidate.sideOfStreet = ReferenceSideOfStreet.LEFT;
}
if(geometry.backReferenceId)
pointCandidate.oneway = false;
else
pointCandidate.oneway = true;
// check bearing and add to candidate list
if(!searchBearing || angleDelta(searchBearing, lineBearing) < this.bearingTolerance)
return pointCandidate;
}
return null;
}
getPointCandidateFromGeom(searchPoint:turfHelpers.Feature<turfHelpers.Point>, pointOnLine:turfHelpers.Feature<turfHelpers.Point>, candidateGeom:SharedStreetsGeometry, candidateGeomFeature:Feature<LineString>, searchBearing:number, direction:ReferenceDirection):PointCandidate {
if(pointOnLine.properties.dist < this.searchRadius) {
var reference:SharedStreetsReference;
if(direction === ReferenceDirection.FORWARD) {
reference = <SharedStreetsReference>this.tileIndex.objectIndex.get(candidateGeom.forwardReferenceId);
}
else {
if(candidateGeom.backReferenceId)
reference = <SharedStreetsReference>this.tileIndex.objectIndex.get(candidateGeom.backReferenceId);
else
return null; // no back-reference
}
var refLength = 0;
for(var lr of reference.locationReferences) {
if(lr.distanceToNextRef)
refLength = refLength + (lr.distanceToNextRef / 100);
}
var interceptBearing = normalizeAngle(bearing(pointOnLine, searchPoint));
var i = pointOnLine.properties.index;
if(candidateGeomFeature.geometry.coordinates.length <= i + 1)
i = i - 1;
var lineBearing = bearing(candidateGeomFeature.geometry.coordinates[i], candidateGeomFeature.geometry.coordinates[i + 1]);
if(direction === ReferenceDirection.BACKWARD)
lineBearing += 180;
lineBearing = normalizeAngle(lineBearing);
var pointCandidate:PointCandidate = new PointCandidate();
pointCandidate.searchPoint = searchPoint;
pointCandidate.pointOnLine = pointOnLine;
pointCandidate.geometryId = candidateGeomFeature.properties.id;
pointCandidate.referenceId = reference.id;
pointCandidate.roadClass = candidateGeom.roadClass;
// if(this.includeStreetnames) {
// var metadata = await this.cache.metadataById(pointCandidate.geometryId);
// pointCandidate.streetname = metadata.name;
// }
pointCandidate.direction = direction;
pointCandidate.referenceLength = refLength;
if(direction === ReferenceDirection.FORWARD)
pointCandidate.location = pointOnLine.properties.location;
else
pointCandidate.location = refLength - pointOnLine.properties.location;
pointCandidate.bearing = normalizeAngle(lineBearing);
pointCandidate.interceptAngle = normalizeAngle(interceptBearing - lineBearing);
pointCandidate.sideOfStreet = ReferenceSideOfStreet.UNKNOWN;
if(pointCandidate.interceptAngle < 180) {
pointCandidate.sideOfStreet = ReferenceSideOfStreet.RIGHT;
}
if(pointCandidate.interceptAngle > 180) {
pointCandidate.sideOfStreet = ReferenceSideOfStreet.LEFT;
}
if(candidateGeom.backReferenceId)
pointCandidate.oneway = false;
else
pointCandidate.oneway = true;
// check bearing and add to candidate list
if(!searchBearing || angleDelta(searchBearing, lineBearing) < this.bearingTolerance)
return pointCandidate;
}
return null;
}
async getPointCandidates(searchPoint:turfHelpers.Feature<turfHelpers.Point>, searchBearing:number, maxCandidates:number):Promise<PointCandidate[]> {
this.tileIndex.addTileType(TileType.REFERENCE);
var candidateFeatures = await this.tileIndex.nearby(searchPoint, TileType.GEOMETRY, this.searchRadius, this.tileParams);
var candidates:PointCandidate[] = new Array();
if(candidateFeatures && candidateFeatures.features) {
for(var candidateFeature of candidateFeatures.features) {
var candidateGeom:SharedStreetsGeometry = <SharedStreetsGeometry>this.tileIndex.objectIndex.get(candidateFeature.properties.id);
var candidateGeomFeature:turfHelpers.Feature<turfHelpers.LineString> = <turfHelpers.Feature<turfHelpers.LineString>>this.tileIndex.featureIndex.get(candidateFeature.properties.id);
var pointOnLine = nearestPointOnLine(candidateGeomFeature, searchPoint, {units:'meters'});
var forwardCandidate = await this.getPointCandidateFromGeom(searchPoint, pointOnLine, candidateGeom, candidateGeomFeature, searchBearing, ReferenceDirection.FORWARD);
var backwardCandidate = await this.getPointCandidateFromGeom(searchPoint, pointOnLine, candidateGeom, candidateGeomFeature, searchBearing, ReferenceDirection.BACKWARD);
if(forwardCandidate != null) {
var snapped = false;
if(this.snapToIntersections) {
if(forwardCandidate.location < this.searchRadius) {
var snappedForwardCandidate1 = Object.assign(new PointCandidate, forwardCandidate);
snappedForwardCandidate1.location = 0;
snappedForwardCandidate1.snappedPoint = along(candidateGeomFeature, 0, {"units":"meters"});
candidates.push(snappedForwardCandidate1);
snapped = true;
}
if(forwardCandidate.referenceLength - forwardCandidate.location < this.searchRadius) {
var snappedForwardCandidate2 = Object.assign(new PointCandidate, forwardCandidate);
snappedForwardCandidate2.location = snappedForwardCandidate2.referenceLength;
snappedForwardCandidate2.snappedPoint = along(candidateGeomFeature, snappedForwardCandidate2.referenceLength, {"units":"meters"});
candidates.push(snappedForwardCandidate2);
snapped = true;
}
}
if(!snapped) {
candidates.push(forwardCandidate);
}
}
if(backwardCandidate != null) {
var snapped = false;
if(this.snapToIntersections) {
if(backwardCandidate.location < this.searchRadius) {
var snappedBackwardCandidate1:PointCandidate = Object.assign(new PointCandidate, backwardCandidate);
snappedBackwardCandidate1.location = 0;
// not reversing the geom so snap to end on backRefs
snappedBackwardCandidate1.snappedPoint = along(candidateGeomFeature, snappedBackwardCandidate1.referenceLength, {"units":"meters"});
candidates.push(snappedBackwardCandidate1);
snapped = true;
}
if(backwardCandidate.referenceLength - backwardCandidate.location < this.searchRadius) {
var snappedBackwardCandidate2 = Object.assign(new PointCandidate, backwardCandidate);
snappedBackwardCandidate2.location = snappedBackwardCandidate2.referenceLength;
// not reversing the geom so snap to start on backRefs
snappedBackwardCandidate2.snappedPoint = along(candidateGeomFeature, 0, {"units":"meters"});
candidates.push(snappedBackwardCandidate2);
snapped = true;
}
}
if(!snapped) {
candidates.push(backwardCandidate);
}
}
}
}
var sortedCandidates = candidates.sort((p1, p2) => {
p1.calcScore();
p2.calcScore();
if(p1.score > p2.score) {
return 1;
}
if(p1.score < p2.score) {
return -1;
}
return 0;
});
if(sortedCandidates.length > maxCandidates) {
sortedCandidates = sortedCandidates.slice(0, maxCandidates);
}
return sortedCandidates;
}
} | the_stack |
import open = require('open');
import { ExtensionContext, QuickPickItem, window, workspace } from 'vscode';
import { CargoManager } from './components/cargo/CargoManager';
import { CommandInvocationReason } from './components/cargo/CommandInvocationReason';
import { Configuration, Mode } from './components/configuration/Configuration';
import { CurrentWorkingDirectoryManager }
from './components/configuration/current_working_directory_manager';
import { RustSource } from './components/configuration/RustSource';
import { Rustup } from './components/configuration/Rustup';
import { RlsConfiguration } from './components/configuration/RlsConfiguration';
import { FormattingManager } from './components/formatting/formatting_manager';
import { Manager as LanguageClientManager } from './components/language_client/manager';
import { LoggingManager } from './components/logging/logging_manager';
import { ChildLogger } from './components/logging/child_logger';
import { RootLogger } from './components/logging/root_logger';
import { CargoInvocationManager } from './CargoInvocationManager';
import { LegacyModeManager } from './legacy_mode_manager';
import * as OutputChannelProcess from './OutputChannelProcess';
import { ShellProviderManager } from './ShellProviderManager';
import { Toolchain } from './Toolchain';
/**
* Asks the user to choose a mode which the extension will run in.
* It is possible that the user will decline choosing and in that case the extension will run in
* Legacy Mode
* @return The promise which is resolved with either the chosen mode by the user or undefined
*/
async function askUserToChooseMode(): Promise<Mode | undefined> {
const message = 'Choose a mode in which the extension will function';
const rlsChoice = 'RLS';
const legacyChoice = 'Legacy';
const readAboutChoice = 'Read about modes';
while (true) {
const choice = await window.showInformationMessage(message, rlsChoice, legacyChoice,
readAboutChoice);
switch (choice) {
case rlsChoice:
return Mode.RLS;
case legacyChoice:
return Mode.Legacy;
case readAboutChoice:
open('https://github.com/editor-rs/vscode-rust/blob/master/doc/main.md');
break;
default:
return undefined;
}
}
}
/**
* Asks the user's permission to install something
* @param what What to install
* @return The flag indicating whether the user gave the permission
*/
async function askPermissionToInstall(what: string): Promise<boolean> {
const installChoice = 'Install';
const message = `It seems ${what} is not installed. Do you want to install it?`;
const choice = await window.showInformationMessage(message, installChoice);
return choice === installChoice;
}
class RlsMode {
private _configuration: Configuration;
private _rlsConfiguration: RlsConfiguration;
private _rustup: Rustup | undefined;
private _cargoInvocationManager: CargoInvocationManager;
private _logger: ChildLogger;
private _extensionContext: ExtensionContext;
public constructor(
configuration: Configuration,
rlsConfiguration: RlsConfiguration,
rustup: Rustup | undefined,
cargoInvocationManager: CargoInvocationManager,
logger: ChildLogger,
extensionContext: ExtensionContext
) {
this._configuration = configuration;
this._rlsConfiguration = rlsConfiguration;
this._rustup = rustup;
this._cargoInvocationManager = cargoInvocationManager;
this._logger = logger;
this._extensionContext = extensionContext;
}
/**
* Starts the extension in RLS mode
* @return The flag indicating whether the extension has been started in RLS mode
*/
public async start(): Promise<boolean> {
const logger = this._logger.createChildLogger('start: ');
logger.debug('enter');
{
const mode = this._configuration.mode();
if (mode !== Mode.RLS) {
logger.error(`mode=${mode}; this method should not have been called`);
return false;
}
}
if (!this._rlsConfiguration.isExecutableUserPathSet()) {
logger.debug('no RLS executable');
if (!this._rustup) {
logger.debug('no rustup');
await this.informUserThatModeCannotBeUsedAndAskToSwitchToAnotherMode('neither RLS executable path is specified nor rustup is installed');
return false;
}
// If the user wants to use the RLS mode and doesn't specify any executable path and rustup is installed, then the user wants the extension to take care of RLS and stuff
if (this._rustup.getNightlyToolchains().length === 0) {
// Since RLS can be installed only for some nightly toolchain and the user does
// not have any, then the extension should install it.
await this.handleMissingNightlyToolchain();
}
// Despite the fact that some nightly toolchains may be installed, the user might have
// chosen some toolchain which isn't installed now
processPossibleSetButMissingUserToolchain(
logger,
this._rustup,
'nightly toolchain',
(r: Rustup) => r.getUserNightlyToolchain(),
(r: Rustup) => r.setUserNightlyToolchain
);
if (!this._rustup.getUserNightlyToolchain()) {
// Either the extension havecleared the user nightly toolchain or the user haven't
// chosen it yet. Either way we need to ask the user to choose some nightly toolchain
await handleMissingRustupUserToolchain(
logger,
'nightly toolchain',
this._rustup.getNightlyToolchains.bind(this._rustup),
this._rustup.setUserNightlyToolchain.bind(this._rustup)
);
}
const userNightlyToolchain = this._rustup.getUserNightlyToolchain();
if (!userNightlyToolchain) {
await await this.informUserThatModeCannotBeUsedAndAskToSwitchToAnotherMode('neither RLS executable path is specified nor any nightly toolchain is chosen');
return false;
}
const userToolchain = this._rustup.getUserToolchain();
if (userNightlyToolchain && (!userToolchain || !userToolchain.equals(userNightlyToolchain))) {
await this._rustup.updateComponents(userNightlyToolchain);
}
await this.processPossiblyMissingRlsComponents();
}
if (!this._rlsConfiguration.getExecutablePath()) {
await this.informUserThatModeCannotBeUsedAndAskToSwitchToAnotherMode('RLS is not found');
return false;
}
if (this._rlsConfiguration.getUseRustfmt() === undefined) {
logger.debug('User has not decided whether rustfmt should be used yet');
await this.handleMissingValueForUseRustfmt();
}
switch (this._rlsConfiguration.getUseRustfmt()) {
case true:
logger.debug('User decided to use rustfmt');
const formattingManager = await FormattingManager.create(
this._extensionContext,
this._configuration,
this._logger
);
if (formattingManager === undefined) {
await this.handleMissingRustfmt();
// The user may have decided not to use rustfmt
if (this._rlsConfiguration.getUseRustfmt()) {
const anotherFormattingManager = await FormattingManager.create(
this._extensionContext,
this._configuration,
this._logger
);
if (anotherFormattingManager === undefined) {
window.showErrorMessage('Formatting: some error happened');
}
}
}
break;
case false:
logger.debug('User decided not to use rustfmt');
break;
case undefined:
logger.debug('User dismissed the dialog');
break;
}
const rlsPath = <string>this._rlsConfiguration.getExecutablePath();
logger.debug(`rlsPath=${rlsPath} `);
const env = this._rlsConfiguration.getEnv();
logger.debug(`env=${JSON.stringify(env)} `);
const args = this._rlsConfiguration.getArgs();
logger.debug(`args=${JSON.stringify(args)} `);
const revealOutputChannelOn = this._rlsConfiguration.getRevealOutputChannelOn();
logger.debug(`revealOutputChannelOn=${revealOutputChannelOn} `);
const languageClientManager = new LanguageClientManager(
this._extensionContext,
logger.createChildLogger('Language Client Manager: '),
rlsPath,
args,
env,
revealOutputChannelOn
);
languageClientManager.initialStart();
return true;
}
private async processPossiblyMissingRlsComponents(): Promise<void> {
async function installComponent(componentName: string, installComponent: () => Promise<boolean>): Promise<boolean> {
window.showInformationMessage(`${componentName} is being installed. It can take a while`);
const componentInstalled = await installComponent();
logger.debug(`${componentName} has been installed=${componentInstalled} `);
if (componentInstalled) {
window.showInformationMessage(`${componentName} has been installed successfully`);
} else {
window.showErrorMessage(`${componentName} has not been installed. Check the output channel "Rust Logging"`);
}
return componentInstalled;
}
const logger = this._logger.createChildLogger('processPossiblyMissingRlsComponents: ');
if (!this._rustup) {
logger.error('no rustup; this method should not have been called');
return;
}
const userToolchain = this._rustup.getUserNightlyToolchain();
if (!userToolchain) {
logger.error('no user toolchain; this method should have not have been called');
return;
}
if (this._rustup.isRlsInstalled()) {
logger.debug('RLS is installed');
} else {
logger.debug('RLS is not installed');
if (this._rustup.canInstallRls()) {
logger.debug('RLS can be installed');
} else {
logger.error('RLS cannot be installed');
return;
}
const userAgreed = await askPermissionToInstall('RLS');
if (!userAgreed) {
return;
}
const rlsInstalled = await installComponent(
'RLS',
async () => {
if (this._rustup) {
return await this._rustup.installRls();
} else {
return false;
}
}
);
if (rlsInstalled) {
logger.debug('RLS has been installed');
} else {
logger.error('RLS has not been installed');
return;
}
}
if (this._rustup.isRustAnalysisInstalled()) {
logger.debug('rust-analysis is installed');
} else {
logger.debug('rust-analysis is not installed');
if (this._rustup.canInstallRustAnalysis()) {
logger.debug('rust-analysis can be installed');
} else {
logger.error('rust-analysis cannot be installed');
return;
}
const userAgreed = await askPermissionToInstall('rust-analysis');
if (!userAgreed) {
return;
}
const rustAnalysisInstalled = await installComponent(
'rust-analysis',
async () => {
if (this._rustup) {
return await this._rustup.installRustAnalysis();
} else {
return false;
}
}
);
if (rustAnalysisInstalled) {
logger.debug('rust-analysis has been installed');
} else {
logger.debug('rust-analysis has not been installed');
}
}
}
private async informUserThatModeCannotBeUsedAndAskToSwitchToAnotherMode(reason: string): Promise<void> {
const logger = this._logger.createChildLogger('informUserThatModeCannotBeUsedAndAskToSwitchToAnotherMode: ');
logger.debug(`reason=${reason}`);
const message = `You have chosen RLS mode, but ${reason}`;
const switchToLegacyModeChoice = 'Switch to Legacy mode';
const askMeLaterChoice = 'Ask me later';
const choice = await window.showErrorMessage(message, switchToLegacyModeChoice, askMeLaterChoice);
switch (choice) {
case switchToLegacyModeChoice:
logger.debug('User decided to switch to Legacy Mode');
this._configuration.setMode(Mode.Legacy);
break;
case askMeLaterChoice:
logger.debug('User asked to be asked later');
this._configuration.setMode(undefined);
break;
default:
logger.debug('User dismissed the dialog');
this._configuration.setMode(undefined);
break;
}
}
/**
* Handles the case when rustup reported that the nightly toolchain wasn't installed
* @param logger The logger to log messages
* @param rustup The rustup
*/
private async handleMissingNightlyToolchain(): Promise<boolean> {
const logger = this._logger.createChildLogger('handleMissingNightlyToolchain: ');
if (!this._rustup) {
logger.error('no rustup; the method should not have been called');
return false;
}
if (this._rustup.getNightlyToolchains().length !== 0) {
logger.error('there are nightly toolchains; the method should not have been called');
return false;
}
const permissionGranted = await askPermissionToInstall('the nightly toolchain');
logger.debug(`permissionGranted=${permissionGranted}`);
if (!permissionGranted) {
return false;
}
window.showInformationMessage('The nightly toolchain is being installed. It can take a while. Please be patient');
const toolchainInstalled = await this._rustup.installToolchain('nightly');
logger.debug(`toolchainInstalled=${toolchainInstalled}`);
if (!toolchainInstalled) {
return false;
}
const toolchains = this._rustup.getNightlyToolchains();
switch (toolchains.length) {
case 0:
logger.error('the nightly toolchain has not been installed');
return false;
case 1:
logger.debug('the nightly toolchain has been installed');
return true;
default:
logger.error(`more than one toolchain detected; toolchains=${toolchains}`);
return false;
}
}
private async handleMissingValueForUseRustfmt(): Promise<void> {
const logger = this._logger.createChildLogger('handleMissingValueForUseRustfmt: ');
logger.debug('enter');
const yesChoice = 'Yes';
const noChoice = 'No';
const message = 'Do you want to use rustfmt for formatting?';
const choice = await window.showInformationMessage(message, yesChoice, noChoice);
switch (choice) {
case yesChoice:
logger.debug('User decided to use rustfmt');
this._rlsConfiguration.setUseRustfmt(true);
break;
case noChoice:
logger.debug('User decided not to use rustfmt');
this._rlsConfiguration.setUseRustfmt(false);
break;
default:
logger.debug('User dismissed the dialog');
break;
}
}
private async handleMissingRustfmt(): Promise<void> {
const logger = this._logger.createChildLogger('handleMissingRustfmt: ');
logger.debug('enter');
const message = 'rustfmt is not installed';
const installRustfmtChoice = 'Install rustfmt';
const dontUseRustfmtChoice = 'Don\'t use rustfmt';
const choice = await window.showInformationMessage(message, installRustfmtChoice, dontUseRustfmtChoice);
switch (choice) {
case installRustfmtChoice:
logger.debug('User decided to install rustfmt');
const { executable, args } = this._cargoInvocationManager.getExecutableAndArgs();
const result = await OutputChannelProcess.create(
executable,
[...args, 'install', 'rustfmt'],
undefined,
'Installing rustfmt'
);
const success = result.success && result.code === 0;
if (success) {
logger.debug('rustfmt has been installed');
window.showInformationMessage('rustfmt has been installed');
} else {
logger.error('rustfmt has not been installed');
window.showErrorMessage('rustfmt has not been installed');
this._rlsConfiguration.setUseRustfmt(false);
}
break;
case dontUseRustfmtChoice:
logger.debug('User decided not to use rustfmt');
this._rlsConfiguration.setUseRustfmt(false);
break;
default:
logger.debug('User dismissed the dialog');
this._rlsConfiguration.setUseRustfmt(undefined);
break;
}
}
}
async function handleMissingRustupUserToolchain(
logger: ChildLogger,
toolchainKind: string,
getToolchains: () => Toolchain[],
setToolchain: (toolchain: Toolchain | undefined) => void
): Promise<void> {
class Item implements QuickPickItem {
public toolchain: Toolchain;
public label: string;
public description: string;
public constructor(toolchain: Toolchain, shouldLabelContainHost: boolean) {
this.toolchain = toolchain;
this.label = toolchain.toString(shouldLabelContainHost, true);
this.description = '';
}
}
const functionLogger = logger.createChildLogger('handleMissingRustupUserToolchain: ');
functionLogger.debug(`toolchainKind=${toolchainKind}`);
await window.showInformationMessage(`To properly function, the extension needs to know what ${toolchainKind} you want to use`);
const toolchains = getToolchains();
if (toolchains.length === 0) {
functionLogger.error('no toolchains');
return;
}
const toolchainsHaveOneHost = toolchains.every(t => t.host === toolchains[0].host);
const items = toolchains.map(t => new Item(t, !toolchainsHaveOneHost));
const item = await window.showQuickPick(items);
if (!item) {
return;
}
setToolchain(item.toolchain);
}
function processPossibleSetButMissingUserToolchain(
logger: ChildLogger,
rustup: Rustup,
toolchainKind: string,
getToolchain: (rustup: Rustup) => Toolchain | undefined,
setToolchain: (rustup: Rustup) => (toolchain: Toolchain | undefined) => void
): void {
const functionLogger = logger.createChildLogger('processPossibleSetButMissingUserToolchain: ');
functionLogger.debug(`toolchainKind=${toolchainKind}`);
const userToolchain = getToolchain(rustup);
if (userToolchain === undefined) {
functionLogger.debug(`no user ${toolchainKind}`);
return;
}
if (rustup.isToolchainInstalled(userToolchain)) {
functionLogger.debug(`user ${toolchainKind} is installed`);
return;
}
logger.error(`user ${toolchainKind} is not installed`);
window.showErrorMessage(`The specified ${toolchainKind} is not installed`);
setToolchain(rustup)(undefined);
}
export async function activate(ctx: ExtensionContext): Promise<void> {
const loggingManager = new LoggingManager();
const logger = loggingManager.getLogger();
const functionLogger = logger.createChildLogger('activate: ');
const rustup = await Rustup.create(logger.createChildLogger('Rustup: '));
if (rustup) {
await rustup.updateToolchains();
processPossibleSetButMissingUserToolchain(
functionLogger,
rustup,
'toolchain',
(r: Rustup) => r.getUserToolchain(),
(r: Rustup) => r.setUserToolchain
);
if (!rustup.getUserToolchain()) {
await handleMissingRustupUserToolchain(
functionLogger,
'toolchain',
rustup.getToolchains.bind(rustup),
rustup.setUserToolchain.bind(rustup)
);
}
const userToolchain = rustup.getUserToolchain();
if (userToolchain) {
await rustup.updateSysrootPath(userToolchain);
await rustup.updateComponents(userToolchain);
await rustup.updatePathToRustSourceCodePath();
}
}
const rustSource = await RustSource.create(rustup);
const configuration = new Configuration(logger.createChildLogger('Configuration: '));
const cargoInvocationManager = new CargoInvocationManager(rustup);
const rlsConfiguration = await RlsConfiguration.create(rustup, rustSource);
if (configuration.mode() === undefined) {
// The current configuration does not contain any specified mode and hence we should try to
// choose one.
const mode = await askUserToChooseMode();
switch (mode) {
case Mode.Legacy:
configuration.setMode(Mode.Legacy);
break;
case Mode.RLS:
configuration.setMode(Mode.RLS);
break;
case undefined:
break;
}
}
const currentWorkingDirectoryManager = new CurrentWorkingDirectoryManager();
const shellProviderManager = new ShellProviderManager(logger);
const cargoManager = new CargoManager(
ctx,
configuration,
cargoInvocationManager,
currentWorkingDirectoryManager,
shellProviderManager,
logger.createChildLogger('Cargo Manager: ')
);
addExecutingActionOnSave(ctx, configuration, cargoManager);
if (configuration.mode() === Mode.RLS) {
const rlsMode = new RlsMode(
configuration,
rlsConfiguration,
rustup,
cargoInvocationManager,
logger.createChildLogger('RlsMode: '),
ctx
);
const started = await rlsMode.start();
if (started) {
return;
}
}
// If we got here, then the chosen mode is not RLS
switch (configuration.mode()) {
case Mode.Legacy:
case undefined:
await runInLegacyMode(
ctx,
configuration,
cargoInvocationManager,
rustSource,
rustup,
currentWorkingDirectoryManager,
shellProviderManager,
logger
);
break;
case Mode.RLS:
break;
}
}
async function runInLegacyMode(
context: ExtensionContext,
configuration: Configuration,
cargoInvocationManager: CargoInvocationManager,
rustSource: RustSource,
rustup: Rustup | undefined,
currentWorkingDirectoryManager: CurrentWorkingDirectoryManager,
shellProviderManager: ShellProviderManager,
logger: RootLogger
): Promise<void> {
const legacyModeManager = await LegacyModeManager.create(
context,
configuration,
cargoInvocationManager,
rustSource,
rustup,
currentWorkingDirectoryManager,
shellProviderManager,
logger.createChildLogger('Legacy Mode Manager: ')
);
await legacyModeManager.start();
}
function addExecutingActionOnSave(
context: ExtensionContext,
configuration: Configuration,
cargoManager: CargoManager
): void {
context.subscriptions.push(workspace.onDidSaveTextDocument(document => {
if (!window.activeTextEditor) {
return;
}
const activeDocument = window.activeTextEditor.document;
if (document !== activeDocument) {
return;
}
if (document.languageId !== 'rust' || !document.fileName.endsWith('.rs')) {
return;
}
const actionOnSave = configuration.getActionOnSave();
if (!actionOnSave) {
return;
}
switch (actionOnSave) {
case 'build':
cargoManager.executeBuildTask(CommandInvocationReason.ActionOnSave);
break;
case 'check':
cargoManager.executeCheckTask(CommandInvocationReason.ActionOnSave);
break;
case 'clippy':
cargoManager.executeClippyTask(CommandInvocationReason.ActionOnSave);
break;
case 'doc':
cargoManager.executeDocTask(CommandInvocationReason.ActionOnSave);
break;
case 'run':
cargoManager.executeRunTask(CommandInvocationReason.ActionOnSave);
break;
case 'test':
cargoManager.executeTestTask(CommandInvocationReason.ActionOnSave);
break;
}
}));
} | the_stack |
import * as path from "path";
import * as fs from "fs";
import { ProjectInSolution } from "./ProjectInSolution";
import { SolutionConfigurationInSolution } from "./SolutionConfigurationInSolution";
import { SolutionProjectType } from "./SolutionProjectType";
import { ProjectConfigurationInSolution } from "./ProjectConfigurationInSolution";
const vbProjectGuid = "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}";
const csProjectGuid = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}";
const cpsProjectGuid = "{13B669BE-BB05-4DDF-9536-439F39A36129}"; //common project system
const cpsCsProjectGuid = "{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"; //common project system
const cpsVbProjectGuid = "{778DAE3C-4631-46EA-AA77-85C1314464D9}"; //common project system
const vjProjectGuid = "{E6FDF86B-F3D1-11D4-8576-0002A516ECE8}";
const vcProjectGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
const fsProjectGuid = "{F2A71F9B-5D33-465A-A702-920D77279786}";
const cpsFsProjectGuid = "{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}";
const dbProjectGuid = "{C8D11400-126E-41CD-887F-60BD40844F9E}";
const wdProjectGuid = "{2CFEAB61-6A3B-4EB8-B523-560B4BEEF521}";
const webProjectGuid = "{E24C65DC-7377-472B-9ABA-BC803B73C61A}";
const solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}";
export class SolutionFile {
private lines: string[];
private currentLineIndex: number;
private projects:{ [id: string] : ProjectInSolution; } = {};
private solutionConfigurations: SolutionConfigurationInSolution[] = [];
private currentVisualStudioVersion: string;
private name: string;
private fullPath: string;
private folderPath: string;
private version: string;
private solutionContainsWebProjects: boolean = false;
private solutionContainsWebDeploymentProjects: boolean = false;
private constructor() {
}
public get Name(): string {
return this.name;
}
public get FullPath(): string {
return this.fullPath;
}
public get FolderPath(): string {
return this.folderPath;
}
public get Version(): string {
return this.version;
}
public get ContainsWebProjects(): boolean {
return this.solutionContainsWebProjects;
}
public get ContainsWebDeploymentProjects(): boolean {
return this.solutionContainsWebDeploymentProjects;
}
public get ProjectsById(): { [id: string] : ProjectInSolution; } {
return this.projects;
}
public get Projects(): ProjectInSolution[] {
let result: ProjectInSolution[] = [];
Object.keys(this.projects).forEach(key => {
result.push(this.projects[key]);
});
return result;
}
public get Configurations(): SolutionConfigurationInSolution[] {
return this.solutionConfigurations;
}
public static Parse(solutionFullPath: string) : Thenable<SolutionFile> {
return new Promise(resolve => {
let solution = new SolutionFile();
solution.fullPath = solutionFullPath;
solution.folderPath = path.dirname(solutionFullPath);
solution.name = solutionFullPath.split(path.sep).pop().replace('.sln', '');
fs.readFile(solutionFullPath, 'utf8', (err, data) => {
solution.lines = data.split('\n');
solution.currentLineIndex = 0;
solution.ParseSolution();
resolve(solution);
});
});
}
private ReadLine(): string {
if (this.currentLineIndex >= this.lines.length)
return null;
return this.lines[this.currentLineIndex++].trim();
}
private ParseSolution(): void {
this.ParseFileHeader();
let str: string;
let rawProjectConfigurationsEntries: { [id: string]: any };
while ((str = this.ReadLine()) != null)
{
if (str.startsWith("Project("))
{
this.ParseProject(str);
}
else if (str.startsWith("GlobalSection(NestedProjects)"))
{
this.ParseNestedProjects();
}
else if (str.startsWith("GlobalSection(SolutionConfigurationPlatforms)"))
{
this.ParseSolutionConfigurations();
}
else if (str.startsWith("GlobalSection(ProjectConfigurationPlatforms)"))
{
rawProjectConfigurationsEntries = this.ParseProjectConfigurations();
}
else if (str.startsWith("VisualStudioVersion"))
{
this.currentVisualStudioVersion = this.ParseVisualStudioVersion(str);
}
else
{
// No other section types to process at this point, so just ignore the line
// and continue.
}
}
if (rawProjectConfigurationsEntries != null)
{
this.ProcessProjectConfigurationSection(rawProjectConfigurationsEntries);
}
}
private ParseFileHeader(): void {
const slnFileHeaderNoVersion: string = "Microsoft Visual Studio Solution File, Format Version ";
for (let i = 1; i <= 2; i++) {
let str: string = this.ReadLine();
if (str == null) {
break;
}
if (str.startsWith(slnFileHeaderNoVersion)) {
// Found it. Validate the version.
this.version = str.substring(slnFileHeaderNoVersion.length);
return;
}
}
}
private ParseProject(firstLine: string): void {
let proj = new ProjectInSolution(this);
// Extract the important information from the first line.
this.ParseFirstProjectLine(firstLine, proj);
let line: string;
while ((line = this.ReadLine()) != null)
{
// If we see an "EndProject", well ... that's the end of this project!
if (line == "EndProject")
{
break;
}
else if (line.startsWith("ProjectSection(SolutionItems)"))
{
// We have a ProjectDependencies section. Each subsequent line should identify
// a dependency.
line = this.ReadLine();
while ((line != null) && (!line.startsWith("EndProjectSection")))
{
const propertyLineRegEx = /(.*)\s*=\s*(.*)/g;
const m = propertyLineRegEx.exec(line);
const fileName: string = path.basename(m[1].trim());
const filePath: string = m[2].trim();
proj.addFile(fileName, filePath);
line = this.ReadLine();
}
}
else if (line.startsWith("ProjectSection(ProjectDependencies)"))
{
// We have a ProjectDependencies section. Each subsequent line should identify
// a dependency.
line = this.ReadLine();
while ((line != null) && (!line.startsWith("EndProjectSection")))
{
let propertyLineRegEx = /(.*)\s*=\s*(.*)/g;
let m = propertyLineRegEx.exec(line);
let parentGuid: string = m[1].trim();
proj.addDependency(parentGuid);
line = this.ReadLine();
}
}
else if (line.startsWith("ProjectSection(WebsiteProperties)"))
{
// We have a WebsiteProperties section. This section is present only in Venus
// projects, and contains properties that we'll need in order to call the
// AspNetCompiler task.
line = this.ReadLine();
while ((line != null) && (!line.startsWith("EndProjectSection")))
{
let propertyLineRegEx = /(.*)\s*=\s*(.*)/g;
let m = propertyLineRegEx.exec(line);
let propertyName: string = m[1].trim();
let propertyValue: string = m[2].trim();
proj.addWebProperty(propertyName, propertyValue);
line = this.ReadLine();
}
}
}
}
private ParseFirstProjectLine(firstLine: string, proj: ProjectInSolution): void {
let projectRegEx = /Project\("(.*)"\)\s*=\s*"(.*)"\s*,\s*"(.*)"\s*,\s*"(.*)"/g;
let m = projectRegEx.exec(firstLine);
proj.projectTypeId = m[1].trim();
proj.projectName = m[2].trim();
proj.relativePath = m[3].trim();
proj.fullPath = path.join(this.FolderPath, m[3].replace(/\\/g, path.sep)).trim();
proj.projectGuid = m[4].trim();
this.projects[proj.projectGuid] = proj;
if ((proj.projectTypeId == vbProjectGuid) ||
(proj.projectTypeId == csProjectGuid) ||
(proj.projectTypeId == cpsProjectGuid) ||
(proj.projectTypeId == cpsCsProjectGuid) ||
(proj.projectTypeId == cpsVbProjectGuid) ||
(proj.projectTypeId == fsProjectGuid) ||
(proj.projectTypeId == cpsFsProjectGuid) ||
(proj.projectTypeId == dbProjectGuid) ||
(proj.projectTypeId == vjProjectGuid))
{
proj.projectType = SolutionProjectType.KnownToBeMSBuildFormat;
}
else if (proj.projectTypeId == solutionFolderGuid)
{
proj.projectType = SolutionProjectType.SolutionFolder;
}
// MSBuild format VC projects have the same project type guid as old style VC projects.
// If it's not an old-style VC project, we'll assume it's MSBuild format
else if (proj.projectTypeId == vcProjectGuid)
{
proj.projectType = SolutionProjectType.KnownToBeMSBuildFormat;
}
else if (proj.projectTypeId == webProjectGuid)
{
proj.projectType = SolutionProjectType.WebProject;
this.solutionContainsWebProjects = true;
}
else if (proj.projectTypeId == wdProjectGuid)
{
proj.projectType = SolutionProjectType.WebDeploymentProject;
this.solutionContainsWebDeploymentProjects = true;
}
else
{
proj.projectType = SolutionProjectType.Unknown;
}
}
private ParseNestedProjects(): void {
let str: string;
do
{
str = this.ReadLine();
if ((str == null) || (str == "EndGlobalSection")) {
break;
}
if (!str) {
continue;
}
let propertyLineRegEx = /(.*)\s*=\s*(.*)/g;
let m = propertyLineRegEx.exec(str);
let projectGuid: string = m[1].trim();
let parentProjectGuid: string = m[2].trim();
let proj: ProjectInSolution = this.projects[projectGuid];
if (!proj) {
// error
}
proj.parentProjectGuid = parentProjectGuid;
} while (true);
}
private ParseSolutionConfigurations(): void {
let str: string;
let nameValueSeparator: string = '=' ;
let configPlatformSeparators: string = '|';
do
{
str = this.ReadLine();
if ((str == null) || (str == "EndGlobalSection")) {
break;
}
if (!str) {
continue;
}
let configurationNames: string[] = str.split(nameValueSeparator);
let fullConfigurationName: string = configurationNames[0].trim();
if (fullConfigurationName === "DESCRIPTION")
continue;
let configurationPlatformParts: string[] = fullConfigurationName.split(configPlatformSeparators);
this.solutionConfigurations.push(new SolutionConfigurationInSolution(configurationPlatformParts[0], configurationPlatformParts[1]));
} while (true);
}
private ParseProjectConfigurations(): { [id: string]: any } {
let rawProjectConfigurationsEntries: { [id: string]: string } = {};
let str : string;
do
{
str = this.ReadLine();
if ((str == null) || (str == "EndGlobalSection")) {
break;
}
if (!str) {
continue;
}
let nameValue: string[] = str.split('=');
rawProjectConfigurationsEntries[nameValue[0].trim()] = nameValue[1].trim();
} while (true);
return rawProjectConfigurationsEntries;
}
private ParseVisualStudioVersion(str: string): string
{
let delimiterChars: string = '=';
let words: string[] = str.split(delimiterChars);
return words[1].trim();
}
private ProcessProjectConfigurationSection(rawProjectConfigurationsEntries: { [id: string]: string }): void {
// Instead of parsing the data line by line, we parse it project by project, constructing the
// entry name (e.g. "{A6F99D27-47B9-4EA4-BFC9-25157CBDC281}.Release|Any CPU.ActiveCfg") and retrieving its
// value from the raw data. The reason for this is that the IDE does it this way, and as the result
// the '.' character is allowed in configuration names although it technically separates different
// parts of the entry name string. This could lead to ambiguous results if we tried to parse
// the entry name instead of constructing it and looking it up. Although it's pretty unlikely that
// this would ever be a problem, it's safer to do it the same way VS IDE does it.
let configPlatformSeparators = '|';
Object.keys(this.projects).forEach(key => {
let project = this.projects[key];
// Solution folders don't have configurations
if (project.projectType != SolutionProjectType.SolutionFolder)
{
this.solutionConfigurations.forEach(solutionConfiguration => {
// The "ActiveCfg" entry defines the active project configuration in the given solution configuration
// This entry must be present for every possible solution configuration/project combination.
let entryNameActiveConfig: string = project.projectGuid + "." + solutionConfiguration.fullName + ".ActiveCfg";
// The "Build.0" entry tells us whether to build the project configuration in the given solution configuration.
// Technically, it specifies a configuration name of its own which seems to be a remnant of an initial,
// more flexible design of solution configurations (as well as the '.0' suffix - no higher values are ever used).
// The configuration name is not used, and the whole entry means "build the project configuration"
// if it's present in the solution file, and "don't build" if it's not.
let entryNameBuild = project.projectGuid + "." + solutionConfiguration.fullName + ".Build.0";
if (rawProjectConfigurationsEntries[entryNameActiveConfig]) {
let configurationPlatformParts = rawProjectConfigurationsEntries[entryNameActiveConfig].split(configPlatformSeparators);
let projectConfiguration = new ProjectConfigurationInSolution(
configurationPlatformParts[0],
(configurationPlatformParts.length > 1) ? configurationPlatformParts[1] : '',
!!rawProjectConfigurationsEntries[entryNameBuild]
);
project.setProjectConfiguration(solutionConfiguration.fullName, projectConfiguration);
}
});
}
});
}
} | the_stack |
import * as ts from "typescript/lib/tsserverlibrary";
import * as lsp from "vscode-languageserver";
import { Logger } from "./logger";
import { ProjectService } from "./project_service";
import { projectLoadingNotification } from "./protocol";
import { ServerHost } from "./server_host";
import { tsDiagnosticToLspDiagnostic } from "./diagnostic";
import { tsCompletionEntryToLspCompletionItem } from "./completion";
import {
filePathToUri,
lspPositionToTsPosition,
tsTextSpanToLspRange,
uriToFilePath,
} from "./utils";
import { isDenoProject } from "./utils/deno";
export interface ConnectionOptions {
host: ServerHost;
logger: Logger;
pluginProbeLocations?: string[];
}
const LanguageTsIds = [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
];
// Empty definition range for files without `scriptInfo`
const EMPTY_RANGE = lsp.Range.create(0, 0, 0, 0);
/**
* Connection is a wrapper around lsp.IConnection, with all the necessary protocol
* handlers installed for Deno language service.
*/
export class Connection {
private readonly connection: lsp.IConnection;
private readonly projectService: ProjectService;
private diagnosticsTimeout: NodeJS.Timeout | null = null;
private isProjectLoading = false;
constructor(options: ConnectionOptions) {
// Create a connection for the server. The connection uses Node's IPC as a transport.
this.connection = lsp.createConnection();
this.addProtocolHandlers(this.connection);
this.projectService = new ProjectService({
host: options.host,
logger: options.logger,
cancellationToken: ts.server.nullCancellationToken,
useSingleInferredProject: true,
useInferredProjectPerProjectRoot: true,
typingsInstaller: ts.server.nullTypingsInstaller,
// Not supressing diagnostic events can cause a type error to be thrown when the
// language server session gets an event for a file that is outside the project
// managed by the project service, and for which a program does not exist in the
// corresponding project's language service.
// See https://github.com/angular/vscode-ng-language-service/issues/693
suppressDiagnosticEvents: true,
eventHandler: (e) => this.handleProjectServiceEvent(e),
globalPlugins: ["typescript-deno-plugin"],
pluginProbeLocations: options.pluginProbeLocations,
allowLocalPluginLoads: false, // do not load plugins from tsconfig.json
});
}
private addProtocolHandlers(conn: lsp.IConnection) {
conn.onDidOpenTextDocument((p) => this.onDidOpenTextDocument(p));
conn.onDidCloseTextDocument((p) => this.onDidCloseTextDocument(p));
conn.onDidSaveTextDocument((p) => this.onDidSaveTextDocument(p));
conn.onDefinition((p) => this.onDefinition(p));
conn.onCompletion((p) => this.onCompletion(p));
}
/**
* An event handler that gets invoked whenever the program changes and
* TS ProjectService sends `ProjectUpdatedInBackgroundEvent`. This particular
* event is used to trigger diagnostic checks.
* @param event
*/
private handleProjectServiceEvent(event: ts.server.ProjectServiceEvent) {
this.connection.console.log("handleProjectServiceEvent");
switch (event.eventName) {
case ts.server.ProjectLoadingStartEvent:
this.isProjectLoading = true;
this.connection.console.log("project loading");
this.connection.sendNotification(projectLoadingNotification.start);
break;
case ts.server.ProjectLoadingFinishEvent: {
const { project } = event.data;
try {
// Disable language service if project is not Deno
this.checkIsDenoProject(project);
} finally {
if (this.isProjectLoading) {
this.isProjectLoading = false;
this.connection.console.log("project load finish");
this.connection.sendNotification(projectLoadingNotification.finish);
}
}
break;
}
case ts.server.ProjectsUpdatedInBackgroundEvent:
// ProjectsUpdatedInBackgroundEvent is sent whenever diagnostics are
// requested via project.refreshDiagnostics()
this.triggerDiagnostics(event.data.openFiles);
break;
}
}
/**
* Retrieve Deno diagnostics for the specified `openFiles` after a specific
* `delay`, or renew the request if there's already a pending one.
* @param openFiles
* @param delay time to wait before sending request (milliseconds)
*/
private triggerDiagnostics(openFiles: string[], delay: number = 200) {
// Do not immediately send a diagnostics request. Send only after user has
// stopped typing after the specified delay.
if (this.diagnosticsTimeout) {
// If there's an existing timeout, cancel it
clearTimeout(this.diagnosticsTimeout);
}
// Set a new timeout
this.diagnosticsTimeout = setTimeout(() => {
this.diagnosticsTimeout = null; // clear the timeout
this.sendPendingDiagnostics(openFiles);
// Default delay is 200ms, consistent with TypeScript. See
// https://github.com/microsoft/vscode/blob/7b944a16f52843b44cede123dd43ae36c0405dfd/extensions/typescript-language-features/src/features/bufferSyncSupport.ts#L493)
}, delay);
}
/**
* Execute diagnostics request for each of the specified `openFiles`.
* @param openFiles
*/
private sendPendingDiagnostics(openFiles: string[]) {
for (const fileName of openFiles) {
const scriptInfo = this.projectService.getScriptInfo(fileName);
if (!scriptInfo) {
continue;
}
const denoLgSrv = this.projectService.getDefaultLanguageService(
scriptInfo,
);
if (!denoLgSrv) {
continue;
}
const diagnostics = denoLgSrv.getSemanticDiagnostics(fileName);
// Need to send diagnostics even if it's empty otherwise editor state will
// not be updated.
this.connection.sendDiagnostics({
uri: filePathToUri(fileName),
diagnostics: diagnostics.map((d) =>
tsDiagnosticToLspDiagnostic(d, scriptInfo)
),
});
}
}
private onDidOpenTextDocument(params: lsp.DidOpenTextDocumentParams) {
const { uri, languageId, text } = params.textDocument;
this.connection.console.log(`open ${uri}`);
const filePath = uriToFilePath(uri);
if (!filePath) {
return;
}
const scriptKind = LanguageTsIds.includes(languageId)
? ts.ScriptKind.TS
: ts.ScriptKind.External;
try {
const result = this.projectService.openClientFile(
filePath,
text,
scriptKind,
);
const { configFileName, configFileErrors } = result;
if (configFileErrors && configFileErrors.length) {
// configFileErrors is an empty array even if there's no error, so check length.
this.connection.console.error(
configFileErrors.map((e) => e.messageText).join("\n"),
);
}
if (!configFileName) {
this.connection.console.error(`No config file for ${filePath}`);
return;
}
const project = this.projectService.findProject(configFileName);
if (!project) {
this.connection.console.error(`Failed to find project for ${filePath}`);
return;
}
if (project.languageServiceEnabled) {
project.refreshDiagnostics(); // Show initial diagnostics
}
} catch (error) {
if (this.isProjectLoading) {
this.isProjectLoading = false;
this.connection.sendNotification(projectLoadingNotification.finish);
}
if (error.stack) {
this.error(error.stack);
}
throw error;
}
}
private onDidCloseTextDocument(params: lsp.DidCloseTextDocumentParams) {
const { textDocument } = params;
const filePath = uriToFilePath(textDocument.uri);
if (!filePath) {
return;
}
this.projectService.closeClientFile(filePath);
}
private onDidSaveTextDocument(params: lsp.DidSaveTextDocumentParams) {
const { text, textDocument } = params;
const filePath = uriToFilePath(textDocument.uri);
const scriptInfo = this.projectService.getScriptInfo(filePath);
if (!scriptInfo) {
return;
}
if (text) {
scriptInfo.open(text);
} else {
scriptInfo.reloadFromFile();
}
}
private onDefinition(params: lsp.TextDocumentPositionParams) {
const { position, textDocument } = params;
const filePath = uriToFilePath(textDocument.uri);
const scriptInfo = this.projectService.getScriptInfo(filePath);
if (!scriptInfo) {
this.connection.console.log(`Script info not found for ${filePath}`);
return;
}
const { fileName } = scriptInfo;
const langSvc = this.projectService.getDefaultLanguageService(scriptInfo);
if (!langSvc) {
return;
}
const offset = lspPositionToTsPosition(scriptInfo, position);
const definition = langSvc.getDefinitionAndBoundSpan(fileName, offset);
if (!definition || !definition.definitions) {
return;
}
const originSelectionRange = tsTextSpanToLspRange(
scriptInfo,
definition.textSpan,
);
const results: lsp.LocationLink[] = [];
for (const d of definition.definitions) {
const scriptInfo = this.projectService.getScriptInfo(d.fileName);
// Some definitions, like definitions of CSS files, may not be recorded files with a
// `scriptInfo` but are still valid definitions because they are files that exist. In this
// case, check to make sure that the text span of the definition is zero so that the file
// doesn't have to be read; if the span is non-zero, we can't do anything with this
// definition.
if (!scriptInfo && d.textSpan.length > 0) {
continue;
}
const range = scriptInfo
? tsTextSpanToLspRange(scriptInfo, d.textSpan)
: EMPTY_RANGE;
const targetUri = filePathToUri(d.fileName);
results.push({
originSelectionRange,
targetUri,
targetRange: range,
targetSelectionRange: range,
});
}
return results;
}
private onCompletion(params: lsp.CompletionParams) {
const { position, textDocument } = params;
const filePath = uriToFilePath(textDocument.uri);
if (!filePath) {
return;
}
const scriptInfo = this.projectService.getScriptInfo(filePath);
if (!scriptInfo) {
return;
}
const { fileName } = scriptInfo;
const langSvc = this.projectService.getDefaultLanguageService(scriptInfo);
if (!langSvc) {
return;
}
const offset = lspPositionToTsPosition(scriptInfo, position);
const completions = langSvc.getCompletionsAtPosition(
fileName,
offset,
{
// options
},
);
if (!completions) {
return;
}
return completions.entries.map(
(e) => tsCompletionEntryToLspCompletionItem(e, position, scriptInfo),
);
}
/**
* Show an error message.
*
* @param message The message to show.
*/
error(message: string): void {
this.connection.console.error(message);
}
/**
* Show a warning message.
*
* @param message The message to show.
*/
warn(message: string): void {
this.connection.console.warn(message);
}
/**
* Show an information message.
*
* @param message The message to show.
*/
info(message: string): void {
this.connection.console.info(message);
}
/**
* Log a message.
*
* @param message The message to log.
*/
log(message: string): void {
this.connection.console.log(message);
}
/**
* Start listening on the input stream for messages to process.
*/
listen() {
this.connection.listen();
}
/**
* Determine if the specified `project` is Deno, and disable the language
* service if not.
* @param project
*/
private checkIsDenoProject(project: ts.server.Project) {
const DENO_MOD = "mod.ts";
const { projectName } = project;
if (!project.languageServiceEnabled) {
const msg = `Language service is already disabled for ${projectName}. ` +
`This could be due to non-TS files that exceeded the size limit (${ts.server.maxProgramSizeForNonTsFiles} bytes).` +
`Please check log file for details.`;
this.connection.console.info(msg); // log to remote console to inform users
project.log(msg); // log to file, so that it's easier to correlate with ts entries
return;
}
if (!isDenoProject(project, DENO_MOD)) {
project.disableLanguageService();
const msg =
`Disabling language service for ${projectName} because it is not an Deno project ` +
`('${DENO_MOD}' could not be found). `;
this.connection.console.info(msg);
project.log(msg);
return;
}
// The language service should be enabled at this point.
this.connection.console.info(
`Enabling language service for ${projectName}.`,
);
}
} | the_stack |
import { t } from "typy";
import { IQueryOperationResolver, IQueryResolver, IEntityQueryResolver } from "@miniql/core-types";
export { INestedEntityResolver, INestedEntityResolvers, IEntityQueryResolver, IQueryOperationResolver, IQueryResolver } from "@miniql/core-types";
//
// Represents a nested/related entity to be resovled.
//
export interface INestedEntityResolve {
//
// Each nested entity is just another entity query.
//
[entityTypeName: string]: IEntityQuery;
}
//
// Represents a query for a particular entity type.
//
export interface IEntityQuery {
//
// The name of the global entity resolver to invoke to get the entity.
// If this is omitted the entity resolver name defaults to the entity name.
//
from?: string;
//
// Arguments to pass to the query resolver (the MiniQL backend).
//
args?: any;
//
// Instructions on what nested/related entities should be resolved.
//
resolve?: INestedEntityResolve;
}
//
// Represents a particular query operation (eg query or update).
//
export interface IQueryOperation {
//
// Sub-queries for each entity.
//
[queryKey: string]: IEntityQuery;
}
//
// Represents a root level query.
//
export interface IQuery {
//
// Sub-queries for each type of operation.
//
[operationName: string]: IQueryOperation;
};
//
// Container for globals passed recursively through the query process.
//
interface IQueryGlobals {
//
// The root resolver for the current query option.
//
operationResolver: IQueryOperationResolver;
//
// Name of the query operation being invoked.
//
opName: string;
//
// Global user-defined context for the query.
//
context: any;
}
//
// Logs a verbose message.
//
function verbose(verbose: boolean, nestingLevel: number, msg: any) {
if (verbose) {
console.log(" ".repeat(nestingLevel*4) + msg);
}
}
//
// Deeply copy on object into anothyer.
//
function deepCopyObject(input: any, output: any, path: string): void {
for (const key of Object.keys(input)) {
const value = input[key];
const tt = t(value);
if (tt.isObject) {
if (output[key] === undefined) {
output[key] = {};
}
else if (!t(output[key]).isObject) {
throw new Error(`Expected existing value at ${path}/${key} to be an object in order to have sub-fields.`);
}
deepCopyObject(value, output[key], `${path}/${key}`);
}
else {
if (output[key] !== undefined) {
throw new Error(`Error merging resolvers, ${path}/${key} is already defined!`)
}
output[key] = input[key];
}
}
}
//
// Executes a query.
//
export async function miniql<T = any>(rootQuery: IQuery, rootResolver: IQueryResolver | IQueryResolver[], context: any): Promise<T> {
const output: any = {};
let queryResolver: IQueryResolver;
if (t(rootResolver).isArray) {
queryResolver = {};
let index = 0;
for (const partialQueryResolver of (rootResolver as IQueryResolver[])) {
deepCopyObject(partialQueryResolver, queryResolver, `[${index}]`);
index += 1;
}
}
else {
queryResolver = rootResolver as IQueryResolver;
}
const opNames = Object.keys(rootQuery); //todo: if more than 1 opName maybe nest output under opname?
if (opNames.length <= 0) {
throw new Error(`Query doesn't contain any operations.`);
}
verbose(context.verbose, 0, `** Executing query.`);
for (const opName of opNames) {
verbose(context.verbose, 1, `= Invoking query operation "${opName}".`);
const queryOperation = getQueryOperation(rootQuery, opName);
const operationResolver = getOperationResolver(queryResolver, opName);
for (const entityTypeName of Object.keys(queryOperation)) {
await resolveRootEntity(queryOperation, output, entityTypeName, { operationResolver, opName, context }, 2);
}
}
return output;
}
//
// Gets an operation resolver from a query with error checkign.
//
function getOperationResolver(rootResolver: IQueryResolver, opName: string) {
const operationResolver = rootResolver[opName];
if (!operationResolver) {
throw new Error(createErrorForMissingQueryOperation(opName));
}
if (!t(operationResolver).isObject) {
throw new Error(`Expected query resolver for "${opName}" to be an object.`);
}
return operationResolver;
}
//
// Gets query operation from a query with some error checking.
//
function getQueryOperation(rootQuery: IQuery, opName: string) {
const queryOperation = rootQuery[opName];
if (!queryOperation) {
throw new Error(`Query operation "${opName}" is missing from query.`);
}
if (!t(queryOperation).isObject) {
throw new Error(`Expected query resolver for "${opName}" to be an object.`);
}
return queryOperation;
}
//
// Resolves a root entity.
//
async function resolveRootEntity(queryOperation: IQueryOperation, output: any, entityTypeName: string, queryGlobals: IQueryGlobals, nestingLevel: number) {
verbose(queryGlobals.context.verbose, nestingLevel, `= Resolving root entity "${entityTypeName}".`);
const entityQuery = queryOperation[entityTypeName];
if (!entityQuery) {
throw new Error(`Entity query "${entityTypeName}" is missing under operation "${queryGlobals.opName}".`);
}
if (!t(entityQuery).isObject) {
throw new Error(`Expected entity query "${entityTypeName}" under operation "${queryGlobals.opName}" to be an object.`);
}
const entityResolverName = entityQuery.from !== undefined ? entityQuery.from : entityTypeName;
const entityResolver = getGlobalEntityResolver(queryGlobals, entityResolverName, entityTypeName, "query result", nestingLevel+1);
//
// Resolve this entity.
//
const resolvedEntity = await entityResolver.invoke(entityQuery.args || {}, queryGlobals.context); //TODO: Do these in parallel.
const entityWasResolved = !(resolvedEntity === null || resolvedEntity === undefined);
if (entityWasResolved) {
if (t(resolvedEntity).isArray) {
verbose(queryGlobals.context.verbose, nestingLevel+1, `Resolved an array of entities.`);
}
else {
verbose(queryGlobals.context.verbose, nestingLevel+1, `Resolved a single entity.`);
}
}
else {
verbose(queryGlobals.context.verbose, nestingLevel+1, `No entity was resovled.`);
}
const clonedEntity =
entityWasResolved
? t(resolvedEntity).isArray // Clone entity so it can be modified.
? resolvedEntity.map((singleEntity: any) => Object.assign({}, singleEntity))
: Object.assign({}, resolvedEntity)
: resolvedEntity;
//
// Plug the resolved entity into the query result.
//
output[entityTypeName] = clonedEntity;
if (entityWasResolved) {
//
// Resolve nested entities.
//
await resolveNestedEntities(entityQuery, clonedEntity, entityResolverName, entityTypeName, queryGlobals, nestingLevel+2);
}
}
//
// Gets the resolver for a particular entity type.
//
function getGlobalEntityResolver(queryGlobals: IQueryGlobals, entityResolverName: string, entityTypeName: string, outputLocation: string, nestingLevel: number): IEntityQueryResolver {
verbose(queryGlobals.context.verbose, nestingLevel, `Getting global entity resolver "${entityResolverName}" to resolve entity type "${entityTypeName}".`);
const entityResolver = queryGlobals.operationResolver[entityResolverName];
if (!entityResolver) {
throw new Error(createErrorForMissingGlobalResolver(queryGlobals.opName, entityResolverName, entityTypeName, outputLocation));
}
if (!entityResolver.invoke) {
throw new Error(createErrorForMissingInvoke(queryGlobals.opName, entityResolverName, entityTypeName, outputLocation));
}
if (!t(entityResolver.invoke).isFunction) {
throw new Error(createErrorForInvokeNotAFn(queryGlobals.opName, entityResolverName, entityTypeName, outputLocation));
}
return entityResolver;
}
//
// Resolve nested entities for an entity.
//
async function resolveNestedEntities(entityQuery: IEntityQuery, parentEntity: any, parentEntityGlobalResolverName: string, parentEntityTypeName: string, queryGlobals: IQueryGlobals, nestingLevel: number) {
if (entityQuery.resolve) {
//
// Resolve nested entities.
//
for (const nestedEntityTypeName of Object.keys(entityQuery.resolve)) {
const nestedEntityQuery = entityQuery.resolve[nestedEntityTypeName];
if (!t(nestedEntityQuery).isObject) {
throw new Error(`Unsupported type for "resolve" field: ${typeof (nestedEntityQuery)}.`);
}
if (t(parentEntity).isArray) {
await Promise.all(parentEntity.map((singleEntity: any) => {
return resolveNestedEntity(nestedEntityQuery, singleEntity, parentEntityGlobalResolverName, parentEntityTypeName, nestedEntityTypeName, queryGlobals, nestingLevel);
}));
}
else {
await resolveNestedEntity(nestedEntityQuery, parentEntity, parentEntityGlobalResolverName, parentEntityTypeName, nestedEntityTypeName, queryGlobals, nestingLevel);
}
}
}
}
//
// Resolves a nested entity.
//
async function resolveNestedEntity(nestedEntityQuery: IEntityQuery, parentEntity: any, parentEntityGlobalResolverName: string, parentEntityTypeName: string, nestedEntityTypeName: string, queryGlobals: IQueryGlobals, nestingLevel: number): Promise<void> {
verbose(queryGlobals.context.verbose, nestingLevel, `= Resolving nested entity "${nestedEntityTypeName}".`);
//
// Get the global resolver for the parent entity.
//
const parentEntityResolver = getGlobalEntityResolver(queryGlobals, parentEntityGlobalResolverName, parentEntityTypeName, `parent entity "${parentEntityTypeName}"`, nestingLevel + 1);
const nestedEntityLocalResolverName = nestedEntityQuery.from !== undefined ? nestedEntityQuery.from : nestedEntityTypeName;
if (!parentEntityResolver.nested) {
throw new Error(`Failed to find nested resolvers for operation "${queryGlobals.opName}" for nested entity "${nestedEntityLocalResolverName}" under "${parentEntityGlobalResolverName}".`); //TODO: flesh out this error msg.
}
const nestedEntityResolver = parentEntityResolver.nested[nestedEntityLocalResolverName];
if (nestedEntityResolver === undefined) {
throw new Error(`Failed to find nested resolver for operation "${queryGlobals.opName}" for nested entity "${nestedEntityLocalResolverName}" under "${parentEntityGlobalResolverName}".`); //TODO: flesh out this error msg.
}
//
// Resolve this entity.
//
const resolvedEntity = await nestedEntityResolver.invoke(parentEntity, nestedEntityQuery.args || {}, queryGlobals.context); //TODO: Do these in parallel.
const entityWasResolved = !(resolvedEntity === null || resolvedEntity === undefined);
if (entityWasResolved) {
if (t(resolvedEntity).isArray) {
verbose(queryGlobals.context.verbose, nestingLevel+1, `Resolved an array of nested entities.`);
}
else {
verbose(queryGlobals.context.verbose, nestingLevel+1, `Resolved a single nested entity.`);
}
}
else {
verbose(queryGlobals.context.verbose, nestingLevel+1, `No nested entity was resovled.`);
}
const clonedEntity =
entityWasResolved
? t(resolvedEntity).isArray // Clone entity so it can be modified.
? resolvedEntity.map((singleEntity: any) => Object.assign({}, singleEntity))
: Object.assign({}, resolvedEntity)
: resolvedEntity;
//
// Plug the resolved entity into the query result.
//
parentEntity[nestedEntityTypeName] = clonedEntity;
if (entityWasResolved) {
//
// Find the global name of the local entity resolver.
//
const nestedEntityGlobalResolverName = nestedEntityResolver.from || nestedEntityLocalResolverName;
//
// Resolve nested entities.
//
await resolveNestedEntities(nestedEntityQuery, clonedEntity, nestedEntityGlobalResolverName, nestedEntityTypeName, queryGlobals, nestingLevel+2);
}
}
//
// Creates an error message for a missing query operation.
//
function createErrorForMissingQueryOperation(opName: string): string {
return `
Query operation "${opName}" is not supported by the resolver.
You must define a query resolver that looks like this:
const root = {
${opName}: {
// ... Entity query resolvers go here.
},
// ... Other query operations go here.
};
`;
}
//
// Creates an error message for a missing global resolver.
//
function createErrorForMissingGlobalResolver(opName: string, entityResolverName: string, entityTypeName: string, outputLocation: string): string {
return `
Failed to find global resolver for entity "${entityResolverName}" of operation "${opName}", outputting to "${entityTypeName}" in ${outputLocation}.\n
You must define a query resolver that looks like this:\n` +
createResolverExample(opName, entityResolverName);
}
//
// Creates an error message for a missing invoke function.
//
function createErrorForMissingInvoke(opName: string, entityResolverName: string, entityTypeName: string, outputLocation: string): string {
return `
Failed to find invoke function for entity "${entityResolverName}" of operation "${opName}", outputting to "${entityTypeName}" in ${outputLocation}.\n
You must define a query resolver that looks like this:\n` +
createResolverExample(opName, entityResolverName);
}
//
// Creates an error message for when the supplied "invoke" function is not a function.
//
function createErrorForInvokeNotAFn(opName: string, entityResolverName: string, entityTypeName: string, outputLocation: string): string {
return `
Expected "invoke" function for entity resolver "${entityTypeName}" is to be a function.
You must define a query resolver that looks like this:\n` +
createResolverExample(opName, entityResolverName);
}
//
// Create an example query resolver.
//
function createResolverExample(opName: string, entityResolverName: string) {
return `
const root = {
${opName}: {
${entityResolverName}: {
invoke: async function (args, context) => {
if (args.something) {
// ... Return or update a single entity that matches 'something'.
}
else {
// ... Return the set of entities (you probably want to use pagination).
// ... Or insert an entity.
}
},
},
// ... Other resolvers go here.
},
// ... Other query operations go here.
};
`;
} | the_stack |
import quip from "quip-apps-api";
import quiptext from "quiptext";
import {
COLUMN_TYPE as TABLE_VIEW_COLUMN_TYPE,
COLUMN_TYPE_LABELS,
ColumnRecord,
DateRecord,
FileRecord,
PersonRecord,
RowRecord,
StatusRecord,
StatusTypeRecord,
TextRecord,
UserRecord,
} from "../../../shared/table-view/model.js";
import debounce from "lodash.debounce";
const colors = quip.apps.ui.ColorMap;
export const COLUMN_TYPE = (({PERSON, STATUS, DATE, FILE, TEXT}) => ({
PERSON,
STATUS,
DATE,
FILE,
TEXT,
}))(TABLE_VIEW_COLUMN_TYPE);
const COLUMN_NAME = {
PROJECT: "project",
};
const DEFAULT_ROW = {
[COLUMN_NAME.PROJECT]: {
contents: {RichText_placeholderText: quiptext("New Project")},
},
};
export class RootRecord extends quip.apps.RootRecord {
static CONSTRUCTOR_KEY = "Root";
static DATA_VERSION = 2;
static getProperties = () => ({
columns: quip.apps.RecordList.Type(ColumnRecord),
rows: quip.apps.RecordList.Type(RowRecord),
widths: "object",
});
static getDefaultProperties = () => ({
columns: [],
rows: [],
widths: {},
});
constructor(...args) {
super(...args);
const _notifyListeners = this.notifyListeners;
this.notifyListeners = debounce(() => _notifyListeners.call(this), 50);
}
private domNode: Node = undefined;
initialize() {
this.updateChangeListeners_();
}
changeListeners_: quip.apps.Record[] = [];
updateChangeListeners_ = () => {
this.changeListeners_.forEach(listener => {
listener.unlisten(this.setStatePayload_);
});
this.changeListeners_ = [];
this.getRows().forEach(row => {
row.listen(this.setStatePayload_);
this.changeListeners_.push(row);
});
this.getColumns().forEach(column => {
column.listen(this.setStatePayload_);
this.changeListeners_.push(column);
});
};
setStatePayload_ = debounce(() => {
// @ts-ignore TODO remove ignore with quip-apps-private
if (typeof quip.apps.setPayload === "function") {
// @ts-ignore
quip.apps.setPayload(this.getExportState());
}
}, 2000);
seed() {
const seedColumns = [
{
name: COLUMN_NAME.PROJECT,
type: COLUMN_TYPE.TEXT,
contents: {
RichText_defaultText: quiptext("Project"),
RichText_placeholderText:
COLUMN_TYPE_LABELS[COLUMN_TYPE.TEXT],
},
draggable: false,
deletable: false,
},
{
type: COLUMN_TYPE.PERSON,
contents: {
RichText_defaultText: quiptext("Owner"),
RichText_placeholderText:
COLUMN_TYPE_LABELS[COLUMN_TYPE.PERSON],
},
},
{
type: COLUMN_TYPE.STATUS,
contents: {
RichText_defaultText: quiptext("Status"),
RichText_placeholderText:
COLUMN_TYPE_LABELS[COLUMN_TYPE.STATUS],
},
},
{
type: COLUMN_TYPE.DATE,
contents: {
RichText_defaultText: quiptext("Deadline"),
RichText_placeholderText:
COLUMN_TYPE_LABELS[COLUMN_TYPE.DATE],
},
},
{
type: COLUMN_TYPE.FILE,
contents: {
RichText_defaultText: quiptext("Attachment"),
RichText_placeholderText:
COLUMN_TYPE_LABELS[COLUMN_TYPE.FILE],
},
},
];
seedColumns.forEach(column => this.addColumn(column));
[...Array(3)].forEach(() => this.addRow());
this.setDataVersion(RootRecord.DATA_VERSION);
}
// We found a case where a Project Tracker had null value where one
// of it's cells should have been which was causing it to fail to
// initialize. This function scans the RootRecord looking for cases
// where cells or missing and replaces them.
checkAndRepairNullCells() {
this.getColumns().map((col, ci) => {
col.getCells().map((cell, ri) => {
if (!cell) {
this.getRows()[ri].addCell(
col,
Object.assign({columnId: col.getId()}));
}
});
});
}
getColumns() {
return this.get("columns").getRecords();
}
getColumnById(id) {
return this.getColumns().find(s => s.getId() === id);
}
getRows() {
return this.get("rows").getRecords();
}
addColumn(
data,
index?,
shouldNotSeed = false,
content = null,
isFirstColumn = false
) {
if (typeof data === "string") {
data = {
type: COLUMN_TYPE[data],
contents: {
RichText_defaultText: content,
RichText_placeholderText:
COLUMN_TYPE_LABELS[COLUMN_TYPE[data]],
},
draggable: !isFirstColumn,
deletable: !isFirstColumn,
};
}
const column = this.get("columns").add(data, index);
if (!shouldNotSeed) {
column.seed();
this.getRows().forEach(row => row.addCell(column));
}
this.updateChangeListeners_();
return column;
}
addRow(data = DEFAULT_ROW) {
const row = this.get("rows").add({});
this.getColumns().forEach(column => {
const columnName = column.get("name");
const cellData = data[columnName] || {};
row.addCell(column, cellData);
});
this.updateChangeListeners_();
return row;
}
setDom(node) {
if (!node) return;
this.domNode = node;
}
getDom() {
return this.domNode;
}
getExportState(): String {
const columns2IdMap = this.getColumns().reduce(
(obj, column, index) => ({
...obj,
[column.getId()]: index.toString(),
}),
{});
const statusId2DevName = new Map();
const statusDevName2Count = new Map();
/**
* Returns the status results given a column.
* eg. {
* label: "Needs work",
* devName: "needs_work_2",
* color: "BLUE",
* }
* @param status - status Record
*/
const getStatusJSON_ = (status: StatusTypeRecord) => {
const label = status.getText();
let devName = label.toLowerCase().replace(" ", "_");
if (statusDevName2Count.has(devName)) {
// If a duplicate exists, increment counter and append a number
// to the end of the devName
// eg. "label", "label_1", "label_2", "label_3"
const newCount = statusDevName2Count.get(devName) + 1;
statusDevName2Count.set(devName, newCount);
devName = devName + "_" + newCount.toString();
} else {
statusDevName2Count.set(devName, 0);
}
// Store devName to id mapping to help export rows information
statusId2DevName.set(status.getId(), devName);
return {
label,
devName,
color: status.getColor().KEY,
};
};
const columns = this.getColumns().map((column, index) => {
const columnMap: {
content: any;
type: string;
id: any;
options?: any;
} = {
content: column.getContents().getTextContent(),
// We pass the key as the type.
type: Object.keys(COLUMN_TYPE).find(
key => COLUMN_TYPE[key] === column.getType()),
id: index.toString(),
};
// Add the "options" value if the column type is "status"
if (column.getType() === COLUMN_TYPE.STATUS) {
columnMap.options = column
.get("statusTypes")
.getRecords()
.map(getStatusJSON_);
}
return columnMap;
});
const rows = this.getRows().map(row =>
row.getJSON(columns2IdMap, statusId2DevName)
);
return JSON.stringify({
columns,
rows,
});
}
populateFromState(state) {
const id2ColumnRecord = new Map();
const devName2StatusId = new Map();
if (state.columns && state.rows) {
state.columns.forEach(column => {
const columnRecord = this.addColumn(
column.type,
null,
true,
column.content,
column === state.columns[0]);
id2ColumnRecord.set(column.id, columnRecord);
// note: column.type stores the key rather than the value of columnType
if (column.type === "STATUS" &&
column.options &&
column.options.length) {
column.options.forEach(option => {
const statusId = columnRecord.addStatusType(
option.label,
colors[option.color]);
devName2StatusId.set(option.devName, statusId.getId());
});
}
});
state.rows.forEach(row => {
const rowRecord = this.get("rows").add({});
const columnsFilled = new Set();
for (const [key, value] of Object.entries(row)) {
if (!id2ColumnRecord.has(key)) {
console.error("Cannot find column with id: " + key);
continue;
}
const columnRecord = id2ColumnRecord.get(key);
columnsFilled.add(columnRecord);
let cellRecord;
switch (columnRecord.getType()) {
case COLUMN_TYPE.TEXT:
cellRecord = rowRecord.addCell(columnRecord, {
contents: {
RichText_defaultText: value,
RichText_placeholderText:
COLUMN_TYPE_LABELS[COLUMN_TYPE.TEXT],
},
});
break;
case COLUMN_TYPE.PERSON:
cellRecord = rowRecord.addCell(columnRecord);
if (Array.isArray(value)) {
new Set(value).forEach(personId => {
cellRecord.addUserById(personId);
});
} else {
console.error("Failed to parse " + value);
}
break;
case COLUMN_TYPE.DATE:
cellRecord = rowRecord.addCell(columnRecord);
cellRecord.setDate(Number(value));
break;
case COLUMN_TYPE.STATUS:
cellRecord = rowRecord.addCell(columnRecord);
if (devName2StatusId.has(value)) {
cellRecord.setStatus(
devName2StatusId.get(value));
}
break;
case COLUMN_TYPE.FILE:
// TODO: Support file blob importing
cellRecord = rowRecord.addCell(columnRecord);
break;
}
}
if (columnsFilled.size < id2ColumnRecord.size) {
// If not all columns were populated, populate the rest
// with empty values.
id2ColumnRecord.forEach(value => {
if (!columnsFilled.has(value)) {
rowRecord.addCell(value);
}
});
}
});
this.updateChangeListeners_();
}
}
}
export default () => {
[
RootRecord,
StatusTypeRecord,
ColumnRecord,
RowRecord,
TextRecord,
PersonRecord,
StatusRecord,
DateRecord,
FileRecord,
UserRecord,
].forEach(c => quip.apps.registerClass(c, c.CONSTRUCTOR_KEY));
}; | the_stack |
import * as childProcess from "child_process"
import * as events from "events"
import * as fs from "fs"
import * as os from "os"
import * as path from "path"
import * as readline from "readline"
const tssPath = path.join(
__dirname,
"..",
"..",
"..",
"..",
"node_modules",
"typescript",
"lib",
"tsserver.js",
)
export class TypeScriptServerHost extends events.EventEmitter {
private _tssProcess = null
private _seqNumber = 0
private _seqToPromises = {}
private _rl: any
private _initPromise: Promise<void>
private _openedFiles: string[] = []
public get pid(): number {
return this._tssProcess.pid
}
constructor(Oni: any) {
super()
// Other tries for creating process:
// this._tssProcess = childProcess.spawn("node", [tssPath], { stdio: "pipe", detached: true, shell: false });
// this._tssProcess = childProcess.fork(tssPath, [], { stdio: "pipe "})
//
// On Windows, an 'npm' window would show up, so it seems like in this context,
// exec was the most reliable
// Note max buffer value - once this exceeded, the process will crash
// TODO: Reload process, or looking at using the --eventPort option instead
// This has some info on using eventPort: https://github.com/Microsoft/TypeScript/blob/master/src/server/server.ts
// which might be more reliable
// Can create the port using this here: https://github.com/Microsoft/TypeScript/blob/master/src/server/server.ts
this._initPromise = this._startTypescriptServer(Oni)
}
public async _startTypescriptServer(Oni): Promise<void> {
this._tssProcess = await Oni.process.spawnNodeScript(tssPath)
console.log("Process ID: " + this._tssProcess.pid) // tslint:disable-line no-console
this._rl = readline.createInterface({
input: this._tssProcess.stdout,
output: this._tssProcess.stdin,
terminal: false,
})
this._tssProcess.stderr.on("data", (data, err) => {
console.warn("Error from tss: " + data) // tslint:disable-line no-console
})
this._tssProcess.on("error", data => {
debugger // tslint:disable-line no-debugger
})
this._tssProcess.on("exit", data => {
debugger // tslint:disable-line no-debugger
})
this._tssProcess.on("close", data => {
debugger // tslint:disable-line no-debugger
})
this._rl.on("line", msg => {
if (msg.indexOf("{") === 0) {
this._parseResponse(msg)
}
})
}
public async openFile(file: string, text?: string): Promise<any> {
if (this._openedFiles.indexOf(file) >= 0) {
return
}
this._openedFiles.push(file)
return this._makeTssRequest("open", {
file,
fileContent: text,
})
}
public getProjectInfo(file: string): Promise<any> {
return this._makeTssRequest("projectInfo", {
file,
needFileNameList: true,
})
}
public getDefinition(file: string, line: number, offset: number): Promise<void> {
return this._makeTssRequest<void>("definition", {
file,
line,
offset,
})
}
public getTypeDefinition(file: string, line: number, offset: number): Promise<void> {
return this._makeTssRequest<void>("typeDefinition", {
file,
line,
offset,
})
}
public getFormattingEdits(
file: string,
line: number,
offset: number,
endLine: number,
endOffset: number,
): Promise<protocol.CodeEdit[]> {
return this._makeTssRequest<protocol.CodeEdit[]>("format", {
file,
line,
offset,
endLine,
endOffset,
})
}
public getCompletions(
file: string,
line: number,
offset: number,
prefix: string,
): Promise<any> {
return this._makeTssRequest<void>("completions", {
file,
line,
offset,
prefix,
})
}
public getCompletionDetails(
file: string,
line: number,
offset: number,
entryNames: string[],
): Promise<any> {
return this._makeTssRequest<void>("completionEntryDetails", {
file,
line,
offset,
entryNames,
})
}
public getRefactors(
file: string,
startLine: number,
startOffset: number,
endLine: number,
endOffset: number,
): Promise<protocol.ApplicableRefactorInfo[]> {
return this._makeTssRequest<protocol.ApplicableRefactorInfo[]>("getApplicableRefactors", {
file,
startLine,
startOffset,
endLine,
endOffset,
})
}
public getEditsForRefactor(
refactor: string,
action: string,
file: string,
startLine: number,
startOffset: number,
endLine: number,
endOffset: number,
): Promise<protocol.RefactorEditInfo> {
return this._makeTssRequest<protocol.RefactorEditInfo>("getEditsForRefactor", {
refactor,
action,
file,
startLine,
startOffset,
endLine,
endOffset,
})
}
public updateFile(file: string, fileContent: string): Promise<void> {
const totalLines = fileContent.split(os.EOL)
return this._makeTssRequest<void>("change", {
file,
line: 1,
offset: 1,
endLine: totalLines.length + 1,
endOffset: 1,
insertString: fileContent,
})
}
public changeLineInFile(file: string, line: number, newLineContents: string): Promise<void> {
return this._makeTssRequest<void>("change", {
file,
line,
offset: 1,
endOffset: 1,
endLine: line + 1,
insertString: newLineContents + os.EOL,
})
}
public getQuickInfo(file: string, line: number, offset: number): Promise<any> {
return this._makeTssRequest<void>("quickinfo", {
file,
line,
offset,
})
}
public saveTo(file: string, tmpfile: string): Promise<void> {
return this._makeTssRequest<void>("saveto", {
file,
tmpfile,
})
}
public getSignatureHelp(file: string, line: number, offset: number): Promise<any> {
return this._makeTssRequest<void>("signatureHelp", {
file,
line,
offset,
})
}
public getErrors(fullFilePath: string): Promise<void> {
return this._makeTssRequest<void>("geterr", {
files: [fullFilePath],
delay: 500,
})
}
public getErrorsAcrossProject(fullFilePath: string): Promise<void> {
return this._makeTssRequest<void>("geterrForProject", {
file: fullFilePath,
})
}
public getNavigationTree(fullFilePath: string): Promise<protocol.NavigationTree> {
return this._makeTssRequest<protocol.NavigationTree>("navtree", {
file: fullFilePath,
})
}
public getDocumentHighlights(file: string, line: number, offset: number): Promise<void> {
return this._makeTssRequest<void>("documentHighlights", {
file,
line,
offset,
})
}
public findAllReferences(
file: string,
line: number,
offset: number,
): Promise<protocol.ReferencesResponseBody> {
return this._makeTssRequest<protocol.ReferencesResponseBody>("references", {
file,
line,
offset,
})
}
public navTo(file: string, query: string): Promise<protocol.NavtoItem[]> {
return this._makeTssRequest<protocol.NavtoItem[]>("navto", {
file,
searchValue: query,
})
}
public rename(
file: string,
line: number,
offset: number,
): Promise<protocol.RenameResponseBody> {
return this._makeTssRequest<protocol.RenameResponseBody>("rename", {
file,
line,
offset,
findInComments: false,
findInStrings: false,
})
}
public async _makeTssRequest<T>(commandName: string, args: any): Promise<T> {
await this._initPromise
const seq = this._seqNumber++
const payload = {
seq,
type: "request",
command: commandName,
arguments: args,
}
const ret = this._createDeferredPromise<T>()
this._seqToPromises[seq] = ret
// TODO: Handle updates in parallel?
this._tssProcess.stdin.write(JSON.stringify(payload) + os.EOL)
return ret.promise
}
private _parseResponse(returnedData: string): void {
const response = JSON.parse(returnedData)
const seq = response["request_seq"] // tslint:disable-line no-string-literal
const success = response["success"] // tslint:disable-line no-string-literal
if (typeof seq === "number") {
if (success) {
this._seqToPromises[seq].resolve(response.body)
} else {
this._seqToPromises[seq].reject(new Error(response.message))
}
this._seqToPromises[seq] = null
} else {
// If a sequence wasn't specified, it might be a call that returns multiple results
// Like 'geterr' - returns both semanticDiag and syntaxDiag
if (response.type && response.type === "event") {
if (response.event && response.event === "semanticDiag") {
this.emit("semanticDiag", response.body)
}
}
}
}
private _createDeferredPromise<T>(): any {
let resolve
let reject
const promise = new Promise((res, rej) => {
resolve = res
reject = rej
})
return {
resolve,
reject,
promise,
}
}
} | the_stack |
import * as vscode from "vscode";
import type { PerEditorState } from "./editors";
import type { Extension } from "./extension";
import type { Mode } from "./modes";
import type { StatusBar } from "./status-bar";
import { Context, Positions, Selections } from "../api";
import { CommandDescriptor } from "../commands";
import { assert, CancellationError } from "../utils/errors";
import { noUndoStops } from "../utils/misc";
type RecordValue = CommandDescriptor | object | vscode.Uri | number | string;
const enum Constants {
NextMask = 0xff,
PrevShift = 8,
}
type IntArray<E extends Entry.Base<any>> = E extends Entry.Base<infer I>
? { readonly [K in keyof I]: I[K] extends undefined ? never : number; }
& { readonly length: number; }
: never;
/**
* A class used to record actions as they happen.
*/
export class Recorder implements vscode.Disposable {
private readonly _descriptors: readonly CommandDescriptor[];
private readonly _onDidAddEntry = new vscode.EventEmitter<Entry>();
private readonly _previousBuffers: Recorder.Buffer[] = [];
private readonly _storedObjects: (object | string)[] = [];
private readonly _storedObjectsMap = new Map<object | string, number>();
private readonly _statusBar: StatusBar;
private readonly _subscriptions: vscode.Disposable[] = [];
private _activeDocument: vscode.TextDocument | undefined;
private _buffer: Recorder.MutableBuffer = [0];
private _lastActiveSelections: readonly vscode.Selection[] | undefined;
private _activeRecordingTokens: vscode.Disposable[] = [];
private _expectedSelectionTranslation?: number;
public get onDidAddEntry() {
return this._onDidAddEntry.event;
}
/**
* {@link Entry} is re-exported here since it defines important values, and
* cannot be imported directly from API functions.
*/
public get Entry() {
return Entry;
}
public constructor(
extension: Extension,
) {
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor !== undefined) {
this._activeDocument = activeEditor.document;
this._lastActiveSelections = activeEditor.selections;
}
this._subscriptions.push(
vscode.window.onDidChangeActiveTextEditor(this._recordActiveTextEditorChange, this),
vscode.window.onDidChangeTextEditorSelection(this._recordExternalSelectionChange, this),
vscode.workspace.onDidChangeTextDocument(this._recordExternalTextChange, this),
extension.editors.onModeDidChange(this._recordActiveTextEditorModeChange, this),
);
this._statusBar = extension.statusBar;
this._descriptors = Object.values(extension.commands);
}
public dispose() {
this._activeRecordingTokens.splice(0).forEach((d) => d.dispose());
this._subscriptions.splice(0).forEach((d) => d.dispose());
}
/**
* Returns the last 100 entries of the recorder, for debugging purposes.
*/
private get debugBuffer() {
return this.lastEntries(100);
}
/**
* Returns the last `n` entries.
*/
public lastEntries(n: number) {
const entries: Entry[] = [],
cursor = this.cursorFromEnd();
for (let i = 0; i < n && cursor.previous(); i++) {
entries.push(cursor.entry());
}
return entries.reverse();
}
/**
* Returns the last entry.
*/
public lastEntry() {
const cursor = this.cursorFromEnd();
if (!cursor.previous()) {
return undefined;
}
return cursor.entry();
}
/**
* Records an action to the current buffer.
*/
private _record<E extends Entry.Base<any>>(
type: (new (...args: any) => E) & { readonly id: number },
...args: IntArray<E>
) {
this._buffer[this._buffer.length - 1] |= type.id;
this._buffer.push(...(args as unknown as number[]), type.id << Constants.PrevShift);
this._archiveBufferIfNeeded();
this._onDidAddEntry.fire(this.lastEntry()!);
}
/**
* Archives the current buffer to `_previousBuffers` if its size exceeded a
* threshold and if no recording is currently ongoing.
*/
private _archiveBufferIfNeeded() {
if (this._activeRecordingTokens.length > 0 || this._buffer.length < 8192) {
return;
}
this._previousBuffers.push(this._buffer);
this._buffer = [];
}
private _storeObject<T extends object | string>(value: T) {
let i = this._storedObjectsMap.get(value);
if (i === undefined) {
this._storedObjectsMap.set(value, i = this._storedObjects.push(value) - 1);
}
return i;
}
/**
* Returns the number of available buffers.
*/
public get bufferCount() {
return this._previousBuffers.length + 1;
}
/**
* Returns the buffer at the given index, if any.
*/
public getBuffer(index: number) {
return index === this._previousBuffers.length ? this._buffer : this._previousBuffers[index];
}
/**
* Returns the stored object at the given index.
*/
public getObject<T extends object>(index: number) {
return this._storedObjects[index] as T;
}
/**
* Returns the stored string at the given index.
*/
public getString(index: number) {
return this._storedObjects[index] as string;
}
/**
* Returns the command descriptor at the given index.
*/
public getDescriptor(index: number) {
return this._descriptors[index];
}
/**
* Returns the entry at the given index.
*/
public entry(buffer: Recorder.Buffer, index: number) {
const entryId = (buffer[index] & Constants.NextMask) as Entry.Identifier;
return Entry.instantiate(entryId, this, buffer, index);
}
/**
* Returns a `Cursor` starting at the start of the recorder.
*/
public cursorFromStart() {
return new Recorder.Cursor(this, 0, 0);
}
/**
* Returns a `Cursor` starting at the end of the recorder at the time of the
* call.
*/
public cursorFromEnd() {
return new Recorder.Cursor(this, this._previousBuffers.length, this._buffer.length - 1);
}
/**
* Returns a `Cursor` starting at the start of the specified recording.
*/
public fromRecordingStart(recording: Recording) {
let bufferIdx = this._previousBuffers.indexOf(recording.buffer);
if (bufferIdx === -1) {
assert(recording.buffer === this._buffer);
bufferIdx = this._previousBuffers.length;
}
return new Recorder.Cursor(this, bufferIdx, recording.offset);
}
/**
* Returns a `Cursor` starting at the end of the specified recording.
*/
public fromRecordingEnd(recording: Recording) {
let bufferIdx = this._previousBuffers.indexOf(recording.buffer);
if (bufferIdx === -1) {
assert(recording.buffer === this._buffer);
bufferIdx = this._previousBuffers.length;
}
return new Recorder.Cursor(this, bufferIdx, recording.offset + recording.length);
}
/**
* Starts recording a series of actions.
*/
public startRecording() {
const onRecordingCompleted = () => {
const index = this._activeRecordingTokens.indexOf(cancellationTokenSource);
if (index === -1) {
throw new Error("recording has already been marked as completed");
}
this._activeRecordingTokens.splice(index, 1);
cancellationTokenSource.dispose();
const activeRecordingsCount = this._activeRecordingTokens.length;
if (activeRecordingsCount === 0) {
this._statusBar.recordingSegment.setContent();
vscode.commands.executeCommand("setContext", "dance.isRecording", false);
} else {
this._statusBar.recordingSegment.setContent("" + activeRecordingsCount);
}
const buffer = this._buffer;
this._archiveBufferIfNeeded();
return new Recording(buffer, offset, buffer.length - offset - 1);
};
this._recordBreak();
const offset = this._buffer.length - 1,
cancellationTokenSource = new vscode.CancellationTokenSource(),
recording = new ActiveRecording(onRecordingCompleted, cancellationTokenSource.token),
activeRecordingsCount = this._activeRecordingTokens.push(cancellationTokenSource);
this._statusBar.recordingSegment.setContent("" + activeRecordingsCount);
if (activeRecordingsCount === 1) {
vscode.commands.executeCommand("setContext", "dance.isRecording", true);
}
return recording;
}
/**
* Records a "break", indicating that a change that cannot be reliably
* replayed just happened.
*/
private _recordBreak() {
const buffer = this._buffer;
if (buffer.length > 0 && buffer[buffer.length - 1] !== Entry.Break.id) {
this._record(Entry.Break);
this._activeRecordingTokens.splice(0).forEach((t) => t.dispose());
}
this._expectedSelectionTranslation = undefined;
}
/**
* Records a change in the active text editor.
*/
private _recordActiveTextEditorChange(e: vscode.TextEditor | undefined) {
this._expectedSelectionTranslation = undefined;
if (e?.document !== this._activeDocument) {
if (e?.document === undefined) {
this._activeDocument = undefined;
this._lastActiveSelections = undefined;
this._recordBreak();
} else {
this._activeDocument = e.document;
this._lastActiveSelections = e.selections;
this._record(Entry.ChangeTextEditor, this._storeObject(e.document.uri));
}
}
}
/**
* Records a change in the mode of the active text editor.
*/
private _recordActiveTextEditorModeChange(e: PerEditorState) {
if (e.editor.document !== this._activeDocument) {
return;
}
this._record(Entry.ChangeTextEditorMode, this._storeObject(e.mode));
}
/**
* Records the invocation of a command.
*/
public recordCommand(descriptor: CommandDescriptor, argument: Record<string, any>) {
const descriptorIndex = this._descriptors.indexOf(descriptor),
argumentIndex = this._storeObject(argument);
this._record(Entry.ExecuteCommand, descriptorIndex, argumentIndex);
}
/**
* Records the invocation of an external (non-Dance) command.
*/
public recordExternalCommand(identifier: string, argument: Record<string, any>) {
const identifierIndex = this._storeObject(identifier),
argumentIndex = this._storeObject(argument);
this._record(Entry.ExecuteExternalCommand, identifierIndex, argumentIndex);
}
/**
* Records a change of a selection.
*/
private _recordExternalSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
if (vscode.window.activeTextEditor !== e.textEditor) {
return;
}
const lastSelections = this._lastActiveSelections,
selections = e.selections;
this._lastActiveSelections = selections;
if (Context.WithoutActiveEditor.currentOrUndefined !== undefined
|| lastSelections === undefined) {
// Selection change is internal.
return;
}
if (lastSelections.length !== selections.length
|| e.kind === vscode.TextEditorSelectionChangeKind.Mouse) {
// Selection change is not supported.
return this._recordBreak();
}
// Determine translations.
const document = e.textEditor.document;
let commonAnchorOffsetDiff = Number.MAX_SAFE_INTEGER,
commonActiveOffsetDiff = Number.MAX_SAFE_INTEGER;
for (let i = 0, len = selections.length; i < len; i++) {
const lastSelection = lastSelections[i],
selection = selections[i];
let anchorOffsetDiff: number;
if (lastSelection.anchor.line === selection.anchor.line) {
anchorOffsetDiff = selection.anchor.character - lastSelection.anchor.character;
} else {
const lastAnchorOffset = document.offsetAt(lastSelection.anchor),
anchorOffset = document.offsetAt(selection.anchor);
anchorOffsetDiff = anchorOffset - lastAnchorOffset;
}
if (commonAnchorOffsetDiff === Number.MAX_SAFE_INTEGER) {
commonAnchorOffsetDiff = anchorOffsetDiff;
} else if (commonAnchorOffsetDiff !== anchorOffsetDiff) {
return this._recordBreak();
}
let activeOffsetDiff: number;
if (lastSelection.active.line === selection.active.line) {
activeOffsetDiff = selection.active.character - lastSelection.active.character;
} else {
const lastActiveOffset = document.offsetAt(lastSelection.active),
activeOffset = document.offsetAt(selection.active);
activeOffsetDiff = activeOffset - lastActiveOffset;
}
if (commonActiveOffsetDiff === Number.MAX_SAFE_INTEGER) {
commonActiveOffsetDiff = activeOffsetDiff;
} else if (commonActiveOffsetDiff !== activeOffsetDiff) {
return this._recordBreak();
}
}
if (commonActiveOffsetDiff === 0 && commonAnchorOffsetDiff === 0) {
// Do not record translations by 0.
return;
}
const expectedTranslation = this._expectedSelectionTranslation;
if (expectedTranslation !== undefined) {
this._expectedSelectionTranslation = undefined;
if (expectedTranslation === commonActiveOffsetDiff
&& expectedTranslation === commonAnchorOffsetDiff) {
return;
}
}
const isSameDiff = commonActiveOffsetDiff === commonAnchorOffsetDiff;
// Merge consecutive events if possible.
if (isSameDiff) {
const cursor = this.cursorFromEnd();
if (cursor.previousIs(Entry.DeleteAfter)) {
const deletionLength = cursor.entry().deletionLength();
if (deletionLength === commonActiveOffsetDiff) {
// DeleteAfter -> Translate = DeleteBefore.
const buffer = cursor.buffer as Recorder.MutableBuffer,
cursorOffset = cursor.offset;
if (cursor.previousIs(Entry.DeleteBefore)) {
// DeleteBefore -> DeleteBefore = DeleteBefore.
buffer.splice(cursorOffset + 1);
buffer[cursor.offset + 1] += deletionLength;
buffer[cursor.offset + Entry.DeleteBefore.size + 1] =
(Entry.DeleteBefore.id << Constants.PrevShift);
} else {
buffer[cursorOffset] =
(buffer[cursorOffset] & ~Constants.NextMask) | Entry.DeleteBefore.id;
buffer[cursorOffset + Entry.DeleteBefore.size + 1] =
(Entry.DeleteBefore.id << Constants.PrevShift);
}
return;
}
} else if (cursor.previousIs(Entry.DeleteBefore)) {
// DeleteBefore -> Translate = DeleteBefore.
if (cursor.entry().deletionLength() === commonActiveOffsetDiff) {
// Already handled in DeleteBefore.
return;
}
} else if (cursor.previousIs(Entry.InsertAfter)) {
const insertedText = cursor.entry().insertedText();
if (insertedText.length === commonActiveOffsetDiff) {
// InsertAfter -> Translate = InsertBefore.
const buffer = cursor.buffer as Recorder.MutableBuffer,
cursorOffset = cursor.offset;
if (cursor.previousIs(Entry.InsertBefore)) {
// InsertBefore -> InsertBefore = InsertBefore.
buffer.splice(cursorOffset + 1);
buffer[cursor.offset + 1] =
this._storeObject(cursor.entry().insertedText() + insertedText);
buffer[cursor.offset + Entry.InsertBefore.size + 1] =
(Entry.InsertBefore.id << Constants.PrevShift);
} else {
buffer[cursorOffset] =
(buffer[cursorOffset] & ~Constants.NextMask) | Entry.InsertBefore.id;
buffer[cursorOffset + Entry.DeleteBefore.size + 1] =
(Entry.InsertBefore.id << Constants.PrevShift);
}
return;
}
}
} else if (commonActiveOffsetDiff === 0 || commonAnchorOffsetDiff === 0) {
const cursor = this.cursorFromEnd();
let type: typeof Entry.DeleteAfter | typeof Entry.DeleteBefore,
translation: number;
if (commonActiveOffsetDiff === 0) {
type = Entry.DeleteAfter;
translation = commonAnchorOffsetDiff;
} else {
type = Entry.DeleteBefore;
translation = commonActiveOffsetDiff;
}
if (cursor.previousIs(type)) {
if (cursor.entry().deletionLength() === translation) {
// Delete{After,Before} -> Translate = Delete{After,Before}.
return;
}
}
}
// Could not merge with previous events; just add an entry.
this._record(Entry.TranslateSelection, commonActiveOffsetDiff, commonAnchorOffsetDiff);
}
/**
* Records a text change.
*/
private _recordExternalTextChange(e: vscode.TextDocumentChangeEvent) {
const editor = vscode.window.activeTextEditor;
if (editor?.document !== e.document) {
return;
}
const lastSelections = this._lastActiveSelections,
selections = editor.selections;
this._lastActiveSelections = selections;
if (Context.WithoutActiveEditor.currentOrUndefined !== undefined
|| lastSelections === undefined || e.contentChanges.length === 0) {
// Text change is internal.
return;
}
if (lastSelections.length !== e.contentChanges.length) {
// Text change is not supported.
return this._recordBreak();
}
this._expectedSelectionTranslation = undefined;
function computeOffsetFromActive(
change: vscode.TextDocumentContentChangeEvent,
selection: vscode.Selection,
) {
const changeStart = change.range.start,
active = selection.active;
if (changeStart.line === active.line) {
return changeStart.character - active.character;
}
return change.rangeOffset - document.offsetAt(active);
}
const document = e.document,
firstChange = e.contentChanges[0],
firstSelection = lastSelections[0],
commonInsertedText = firstChange.text,
commonDeletionLength = firstChange.rangeLength,
commonOffsetFromActive = computeOffsetFromActive(firstChange, firstSelection);
for (let i = 1, len = lastSelections.length; i < len; i++) {
const change = e.contentChanges[i];
if (change.text !== commonInsertedText || change.rangeLength !== commonDeletionLength) {
return this._recordBreak();
}
const offsetFromActive = computeOffsetFromActive(change, selections[i]);
if (offsetFromActive !== commonOffsetFromActive) {
return this._recordBreak();
}
}
// Merge consecutive events, if possible.
if (commonDeletionLength > 0 && commonInsertedText.length > 0) {
if (commonInsertedText.length - commonDeletionLength === commonOffsetFromActive) {
this._record(Entry.ReplaceWith, this._storeObject(commonInsertedText));
return;
}
}
if (commonDeletionLength > 0) {
const cursor = this.cursorFromEnd(),
type = commonOffsetFromActive === 0 ? Entry.DeleteAfter : Entry.DeleteBefore;
if (type === Entry.DeleteBefore) {
this._expectedSelectionTranslation = commonOffsetFromActive;
}
if (cursor.previousIs(type)) {
// Delete -> Delete = Delete.
(cursor.buffer as Recorder.MutableBuffer)[cursor.offset + 1] += commonDeletionLength;
} else if (type === Entry.DeleteBefore && cursor.previousIs(Entry.InsertBefore)) {
const insertedText = cursor.entry().insertedText();
if (insertedText.length > commonDeletionLength) {
// InsertBefore -> DeleteBefore = InsertBefore.
(cursor.buffer as Recorder.MutableBuffer)[cursor.offset + 1] =
this._storeObject(insertedText.slice(0, insertedText.length - commonDeletionLength));
} else {
const previousType = cursor.previousType();
(cursor.buffer as Recorder.MutableBuffer).splice(cursor.offset);
if (insertedText.length === commonDeletionLength) {
// InsertBefore -> DeleteBefore = Nop.
(cursor.buffer as Recorder.MutableBuffer).push(previousType << Constants.PrevShift);
} else {
// InsertBefore -> DeleteBefore = DeleteBefore.
(cursor.buffer as Recorder.MutableBuffer).push(
(previousType << Constants.PrevShift) | Entry.DeleteBefore.id,
commonDeletionLength,
Entry.DeleteBefore.id << Constants.PrevShift,
);
}
}
} else {
this._record(type, commonDeletionLength);
}
}
if (commonInsertedText.length > 0) {
const cursor = this.cursorFromEnd();
if (cursor.previousIs(Entry.InsertAfter)) {
// Insert -> Insert = Insert.
const previousInsertedText = cursor.entry().insertedText();
if (previousInsertedText.length === commonOffsetFromActive) {
(cursor.buffer as Recorder.MutableBuffer)[cursor.offset + 1] =
this._storeObject(previousInsertedText + commonInsertedText);
} else {
this._record(Entry.InsertAfter, this._storeObject(commonInsertedText));
}
} else {
// TODO: handle offset from active
this._record(Entry.InsertAfter, this._storeObject(commonInsertedText));
}
}
}
}
export namespace Recorder {
/**
* A buffer of `Recorder` values.
*/
export type Buffer = { readonly [index: number]: number; } & { readonly length: number; };
/**
* The mutable version of `Buffer`.
*/
export type MutableBuffer = number[];
/**
* A cursor used to enumerate records in a `Recorder` or `Recording`.
*/
export class Cursor<T extends Entry.Any = Entry.Any> {
private _buffer: Buffer;
private _bufferIdx: number;
private _offset: number;
public constructor(
/**
* The recorder from which records are read.
*/
public readonly recorder: Recorder,
buffer: number,
offset: number,
) {
this._buffer = recorder.getBuffer(buffer);
this._bufferIdx = buffer;
this._offset = offset;
}
/**
* Returns the buffer storing the current record.
*/
public get buffer() {
return this._buffer;
}
/**
* Returns the offset of the current record in its buffer.
*/
public get offset() {
return this._offset;
}
/**
* Returns the offset of the previous record in its buffer, or `undefined`
* if the current record is the first of its buffer.
*/
public get previousOffset() {
return this._offset === 0
? undefined
: this._offset - Entry.size(this.previousType()) - 1;
}
/**
* Returns a different instance of a `Cursor` that points to the same
* record.
*/
public clone() {
return new Cursor<T>(this.recorder, this._bufferIdx, this._offset);
}
/**
* Returns whether the current cursor is before or equal to the given
* cursor.
*/
public isBeforeOrEqual(other: Cursor) {
return this._bufferIdx < other._bufferIdx
|| (this._bufferIdx === other._bufferIdx && this._offset <= other._offset);
}
/**
* Returns whether the current cursor is after or equal to the given
* cursor.
*/
public isAfterOrEqual(other: Cursor) {
return this._bufferIdx > other._bufferIdx
|| (this._bufferIdx === other._bufferIdx && this._offset >= other._offset);
}
/**
* Replays the record pointed at by the cursor.
*/
public replay(context: Context.WithoutActiveEditor) {
return this.entry().replay(context);
}
/**
* Returns the entry pointed at by the cursor.
*/
public entry() {
return Entry.instantiate(this.type(), this.recorder, this._buffer, this._offset) as T;
}
/**
* Returns the type of the current record.
*/
public type() {
return ((this._buffer[this._offset] as number) & Constants.NextMask) as Entry.Identifier;
}
/**
* Returns the type of the previous record.
*/
public previousType() {
return (this._buffer[this._offset] as number >> Constants.PrevShift) as Entry.Identifier;
}
/**
* Returns whether the cursor points to a record of the given type.
*/
public is<T extends Entry.AnyClass>(type: T): this is Cursor<InstanceType<T>> {
return this.type() === type.id;
}
/**
* Returns whether, when going backward, the type will be correspond to the
* given type. If so, goes backward.
*/
public previousIs<T extends Entry.AnyClass>(type: T): this is Cursor<InstanceType<T>> {
if (this.previousType() === type.id) {
this.previous();
return true;
}
return false;
}
/**
* Switches to the next record, and returns `true` if the operation
* succeeded or `false` if the current record is the last one available.
*/
public next(): this is Cursor<Entry.Any> {
if (this._offset === this._buffer.length - 1) {
if (this._bufferIdx === this.recorder.bufferCount) {
return false;
}
this._bufferIdx++;
this._buffer = this.recorder.getBuffer(this._bufferIdx);
this._offset = 0;
return true;
}
this._offset += Entry.size(this.type()) + 1;
return true;
}
/**
* Switches to the previous record, and returns `true` if the operation
* succeeded or `false` if the current record is the first one available.
*/
public previous(): this is Cursor<Entry.Any> {
assert(this._offset >= 0);
if (this._offset === 0) {
if (this._bufferIdx === 0) {
return false;
}
this._bufferIdx--;
this._buffer = this.recorder.getBuffer(this._bufferIdx);
this._offset = this._buffer.length - 1;
return true;
}
this._offset -= Entry.size(this.previousType()) + 1;
return true;
}
/**
* Returns whether the record pointed at by the cursor is included in the
* specified recording.
*/
public isInRecording(recording: Recording) {
return recording.offset <= this._offset && this._offset < recording.offset + recording.length
&& recording.buffer === this._buffer;
}
/**
* Returns `this` with a more generic type. Use when TypeScript merges types
* incorrectly.
*/
public upcast(): Cursor<Entry.Any> {
return this;
}
}
}
/**
* An ongoing `Recording`.
*/
export class ActiveRecording {
public constructor(
private readonly _notifyCompleted: () => Recording,
/**
* A cancellation token that will be cancelled if the recording is forcibly
* stopped due to an unknown change.
*/
public readonly cancellationToken: vscode.CancellationToken,
) {}
public complete() {
CancellationError.throwIfCancellationRequested(this.cancellationToken);
return this._notifyCompleted();
}
}
/**
* A recording of actions performed in VS Code.
*/
export class Recording {
public readonly buffer: Recorder.Buffer;
public readonly offset: number;
public readonly length: number;
public constructor(buffer: Recorder.Buffer, offset: number, length: number) {
this.buffer = buffer;
this.offset = offset;
this.length = length;
}
/**
* Returns the result of calling `entries()`, for debugging purposes.
*/
private get debugEntries() {
return [...this.entries()];
}
/**
* Returns an iterator over all the entries in the recorder.
*/
public *entries(context = Context.WithoutActiveEditor.current) {
let offset = this.offset;
const buffer = this.buffer,
end = offset + this.length,
recorder = context.extension.recorder;
while (offset < end) {
const entry = recorder.entry(buffer, offset);
yield entry;
offset += entry.size + 1;
}
}
/**
* Replays the recording in the given context.
*/
public async replay(context = Context.WithoutActiveEditor.current) {
for (const entry of this.entries(context)) {
await entry.replay(context);
}
}
}
/**
* Represents an entry in the `Recorder`.
*/
export type Entry = Entry.Any;
export namespace Entry {
export type Identifier = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
export type AnyClass = typeof entries extends readonly (infer A)[] ? A : never;
export type Any = InstanceType<AnyClass>;
export abstract class Base<Items extends readonly [...RecordValue[]]> {
public constructor(
/**
* The recorder to which this entry belongs.
*/
public readonly recorder: Recorder,
/**
* The buffer in which the entry is recorded.
*/
public readonly buffer: Recorder.Buffer,
/**
* The offset in the buffer at which the entry is recorded.
*/
public readonly offset: number,
) {}
/**
* Returns the identifier of the record.
*/
public get id() {
return this.type.id;
}
/**
* Returns the size of the record, excluding identifier before and after.
*/
public get size() {
return this.type.size;
}
/**
* Returns the type of the entry.
*/
public get type() {
return this.constructor as Entry.AnyClass;
}
/**
* Returns the result of calling `items()`, for debugging purposes.
*/
private get debugItems() {
return this.items();
}
/**
* Replays the recorded entry.
*/
public abstract replay(context: Context.WithoutActiveEditor): Thenable<void>;
/**
* Returns the items that make up the entry.
*/
public abstract items(): Items;
/**
* Returns the item at the given index.
*/
protected item<I extends keyof Items & number>(index: I) {
return this.buffer[this.offset + 1 + index];
}
private static _entryIds = 0;
/**
* Returns an abstract class that should be extended to implement a new
* `Entry`.
*/
public static define<Items extends readonly [...RecordValue[]]>(size: Items["length"]) {
const id = this._entryIds++;
abstract class EntryWithSize extends Base<Readonly<Items>> {
public static readonly size = size;
public static readonly id = id;
}
// We need to wrap `EntryWithSize` into an actual, textually-representable
// type below in order to generate a valid declaration for `define` in a
// `.d.ts` file.
return EntryWithSize as unknown as {
readonly size: number;
readonly id: number;
new(
...args: typeof Base extends abstract new(...args: infer Args) => any ? Args : never
): Base<Readonly<Items>>;
};
}
}
/**
* An action that cannot be reliably replayed and that interrupts a
* recording.
*/
export class Break extends Base.define<[]>(0) {
public replay() {
return Promise.resolve();
}
public items() {
return [] as const;
}
}
/**
* A selection translation.
*/
export class TranslateSelection extends Base.define<
[activeTranslation: number, anchorTranslation: number]
>(2) {
public replay(context: Context.WithoutActiveEditor) {
Context.assert(context);
const document = context.document,
activeTranslation = this.activeTranslation(),
anchorTranslation = this.anchorTranslation();
context.run(() => Selections.update.byIndex((_, selection) => {
const newActive = Positions.offset.orEdge(selection.active, activeTranslation, document),
newAnchor = Positions.offset.orEdge(selection.anchor, anchorTranslation, document);
return new vscode.Selection(newAnchor, newActive);
}));
return Promise.resolve();
}
public activeTranslation() {
return this.item(0);
}
public anchorTranslation() {
return this.item(1);
}
public items() {
return [this.activeTranslation(), this.anchorTranslation()] as const;
}
}
/**
* An insertion before each selection (cursor moves forward).
*/
export class InsertBefore extends Base.define<[insertedText: string]>(1) {
public replay(context: Context.WithoutActiveEditor) {
Context.assert(context);
const editor = context.editor as vscode.TextEditor;
return editor.edit((editBuilder) => {
const insertedText = this.insertedText();
for (const selection of editor.selections) {
editBuilder.insert(selection.start, insertedText);
}
}, noUndoStops).then(() => {});
}
public insertedText() {
return this.recorder.getString(this.item(0));
}
public items() {
return [this.insertedText()] as const;
}
}
/**
* An insertion after each selection (cursor does not move).
*/
export class InsertAfter extends Base.define<[insertedText: string]>(1) {
public replay(context: Context.WithoutActiveEditor) {
Context.assert(context);
const editor = context.editor as vscode.TextEditor;
return editor.edit((editBuilder) => {
const insertedText = this.insertedText();
for (const selection of editor.selections) {
editBuilder.replace(selection.end, insertedText);
}
}, noUndoStops).then(() => {});
}
public insertedText() {
return this.recorder.getString(this.item(0));
}
public items() {
return [this.insertedText()] as const;
}
}
/**
* A deletion before each selection (cursor moves backward).
*/
export class DeleteBefore extends Base.define<[deletionLength: number]>(1) {
public replay(context: Context.WithoutActiveEditor) {
Context.assert(context);
const editor = context.editor as vscode.TextEditor;
return editor.edit((editBuilder) => {
const deletionLength = this.deletionLength(),
document = editor.document;
for (const selection of editor.selections) {
const endPosition = selection.start,
startPosition = Positions.offset.orEdge(endPosition, -deletionLength, document);
editBuilder.delete(new vscode.Range(startPosition, endPosition));
}
}).then(() => {});
}
public deletionLength() {
return this.item(0);
}
public items() {
return [this.deletionLength()] as const;
}
}
/**
* A deletion after each selection (cursor does not move).
*/
export class DeleteAfter extends Base.define<[deletionLength: number]>(1) {
public replay(context: Context.WithoutActiveEditor) {
Context.assert(context);
const editor = context.editor as vscode.TextEditor;
return editor.edit((editBuilder) => {
const deletionLength = this.deletionLength(),
document = editor.document;
for (const selection of editor.selections) {
const startPosition = selection.end,
endPosition = Positions.offset.orEdge(startPosition, deletionLength, document);
editBuilder.delete(new vscode.Range(startPosition, endPosition));
}
}).then(() => {});
}
public deletionLength() {
return this.item(0);
}
public items() {
return [this.deletionLength()] as const;
}
}
/**
* A text replacement.
*/
export class ReplaceWith extends Base.define<[text: string]>(1) {
public replay(context: Context.WithoutActiveEditor) {
Context.assert(context);
const editor = context.editor as vscode.TextEditor;
return editor.edit((editBuilder) => {
const text = this.text();
for (const selection of editor.selections) {
editBuilder.replace(selection, text);
}
}).then(() => {});
}
public text() {
return this.recorder.getString(this.item(0));
}
public items() {
return [this.text()] as const;
}
}
/**
* An active text editor change.
*/
export class ChangeTextEditor extends Base.define<[uri: vscode.Uri]>(1) {
public replay() {
return vscode.window.showTextDocument(this.uri()).then(() => {});
}
public uri() {
return this.recorder.getObject<vscode.Uri>(this.item(0));
}
public items() {
return [this.uri()] as const;
}
}
/**
* A change of the active text editor mode.
*/
export class ChangeTextEditorMode extends Base.define<[mode: Mode]>(1) {
public replay(context: Context.WithoutActiveEditor) {
Context.assert(context);
return context.switchToMode(this.mode());
}
public mode() {
return this.recorder.getObject<Mode>(this.item(0));
}
public items() {
return [this.mode()] as const;
}
}
/**
* An internal command invocation.
*/
export class ExecuteCommand extends Base.define<
[descriptor: CommandDescriptor, argument: object]
>(2) {
public async replay(context: Context.WithoutActiveEditor) {
const descriptor = this.descriptor(),
argument = this.argument();
if ((descriptor.flags & CommandDescriptor.Flags.DoNotReplay) === 0) {
await descriptor.replay(context, argument);
}
}
public descriptor() {
return this.recorder.getDescriptor(this.item(0));
}
public argument() {
return this.recorder.getObject<{}>(this.item(1));
}
public items() {
return [this.descriptor(), this.argument()] as const;
}
}
/**
* An external command invocation.
*/
export class ExecuteExternalCommand extends Base.define<
[identifier: string, argument: object]
>(2) {
public replay() {
return vscode.commands.executeCommand(this.identifier(), this.argument()).then(() => {});
}
public identifier() {
return this.recorder.getString(this.item(0));
}
public argument() {
return this.recorder.getObject<{}>(this.item(1));
}
public items() {
return [this.identifier(), this.argument()] as const;
}
}
const entries = [
Break,
ChangeTextEditor,
ChangeTextEditorMode,
DeleteAfter,
DeleteBefore,
ExecuteCommand,
ExecuteExternalCommand,
InsertAfter,
InsertBefore,
ReplaceWith,
TranslateSelection,
] as const;
const sortedEntries = entries.slice().sort((a, b) => a.id - b.id);
/**
* Returns the class of the entry corresponding to the given entry identifier.
*/
export function byId(id: Identifier) {
return sortedEntries[id];
}
/**
* Returns the entry corresponding to the given entry identifier.
*/
export function instantiate(id: Identifier, ...args: ConstructorParameters<AnyClass>) {
return new sortedEntries[id](...args);
}
/**
* Returns the size of the object at the given index.
*/
export function size(id: Identifier) {
return byId(id).size;
}
} | the_stack |
import * as assert from 'assert';
import * as diff from 'diff';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as text from '../src/util/AnnotatedText';
import * as proto from '../src/coqtop/coq-proto';
import * as db from '../src/coqtop/xml-protocol/deserialize.base';
import * as d from '../src/coqtop/xml-protocol/deserialize.8.5';
import * as p from '../src/coqtop/xml-protocol/coq-xml';
import * as stream from 'stream';
// Defines a Mocha test suite to group tests of similar kind together
suite("Deserialize 8.5", () => {
let data : stream.PassThrough;
let deserializer : db.Deserialize;
let parser : p.XmlStream;
beforeEach("init", function() {
data = new stream.PassThrough();
deserializer = new d.Deserialize_8_5();
parser = new p.XmlStream(data,deserializer);
})
function parse(xml: string|string[]) : Promise<proto.ReturnValue[]> {
return new Promise<proto.ReturnValue[]>((resolve, reject) => {
const results : proto.ReturnValue[] = [];
parser.on('response', (tag, v) => results.push(v));
parser.on('error', reject);
parser.on('end', () => resolve(results));
if(xml instanceof Array)
xml.forEach((x)=> data.emit('data', x))
else
data.emit('data', xml);
data.emit('end', '')
})
}
test("state_id", async function () {
const results = await parse('<state_id val="5" />');
assert.deepStrictEqual(results, [5]);
});
test("edit_id", async function () {
const results = await parse('<edit_id val="6" />');
assert.deepStrictEqual(results, [6]);
});
test("int", async function () {
const results = await parse('<int>3</int>');
assert.deepStrictEqual(results, [3]);
});
test("string", async function () {
const results = await parse('<string>hi</string>');
assert.deepStrictEqual(results, ["hi"]);
});
test("string - nbsp gt", async function () {
const results = await parse('<string>hi there! >:</string>');
assert.deepStrictEqual(results, ["hi\u00a0there! >:"]);
});
test("string: pretty long", async function () {
const results = await parse('<string>' + ".".repeat(100000) + '</string>');
assert.deepStrictEqual(results, [".".repeat(100000)]);
});
test("unit", async function () {
const results = await parse('<unit/>');
assert.deepStrictEqual(results, [{}]);
});
test("pair", async function () {
const results = await parse('<pair><int>4</int><string>hi</string></pair>');
assert.deepStrictEqual(results, [[4, 'hi']]);
});
test("list", async function () {
const results = await parse('<list><int>4</int><string>hi</string><int>1</int></list>');
assert.deepStrictEqual(results, [[4, 'hi', 1]]);
});
test("bool", async function () {
const results = await parse([
'<bool val="true"></bool>',
'<bool val="false"></bool>',
'<bool val="True"></bool>',
'<bool val="False"></bool>',
'<bool val="TruE"></bool>',
'<bool val="FalsE"></bool>',
]);
assert.deepStrictEqual(results, [true,false,true,false,true,false]);
});
test("union", async function () {
const results = await parse([
'<union val="in_l"><int>5</int></union>',
'<union val="in_r"><string>hi</string></union>',
]);
assert.deepStrictEqual(results, [{tag: "inl", value: 5},{tag: "inr", value: "hi"}]);
});
test("option", async function () {
const results = await parse([
'<option val="some"><int>5</int></option>',
'<option val="none"/>',
]);
assert.deepStrictEqual(results, [5,null]);
});
test("option_value", async function () {
const results = await parse([
'<option_value val="intvalue"><option val="some"><int>5</int></option></option_value>',
'<option_value val="intvalue"><option val="none"/></option_value>',
'<option_value val="stringoptvalue"><option val="some"><string>hi</string></option></option_value>',
'<option_value val="stringoptvalue"><option val="none"/></option_value>',
'<option_value val="boolvalue"><bool val="true"/></option_value>',
'<option_value val="boolvalue"><bool val="false"/></option_value>',
'<option_value val="stringvalue"><string>hi</string></option_value>',
]);
assert.deepStrictEqual(results, [5,null,"hi",null,true,false,"hi"]);
});
test("option_state", async function () {
const results = await parse([
'<option_state><bool val="true"/><bool val="false"/><string>hi</string><int>5</int></option_state>',
'<option_state><bool val="true"/><bool val="false"/><string>hi</string><string>5</string></option_state>',
'<option_state><bool val="true"/><bool val="false"/><string>hi</string><bool val="true"/></option_state>',
]);
assert.deepStrictEqual(results, [
{synchronized: true, deprecated: false, name: "hi", value: 5},
{synchronized: true, deprecated: false, name: "hi", value: "5"},
{synchronized: true, deprecated: false, name: "hi", value: true},
]);
});
test("loc", async function () {
const results = await parse('<loc start="2" stop="10"/>');
assert.deepStrictEqual(results, [{start: 2, stop: 10}]);
});
test("richpp", async function () {
const results = await parse('<option val="some"><richpp><_><aa>t</aa>h<bb>er</bb>e</_></richpp></option>');
assert.notEqual(results, null);
const r = results.map((r) => text.normalizeText(r as text.AnnotatedText));
assert.deepStrictEqual(r, [{scope:"_",text:[{scope: "aa", text:"t"},"h",{scope: "bb", text:"er"},"e"]}]);
});
test("message_level", async function () {
const results = await parse([
'<message_level val="warning"/>',
'<message_level val="info"/>',
'<message_level val="notice"/>',
'<message_level val="error"/>',
'<message_level val="debug"/>',
]);
assert.deepStrictEqual(results, [
proto.MessageLevel.Warning, proto.MessageLevel.Info, proto.MessageLevel.Notice,
proto.MessageLevel.Error, proto.MessageLevel.Debug]);
});
test("message", async function () {
const results = await parse([
'<message><message_level val="warning"/><string>hi</string></message>',
]);
assert.deepStrictEqual(results, [
{level: proto.MessageLevel.Warning, message: "hi"}]);
});
test("feedback - errormsg", async function () {
const results = await parse('<feedback_content val="errormsg"><loc start="1" stop="3"/><string>hi</string></feedback_content>');
assert.deepStrictEqual(results, [
{feedbackKind: "message", level: proto.MessageLevel.Error, location: {start: 1, stop: 3}, message: "hi"}]);
});
test("feedback - (sentence-status)", async function () {
const results = await parse([
'<feedback_content val="processed"></feedback_content>',
'<feedback_content val="incomplete"></feedback_content>',
'<feedback_content val="complete"></feedback_content>',
'<feedback_content val="processingin"><string>worker</string></feedback_content>',
]);
assert.deepStrictEqual(results[0],{feedbackKind: "sentence-status", status: proto.SentenceStatus.Processed, worker: "", inProgressDelta: 0});
assert.deepStrictEqual(results[1],{feedbackKind: "sentence-status", status: proto.SentenceStatus.Incomplete, worker: "", inProgressDelta: 0});
assert.deepStrictEqual(results[2],{feedbackKind: "sentence-status", status: proto.SentenceStatus.Complete, worker: "", inProgressDelta: 0});
assert.deepStrictEqual(results[3],{feedbackKind: "sentence-status", status: proto.SentenceStatus.ProcessingInWorker, worker: "worker", inProgressDelta: 0});
});
suite("LtacProf", () => {
function ltacprof_tactic(name,total,self,num_calls,max_total,children: string[]) {
return `<ltacprof_tactic name="${name.toString()}" total="${total.toString()}" self="${self.toString()}" num_calls="${num_calls.toString()}" max_total="${max_total.toString()}">${children.join('')}</ltacprof_tactic>`;
}
test("ltacprof_tactic", async function () {
const results = await parse([
ltacprof_tactic('abc',0,0,0,0,[]),
ltacprof_tactic('foo',4.4,3.3,2,1.1,[]),
ltacprof_tactic('aaa',4.4,3.3,2,1.1,[ltacprof_tactic('bbb',0,0,0,0,[]), ltacprof_tactic('ccc',0,0,0,0,[])]),
]);
assert.deepStrictEqual(results[0],{name: "abc", statistics: {total: 0, local: 0, num_calls: 0, max_total: 0}, tactics: []});
assert.deepStrictEqual(results[1],{name: "foo", statistics: {total: 4.4, local: 3.3, num_calls: 2, max_total: 1.1}, tactics: []});
assert.deepStrictEqual(results[2],{
name: "aaa",
statistics: {total: 4.4, local: 3.3, num_calls: 2, max_total: 1.1},
tactics: [
{name: "bbb", statistics: {total: 0, local: 0, num_calls: 0, max_total: 0}, tactics: []},
{name: "ccc", statistics: {total: 0, local: 0, num_calls: 0, max_total: 0}, tactics: []},
]
});
});
test("ltacprof", async function () {
const results = await parse(`<ltacprof total_time="10.1">${ltacprof_tactic('abc',0,0,0,0,[])}${ltacprof_tactic('foo',1,2,3,4,[])}</ltacprof>`);
assert.deepStrictEqual(results,[{
total_time: 10.1,
tactics: [
{name: "abc", statistics: {total: 0, local: 0, num_calls: 0, max_total: 0}, tactics: []},
{name: "foo", statistics: {total: 1, local: 2, num_calls: 3, max_total: 4}, tactics: []},
]}]);
});
test("feedback_content - ltacprof", async function () {
const results = await parse(`<feedback_content val="custom"><option val="none"/><string>ltacprof_results</string><ltacprof total_time="10.1">${ltacprof_tactic('abc',0,0,0,0,[])}${ltacprof_tactic('foo',1,2,3,4,[])}</ltacprof></feedback_content>`);
assert.deepStrictEqual(results,[{
feedbackKind: 'ltacprof',
total_time: 10.1,
tactics: [
{name: "abc", statistics: {total: 0, local: 0, num_calls: 0, max_total: 0}, tactics: []},
{name: "foo", statistics: {total: 1, local: 2, num_calls: 3, max_total: 4}, tactics: []},
]}]);
});
});
test("feedback", async function () {
const results = await parse([
'<feedback object="state" route="1"><state_id val="5"/><feedback_content val="errormsg"><loc start="1" stop="3"/><string>hi</string></feedback_content></feedback>',
'<feedback object="edit"><edit_id val="4"/><feedback_content val="errormsg"><loc start="1" stop="3"/><string>hi</string></feedback_content></feedback>',
]);
assert.deepStrictEqual(results[0], {
objectId: {objectKind: "stateid", stateId: 5},
route: 1,
feedbackKind: "message",
level: proto.MessageLevel.Error,
location: {start: 1, stop: 3}, message: "hi"
});
assert.deepStrictEqual(results[1], {
objectId: {objectKind: "editid", editId: 4},
route: 0,
feedbackKind: "message",
level: proto.MessageLevel.Error,
location: {start: 1, stop: 3}, message: "hi"
});
});
test("goal", async function () {
const results = await parse([
'<goal><int>5</int><list/><string>True</string></goal>',
'<goal><int>5</int><list><string>hi</string></list><string>True</string></goal>',
'<goal><int>5</int><list><string>hi</string><richpp><_><aa>t</aa>h<bb>er</bb>e</_></richpp></list><string>True</string></goal>',
]);
results.forEach((g:proto.Subgoal) => {
g.hypotheses = g.hypotheses.map((h)=>text.normalizeText(h));
g.goal = text.normalizeText(g.goal)
})
assert.deepStrictEqual(results, [
{id: 5, hypotheses: [], goal: "True"},
{id: 5, hypotheses: ["hi"], goal: "True"},
{id: 5, hypotheses: ["hi", {scope:"_",text:[{scope: "aa", text:"t"},"h",{scope: "bb", text:"er"},"e"]}], goal: "True"},
]);
});
test("goals", async function () {
const results = await parse([
'<goals><list/><list/><list/><list/></goals>',
'<goals><list><goal><int>5</int><list/><string>True</string></goal></list><list/><list><goal><int>5</int><list/><string>True</string></goal></list><list><goal><int>5</int><list/><string>True</string></goal></list></goals>',
'<goals><list/><list><pair><list/><list/></pair></list><list/><list/></goals>',
'<goals><list/><list><pair><list><goal><int>1</int><list/><string>True</string></goal></list><list><goal><int>2</int><list/><string>True</string></goal></list></pair></list><list/><list/></goals>',
'<goals><list/><list><pair><list><goal><int>1</int><list/><string>True</string></goal><goal><int>2</int><list/><string>True</string></goal></list><list><goal><int>3</int><list/><string>True</string></goal><goal><int>4</int><list/><string>True</string></goal></list></pair></list><list/><list/></goals>',
'<goals><list/><list><pair><list><goal><int>1</int><list/><string>True</string></goal></list><list><goal><int>2</int><list/><string>True</string></goal></list></pair><pair><list><goal><int>3</int><list/><string>True</string></goal></list><list><goal><int>4</int><list/><string>True</string></goal></list></pair></list><list/><list/></goals>',
]);
assert.deepStrictEqual(results[0], {goals: [], backgroundGoals: null, shelvedGoals: [], abandonedGoals: []});
assert.deepStrictEqual(results[1], {goals: [{id: 5, hypotheses: [], goal: "True"}], backgroundGoals: null, shelvedGoals: [{id: 5, hypotheses: [], goal: "True"}], abandonedGoals: [{id: 5, hypotheses: [], goal: "True"}]});
assert.deepStrictEqual(results[2], {
goals: [],
backgroundGoals: {before: [], next: null, after: []},
shelvedGoals: [],
abandonedGoals: []});
assert.deepStrictEqual(results[3], {
goals: [],
backgroundGoals: {
before: [{id: 1, hypotheses: [], goal: "True"}],
next: null,
after: [{id: 2, hypotheses: [], goal: "True"}]},
shelvedGoals: [],
abandonedGoals: []});
assert.deepStrictEqual(results[4], {
goals: [],
backgroundGoals: {
before: [{id: 1, hypotheses: [], goal: "True"}, {id: 2, hypotheses: [], goal: "True"}],
next: null,
after: [{id: 3, hypotheses: [], goal: "True"}, {id: 4, hypotheses: [], goal: "True"}]},
shelvedGoals: [],
abandonedGoals: []});
assert.deepStrictEqual(results[5], {
goals: [],
backgroundGoals: {
before: [{id: 3, hypotheses: [], goal: "True"}],
next: {
before: [{id: 1, hypotheses: [], goal: "True"}],
next: null,
after: [{id: 2, hypotheses: [], goal: "True"}]},
after: [{id: 4, hypotheses: [], goal: "True"}]},
shelvedGoals: [],
abandonedGoals: []});
});
}); | the_stack |
import * as React from 'react';
import { mount } from 'enzyme';
import { PluginHost } from '@devexpress/dx-react-core';
import {
pluginDepsToComponents,
getComputedState,
executeComputedAction,
testStatePluginField,
setupConsole,
} from '@devexpress/dx-testing';
import {
changeColumnGrouping,
toggleExpandedGroups,
draftColumnGrouping,
cancelColumnGroupingDraft,
getColumnExtensionValueGetter,
adjustSortIndex,
} from '@devexpress/dx-grid-core';
import { GroupingState } from './grouping-state';
jest.mock('@devexpress/dx-grid-core', () => ({
changeColumnGrouping: jest.fn(),
toggleExpandedGroups: jest.fn(),
draftColumnGrouping: jest.fn(),
cancelColumnGroupingDraft: jest.fn(),
getColumnExtensionValueGetter: jest.fn(),
adjustSortIndex: jest.fn(),
}));
const defaultDeps = {
getter: {
rows: [{ id: 1 }],
getRowId: row => row.id,
},
};
describe('GroupingState', () => {
let resetConsole;
beforeAll(() => {
resetConsole = setupConsole();
});
afterAll(() => {
resetConsole();
});
beforeEach(() => {
changeColumnGrouping.mockImplementation(() => {});
toggleExpandedGroups.mockImplementation(() => {});
draftColumnGrouping.mockImplementation(() => {});
cancelColumnGroupingDraft.mockImplementation(() => {});
getColumnExtensionValueGetter.mockImplementation(() => () => {});
adjustSortIndex.mockImplementation(() => 0);
});
afterEach(() => {
jest.resetAllMocks();
});
testStatePluginField({
defaultDeps,
Plugin: GroupingState,
propertyName: 'grouping',
values: [
[{ columnName: 'a' }],
[{ columnName: 'b' }],
[{ columnName: 'c' }],
],
actions: [{
actionName: 'changeColumnGrouping',
reducer: changeColumnGrouping,
fieldReducer: false,
}],
});
testStatePluginField({
defaultDeps,
Plugin: GroupingState,
propertyName: 'expandedGroups',
values: [
['A'],
['B'],
['C'],
],
actions: [{
actionName: 'toggleGroupExpanded',
reducer: toggleExpandedGroups,
fieldReducer: false,
}, {
actionName: 'changeColumnGrouping',
reducer: changeColumnGrouping,
fieldReducer: false,
}],
});
describe('draftGrouping', () => {
it('should provide draftGrouping getter', () => {
const defaultGrouping = [{ columnName: 'a' }];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GroupingState
defaultGrouping={defaultGrouping}
/>
</PluginHost>
));
expect(getComputedState(tree).draftGrouping)
.toBe(defaultGrouping);
});
// tslint:disable-next-line: max-line-length
it('should provide draftGrouping getter based on the result of draftColumnGrouping action', () => {
const defaultGrouping = [{ columnName: 'a' }];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GroupingState
defaultGrouping={defaultGrouping}
/>
</PluginHost>
));
const payload = { columnName: 'a' };
draftColumnGrouping.mockImplementation(() => ({ draftGrouping: [{ columnName: 'b' }] }));
executeComputedAction(tree, actions => actions.draftColumnGrouping(payload));
expect(draftColumnGrouping)
.toBeCalledWith(
expect.objectContaining({ grouping: defaultGrouping, draftGrouping: null }),
payload,
);
expect(getComputedState(tree).draftGrouping)
.toEqual([{ columnName: 'b' }]);
});
// tslint:disable-next-line: max-line-length
it('should provide draftGrouping getter based on the result of cancelColumnGroupingDraft result', () => {
const defaultGrouping = [{ columnName: 'a' }];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GroupingState
defaultGrouping={defaultGrouping}
/>
</PluginHost>
));
const payload = { columnName: 'a' };
cancelColumnGroupingDraft.mockImplementation(() => ({ groupingChange: 'change' }));
executeComputedAction(tree, actions => actions.cancelColumnGroupingDraft(payload));
expect(cancelColumnGroupingDraft)
.toBeCalledWith(
expect.objectContaining({ grouping: defaultGrouping, draftGrouping: null }),
payload,
);
});
});
describe('changeColumnSorting action extending', () => {
it('should modify changeColumnSorting action payload when sorted column is grouped', () => {
const deps = {
getter: {
sorting: [],
},
action: {
changeColumnSorting: jest.fn(),
},
};
const defaultGrouping = [{ columnName: 'a' }];
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps, deps)}
<GroupingState
defaultGrouping={defaultGrouping}
/>
</PluginHost>
));
executeComputedAction(tree, actions => actions
.changeColumnSorting({ columnName: 'a', direction: 'asc' }),
);
expect(adjustSortIndex).toBeCalledWith(0, defaultGrouping, []);
expect(deps.action.changeColumnSorting.mock.calls[0][0])
.toEqual({
columnName: 'a',
direction: 'asc',
keepOther: true,
sortIndex: 0,
});
});
// tslint:disable-next-line: max-line-length
it('should modify changeColumnSorting action payload when several grouped columns is sorted', () => {
const defaultGrouping = [{ columnName: 'a' }, { columnName: 'b' }, { columnName: 'c' }];
const sorting = [{ columnName: 'a' }, { columnName: 'b' }, { columnName: 'c' }];
const deps = {
getter: {
sorting,
},
action: {
changeColumnSorting: jest.fn(),
},
};
adjustSortIndex.mockImplementation(() => 2);
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps, deps)}
<GroupingState
defaultGrouping={defaultGrouping}
/>
</PluginHost>
));
executeComputedAction(tree, actions => actions.changeColumnSorting({ columnName: 'c' }));
expect(adjustSortIndex).toBeCalledWith(2, defaultGrouping, sorting);
expect(deps.action.changeColumnSorting.mock.calls[0][0])
.toEqual({
columnName: 'c',
keepOther: true,
sortIndex: 2,
});
});
// tslint:disable-next-line: max-line-length
it('should correctly set sortIndex for changeColumnSorting action when some grouped columns is not sorted', () => {
const defaultGrouping = [{ columnName: 'a' }, { columnName: 'b' }, { columnName: 'c' }];
const sorting = [
{ columnName: 'a', direction: 'asc' },
{ columnName: 'c', direction: 'asc' },
];
const deps = {
getter: {
sorting,
},
action: {
changeColumnSorting: jest.fn(),
},
};
adjustSortIndex.mockImplementation(() => 1);
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps, deps)}
<GroupingState
defaultGrouping={defaultGrouping}
/>
</PluginHost>
));
executeComputedAction(tree, actions => actions.changeColumnSorting({ columnName: 'c' }));
expect(adjustSortIndex).toBeCalledWith(2, defaultGrouping, sorting);
expect(deps.action.changeColumnSorting.mock.calls[0][0])
.toEqual({
columnName: 'c',
keepOther: true,
sortIndex: 1,
});
});
it('should modify changeColumnSorting action payload when one grouped column is sorted', () => {
const defaultGrouping = [{ columnName: 'a' }, { columnName: 'b' }];
const deps = {
getter: {
sorting: [],
},
action: {
changeColumnSorting: jest.fn(),
},
};
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps, deps)}
<GroupingState
defaultGrouping={defaultGrouping}
/>
</PluginHost>
));
executeComputedAction(tree, actions => actions.changeColumnSorting({ columnName: 'b' }));
expect(adjustSortIndex).toBeCalledWith(1, defaultGrouping, []);
expect(deps.action.changeColumnSorting.mock.calls[0][0])
.toEqual({
columnName: 'b',
keepOther: true,
sortIndex: 0,
});
});
it('should modify changeColumnSorting action payload when sorted column is not grouped', () => {
const deps = {
getter: {
sorting: [],
},
action: {
changeColumnSorting: jest.fn(),
},
};
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps, deps)}
<GroupingState
defaultGrouping={[{ columnName: 'a' }, { columnName: 'b' }]}
/>
</PluginHost>
));
executeComputedAction(tree, actions => actions
.changeColumnSorting({ columnName: 'c', direction: 'asc' }),
);
expect(deps.action.changeColumnSorting.mock.calls[0][0])
.toEqual({
columnName: 'c',
direction: 'asc',
keepOther: ['a', 'b'],
});
});
});
describe('changeColumnSorting action on changeColumnGrouping action', () => {
it('should fire changeColumnSorting action when grouped by sorted column', () => {
const sorting = [
{ columnName: 'b', direction: 'asc' },
{ columnName: 'a', direction: 'asc' },
];
const grouping = [{ columnName: 'a' }];
const deps = {
getter: {
sorting,
},
action: {
changeColumnSorting: jest.fn(),
},
};
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps, deps)}
<GroupingState
defaultGrouping={[]}
/>
</PluginHost>
));
changeColumnGrouping.mockReturnValue({ grouping });
executeComputedAction(tree, actions => actions.changeColumnGrouping({ columnName: 'a' }));
expect(adjustSortIndex).toBeCalledWith(0, grouping, sorting);
expect(deps.action.changeColumnSorting.mock.calls[0][0])
.toEqual({
columnName: 'a',
direction: 'asc',
keepOther: true,
sortIndex: 0,
});
});
it('should fire changeColumnSorting action when ungrouped by sorted column', () => {
const sorting = [
{ columnName: 'a', direction: 'asc' },
{ columnName: 'b', direction: 'asc' },
];
const grouping = [{ columnName: 'b' }];
const deps = {
getter: {
sorting,
},
action: {
changeColumnSorting: jest.fn(),
},
};
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps, deps)}
<GroupingState
defaultGrouping={[{ columnName: 'a' }, { columnName: 'b' }]}
/>
</PluginHost>
));
adjustSortIndex.mockImplementation(() => 1);
changeColumnGrouping.mockReturnValue({ grouping });
executeComputedAction(tree, actions => actions.changeColumnGrouping({ columnName: 'a' }));
expect(adjustSortIndex).toBeCalledWith(1, grouping, sorting);
expect(deps.action.changeColumnSorting.mock.calls[0][0])
.toEqual({
columnName: 'a',
direction: 'asc',
keepOther: true,
sortIndex: 1,
});
});
it('should correctly calculate sortIndex when some grouped columns is not sorted', () => {
const sorting = [
{ columnName: 'a', direction: 'asc' },
{ columnName: 'c', direction: 'asc' },
];
const grouping = [{ columnName: 'a' }, { columnName: 'b' }, { columnName: 'c' }];
const deps = {
getter: {
sorting,
},
action: {
changeColumnSorting: jest.fn(),
},
};
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps, deps)}
<GroupingState
defaultGrouping={[{ columnName: 'a' }, { columnName: 'b' }, { columnName: 'c' }]}
/>
</PluginHost>
));
changeColumnGrouping.mockReturnValue({ grouping });
executeComputedAction(tree, actions => actions
.changeColumnGrouping({ columnName: 'a', groupIndex: 1 }),
);
expect(adjustSortIndex).toBeCalledWith(0, grouping, sorting);
expect(deps.action.changeColumnSorting)
.not.toBeCalled();
});
it('should not fire changeColumnSorting action when ungrouped last sorted column', () => {
const deps = {
getter: {
sorting: [{ columnName: 'a', direction: 'asc' }],
},
action: {
changeColumnSorting: jest.fn(),
},
};
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps, deps)}
<GroupingState
defaultGrouping={[{ columnName: 'a' }]}
/>
</PluginHost>
));
changeColumnGrouping.mockReturnValue({ grouping: [] });
executeComputedAction(tree, actions => actions.changeColumnGrouping({ columnName: 'a' }));
expect(deps.action.changeColumnSorting)
.not.toBeCalled();
});
// tslint:disable-next-line: max-line-length
it('should not fire changeColumnSorting action when grouped column sorting index is correct', () => {
const sorting = [
{ columnName: 'a', direction: 'asc' },
{ columnName: 'b', direction: 'asc' },
];
const grouping = [{ columnName: 'a' }, { columnName: 'b' }];
const deps = {
getter: {
sorting,
},
action: {
changeColumnSorting: jest.fn(),
},
};
const tree = mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps, deps)}
<GroupingState
defaultGrouping={[{ columnName: 'a' }]}
/>
</PluginHost>
));
changeColumnGrouping.mockReturnValue({ grouping });
executeComputedAction(tree, actions => actions.changeColumnGrouping({ columnName: 'a' }));
expect(adjustSortIndex).toBeCalledWith(0, grouping, sorting);
expect(deps.action.changeColumnSorting)
.not.toBeCalled();
});
});
describe('column extensions', () => {
it('should call getColumnExtensionValueGetter correctly', () => {
const columnExtensions = [{ columnName: 'a', groupingEnabled: true }];
mount((
<PluginHost>
{pluginDepsToComponents(defaultDeps)}
<GroupingState
columnGroupingEnabled={false}
columnExtensions={columnExtensions}
/>
</PluginHost>
));
expect(getColumnExtensionValueGetter)
.toBeCalledWith(columnExtensions, 'groupingEnabled', false);
});
});
}); | the_stack |
import { Params } from "../server/params";
import { Stores } from "../schema/stores";
import zlib from "zlib";
import { KotsAppStore } from "./kots_app_store";
import { eq, eqIgnoringLeadingSlash, FilesAsBuffers, TarballUnpacker, isTgzByName } from "../troubleshoot/util";
import { kotsRenderFile, kotsTemplateConfig } from "./kots_ffi";
import { ReplicatedError } from "../server/errors";
import { getS3 } from "../util/s3";
import tmp from "tmp";
import fs from "fs";
import path from "path";
import tar from "tar-stream";
import mkdirp from "mkdirp";
import { exec } from "child_process";
import { Cluster } from "../cluster";
import * as _ from "lodash";
import yaml from "js-yaml";
import { ApplicationSpec } from "./kots_app_spec";
export class KotsApp {
id: string;
name: string;
license?: string;
iconUri: string;
upstreamUri: string;
createdAt: Date;
updatedAt?: Date;
slug: string;
currentSequence?: number;
lastUpdateCheckAt?: Date;
bundleCommand: string;
currentVersion: KotsVersion;
airgapUploadPending: boolean;
isAirgap: boolean;
hasPreflight: boolean;
isConfigurable: boolean;
snapshotTTL?: string;
snapshotSchedule?: string;
restoreInProgressName?: string;
restoreUndeployStatus?: string;
// Version Methods
public async getCurrentAppVersion(stores: Stores): Promise<KotsVersion | undefined> {
// this is to get the current version of the upsteam from the app_version table
// annoying to have a separate method for this but the others require a clusteId.
// good candidate for a refactor
return stores.kotsAppStore.getCurrentAppVersion(this.id);
}
public async getCurrentVersion(clusterId: string, stores: Stores): Promise<KotsVersion | undefined> {
return stores.kotsAppStore.getCurrentVersion(this.id, clusterId);
}
public async getPendingVersions(clusterId: string, stores: Stores): Promise<KotsVersion[]> {
return stores.kotsAppStore.listPendingVersions(this.id, clusterId);
}
public async getPastVersions(clusterId: string, stores: Stores): Promise<KotsVersion[]> {
return stores.kotsAppStore.listPastVersions(this.id, clusterId);
}
public async getKotsAppSpec(clusterId: string, kotsAppStore: KotsAppStore): Promise<ApplicationSpec | undefined> {
const activeDownstream = await kotsAppStore.getCurrentVersion(this.id, clusterId);
if (!activeDownstream) {
return undefined;
}
return kotsAppStore.getKotsAppSpec(this.id, activeDownstream.parentSequence!);
}
public async getDownstreamGitOps(clusterId: string, stores: Stores): Promise<any> {
const gitops = await stores.kotsAppStore.getDownstreamGitOps(this.id, clusterId);
return gitops;
}
public async getRealizedLinksFromAppSpec(clusterId: string, stores: Stores): Promise<KotsAppLink[]> {
const activeDownstream = await stores.kotsAppStore.getCurrentVersion(this.id, clusterId);
if (!activeDownstream) {
return [];
}
const appSpec = await stores.kotsAppStore.getAppSpec(this.id, activeDownstream.parentSequence!);
if (!appSpec) {
return [];
}
const parsedKotsAppSpec = await stores.kotsAppStore.getKotsAppSpec(this.id, activeDownstream.parentSequence!);
try {
const parsedAppSpec = yaml.safeLoad(appSpec);
if (!parsedAppSpec.spec.descriptor || !parsedAppSpec.spec.descriptor.links) {
return [];
}
const links: KotsAppLink[] = [];
for (const unrealizedLink of parsedAppSpec.spec.descriptor.links) {
// this is a pretty naive solution that works when there is 1 downstream only
// we need to think about what the product experience is when
// there are > 1 downstreams
let rewrittenUrl = unrealizedLink.url;
if (parsedKotsAppSpec && parsedKotsAppSpec.ports) {
const mapped = _.find(parsedKotsAppSpec.ports, (port: any) => {
return port.applicationUrl === unrealizedLink.url;
});
if (mapped) {
rewrittenUrl = parsedAppSpec ? `http://localhost:${mapped.localPort}` : unrealizedLink;
}
}
const realized: KotsAppLink = {
title: unrealizedLink.description,
uri: rewrittenUrl,
};
links.push(realized);
}
return links;
} catch (err) {
console.log(err);
return [];
}
}
async getFilesPaths(sequence: string): Promise<string[]> {
const bundleIndexJsonPath = "index.json";
const indexFiles = await this.downloadFiles(this.id, sequence, [{
path: bundleIndexJsonPath,
matcher: eq(bundleIndexJsonPath),
}]);
const index = indexFiles.files[bundleIndexJsonPath] &&
JSON.parse(indexFiles.files[bundleIndexJsonPath].toString());
let paths: string[] = [];
if (!index) {
paths = indexFiles.fakeIndex;
} else {
index.map((p) => (paths.push(p.path)));
}
return paths;
}
getPasswordMask(): string {
return "***HIDDEN***";
}
getOriginalItem(groups: KotsConfigGroup[], itemName: string) {
for (let g = 0; g < groups.length; g++) {
const group = groups[g];
for (let i = 0; i < group.items.length; i++) {
const item = group.items[i];
if (item.name === itemName) {
return item;
}
}
}
return null;
}
private async getConfigDataFromFiles(files: FilesAsBuffers): Promise<ConfigData> {
let configSpec: string = "",
configValues: string = "",
configValuesPath: string = "";
for (const path in files.files) {
try {
const content = files.files[path];
const parsedContent = yaml.safeLoad(content.toString());
if (!parsedContent) {
continue;
}
if (parsedContent.kind === "Config" && parsedContent.apiVersion === "kots.io/v1beta1") {
configSpec = content.toString();
} else if (parsedContent.kind === "ConfigValues" && parsedContent.apiVersion === "kots.io/v1beta1") {
configValues = content.toString();
configValuesPath = path;
}
} catch {
// TODO: this will happen on multi-doc files.
}
}
return {
configSpec,
configValues,
configValuesPath,
}
}
shouldUpdateConfigValues(configGroups: KotsConfigGroup[], configValues: any, item: KotsConfigItem): boolean {
if (item.hidden || item.when === "false" || (item.type === "password" && item.value === this.getPasswordMask())) {
return false;
}
if (item.name in configValues) {
return item.value !== configValues[item.name];
} else {
const originalItem = this.getOriginalItem(configGroups, item.name);
if (originalItem && item.value) {
if (originalItem.value) {
return item.value !== originalItem.value;
} else if (originalItem.default) {
return item.value !== originalItem.default;
} else {
return true;
}
}
}
return false;
}
async applyConfigValues(configSpec: string, configValues: string, license: string, registryInfo: KotsAppRegistryDetails): Promise<KotsConfigGroup[]> {
const templatedConfig = await kotsTemplateConfig(configSpec, configValues, license, registryInfo);
if (!templatedConfig.spec || !templatedConfig.spec.groups) {
throw new ReplicatedError("Config groups not found");
}
const specConfigGroups = templatedConfig.spec.groups;
return specConfigGroups;
}
async getAppConfigGroups(stores: Stores, appId: string, sequence: string): Promise<KotsConfigGroup[]> {
try {
const app = await stores.kotsAppStore.getApp(appId);
const registryInfo = await stores.kotsAppStore.getAppRegistryDetails(app.id);
const configData = await stores.kotsAppStore.getAppConfigData(appId, sequence);
const { configSpec, configValues } = configData!;
return await this.applyConfigValues(configSpec, configValues, String(app.license), registryInfo);
} catch (err) {
throw new ReplicatedError(`Failed to get config groups ${err}`);
}
}
async templateConfigGroups(stores: Stores, appId: string, sequence: string, configGroups: KotsConfigGroup[]): Promise<KotsConfigGroup[]> {
const app = await stores.kotsAppStore.getApp(appId);
const configData = await stores.kotsAppStore.getAppConfigData(appId, sequence);
const { configSpec, configValues } = configData!;
const parsedConfig = yaml.safeLoad(configSpec);
const parsedConfigValues = yaml.safeLoad(configValues);
const specConfigValues = parsedConfigValues.spec.values;
const specConfigGroups = parsedConfig.spec.groups;
configGroups.forEach(group => {
group.items.forEach(async item => {
if (this.shouldUpdateConfigValues(specConfigGroups, specConfigValues, item)) {
let configVal = {}
if (item.value) {
configVal["value"] = item.value;
}
if (item.default) {
configVal["default"] = item.default;
}
specConfigValues[item.name] = configVal;
}
});
});
const updatedConfigValues = yaml.safeDump(parsedConfigValues);
const registryInfo = await stores.kotsAppStore.getAppRegistryDetails(app.id);
return await this.applyConfigValues(configSpec, updatedConfigValues, String(app.license), registryInfo);
}
// Source files
async generateFileTreeIndex(sequence) {
const paths = await this.getFilesPaths(sequence);
const dirTree = await this.arrangeIntoTree(paths);
return dirTree;
}
arrangeIntoTree(paths) {
const tree: any[] = [];
_.each(paths, (path) => {
const pathParts = path.split("/");
if (pathParts[0] === "") {
pathParts.shift(); // remove first blank element from the parts array.
}
let currentLevel = tree; // initialize currentLevel to root
_.each(pathParts, (part) => {
// check to see if the path already exists.
const existingPath = _.find(currentLevel, ["name", part]);
if (existingPath) {
// the path to this item was already in the tree, so don't add it again.
// set the current level to this path's children
currentLevel = existingPath.children;
} else {
const newPart = {
name: part,
path: `${path}`,
children: [],
};
currentLevel.push(newPart);
currentLevel = newPart.children;
}
});
});
return tree;
}
async getFiles(sequence: string, fileNames: string[]): Promise<FilesAsBuffers> {
const fileNameList = fileNames.map((fileName) => ({
path: fileName,
matcher: eqIgnoringLeadingSlash(fileName),
}));
const filesWeWant = await this.downloadFiles(this.id, sequence, fileNameList);
return filesWeWant;
}
async getFilesJSON(sequence: string, fileNames: string[]): Promise<string> {
const files: FilesAsBuffers = await this.getFiles(sequence, fileNames);
let fileStrings: {
[key: string]: string;
} = {};
for (const path in files.files) {
const content = files.files[path];
if (isTgzByName(path)) {
fileStrings[path] = content.toString('base64');
} else {
fileStrings[path] = content.toString();
}
}
const jsonFiles = JSON.stringify(fileStrings);
return jsonFiles;
}
async downloadFiles(appId: string, sequence: string, filesWeCareAbout: Array<{ path: string; matcher }>): Promise<FilesAsBuffers> {
const replicatedParams = await Params.getParams();
return new Promise<FilesAsBuffers>((resolve, reject) => {
const params = {
Bucket: replicatedParams.shipOutputBucket,
Key: `${replicatedParams.s3BucketEndpoint !== "" ? `${replicatedParams.shipOutputBucket}/` : ""}${appId}/${sequence}.tar.gz`,
};
const tarGZStream = getS3(replicatedParams).getObject(params).createReadStream();
tarGZStream.on("error", err => {
reject(err);
});
const unzipperStream = zlib.createGunzip();
unzipperStream.on("error", err => {
reject(err);
});
tarGZStream.pipe(unzipperStream);
const bundleUnpacker = new TarballUnpacker();
bundleUnpacker.unpackFrom(unzipperStream, filesWeCareAbout)
.then(resolve)
.catch(reject);
});
}
async getArchive(sequence: string): Promise<any> {
const replicatedParams = await Params.getParams();
const params = {
Bucket: replicatedParams.shipOutputBucket,
Key: `${replicatedParams.s3BucketEndpoint !== "" ? `${replicatedParams.shipOutputBucket}/` : ""}${this.id}/${sequence}.tar.gz`,
};
const result = await getS3(replicatedParams).getObject(params).promise();
return result.Body;
}
async getImagePullSecretFromArchive(sequence: string): Promise<string> {
const replicatedParams = await Params.getParams();
const params = {
Bucket: replicatedParams.shipOutputBucket,
Key: `${replicatedParams.s3BucketEndpoint !== "" ? `${replicatedParams.shipOutputBucket}/` : ""}${this.id}/${sequence}.tar.gz`,
};
const tgzStream = getS3(replicatedParams).getObject(params).createReadStream();
const extract = tar.extract();
const gzunipStream = zlib.createGunzip();
return new Promise((resolve, reject) => {
const tmpDir = tmp.dirSync();
extract.on("entry", async (header, stream, next) => {
if (header.type !== "file") {
stream.resume();
next();
return;
}
const contents = await this.readFile(stream);
const fileName = path.join(tmpDir.name, header.name);
const parsed = path.parse(fileName);
if (!fs.existsSync(parsed.dir)) {
// TODO, move to node 10 and use the built in
// fs.mkdirSync(parsed.dir, {recursive: true});
mkdirp.sync(parsed.dir);
}
fs.writeFileSync(fileName, contents);
next();
});
extract.on("finish", () => {
// read the file IF IT EXISTS
const secretFile = path.join(tmpDir.name, "overlays", "midstream", "secret.yaml")
if (!fs.existsSync(secretFile)) {
resolve("");
return;
}
const content = fs.readFileSync(secretFile, "utf-8");
resolve(content);
});
tgzStream.pipe(gzunipStream).pipe(extract);
});
}
async render(sequence: string, overlayPath: string, kustomizeVersion: string | undefined): Promise<string> {
const replicatedParams = await Params.getParams();
const params = {
Bucket: replicatedParams.shipOutputBucket,
Key: `${replicatedParams.s3BucketEndpoint !== "" ? `${replicatedParams.shipOutputBucket}/` : ""}${this.id}/${sequence}.tar.gz`,
};
const tgzStream = getS3(replicatedParams).getObject(params).createReadStream();
const extract = tar.extract();
const gzunipStream = zlib.createGunzip();
return new Promise((resolve, reject) => {
const tmpDir = tmp.dirSync();
extract.on("entry", async (header, stream, next) => {
if (header.type !== "file") {
stream.resume();
next();
return;
}
const contents = await this.readFile(stream);
const fileName = path.join(tmpDir.name, header.name);
const parsed = path.parse(fileName);
if (!fs.existsSync(parsed.dir)) {
// TODO, move to node 10 and use the built in
// fs.mkdirSync(parsed.dir, {recursive: true});
mkdirp.sync(parsed.dir);
}
fs.writeFileSync(fileName, contents);
next();
});
extract.on("finish", () => {
// Choose kustomize binary
let kustomizeString = "kustomize3.5.4";
if (kustomizeVersion && kustomizeVersion !== "") {
if (kustomizeVersion !== "latest") {
kustomizeString = `kustomize${kustomizeVersion}`;
}
}
// Run kustomize
exec(`${kustomizeString} build ${path.join(tmpDir.name, overlayPath)}`, { maxBuffer: 1024 * 5000 }, (err, stdout, stderr) => {
tmpDir.removeCallback();
if (err) {
// logger.error({ msg: "err running kustomize", err, stderr })
reject(err);
return;
}
resolve(stdout);
});
});
tgzStream.on("error", err => {
reject(err);
});
tgzStream.pipe(gzunipStream).pipe(extract);
});
}
public async isGitOpsSupported(stores: Stores): Promise<boolean> {
const sequence = this.currentSequence || 0;
return await stores.kotsAppStore.isGitOpsSupported(this.id, sequence);
}
private async isAllowRollback(stores: Stores): Promise<boolean> {
const parsedKotsAppSpec = await stores.kotsAppStore.getKotsAppSpec(this.id, this.currentSequence!);
try {
if (parsedKotsAppSpec && parsedKotsAppSpec.allowRollback) {
return true;
}
} catch {
/* not a valid app spec */
}
return false;
}
private async isAllowSnapshots(stores: Stores, downstreams: Cluster[]): Promise<boolean> {
if (!downstreams.length) {
return false;
}
const clusterID = downstreams[0].id;
const tmpl = await stores.kotsAppStore.getDeployedVersionBackup(this.id, clusterID);
if (!tmpl) {
return false;
}
const registryInfo = await stores.kotsAppStore.getAppRegistryDetails(this.id);
const rendered = await kotsRenderFile(this, stores, tmpl, registryInfo);
const backup = yaml.safeLoad(rendered);
const annotations = _.get(backup, "metadata.annotations") as any;
if (!_.isPlainObject(annotations)) {
// Backup exists and there are no annotation overrides so snapshots are enabled
return true;
}
const exclude = annotations["kots.io/exclude"];
if (exclude === "true" || exclude === true) {
return false;
}
const when = annotations["kots.io/when"];
if (when === "false" || when === false) {
return false;
}
return true;
}
private async getKotsLicenseType(stores: Stores): Promise<string> {
const id = await stores.kotsAppStore.getIdFromSlug(this.slug);
const sequence = await stores.kotsAppStore.getMaxSequence(id);
return await stores.kotsAppStore.getKotsAppLicenseType(id, sequence);
}
private readFile(s: NodeJS.ReadableStream): Promise<string> {
return new Promise<string>((resolve, reject) => {
let contents = ``;
s.on("data", (chunk) => {
contents += chunk.toString();
});
s.on("error", reject);
s.on("end", () => {
resolve(contents);
});
});
}
public async getSupportBundleCommand(watchSlug: string): Promise<string> {
const params = await Params.getParams();
const bundleCommand = `
curl https://krew.sh/support-bundle | bash
kubectl support-bundle API_ADDRESS/api/v1/troubleshoot/${watchSlug}
`;
return bundleCommand;
}
public toSchema(downstreams: Cluster[], stores: Stores) {
return {
...this,
isGitOpsSupported: () => this.isGitOpsSupported(stores),
allowRollback: () => this.isAllowRollback(stores),
allowSnapshots: () => this.isAllowSnapshots(stores, downstreams),
currentVersion: () => this.getCurrentAppVersion(stores),
licenseType: () => this.getKotsLicenseType(stores),
downstreams: _.map(downstreams, (downstream) => {
const kotsSchemaCluster = downstream.toKotsAppSchema(this.id, stores);
return {
name: downstream.title,
gitops: () => this.getDownstreamGitOps(downstream.id, stores),
links: () => this.getRealizedLinksFromAppSpec(kotsSchemaCluster.id, stores),
currentVersion: () => this.getCurrentVersion(downstream.id, stores),
pastVersions: () => this.getPastVersions(downstream.id, stores),
pendingVersions: () => this.getPendingVersions(downstream.id, stores),
cluster: kotsSchemaCluster
};
}),
};
}
}
export interface KotsAppLink {
title: string;
uri: string;
}
export interface KotsVersion {
title: string;
status: string;
createdOn: string;
parentSequence?: number;
sequence: number;
releaseNotes: string;
deployedAt: string;
preflightResult: string;
preflightResultCreatedAt: string;
hasError?: boolean;
source?: string;
diffSummary?: string;
commitUrl?: string;
gitDeployable?: boolean;
backupSpec?: string;
}
export interface AppRegistryDetails {
appSlug: string;
hostname: string;
username: string;
password: string;
namespace: string;
}
export interface KotsAppRegistryDetails {
registryHostname: string;
registryUsername: string;
registryPassword: string;
registryPasswordEnc: string;
namespace: string;
lastSyncedAt: string;
}
export interface KotsConfigChildItem {
name: string;
title: string;
recommended: boolean;
default: string;
value: string;
}
export interface KotsConfigItem {
name: string;
type: string;
title: string;
help_text: string;
recommended: boolean;
default: string;
value: string;
error: string;
data: string;
multi_value: [string];
readonly: boolean;
write_once: boolean;
when: string;
multiple: boolean;
hidden: boolean;
position: number;
affix: string;
required: boolean;
items: KotsConfigChildItem[];
}
export interface KotsConfigGroup {
name: string;
title: string;
description: string;
items: KotsConfigItem[];
}
export interface KotsDownstreamOutput {
dryrunStdout: string;
dryrunStderr: string;
applyStdout: string;
applyStderr: string;
renderError: string | null;
}
export interface ConfigData {
configSpec: string;
configValues: string;
configValuesPath?: string;
} | the_stack |
import * as React from 'react';
import {
Categorization,
Category,
ControlElement,
JsonSchema,
Layout,
} from '@jsonforms/core';
import { JsonFormsStateProvider } from '@jsonforms/react';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import Enzyme, { mount, ReactWrapper } from 'enzyme';
import CategorizationRenderer, { categorizationTester } from '../../src/complex/categorization';
import { initCore } from '../util';
import { vanillaRenderers } from '../../src';
Enzyme.configure({ adapter: new Adapter() });
const category: Category = {
type: 'Category',
label: 'B',
elements: []
};
const fixture = {
data: {},
schema: {
type: 'object',
properties: {
name: {
type: 'string'
}
}
},
uischema: {
type: 'Categorization',
label: 'A',
elements: [category]
}
};
describe('Categorization tester', () => {
test('tester', () => {
expect(categorizationTester(undefined, undefined)).toBe(-1);
expect(categorizationTester(null, undefined)).toBe(-1);
expect(categorizationTester({ type: 'Foo' }, undefined)).toBe(-1);
expect(categorizationTester({ type: 'Categorization' }, undefined)).toBe(-1);
});
test('tester with null elements and no schema', () => {
const uischema: Layout = {
type: 'Categorization',
elements: null
};
expect(
categorizationTester(
uischema,
undefined
)
).toBe(-1);
});
test('tester with empty elements and no schema', () => {
const uischema: Layout = {
type: 'Categorization',
elements: []
};
expect(
categorizationTester(
uischema,
undefined
)
).toBe(-1);
});
test('apply tester with single unknown element and no schema', () => {
const uischema: Layout = {
type: 'Categorization',
elements: [
{
type: 'Foo'
},
]
};
expect(
categorizationTester(
uischema,
undefined
)
).toBe(-1);
});
test('tester with single category and no schema', () => {
const categorization = {
type: 'Categorization',
elements: [
{
type: 'Category'
}
]
};
expect(
categorizationTester(
categorization,
undefined
)
).toBe(1);
});
test('tester with nested categorization and single category and no schema', () => {
const nestedCategorization: Layout = {
type: 'Categorization',
elements: [
{
type: 'Category'
}
]
};
const categorization: Layout = {
type: 'Categorization',
elements: [nestedCategorization]
};
expect(
categorizationTester(
categorization,
undefined)
).toBe(1);
});
test('tester with nested categorizations, but no category and no schema', () => {
const categorization: any = {
type: 'Categorization',
elements: [
{
type: 'Categorization'
}
]
};
expect(
categorizationTester(
categorization,
undefined
)
).toBe(-1);
});
test('tester with nested categorizations, null elements and no schema', () => {
const categorization: any = {
type: 'Categorization',
elements: [
{
type: 'Categorization',
label: 'Test',
elements: null
}
]
};
expect(
categorizationTester(
categorization,
undefined
)
).toBe(-1);
});
test('tester with nested categorizations, empty elements and no schema', () => {
const categorization: any = {
type: 'Categorization',
elements: [
{
type: 'Categorization',
elements: []
}
]
};
expect(
categorizationTester(
categorization,
undefined
)
).toBe(-1);
});
});
describe('Categorization renderer', () => {
let wrapper: ReactWrapper;
afterEach(() => wrapper.unmount());
test('render', () => {
const schema: JsonSchema = {
type: 'object',
properties: {
name: {
type: 'string'
}
}
};
const nameControl = {
type: 'Control',
scope: '#/properties/name'
};
const innerCat: Categorization = {
type: 'Categorization',
label: 'Bar',
elements: [
{
type: 'Category',
label: 'A',
elements: [nameControl]
}
]
};
const uischema: Categorization = {
type: 'Categorization',
label: 'Root',
elements: [
innerCat,
{
type: 'Category',
label: 'B',
elements: [nameControl]
}
]
};
const core = initCore(schema, uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<CategorizationRenderer
schema={schema}
uischema={uischema}
/>
</JsonFormsStateProvider>
);
const div = wrapper.find('.categorization').getDOMNode();
const master = wrapper.find('.categorization-master').getDOMNode();
const ul = master.children[0];
const liA = ul.children[0];
const spanA = liA.children[0];
const innerUlA = liA.children[1];
const innerLiA = innerUlA.children[0];
const innerSpanA = innerLiA.children[0];
const liB = ul.children[1];
const spanB = liB.children[0];
// detail
const detail = div.children[1] as HTMLDivElement;
expect(div.className).toBe('categorization');
expect(div.childNodes).toHaveLength(2);
expect(master.className).toBe('categorization-master');
expect(master.children).toHaveLength(1);
expect(ul.children).toHaveLength(2);
expect(liA.className).toBe('category-group');
expect(liA.children).toHaveLength(2);
expect(spanA.textContent).toBe('Bar');
expect(innerUlA.className).toBe('category-subcategories');
expect(innerUlA.children).toHaveLength(1);
expect(innerLiA.children).toHaveLength(1);
expect(innerSpanA.textContent).toBe('A');
expect(liB.className).not.toBe('category-group');
expect(liB.children).toHaveLength(1);
expect(spanB.textContent).toBe('B');
expect(detail.className).toBe('categorization-detail');
expect(detail.children).toHaveLength(1);
expect(detail.children.item(0).tagName).toBe('DIV');
expect(detail.children.item(0).children).toHaveLength(1);
});
test('render on click', () => {
const data = { 'name': 'Foo' };
const nameControl: ControlElement = {
type: 'Control',
scope: '#/properties/name'
};
const innerCategorization: Categorization = {
type: 'Categorization',
label: 'Bar',
elements: [
{
type: 'Category',
label: 'A',
elements: [nameControl]
},
]
};
const uischema: Categorization = {
type: 'Categorization',
label: 'Root',
elements: [
innerCategorization,
{
type: 'Category',
label: 'B',
elements: [nameControl, nameControl]
},
{
type: 'Category',
label: 'C',
elements: undefined
},
{
type: 'Category',
label: 'D',
elements: null
},
]
};
const core = initCore(fixture.schema, uischema, data);
wrapper = mount(
<JsonFormsStateProvider initState={{ core }}>
<CategorizationRenderer
schema={fixture.schema}
uischema={uischema}
/>
</JsonFormsStateProvider>
);
const div: HTMLDivElement = wrapper.find('.categorization').getDOMNode();
const master = div.children[0] as HTMLDivElement;
const ul = master.children[0];
const listItems = wrapper.find('li');
const liB = listItems.at(2);
const liC = listItems.at(3);
const liD = listItems.at(4);
const detail = div.children[1] as HTMLDivElement;
expect(div.className).toBe('categorization');
expect(div.childNodes).toHaveLength(2);
expect(master.children).toHaveLength(1);
expect(ul.children).toHaveLength(4);
expect(detail.children).toHaveLength(1);
expect(detail.children.item(0).tagName).toBe('DIV');
expect(detail.children.item(0).children).toHaveLength(1);
liB.simulate('click');
expect(detail.children).toHaveLength(1);
expect(detail.children.item(0).tagName).toBe('DIV');
expect(detail.children.item(0).children).toHaveLength(2);
liC.simulate('click');
expect(detail.children).toHaveLength(1);
expect(detail.children.item(0).tagName).toBe('DIV');
expect(detail.children.item(0).children).toHaveLength(0);
liD.simulate('click');
expect(detail.children).toHaveLength(1);
expect(detail.children.item(0).tagName).toBe('DIV');
expect(detail.children.item(0).children).toHaveLength(0);
});
test('hide', () => {
const uischema: Categorization = {
type: 'Categorization',
label: '',
elements: [
{
type: 'Category',
label: 'B',
elements: []
}
]
};
const core = initCore(fixture.schema, uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ renderers: vanillaRenderers, core }}>
<CategorizationRenderer
schema={fixture.schema}
uischema={uischema}
visible={false}
/>
</JsonFormsStateProvider>
);
const div = wrapper.find('.categorization').getDOMNode() as HTMLDivElement;
expect(div.hidden).toBe(true);
});
test('showed by default', () => {
const uischema: Categorization = {
type: 'Categorization',
label: '',
elements: [
{
type: 'Category',
label: 'B',
elements: []
}
]
};
const core = initCore(fixture.schema, uischema, fixture.data);
wrapper = mount(
<JsonFormsStateProvider initState={{ renderers: vanillaRenderers, core }}>
<CategorizationRenderer
schema={fixture.schema}
uischema={uischema}
/>
</JsonFormsStateProvider>
);
const div: HTMLDivElement = wrapper.find('.categorization').getDOMNode();
expect(div.hidden).toBe(false);
});
}); | the_stack |
import { QuickPickItem, window } from 'vscode';
import { GitActions } from '../../commands/gitCommands.actions';
import { OpenChangedFilesCommandArgs } from '../../commands/openChangedFiles';
import { QuickCommandButtons } from '../../commands/quickCommand.buttons';
import { Commands, GlyphChars } from '../../constants';
import { Container } from '../../container';
import { CommitFormatter } from '../../git/formatters';
import { GitCommit, GitFile, GitFileChange, GitStatusFile } from '../../git/models';
import { Keys } from '../../keyboard';
import { basename } from '../../system/path';
import { pad } from '../../system/string';
import { CommandQuickPickItem } from './common';
export class CommitFilesQuickPickItem extends CommandQuickPickItem {
constructor(
readonly commit: GitCommit,
options?: {
file?: GitFileChange;
unpublished?: boolean | undefined;
picked?: boolean;
hint?: string;
},
) {
super(
{
label: commit.summary,
description: `${CommitFormatter.fromTemplate(`\${author}, \${ago} $(git-commit) \${id}`, commit)}${
options?.unpublished ? ' (unpublished)' : ''
}`,
detail: `${
options?.file != null
? `$(file) ${basename(options.file.path)}${options.file.formatStats({
expand: true,
separator: ', ',
prefix: ` ${GlyphChars.Dot} `,
})}`
: `$(files) ${commit.formatStats({
expand: true,
separator: ', ',
empty: 'No files changed',
})}`
}${options?.hint != null ? `${pad(GlyphChars.Dash, 4, 2, GlyphChars.Space)}${options.hint}` : ''}`,
alwaysShow: true,
picked: options?.picked ?? true,
buttons: GitCommit.isStash(commit)
? [QuickCommandButtons.RevealInSideBar]
: [QuickCommandButtons.RevealInSideBar, QuickCommandButtons.SearchInSideBar],
},
undefined,
undefined,
{ suppressKeyPress: true },
);
}
get sha(): string {
return this.commit.sha;
}
}
export class CommitFileQuickPickItem extends CommandQuickPickItem {
constructor(readonly commit: GitCommit, readonly file: GitFile, picked?: boolean) {
super({
label: `${pad(GitFile.getStatusCodicon(file.status), 0, 2)}${basename(file.path)}`,
description: GitFile.getFormattedDirectory(file, true),
picked: picked,
});
// TODO@eamodio - add line diff details
// this.detail = this.commit.getFormattedDiffStatus({ expand: true });
}
get sha(): string {
return this.commit.sha;
}
override execute(options?: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return GitActions.Commit.openChanges(this.file, this.commit, options);
// const fileCommit = await this.commit.getCommitForFile(this.file)!;
// if (fileCommit.previousSha === undefined) {
// void (await findOrOpenEditor(
// GitUri.toRevisionUri(fileCommit.sha, this.file, fileCommit.repoPath),
// options,
// ));
// return;
// }
// const commandArgs: DiffWithPreviousCommandArgs = {
// commit: fileCommit,
// showOptions: options,
// };
// void (await executeCommand(Commands.DiffWithPrevious, fileCommit.toGitUri(), commandArgs));
}
}
export class CommitBrowseRepositoryFromHereCommandQuickPickItem extends CommandQuickPickItem {
constructor(
private readonly commit: GitCommit,
private readonly executeOptions?: {
before?: boolean;
openInNewWindow: boolean;
},
item?: QuickPickItem,
) {
super(
item ??
`$(folder-opened) Browse Repository from${executeOptions?.before ? ' Before' : ''} Here${
executeOptions?.openInNewWindow ? ' in New Window' : ''
}`,
);
}
override execute(_options: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return GitActions.browseAtRevision(this.commit.getGitUri(), {
before: this.executeOptions?.before,
openInNewWindow: this.executeOptions?.openInNewWindow,
});
}
}
export class CommitCompareWithHEADCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, item?: QuickPickItem) {
super(item ?? '$(compare-changes) Compare with HEAD');
}
override execute(_options: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return Container.instance.searchAndCompareView.compare(this.commit.repoPath, this.commit.ref, 'HEAD');
}
}
export class CommitCompareWithWorkingCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, item?: QuickPickItem) {
super(item ?? '$(compare-changes) Compare with Working Tree');
}
override execute(_options: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return Container.instance.searchAndCompareView.compare(this.commit.repoPath, this.commit.ref, '');
}
}
export class CommitCopyIdQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, item?: QuickPickItem) {
super(item ?? '$(copy) Copy SHA');
}
override execute(): Promise<void> {
return GitActions.Commit.copyIdToClipboard(this.commit);
}
override async onDidPressKey(key: Keys): Promise<void> {
await super.onDidPressKey(key);
void window.showInformationMessage('Commit SHA copied to the clipboard');
}
}
export class CommitCopyMessageQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, item?: QuickPickItem) {
super(item ?? '$(copy) Copy Message');
}
override execute(): Promise<void> {
return GitActions.Commit.copyMessageToClipboard(this.commit);
}
override async onDidPressKey(key: Keys): Promise<void> {
await super.onDidPressKey(key);
void window.showInformationMessage(
`${this.commit.stashName ? 'Stash' : 'Commit'} Message copied to the clipboard`,
);
}
}
export class CommitOpenAllChangesCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, item?: QuickPickItem) {
super(item ?? '$(git-compare) Open All Changes');
}
override execute(options: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return GitActions.Commit.openAllChanges(this.commit, options);
}
}
export class CommitOpenAllChangesWithDiffToolCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, item?: QuickPickItem) {
super(item ?? '$(git-compare) Open All Changes (difftool)');
}
override execute(): Promise<void> {
return GitActions.Commit.openAllChangesWithDiffTool(this.commit);
}
}
export class CommitOpenAllChangesWithWorkingCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, item?: QuickPickItem) {
super(item ?? '$(git-compare) Open All Changes with Working Tree');
}
override execute(options: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return GitActions.Commit.openAllChangesWithWorking(this.commit, options);
}
}
export class CommitOpenChangesCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, private readonly file: string | GitFile, item?: QuickPickItem) {
super(item ?? '$(git-compare) Open Changes');
}
override execute(options: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return GitActions.Commit.openChanges(this.file, this.commit, options);
}
}
export class CommitOpenChangesWithDiffToolCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, private readonly file: string | GitFile, item?: QuickPickItem) {
super(item ?? '$(git-compare) Open Changes (difftool)');
}
override execute(): Promise<void> {
return GitActions.Commit.openChangesWithDiffTool(this.file, this.commit);
}
}
export class CommitOpenChangesWithWorkingCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, private readonly file: string | GitFile, item?: QuickPickItem) {
super(item ?? '$(git-compare) Open Changes with Working File');
}
override execute(options: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return GitActions.Commit.openChangesWithWorking(this.file, this.commit, options);
}
}
export class CommitOpenDirectoryCompareCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, item?: QuickPickItem) {
super(item ?? '$(git-compare) Open Directory Compare');
}
override execute(): Promise<void> {
return GitActions.Commit.openDirectoryCompareWithPrevious(this.commit);
}
}
export class CommitOpenDirectoryCompareWithWorkingCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, item?: QuickPickItem) {
super(item ?? '$(git-compare) Open Directory Compare with Working Tree');
}
override execute(): Promise<void> {
return GitActions.Commit.openDirectoryCompareWithWorking(this.commit);
}
}
export class CommitOpenFilesCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, item?: QuickPickItem) {
super(item ?? '$(files) Open Files');
}
override execute(_options: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return GitActions.Commit.openFiles(this.commit);
}
}
export class CommitOpenFileCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, private readonly file: string | GitFile, item?: QuickPickItem) {
super(item ?? '$(file) Open File');
}
override execute(options?: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return GitActions.Commit.openFile(this.file, this.commit, options);
}
}
export class CommitOpenRevisionsCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, item?: QuickPickItem) {
super(item ?? '$(files) Open Files at Revision');
}
override execute(_options: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return GitActions.Commit.openFilesAtRevision(this.commit);
}
}
export class CommitOpenRevisionCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, private readonly file: string | GitFile, item?: QuickPickItem) {
super(item ?? '$(file) Open File at Revision');
}
override execute(options?: { preserveFocus?: boolean; preview?: boolean }): Promise<void> {
return GitActions.Commit.openFileAtRevision(this.file, this.commit, options);
}
}
export class CommitApplyFileChangesCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, private readonly file: string | GitFile, item?: QuickPickItem) {
super(item ?? 'Apply Changes');
}
override async execute(): Promise<void> {
return GitActions.Commit.applyChanges(this.file, this.commit);
}
}
export class CommitRestoreFileChangesCommandQuickPickItem extends CommandQuickPickItem {
constructor(private readonly commit: GitCommit, private readonly file: string | GitFile, item?: QuickPickItem) {
super(
item ?? {
label: 'Restore',
description: 'aka checkout',
},
);
}
override execute(): Promise<void> {
return GitActions.Commit.restoreFile(this.file, this.commit);
}
}
export class OpenChangedFilesCommandQuickPickItem extends CommandQuickPickItem {
constructor(files: GitStatusFile[], item?: QuickPickItem) {
const commandArgs: OpenChangedFilesCommandArgs = {
uris: files.map(f => f.uri),
};
super(item ?? '$(files) Open All Changed Files', Commands.OpenChangedFiles, [commandArgs]);
}
} | the_stack |
import { wait } from "@core/lib/utils/wait";
import { SharedIniFileCredentials } from "aws-sdk";
import IAM from "aws-sdk/clients/iam";
import ECR from "aws-sdk/clients/ecr";
import ECS from "aws-sdk/clients/ecs";
import EC2 from "aws-sdk/clients/ec2";
import ELBv2 from "aws-sdk/clients/elbv2";
import CF from "aws-sdk/clients/cloudformation";
import CodeBuild from "aws-sdk/clients/codebuild";
import Secrets from "aws-sdk/clients/secretsmanager";
import S3 from "aws-sdk/clients/s3";
import SNS from "aws-sdk/clients/sns";
import {
dangerouslyDeleteS3BucketsWithConfirm,
dangerouslyDeleteSecretsWithConfirm,
deleteDeployTag,
getAwsAccountId,
listCodebuildProjects,
} from "./aws-helpers";
import {
CfStack,
getEcrRepoName,
getSnsAlertTopicArn,
} from "./stack-constants";
import * as R from "ramda";
export const destroyHost = async (params: {
deploymentTag: string;
primaryRegion: string;
failoverRegion?: string;
dryRun?: boolean;
profile?: string;
}): Promise<boolean> => {
const { dryRun, deploymentTag, profile, primaryRegion, failoverRegion } =
params;
const credentials = profile
? new SharedIniFileCredentials({
profile,
})
: undefined;
const s3 = new S3({ region: primaryRegion, credentials });
const s3Secondary = new S3({ region: failoverRegion, credentials });
const cfPrimary = new CF({
region: primaryRegion,
credentials,
});
const cfSecondary = failoverRegion
? new CF({
region: failoverRegion,
credentials,
})
: undefined;
const codeBuild = new CodeBuild({ region: primaryRegion, credentials });
const secretsManager = new Secrets({ region: primaryRegion, credentials });
const sns = new SNS({ region: primaryRegion, credentials });
const iam = new IAM({ region: primaryRegion, credentials });
const ecr = new ECR({ region: primaryRegion, credentials });
const ecs = new ECS({ region: primaryRegion, credentials });
const elbPrimary = new ELBv2({ region: primaryRegion, credentials });
const elbSecondary = failoverRegion
? new ELBv2({ region: failoverRegion, credentials })
: undefined;
const ec2Primary = new EC2({ region: primaryRegion, credentials });
const ec2Secondary = failoverRegion
? new EC2({ region: failoverRegion, credentials })
: undefined;
let failed = false;
if (dryRun) {
console.log("DRY RUN - no resources will be deleted.");
}
const awsAccountId = await getAwsAccountId(profile);
const tagFinder = (tag: EC2.Tag) =>
tag.Key == "envkey-deployment" && tag.Value == deploymentTag;
const tagFilters = [
{ Name: "tag:envkey-deployment", Values: [deploymentTag] },
];
const deleteStackAndWait = async (
cf: CF,
stack: CfStack,
timeout?: number
) => {
try {
await cf
.describeStacks({
StackName: [stack, deploymentTag].join("-"),
})
.promise()
.catch(() => ({ Stacks: undefined }))
.then(({ Stacks }) => {
if (Stacks && Stacks[0]?.StackId) {
if (dryRun) {
console.log("Stack:\n ", stack, "\n ", Stacks[0].StackId);
return;
}
console.log("Stack:\n Deleting", stack, Stacks[0].StackId);
return cf.deleteStack({ StackName: Stacks[0].StackId }).promise();
}
});
} catch (err) {
console.error(err.message);
failed = true;
}
let waitForDelete = true;
const start = Date.now();
let elapsed = 0;
while (waitForDelete) {
await cf
.describeStacks({
StackName: [stack, deploymentTag].join("-"),
})
.promise()
.catch(() => ({ Stacks: undefined }))
.then(({ Stacks }) => {
if (!Stacks || Stacks.length == 0) {
waitForDelete = false;
}
});
await wait(2000);
elapsed = Date.now() - start;
if (timeout && elapsed > timeout) {
waitForDelete = false;
}
}
};
// delete ecr repo first - CF won't delete ECR repos with --force so it always fails,
// leaving the stack around
try {
const repositoryName = getEcrRepoName(deploymentTag);
if (dryRun) {
console.log("Container registry:\n ", repositoryName);
} else {
console.log("Deleting container registry:\n ", repositoryName);
await ecr.deleteRepository({ repositoryName, force: true }).promise();
}
} catch (err) {
if (err.code === "RepositoryNotFoundException") {
console.error(" no container registry to delete.");
} else {
console.error(" ", err.message);
failed = true;
}
}
// bring down any running fargate tasks and delete the cluster since cloudformation has a hard time deleting it
const clusterRes = await ecs.listClusters().promise();
for (let clusterArn of clusterRes.clusterArns ?? []) {
if (clusterArn.includes(deploymentTag)) {
console.log("Bringing down cluster: ", clusterArn);
let serviceRes = await ecs
.listServices({ cluster: clusterArn })
.promise();
console.log("Deleting service...");
await ecs
.deleteService({
service: serviceRes!.serviceArns![0],
cluster: clusterArn,
force: true,
})
.promise();
while (serviceRes.serviceArns?.length) {
console.log("Waiting for service to delete...");
await wait(2000);
serviceRes = await ecs.listServices({ cluster: clusterArn }).promise();
}
let tasksRes = await ecs.listTasks({ cluster: clusterArn }).promise();
await Promise.all(
(tasksRes.taskArns ?? []).map((taskArn) =>
ecs.stopTask({ cluster: clusterArn, task: taskArn }).promise()
)
);
while (tasksRes.taskArns?.length) {
console.log("Waiting for tasks to stop...");
await wait(2000);
tasksRes = await ecs.listTasks({ cluster: clusterArn }).promise();
}
console.log("Deleting cluster...");
await ecs.deleteCluster({ cluster: clusterArn! }).promise();
}
}
console.log("Deleting listener and privatelink CloudFormation stacks...");
await Promise.all([
deleteStackAndWait(cfPrimary, CfStack.ENVKEY_LISTENER_RULES),
deleteStackAndWait(cfPrimary, CfStack.ENVKEY_PRIVATE_LINK),
]);
console.log("Clearing out lambda stacks...");
await Promise.all([
deleteStackAndWait(cfPrimary, CfStack.ENVKEY_FAILOVER_LAMBDA),
cfSecondary
? deleteStackAndWait(cfSecondary, CfStack.ENVKEY_SECONDARY_LAMBDA)
: undefined,
]);
console.log("Deleting load balancer CloudFormation stacks...");
await Promise.all([
deleteStackAndWait(cfPrimary, CfStack.ENVKEY_INTERNAL_LOAD_BALANCERS),
deleteStackAndWait(cfPrimary, CfStack.ENVKEY_INTERNET_LOAD_BALANCERS),
cfSecondary
? deleteStackAndWait(cfSecondary, CfStack.ENVKEY_SECONDARY_INTERNET)
: undefined,
]);
console.log("Deleting vpc networking CloudFormation stack...");
await Promise.all([
deleteStackAndWait(cfPrimary, CfStack.ENVKEY_VPC_NETWORKING),
]);
console.log(
"Deleting any networking resources that were created dynamically by api..."
);
await Promise.all(
(
[
[ec2Primary, "primary"],
...(ec2Secondary ? [[ec2Secondary, "secondary"]] : []),
] as [EC2, "primary" | "secondary"][]
).map(async ([ec2, region]) => {
const [igwRes, routeTableRes, subnetsRes, securityGroupsRes] =
await Promise.all([
ec2.describeInternetGateways({ Filters: tagFilters }).promise(),
ec2.describeRouteTables({ Filters: tagFilters }).promise(),
ec2.describeSubnets({ Filters: tagFilters }).promise(),
ec2
.describeSecurityGroups({
Filters: [
{
Name: "group-name",
Values: [`envkey-alb-sg-${deploymentTag}`],
},
],
})
.promise(),
]);
const publicRouteTable = (routeTableRes.RouteTables ?? [])[0];
const publicRouteTableId = publicRouteTable?.RouteTableId;
const loadBalancerSubnets = subnetsRes.Subnets ?? [];
const albSecurityGroup = (securityGroupsRes.SecurityGroups ?? [])[0];
for (let igw of igwRes.InternetGateways!) {
if ((igw.Tags ?? []).find(tagFinder)) {
if (publicRouteTableId) {
console.log(`Deleting api-created public route...`);
await ec2
.deleteRoute({
RouteTableId: publicRouteTableId,
DestinationCidrBlock: "0.0.0.0/0",
})
.promise()
.catch((err) => {
console.log("Couldn't delete public route", {
routeTableId: publicRouteTableId,
err,
region,
});
});
}
if (igw.Attachments && igw.Attachments.length > 0) {
console.log(
`Detaching api-created internet gateway in ${region} region...`
);
for (let attachment of igw.Attachments) {
await ec2
.detachInternetGateway({
VpcId: attachment.VpcId!,
InternetGatewayId: igw.InternetGatewayId!,
})
.promise()
.catch((err) => {
console.log("Couldn't detach internet gateway", {
attachment,
igw,
err,
region,
});
});
}
}
console.log(
`Deleting api-created internet gateway in ${region} region...`
);
await ec2
.deleteInternetGateway({
InternetGatewayId: igw.InternetGatewayId!,
})
.promise()
.catch((err) => {
console.log("Couldn't delete internet gateway", {
igw,
err,
region,
});
});
}
}
if (publicRouteTable && loadBalancerSubnets.length > 0) {
console.log(
`Disassociating api-created route table from all subnets in ${region} region...`
);
await Promise.all(
loadBalancerSubnets.map(async (subnet) => {
const association = (publicRouteTable.Associations ?? []).find(
(assoc) => assoc.SubnetId == subnet.SubnetId!
);
if (association) {
return ec2
.disassociateRouteTable({
AssociationId: association.RouteTableAssociationId!,
})
.promise()
.catch((err) => {
console.log("Couldn't disassociate route table", {
association,
err,
region,
});
});
}
})
);
}
if (publicRouteTableId) {
console.log(
`Deleting api-created public route table in ${region} region...`
);
await ec2
.deleteRouteTable({ RouteTableId: publicRouteTableId })
.promise()
.catch((err) => {
console.log("Couldn't delete route table", {
publicRouteTableId,
err,
region,
});
});
}
if (loadBalancerSubnets.length > 0) {
console.log(`Deleting api-created subnets in ${region} region...`);
let numAttempts = 0;
let taggedSubnets = loadBalancerSubnets;
while (numAttempts < 5) {
console.log("Deleting subnets...", { numAttempts });
try {
await Promise.all(
taggedSubnets.map((subnet) =>
ec2.deleteSubnet({ SubnetId: subnet.SubnetId! }).promise()
)
);
break;
} catch (err) {
console.log("Error deleting subnets, retrying in 10s...", {
err,
numAttempts,
region,
});
const res = await ec2
.describeSubnets({ Filters: tagFilters })
.promise();
taggedSubnets = res.Subnets!;
await wait(10000);
numAttempts++;
}
}
}
if (albSecurityGroup) {
console.log(`Deleting alb security group in ${region} region...`);
await ec2
.deleteSecurityGroup({ GroupId: albSecurityGroup.GroupId! })
.promise();
}
})
);
if (ec2Secondary) {
const secondaryVpcRes = await ec2Secondary.describeVpcs().promise();
const secondaryVpc = (secondaryVpcRes.Vpcs ?? []).find((vpc) =>
(vpc.Tags ?? []).find(tagFinder)
);
if (secondaryVpc) {
console.log("Deleting secondary region VPC...");
await ec2Secondary.deleteVpc({ VpcId: secondaryVpc.VpcId! });
}
}
console.log("Deleting all CloudFormation stacks...");
for (const stackBaseName of R.reverse(Object.values(CfStack))) {
const cfClient =
cfSecondary && stackBaseName.includes("-secondary-")
? cfSecondary
: cfPrimary;
const stackName = [stackBaseName, deploymentTag].join("-");
try {
await cfClient
.describeStacks({ StackName: stackName })
.promise()
.catch(() => ({ Stacks: undefined }))
.then(({ Stacks }) => {
if (Stacks && Stacks[0]?.StackId) {
if (dryRun) {
console.log("Stack:\n ", stackName, "\n ", Stacks[0].StackId);
return;
}
console.log("Stack:\n Deleting", stackName, Stacks[0].StackId);
return cfClient
.deleteStack({ StackName: Stacks[0].StackId })
.promise();
}
});
} catch (err) {
console.error(err.message);
failed = true;
}
}
// delete codebuild projects by deploymentTag
const tagProjects = await listCodebuildProjects(codeBuild, deploymentTag);
console.log("Build projects to delete:", tagProjects.length);
for (const name of tagProjects) {
if (dryRun) {
console.log(" Build project:", name);
continue;
}
console.log(" Deleting build project:", name);
try {
await codeBuild
.deleteProject({
name,
})
.promise();
} catch (err) {
console.error(err.message);
failed = failed || !err.message?.includes("does not exist");
}
}
// delete sns topics
try {
const topicArn = getSnsAlertTopicArn(
deploymentTag,
primaryRegion,
awsAccountId
);
if (dryRun) {
console.log("SNS topic:\n ", topicArn);
} else {
console.log("Deleting SNS topic:\n ", topicArn);
await sns.deleteTopic({ TopicArn: topicArn }).promise();
}
} catch (err) {
console.error(err.message);
failed = failed || !err.message?.includes("does not exist");
}
// delete IAM roles
const roleNames: string[] = [];
let marker: string | undefined;
while (true) {
const { Roles: roles, Marker: m } = await iam
.listRoles(marker ? { MaxItems: 100, Marker: marker } : { MaxItems: 100 })
.promise();
marker = m;
const filteredRoles = roles.filter((role) =>
role.RoleName.includes(deploymentTag)
);
roleNames.push(...filteredRoles.map((role) => role.RoleName));
if (!roles.length || !marker) {
break;
}
}
console.log("IAM roles found:", roleNames.length);
for (const roleName of roleNames) {
if (dryRun) {
console.log(" IAM role:", roleName);
continue;
}
console.log(" Deleting iam role", roleName);
try {
await iam.deleteRole({ RoleName: roleName });
} catch (err) {
console.error(err.message);
failed = failed || !err.message?.includes("does not exist");
}
}
// delete all buckets by deploymentTag
try {
// primary
console.log("Primary buckets...");
await dangerouslyDeleteS3BucketsWithConfirm({
s3,
all: true,
force: true,
filterInclude: deploymentTag,
dryRun,
});
} catch (err) {
console.error(err.message);
failed = failed || !err.message?.includes("does not exist");
}
try {
// secondary
console.log("Secondary buckets...");
await dangerouslyDeleteS3BucketsWithConfirm({
s3: s3Secondary,
all: true,
force: true,
filterInclude: deploymentTag,
dryRun,
});
} catch (err) {
console.error(err.message);
failed = failed || !err.message?.includes("does not exist");
}
// delete all secrets by deploymentTag
try {
await dangerouslyDeleteSecretsWithConfirm({
secretsManager,
all: true,
force: true,
filterInclude: deploymentTag,
dryRun,
});
} catch (err) {
console.error(err.message);
failed = failed || !err.message?.includes("does not exist");
}
if (!dryRun && !failed) {
try {
await deleteDeployTag({ profile, primaryRegion, deploymentTag });
} catch (err) {
console.log(err.message);
failed = true;
}
}
return failed;
}; | the_stack |
import { mockAwsRekognition, mockAwsS3 } from './mock';
import fs from 'fs';
import sharp from 'sharp';
import S3 from 'aws-sdk/clients/s3';
import Rekognition from 'aws-sdk/clients/rekognition';
import { ImageHandler } from '../image-handler';
import { BoundingBox, BoxSize, ImageEdits, ImageFormatTypes, ImageHandlerError, ImageRequestInfo, RequestTypes, StatusCodes } from '../lib';
const s3Client = new S3();
const rekognitionClient = new Rekognition();
describe('process()', () => {
beforeEach(() => {
jest.resetAllMocks();
});
afterEach(() => {
jest.clearAllMocks();
});
describe('001/default', () => {
it('Should pass if the output image is different from the input image with edits applied', async () => {
// Arrange
const request: ImageRequestInfo = {
requestType: RequestTypes.DEFAULT,
bucket: 'sample-bucket',
key: 'sample-image-001.jpg',
edits: {
grayscale: true,
flip: true
},
originalImage: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.process(request);
// Assert
expect(result).not.toEqual(request.originalImage);
});
});
describe('002/withToFormat', () => {
it('Should pass if the output image is in a different format than the original image', async () => {
// Arrange
const request: ImageRequestInfo = {
requestType: RequestTypes.DEFAULT,
bucket: 'sample-bucket',
key: 'sample-image-001.jpg',
outputFormat: ImageFormatTypes.PNG,
edits: {
grayscale: true,
flip: true
},
originalImage: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.process(request);
// Assert
expect(result).not.toEqual(request.originalImage);
});
it('Should pass if the output image is webp format and reductionEffort is provided', async () => {
// Arrange
const request: ImageRequestInfo = {
requestType: RequestTypes.DEFAULT,
bucket: 'sample-bucket',
key: 'sample-image-001.jpg',
outputFormat: ImageFormatTypes.WEBP,
reductionEffort: 3,
originalImage: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')
};
jest.spyOn(sharp(), 'webp');
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.process(request);
// Assert
expect(result).not.toEqual(request.originalImage);
});
});
describe('003/noEditsSpecified', () => {
it('Should pass if no edits are specified and the original image is returned', async () => {
// Arrange
const request: ImageRequestInfo = {
requestType: RequestTypes.DEFAULT,
bucket: 'sample-bucket',
key: 'sample-image-001.jpg',
originalImage: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.process(request);
// Assert
expect(result).toEqual(request.originalImage.toString('base64'));
});
});
describe('004/ExceedsLambdaPayloadLimit', () => {
it('Should fail the return payload is larger than 6MB', async () => {
// Arrange
const request: ImageRequestInfo = {
requestType: RequestTypes.DEFAULT,
bucket: 'sample-bucket',
key: 'sample-image-001.jpg',
originalImage: Buffer.alloc(6 * 1024 * 1024)
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
try {
await imageHandler.process(request);
} catch (error) {
// Assert
expect(error).toMatchObject({
status: StatusCodes.REQUEST_TOO_LONG,
code: 'TooLargeImageException',
message: 'The converted image is too large to return.'
});
}
});
});
describe('005/RotateNull', () => {
it('Should pass if rotate is null and return image without EXIF and ICC', async () => {
// Arrange
const originalImage = fs.readFileSync('./test/image/1x1.jpg');
const request: ImageRequestInfo = {
requestType: RequestTypes.DEFAULT,
bucket: 'sample-bucket',
key: 'test.jpg',
edits: {
rotate: null
},
originalImage: originalImage
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.process(request);
// Assert
const metadata = await sharp(Buffer.from(result, 'base64')).metadata();
expect(metadata).not.toHaveProperty('exif');
expect(metadata).not.toHaveProperty('icc');
expect(metadata).not.toHaveProperty('orientation');
});
});
describe('006/ImageOrientation', () => {
it('Should pass if the original image has orientation', async () => {
// Arrange
const originalImage = fs.readFileSync('./test/image/1x1.jpg');
const request: ImageRequestInfo = {
requestType: RequestTypes.DEFAULT,
bucket: 'sample-bucket',
key: 'test.jpg',
edits: {
resize: {
width: 100,
height: 100
}
},
originalImage: originalImage
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.process(request);
// Assert
const metadata = await sharp(Buffer.from(result, 'base64')).metadata();
expect(metadata).toHaveProperty('icc');
expect(metadata).toHaveProperty('exif');
expect(metadata.orientation).toEqual(3);
});
});
describe('007/ImageWithoutOrientation', () => {
it('Should pass if the original image does not have orientation', async () => {
// Arrange
const request: ImageRequestInfo = {
requestType: RequestTypes.DEFAULT,
bucket: 'sample-bucket',
key: 'test.jpg',
edits: {
resize: {
width: 100,
height: 100
}
},
originalImage: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.process(request);
// Assert
const metadata = await sharp(Buffer.from(result, 'base64')).metadata();
expect(metadata).not.toHaveProperty('orientation');
});
});
});
describe('applyEdits()', () => {
describe('001/standardEdits', () => {
it('Should pass if a series of standard edits are provided to the function', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const edits: ImageEdits = {
grayscale: true,
flip: true
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
/* eslint-disable dot-notation */
const expectedResult1 = result['options'].greyscale;
const expectedResult2 = result['options'].flip;
const combinedResults = expectedResult1 && expectedResult2;
expect(combinedResults).toEqual(true);
});
});
describe('002/overlay', () => {
it('Should pass if an edit with the overlayWith keyname is passed to the function', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const edits: ImageEdits = {
overlayWith: {
bucket: 'aaa',
key: 'bbb'
}
};
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({ Body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64') });
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'aaa', Key: 'bbb' });
expect(result['options'].input.buffer).toEqual(originalImage);
});
});
describe('003/overlay/options/smallerThanZero', () => {
it('Should pass if an edit with the overlayWith keyname is passed to the function', async () => {
// Arrange
const originalImage = Buffer.from(
'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAEAAQDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACv/EABQQAQAAAAAAAAAAAAAAAAAAAAD/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AfwD/2Q==',
'base64'
);
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const edits: ImageEdits = {
overlayWith: {
bucket: 'aaa',
key: 'bbb',
options: {
left: '-1',
top: '-1'
}
}
};
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({ Body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64') });
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'aaa', Key: 'bbb' });
expect(result['options'].input.buffer).toEqual(originalImage);
});
});
describe('004/overlay/options/greaterThanZero', () => {
it('Should pass if an edit with the overlayWith keyname is passed to the function', async () => {
// Arrange
const originalImage = Buffer.from(
'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAEAAQDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACv/EABQQAQAAAAAAAAAAAAAAAAAAAAD/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AfwD/2Q==',
'base64'
);
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const edits: ImageEdits = {
overlayWith: {
bucket: 'aaa',
key: 'bbb',
options: {
left: '1',
top: '1'
}
}
};
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({ Body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64') });
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'aaa', Key: 'bbb' });
expect(result['options'].input.buffer).toEqual(originalImage);
});
});
describe('005/overlay/options/percentage/greaterThanZero', () => {
it('Should pass if an edit with the overlayWith keyname is passed to the function', async () => {
// Arrange
const originalImage = Buffer.from(
'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAEAAQDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACv/EABQQAQAAAAAAAAAAAAAAAAAAAAD/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AfwD/2Q==',
'base64'
);
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const edits: ImageEdits = {
overlayWith: {
bucket: 'aaa',
key: 'bbb',
options: {
left: '50p',
top: '50p'
}
}
};
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({ Body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64') });
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'aaa', Key: 'bbb' });
expect(result['options'].input.buffer).toEqual(originalImage);
});
it('Should pass if an edit with the overlayWith keyname contains position which could produce float number', async () => {
// Arrange
const originalImage = fs.readFileSync('./test/image/25x15.png');
const overlayImage = fs.readFileSync('./test/image/1x1.jpg');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const edits: ImageEdits = {
overlayWith: {
bucket: 'bucket',
key: 'key',
options: {
left: '25.5p',
top: '25.5p'
}
}
};
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({ Body: overlayImage });
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
const metadata = await result.metadata();
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'aaa', Key: 'bbb' });
expect(metadata.width).toEqual(25);
expect(metadata.height).toEqual(15);
expect(result.toBuffer()).not.toEqual(originalImage);
});
});
describe('006/overlay/options/percentage/smallerThanZero', () => {
it('Should pass if an edit with the overlayWith keyname is passed to the function', async () => {
// Arrange
const originalImage = Buffer.from(
'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAEAAQDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACv/EABQQAQAAAAAAAAAAAAAAAAAAAAD/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AfwD/2Q==',
'base64'
);
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const edits: ImageEdits = {
overlayWith: {
bucket: 'aaa',
key: 'bbb',
options: {
left: '-50p',
top: '-50p'
}
}
};
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({ Body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64') });
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'aaa', Key: 'bbb' });
expect(result['options'].input.buffer).toEqual(originalImage);
});
});
describe('007/smartCrop', () => {
it('Should pass if an edit with the smartCrop keyname is passed to the function', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const buffer = await image.toBuffer();
const edits: ImageEdits = {
smartCrop: {
faceIndex: 0,
padding: 0
}
};
// Mock
mockAwsRekognition.detectFaces.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
FaceDetails: [
{
BoundingBox: {
Height: 0.18,
Left: 0.55,
Top: 0.33,
Width: 0.23
}
}
]
});
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: buffer } });
expect(result['options'].input).not.toEqual(originalImage);
});
});
describe('008/smartCrop/paddingOutOfBoundsError', () => {
it('Should pass if an excessive padding value is passed to the smartCrop filter', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const buffer = await image.toBuffer();
const edits: ImageEdits = {
smartCrop: {
faceIndex: 0,
padding: 80
}
};
// Mock
mockAwsRekognition.detectFaces.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
FaceDetails: [
{
BoundingBox: {
Height: 0.18,
Left: 0.55,
Top: 0.33,
Width: 0.23
}
}
]
});
}
}));
// Act
try {
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
await imageHandler.applyEdits(image, edits);
} catch (error) {
// Assert
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: buffer } });
expect(error).toMatchObject({
status: StatusCodes.BAD_REQUEST,
code: 'SmartCrop::PaddingOutOfBounds',
message:
'The padding value you provided exceeds the boundaries of the original image. Please try choosing a smaller value or applying padding via Sharp for greater specificity.'
});
}
});
});
describe('009/smartCrop/boundingBoxError', () => {
it('Should pass if an excessive faceIndex value is passed to the smartCrop filter', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const buffer = await image.toBuffer();
const edits: ImageEdits = {
smartCrop: {
faceIndex: 10,
padding: 0
}
};
// Mock
mockAwsRekognition.detectFaces.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
FaceDetails: [
{
BoundingBox: {
Height: 0.18,
Left: 0.55,
Top: 0.33,
Width: 0.23
}
}
]
});
}
}));
// Act
try {
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
await imageHandler.applyEdits(image, edits);
} catch (error) {
// Assert
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: buffer } });
expect(error).toMatchObject({
status: StatusCodes.BAD_REQUEST,
code: 'SmartCrop::FaceIndexOutOfRange',
message: 'You have provided a FaceIndex value that exceeds the length of the zero-based detectedFaces array. Please specify a value that is in-range.'
});
}
});
});
describe('010/smartCrop/faceIndexUndefined', () => {
it('Should pass if a faceIndex value of undefined is passed to the smartCrop filter', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const buffer = await image.toBuffer();
const edits: ImageEdits = {
smartCrop: true
};
// Mock
mockAwsRekognition.detectFaces.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
FaceDetails: [
{
BoundingBox: {
Height: 0.18,
Left: 0.55,
Top: 0.33,
Width: 0.23
}
}
]
});
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: buffer } });
expect(result['options'].input).not.toEqual(originalImage);
});
});
describe('011/resizeStringTypeNumber', () => {
it('Should pass if resize width and height are provided as string number to the function', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const edits: ImageEdits = {
resize: {
width: '99.1',
height: '99.9'
}
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
const resultBuffer = await result.toBuffer();
const convertedImage = await sharp(originalImage, { failOnError: false }).withMetadata().resize({ width: 99, height: 100 }).toBuffer();
expect(resultBuffer).toEqual(convertedImage);
});
});
describe('012/roundCrop/noOptions', () => {
it('Should pass if roundCrop keyName is passed with no additional options', async () => {
// Arrange
const originalImage = Buffer.from(
'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAEAAQDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACv/EABQQAQAAAAAAAAAAAAAAAAAAAAD/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AfwD/2Q==',
'base64'
);
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const metadata = await image.metadata();
const edits: ImageEdits = {
roundCrop: true
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
const expectedResult: ImageEdits = { width: metadata.width / 2, height: metadata.height / 2 };
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'aaa', Key: 'bbb' });
expect(result['options'].input).not.toEqual(expectedResult);
});
});
describe('013/roundCrop/withOptions', () => {
it('Should pass if roundCrop keyName is passed with additional options', async () => {
// Arrange
const originalImage = Buffer.from(
'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAEAAQDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACv/EABQQAQAAAAAAAAAAAAAAAAAAAAD/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AfwD/2Q==',
'base64'
);
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const metadata = await image.metadata();
const edits: ImageEdits = {
roundCrop: {
top: 100,
left: 100,
rx: 100,
ry: 100
}
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
const expectedResult: ImageEdits = { width: metadata.width / 2, height: metadata.height / 2 };
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'aaa', Key: 'bbb' });
expect(result['options'].input).not.toEqual(expectedResult);
});
});
describe('014/contentModeration', () => {
it('Should pass and blur image with minConfidence provided', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const buffer = await image.toBuffer();
const edits: ImageEdits = {
contentModeration: {
minConfidence: 75
}
};
// Mock
mockAwsRekognition.detectModerationLabels.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
ModerationLabels: [
{
Confidence: 99.76720428466,
Name: 'Smoking',
ParentName: 'Tobacco'
},
{ Confidence: 99.76720428466, Name: 'Tobacco', ParentName: '' }
],
ModerationModelVersion: '4.0'
});
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
const expected = image.blur(50);
// Assert
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: buffer } });
expect(result['options'].input).not.toEqual(originalImage);
expect(result).toEqual(expected);
});
it('should pass and blur to specified amount if blur option is provided', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const buffer = await image.toBuffer();
const edits: ImageEdits = {
contentModeration: {
minConfidence: 75,
blur: 100
}
};
// Mock
mockAwsRekognition.detectModerationLabels.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
ModerationLabels: [
{
Confidence: 99.76720428466,
Name: 'Smoking',
ParentName: 'Tobacco'
},
{ Confidence: 99.76720428466, Name: 'Tobacco', ParentName: '' }
],
ModerationModelVersion: '4.0'
});
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
const expected = image.blur(100);
// Assert
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: buffer } });
expect(result['options'].input).not.toEqual(originalImage);
expect(result).toEqual(expected);
});
it('should pass and blur if content moderation label matches specified moderation label', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const buffer = await image.toBuffer();
const edits: ImageEdits = {
contentModeration: {
moderationLabels: ['Smoking']
}
};
// Mock
mockAwsRekognition.detectModerationLabels.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
ModerationLabels: [
{
Confidence: 99.76720428466,
Name: 'Smoking',
ParentName: 'Tobacco'
},
{ Confidence: 99.76720428466, Name: 'Tobacco', ParentName: '' }
],
ModerationModelVersion: '4.0'
});
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
const expected = image.blur(50);
// Assert
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: buffer } });
expect(result['options'].input).not.toEqual(originalImage);
expect(result).toEqual(expected);
});
it('should not blur if provided moderationLabels not found', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const buffer = await image.toBuffer();
const edits: ImageEdits = {
contentModeration: {
minConfidence: 75,
blur: 100,
moderationLabels: ['Alcohol']
}
};
// Mock
mockAwsRekognition.detectModerationLabels.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
ModerationLabels: [
{
Confidence: 99.76720428466,
Name: 'Smoking',
ParentName: 'Tobacco'
},
{ Confidence: 99.76720428466, Name: 'Tobacco', ParentName: '' }
],
ModerationModelVersion: '4.0'
});
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.applyEdits(image, edits);
// Assert
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: buffer } });
expect(result).toEqual(image);
});
it('should fail if rekognition returns an error', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const buffer = await image.toBuffer();
const edits: ImageEdits = {
contentModeration: {
minConfidence: 75,
blur: 100
}
};
// Mock
mockAwsRekognition.detectModerationLabels.mockImplementationOnce(() => ({
promise() {
return Promise.reject(
new ImageHandlerError(StatusCodes.INTERNAL_SERVER_ERROR, 'InternalServerError', 'Amazon Rekognition experienced a service issue. Try your call again.')
);
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
try {
await imageHandler.applyEdits(image, edits);
} catch (error) {
// Assert
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: buffer } });
expect(error).toMatchObject({
status: StatusCodes.INTERNAL_SERVER_ERROR,
code: 'InternalServerError',
message: 'Amazon Rekognition experienced a service issue. Try your call again.'
});
}
});
});
describe('015/crop/areaOutOfBoundsError', () => {
it('Should pass if a cropping area value is out of bounds', async () => {
// Arrange
const originalImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
const image = sharp(originalImage, { failOnError: false }).withMetadata();
const edits: ImageEdits = {
crop: {
left: 0,
right: 0,
width: 100,
height: 100
}
};
// Act
try {
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
await imageHandler.applyEdits(image, edits);
} catch (error) {
// Assert
expect(error).toMatchObject({
status: StatusCodes.BAD_REQUEST,
code: 'Crop::AreaOutOfBounds',
message: 'The cropping area you provided exceeds the boundaries of the original image. Please try choosing a correct cropping value.'
});
}
});
});
});
describe('getOverlayImage()', () => {
describe('001/validParameters', () => {
it('Should pass if the proper bucket name and key are supplied, simulating an image file that can be retrieved', async () => {
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({ Body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64') });
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const metadata = await sharp(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')).metadata();
const result = await imageHandler.getOverlayImage('validBucket', 'validKey', '100', '100', '20', metadata);
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'validBucket', Key: 'validKey' });
expect(result).toEqual(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACXBIWXMAAAsTAAALEwEAmpwYAAAADUlEQVQI12P4z8CQCgAEZgFlTg0nBwAAAABJRU5ErkJggg==', 'base64'));
});
it('Should pass and do not throw an exception that the overlay image dimensions are not integer numbers', async () => {
// Mock
const originalImage = fs.readFileSync('./test/image/25x15.png');
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({ Body: originalImage });
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const originalImageMetadata = await sharp(originalImage).metadata();
const result = await imageHandler.getOverlayImage('bucket', 'key', '75', '75', '20', originalImageMetadata);
const overlayImageMetadata = await sharp(result).metadata();
// Assert
expect(overlayImageMetadata.width).toEqual(18);
expect(overlayImageMetadata.height).toEqual(11);
});
});
describe('002/imageDoesNotExist', () => {
it('Should throw an error if an invalid bucket or key name is provided, simulating a nonexistent overlay image', async () => {
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.reject(new ImageHandlerError(StatusCodes.INTERNAL_SERVER_ERROR, 'InternalServerError', 'SimulatedInvalidParameterException'));
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const metadata = await sharp(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')).metadata();
try {
await imageHandler.getOverlayImage('invalidBucket', 'invalidKey', '100', '100', '20', metadata);
} catch (error) {
// Assert
expect(mockAwsS3.getObject).toHaveBeenCalledWith({ Bucket: 'invalidBucket', Key: 'invalidKey' });
expect(error).toMatchObject({
status: StatusCodes.INTERNAL_SERVER_ERROR,
code: 'InternalServerError',
message: 'SimulatedInvalidParameterException'
});
}
});
});
});
describe('getCropArea()', () => {
describe('001/validParameters', () => {
it('Should pass if the crop area can be calculated using a series of valid inputs/parameters', () => {
// Arrange
const boundingBox: BoundingBox = {
height: 0.18,
left: 0.55,
top: 0.33,
width: 0.23
};
const metadata: BoxSize = {
width: 200,
height: 400
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = imageHandler.getCropArea(boundingBox, 20, metadata);
// Assert
const expectedResult: BoundingBox = {
left: 90,
top: 112,
width: 86,
height: 112
};
expect(result).toEqual(expectedResult);
});
});
describe('002/validParameters and out of range', () => {
it('Should pass if the crop area is beyond the range of the image after padding is applied', () => {
// Arrange
const boundingBox: BoundingBox = {
height: 0.18,
left: 0.55,
top: 0.33,
width: 0.23
};
const metadata: BoxSize = {
width: 200,
height: 400
};
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = imageHandler.getCropArea(boundingBox, 500, metadata);
// Assert
const expectedResult: BoundingBox = {
left: 0,
top: 0,
width: 200,
height: 400
};
expect(result).toEqual(expectedResult);
});
});
});
describe('getBoundingBox()', () => {
describe('001/validParameters', () => {
it('Should pass if the proper parameters are passed to the function', async () => {
// Arrange
const currentImage = Buffer.from('TestImageData');
const faceIndex = 0;
// Mock
mockAwsRekognition.detectFaces.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
FaceDetails: [
{
BoundingBox: {
Height: 0.18,
Left: 0.55,
Top: 0.33,
Width: 0.23
}
}
]
});
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.getBoundingBox(currentImage, faceIndex);
// Assert
const expectedResult: BoundingBox = {
height: 0.18,
left: 0.55,
top: 0.33,
width: 0.23
};
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: currentImage } });
expect(result).toEqual(expectedResult);
});
});
describe('002/errorHandling', () => {
it('Should simulate an error condition returned by Rekognition', async () => {
// Arrange
const currentImage = Buffer.from('NotTestImageData');
const faceIndex = 0;
// Mock
mockAwsRekognition.detectFaces.mockImplementationOnce(() => ({
promise() {
return Promise.reject(new ImageHandlerError(StatusCodes.INTERNAL_SERVER_ERROR, 'InternalServerError', 'SimulatedError'));
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
try {
await imageHandler.getBoundingBox(currentImage, faceIndex);
} catch (error) {
// Assert
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: currentImage } });
expect(error).toMatchObject({
status: StatusCodes.INTERNAL_SERVER_ERROR,
code: 'InternalServerError',
message: 'SimulatedError'
});
}
});
});
describe('003/noDetectedFaces', () => {
it('Should pass if no faces are detected', async () => {
// Arrange
const currentImage = Buffer.from('TestImageData');
const faceIndex = 0;
// Mock
mockAwsRekognition.detectFaces.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
FaceDetails: []
});
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.getBoundingBox(currentImage, faceIndex);
// Assert
const expectedResult: BoundingBox = {
height: 1,
left: 0,
top: 0,
width: 1
};
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: currentImage } });
expect(result).toEqual(expectedResult);
});
});
describe('004/boundsGreaterThanImageDimensions', () => {
it('Should pass if bounds detected go beyond the image dimensions', async () => {
// Arrange
const currentImage = Buffer.from('TestImageData');
const faceIndex = 0;
// Mock
mockAwsRekognition.detectFaces.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({
FaceDetails: [
{
BoundingBox: {
Height: 1,
Left: 0.5,
Top: 0.3,
Width: 0.65
}
}
]
});
}
}));
// Act
const imageHandler = new ImageHandler(s3Client, rekognitionClient);
const result = await imageHandler.getBoundingBox(currentImage, faceIndex);
// Assert
const expectedResult: BoundingBox = {
height: 0.7,
left: 0.5,
top: 0.3,
width: 0.5
};
expect(mockAwsRekognition.detectFaces).toHaveBeenCalledWith({ Image: { Bytes: currentImage } });
expect(result).toEqual(expectedResult);
});
});
}); | the_stack |
import { StatusCode, StatusCodes } from "node-opcua-status-code";
import { BrowseResultOptions, ReferenceDescription } from "node-opcua-types";
import {
ContinuationPoint,
IContinuationPointManager,
IContinuationPointInfo,
ContinuationData
} from "node-opcua-address-space-base";
import { DataValue } from "node-opcua-data-value";
import { runInThisContext } from "vm";
/**
* from https://reference.opcfoundation.org/v104/Core/docs/Part4/7.6/
*
* A ContinuationPoint is used to pause a Browse, QueryFirst or HistoryRead operation and allow it to be restarted later by calling BrowseNext,
* QueryNext or HistoryRead.
* - Operations are paused when the number of results found exceeds the limits set by either the Client or the Server.
* - The Client specifies the maximum number of results per operation in the request message.
* - A Server shall not return more than this number of results but it may return fewer results.
* - The Server allocates a ContinuationPoint if there are more results to return.
* - Servers shall support at least one ContinuationPoint per Session.
* - Servers specify a maximum number of ContinuationPoints per Session in the ServerCapabilities Object defined in OPC 10000-5.
* - ContinuationPoints remain active until
* a/ the Client retrieves the remaining results,
* b/ or, the Client releases the ContinuationPoint
* c/ or the Session is closed.
* - A Server shall automatically free ContinuationPoints from prior requests from a Session if they are needed to process a new request
* from this Session.
* - The Server returns a Bad_ContinuationPointInvalid error if a Client tries to use a ContinuationPoint that has been released.
* - A Client can avoid this situation by completing paused operations before starting new operations.
* - Requests will often specify multiple operations that may or may not require a ContinuationPoint.
* - A Server shall process the operations until it uses the maximum number of continuation points in this response.
* Once that happens the Server shall return a Bad_NoContinuationPoints error for any remaining operations. A Client can avoid
* this situation by sending requests with a number of operations that do not exceed the maximum number of ContinuationPoints
* per Session defined for the Service in the ServerCapabilities Object defined in OPC 10000-5.
* A Client restarts an operation by passing the ContinuationPoint back to the Server. Server should always be able to reuse the ContinuationPoint
* provided so Servers shall never return Bad_NoContinuationPoints error when continuing a previously halted operation.
* A ContinuationPoint is a subtype of the ByteString data type.
*
*
* for historical access: https://reference.opcfoundation.org/v104/Core/docs/Part11/6.3/
*
* The continuationPoint parameter in the HistoryRead Service is used to mark a point from which to continue
* the read if not all values could be returned in one response. The value is opaque for the Client and is
* only used to maintain the state information for the Server to continue from. *
*
* For HistoricalDataNode requests, a Server may use the timestamp of the last returned data item if the timestamp
* is unique. This can reduce the need in the Server to store state information for the continuation point.
* The Client specifies the maximum number of results per operation in the request Message. A Server shall
* not return more than this number of results but it may return fewer results. The Server allocates a
* ContinuationPoint if there are more results to return. The Server may return fewer results due to buffer issues
* or other internal constraints. It may also be required to return a continuationPoint due to HistoryRead
* parameter constraints. If a request is taking a long time to calculate and is approaching the timeout time, the
* Server may return partial results with a continuation point. This may be done if the calculation is going to
* take more time than the Client timeout. In some cases it may take longer than the Client timeout to calculate
* even one result. Then the Server may return zero results with a continuation point that allows the Server to
* resume the calculation on the next Client read call. For additional discussions regarding ContinuationPoints
* and HistoryRead please see the individual extensible HistoryReadDetails parameter in 6.4.
* If the Client specifies a ContinuationPoint, then the HistoryReadDetails parameter and the TimestampsToReturn
* parameter are ignored, because it does not make sense to request different parameters when continuing from a
* previous call. It is permissible to change the dataEncoding parameter with each request.
* If the Client specifies a ContinuationPoint that is no longer valid, then the Server shall return a
* Bad_ContinuationPointInvalid error.
* If the releaseContinuationPoints parameter is set in the request the Server shall not return any data and shall
* release all ContinuationPoints passed in the request. If the ContinuationPoint for an operation is missing or
* invalid then the StatusCode for the operation shall be Bad_ContinuationPointInvalid.
*/
let counter = 0;
function make_key() {
// return crypto.randomBytes(32);
counter += 1;
return Buffer.from(counter.toString(), "ascii");
}
interface Data {
maxElements: number;
values: ReferenceDescription[] | DataValue[];
}
export class ContinuationPointManager implements IContinuationPointManager {
private _map: Map<string, Data>;
constructor() {
this._map = new Map();
}
/**
* returns true if the current number of active continuation point has reached the limit
* specified in maxContinuationPoint
* @param maxBrowseContinuationPoint
*/
public hasReachedMaximum(maxContinuationPoint: number): boolean {
if (maxContinuationPoint === 0) {
return false;
}
const nbContinuationPoints = this._map.size;
return nbContinuationPoints >= maxContinuationPoint;
}
public clearContinuationPoints() {
// call when a new request to the server is received
this._map.clear();
}
public registerHistoryReadRaw(
numValuesPerNode: number,
dataValues: DataValue[],
continuationData: ContinuationData
): IContinuationPointInfo<DataValue> {
return this._register(numValuesPerNode, dataValues, continuationData);
}
public getNextHistoryReadRaw(numValues: number, continuationData: ContinuationData): IContinuationPointInfo<DataValue> {
return this._getNext(numValues, continuationData);
}
registerReferences(
maxElements: number,
values: ReferenceDescription[],
continuationData: ContinuationData
): IContinuationPointInfo<ReferenceDescription> {
return this._register(maxElements, values, continuationData);
}
/**
* - releaseContinuationPoints = TRUE
*
* passed continuationPoints shall be reset to free resources in
* the Server. The continuation points are released and the results
* and diagnosticInfos arrays are empty.
*
* - releaseContinuationPoints = FALSE
*
* passed continuationPoints shall be used to get the next set of
* browse information
*/
getNextReferences(numValues: number, continuationData: ContinuationData): IContinuationPointInfo<ReferenceDescription> {
return this._getNext(numValues, continuationData);
}
private _register<T extends DataValue | ReferenceDescription>(
maxValues: number,
values: T[],
continuationData: ContinuationData
): IContinuationPointInfo<T> {
if (continuationData.releaseContinuationPoints) {
this.clearContinuationPoints();
return {
continuationPoint: undefined,
values: [],
statusCode: StatusCodes.Good
};
}
if (!continuationData.continuationPoint && !continuationData.index) {
this.clearContinuationPoints();
}
if (maxValues >= 1) {
// now make sure that only the requested number of value is returned
if (values.length === 0) {
return {
continuationPoint: undefined,
values: null,
statusCode: StatusCodes.GoodNoData
};
}
}
maxValues = maxValues || values.length;
if (maxValues >= values.length) {
return {
continuationPoint: undefined,
values,
statusCode: StatusCodes.Good
};
}
// split the array in two ( values)
const current_block = values.splice(0, maxValues);
const key = make_key();
const keyHash = key.toString("ascii");
const result = {
continuationPoint: key,
values: current_block,
statusCode: StatusCodes.Good
};
// create
const data: Data = {
maxElements: maxValues,
values: values as DataValue[] | ReferenceDescription[]
};
this._map.set(keyHash, data);
return result;
}
private _getNext<T extends DataValue | ReferenceDescription>(
numValues: number,
continuationData: ContinuationData
): IContinuationPointInfo<T> {
if (!continuationData.continuationPoint) {
return {
continuationPoint: undefined,
values: null,
statusCode: StatusCodes.BadContinuationPointInvalid
};
}
const keyHash = continuationData.continuationPoint.toString("ascii");
const data = this._map.get(keyHash);
if (!data) {
return {
continuationPoint: undefined,
values: null,
statusCode: StatusCodes.BadContinuationPointInvalid
};
}
const values = data.values.splice(0, numValues || data.maxElements) as T[];
let continuationPoint: ContinuationPoint | undefined = continuationData.continuationPoint;
if (data.values.length === 0 || continuationData.releaseContinuationPoints) {
// no more data available for next call
this._map.delete(keyHash);
continuationPoint = undefined;
}
return {
continuationPoint,
values,
statusCode: StatusCodes.Good
};
}
} | the_stack |
import { Widget } from '@lumino/widgets';
import { DocumentRegistry } from '@jupyterlab/docregistry';
import { PromiseDelegate, UUID } from '@lumino/coreutils';
import { PathExt } from '@jupyterlab/coreutils';
import Papa from 'papaparse';
import { Message } from '@lumino/messaging';
import jexcel from 'jexcel';
import { Signal } from '@lumino/signaling';
import { ICellCoordinates } from './searchprovider';
type columnTypeId =
| 'autocomplete'
| 'calendar'
| 'checkbox'
| 'color'
| 'dropdown'
| 'hidden'
| 'html'
| 'image'
| 'numeric'
| 'radio'
| 'text';
export interface ISelection {
rows: number;
columns: number;
}
/**
* An spreadsheet widget.
*/
export class SpreadsheetWidget extends Widget {
/**
* Construct a new Spreadsheet widget.
*/
public jexcel: jexcel.JExcelElement;
protected separator: string;
protected linebreak: string;
public fitMode: 'all-equal-default' | 'all-equal-fit' | 'fit-cells';
public changed: Signal<this, void>;
protected hasFrozenColumns: boolean;
private editor: HTMLDivElement;
private container: HTMLDivElement;
private columnTypesBar: HTMLDivElement;
private selectAllElement: HTMLElement;
protected firstRowAsHeader: boolean;
private header: Array<string>;
private columnTypes: Array<columnTypeId>;
public selectionChanged: Signal<SpreadsheetWidget, ISelection>;
constructor(context: DocumentRegistry.CodeContext) {
super();
this.id = UUID.uuid4();
this.title.label = PathExt.basename(context.localPath);
this.title.closable = true;
this.context = context;
this.separator = ''; // Papa auto detect
this.fitMode = 'all-equal-default';
if (context.localPath.endsWith('tsv')) {
this.separator = '\t';
}
if (context.localPath.endsWith('csv')) {
this.separator = ',';
}
this.hasFrozenColumns = false;
this.firstRowAsHeader = false;
context.ready
.then(() => {
this._onContextReady();
})
.catch(console.warn);
this.changed = new Signal<this, void>(this);
this._selection = {
rows: 0,
columns: 0
};
this.selectionChanged = new Signal(this);
}
protected parseValue(content: string): jexcel.CellValue[][] {
const parsed = Papa.parse<string[]>(content, { delimiter: this.separator });
if (!this.separator) {
this.separator = parsed.meta.delimiter;
}
this.linebreak = parsed.meta.linebreak;
if (parsed.errors.length) {
console.warn('Parsing errors encountered', parsed.errors);
}
const columnsNumber = this.extractColumnNumber(parsed.data);
// TODO: read the actual type from a file?
// TODO only redefine if reading for the first time?
// TODO add/remove when column added removed?
if (typeof this.columnTypes === 'undefined') {
this.columnTypes = [
...Array(columnsNumber).map(() => 'text' as columnTypeId)
];
}
if (this.firstRowAsHeader) {
this.header = parsed.data.shift();
} else {
this.header = null;
}
return parsed.data;
}
extractColumnNumber(data: jexcel.CellValue[][]): number {
return data.length ? data[0].length : 0;
}
columns(columnsNumber: number) {
const columns: Array<jexcel.Column> = [];
for (let i = 0; i < columnsNumber; i++) {
columns.push({
title: this.header ? this.header[i] : null,
type: this.columnTypes[i]
});
}
return columns;
}
private onChange(): void {
this.context.model.value.text = this.getValue();
this.changed.emit();
}
public get selection(): ISelection {
return this._selection;
}
private _selection: ISelection;
private _onContextReady(): void {
if (this.isDisposed) {
return;
}
const contextModel = this.context.model;
// Set the editor model value.
const content = contextModel.toString();
const data = this.parseValue(content);
const options: jexcel.Options = {
data: data,
minDimensions: [1, 1],
// minSpareCols: 1,
// minSpareRows: 1,
csvFileName: this.title.label,
columnDrag: true,
onchange: () => {
this.onChange();
},
// insert
oninsertrow: () => {
this.onChange();
},
oninsertcolumn: () => {
this.onChange();
this.populateColumnTypesBar();
this.onResize();
},
// move
onmoverow: () => {
this.onChange();
},
onmovecolumn: () => {
this.onChange();
},
// delete
ondeleterow: () => {
this.onChange();
},
ondeletecolumn: () => {
this.onChange();
this.populateColumnTypesBar();
this.onResize();
},
// resize
onresizecolumn: () => {
this.adjustColumnTypesWidth();
},
onselection: (
el: HTMLElement,
borderLeft: number,
borderTop: number,
borderRight: number,
borderBottom: number,
origin: any
) => {
this._selection = {
rows: borderBottom - borderTop + 1,
columns: borderRight - borderLeft + 1
};
this.selectionChanged.emit(this._selection);
// TODO: support all corners of selection
this.scrollCellIntoView({ column: borderLeft, row: borderTop });
},
columns: this.columns(this.extractColumnNumber(data))
};
const container = document.createElement('div');
container.className = 'se-area-container';
this.node.appendChild(container);
// TODO: move to a separate class/widget
this.columnTypesBar = document.createElement('div');
this.columnTypesBar.classList.add('se-column-types');
this.columnTypesBar.classList.add('se-hidden');
this.columnTypeSelectors = new Map();
container.appendChild(this.columnTypesBar);
this.editor = document.createElement('div');
container.appendChild(this.editor);
this.container = container;
this.createEditor(options);
// Wire signal connections.
contextModel.contentChanged.connect(this._onContentChanged, this);
this.populateColumnTypesBar();
// If the sheet is not too big, use the more user-friendly columns width adjustment model
if (data.length && data[0].length * data.length < 100 * 100) {
this.fitMode = 'fit-cells';
this.relayout();
}
// Resolve the ready promise.
this._ready.resolve(undefined);
}
reloadEditor(options: jexcel.Options) {
const config = this.jexcel.getConfig();
this.jexcel.destroy();
this.createEditor({
...config,
...options
});
this.relayout();
}
switchHeaders() {
const value = this.getValue();
this.firstRowAsHeader = !this.firstRowAsHeader;
const data = this.parseValue(value);
this.reloadEditor({
data: data,
columns: this.columns(this.extractColumnNumber(data))
});
}
switchTypesBar() {
this.columnTypesBar.classList.toggle('se-hidden');
}
columnTypeSelectors: Map<number, HTMLSelectElement>;
protected populateColumnTypesBar() {
// TODO: interface with name, id, options callback?
const options = [
'text',
'numeric',
'hidden',
'dropdown',
'autocomplete',
'checkbox',
'radio',
'calendar',
'image',
'color',
'html'
];
this.columnTypesBar.innerHTML = '';
this.columnTypeSelectors.clear();
for (let columnId = 0; columnId < this.columnsNumber; columnId++) {
// TODO react widget
const columnTypeSelector = document.createElement('select');
for (const option of options) {
const optionElement = document.createElement('option');
optionElement.value = option;
optionElement.text = option;
columnTypeSelector.appendChild(optionElement);
}
columnTypeSelector.onchange = ev => {
const select = ev.target as HTMLSelectElement;
this.columnTypes[columnId] = select.options[select.selectedIndex]
.value as columnTypeId;
this.reloadEditor({ columns: this.columns(this.columnTypes.length) });
};
this.columnTypeSelectors.set(columnId, columnTypeSelector);
this.columnTypesBar.appendChild(columnTypeSelector);
}
}
protected adjustColumnTypesWidth() {
if (this.columnTypeSelectors.size === 0) {
return;
}
this.columnTypesBar.style.marginLeft =
this.selectAllElement.offsetWidth + 'px';
const widths = this.jexcel.getWidth(null);
for (let columnId = 0; columnId < this.columnsNumber; columnId++) {
this.columnTypeSelectors.get(columnId).style.width =
widths[columnId] + 'px';
}
}
protected createEditor(options: jexcel.Options) {
this.jexcel = jexcel(this.editor, options);
this.selectAllElement = this.jexcel.headerContainer.querySelector(
'.jexcel_selectall'
);
}
protected onAfterShow(msg: Message) {
super.onAfterShow(msg);
this.relayout();
}
get ready(): Promise<void> {
return this._ready.promise;
}
getValue(): string {
const data = this.jexcel.getData();
if (this.firstRowAsHeader) {
data.unshift(this.jexcel.getHeaders(true));
}
return Papa.unparse(data, {
delimiter: this.separator,
newline: this.linebreak
});
}
setValue(value: string) {
const parsed = this.parseValue(value);
this.jexcel.setData(parsed);
}
private _onContentChanged(): void {
const oldValue = this.getValue();
const newValue = this.context.model.toString();
if (oldValue !== newValue) {
this.setValue(newValue);
}
}
get wrapper() {
if (this.hasFrozenColumns) {
return this.jexcel.content;
}
return this.container;
}
onResize() {
if (typeof this.jexcel === 'undefined') {
return;
}
if (this.fitMode === 'all-equal-fit') {
this.relayout();
}
if (this.hasFrozenColumns) {
this.jexcel.content.style.width = this.node.offsetWidth + 'px';
this.jexcel.content.style.height =
(this.node.querySelector('.jexcel_content') as HTMLElement)
.offsetHeight + 'px';
}
this.adjustColumnTypesWidth();
}
protected onActivateRequest(msg: Message): void {
// ensure focus
this.jexcel.el.focus();
}
dispose(): void {
if (this.jexcel) {
this.jexcel.destroy();
}
super.dispose();
}
updateModel() {
this.context.model.value.text = this.getValue();
}
freezeSelectedColumns() {
const columns = this.jexcel.getSelectedColumns();
this.reloadEditor({
// @ts-ignore
freezeColumns: Math.max(...columns) + 1,
tableOverflow: true,
tableWidth: this.node.offsetWidth + 'px',
tableHeight: this.node.offsetHeight + 'px'
});
this.hasFrozenColumns = true;
}
unfreezeColumns() {
this.reloadEditor({
// @ts-ignore
freezeColumns: null,
tableOverflow: false,
tableWidth: null,
tableHeight: null
});
this.hasFrozenColumns = false;
}
get columnsNumber(): number {
const data = this.jexcel.getData();
if (!data.length) {
return;
}
return data[0].length;
}
getHeaderElements() {
const headers = [];
for (const element of this.jexcel.headerContainer.children) {
// TODO use data attribute?
if (element.className !== 'jexcel_selectall') {
headers.push(element);
}
}
return headers;
}
relayout() {
if (typeof this.jexcel === 'undefined') {
return;
}
const columns = this.columnsNumber;
if (!columns) {
return;
}
switch (this.fitMode) {
case 'all-equal-default': {
const options = this.jexcel.getConfig();
for (let i = 0; i < columns; i++) {
this.jexcel.setWidth(i, options.defaultColWidth, null);
}
break;
}
case 'all-equal-fit': {
const indexColumn = this.node.querySelector(
'.jexcel_selectall'
) as HTMLElement;
const availableWidth = this.node.clientWidth - indexColumn.offsetWidth;
const widthPerColumn = availableWidth / columns;
for (let i = 0; i < columns; i++) {
this.jexcel.setWidth(i, widthPerColumn, null);
}
break;
}
case 'fit-cells': {
const data = this.jexcel.getData();
const headers = this.getHeaderElements();
for (let i = 0; i < columns; i++) {
let maxColumnWidth = Math.max(25, headers[i].scrollWidth);
for (let j = 0; j < data.length; j++) {
const cell = this.jexcel.getCellFromCoords(i, j) as HTMLElement;
maxColumnWidth = Math.max(maxColumnWidth, cell.scrollWidth);
}
this.jexcel.setWidth(i, maxColumnWidth, null);
}
break;
}
}
this.adjustColumnTypesWidth();
}
context: DocumentRegistry.CodeContext;
private _ready = new PromiseDelegate<void>();
scrollCellIntoView(match: ICellCoordinates) {
const cell = this.jexcel.getCellFromCoords(match.column, match.row);
const cellRect = cell.getBoundingClientRect();
const wrapperRect = this.wrapper.getBoundingClientRect();
let alignToTop = false;
const softMargin = 3;
if (cellRect.right > wrapperRect.right) {
this.wrapper.scrollBy(cellRect.right - wrapperRect.right, 0);
} else if (cellRect.left < wrapperRect.left) {
this.wrapper.scrollBy(cellRect.left - wrapperRect.left, 0);
}
if (cellRect.top - softMargin < wrapperRect.top) {
alignToTop = true;
}
if (alignToTop || cellRect.bottom + softMargin > wrapperRect.bottom) {
cell.scrollIntoView(alignToTop);
}
}
} | the_stack |
import {
IDisposable
} from '@phosphor/disposable';
import {
Platform
} from '@phosphor/domutils';
import {
Drag
} from '@phosphor/dragdrop';
import {
DataGrid
} from './datagrid';
import {
DataModel
} from './datamodel';
import {
SelectionModel
} from './selectionmodel';
/**
* A basic implementation of a data grid mouse handler.
*
* #### Notes
* This class may be subclassed and customized as needed.
*/
export
class BasicMouseHandler implements DataGrid.IMouseHandler {
/**
* Dispose of the resources held by the mouse handler.
*/
dispose(): void {
// Bail early if the handler is already disposed.
if (this._disposed) {
return;
}
// Release any held resources.
this.release();
// Mark the handler as disposed.
this._disposed = true;
}
/**
* Whether the mouse handler is disposed.
*/
get isDisposed(): boolean {
return this._disposed;
}
/**
* Release the resources held by the handler.
*/
release(): void {
// Bail early if the is no press data.
if (!this._pressData) {
return;
}
// Clear the autoselect timeout.
if (this._pressData.type === 'select') {
this._pressData.timeout = -1;
}
// Clear the press data.
this._pressData.override.dispose();
this._pressData = null;
}
/**
* Handle the mouse hover event for the data grid.
*
* @param grid - The data grid of interest.
*
* @param event - The mouse hover event of interest.
*/
onMouseHover(grid: DataGrid, event: MouseEvent): void {
// Hit test the grid.
let hit = grid.hitTest(event.clientX, event.clientY);
// Get the resize handle for the hit test.
let handle = Private.resizeHandleForHitTest(hit);
// Fetch the cursor for the handle.
let cursor = Private.cursorForHandle(handle);
// Update the viewport cursor based on the part.
grid.viewport.node.style.cursor = cursor;
// TODO support user-defined hover items
}
/**
* Handle the mouse leave event for the data grid.
*
* @param grid - The data grid of interest.
*
* @param event - The mouse hover event of interest.
*/
onMouseLeave(grid: DataGrid, event: MouseEvent): void {
// TODO support user-defined hover popups.
// Clear the viewport cursor.
grid.viewport.node.style.cursor = '';
}
/**
* Handle the mouse down event for the data grid.
*
* @param grid - The data grid of interest.
*
* @param event - The mouse down event of interest.
*/
onMouseDown(grid: DataGrid, event: MouseEvent): void {
// Unpack the event.
let { clientX, clientY } = event;
// Hit test the grid.
let hit = grid.hitTest(clientX, clientY);
// Unpack the hit test.
let { region, row, column } = hit;
// Bail if the hit test is on an uninteresting region.
if (region === 'void') {
return;
}
// Fetch the modifier flags.
let shift = event.shiftKey;
let accel = Platform.accelKey(event);
// If the hit test is the body region, the only option is select.
if (region === 'body') {
// Fetch the selection model.
let model = grid.selectionModel;
// Bail early if there is no selection model.
if (!model) {
return;
}
// Override the document cursor.
let override = Drag.overrideCursor('default');
// Set up the press data.
this._pressData = {
type: 'select', region, row, column, override,
localX: -1, localY: -1, timeout: -1
};
// Set up the selection variables.
let r1: number;
let c1: number;
let r2: number;
let c2: number;
let cursorRow: number;
let cursorColumn: number;
let clear: SelectionModel.ClearMode;
// Accel == new selection, keep old selections.
if (accel) {
r1 = row;
r2 = row;
c1 = column;
c2 = column;
cursorRow = row;
cursorColumn = column;
clear = 'none';
} else if (shift) {
r1 = model.cursorRow;
r2 = row;
c1 = model.cursorColumn;
c2 = column;
cursorRow = model.cursorRow;
cursorColumn = model.cursorColumn;
clear = 'current';
} else {
r1 = row;
r2 = row;
c1 = column;
c2 = column;
cursorRow = row;
cursorColumn = column;
clear = 'all';
}
// Make the selection.
model.select({ r1, c1, r2, c2, cursorRow, cursorColumn, clear });
// Done.
return;
}
// Otherwise, the hit test is on a header region.
// Convert the hit test into a part.
let handle = Private.resizeHandleForHitTest(hit);
// Fetch the cursor for the handle.
let cursor = Private.cursorForHandle(handle);
// Handle horizontal resize.
if (handle === 'left' || handle === 'right' ) {
// Set up the resize data type.
let type: 'column-resize' = 'column-resize';
// Determine the column region.
let rgn: DataModel.ColumnRegion = (
region === 'column-header' ? 'body' : 'row-header'
);
// Determine the section index.
let index = handle === 'left' ? column - 1 : column;
// Fetch the section size.
let size = grid.columnSize(rgn, index);
// Override the document cursor.
let override = Drag.overrideCursor(cursor);
// Create the temporary press data.
this._pressData = { type, region: rgn, index, size, clientX, override };
// Done.
return;
}
// Handle vertical resize
if (handle === 'top' || handle === 'bottom') {
// Set up the resize data type.
let type: 'row-resize' = 'row-resize';
// Determine the row region.
let rgn: DataModel.RowRegion = (
region === 'row-header' ? 'body' : 'column-header'
);
// Determine the section index.
let index = handle === 'top' ? row - 1 : row;
// Fetch the section size.
let size = grid.rowSize(rgn, index);
// Override the document cursor.
let override = Drag.overrideCursor(cursor);
// Create the temporary press data.
this._pressData = { type, region: rgn, index, size, clientY, override };
// Done.
return;
}
// Otherwise, the only option is select.
// Fetch the selection model.
let model = grid.selectionModel;
// Bail if there is no selection model.
if (!model) {
return;
}
// Override the document cursor.
let override = Drag.overrideCursor('default');
// Set up the press data.
this._pressData = {
type: 'select', region, row, column, override,
localX: -1, localY: -1, timeout: -1
};
// Set up the selection variables.
let r1: number;
let c1: number;
let r2: number;
let c2: number;
let cursorRow: number;
let cursorColumn: number;
let clear: SelectionModel.ClearMode;
// Compute the selection based on the pressed region.
if (region === 'corner-header') {
r1 = 0;
r2 = Infinity;
c1 = 0;
c2 = Infinity;
cursorRow = accel ? 0 : shift ? model.cursorRow : 0;
cursorColumn = accel ? 0 : shift ? model.cursorColumn : 0;
clear = accel ? 'none' : shift ? 'current' : 'all';
} else if (region === 'row-header') {
r1 = accel ? row : shift ? model.cursorRow : row;
r2 = row;
c1 = 0;
c2 = Infinity;
cursorRow = accel ? row : shift ? model.cursorRow : row;
cursorColumn = accel ? 0 : shift ? model.cursorColumn : 0;
clear = accel ? 'none' : shift ? 'current' : 'all';
} else if (region === 'column-header') {
r1 = 0;
r2 = Infinity;
c1 = accel ? column : shift ? model.cursorColumn : column;
c2 = column;
cursorRow = accel ? 0 : shift ? model.cursorRow : 0;
cursorColumn = accel ? column : shift ? model.cursorColumn : column;
clear = accel ? 'none' : shift ? 'current' : 'all';
} else {
r1 = accel ? row : shift ? model.cursorRow : row;
r2 = row;
c1 = accel ? column : shift ? model.cursorColumn : column;
c2 = column;
cursorRow = accel ? row : shift ? model.cursorRow : row;
cursorColumn = accel ? column : shift ? model.cursorColumn : column;
clear = accel ? 'none' : shift ? 'current' : 'all';
}
// Make the selection.
model.select({ r1, c1, r2, c2, cursorRow, cursorColumn, clear });
}
/**
* Handle the mouse move event for the data grid.
*
* @param grid - The data grid of interest.
*
* @param event - The mouse move event of interest.
*/
onMouseMove(grid: DataGrid, event: MouseEvent): void {
// Fetch the press data.
const data = this._pressData;
// Bail early if there is no press data.
if (!data) {
return;
}
// Handle a row resize.
if (data.type === 'row-resize') {
let dy = event.clientY - data.clientY;
grid.resizeRow(data.region, data.index, data.size + dy);
return;
}
// Handle a column resize.
if (data.type === 'column-resize') {
let dx = event.clientX - data.clientX;
grid.resizeColumn(data.region, data.index, data.size + dx);
return;
}
// Otherwise, it's a select.
// Mouse moves during a corner header press are a no-op.
if (data.region === 'corner-header') {
return;
}
// Fetch the selection model.
let model = grid.selectionModel;
// Bail early if the selection model was removed.
if (!model) {
return;
}
// Map to local coordinates.
let { lx, ly } = grid.mapToLocal(event.clientX, event.clientY);
// Update the local mouse coordinates in the press data.
data.localX = lx;
data.localY = ly;
// Fetch the grid geometry.
let hw = grid.headerWidth;
let hh = grid.headerHeight;
let vpw = grid.viewportWidth;
let vph = grid.viewportHeight;
let sx = grid.scrollX;
let sy = grid.scrollY;
let msx = grid.maxScrollY;
let msy = grid.maxScrollY;
// Fetch the selection mode.
let mode = model.selectionMode;
// Set up the timeout variable.
let timeout = -1;
// Compute the timemout based on hit region and mouse position.
if (data.region === 'row-header' || mode === 'row') {
if (ly < hh && sy > 0) {
timeout = Private.computeTimeout(hh - ly);
} else if (ly >= vph && sy < msy) {
timeout = Private.computeTimeout(ly - vph);
}
} else if (data.region === 'column-header' || mode === 'column') {
if (lx < hw && sx > 0) {
timeout = Private.computeTimeout(hw - lx);
} else if (lx >= vpw && sx < msx) {
timeout = Private.computeTimeout(lx - vpw);
}
} else {
if (lx < hw && sx > 0) {
timeout = Private.computeTimeout(hw - lx);
} else if (lx >= vpw && sx < msx) {
timeout = Private.computeTimeout(lx - vpw);
} else if (ly < hh && sy > 0) {
timeout = Private.computeTimeout(hh - ly);
} else if (ly >= vph && sy < msy) {
timeout = Private.computeTimeout(ly - vph);
}
}
// Update or initiate the autoselect if needed.
if (timeout >= 0) {
if (data.timeout < 0) {
data.timeout = timeout;
setTimeout(() => { Private.autoselect(grid, data); }, timeout);
} else {
data.timeout = timeout;
}
return;
}
// Otherwise, clear the autoselect timeout.
data.timeout = -1;
// Map the position to virtual coordinates.
let { vx, vy } = grid.mapToVirtual(event.clientX, event.clientY);
// Clamp the coordinates to the limits.
vx = Math.max(0, Math.min(vx, grid.bodyWidth -1));
vy = Math.max(0, Math.min(vy, grid.bodyHeight - 1));
// Set up the selection variables.
let r1: number;
let c1: number;
let r2: number;
let c2: number;
let cursorRow = model.cursorRow;
let cursorColumn = model.cursorColumn;
let clear: SelectionModel.ClearMode = 'current';
// Compute the selection based pressed region.
if (data.region === 'row-header' || mode === 'row') {
r1 = data.row;
r2 = grid.rowAt('body', vy);
c1 = 0;
c2 = Infinity;
} else if (data.region === 'column-header' || mode === 'column') {
r1 = 0;
r2 = Infinity;
c1 = data.column;
c2 = grid.columnAt('body', vx);
} else {
r1 = cursorRow;
r2 = grid.rowAt('body', vy);
c1 = cursorColumn;
c2 = grid.columnAt('body', vx);
}
// Make the selection.
model.select({ r1, c1, r2, c2, cursorRow, cursorColumn, clear });
}
/**
* Handle the mouse up event for the data grid.
*
* @param grid - The data grid of interest.
*
* @param event - The mouse up event of interest.
*/
onMouseUp(grid: DataGrid, event: MouseEvent): void {
this.release();
}
/**
* Handle the context menu event for the data grid.
*
* @param grid - The data grid of interest.
*
* @param event - The context menu event of interest.
*/
onContextMenu(grid: DataGrid, event: MouseEvent): void {
// TODO support user-defined context menus
}
/**
* Handle the wheel event for the data grid.
*
* @param grid - The data grid of interest.
*
* @param event - The wheel event of interest.
*/
onWheel(grid: DataGrid, event: WheelEvent): void {
// Bail if a mouse press is in progress.
if (this._pressData) {
return;
}
// Extract the delta X and Y movement.
let dx = event.deltaX;
let dy = event.deltaY;
// Convert the delta values to pixel values.
switch (event.deltaMode) {
case 0: // DOM_DELTA_PIXEL
break;
case 1: // DOM_DELTA_LINE
let ds = grid.defaultSizes;
dx *= ds.columnWidth;
dy *= ds.rowHeight;
break;
case 2: // DOM_DELTA_PAGE
dx *= grid.pageWidth;
dy *= grid.pageHeight;
break;
default:
throw 'unreachable';
}
// Scroll by the desired amount.
grid.scrollBy(dx, dy);
}
private _disposed = false;
private _pressData: Private.PressData | null;
}
/**
* The namespace for the module implementation details.
*/
namespace Private {
/**
* A type alias for the row resize data.
*/
export
type RowResizeData = {
/**
* The descriminated type for the data.
*/
readonly type: 'row-resize';
/**
* The row region which holds the section being resized.
*/
readonly region: DataModel.RowRegion;
/**
* The index of the section being resized.
*/
readonly index: number;
/**
* The original size of the section.
*/
readonly size: number;
/**
* The original client Y position of the mouse.
*/
readonly clientY: number;
/**
* The disposable to clear the cursor override.
*/
readonly override: IDisposable;
};
/**
* A type alias for the column resize data.
*/
export
type ColumnResizeData = {
/**
* The descriminated type for the data.
*/
readonly type: 'column-resize';
/**
* The column region which holds the section being resized.
*/
readonly region: DataModel.ColumnRegion;
/**
* The index of the section being resized.
*/
readonly index: number;
/**
* The original size of the section.
*/
readonly size: number;
/**
* The original client X position of the mouse.
*/
readonly clientX: number;
/**
* The disposable to clear the cursor override.
*/
readonly override: IDisposable;
};
/**
* A type alias for the select data.
*/
export
type SelectData = {
/**
* The descriminated type for the data.
*/
readonly type: 'select';
/**
* The original region for the mouse press.
*/
readonly region: DataModel.CellRegion;
/**
* The original row that was selected.
*/
readonly row: number;
/**
* The original column that was selected.
*/
readonly column: number;
/**
* The disposable to clear the cursor override.
*/
readonly override: IDisposable;
/**
* The current local X position of the mouse.
*/
localX: number;
/**
* The current local Y position of the mouse.
*/
localY: number;
/**
* The timeout delay for the autoselect loop.
*/
timeout: number;
};
/**
* A type alias for the resize handler press data.
*/
export
type PressData = RowResizeData | ColumnResizeData | SelectData ;
/**
* A type alias for the resize handle types.
*/
export
type ResizeHandle = 'top' | 'left' | 'right' | 'bottom' | 'none';
/**
* Get the resize handle for a grid hit test.
*/
export
function resizeHandleForHitTest(hit: DataGrid.HitTestResult): ResizeHandle {
// Fetch the row and column.
let r = hit.row;
let c = hit.column;
// Fetch the leading and trailing sizes.
let lw = hit.x;
let lh = hit.y;
let tw = hit.width - hit.x;
let th = hit.height - hit.y;
// Set up the result variable.
let result: ResizeHandle;
// Dispatch based on hit test region.
switch (hit.region) {
case 'corner-header':
if (c > 0 && lw <= 5) {
result = 'left';
} else if (tw <= 6) {
result = 'right';
} else if (r > 0 && lh <= 5) {
result = 'top';
} else if (th <= 6) {
result = 'bottom';
} else {
result = 'none';
}
break;
case 'column-header':
if (c > 0 && lw <= 5) {
result = 'left';
} else if (tw <= 6) {
result = 'right';
} else if (r > 0 && lh <= 5) {
result = 'top';
} else if (th <= 6) {
result = 'bottom';
} else {
result = 'none';
}
break;
case 'row-header':
if (c > 0 && lw <= 5) {
result = 'left';
} else if (tw <= 6) {
result = 'right';
} else if (r > 0 && lh <= 5) {
result = 'top';
} else if (th <= 6) {
result = 'bottom';
} else {
result = 'none';
}
break;
case 'body':
result = 'none';
break;
case 'void':
result = 'none';
break;
default:
throw 'unreachable';
}
// Return the result.
return result;
}
/**
* Convert a resize handle into a cursor.
*/
export
function cursorForHandle(handle: ResizeHandle): string {
return cursorMap[handle];
}
/**
* A timer callback for the autoselect loop.
*
* @param grid - The datagrid of interest.
*
* @param data - The select data of interest.
*/
export
function autoselect(grid: DataGrid, data: SelectData): void {
// Bail early if the timeout has been reset.
if (data.timeout < 0) {
return;
}
// Fetch the selection model.
let model = grid.selectionModel;
// Bail early if the selection model has been removed.
if (!model) {
return;
}
// Fetch the current selection.
let cs = model.currentSelection();
// Bail early if there is no current selection.
if (!cs) {
return;
}
// Fetch local X and Y coordinates of the mouse.
let lx = data.localX;
let ly = data.localY;
// Set up the selection variables.
let r1 = cs.r1;
let c1 = cs.c1;
let r2 = cs.r2;
let c2 = cs.c2;
let cursorRow = model.cursorRow;
let cursorColumn = model.cursorColumn;
let clear: SelectionModel.ClearMode = 'current';
// Fetch the grid geometry.
let hw = grid.headerWidth;
let hh = grid.headerHeight;
let vpw = grid.viewportWidth;
let vph = grid.viewportHeight;
// Fetch the selection mode.
let mode = model.selectionMode;
// Update the selection based on the hit region.
if (data.region === 'row-header' || mode === 'row') {
r2 += ly <= hh ? -1 : ly >= vph ? 1 : 0;
} else if (data.region === 'column-header' || mode === 'column') {
c2 += lx <= hw ? -1 : lx >= vpw ? 1 : 0;
} else {
r2 += ly <= hh ? -1 : ly >= vph ? 1 : 0;
c2 += lx <= hw ? -1 : lx >= vpw ? 1 : 0;
}
// Update the current selection.
model.select({ r1, c1, r2, c2, cursorRow, cursorColumn, clear });
// Re-fetch the current selection.
cs = model.currentSelection();
// Bail if there is no selection.
if (!cs) {
return
}
// Scroll the grid based on the hit region.
if (data.region === 'row-header' || mode === 'row') {
grid.scrollToRow(cs.r2);
} else if (data.region === 'column-header' || mode == 'column') {
grid.scrollToColumn(cs.c2);
} else if (mode === 'cell') {
grid.scrollToCell(cs.r2, cs.c2);
}
// Schedule the next call with the current timeout.
setTimeout(() => { autoselect(grid, data); }, data.timeout);
}
/**
* Compute the scroll timeout for the given delta distance.
*
* @param delta - The delta pixels from the origin.
*
* @returns The scaled timeout in milliseconds.
*/
export
function computeTimeout(delta: number): number {
return 5 + 120 * (1 - Math.min(128, Math.abs(delta)) / 128);
}
/**
* A mapping of resize handle to cursor.
*/
const cursorMap = {
top: 'ns-resize',
left: 'ew-resize',
right: 'ew-resize',
bottom: 'ns-resize',
none: 'default'
};
} | the_stack |
namespace ergometer {
import hasWebBlueTooth = ergometer.ble.hasWebBlueTooth;
export interface RowingGeneralStatusEvent extends pubSub.ISubscription {
(data : RowingGeneralStatus) : void;
}
export interface RowingAdditionalStatus1Event extends pubSub.ISubscription {
(data : RowingAdditionalStatus1) : void;
}
export interface RowingAdditionalStatus2Event extends pubSub.ISubscription {
(data : RowingAdditionalStatus2) : void;
}
export interface RowingStrokeDataEvent extends pubSub.ISubscription {
(data : RowingStrokeData) : void;
}
export interface RowingAdditionalStrokeDataEvent extends pubSub.ISubscription {
(data : RowingAdditionalStrokeData) : void;
}
export interface RowingSplitIntervalDataEvent extends pubSub.ISubscription {
(data : RowingSplitIntervalData) : void;
}
export interface RowingAdditionalSplitIntervalDataEvent extends pubSub.ISubscription {
(data : RowingAdditionalSplitIntervalData) : void;
}
export interface WorkoutSummaryDataEvent extends pubSub.ISubscription {
(data : WorkoutSummaryData) : void;
}
export interface AdditionalWorkoutSummaryDataEvent extends pubSub.ISubscription {
(data : AdditionalWorkoutSummaryData) : void;
}
export interface AdditionalWorkoutSummaryData2Event extends pubSub.ISubscription {
(data : AdditionalWorkoutSummaryData2) : void;
}
export interface HeartRateBeltInformationEvent extends pubSub.ISubscription {
(data : HeartRateBeltInformation) : void;
}
export interface DeviceInfo {
//values filled when the device is found
connected : boolean;
name : string;
address : string;
quality : number;
//values filed when the device is connected:
serial? : string;
hardwareRevision? : string;
firmwareRevision? : string;
manufacturer? : string;
/** @internal */
_internalDevice : ble.IDevice; //for internal usage when you use this I can not guarantee compatibility
}
/**
*
* Usage:
*
* Create this class to acess the performance data
* var performanceMonitor= new ergometer.PerformanceMonitor();
*
* after this connect to the events to get data
* performanceMonitor.rowingGeneralStatusEvent.sub(this,this.onRowingGeneralStatus);
* On some android phones you can connect to a limited number of events. Use the multiplex property to overcome
* this problem. When the multi plex mode is switched on the data send to the device can be a a bit different, see
* the documentation in the properties You must set the multi plex property before connecting
* performanceMonitor.multiplex=true;
*
* to start the connection first start scanning for a device,
* you should call when the cordova deviceready event is called (or later)
* performanceMonitor.startScan((device : ergometer.DeviceInfo) : boolean => {
* //return true when you want to connect to the device
* return device.name=='My device name';
* });
* to connect at at a later time
* performanceMonitor.connectToDevice('my device name');
* the devices which where found during the scan are collected in
* performanceMonitor.devices
* when you connect to a device the scan is stopped, when you want to stop the scan earlier you need to call
* performanceMonitor.stopScan
*
*/
export class PerformanceMonitorBle extends PerformanceMonitorBase {
private _driver: ble.IDriver;
private _recordingDriver : ble.RecordingDriver;
private _replayDriver : ble.ReplayDriver;
//ergomter data events
private _rowingGeneralStatusEvent: pubSub.Event<RowingGeneralStatusEvent>;
private _rowingAdditionalStatus1Event: pubSub.Event<RowingAdditionalStatus1Event>;
private _rowingAdditionalStatus2Event: pubSub.Event<RowingAdditionalStatus2Event>;
private _rowingStrokeDataEvent: pubSub.Event<RowingStrokeDataEvent>;
private _rowingAdditionalStrokeDataEvent: pubSub.Event<RowingAdditionalStrokeDataEvent>;
private _rowingSplitIntervalDataEvent: pubSub.Event<RowingSplitIntervalDataEvent>;
private _rowingAdditionalSplitIntervalDataEvent: pubSub.Event<RowingAdditionalSplitIntervalDataEvent>;
private _workoutSummaryDataEvent: pubSub.Event<WorkoutSummaryDataEvent>;
private _additionalWorkoutSummaryDataEvent: pubSub.Event<AdditionalWorkoutSummaryDataEvent>;
private _additionalWorkoutSummaryData2Event: pubSub.Event<AdditionalWorkoutSummaryData2Event>;
private _heartRateBeltInformationEvent: pubSub.Event<HeartRateBeltInformationEvent>;
private _deviceInfo : DeviceInfo;
private _rowingGeneralStatus : RowingGeneralStatus;
private _rowingAdditionalStatus1 : RowingAdditionalStatus1;
private _rowingAdditionalStatus2 : RowingAdditionalStatus2;
private _rowingStrokeData : RowingStrokeData;
private _rowingAdditionalStrokeData : RowingAdditionalStrokeData;
private _rowingSplitIntervalData : RowingSplitIntervalData;
private _rowingAdditionalSplitIntervalData : RowingAdditionalSplitIntervalData;
private _workoutSummaryData : WorkoutSummaryData;
private _additionalWorkoutSummaryData : AdditionalWorkoutSummaryData;
private _additionalWorkoutSummaryData2 : AdditionalWorkoutSummaryData2;
private _heartRateBeltInformation : HeartRateBeltInformation;
private _devices : DeviceInfo[] =[];
private _multiplex : boolean = false;
private _multiplexSubscribeCount: number =0;
private _sampleRate : SampleRate = SampleRate.rate500ms;
//disabled the auto reconnect, because it reconnects while the connection on the device is switched off
//this causes some strange state on the device which breaks communcation after reconnecting
private _autoReConnect : boolean = false;
private _generalStatusEventAttachedByPowerCurve =false;
private _recording : boolean =false;
protected get recordingDriver():ergometer.ble.RecordingDriver {
if (!this._recordingDriver) {
this._recordingDriver= new ble.RecordingDriver(this,this._driver)
}
return this._recordingDriver;
}
public set driver(value:ble.IDriver) {
this._driver = value;
}
public get recording():boolean {
return this._recording;
}
public set recording(value:boolean) {
this._recording = value;
if (value) this.recordingDriver.startRecording();
}
get replayDriver():ble.ReplayDriver {
if (!this._replayDriver)
this._replayDriver = new ble.ReplayDriver(this,this._driver);
return this._replayDriver;
}
get replaying():boolean {
return this.replayDriver.playing;
}
public replay(events : ble.IRecordingItem[]) {
this.replayDriver.replay(events);
}
set replaying(value:boolean) {
this.replayDriver.playing=value;
}
public get recordingEvents() : ble.IRecordingItem[] {
return this.recordingDriver.events;
}
public set recordingEvents(value : ble.IRecordingItem[]) {
this.recordingDriver.events=value;
}
public get driver():ergometer.ble.IDriver {
if (this.recording) {
return this.recordingDriver;
}
else if (this.replaying)
return this.replayDriver
else return this._driver;
}
/**
* when the connection is lost re-connect
* @returns {boolean}
*/
get autoReConnect():boolean {
return this._autoReConnect;
}
/**
*
* when the connection is lost re-connect
* @param value
*/
set autoReConnect(value:boolean) {
this._autoReConnect = value;
}
/**
* On some android phones you can connect to a limited number of events. Use the multiplex property to overcome
* this problem. When the multi plex mode is switched on the data send to the device can be a a bit different, see
* the documentation in the properties You must set the multi plex property before connecting
*
* @returns {boolean}
*/
public get multiplex():boolean {
return this._multiplex;
}
/**
* On some android phones you can connect to a limited number of events. Use the multiplex property to overcome
* this problem. When the multi plex mode is switched on the data send to the device can be a a bit different, see
* the documentation in the properties You must set the multi plex property before connecting
* @param value
*/
public set multiplex(value:boolean) {
if (value != this._multiplex) {
if (this.connectionState>=MonitorConnectionState.servicesFound)
throw "property multiplex can not be changed after the connection is made.";
this._multiplex = value;
}
}
/**
* an array of of performance monitor devices which where found during the scan.
* the array is sorted by connection quality (best on top)
*
* @returns {DeviceInfo[]}
*/
public get devices():ergometer.DeviceInfo[] {
return this._devices;
}
/**
* The values of the last rowingGeneralStatus event
*
* @returns {RowingGeneralStatus}
*/
public get rowingGeneralStatus():RowingGeneralStatus {
return this._rowingGeneralStatus;
}
/**
* The values of the last rowingAdditionalStatus1 event
* @returns {RowingAdditionalStatus1}
*/
public get rowingAdditionalStatus1():RowingAdditionalStatus1 {
return this._rowingAdditionalStatus1;
}
/**
* The values of the last RowingAdditionalStatus2 event
* @returns {RowingAdditionalStatus2}
*/
public get rowingAdditionalStatus2():RowingAdditionalStatus2 {
return this._rowingAdditionalStatus2;
}
/**
* The values of the last rowingStrokeData event
* @returns {RowingStrokeData}
*/
public get rowingStrokeData():RowingStrokeData {
return this._rowingStrokeData;
}
/**
* The values of the last rowingAdditionalStrokeData event
* @returns {RowingAdditionalStrokeData}
*/
public get rowingAdditionalStrokeData():RowingAdditionalStrokeData {
return this._rowingAdditionalStrokeData;
}
/**
* The values of the last rowingSplitIntervalData event
* @returns {RowingSplitIntervalData}
*/
public get rowingSplitIntervalData():RowingSplitIntervalData {
return this._rowingSplitIntervalData;
}
/**
* The values of the last rowingAdditionalSplitIntervalData event
* @returns {RowingAdditionalSplitIntervalData}
*/
public get rowingAdditionalSplitIntervalData():RowingAdditionalSplitIntervalData {
return this._rowingAdditionalSplitIntervalData;
}
/**
* The values of the last workoutSummaryData event
* @returns {WorkoutSummaryData}
*/
public get workoutSummaryData():WorkoutSummaryData {
return this._workoutSummaryData;
}
/**
* The values of the last additionalWorkoutSummaryData event
* @returns {AdditionalWorkoutSummaryData}
*/
public get additionalWorkoutSummaryData():AdditionalWorkoutSummaryData {
return this._additionalWorkoutSummaryData;
}
/**
* The values of the last AdditionalWorkoutSummaryData2 event
* @returns {AdditionalWorkoutSummaryData2}
*/
public get additionalWorkoutSummaryData2():AdditionalWorkoutSummaryData2 {
return this._additionalWorkoutSummaryData2;
}
/**
* The values of the last heartRateBeltInformation event
* @returns {HeartRateBeltInformation}
*/
public get heartRateBeltInformation():HeartRateBeltInformation {
return this._heartRateBeltInformation;
}
/**
* read rowingGeneralStatus data
* connect to the using .sub(this,myFunction)
* @returns {pubSub.Event<RowingGeneralStatusEvent>}
*/
public get rowingGeneralStatusEvent(): pubSub.Event<RowingGeneralStatusEvent> {
return this._rowingGeneralStatusEvent;
}
/**
* read rowingGeneralStatus1 data
* connect to the using .sub(this,myFunction)
* @returns {pubSub.Event<RowingAdditionalStatus1Event>}
*/
public get rowingAdditionalStatus1Event():pubSub.Event<RowingAdditionalStatus1Event> {
return this._rowingAdditionalStatus1Event;
}
/**
* read rowingAdditionalStatus2 data
* connect to the using .sub(this,myFunction)
* @returns {pubSub.Event<RowingAdditionalStatus2Event>}
*/
public get rowingAdditionalStatus2Event():pubSub.Event<RowingAdditionalStatus2Event> {
return this._rowingAdditionalStatus2Event;
}
/**
* read rowingStrokeData data
* connect to the using .sub(this,myFunction)
* @returns {pubSub.Event<RowingStrokeDataEvent>}
*/
public get rowingStrokeDataEvent():pubSub.Event<RowingStrokeDataEvent> {
return this._rowingStrokeDataEvent;
}
/**
* read rowingAdditionalStrokeData data
* connect to the using .sub(this,myFunction)
* @returns {pubSub.Event<RowingAdditionalStrokeDataEvent>}
*/
public get rowingAdditionalStrokeDataEvent():pubSub.Event<RowingAdditionalStrokeDataEvent> {
return this._rowingAdditionalStrokeDataEvent;
}
/**
* read rowingSplitIntervalDat data
* connect to the using .sub(this,myFunction)
* @returns {pubSub.Event<RowingSplitIntervalDataEvent>}
*/
public get rowingSplitIntervalDataEvent():pubSub.Event<RowingSplitIntervalDataEvent> {
return this._rowingSplitIntervalDataEvent;
}
/**
* read rowingAdditionalSplitIntervalData data
* connect to the using .sub(this,myFunction)
* @returns {pubSub.Event<RowingAdditionalSplitIntervalDataEvent>}
*/
public get rowingAdditionalSplitIntervalDataEvent():pubSub.Event<RowingAdditionalSplitIntervalDataEvent> {
return this._rowingAdditionalSplitIntervalDataEvent;
}
/**
* read workoutSummaryData data
* connect to the using .sub(this,myFunction)
* @returns {pubSub.Event<WorkoutSummaryDataEvent>}
*/
public get workoutSummaryDataEvent():pubSub.Event<WorkoutSummaryDataEvent> {
return this._workoutSummaryDataEvent;
}
/**
* read additionalWorkoutSummaryData data
* connect to the using .sub(this,myFunction)
* @returns {pubSub.Event<AdditionalWorkoutSummaryDataEvent>}
*/
public get additionalWorkoutSummaryDataEvent():pubSub.Event<AdditionalWorkoutSummaryDataEvent> {
return this._additionalWorkoutSummaryDataEvent;
}
/**
* read additionalWorkoutSummaryData2 data
* connect to the using .sub(this,myFunction)
* @returns {pubSub.Event<AdditionalWorkoutSummaryData2Event>}
*/
public get additionalWorkoutSummaryData2Event():pubSub.Event<AdditionalWorkoutSummaryData2Event> {
return this._additionalWorkoutSummaryData2Event;
}
/**
* read heartRateBeltInformation data
* connect to the using .sub(this,myFunction)
* @returns {pubSub.Event<HeartRateBeltInformationEvent>}
*/
public get heartRateBeltInformationEvent():pubSub.Event<HeartRateBeltInformationEvent> {
return this._heartRateBeltInformationEvent;
}
/**
* Get device information of the connected device.
* @returns {DeviceInfo}
*/
public get deviceInfo():ergometer.DeviceInfo {
return this._deviceInfo;
}
/**
* read the performance montitor sample rate. By default this is 500 ms
* @returns {number}
*/
public get sampleRate():SampleRate {
return this._sampleRate;
}
/**
* Change the performance monitor sample rate.
* @param value
*/
public set sampleRate(value:SampleRate) {
if (value != this._sampleRate) {
var dataView = new DataView(new ArrayBuffer(1));
dataView.setUint8(0, value);
this.driver.writeCharacteristic(ble.PMROWING_SERVICE, ble.ROWING_STATUS_SAMPLE_RATE_CHARACTERISIC, dataView)
.then(
()=> {
this._sampleRate = value;
},
this.getErrorHandlerFunc("Can not set sample rate"));
}
}
/**
* disconnect the current connected device
*/
public disconnect() {
if (this.connectionState>=MonitorConnectionState.deviceReady) {
this.driver.disconnect();
this.changeConnectionState(MonitorConnectionState.deviceReady)
}
}
protected clearAllBuffers() {
this.clearRegisterdGuids();
}
/**
*
*/
protected enableMultiplexNotification() :Promise<void> {
var result : Promise<void>;
if (this._multiplexSubscribeCount==0)
result=this.enableNotification(ble.PMROWING_SERVICE,ble.MULTIPLEXED_INFO_CHARACTERISIC,
(data:ArrayBuffer) => { this.handleDataCallbackMulti(data);})
.catch( this.getErrorHandlerFunc("Can not enable multiplex"));
else result= Promise.resolve();
this._multiplexSubscribeCount++;
return result;
}
/**
*
*/
protected disableMultiPlexNotification() :Promise<void> {
var result : Promise<void>;
this._multiplexSubscribeCount--;
if (this._multiplexSubscribeCount==0)
result=this.disableNotification(ble.PMROWING_SERVICE,ble.MULTIPLEXED_INFO_CHARACTERISIC)
.catch( this.getErrorHandlerFunc("can not disable multiplex"));
else result= Promise.resolve();
return result;
}
private _registeredGuids = {};
protected clearRegisterdGuids() {
this._registeredGuids ={};
}
protected enableNotification(serviceUIID : string,characteristicUUID:string, receive:(data:ArrayBuffer) =>void) : Promise<void> {
if (this._registeredGuids[characteristicUUID]===1) return Promise.resolve();
this._registeredGuids[characteristicUUID]=1;
return this.driver.enableNotification(serviceUIID,characteristicUUID,receive);
}
protected disableNotification(serviceUIID : string,characteristicUUID:string) : Promise<void> {
if (this._registeredGuids[characteristicUUID]===1) {
this._registeredGuids[characteristicUUID]=0;
return this.driver.disableNotification(serviceUIID, characteristicUUID);
}
return Promise.resolve();
}
/**
*
*/
protected enableDisableNotification() : Promise<void> {
super.enableDisableNotification();
var promises : Promise<void>[] =[];
var enableMultiPlex=false;
if (this.connectionState>=MonitorConnectionState.servicesFound) {
if (this.rowingGeneralStatusEvent.count > 0) {
if (this.multiplex) {
enableMultiPlex=true;
}
else {
promises.push(this.enableNotification(ble.PMROWING_SERVICE,ble.ROWING_STATUS_CHARACTERISIC,
(data:ArrayBuffer) => {
this.handleDataCallback(data, this.handleRowingGeneralStatus);
}).catch(this.getErrorHandlerFunc("")));
}
}
else {
if (!this.multiplex) promises.push(this.disableNotification(ble.PMROWING_SERVICE,ble.ROWING_STATUS_CHARACTERISIC)
.catch(this.getErrorHandlerFunc("")));
}
if (this.rowingAdditionalStatus1Event.count > 0) {
if (this.multiplex) {
enableMultiPlex=true;
}
else {
promises.push(this.enableNotification(ble.PMROWING_SERVICE,ble.EXTRA_STATUS1_CHARACTERISIC,
(data:ArrayBuffer) => {
this.handleDataCallback(data, this.handleRowingAdditionalStatus1);
}).catch(this.getErrorHandlerFunc("")));
}
}
else {
if (!this.multiplex)
promises.push(this.disableNotification(ble.PMROWING_SERVICE,ble.EXTRA_STATUS1_CHARACTERISIC)
.catch(this.getErrorHandlerFunc("")));
}
if (this.rowingAdditionalStatus2Event.count > 0) {
if (this.multiplex) {
enableMultiPlex=true;
}
else {
promises.push(this.enableNotification(ble.PMROWING_SERVICE,ble.EXTRA_STATUS2_CHARACTERISIC,
(data:ArrayBuffer) => {
this.handleDataCallback(data, this.handleRowingAdditionalStatus2);
}).catch(this.getErrorHandlerFunc("")));
}
}
else {
if (!this.multiplex)
promises.push(this.disableNotification(ble.PMROWING_SERVICE,ble.EXTRA_STATUS2_CHARACTERISIC)
.catch( this.getErrorHandlerFunc("")));
}
if (this.rowingStrokeDataEvent.count > 0) {
if (this.multiplex) {
enableMultiPlex=true;
}
else {
promises.push(this.enableNotification(ble.PMROWING_SERVICE,ble.STROKE_DATA_CHARACTERISIC,
(data:ArrayBuffer) => {
this.handleDataCallback(data, this.handleRowingStrokeData);
}).catch(this.getErrorHandlerFunc("")));
}
}
else {
if (!this.multiplex) promises.push(this.disableNotification(ble.PMROWING_SERVICE,ble.STROKE_DATA_CHARACTERISIC)
.catch( this.getErrorHandlerFunc("")));
}
if (this.rowingAdditionalStrokeDataEvent.count > 0) {
if (this.multiplex) {
enableMultiPlex=true;
}
else {
promises.push(this.enableNotification(ble.PMROWING_SERVICE,ble.EXTRA_STROKE_DATA_CHARACTERISIC,
(data:ArrayBuffer) => {
this.handleDataCallback(data, this.handleRowingAdditionalStrokeData);
}).catch(this.getErrorHandlerFunc("")));
}
}
else {
if (!this.multiplex) promises.push(this.disableNotification(ble.PMROWING_SERVICE,ble.EXTRA_STROKE_DATA_CHARACTERISIC)
.catch(this.getErrorHandlerFunc("")));
}
if (this.rowingSplitIntervalDataEvent.count > 0) {
if (this.multiplex) {
enableMultiPlex=true;
}
else {
promises.push(this.enableNotification(ble.PMROWING_SERVICE,ble.SPLIT_INTERVAL_DATA_CHARACTERISIC,
(data:ArrayBuffer) => {
this.handleDataCallback(data, this.handleRowingSplitIntervalData);
}).catch(this.getErrorHandlerFunc("")));
}
}
else {
if (!this.multiplex) promises.push(this.disableNotification(ble.PMROWING_SERVICE,ble.SPLIT_INTERVAL_DATA_CHARACTERISIC)
.catch(this.getErrorHandlerFunc("")));
}
if (this.rowingAdditionalSplitIntervalDataEvent.count > 0) {
if (this.multiplex) {
enableMultiPlex=true;
}
else {
promises.push(this.enableNotification(ble.PMROWING_SERVICE,ble.EXTRA_SPLIT_INTERVAL_DATA_CHARACTERISIC,
(data:ArrayBuffer) => {
this.handleDataCallback(data, this.handleRowingAdditionalSplitIntervalData);
}).catch(this.getErrorHandlerFunc("")));
}
}
else {
if (!this.multiplex) promises.push(this.disableNotification(ble.PMROWING_SERVICE,ble.EXTRA_SPLIT_INTERVAL_DATA_CHARACTERISIC)
.catch( this.getErrorHandlerFunc("")));
}
if (this.workoutSummaryDataEvent.count > 0) {
if (this.multiplex) {
enableMultiPlex=true;
}
else {
promises.push(this.enableNotification(ble.PMROWING_SERVICE,ble.ROWING_SUMMARY_CHARACTERISIC,
(data:ArrayBuffer) => {
this.handleDataCallback(data, this.handleWorkoutSummaryData);
}).catch(this.getErrorHandlerFunc("")));
}
}
else {
if (!this.multiplex) promises.push(this.disableNotification(ble.PMROWING_SERVICE,ble.ROWING_SUMMARY_CHARACTERISIC)
.catch(this.getErrorHandlerFunc("")));
}
if (this.additionalWorkoutSummaryDataEvent.count > 0) {
if (this.multiplex) {
enableMultiPlex=true;
}
else {
promises.push(this.enableNotification(ble.PMROWING_SERVICE,ble.EXTRA_ROWING_SUMMARY_CHARACTERISIC,
(data:ArrayBuffer) => {
this.handleDataCallback(data, this.handleAdditionalWorkoutSummaryData);
}).catch(this.getErrorHandlerFunc("")));
}
}
else {
if (!this.multiplex) promises.push(this.disableNotification(ble.PMROWING_SERVICE,ble.EXTRA_ROWING_SUMMARY_CHARACTERISIC )
.catch( this.getErrorHandlerFunc("")));
}
if (this.additionalWorkoutSummaryData2Event.count > 0) {
if (this.multiplex) {
enableMultiPlex=true;
}
//this data is only available for multi ples
}
if (this.heartRateBeltInformationEvent.count > 0) {
if (this.multiplex) {
enableMultiPlex=true;
}
else {
promises.push(this.enableNotification(ble.PMROWING_SERVICE,ble.HEART_RATE_BELT_INFO_CHARACTERISIC,
(data:ArrayBuffer) => {
this.handleDataCallback(data, this.handleHeartRateBeltInformation);
}).catch(this.getErrorHandlerFunc("")));
}
}
else {
if (!this.multiplex) promises.push(this.disableNotification(ble.PMROWING_SERVICE,ble.HEART_RATE_BELT_INFO_CHARACTERISIC)
.catch( this.getErrorHandlerFunc("")));
}
if (this.powerCurveEvent.count>0) {
//when the status changes collect the power info
if (!this._generalStatusEventAttachedByPowerCurve) {
this._generalStatusEventAttachedByPowerCurve=true;
this.rowingGeneralStatusEvent.sub(this,this.onPowerCurveRowingGeneralStatus);
}
}
else {
if (this._generalStatusEventAttachedByPowerCurve) {
this._generalStatusEventAttachedByPowerCurve=false;
this.rowingGeneralStatusEvent.unsub(this.onPowerCurveRowingGeneralStatus);
}
}
if (this.multiplex && enableMultiPlex) {
enableMultiPlex=true;
promises.push(this.enableMultiplexNotification());
}
else promises.push(this.disableMultiPlexNotification());
}
//utils.promiseAllSync(promisses) or use a slower method
return Promise.all(promises).then(()=>{
return Promise.resolve()});
}
protected onPowerCurveRowingGeneralStatus(data : ergometer.RowingGeneralStatus) {
if (this.logLevel>=LogLevel.trace)
this.traceInfo('RowingGeneralStatus:'+JSON.stringify(data));
//test to receive the power curve
if (this.rowingGeneralStatus && this.rowingGeneralStatus.strokeState!=data.strokeState) {
if (data.strokeState ==StrokeState.recoveryState) {
//send a power curve request
this.newCsafeBuffer()
.getPowerCurve({
onDataReceived: (curve : number[]) =>{
this.powerCurveEvent.pub(curve);
this._powerCurve=curve;
}
})
.send();
}
}
}
public currentDriverIsWebBlueTooth() : boolean {
return this._driver instanceof ble.DriverWebBlueTooth;
}
protected initDriver() {
if (bleCentral.available()) this._driver= new bleCentral.DriverBleCentral([ergometer.ble.PMDEVICE])
else if ((typeof bleat !== 'undefined' ) && bleat) this._driver = new ble.DriverBleat();
else if ((typeof simpleBLE !== 'undefined' ) && simpleBLE ) this._driver = new ble.DriverSimpleBLE();
else if (ble.hasWebBlueTooth()) this._driver= new ble.DriverWebBlueTooth(this,[ble.PMDEVICE],[ble.PMDEVICE_INFO_SERVICE,ble.PMCONTROL_SERVICE,ble.PMROWING_SERVICE]);
else this.handleError("No suitable blue tooth driver found to connect to the ergometer. You need to load bleat on native platforms and a browser with web blue tooth capability.") ;
}
protected checkInitDriver() {
if (!this._driver) this.initDriver();
if (!this._driver) throw "No suitable blue tooth driver found to connect to the ergometer.";
}
/**
*
*/
protected initialize() {
super.initialize();
this._splitCommandsWhenToBig=true;
this._receivePartialBuffers=true;
/*document.addEventListener(
'deviceready',
()=> {
evothings.scriptsLoaded(()=>{
this.onDeviceReady();})},
false); */
this.initDriver();
var enableDisableFunc = ()=>{this.enableDisableNotification().catch(this.handleError)};
this._rowingGeneralStatusEvent = new pubSub.Event<RowingGeneralStatusEvent>();
this.rowingGeneralStatusEvent.registerChangedEvent(enableDisableFunc);
this._rowingAdditionalStatus1Event = new pubSub.Event<RowingAdditionalStatus1Event>();
this.rowingAdditionalStatus1Event.registerChangedEvent(enableDisableFunc);
this._rowingAdditionalStatus2Event = new pubSub.Event<RowingAdditionalStatus2Event>();
this.rowingAdditionalStatus2Event.registerChangedEvent(enableDisableFunc);
this._rowingStrokeDataEvent = new pubSub.Event<RowingStrokeDataEvent>();
this.rowingStrokeDataEvent.registerChangedEvent(enableDisableFunc);
this._rowingAdditionalStrokeDataEvent = new pubSub.Event<RowingAdditionalStrokeDataEvent>();
this.rowingAdditionalStrokeDataEvent.registerChangedEvent(enableDisableFunc);
this._rowingSplitIntervalDataEvent = new pubSub.Event<RowingSplitIntervalDataEvent>();
this.rowingSplitIntervalDataEvent.registerChangedEvent(enableDisableFunc);
this._rowingAdditionalSplitIntervalDataEvent = new pubSub.Event<RowingAdditionalSplitIntervalDataEvent>();
this.rowingAdditionalSplitIntervalDataEvent.registerChangedEvent(enableDisableFunc);
this._workoutSummaryDataEvent = new pubSub.Event<WorkoutSummaryDataEvent>();
this.workoutSummaryDataEvent.registerChangedEvent(enableDisableFunc);
this._additionalWorkoutSummaryDataEvent = new pubSub.Event<AdditionalWorkoutSummaryDataEvent>();
this.additionalWorkoutSummaryDataEvent.registerChangedEvent(enableDisableFunc);
this._additionalWorkoutSummaryData2Event = new pubSub.Event<AdditionalWorkoutSummaryData2Event>();
this.additionalWorkoutSummaryData2Event.registerChangedEvent(enableDisableFunc);
this._heartRateBeltInformationEvent = new pubSub.Event<HeartRateBeltInformationEvent>();
this.heartRateBeltInformationEvent.registerChangedEvent(enableDisableFunc);
}
/**
* When low level initialization complete, this function is called.
*/
/*
protected onDeviceReady() {
// Report status.
this.changeConnectionState( MonitorConnectionState.deviceReady);
if (this._active)
this.startConnection();
}
*/
/**
*
* @param device
*/
protected removeDevice(device : DeviceInfo) {
this._devices=this._devices.splice(this._devices.indexOf(device),1);
}
/**
*
* @param device
*/
protected addDevice(device : DeviceInfo) {
var existing = this.findDevice(device.name);
if (existing) this.removeDevice(existing);
this._devices.push(device);
//sort on hightest quality above
this._devices.sort((device1,device2 : DeviceInfo) : number=>{ return device2.quality-device1.quality });
}
/**
*
* @param name
* @returns {DeviceInfo}
*/
protected findDevice(name : string) : DeviceInfo {
var result : DeviceInfo=null;
this._devices.forEach((device)=> {
if (device.name==name) result=device;
});
return result;
}
/**
*
*/
public stopScan() {
if (this.connectionState==MonitorConnectionState.scanning) {
this.driver.stopScan(); }
}
/**
* Scan for device use the deviceFound to connect .
* @param deviceFound
*/
public startScan(deviceFound : (device : DeviceInfo)=>boolean,errorFn? : ErrorHandler ) :Promise<void> {
try {
this.checkInitDriver();
this._devices=[];
// Save it for next time we use the this.
//localStorage.setItem('deviceName', this._deviceName);
// Call stop before you start, just in case something else is running.
this.stopScan();
this.changeConnectionState(MonitorConnectionState.scanning);
// Only report s once.
//evothings.easyble.reportDeviceOnce(true);
return this.driver.startScan(
(device) => {
// Do not show un-named devices.
/*var deviceName = device.advertisementData ?
device.advertisementData.kCBAdvDataLocalName : null;
*/
if (!device.name) {
return
}
// Print "name : mac address" for every device found.
this.debugInfo(device.name + ' : ' + device.address.toString().split(':').join(''));
// If my device is found connect to it.
//find any thing starting with PM and then a number a space and a serial number
if ( device.name.match(/PM\d \d*/g) ) {
this.showInfo('Status: DeviceInfo found: ' + device.name);
var deviceInfo : DeviceInfo={
connected:false,
_internalDevice: device,
name:device.name,
address:device.address,
quality: 2* (device.rssi + 100) };
this.addDevice(deviceInfo);
if ( deviceFound && deviceFound(deviceInfo)) {
this.connectToDevice(deviceInfo.name);
}
}
}
).then(()=> {
this.showInfo('Status: Scanning...');
}).catch(
this.getErrorHandlerFunc("Scan error",(e)=>{
if (errorFn) errorFn(e);
if (this.connectionState<MonitorConnectionState.connected)
this.changeConnectionState(MonitorConnectionState.deviceReady);
})
);
}
catch (e) {
if (this.connectionState<MonitorConnectionState.connected)
this.changeConnectionState(MonitorConnectionState.inactive);
this.getErrorHandlerFunc("Scan error",errorFn)(e);
return Promise.reject(e);
}
}
/**
* connect to a specific device. This should be a PM5 device which is found by the startScan. You can
* only call this function after startScan is called. Connection to a device will stop the scan.
* @param deviceName
*/
public connectToDevice(deviceName : string) : Promise<void> {
this.showInfo('Status: Connecting...');
this.stopScan();
this.changeConnectionState(MonitorConnectionState.connecting);
var deviceInfo = this.findDevice(deviceName);
if (!deviceInfo) throw `Device ${deviceName} not found`;
this._deviceInfo = deviceInfo;
return this.driver.connect(deviceInfo._internalDevice,
() => {
this.changeConnectionState(MonitorConnectionState.deviceReady);
this.showInfo('Disconnected');
if (this.autoReConnect && !this.currentDriverIsWebBlueTooth()) {
//do not auto connect too quick otherwise it will reconnect when
//the device has triggered a disconenct and it will end up half disconnected
setTimeout(()=>{
this.startScan((device:DeviceInfo)=> {
return device.name == deviceName
});
},2000);
}
}
).then(()=> {
this.changeConnectionState(MonitorConnectionState.connected);
this.showInfo('Status: Connected');
return this.readPheripheralInfo()
}).then( ()=> {
// Debug logging of all services, characteristics and descriptors
// reported by the BLE board.
this.deviceConnected();
}).catch((errorCode)=> {
this.changeConnectionState(MonitorConnectionState.deviceReady);
this.handleError(errorCode);
});
}
/**
* the promise is never fail
* @param serviceUUID
* @param UUID
* @param readValue
*/
protected readStringCharacteristic(serviceUUID : string,UUID : string) : Promise<string> {
return new Promise<string>((resolve, reject) => {
this.driver.readCharacteristic(serviceUUID, UUID).then(
(data:ArrayBuffer)=> {
resolve(utils.bufferToString(data));
},
reject
)
})
}
/**
* the promise will never fail
* @param done
*/
protected readSampleRate( ) : Promise<void> {
return this.driver.readCharacteristic(ble.PMROWING_SERVICE,ble.ROWING_STATUS_SAMPLE_RATE_CHARACTERISIC)
.then((data:ArrayBuffer)=>{
var view = new DataView(data);
this._sampleRate= view.getUint8(0);
})
}
/**
*
* @param done
*/
protected readPheripheralInfo() :Promise<void> {
return new Promise<void>((resolve, reject) => {
Promise.all([
this.readStringCharacteristic(ble.PMDEVICE_INFO_SERVICE, ble.SERIALNUMBER_CHARACTERISTIC)
.then((value:string)=> {
this._deviceInfo.serial = value;
}),
this.readStringCharacteristic(ble.PMDEVICE_INFO_SERVICE, ble.HWREVISION_CHARACTERISIC)
.then((value:string)=> {
this._deviceInfo.hardwareRevision = value;
}),
this.readStringCharacteristic(ble.PMDEVICE_INFO_SERVICE, ble.FWREVISION_CHARACTERISIC)
.then((value:string)=> {
this._deviceInfo.firmwareRevision = value;
}),
this.readStringCharacteristic(ble.PMDEVICE_INFO_SERVICE, ble.MANUFNAME_CHARACTERISIC)
.then((value:string)=> {
this._deviceInfo.manufacturer = value;
this._deviceInfo.connected = true;
}),
this.readSampleRate()
]).then(
()=>{resolve()},
(e)=>{this.handleError(e); resolve(e)}); //log erro let not get this into the way of connecting
});
}
/**
*
* @param data
*/
protected handleRowingGeneralStatus(data:DataView) {
var parsed:RowingGeneralStatus = {
elapsedTime: utils.getUint24(data, ble.PM_Rowing_Status_BLE_Payload.ELAPSED_TIME_LO) * 10, //in mili seconds
distance: utils.getUint24(data, ble.PM_Rowing_Status_BLE_Payload.DISTANCE_LO) / 10,
workoutType: data.getUint8(ble.PM_Rowing_Status_BLE_Payload.WORKOUT_TYPE),
intervalType: data.getUint8(ble.PM_Rowing_Status_BLE_Payload.INTERVAL_TYPE),
workoutState: data.getUint8(ble.PM_Rowing_Status_BLE_Payload.WORKOUT_STATE),
rowingState: data.getUint8(ble.PM_Rowing_Status_BLE_Payload.ROWING_STATE),
strokeState: data.getUint8(ble.PM_Rowing_Status_BLE_Payload.STROKE_STATE),
totalWorkDistance:utils.getUint24(data, ble.PM_Rowing_Status_BLE_Payload.TOTAL_WORK_DISTANCE_LO),
workoutDuration:utils.getUint24(data, ble.PM_Rowing_Status_BLE_Payload.WORKOUT_DURATION_LO),
workoutDurationType :data.getUint8(ble.PM_Rowing_Status_BLE_Payload.WORKOUT_DURATION_TYPE),
dragFactor : data.getUint8(ble.PM_Rowing_Status_BLE_Payload.DRAG_FACTOR),
};
if (parsed.workoutDurationType==WorkoutDurationType.timeDuration)
parsed.workoutDuration=parsed.workoutDuration*10;//in mili seconds
if (JSON.stringify(this.rowingGeneralStatus) !== JSON.stringify(parsed)) {
this.rowingGeneralStatusEvent.pub(parsed);
this._rowingGeneralStatus=parsed;
}
}
protected calcPace(lowByte,highByte : number) {
return (lowByte + highByte*256)*10;
}
/**
*
* @param data
*/
protected handleRowingAdditionalStatus1(data:DataView) {
var parsed:RowingAdditionalStatus1 = {
elapsedTime: utils.getUint24(data, ble.PM_Extra_Status1_BLE_Payload.ELAPSED_TIME_LO)* 10, //in mili seconds
speed : data.getUint16(ble.PM_Extra_Status1_BLE_Payload.SPEED_LO)/1000, // m/s
strokeRate : data.getUint8(ble.PM_Extra_Status1_BLE_Payload.STROKE_RATE),
heartRate : utils.valueToNullValue(data.getUint8(ble.PM_Extra_Status1_BLE_Payload.HEARTRATE),255),
currentPace : this.calcPace(data.getUint8(ble.PM_Extra_Status1_BLE_Payload.CURRENT_PACE_LO),data.getUint8(ble.PM_Extra_Status1_BLE_Payload.CURRENT_PACE_HI)),
averagePace : this.calcPace(data.getUint8(ble.PM_Extra_Status1_BLE_Payload.AVG_PACE_LO),data.getUint8(ble.PM_Extra_Status1_BLE_Payload.AVG_PACE_HI)),
restDistance : data.getUint16(ble.PM_Extra_Status1_BLE_Payload.REST_DISTANCE_LO),
restTime : utils.getUint24(data,ble.PM_Extra_Status1_BLE_Payload.REST_TIME_LO)*10, //mili seconds
averagePower : null
};
if (data.byteLength==ble.PM_Mux_Extra_Status1_BLE_Payload.BLE_PAYLOAD_SIZE)
parsed.averagePower=data.getUint16(ble.PM_Mux_Extra_Status1_BLE_Payload.AVG_POWER_LO);
if ( JSON.stringify(this.rowingAdditionalStatus1) !== JSON.stringify(parsed)) {
this.rowingAdditionalStatus1Event.pub(parsed);
this._rowingAdditionalStatus1=parsed;
}
}
/**
*
* @param data
*/
protected handleRowingAdditionalStatus2(data:DataView) {
var parsed:RowingAdditionalStatus2;
if (data.byteLength == ble.PM_Extra_Status2_BLE_Payload.BLE_PAYLOAD_SIZE) {
parsed = {
elapsedTime: utils.getUint24(data, ble.PM_Extra_Status2_BLE_Payload.ELAPSED_TIME_LO) * 10, //in mili seconds
intervalCount: data.getUint8(ble.PM_Extra_Status2_BLE_Payload.INTERVAL_COUNT),
averagePower: data.getUint16(ble.PM_Extra_Status2_BLE_Payload.AVG_POWER_LO),
totalCalories: data.getUint16(ble.PM_Extra_Status2_BLE_Payload.TOTAL_CALORIES_LO),
splitAveragePace: this.calcPace(data.getUint8(ble.PM_Extra_Status2_BLE_Payload.SPLIT_INTERVAL_AVG_PACE_LO),data.getUint8(ble.PM_Extra_Status2_BLE_Payload.SPLIT_INTERVAL_AVG_PACE_HI)),// ms,
splitAveragePower: data.getUint16(ble.PM_Extra_Status2_BLE_Payload.SPLIT_INTERVAL_AVG_POWER_LO),//watt
splitAverageCalories: data.getUint16(ble.PM_Extra_Status2_BLE_Payload.SPLIT_INTERVAL_AVG_CALORIES_LO), // cal/hour
lastSplitTime: data.getUint16(ble.PM_Extra_Status2_BLE_Payload.LAST_SPLIT_TIME_LO) *100, //the doc 0.1 factor is this right?
lastSplitDistance: utils.getUint24(data, ble.PM_Extra_Status2_BLE_Payload.LAST_SPLIT_DISTANCE_LO)
};
}
else {
parsed = {
elapsedTime: utils.getUint24(data, ble.PM_Mux_Extra_Status2_BLE_Payload.ELAPSED_TIME_LO) * 10, //in mili seconds
intervalCount: data.getUint8(ble.PM_Mux_Extra_Status2_BLE_Payload.INTERVAL_COUNT),
averagePower: null,
totalCalories: data.getUint16(ble.PM_Mux_Extra_Status2_BLE_Payload.TOTAL_CALORIES_LO),
splitAveragePace: this.calcPace(data.getUint8(ble.PM_Mux_Extra_Status2_BLE_Payload.SPLIT_INTERVAL_AVG_PACE_LO),data.getUint8(ble.PM_Mux_Extra_Status2_BLE_Payload.SPLIT_INTERVAL_AVG_PACE_HI)), //ms,
splitAveragePower: data.getUint16(ble.PM_Mux_Extra_Status2_BLE_Payload.SPLIT_INTERVAL_AVG_POWER_LO),//watt
splitAverageCalories: data.getUint16(ble.PM_Mux_Extra_Status2_BLE_Payload.SPLIT_INTERVAL_AVG_CALORIES_LO), // cal/hour
lastSplitTime: data.getUint16(ble.PM_Mux_Extra_Status2_BLE_Payload.LAST_SPLIT_TIME_LO) *100, //the doc 0.1 factor is this right?
lastSplitDistance: utils.getUint24(data, ble.PM_Mux_Extra_Status2_BLE_Payload.LAST_SPLIT_DISTANCE_LO)
}
}
if (JSON.stringify(this.rowingAdditionalStatus2) !== JSON.stringify(parsed)) {
this.rowingAdditionalStatus2Event.pub(parsed);
this._rowingAdditionalStatus2 = parsed;
}
}
/**
*
* @param data
*/
protected handleRowingStrokeData(data:DataView) {
var parsed:RowingStrokeData;
if (data.byteLength == ble.PM_Stroke_Data_BLE_Payload.BLE_PAYLOAD_SIZE) {
parsed = {
elapsedTime: utils.getUint24(data, ble.PM_Stroke_Data_BLE_Payload.ELAPSED_TIME_LO) * 10, //in mili seconds
distance: utils.getUint24(data, ble.PM_Stroke_Data_BLE_Payload.DISTANCE_LO) / 10, //meter
driveLength: data.getUint8(ble.PM_Stroke_Data_BLE_Payload.DRIVE_LENGTH) / 100, //meters
driveTime: data.getUint8(ble.PM_Stroke_Data_BLE_Payload.DRIVE_TIME) * 10, //ms
strokeRecoveryTime: (data.getUint8(ble.PM_Stroke_Data_BLE_Payload.STROKE_RECOVERY_TIME_LO) + data.getUint8(ble.PM_Stroke_Data_BLE_Payload.STROKE_RECOVERY_TIME_HI)*256) * 10, //ms
strokeDistance: data.getUint16(ble.PM_Stroke_Data_BLE_Payload.STROKE_DISTANCE_LO) / 100,//meter
peakDriveForce: data.getUint16(ble.PM_Stroke_Data_BLE_Payload.PEAK_DRIVE_FORCE_LO) / 10, //lbs
averageDriveForce: data.getUint16(ble.PM_Stroke_Data_BLE_Payload.AVG_DRIVE_FORCE_LO) / 10, //lbs
workPerStroke: data.getUint16(ble.PM_Stroke_Data_BLE_Payload.WORK_PER_STROKE_LO) / 10, //jouls
strokeCount: data.getUint8(ble.PM_Stroke_Data_BLE_Payload.STROKE_COUNT_LO)+data.getUint8(ble.PM_Stroke_Data_BLE_Payload.STROKE_COUNT_HI) * 256 //PM bug: LSB and MSB are swapped
}
}
else {
parsed = {
elapsedTime: utils.getUint24(data, ble.PM_Mux_Stroke_Data_BLE_Payload.ELAPSED_TIME_LO) * 10, //in mili seconds
distance: utils.getUint24(data, ble.PM_Mux_Stroke_Data_BLE_Payload.DISTANCE_LO) / 10, //meter
driveLength: data.getUint8(ble.PM_Mux_Stroke_Data_BLE_Payload.DRIVE_LENGTH) / 100, //meters
driveTime: data.getUint8(ble.PM_Mux_Stroke_Data_BLE_Payload.DRIVE_TIME) * 10, //ms
strokeRecoveryTime: data.getUint16(ble.PM_Mux_Stroke_Data_BLE_Payload.STROKE_RECOVERY_TIME_LO) * 10, //ms
strokeDistance: data.getUint16(ble.PM_Mux_Stroke_Data_BLE_Payload.STROKE_DISTANCE_LO) / 100,//meter
peakDriveForce: data.getUint16(ble.PM_Mux_Stroke_Data_BLE_Payload.PEAK_DRIVE_FORCE_LO) / 10, //lbs
averageDriveForce: data.getUint16(ble.PM_Mux_Stroke_Data_BLE_Payload.AVG_DRIVE_FORCE_LO) / 10, //lbs
workPerStroke: null,
strokeCount: data.getUint8(ble.PM_Mux_Stroke_Data_BLE_Payload.STROKE_COUNT_LO)+data.getUint8(ble.PM_Mux_Stroke_Data_BLE_Payload.STROKE_COUNT_HI) * 256 //PM bug: LSB and MSB are swapped
}
}
if (JSON.stringify(this.rowingStrokeData) !== JSON.stringify(parsed)) {
this.rowingStrokeDataEvent.pub(parsed);
this._rowingStrokeData = parsed;
}
}
/**
*
* @param data
*/
protected handleRowingAdditionalStrokeData(data:DataView) {
var parsed:RowingAdditionalStrokeData = {
elapsedTime: utils.getUint24(data, ble.PM_Extra_Stroke_Data_BLE_Payload.ELAPSED_TIME_LO) * 10, //in mili seconds
strokePower : data.getUint8(ble.PM_Extra_Stroke_Data_BLE_Payload.STROKE_POWER_LO) +data.getUint8(ble.PM_Extra_Stroke_Data_BLE_Payload.STROKE_POWER_HI) *256, //watts
strokeCalories : data.getUint16(ble.PM_Extra_Stroke_Data_BLE_Payload.STROKE_CALORIES_LO), //cal/hr
strokeCount: data.getUint8(ble.PM_Extra_Stroke_Data_BLE_Payload.STROKE_COUNT_LO)+data.getUint8(ble.PM_Extra_Stroke_Data_BLE_Payload.STROKE_COUNT_HI) * 256, //PM bug: LSB and MSB are swapped
projectedWorkTime : utils.getUint24(data, ble.PM_Extra_Stroke_Data_BLE_Payload.PROJ_WORK_TIME_LO)*1000, //ms
projectedWorkDistance : utils.getUint24(data, ble.PM_Extra_Stroke_Data_BLE_Payload.PROJ_WORK_DIST_LO), //meter
workPerStroke : null //filled when multiplexed is true
};
if (data.byteLength==ble.PM_Mux_Extra_Stroke_Data_BLE_Payload.BLE_PAYLOAD_SIZE)
parsed.workPerStroke = data.getUint16(ble.PM_Mux_Extra_Stroke_Data_BLE_Payload.WORK_PER_STROKE_LO);
if (JSON.stringify(this.rowingAdditionalStrokeData) !== JSON.stringify(parsed)) {
this.rowingAdditionalStrokeDataEvent.pub(parsed);
this._rowingAdditionalStrokeData = parsed;
}
}
/**
*
* @param data
*/
protected handleRowingSplitIntervalData(data:DataView) {
var parsed:RowingSplitIntervalData = {
elapsedTime: utils.getUint24(data, ble.PM_Split_Interval_Data_BLE_Payload.ELAPSED_TIME_LO) * 10, //in mili seconds
distance : utils.getUint24(data, ble.PM_Split_Interval_Data_BLE_Payload.DISTANCE_LO)/10, //meters
intervalTime : utils.getUint24(data, ble.PM_Split_Interval_Data_BLE_Payload.SPLIT_TIME_LO)*100,
intervalDistance : utils.getUint24(data, ble.PM_Split_Interval_Data_BLE_Payload.SPLIT_DISTANCE_LO),
intervalRestTime : data.getUint16(ble.PM_Split_Interval_Data_BLE_Payload.REST_TIME_LO)*1000,
intervalRestDistance : data.getUint16(ble.PM_Split_Interval_Data_BLE_Payload.REST_DISTANCE_LO),//meter
intervalType : data.getUint8(ble.PM_Split_Interval_Data_BLE_Payload.TYPE),
intervalNumber : data.getUint8(ble.PM_Split_Interval_Data_BLE_Payload.INT_NUMBER),
};
if (JSON.stringify(this.rowingSplitIntervalData) !== JSON.stringify(parsed)) {
this.rowingSplitIntervalDataEvent.pub(parsed);
this._rowingSplitIntervalData = parsed;
}
}
/**
*
* @param data
*/
protected handleRowingAdditionalSplitIntervalData(data:DataView) {
var parsed:RowingAdditionalSplitIntervalData = {
elapsedTime: utils.getUint24(data, ble.PM_Extra_Split_Interval_Data_BLE_Payload.ELAPSED_TIME_LO) * 10, //in mili seconds
intervalAverageStrokeRate : data.getUint8(ble.PM_Extra_Split_Interval_Data_BLE_Payload.STROKE_RATE),
intervalWorkHeartrate : data.getUint8(ble.PM_Extra_Split_Interval_Data_BLE_Payload.WORK_HR),
intervalRestHeartrate : data.getUint8(ble.PM_Extra_Split_Interval_Data_BLE_Payload.REST_HR),
intervalAveragePace : data.getUint16(ble.PM_Extra_Split_Interval_Data_BLE_Payload.AVG_PACE_LO)*10, //ms lbs
intervalTotalCalories : data.getUint16(ble.PM_Extra_Split_Interval_Data_BLE_Payload.CALORIES_LO),
intervalAverageCalories : data.getUint16(ble.PM_Extra_Split_Interval_Data_BLE_Payload.AVG_CALORIES_LO),
intervalSpeed : data.getUint16(ble.PM_Extra_Split_Interval_Data_BLE_Payload.SPEED_LO)/1000, //m/s
intervalPower : data.getUint16(ble.PM_Extra_Split_Interval_Data_BLE_Payload.POWER_LO),
splitAverageDragFactor : data.getUint8(ble.PM_Extra_Split_Interval_Data_BLE_Payload.AVG_DRAG_FACTOR),
intervalNumber : data.getUint8(ble.PM_Extra_Split_Interval_Data_BLE_Payload.INT_NUMBER)
};
if (JSON.stringify(this.rowingAdditionalSplitIntervalData) !== JSON.stringify(parsed)) {
this.rowingAdditionalSplitIntervalDataEvent.pub(parsed);
this._rowingAdditionalSplitIntervalData = parsed;
}
}
/**
*
* @param data
*/
protected handleWorkoutSummaryData(data:DataView) {
var parsed:WorkoutSummaryData = {
logEntryDate : data.getUint16(ble.PM_Workout_Summary_Data_BLE_Payload.LOG_DATE_LO),
logEntryTime : data.getUint16(ble.PM_Workout_Summary_Data_BLE_Payload.LOG_TIME_LO),
elapsedTime : utils.getUint24(data, ble.PM_Workout_Summary_Data_BLE_Payload.ELAPSED_TIME_LO) * 10,
distance : utils.getUint24(data, ble.PM_Workout_Summary_Data_BLE_Payload.DISTANCE_LO)/10,
averageStrokeRate : data.getUint8(ble.PM_Workout_Summary_Data_BLE_Payload.AVG_SPM),
endingHeartrate : data.getUint8(ble.PM_Workout_Summary_Data_BLE_Payload.END_HR),
averageHeartrate : data.getUint8(ble.PM_Workout_Summary_Data_BLE_Payload.AVG_HR),
minHeartrate : data.getUint8(ble.PM_Workout_Summary_Data_BLE_Payload.MIN_HR),
maxHeartrate : data.getUint8(ble.PM_Workout_Summary_Data_BLE_Payload.MAX_HR),
dragFactorAverage : data.getUint8(ble.PM_Workout_Summary_Data_BLE_Payload.AVG_DRAG_FACTOR),
recoveryHeartRate : data.getUint8(ble.PM_Workout_Summary_Data_BLE_Payload.RECOVERY_HR),
workoutType : data.getUint8(ble.PM_Workout_Summary_Data_BLE_Payload.WORKOUT_TYPE),
averagePace : null
};
if (data.byteLength==ble.PM_Workout_Summary_Data_BLE_Payload.BLE_PAYLOAD_SIZE) {
parsed.averagePace = data.getUint16(ble.PM_Workout_Summary_Data_BLE_Payload.AVG_PACE_LO);
}
if (JSON.stringify(this.workoutSummaryData) !== JSON.stringify(parsed)) {
this.workoutSummaryDataEvent.pub(parsed);
this._workoutSummaryData = parsed;
}
}
/**
*
* @param data
*/
protected handleAdditionalWorkoutSummaryData(data:DataView) {
var parsed:AdditionalWorkoutSummaryData;
if (data.byteLength==ble.PM_Extra_Workout_Summary_Data_BLE_Payload.DATA_BLE_PAYLOAD_SIZE) {
parsed = {
logEntryDate : data.getUint16(ble.PM_Extra_Workout_Summary_Data_BLE_Payload.LOG_DATE_LO),
logEntryTime : data.getUint16(ble.PM_Extra_Workout_Summary_Data_BLE_Payload.LOG_DATE_HI),
intervalType : data.getUint8(ble.PM_Extra_Workout_Summary_Data_BLE_Payload.SPLIT_INT_TYPE),
intervalSize: data.getUint16(ble.PM_Extra_Workout_Summary_Data_BLE_Payload.SPLIT_INT_SIZE_LO),//meters or seconds
intervalCount: data.getUint8(ble.PM_Extra_Workout_Summary_Data_BLE_Payload.SPLIT_INT_COUNT),
totalCalories: data.getUint16(ble.PM_Extra_Workout_Summary_Data_BLE_Payload.WORK_CALORIES_LO),
watts: data.getUint16(ble.PM_Extra_Workout_Summary_Data_BLE_Payload.WATTS_LO),
totalRestDistance : utils.getUint24(data, ble.PM_Extra_Workout_Summary_Data_BLE_Payload.TOTAL_REST_DISTANCE_LO) ,
intervalRestTime : data.getUint16(ble.PM_Extra_Workout_Summary_Data_BLE_Payload.INTERVAL_REST_TIME_LO),
averageCalories : data.getUint16(ble.PM_Extra_Workout_Summary_Data_BLE_Payload.AVG_CALORIES_LO)
}
}
else {
parsed = {
logEntryDate : data.getUint16(ble.PM_Mux_Extra_Workout_Summary_Data_BLE_Payload.LOG_DATE_LO),
logEntryTime : data.getUint16(ble.PM_Mux_Extra_Workout_Summary_Data_BLE_Payload.LOG_TIME_LO),
intervalType : null,
intervalSize: data.getUint16(ble.PM_Mux_Extra_Workout_Summary_Data_BLE_Payload.SPLIT_INT_SIZE_LO),//meters or seconds
intervalCount: data.getUint8(ble.PM_Mux_Extra_Workout_Summary_Data_BLE_Payload.SPLIT_INT_COUNT),
totalCalories: data.getUint16(ble.PM_Mux_Extra_Workout_Summary_Data_BLE_Payload.WORK_CALORIES_LO),
watts: data.getUint16(ble.PM_Mux_Extra_Workout_Summary_Data_BLE_Payload.WATTS_LO),
totalRestDistance : utils.getUint24(data, ble.PM_Mux_Extra_Workout_Summary_Data_BLE_Payload.TOTAL_REST_DISTANCE_LO) ,
intervalRestTime : data.getUint16(ble.PM_Mux_Extra_Workout_Summary_Data_BLE_Payload.INTERVAL_REST_TIME_LO),
averageCalories : data.getUint16(ble.PM_Mux_Extra_Workout_Summary_Data_BLE_Payload.AVG_CALORIES_LO)
}
}
if (JSON.stringify(this.additionalWorkoutSummaryData) !== JSON.stringify(parsed)) {
this.additionalWorkoutSummaryDataEvent.pub(parsed);
this._additionalWorkoutSummaryData = parsed;
}
}
/**
*
* @param data
*/
protected handleAdditionalWorkoutSummaryData2(data:DataView) {
var parsed:AdditionalWorkoutSummaryData2 = {
logEntryDate : data.getUint16(ble.PM_Mux_Extra_Workout_Summary2_Data_BLE_Payload.LOG_DATE_LO),
logEntryTime : data.getUint16(ble.PM_Mux_Extra_Workout_Summary2_Data_BLE_Payload.LOG_DATE_HI),
averagePace : data.getUint16(ble.PM_Mux_Extra_Workout_Summary2_Data_BLE_Payload.AVG_PACE_LO),
gameIdentifier : data.getUint8(ble.PM_Mux_Extra_Workout_Summary2_Data_BLE_Payload.GAME_ID),
gameScore : data.getUint16(ble.PM_Mux_Extra_Workout_Summary2_Data_BLE_Payload.GAME_SCORE_LO),
ergMachineType : data.getUint8(ble.PM_Mux_Extra_Workout_Summary2_Data_BLE_Payload.MACHINE_TYPE),
};
if (JSON.stringify(this.additionalWorkoutSummaryData2) !== JSON.stringify(parsed)) {
this.additionalWorkoutSummaryData2Event.pub(parsed);
this._additionalWorkoutSummaryData2 = parsed;
}
}
/**
*
* @param data
*/
protected handleHeartRateBeltInformation(data:DataView) {
var parsed:HeartRateBeltInformation = {
manufacturerId : data.getUint8(ble.PM_Heart_Rate_Belt_Info_BLE_Payload.MANUFACTURER_ID),
deviceType: data.getUint8(ble.PM_Heart_Rate_Belt_Info_BLE_Payload.DEVICE_TYPE),
beltId : data.getUint32(ble.PM_Heart_Rate_Belt_Info_BLE_Payload.BELT_ID_LO),
};
if (JSON.stringify(this.heartRateBeltInformation) !== JSON.stringify(parsed)) {
this.heartRateBeltInformationEvent.pub(parsed);
this._heartRateBeltInformation = parsed;
}
}
/**
*
* @internal
*/
protected deviceConnected() {
this.debugInfo("readServices success");
this.debugInfo('Status: notifications are activated');
//handle to the notification
this.changeConnectionState(MonitorConnectionState.servicesFound);
//first enable all notifications and wait till they are active
//and then set the connection state to ready
this.handleCSafeNotifications().then(()=>{
return this.enableDisableNotification()
}).then(()=>{
//fix problem of notifications not completaly ready yet
this.changeConnectionState(MonitorConnectionState.readyForCommunication);
}).catch(this.handleError);
//allways connect to csafe
}
public handleCSafeNotifications(): Promise<void> {
this.traceInfo("enable notifications csafe");
return this.enableNotification(ble.PMCONTROL_SERVICE,ble.RECEIVE_FROM_PM_CHARACTERISIC,
(data:ArrayBuffer) => {
var dataView = new DataView(data);
this.handeReceivedDriverData(dataView);
}
).catch(this.getErrorHandlerFunc(""));
}
/**
*
* @param data
*/
protected handleDataCallbackMulti(data:ArrayBuffer) {
//this.debugInfo("multi data received: " + evothings.util.typedArrayToHexString(data));
var ar = new DataView(data);
var dataType:ble.PM_Multiplexed_Info_Type_ID = ar.getUint8(0);
ar = new DataView(data, 1);
switch (dataType) {
case ble.PM_Multiplexed_Info_Type_ID.ROWING_GENERAL_STATUS : {
if (this.rowingGeneralStatusEvent.count>0) this.handleRowingGeneralStatus(ar);
break;
}
case ble.PM_Multiplexed_Info_Type_ID.ROWING_ADDITIONAL_STATUS1 : {
if (this.rowingAdditionalStatus1Event.count>0) this.handleRowingAdditionalStatus1(ar);
break;
}
case ble.PM_Multiplexed_Info_Type_ID.ROWING_ADDITIONAL_STATUS2 : {
if (this.rowingAdditionalStatus2Event.count>0) this.handleRowingAdditionalStatus2(ar);
break;
}
case ble.PM_Multiplexed_Info_Type_ID.STROKE_DATA_STATUS : {
if (this.rowingStrokeDataEvent.count>0) this.handleRowingStrokeData(ar);
break;
}
case ble.PM_Multiplexed_Info_Type_ID.EXTRA_STROKE_DATA_STATUS : {
if (this.rowingAdditionalStrokeDataEvent.count>0) this.handleRowingAdditionalStrokeData(ar);
break;
}
case ble.PM_Multiplexed_Info_Type_ID.SPLIT_INTERVAL_STATUS : {
if (this.rowingSplitIntervalDataEvent.count>0) this.handleRowingSplitIntervalData(ar);
break;
}
case ble.PM_Multiplexed_Info_Type_ID.EXTRA_SPLIT_INTERVAL_STATUS : {
if (this.rowingAdditionalSplitIntervalDataEvent.count>0) this.handleRowingAdditionalSplitIntervalData(ar);
break;
}
case ble.PM_Multiplexed_Info_Type_ID.WORKOUT_SUMMARY_STATUS : {
if (this.workoutSummaryDataEvent.count>0) this.handleWorkoutSummaryData(ar);
break;
}
case ble.PM_Multiplexed_Info_Type_ID.EXTRA_WORKOUT_SUMMARY_STATUS1 : {
if (this.additionalWorkoutSummaryDataEvent.count>0) this.handleAdditionalWorkoutSummaryData(ar);
break;
}
case ble.PM_Multiplexed_Info_Type_ID.HEART_RATE_BELT_INFO_STATUS : {
if (this.heartRateBeltInformationEvent.count>0) this.handleHeartRateBeltInformation(ar);
break;
}
case ble.PM_Multiplexed_Info_Type_ID.EXTRA_WORKOUT_SUMMARY_STATUS2 : {
if (this.additionalWorkoutSummaryData2Event.count>0) this.handleAdditionalWorkoutSummaryData2(ar);
break;
}
}
};
/**
*
* @param data
* @param func
*/
protected handleDataCallback(data:ArrayBuffer, func:(data:DataView)=>void) {
//this.debugInfo("data received: " + evothings.util.typedArrayToHexString(data));
var ar = new DataView(data);
//call the function within the scope of the object
func.apply(this,[ar]);
}
protected driver_write( data:ArrayBufferView) : Promise<void> {
return this.driver.writeCharacteristic(ble.PMCONTROL_SERVICE,ble.TRANSMIT_TO_PM_CHARACTERISIC,data)
}
protected getPacketSize() : number {
return ble.PACKET_SIZE;
}
}
} | the_stack |
import { once } from 'vs/base/common/functional';
import { Disposable } from 'vs/base/common/lifecycle';
import { IStorage } from 'vs/base/parts/storage/common/storage';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IFileService } from 'vs/platform/files/common/files';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ILifecycleMainService, LifecycleMainPhase, ShutdownReason } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
import { ILogService } from 'vs/platform/log/common/log';
import { AbstractStorageService, IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { ApplicationStorageMain, GlobalStorageMain, InMemoryStorageMain, IStorageMain, IStorageMainOptions, WorkspaceStorageMain } from 'vs/platform/storage/electron-main/storageMain';
import { IUserDataProfile, IUserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfile';
import { IEmptyWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, IWorkspaceIdentifier } from 'vs/platform/workspace/common/workspace';
//#region Storage Main Service (intent: make application, global and workspace storage accessible to windows from main process)
export const IStorageMainService = createDecorator<IStorageMainService>('storageMainService');
export interface IStorageMainService {
readonly _serviceBrand: undefined;
/**
* Provides access to the application storage shared across all
* windows and all profiles.
*
* Note: DO NOT use this for reading/writing from the main process!
* Rather use `IApplicationStorageMainService` for that purpose.
*/
applicationStorage: IStorageMain;
/**
* Provides access to the global storage shared across all windows
* for the provided profile.
*
* Note: DO NOT use this for reading/writing from the main process!
* This is currently not supported.
*/
globalStorage(profile: IUserDataProfile): IStorageMain;
/**
* Provides access to the workspace storage specific to a single window.
*
* Note: DO NOT use this for reading/writing from the main process!
* This is currently not supported.
*/
workspaceStorage(workspace: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | IEmptyWorkspaceIdentifier): IStorageMain;
}
export class StorageMainService extends Disposable implements IStorageMainService {
declare readonly _serviceBrand: undefined;
private shutdownReason: ShutdownReason | undefined = undefined;
constructor(
@ILogService private readonly logService: ILogService,
@IEnvironmentService private readonly environmentService: IEnvironmentService,
@IUserDataProfilesService private readonly userDataProfilesService: IUserDataProfilesService,
@ILifecycleMainService private readonly lifecycleMainService: ILifecycleMainService,
@IFileService private readonly fileService: IFileService
) {
super();
this.registerListeners();
}
protected getStorageOptions(): IStorageMainOptions {
return {
useInMemoryStorage: !!this.environmentService.extensionTestsLocationURI // no storage during extension tests!
};
}
private registerListeners(): void {
// Application Storage: Warmup when any window opens
(async () => {
await this.lifecycleMainService.when(LifecycleMainPhase.AfterWindowOpen);
this.applicationStorage.init();
})();
this._register(this.lifecycleMainService.onWillLoadWindow(e => {
// Global Storage: Warmup when related window with profile loads
if (e.window.profile) {
this.globalStorage(e.window.profile).init();
}
// Workspace Storage: Warmup when related window with workspace loads
if (e.workspace) {
this.workspaceStorage(e.workspace).init();
}
}));
// All Storage: Close when shutting down
this._register(this.lifecycleMainService.onWillShutdown(e => {
this.logService.trace('storageMainService#onWillShutdown()');
// Remember shutdown reason
this.shutdownReason = e.reason;
// Application Storage
e.join(this.applicationStorage.close());
// Global Storage(s)
for (const [, globalStorage] of this.mapProfileToStorage) {
e.join(globalStorage.close());
}
// Workspace Storage(s)
for (const [, workspaceStorage] of this.mapWorkspaceToStorage) {
e.join(workspaceStorage.close());
}
}));
}
//#region Application Storage
readonly applicationStorage = this.createApplicationStorage();
private createApplicationStorage(): IStorageMain {
this.logService.trace(`StorageMainService: creating application storage`);
const applicationStorage = new ApplicationStorageMain(this.getStorageOptions(), this.userDataProfilesService, this.logService, this.fileService);
once(applicationStorage.onDidCloseStorage)(() => {
this.logService.trace(`StorageMainService: closed application storage`);
});
return applicationStorage;
}
//#endregion
//#region Global Storage
private readonly mapProfileToStorage = new Map<string /* profile ID */, IStorageMain>();
globalStorage(profile: IUserDataProfile): IStorageMain {
if (profile.isDefault) {
return this.applicationStorage; // for default profile, use application storage
}
let globalStorage = this.mapProfileToStorage.get(profile.id);
if (!globalStorage) {
this.logService.trace(`StorageMainService: creating global storage (${profile.name})`);
globalStorage = this.createGlobalStorage(profile);
this.mapProfileToStorage.set(profile.id, globalStorage);
once(globalStorage.onDidCloseStorage)(() => {
this.logService.trace(`StorageMainService: closed global storage (${profile.name})`);
this.mapProfileToStorage.delete(profile.id);
});
}
return globalStorage;
}
private createGlobalStorage(profile: IUserDataProfile): IStorageMain {
if (this.shutdownReason === ShutdownReason.KILL) {
// Workaround for native crashes that we see when
// SQLite DBs are being created even after shutdown
// https://github.com/microsoft/vscode/issues/143186
return new InMemoryStorageMain(this.logService, this.fileService);
}
return new GlobalStorageMain(profile, this.getStorageOptions(), this.logService, this.fileService);
}
//#endregion
//#region Workspace Storage
private readonly mapWorkspaceToStorage = new Map<string /* workspace ID */, IStorageMain>();
workspaceStorage(workspace: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | IEmptyWorkspaceIdentifier): IStorageMain {
let workspaceStorage = this.mapWorkspaceToStorage.get(workspace.id);
if (!workspaceStorage) {
this.logService.trace(`StorageMainService: creating workspace storage (${workspace.id})`);
workspaceStorage = this.createWorkspaceStorage(workspace);
this.mapWorkspaceToStorage.set(workspace.id, workspaceStorage);
once(workspaceStorage.onDidCloseStorage)(() => {
this.logService.trace(`StorageMainService: closed workspace storage (${workspace.id})`);
this.mapWorkspaceToStorage.delete(workspace.id);
});
}
return workspaceStorage;
}
private createWorkspaceStorage(workspace: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | IEmptyWorkspaceIdentifier): IStorageMain {
if (this.shutdownReason === ShutdownReason.KILL) {
// Workaround for native crashes that we see when
// SQLite DBs are being created even after shutdown
// https://github.com/microsoft/vscode/issues/143186
return new InMemoryStorageMain(this.logService, this.fileService);
}
return new WorkspaceStorageMain(workspace, this.getStorageOptions(), this.logService, this.environmentService, this.fileService);
}
//#endregion
}
//#endregion
//#region Application Main Storage Service (intent: use application storage from main process)
export const IApplicationStorageMainService = createDecorator<IStorageMainService>('applicationStorageMainService');
/**
* A specialized `IStorageService` interface that only allows
* access to the `StorageScope.APPLICATION` scope.
*/
export interface IApplicationStorageMainService extends IStorageService {
/**
* Important: unlike other storage services in the renderer, the
* main process does not await the storage to be ready, rather
* storage is being initialized while a window opens to reduce
* pressure on startup.
*
* As such, any client wanting to access application storage from the
* main process needs to wait for `whenReady`, otherwise there is
* a chance that the service operates on an in-memory store that
* is not backed by any persistent DB.
*/
readonly whenReady: Promise<void>;
get(key: string, scope: StorageScope.APPLICATION, fallbackValue: string): string;
get(key: string, scope: StorageScope.APPLICATION, fallbackValue?: string): string | undefined;
getBoolean(key: string, scope: StorageScope.APPLICATION, fallbackValue: boolean): boolean;
getBoolean(key: string, scope: StorageScope.APPLICATION, fallbackValue?: boolean): boolean | undefined;
getNumber(key: string, scope: StorageScope.APPLICATION, fallbackValue: number): number;
getNumber(key: string, scope: StorageScope.APPLICATION, fallbackValue?: number): number | undefined;
store(key: string, value: string | boolean | number | undefined | null, scope: StorageScope.APPLICATION, target: StorageTarget): void;
remove(key: string, scope: StorageScope.APPLICATION): void;
keys(scope: StorageScope.APPLICATION, target: StorageTarget): string[];
switch(): never;
isNew(scope: StorageScope.APPLICATION): boolean;
}
export class ApplicationStorageMainService extends AbstractStorageService implements IApplicationStorageMainService {
declare readonly _serviceBrand: undefined;
readonly whenReady = this.storageMainService.applicationStorage.whenInit;
constructor(
@IUserDataProfilesService private readonly userDataProfilesService: IUserDataProfilesService,
@IStorageMainService private readonly storageMainService: IStorageMainService
) {
super();
}
protected doInitialize(): Promise<void> {
// application storage is being initialized as part
// of the first window opening, so we do not trigger
// it here but can join it
return this.storageMainService.applicationStorage.whenInit;
}
protected getStorage(scope: StorageScope): IStorage | undefined {
if (scope === StorageScope.APPLICATION) {
return this.storageMainService.applicationStorage.storage;
}
return undefined; // any other scope is unsupported from main process
}
protected getLogDetails(scope: StorageScope): string | undefined {
if (scope === StorageScope.APPLICATION) {
return this.userDataProfilesService.defaultProfile.globalStorageHome.fsPath;
}
return undefined; // any other scope is unsupported from main process
}
protected override shouldFlushWhenIdle(): boolean {
return false; // not needed here, will be triggered from any window that is opened
}
override switch(): never {
throw new Error('Migrating storage is unsupported from main process');
}
protected switchToProfile(): never {
throw new Error('Switching storage profile is unsupported from main process');
}
protected switchToWorkspace(): never {
throw new Error('Switching storage workspace is unsupported from main process');
}
} | the_stack |
import React, {useEffect, useRef, useState, useImperativeHandle} from 'react';
import marked from "marked";
import hljs from 'highlight.js'
import './mdEditor.scss'
import './preview.scss'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/darcula.css'
import 'codemirror/addon/fold/foldgutter.css'
const renderer = new marked.Renderer();
marked.setOptions({
renderer: renderer,
gfm: true,
// tables: true,
breaks: true,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
highlight(code, lang, callback) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(lang, code).value;
} catch (__) {
}
}
// return hljs.highlightAuto(code).value; // 这个方法内容稍微多一点会卡得要死。。。
}
});
const Codemirror = require('codemirror')
require('codemirror/mode/meta.js');
require('codemirror/mode/go/go.js');
require('codemirror/mode/gfm/gfm.js');
require('codemirror/mode/vue/vue.js');
require('codemirror/mode/css/css.js');
require('codemirror/mode/lua/lua.js');
require('codemirror/mode/php/php.js');
require('codemirror/mode/xml/xml.js');
require('codemirror/mode/jsx/jsx.js');
require('codemirror/mode/sql/sql.js');
require('codemirror/mode/pug/pug.js');
require('codemirror/mode/lua/lua.js');
require('codemirror/mode/sass/sass.js');
require('codemirror/mode/http/http.js');
require('codemirror/mode/perl/perl.js');
require('codemirror/mode/ruby/ruby.js');
require('codemirror/mode/nginx/nginx.js');
require('codemirror/mode/shell/shell.js');
require('codemirror/mode/clike/clike.js');
require('codemirror/mode/stylus/stylus.js');
require('codemirror/mode/python/python.js');
require('codemirror/mode/haskell/haskell.js');
require('codemirror/mode/markdown/markdown.js');
require('codemirror/mode/htmlmixed/htmlmixed.js');
require('codemirror/mode/javascript/javascript.js');
require('codemirror/addon/mode/overlay.js');
require('codemirror/addon/edit/closetag.js');
require('codemirror/addon/edit/continuelist.js');
require('codemirror/addon/edit/closebrackets.js');
require('codemirror/addon/scroll/annotatescrollbar.js');
require('codemirror/addon/selection/active-line.js');
require('codemirror/addon/selection/mark-selection.js');
require('codemirror/addon/search/searchcursor.js');
require('codemirror/addon/search/matchesonscrollbar.js');
require('codemirror/addon/search/searchcursor.js');
require('codemirror/addon/search/match-highlighter.js');
require('codemirror/addon/fold/foldcode.js');
require('codemirror/addon/fold/xml-fold.js');
require('codemirror/addon/fold/foldgutter.js');
require('codemirror/addon/fold/comment-fold.js');
require('codemirror/addon/fold/indent-fold.js');
require('codemirror/addon/fold/brace-fold.js');
require('codemirror/addon/fold/markdown-fold.js');
function MdEditor(props: any) {
const inputRef = useRef(null) // 获取 输入框 dom
const mdContainer = useRef(null) // 获取 md 容器 dom
const fileUpload = useRef<HTMLInputElement>(null) // 获取 上产文件的input dom
const previewDom = useRef<HTMLInputElement>(null) // 获取 预览 dom
const [showUpload, setShowUpload] = useState(false) // 上传图片按钮处理
const [fullscreen, setFullscreen] = useState(false) // 全屏
const [mdEditor, setMdEditor] = useState()
const [linkToNewPage, setLinkToNewPage] = useState(true)
const [previewContent, setPreviewContent] = useState('') // 预览内容
const [mdVal, setMdVal] = useState('') // 预览内容
useEffect(() => {
setMdEditor(Codemirror(inputRef.current, {
mode: 'gfm',
// 行号
lineNumbers: true,
// 自动验证错误
matchBrackets: true,
// 是否换行
lineWrapping: true,
// 点击高亮正行
styleActiveLine: true,
// 配色
theme: 'darcula',
// 自动补全括号
autoCloseBrackets: true,
// 自动闭合标签
autoCloseTags: true,
// 自动高亮所有选中单词
// styleSelectedText: true,
// highlightSelectionMatches: { showToken: /w/, annotateScrollbar: true },
// 展开折叠
foldGutter: true,
autofocus: true,
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
// 回车键自动补全上一步格式
extraKeys: {
Enter: 'newlineAndIndentContinueMarkdownList'
},
}))
},
[inputRef])
useEffect(() => {
if (mdEditor) {
// 监听内容改变
mdEditor.on('change', (cm: any) => {
let inputVal = cm.getValue()
if (linkToNewPage) {
setPreviewContent(marked(inputVal).replace(/<a/g, '<a target="_blank"'))
} else {
setPreviewContent(marked(inputVal))
}
// setMdVal(inputVal)
if (props && props.updateContent) {
props.updateContent(inputVal)
}
})
// 编辑器滚动时触发
mdEditor.on('scroll', (instance: any, from: number, to: number) => {
let editScrollTop = instance.doc.scrollTop // 编辑器滚动条距顶部的距离
let editScrollHeight = instance.doc.height // 编辑器滚动区域总高度
// @ts-ignore
let previewDomHeight = previewDom.current.scrollHeight // 预览区总高度
// @ts-ignore
previewDom.current.scrollTop = (editScrollTop / editScrollHeight) * previewDomHeight
})
}
}, [mdEditor, linkToNewPage])
// useEffect(() => {
// if (props && props.updateContent) {
// props.updateContent(mdVal)
// }
// }, [mdVal])
useEffect(() => {
Codemirror.commands.undo = function () {
undo()
}
Codemirror.commands.redo = function () {
redo()
}
}, [mdEditor])
useEffect(() => {
if (props && typeof props.imgUpload === 'function') {
setShowUpload(true)
} else {
setShowUpload(false)
}
if (props && props.defaultMd) {
mdEditor.setValue(props.defaultMd)
}
}, [props, mdEditor])
// 上传图片-上传
const fileChange = (e: any) => {
let file = e.target.files[0]
if (showUpload) {
props.imgUpload(file)
} else {
insertImage('请自定义配置上传图片的方法')
}
}
// 上传图片-点击事件
const uploadImage = () => {
if (fileUpload && fileUpload.current) {
fileUpload.current.click()
}
}
// 插入图片链接
const insertImage = (url?: string) => {
let position = mdEditor.getCursor() // 获取当前光标位置 {line: 0,ch: 0}
let hasUrl = ``
let insertTxt = url ? hasUrl : '![]()'
mdEditor.replaceSelection(insertTxt, position) // 在光标位置插入数据
let posCh = url ? hasUrl.length : 4
position.ch += posCh
mdEditor.focus()
mdEditor.setCursor(position) // 设置光标位置
}
// 插入代码
const insertCode = async () => {
let position = mdEditor.getCursor() // 获取当前光标位置 {line: 0,ch: 0}
let insertTxt = '```\n\n```'
mdEditor.replaceSelection(insertTxt, position) // 在光标位置插入数据
position.ch += 3
mdEditor.focus()
mdEditor.setCursor(position) // 设置光标位置
}
// 插入行内代码
const insertLineCode = () => {
let position = mdEditor.getCursor() // 获取当前光标位置 {line: 0,ch: 0}
let insertTxt = '``'
mdEditor.replaceSelection(insertTxt, position) // 在光标位置插入数据
position.ch += 1
mdEditor.focus()
mdEditor.setCursor(position) // 设置光标位置
}
// 插入链接
const insertLink = () => {
let position = mdEditor.getCursor() // 获取当前光标位置 {line: 0,ch: 0}
let insertTxt = `[Link]( 'Link title')`
mdEditor.replaceSelection(insertTxt, position) // 在光标位置插入数据
position.ch += 7
mdEditor.focus()
mdEditor.setCursor(position) // 设置光标位置
}
// 删除
const insertDel = () => {
let position = mdEditor.getCursor() // 获取当前光标位置 {line: 0,ch: 0}
let insertTxt = '~~~~'
mdEditor.replaceSelection(insertTxt, position) // 在光标位置插入数据
position.ch += 2
mdEditor.focus()
mdEditor.setCursor(position) // 设置光标位置
}
// 插入表格
const insertTable = () => {
let position = mdEditor.getCursor() // 获取当前光标位置 {line: 0,ch: 0}
let insertTxt = `\n| |\n| --- |\n| |\n`
mdEditor.replaceSelection(insertTxt, position) // 在光标位置插入数据
position.ch += 3
mdEditor.focus()
mdEditor.setCursor(position) // 设置光标位置
}
// 回退
const undo = () => {
let position = mdEditor.getCursor() // 获取当前光标位置 {line: 0,ch: 0}
mdEditor.undo()
mdEditor.focus()
mdEditor.setCursor(position)
}
// 撤销
const redo = () => {
let position = mdEditor.getCursor() // 获取当前光标位置 {line: 0,ch: 0}
mdEditor.redo()
console.log(position)
mdEditor.focus()
mdEditor.setCursor(position)
}
// 全屏-开启与退出
const handleFullScreen = () => {
let element = mdContainer.current as any;
let doc = document as any;
// 判断是否已经是全屏
// 如果是全屏,退出
if (fullscreen) {
if (doc.exitFullscreen) {
doc.exitFullscreen();
} else if (doc.webkitCancelFullScreen) {
doc.webkitCancelFullScreen();
} else if (doc.mozCancelFullScreen) {
doc.mozCancelFullScreen();
} else if (doc.msExitFullscreen) {
doc.msExitFullscreen();
}
} else { // 否则,进入全屏
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.webkitRequestFullScreen) {
element.webkitRequestFullScreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
// IE11
element.msRequestFullscreen();
}
}
setFullscreen(!fullscreen)
}
window.onresize = function () {
let doc = document as any;
let isFull = !!(doc.webkitIsFullScreen || doc.mozFullScreen ||
doc.msFullscreenElement || doc.fullscreenElement
);//!document.webkitIsFullScreen都为true。因此用!!
if (isFull === false) {
setFullscreen(false)
}
}
// 复制DOM
const handleCopyDom = () => {
let doc = document as any
let div = previewDom.current as any
if (doc.body.createTextRange) {
let range = doc.body.createTextRange();
range.moveToElementText(div);
range.select();
} else if (window.getSelection) {
let selection = window.getSelection() as any;
let range = doc.createRange();
range.selectNodeContents(div);
selection.removeAllRanges();
selection.addRange(range);
/*if(selection.setBaseAndExtent){
selection.setBaseAndExtent(text, 0, text, 1);
}*/
} else {
console.warn("none");
}
doc.execCommand("Copy"); // 执行浏览器复制命令
alert("已复制好,去不支持 Markdown 语法的其他平台粘贴试试。");
}
// 暴露给父组件使用的方法
useImperativeHandle(props.cRef, () => ({
addImg: (params: string) => {
// 父组件向该组件 markdown 中插入图片链接
insertImage(params)
},
getInputData() {
// 获取该组件输入的数据,返回给父组件
// 方便父组件拿到数据,和其他数据一起进行存储
return {
md: mdEditor.getValue(), // md 格式
mdToHtml: marked(mdEditor.getValue()) // md 专成 html 格式后的数据
}
}
}))
return (
<div className="react-md-container" ref={mdContainer}>
<div className='react-md-editor-toolbar'>
<ul className='tool-bar-lists-left'>
<li onClick={insertCode}>代码</li>
<li onClick={insertLineCode}>行内代码</li>
<li onClick={insertLink}>链接</li>
<li onClick={uploadImage}>
<input onChange={(e) => fileChange(e)} ref={fileUpload} type="file" style={{display: "none"}}/>
上传图片
</li>
<li onClick={() => insertImage()}>图片链接</li>
<li onClick={() => insertDel()}>删除</li>
<li onClick={() => insertTable()}>表格</li>
<li onClick={undo}>回退</li>
<li onClick={redo}>撤销</li>
</ul>
<ul className='tool-bar-lists-right'>
<li onClick={() => handleFullScreen()}>{fullscreen ? '退出全屏' : '全屏'}</li>
<li onClick={() => handleCopyDom()}>复制DOM</li>
<li className='tool-bar-setting'>
<div>设置</div>
<div className='setting-panel'>
<div className='panelItem'>
<input id='linkCheck' checked={linkToNewPage} onChange={(e) => {
setLinkToNewPage(e.target.checked)
}} type="checkbox"/>
<label htmlFor="linkCheck">
链接打开新页面
</label>
</div>
</div>
</li>
</ul>
</div>
<div className='react-md-editor-main'>
<div className='react-md-editor-input'>
<div style={{position: "absolute", top: 0, left: 0, right: 0, bottom: 0}}>
<div style={{height: '100%'}} ref={inputRef}></div>
</div>
</div>
<div className='react-md-editor-preview'>
<div className='preview-box' ref={previewDom}>
<div id='r-md-preview' style={{minHeight: '100%', width: '100%'}}
dangerouslySetInnerHTML={{__html: previewContent}}></div>
</div>
</div>
</div>
</div>
);
}
export default MdEditor; | the_stack |
import fs from 'fs'
import test from 'blue-tape'
import { mock, unmock } from 'mocku'
import { createSpy, getSpyCalls } from 'spyfn'
import foxr from '../../src/'
import ElementHandle from '../../src/api/ElementHandle'
import { testWithFirefox } from '../helpers/firefox'
import JSHandle from '../../src/api/JSHandle'
test('Page: `close` event on browser close', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
const onCloseSpy = createSpy(() => {})
page.on('close', onCloseSpy)
await browser.close()
t.deepEqual(
getSpyCalls(onCloseSpy),
[[]],
'should emit `close` event'
)
}))
test('Page: `close` event on browser disconnect', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
const onCloseSpy = createSpy(() => {})
page.on('close', onCloseSpy)
await browser.disconnect()
t.deepEqual(
getSpyCalls(onCloseSpy),
[[]],
'should emit `close` event'
)
}))
test('Page: `$()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
await page.setContent('<h2>hello</h2><h2>world</h2>')
t.equal(
await page.$('h1'),
null,
'should return null if nothing has been found'
)
const element = await page.$('h2')
t.true(
element !== null && element instanceof ElementHandle,
'should return a single Element'
)
t.equal(
element,
await await page.$('h2'),
'should return the same element twice'
)
try {
await page.$('(')
t.fail()
} catch (err) {
t.true(
err.message.startsWith('Given css selector expression'),
'should throw'
)
}
}))
test('Page: `$$()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
await page.setContent('<h2>hello</h2><h2>world</h2>')
t.deepEqual(
await page.$$('h1'),
[],
'should return empty array if nothing has been found'
)
const elements = await page.$$('h2')
t.true(
elements.length === 2 && elements.every((el) => el instanceof ElementHandle),
'should return multiple Elements'
)
t.deepEqual(
elements,
await page.$$('h2'),
'should return the same elements twice'
)
}))
test('Page: `$eval()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
await page.setContent('<h1>hi</h1>')
t.equal(
// @ts-ignore
await page.$eval('h1', (el) => el.tagName),
'H1',
'should evaluate function without arguments'
)
t.equal(
// @ts-ignore
await page.$eval('h1', (el, foo, bar) => `${el.tagName}-${foo}-${bar}`, 'foo', 'bar'),
'H1-foo-bar',
'should evaluate function with arguments'
)
const bodyJSHandle = await page.evaluateHandle('document.body')
const bodyElementHandle = await page.$('body')
t.equal(
// @ts-ignore
await page.$eval('h1', (el, handle) => `${el.tagName}-${handle.tagName}`, bodyJSHandle),
'H1-BODY',
'should evaluate function with arguments as JSHandle'
)
t.equal(
// @ts-ignore
await page.$eval('h1', (el, handle) => `${el.tagName}-${handle.tagName}`, bodyElementHandle),
'H1-BODY',
'should evaluate function with arguments as ElementHandle'
)
try {
await page.$eval('h1', () => { throw new Error('oops') })
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: oops',
'should evaluate functions that throws'
)
}
t.equal(
// @ts-ignore
await page.$eval('h1', (el) => Promise.resolve(el.tagName)),
'H1',
'should evaluate function that returns a resolved Promise'
)
t.equal(
// @ts-ignore
await page.$eval('h1', (el, foo, bar) => Promise.resolve(`${el.tagName}-${foo}-${bar}`), 'foo', 'bar'),
'H1-foo-bar',
'should evaluate function with arguments that returns a resolved Promise'
)
t.equal(
// @ts-ignore
await page.$eval('h1', (el, handle) => Promise.resolve(`${el.tagName}-${handle.tagName}`), bodyJSHandle),
'H1-BODY',
'should evaluate function with arguments as JSHandle that returns a resolved Promise'
)
t.equal(
// @ts-ignore
await page.$eval('h1', (el, handle) => Promise.resolve(`${el.tagName}-${handle.tagName}`), bodyElementHandle),
'H1-BODY',
'should evaluate function with arguments as ElementHandle that returns a resolved Promise'
)
try {
await page.$eval('h1', () => Promise.reject(new Error('oops')))
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: oops',
'should evaluate functions that returns a rejected Promise'
)
}
try {
// @ts-ignore
await page.$eval('h2', (el) => el.tagName)
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: unable to find element',
'should throw if there is no such an element'
)
}
}))
test('Page: `$$eval()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
await page.setContent('<div><h2>hi</h2><h2>hello</h2></div>')
t.deepEqual(
// @ts-ignore
await page.$$eval('h2', (el) => el.textContent),
['hi', 'hello'],
'should evaluate function without arguments'
)
t.deepEqual(
// @ts-ignore
await page.$$eval('h2', (el, foo, bar) => `${el.textContent}-${foo}-${bar}`, 'foo', 'bar'),
['hi-foo-bar', 'hello-foo-bar'],
'should evaluate function with arguments'
)
const bodyJSHandle = await page.evaluateHandle('document.body')
const bodyElementHandle = await page.$('body')
t.deepEqual(
// @ts-ignore
await page.$$eval('h2', (el, handle) => `${el.textContent}-${handle.tagName}`, bodyJSHandle),
['hi-BODY', 'hello-BODY'],
'should evaluate function with JSHandle as arguments'
)
t.deepEqual(
// @ts-ignore
await page.$$eval('h2', (el, handle) => `${el.textContent}-${handle.tagName}`, bodyElementHandle),
['hi-BODY', 'hello-BODY'],
'should evaluate function with ElementHandle as arguments'
)
try {
await page.$$eval('h2', () => { throw new Error('oops') })
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: oops',
'should evaluate functions that throws'
)
}
t.deepEqual(
// @ts-ignore
await page.$$eval('h2', (el) => Promise.resolve(el.textContent)),
['hi', 'hello'],
'should evaluate function that returns a resolved Promise'
)
t.deepEqual(
// @ts-ignore
await page.$$eval('h2', (el, foo, bar) => Promise.resolve(`${el.textContent}-${foo}-${bar}`), 'foo', 'bar'),
['hi-foo-bar', 'hello-foo-bar'],
'should evaluate function with arguments that returns a resolved Promise'
)
t.deepEqual(
// @ts-ignore
await page.$$eval('h2', (el, handle) => Promise.resolve(`${el.textContent}-${handle.tagName}`), bodyJSHandle),
['hi-BODY', 'hello-BODY'],
'should evaluate function with JSHandle as arguments that returns a resolved Promise'
)
t.deepEqual(
// @ts-ignore
await page.$$eval('h2', (el, handle) => Promise.resolve(`${el.textContent}-${handle.tagName}`), bodyElementHandle),
['hi-BODY', 'hello-BODY'],
'should evaluate function with ElementHandle as arguments that returns a resolved Promise'
)
try {
await page.$$eval('h2', () => Promise.reject(new Error('oops')))
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: oops',
'should evaluate functions that returns a rejected Promise'
)
}
t.deepEqual(
// @ts-ignore
await page.$$eval('h1', (el) => el.textContent),
[],
'should return an emptry array if nothing has been found'
)
}))
test('Page: `bringToFront()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page1 = await browser.newPage()
await page1.setContent('<title>page1</title>')
const page2 = await browser.newPage()
await page2.setContent('<title>page2</title>')
t.equal(
await page1.title(),
'page2',
'should perform actions only with current page'
)
await page1.bringToFront()
t.equal(
await page1.title(),
'page1',
'should activate page'
)
}))
test('Page: `browser()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
t.strictEqual(
browser,
page.browser(),
'should return an underlying browser instance'
)
}))
test('Page: `close()` + `close` event', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
const onCloseSpy = createSpy(() => {})
page.on('close', onCloseSpy)
await page.close()
const pages = await browser.pages()
t.equal(
pages.length,
1,
'should close page'
)
t.deepEqual(
getSpyCalls(onCloseSpy),
[[]],
'should emit `close` event'
)
}))
test('Page: `setContent()` + `content()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
const html = '<h1>hello</h1>'
t.equal(
await page.content(),
'<html><head></head><body></body></html>',
'content() should return page HTML'
)
await page.setContent(html)
t.equal(
await page.content(),
`<html><head></head><body>${html}</body></html>`,
'setContent() should set page HTML'
)
}))
test('Page: `evaluate()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
t.equal(
await page.evaluate('2 + 2'),
4,
'should evaluate strings'
)
try {
await page.evaluate('{ throw 123 }')
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: 123',
'should evaluate strings that throws'
)
}
t.equal(
await page.evaluate('Promise.resolve(2 + 2)'),
4,
'should evaluate resolved Promises as string'
)
try {
await page.evaluate('Promise.reject(123)')
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: 123',
'should evaluate rejected Promises as string'
)
}
t.equal(
await page.evaluate(() => 1 + 2),
3,
'should evaluate functions without arguments'
)
t.equal(
// @ts-ignore
await page.evaluate((x, y) => { return x + y }, 1, 2),
3,
'should evaluate functions with arguments'
)
const bodyJSHandle = await page.evaluateHandle('document.body')
const bodyElementHandle = await page.$('body')
t.equal(
// @ts-ignore
await page.evaluate((handle) => handle.tagName, bodyJSHandle),
'BODY',
'should evaluate functions with JSHandle as arguments'
)
t.equal(
// @ts-ignore
await page.evaluate((handle) => handle.tagName, bodyElementHandle),
'BODY',
'should evaluate functions with ElementHandle as arguments'
)
try {
await page.evaluate(() => { throw new Error('oops') })
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: oops',
'should evaluate functions that throws'
)
}
t.equal(
// @ts-ignore
await page.evaluate((x, y) => Promise.resolve(x + y), 1, 2),
3,
'should evaluate functions with arguments that returns a resolved Promise'
)
t.equal(
// @ts-ignore
await page.evaluate((handle) => Promise.resolve(handle.tagName), bodyJSHandle),
'BODY',
'should evaluate functions with JSHandle as arguments that returns a resolved Promise'
)
t.equal(
// @ts-ignore
await page.evaluate((handle) => Promise.resolve(handle.tagName), bodyElementHandle),
'BODY',
'should evaluate functions with ElementHandle as arguments that returns a resolved Promise'
)
try {
await page.evaluate(() => Promise.reject(new Error('oops')))
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: oops',
'should evaluate functions that returns a rejected Promise'
)
}
}))
test('Page: `evaluateHandle()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
t.true(
(await page.evaluateHandle('document.body')) instanceof JSHandle,
'should evaluate strings'
)
try {
await page.evaluateHandle('{ throw 123 }')
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: 123',
'should evaluate strings that throws'
)
}
try {
await page.evaluateHandle('window._foo_')
t.fail()
} catch (err) {
t.equal(
err.message,
'Unable to get a JSHandle',
'should throw if no JSHandle has been returned from string'
)
}
t.true(
(await page.evaluateHandle('Promise.resolve(document.body)')) instanceof JSHandle,
'should evaluate resolved Promises as string'
)
try {
await page.evaluateHandle('Promise.reject(123)')
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: 123',
'should evaluate rejected Promises as string'
)
}
t.true(
// @ts-ignore
(await page.evaluateHandle(() => document.body)) instanceof JSHandle,
'should evaluate functions without arguments'
)
t.true(
// @ts-ignore
(await page.evaluateHandle((prop) => document[prop], 'body')) instanceof JSHandle,
'should evaluate functions with arguments'
)
const bodyJSHandle = await page.evaluateHandle('document.body')
const bodyElementHandle = await page.$('body')
t.true(
// @ts-ignore
(await page.evaluateHandle((handle) => handle, bodyJSHandle)) instanceof JSHandle,
'should evaluate functions with JSHandle as arguments'
)
t.true(
// @ts-ignore
(await page.evaluateHandle((handle) => handle, bodyElementHandle)) instanceof JSHandle,
'should evaluate functions with ElementHandle as arguments'
)
try {
// @ts-ignore
await page.evaluateHandle(() => window.__foo_)
t.fail()
} catch (err) {
t.equal(
err.message,
'Unable to get a JSHandle',
'should throw if no JSHandle has been returned from function'
)
}
try {
await page.evaluateHandle(() => { throw new Error('oops') })
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: oops',
'should evaluate functions that throws'
)
}
t.true(
// @ts-ignore
(await page.evaluateHandle((prop) => Promise.resolve(document[prop]), 'body')) instanceof JSHandle,
'should evaluate functions with arguments that returns a resolved Promise'
)
try {
// @ts-ignore
await page.evaluateHandle(() => Promise.resolve(window.__foo_))
t.fail()
} catch (err) {
t.equal(
err.message,
'Unable to get a JSHandle',
'should throw if no JSHandle has been returned from function that returns a resolve Promise'
)
}
t.true(
// @ts-ignore
(await page.evaluateHandle((handle) => Promise.resolve(handle), bodyJSHandle)) instanceof JSHandle,
'should evaluate functions with JSHandle arguments that returns a resolved Promise'
)
t.true(
// @ts-ignore
(await page.evaluateHandle((handle) => Promise.resolve(handle), bodyElementHandle)) instanceof JSHandle,
'should evaluate functions with ElementHandle arguments that returns a resolved Promise'
)
try {
await page.evaluateHandle(() => Promise.reject(new Error('oops')))
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: oops',
'should evaluate functions that returns a rejected Promise'
)
}
}))
test('Page: `focus()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
await page.setContent('<div><input/><svg></svg></div>')
const activeElementBefore = await page.evaluate('document.activeElement.tagName')
await page.focus('input')
const activeElementAfter = await page.evaluate('document.activeElement.tagName')
t.true(
activeElementBefore !== activeElementAfter && activeElementAfter === 'INPUT',
'should focus element'
)
try {
await page.focus('foo')
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: unable to find element',
'should throw if there is no such an element'
)
}
try {
await page.focus('svg')
t.fail()
} catch (err) {
t.equal(
err.message,
'Evaluation failed: Found element is not HTMLElement and not focusable',
'should throw if found element is not focusable'
)
}
}))
test('Page: `goto()` + `url()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
await page.goto('data:text/html,<title>hi</title>')
t.equal(
await page.url(),
'data:text/html,<title>hi</title>',
'should change page url'
)
await page.goto('data:text/html,<title>hello</title>')
t.equal(
await page.url(),
'data:text/html,<title>hello</title>',
'should change page url again'
)
}))
test('Page: `screenshot()`', testWithFirefox(async (t) => {
const writeFileSpy = createSpy(({ args }) => args[args.length - 1](null))
mock('../../src/', {
fs: {
...fs,
writeFile: writeFileSpy
}
})
const { default: foxr } = await import('../../src/')
const browser = await foxr.connect()
const page = await browser.newPage()
await page.setContent('<h1>hello</h1>')
const screenshot1 = await page.screenshot()
t.true(
Buffer.isBuffer(screenshot1) && screenshot1.length > 0,
'should return non-empty Buffer'
)
const screenshot2 = await page.screenshot({ path: 'test.png' })
const spyArgs = getSpyCalls(writeFileSpy)[0]
t.equal(
spyArgs[0],
'test.png',
'path: should handle `path` option'
)
t.true(
Buffer.isBuffer(spyArgs[1]) && spyArgs[1].length > 0,
'path: should write screenshot to file'
)
t.true(
Buffer.isBuffer(screenshot2) && screenshot2.length > 0,
'path: should return non-empty buffer'
)
unmock('../../src/')
}))
test('Page: `viewport()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
const result = await page.viewport()
t.deepEqual(
result,
{ width: 800, height: 600 },
'should return width and height'
)
}))
test('Page: `title()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
await page.setContent('<title>hi</title>')
const title = await page.title()
t.equal(
title,
'hi',
'should get page title'
)
}))
test('Page: `goback()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
await page.goto('data:text/html,<title>hi</title>')
t.equal(
await page.url(),
'data:text/html,<title>hi</title>',
'should change page url'
)
await page.goto('data:text/html,<title>hello</title>')
t.equal(
await page.url(),
'data:text/html,<title>hello</title>',
'should change page url again'
)
await page.goBack()
t.equal(
await page.url(),
'data:text/html,<title>hi</title>',
'should go back to previous page'
)
}))
test('Page: `goforward()`', testWithFirefox(async (t) => {
const browser = await foxr.connect()
const page = await browser.newPage()
await page.goto('data:text/html,<title>hi</title>')
t.equal(
await page.url(),
'data:text/html,<title>hi</title>',
'should change page url'
)
await page.goto('data:text/html,<title>hello</title>')
t.equal(
await page.url(),
'data:text/html,<title>hello</title>',
'should change page url again'
)
await page.goBack()
t.equal(
await page.url(),
'data:text/html,<title>hi</title>',
'should go back to previous page'
)
await page.goForward()
t.equal(
await page.url(),
'data:text/html,<title>hello</title>',
'should go forward to next page'
)
})) | the_stack |
import {
expect
} from 'chai';
import {
find, map, toArray
} from '@phosphor/algorithm';
import {
LinkedList
} from '@phosphor/collections';
describe('@phosphor/collections', () => {
describe('LinkedList', () => {
describe('#constructor()', () => {
let list = new LinkedList<number>();
expect(list).to.be.an.instanceof(LinkedList);
});
describe('#isEmpty', () => {
it('should be `true` for an empty list', () => {
let list = new LinkedList<number>();
expect(list.isEmpty).to.equal(true);
});
it('should be `false` for a non-empty list', () => {
let data = [0, 1, 2, 3, 4, 5];
let list = LinkedList.from(data);
expect(list.isEmpty).to.equal(false);
});
});
describe('#length', () => {
it('should be `0` for an empty list', () => {
let list = new LinkedList<number>();
expect(list.length).to.equal(0);
});
it('should equal the number of items in a list', () => {
let data = [0, 1, 2, 3, 4, 5];
let list = LinkedList.from(data);
expect(list.length).to.equal(data.length);
});
});
describe('#first', () => {
it('should be the first value in the list', () => {
let data = [0, 1, 2, 3, 4, 5];
let list = LinkedList.from(data);
expect(list.first).to.equal(data[0]);
});
it('should be `undefined` if the list is empty', () => {
let list = new LinkedList<number>();
expect(list.first).to.equal(undefined);
});
});
describe('#last', () => {
it('should be the last value in the list', () => {
let data = [0, 1, 2, 3, 4, 5];
let list = LinkedList.from(data);
expect(list.last).to.equal(data[data.length - 1]);
});
it('should be `undefined` if the list is empty', () => {
let list = new LinkedList<number>();
expect(list.last).to.equal(undefined);
});
});
describe('#firstNode', () => {
it('should be the first node in the list', () => {
let data = [0, 1, 2, 3, 4, 5];
let list = LinkedList.from(data);
expect(list.firstNode!.value).to.equal(data[0]);
});
it('should be `null` if the list is empty', () => {
let list = new LinkedList<number>();
expect(list.firstNode).to.equal(null);
});
});
describe('#lastNode', () => {
it('should be the last node in the list', () => {
let data = [0, 1, 2, 3, 4, 5];
let list = LinkedList.from(data);
expect(list.lastNode!.value).to.equal(data[data.length - 1]);
});
it('should be `null` if the list is empty', () => {
let list = new LinkedList<number>();
expect(list.lastNode).to.equal(null);
});
});
describe('#iter()', () => {
it('should return an iterator over the list values', () => {
let data = [0, 1, 2, 3, 4, 5];
let list = LinkedList.from(data);
let it1 = list.iter();
let it2 = it1.clone();
expect(it1.iter()).to.equal(it1);
expect(it2.iter()).to.equal(it2);
expect(toArray(it1)).to.deep.equal(data);
expect(toArray(it2)).to.deep.equal(data);
});
});
describe('#retro()', () => {
it('should return a reverse iterator over the list values', () => {
let data = [0, 1, 2, 3, 4, 5];
let reversed = data.slice().reverse();
let list = LinkedList.from(data);
let it1 = list.retro();
let it2 = it1.clone();
expect(it1.iter()).to.equal(it1);
expect(it2.iter()).to.equal(it2);
expect(toArray(it1)).to.deep.equal(reversed);
expect(toArray(it2)).to.deep.equal(reversed);
});
});
describe('#nodes()', () => {
it('should return an iterator over the list nodes', () => {
let data = [0, 1, 2, 3, 4, 5];
let list = LinkedList.from(data);
let it1 = list.nodes();
let it2 = it1.clone();
let v1 = map(it1, n => n.value);
let v2 = map(it2, n => n.value);
expect(it1.iter()).to.equal(it1);
expect(it2.iter()).to.equal(it2);
expect(toArray(v1)).to.deep.equal(data);
expect(toArray(v2)).to.deep.equal(data);
});
});
describe('#retroNodes()', () => {
it('should return a reverse iterator over the list nodes', () => {
let data = [0, 1, 2, 3, 4, 5];
let reversed = data.slice().reverse();
let list = LinkedList.from(data);
let it1 = list.retroNodes();
let it2 = it1.clone();
let v1 = map(it1, n => n.value);
let v2 = map(it2, n => n.value);
expect(it1.iter()).to.equal(it1);
expect(it2.iter()).to.equal(it2);
expect(toArray(v1)).to.deep.equal(reversed);
expect(toArray(v2)).to.deep.equal(reversed);
});
});
describe('#addFirst()', () => {
it('should add a value to the beginning of the list', () => {
let list = new LinkedList<number>();
expect(list.isEmpty).to.equal(true);
expect(list.length).to.equal(0);
expect(list.first).to.equal(undefined);
expect(list.last).to.equal(undefined);
let n1 = list.addFirst(99);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(1);
expect(list.first).to.equal(99);
expect(list.last).to.equal(99);
let n2 = list.addFirst(42);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(2);
expect(list.first).to.equal(42);
expect(list.last).to.equal(99);
let n3 = list.addFirst(7);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(3);
expect(list.first).to.equal(7);
expect(list.last).to.equal(99);
expect(toArray(list)).to.deep.equal([7, 42, 99]);
expect(n1.list).to.equal(list);
expect(n1.next).to.equal(null);
expect(n1.prev).to.equal(n2);
expect(n1.value).to.equal(99);
expect(n2.list).to.equal(list);
expect(n2.next).to.equal(n1);
expect(n2.prev).to.equal(n3);
expect(n2.value).to.equal(42);
expect(n3.list).to.equal(list);
expect(n3.next).to.equal(n2);
expect(n3.prev).to.equal(null);
expect(n3.value).to.equal(7);
});
});
describe('#addLast()', () => {
it('should add a value to the end of the list', () => {
let list = new LinkedList<number>();
expect(list.isEmpty).to.equal(true);
expect(list.length).to.equal(0);
expect(list.first).to.equal(undefined);
expect(list.last).to.equal(undefined);
let n1 = list.addLast(99);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(1);
expect(list.first).to.equal(99);
expect(list.last).to.equal(99);
let n2 = list.addLast(42);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(2);
expect(list.first).to.equal(99);
expect(list.last).to.equal(42);
let n3 = list.addLast(7);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(3);
expect(list.first).to.equal(99);
expect(list.last).to.equal(7);
expect(toArray(list)).to.deep.equal([99, 42, 7]);
expect(n1.list).to.equal(list);
expect(n1.next).to.equal(n2);
expect(n1.prev).to.equal(null);
expect(n1.value).to.equal(99);
expect(n2.list).to.equal(list);
expect(n2.next).to.equal(n3);
expect(n2.prev).to.equal(n1);
expect(n2.value).to.equal(42);
expect(n3.list).to.equal(list);
expect(n3.next).to.equal(null);
expect(n3.prev).to.equal(n2);
expect(n3.value).to.equal(7);
});
});
describe('#insertBefore()', () => {
it('should insert a value before the given reference node', () => {
let list = LinkedList.from([0, 1, 2, 3]);
let n1 = find(list.nodes(), n => n.value === 2)!;
let n2 = list.insertBefore(7, n1);
let n3 = list.insertBefore(8, n2);
let n4 = list.insertBefore(9, null);
let n5 = find(list.nodes(), n => n.value === 1);
let n6 = find(list.nodes(), n => n.value === 0);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(7);
expect(list.first).to.equal(9);
expect(list.last).to.equal(3);
expect(toArray(list)).to.deep.equal([9, 0, 1, 8, 7, 2, 3]);
expect(n1.list).to.equal(list);
expect(n1.next).to.equal(list.lastNode);
expect(n1.prev).to.equal(n2);
expect(n1.value).to.equal(2);
expect(n2.list).to.equal(list);
expect(n2.next).to.equal(n1);
expect(n2.prev).to.equal(n3);
expect(n2.value).to.equal(7);
expect(n3.list).to.equal(list);
expect(n3.next).to.equal(n2);
expect(n3.prev).to.equal(n5);
expect(n3.value).to.equal(8);
expect(n4.list).to.equal(list);
expect(n4.next).to.equal(n6);
expect(n4.prev).to.equal(null);
expect(n4.value).to.equal(9);
});
it('should throw an error if the reference node is invalid', () => {
let list1 = LinkedList.from([0, 1, 2, 3]);
let list2 = LinkedList.from([0, 1, 2, 3]);
let insert = () => { list2.insertBefore(4, list1.firstNode ); };
expect(insert).to.throw(Error);
});
});
describe('#insertAfter()', () => {
it('should insert a value after the given reference node', () => {
let list = LinkedList.from([0, 1, 2, 3]);
let n1 = find(list.nodes(), n => n.value === 2)!;
let n2 = list.insertAfter(7, n1);
let n3 = list.insertAfter(8, n2);
let n4 = list.insertAfter(9, null);
let n5 = find(list.nodes(), n => n.value === 1);
let n6 = find(list.nodes(), n => n.value === 3);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(7);
expect(list.first).to.equal(0);
expect(list.last).to.equal(9);
expect(toArray(list)).to.deep.equal([0, 1, 2, 7, 8, 3, 9]);
expect(n1.list).to.equal(list);
expect(n1.next).to.equal(n2);
expect(n1.prev).to.equal(n5);
expect(n1.value).to.equal(2);
expect(n2.list).to.equal(list);
expect(n2.next).to.equal(n3);
expect(n2.prev).to.equal(n1);
expect(n2.value).to.equal(7);
expect(n3.list).to.equal(list);
expect(n3.next).to.equal(n6);
expect(n3.prev).to.equal(n2);
expect(n3.value).to.equal(8);
expect(n4.list).to.equal(list);
expect(n4.next).to.equal(null);
expect(n4.prev).to.equal(n6);
expect(n4.value).to.equal(9);
});
it('should throw an error if the reference node is invalid', () => {
let list1 = LinkedList.from([0, 1, 2, 3]);
let list2 = LinkedList.from([0, 1, 2, 3]);
let insert = () => { list2.insertAfter(4, list1.firstNode ); };
expect(insert).to.throw(Error);
});
});
describe('#removeFirst()', () => {
it('should remove the first value from the list', () => {
let list = LinkedList.from([0, 1, 2, 3]);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(4);
expect(list.first).to.equal(0);
expect(list.last).to.equal(3);
expect(toArray(list)).to.deep.equal([0, 1, 2, 3]);
let v1 = list.removeFirst();
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(3);
expect(list.first).to.equal(1);
expect(list.last).to.equal(3);
expect(toArray(list)).to.deep.equal([1, 2, 3]);
let v2 = list.removeFirst();
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(2);
expect(list.first).to.equal(2);
expect(list.last).to.equal(3);
expect(toArray(list)).to.deep.equal([2, 3]);
let v3 = list.removeFirst();
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(1);
expect(list.first).to.equal(3);
expect(list.last).to.equal(3);
expect(toArray(list)).to.deep.equal([3]);
let v4 = list.removeFirst();
expect(list.isEmpty).to.equal(true);
expect(list.length).to.equal(0);
expect(list.first).to.equal(undefined);
expect(list.last).to.equal(undefined);
expect(toArray(list)).to.deep.equal([]);
let v5 = list.removeFirst();
expect(list.isEmpty).to.equal(true);
expect(list.length).to.equal(0);
expect(list.first).to.equal(undefined);
expect(list.last).to.equal(undefined);
expect(toArray(list)).to.deep.equal([]);
expect(v1).to.equal(0);
expect(v2).to.equal(1);
expect(v3).to.equal(2);
expect(v4).to.equal(3);
expect(v5).to.equal(undefined);
});
});
describe('#removeLast()', () => {
it('should remove the last value from the list', () => {
let list = LinkedList.from([0, 1, 2, 3]);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(4);
expect(list.first).to.equal(0);
expect(list.last).to.equal(3);
expect(toArray(list)).to.deep.equal([0, 1, 2, 3]);
let v1 = list.removeLast();
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(3);
expect(list.first).to.equal(0);
expect(list.last).to.equal(2);
expect(toArray(list)).to.deep.equal([0, 1, 2]);
let v2 = list.removeLast();
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(2);
expect(list.first).to.equal(0);
expect(list.last).to.equal(1);
expect(toArray(list)).to.deep.equal([0, 1]);
let v3 = list.removeLast();
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(1);
expect(list.first).to.equal(0);
expect(list.last).to.equal(0);
expect(toArray(list)).to.deep.equal([0]);
let v4 = list.removeLast();
expect(list.isEmpty).to.equal(true);
expect(list.length).to.equal(0);
expect(list.first).to.equal(undefined);
expect(list.last).to.equal(undefined);
expect(toArray(list)).to.deep.equal([]);
let v5 = list.removeLast();
expect(list.isEmpty).to.equal(true);
expect(list.length).to.equal(0);
expect(list.first).to.equal(undefined);
expect(list.last).to.equal(undefined);
expect(toArray(list)).to.deep.equal([]);
expect(v1).to.equal(3);
expect(v2).to.equal(2);
expect(v3).to.equal(1);
expect(v4).to.equal(0);
expect(v5).to.equal(undefined);
});
});
describe('#removeNode()', () => {
it('should remove the specified node from the list', () => {
let list = LinkedList.from([0, 1, 2, 3]);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(4);
expect(list.first).to.equal(0);
expect(list.last).to.equal(3);
expect(toArray(list)).to.deep.equal([0, 1, 2, 3]);
let n1 = find(list.nodes(), n => n.value === 2)!;
list.removeNode(n1);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(3);
expect(list.first).to.equal(0);
expect(list.last).to.equal(3);
expect(toArray(list)).to.deep.equal([0, 1, 3]);
expect(n1.list).to.equal(null);
expect(n1.next).to.equal(null);
expect(n1.prev).to.equal(null);
expect(n1.value).to.equal(2);
let n2 = find(list.nodes(), n => n.value === 3)!;
list.removeNode(n2);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(2);
expect(list.first).to.equal(0);
expect(list.last).to.equal(1);
expect(toArray(list)).to.deep.equal([0, 1]);
expect(n2.list).to.equal(null);
expect(n2.next).to.equal(null);
expect(n2.prev).to.equal(null);
expect(n2.value).to.equal(3);
let n3 = find(list.nodes(), n => n.value === 0)!;
list.removeNode(n3);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(1);
expect(list.first).to.equal(1);
expect(list.last).to.equal(1);
expect(toArray(list)).to.deep.equal([1]);
expect(n3.list).to.equal(null);
expect(n3.next).to.equal(null);
expect(n3.prev).to.equal(null);
expect(n3.value).to.equal(0);
let n4 = find(list.nodes(), n => n.value === 1)!;
list.removeNode(n4);
expect(list.isEmpty).to.equal(true);
expect(list.length).to.equal(0);
expect(list.first).to.equal(undefined);
expect(list.last).to.equal(undefined);
expect(toArray(list)).to.deep.equal([]);
expect(n4.list).to.equal(null);
expect(n4.next).to.equal(null);
expect(n4.prev).to.equal(null);
expect(n4.value).to.equal(1);
});
});
describe('#clear()', () => {
it('should remove all values from the list', () => {
let list = LinkedList.from([0, 1, 2, 3]);
expect(list.isEmpty).to.equal(false);
expect(list.length).to.equal(4);
expect(list.first).to.equal(0);
expect(list.last).to.equal(3);
expect(toArray(list)).to.deep.equal([0, 1, 2, 3]);
list.clear();
expect(list.isEmpty).to.equal(true);
expect(list.length).to.equal(0);
expect(list.first).to.equal(undefined);
expect(list.last).to.equal(undefined);
expect(toArray(list)).to.deep.equal([]);
});
});
describe('.from()', () => {
it('should initialize a list from an iterable', () => {
let list1 = LinkedList.from([0, 1, 2, 3]);
let list2 = LinkedList.from(list1);
expect(list2.isEmpty).to.equal(false);
expect(list2.length).to.equal(4);
expect(list2.first).to.equal(0);
expect(list2.last).to.equal(3);
expect(toArray(list2)).to.deep.equal([0, 1, 2, 3]);
});
});
describe('.ForwardValueIterator', () => {
it('should create a forward iterator over the values', () => {
let list = LinkedList.from([0, 1, 2, 3, 4]);
let n = find(list.nodes(), n => n.value === 2)!;
let it1 = new LinkedList.ForwardValueIterator(n);
let it2 = it1.clone();
expect(it1.iter()).to.equal(it1);
expect(it2.iter()).to.equal(it2);
expect(toArray(it1)).to.deep.equal([2, 3, 4]);
expect(toArray(it2)).to.deep.equal([2, 3, 4]);
});
});
describe('.RetroValueIterator', () => {
it('should create a reverse iterator over the values', () => {
let list = LinkedList.from([0, 1, 2, 3, 4]);
let n = find(list.nodes(), n => n.value === 2)!;
let it1 = new LinkedList.RetroValueIterator(n);
let it2 = it1.clone();
expect(it1.iter()).to.equal(it1);
expect(it2.iter()).to.equal(it2);
expect(toArray(it1)).to.deep.equal([2, 1, 0]);
expect(toArray(it2)).to.deep.equal([2, 1, 0]);
});
});
describe('.ForwardNodeIterator', () => {
it('should create a forward iterator over the nodes', () => {
let list = LinkedList.from([0, 1, 2, 3, 4]);
let n = find(list.nodes(), n => n.value === 2)!;
let it1 = new LinkedList.ForwardNodeIterator(n);
let it2 = it1.clone();
let v1 = map(it1, n => n.value);
let v2 = map(it2, n => n.value);
expect(it1.iter()).to.equal(it1);
expect(it2.iter()).to.equal(it2);
expect(toArray(v1)).to.deep.equal([2, 3, 4]);
expect(toArray(v2)).to.deep.equal([2, 3, 4]);
});
});
describe('.RetroNodeIterator', () => {
it('should create a reverse iterator over the nodes', () => {
let list = LinkedList.from([0, 1, 2, 3, 4]);
let n = find(list.nodes(), n => n.value === 2)!;
let it1 = new LinkedList.RetroNodeIterator(n);
let it2 = it1.clone();
let v1 = map(it1, n => n.value);
let v2 = map(it2, n => n.value);
expect(it1.iter()).to.equal(it1);
expect(it2.iter()).to.equal(it2);
expect(toArray(v1)).to.deep.equal([2, 1, 0]);
expect(toArray(v2)).to.deep.equal([2, 1, 0]);
});
});
});
}); | the_stack |
import { ActionType, ActionsType, ActionType2 } from './../../types'
import {
AppProps, App, Init, View, Subscribe,
OnUpdate, runActionResult, Context, Patch,
Component, normalize, ActionReturn
} from './../../index'
import { Dt, dt, never, CombinedComps } from '../../helpers'
import Cmd, { CmdType } from './../../cmd'
import { get, isFn, debug, error } from '../../utils'
import {
HistoryProps, BaseHistory, HashHistory,
BrowserHistory, MemoryHistory, MemoryHistoryProps,
parsePath, matchPath
} from './history'
import { inject } from '../../dispatcher';
export { parsePath, matchPath }
export {
HistoryProps, BaseHistory, HashHistory,
BrowserHistory, MemoryHistory, MemoryHistoryProps,
Context,
}
const CHANGE_LOCATION = '@@hydux-router/CHANGE_LOCATION'
export interface Param { [key: string]: string }
export interface Query { [key: string]: string | string[] }
export interface Location<P extends Param = Param, Q extends Query = Query> {
template: string | null
pathname: string
params: P
query: Q
search: string
hash: string
}
export interface History {
push: (path: string) => void,
replace: (path: string) => void,
go: (delta: number) => void,
back: () => void,
forward: () => void,
}
export type RouterActions<Actions extends Object> = Actions & {
history: History
}
export type RouterState<State extends Object, LazyComps = any> = State & {
location: Location
lazyComps: LazyComps
}
export interface LinkProps {
to: string,
onClick?: (e: any) => void,
replace?: boolean,
/** Prefetch splitted components, this will work only if you add code splitting first. */
prefetch?: boolean,
onMouseOver?: (e: any) => void
onMouseOut?: (e: any) => void
onTouchStart?: (e: any) => void
className?: string
onTouchEnd?: (e: any) => void
onTouchMove?: (e: any) => void
[k: string]: any
// Feel free to add more...
}
export function mkLink(history: BaseHistory, h, opts: {
comp?: string
} = {}) {
const React = { createElement: h }
return function Link({
to,
onClick,
replace = false,
prefetch = false,
...props
}: LinkProps,
children?: any
) {
function handleClick(e: any) {
if (replace) {
history.replace(to)
} else {
history.push(to)
}
e.preventDefault()
e.stopPropagation()
onClick && onClick(e)
}
const Comp: any = opts.comp || 'a'
if ('children' in props) {
children = (props as any).children
}
function handlePrefetch(e: any) {
if (!prefetch) {
return
}
const h = history as BaseHistory
if (!h._routesMeta) {
return console.error(`[hydux-router] Prefetch link requires passing nested routes to withRouter!`)
}
const loc = h.parsePath(to)
if (loc.template) {
const meta = h._routesMeta[loc.template]
if (!meta || !meta.getComponent) {
return console.error(`[hydux-router] Prefetch link requires code-splitting components as router component!`)
}
const [key, comp] = meta.getComponent()
comp.then(() => {
debug('router-link', `Component ${key} prefetched!`)
})
}
}
return (
<Comp
href={history.realPath(to)}
{...props}
onMouseOver={e => {
handlePrefetch(e)
props.onMouseOver && props.onMouseOver(e)
}}
onTouchStart={e => {
handlePrefetch(e)
props.onTouchStart && props.onTouchStart(e)
}}
onClick={handleClick}
>
{children}
</Comp>
)
}
}
export type Routes<State, Actions> = {
[key: string]: ActionType<Location<any, any>, State, Actions>
}
export interface RouterAppProps<State, Actions> extends AppProps<State, Actions> {
view: View<RouterState<State>, RouterActions<Actions>>
onUpdated?: OnUpdate<RouterState<State>, RouterActions<Actions>>,
}
export type Options<S, A> = {
history?: BaseHistory,
/** Whether is running in SSR mode, used for code-splitting */
ssr?: boolean,
/** Whether is running in the server side, if `ssr` is true, used for code-splitting */
isServer?: boolean,
routes: Routes<S, A> | NestedRoutes<S, A>,
hot?: boolean
}
let _hotListener = null as any
export default function withRouter<State, Actions>(props: Options<State, Actions> = { routes: {} }) {
const {
history = new HashHistory(),
routes,
ssr = false,
isServer = typeof window === 'undefined' || (typeof self !== undefined && window !== self),
hot = module['hot'],
} = props
let timer
return (app: App<State, Actions>) => (props: RouterAppProps<State, Actions>) => {
let routesMap: Routes<State, Actions> = routes as any
let routesMeta = {} as any as RoutesMeta<State, Actions>
if (('path' in routes) && typeof (routes as any).path === 'string') {
const parsed = parseNestedRoutes<State, Actions>(routes as any)
routesMap = parsed.routes
routesMeta = parsed.meta
}
history._setRoutes(routesMap, routesMeta)
const loc: Location<any, any> = history.location
const meta = routesMeta[loc.template!]
const getRouteComp = (meta?: RouteMeta<State, Actions>, fromInit = false): RouteComp<State, Actions> => {
if (!meta || !meta.getComponent) {
return dt('crossNormal', null)
}
const ret = meta.getComponent()
const [key, comp] = ret
let renderOnServer = true
if (ret.length >= 3) {
renderOnServer = ret[2] as boolean
}
if (ssr) {
if (isServer && !renderOnServer) {
return dt('crossNormal', null)
}
if (fromInit && !isServer && renderOnServer) {
return dt('clientHydrate', { key, comp })
}
}
return dt('crossDynamic', { key, comp })
}
let initComp = getRouteComp(meta, true)
let isRenderable = false
function runRoute<S, A>(routeComp: RouteComp<S, A>, actions: A, loc: Location) {
const meta = routesMeta[loc.template!]
switch (routeComp.tag) {
case 'crossDynamic':
case 'clientHydrate':
const key = routeComp.data.key
const isClientHydrate = routeComp.tag === 'clientHydrate'
return routeComp.data.comp.then(
comp => ctx.patch(key, comp, isClientHydrate)
).then(
() => {
if (isClientHydrate) { // trigger client ssr render
isRenderable = true
return ctx.render()
}
isRenderable = true
return actions[CHANGE_LOCATION](loc) as CmdType<A>
}
)
case 'crossNormal':
isRenderable = true
return actions[CHANGE_LOCATION](loc) as CmdType<A>
default: return never(routeComp)
}
}
const ctx = app({
...props,
init: () => {
let result = normalize(props.init())
let cmd = Cmd.batch(
result.cmd,
Cmd.ofSub<RouterActions<Actions>>(
actions => {
const ar = runRoute(initComp, actions, loc)
if (ar instanceof Promise) {
return ar
}
return Promise.all(ar)
}
)
)
let state = { ...result.state as any, location: loc, lazyComps: {} } as RouterState<State>
return { state, cmd }
},
subscribe: state => Cmd.batch(
Cmd.ofSub<RouterActions<Actions>>(actions => {
let _listener = path => {
const loc = history.location
const meta = routesMeta[loc.template!]
let comp = getRouteComp(meta, false)
runRoute(comp, actions, loc)
if (meta && meta.redirect) {
setTimeout(() => {
history.replace(meta.redirect!)
})
}
}
if (hot) {
const key = '@hydux-router/listener'
if (_hotListener) {
history.unlisten(_hotListener)
}
_hotListener = _listener
}
history.listen(_listener)
}),
props.subscribe ? props.subscribe(state) : Cmd.none
),
actions: {
...props.actions as any,
history: ({
push: path => setTimeout(() => history.push(path)),
replace: path => setTimeout(() => history.replace(path)),
go: delta => setTimeout(() => history.go(delta)),
back: () => setTimeout(() => history.back()),
forward: () => setTimeout(() => history.forward()),
} as History),
[CHANGE_LOCATION]: (loc: Location<any, any>, resolve?: Function) => (state: State, actions: Actions) => {
let ctx = inject()
if (loc.template) {
let action = routesMap[loc.template]
let { state: nextState, cmd } = runActionResult(action(loc))
ctx.setState({
...nextState as any,
location: loc
})
ctx._internals.cmd = cmd
} else {
ctx.setState({
...state as any,
location: loc
})
}
},
},
onRender(view) {
if (isRenderable) {
props.onRender && props.onRender(view)
}
}
})
return ctx
}
}
export type RouteComp<S, A> =
/**
* patch and render dynamic component on the server or client
*/
| Dt<'crossDynamic', {key: string, comp: Promise<Component<S, A>>}>
/**
* client hydrate for dynamic component on the client side
*/
| Dt<'clientHydrate', {key: string, comp: Promise<Component<S, A>>}>
/**
* render as normal static component on the server or client
*/
| Dt<'crossNormal', null>
export type GetComp<S, A> = () =>
| [string /** key */, Promise<Component<S, A>>]
| [string /** key */, Promise<Component<S, A>>, boolean /** whether rendering on the server side, default is true */]
export interface NestedRoutes<State, Actions> {
path: string,
label?: string,
// key?: keyof Actions
// component?: Component<any, any>
action?: ActionType<Location<any, any>, State, Actions>,
children?: NestedRoutes<State, Actions>[],
/**
* Get a dynamic component, you need to return the key and the promise of the component, if you setup SSR, it would automatically rendered in the server side, but you can return a third boolean value to indicate whether rendering on the server side.
* e.g.
* () =>
* | [string /** key *\/, Promise<Component<S, A>>]
* | [string /** key *\/, Promise<Component<S, A>>, boolean /** false to disable rendering on the server side *\/]
*/
getComponent?: GetComp<any, any>
}
export interface RouteInfo<State, Actions> {
path: string,
label?: string,
action?: ActionType<Location<any, any>, State, Actions>,
}
export interface RouteMeta<State, Actions> {
path: string,
redirect?: string
label?: string,
action?: ActionType<Location<any, any>, State, Actions>,
getComponent?: GetComp<State, Actions>
parents: RouteInfo<State, Actions>[],
children: RouteInfo<State, Actions>[],
}
export interface RoutesMeta<State, Actions> {
[key: string]: RouteMeta<State, Actions>
}
export function join(...args: string[]) {
return args.join('/').replace(/\/+/g, '/')
}
/**
* @param routes nested routes contains path, action, children, it would parse it to a `route` field (path:action map) for router enhancer, and a `meta` field which contains each route's parents.
*/
export function parseNestedRoutes<State, Actions>(routes: NestedRoutes<State, Actions>): {
routes: Routes<State, Actions>,
meta: RoutesMeta<State, Actions>,
} {
function rec(routes: NestedRoutes<State, Actions>, newRoutes: {}): RoutesMeta<State, Actions> {
let children = routes.children || []
newRoutes[routes.path] = {
...routes,
parents: (routes as any).parents || [],
children: children.map(r => ({ ...r, parents: void 0, children: void 0 }))
}
children
.map(r => {
let action = r.action
return {
...r,
path: join(routes.path, r.path),
action,
parents: ((routes as any).parents || []).concat({
...routes,
parents: void 0,
children: void 0,
}),
children: r.children,
}
})
.forEach(r => rec(r as any, newRoutes))
return newRoutes
}
const meta = rec(routes, {})
let simpleRoutes = {} as Routes<State, Actions>
for (const key in meta) {
const route = meta[key]
if (route.action) {
simpleRoutes[key] = route.action
}
}
return { routes: simpleRoutes, meta }
} | the_stack |
import {Injectable} from '@angular/core';
import {SettingsService} from './settings.service';
import * as child from 'child_process';
import * as path from 'path';
import {LogService} from './log.service';
import {LogType} from '../enum/log.type.enum';
import * as AWS from 'aws-sdk';
import {ElectronService} from 'ngx-electron';
import * as fse from 'fs-extra';
import * as sugar from 'sugar';
import * as moment from 'moment';
import {Job} from '../models/job.model';
import {JobsService} from './jobs.service';
import {JobType} from '../enum/job.type.enum';
import {NotificationsService} from './notifications.service';
import {isNull, isUndefined} from 'util';
import {ProcessesHandlerService} from './processes-handler.service';
@Injectable({
providedIn: 'root'
})
export class AwsService {
client: any;
constructor(
private settings: SettingsService,
private logService: LogService,
private electron: ElectronService,
private jobService: JobsService,
private notification: NotificationsService,
private processedHandler: ProcessesHandlerService) {
}
checkCli() {
return new Promise<boolean>(resolve => {
const proc = child.spawn('aws', ['configure', 'list'], {shell: true});
proc.stderr.on('data', err => {
resolve(false);
});
proc.stdout.on('data', data => {
resolve(true);
});
proc.on('error', (err) => {
resolve(false);
});
});
}
async checkCredentials() {
const settings = this.settings.getSettings();
if (isUndefined(settings.awsAccessKeyID) || isUndefined(settings.awsSecretAccessKey) || isUndefined(settings.awsRegion)) {
return new Promise<boolean>(resolve => {
resolve(false);
});
}
await this.configureAwsCli();
return new Promise<boolean>(resolve => {
const proc = child.spawn('aws', ['s3', 'ls'], {shell: true});
proc.stderr.on('data', err => {
resolve(false);
});
proc.stdout.on('data', data => {
resolve(true);
});
proc.on('error', (err) => {
resolve(false);
});
// TODO: quando non ci sono bucket s3 associati all'account il loader non scompare perchè la aws cli non restituisce nulla
});
}
async configureAwsCli() {
const settings = this.settings.getSettings();
await child.spawn('aws', ['configure', 'set', 'aws_access_key_id', settings.awsAccessKeyID], {shell: true});
await child.spawn('aws', ['configure', 'set', 'aws_secret_access_key', settings.awsSecretAccessKey], {shell: true});
await child.spawn('aws', ['configure', 'set', 'default.region', settings.awsRegion], {shell: true});
await child.spawn('aws', ['configure', 'set', 'default.s3.max_concurrent_requests', settings.s3MaxConcurrentRequests], {shell: true});
await child.spawn('aws', ['configure', 'set', 'default.s3.max_bandwidth', settings.s3MaxBandwidth + 'KB/s'], {shell: true});
}
s3Sync(job: Job) {
if (job.isRunning && job.type !== JobType.Live) {
const msg = 'Couldn\'t run job "' + job.name + '" because it was already run. Probably the job is too big for the time slot.';
this.logService.printLog(LogType.WARNING, msg);
return;
}
job.setIsRunning(true);
if (job.type !== JobType.Live) {
this.logService.printLog(LogType.INFO, 'Start job: ' + job.name);
this.notification.sendNotification('Start job: ' + job.name, 'The job ' + job.name +
' has just begun you will receive another email notification on job end. <br/> - AWS S3 Backup', 'email');
}
const commands = [];
for (const file of job.files) {
let s3Args = [];
let bucket = 's3://' + job.bucket;
if (file.type === 'file') {
const filePath = path.dirname(file.path);
const dirPath = new URL(`file:///${filePath}`);
bucket += dirPath.pathname;
const fileInclude = '--include="' + path.basename(file.path) + '"';
s3Args = ['s3', 'sync', path.dirname(file.path), bucket, '--exclude="*"', fileInclude];
} else {
const filePath = file.path;
const dirPath = new URL(`file:///${filePath}`);
bucket += dirPath.pathname;
s3Args = ['s3', 'sync', file.path, bucket];
}
if (job.syncDeletedFiles) {
s3Args.push('--delete');
}
s3Args.push('--no-progress');
s3Args.push('--no-follow-symlinks');
commands.push(s3Args);
}
const runCommands = (commandsToRun, callback) => {
let index = 0;
const results = [];
const next = () => {
if (index < commandsToRun.length) {
const proc = child.spawn('aws', commandsToRun[index++], {shell: true});
this.processedHandler.addJobProcess(job.id, proc);
proc.on('close', (code) => {
this.processedHandler.killJobProcess(job.id, proc.pid);
if (code === 0 || code === 2) {
next();
} else {
return callback(null, null);
}
});
proc.on('error', err => {
job.setAlert(true);
this.jobService.save(job);
this.logService.printLog(LogType.ERROR, 'Can\'t run job ' + job.name + ' because of: \r\n' + err);
if (err) {
return callback(err);
}
});
proc.stdout.on('data', data => {
// if (job.type !== JobType.Live) {
// this.logService.printLog(LogType.INFO, data);
// }
// results.push(data.toString());
});
proc.stderr.on('data', err => {
job.setAlert(true);
this.jobService.save(job);
this.logService.printLog(LogType.ERROR, 'Error with job ' + job.name + ' because of: \r\n' + err);
});
} else {
// all done here
callback(null, results);
}
};
// start the first iteration
next();
};
let timeout = null;
if ( job.maxExecutionTime > 0 ) {
timeout = setTimeout(() => {
this.logService.printLog(LogType.INFO, 'The job ' + job.name + ' has just stopped because hit the maximum execution time. \r\n');
this.processedHandler.killJobProcesses(job.id);
}, job.maxExecutionTime);
}
runCommands(commands, (err, results) => {
if ( !isNull(timeout) ) {
clearTimeout(timeout);
}
job.setIsRunning(false);
this.jobService.save(job);
if (job.type !== JobType.Live) {
this.logService.printLog(LogType.INFO, 'End job: ' + job.name);
if (job.alert) {
this.notification.sendNotification('Problem with job: ' + job.name, 'The job ' + job.name +
' generated an alert, for further details see the log in attachment.<br/> - AWS S3 Backup', 'email', true);
}
this.notification.sendNotification('End job: ' + job.name, 'The job ' + job.name +
' has just ended. <br/> - AWS S3 Backup', 'email');
this.jobService.checkExpiredJob(job);
}
this.processedHandler.killJobProcesses(job.id);
});
}
configureAwsSdk() {
// non serve se è installata e configurata l'AWS CLI
const credentials = this.settings.getSettings();
const config = new AWS.Config({
accessKeyId: credentials.awsAccessKeyID, secretAccessKey: credentials.awsSecretAccessKey, region: credentials.awsRegion
});
}
async getBucketSizeBytesLastDays(bucket, storageType, days) {
const credentials = this.settings.getSettings();
const cloudwatch = new AWS.CloudWatch({region: credentials.awsRegion});
const today = new Date();
const daysBack = new Date();
daysBack.setDate(daysBack.getDate() - days);
const params = {
EndTime: today, /* required */
MetricName: 'BucketSizeBytes', /* required */
Namespace: 'AWS/S3', /* required */
Period: 86400, /* required */
StartTime: daysBack, /* required */
Dimensions: [
{
Name: 'BucketName', /* required */
Value: bucket /* required */
},
{
Name: 'StorageType',
Value: storageType
}
/* more items */
],
Statistics: [
'Average'
],
Unit: 'Bytes'
};
try {
const data = await cloudwatch.getMetricStatistics(params).promise();
if (!isUndefined(data.Datapoints)) {
const datapoints = data.Datapoints;
sugar.Array.sortBy(datapoints, (datapoint: any) => {
return datapoint.Timestamp;
});
return datapoints;
}
} catch (e) {
console.log(e);
return [];
}
}
async getBucketNumberOfObjectsLastDays(bucket, storageType, days) {
const credentials = this.settings.getSettings();
const cloudwatch = new AWS.CloudWatch({region: credentials.awsRegion});
const today = new Date();
const daysBack = new Date();
daysBack.setDate(daysBack.getDate() - days);
const params = {
EndTime: today, /* required */
MetricName: 'NumberOfObjects', /* required */
Namespace: 'AWS/S3', /* required */
Period: 86400, /* required */
StartTime: daysBack, /* required */
Dimensions: [
{
Name: 'BucketName', /* required */
Value: bucket /* required */
},
{
Name: 'StorageType',
Value: 'AllStorageTypes'
}
/* more items */
],
Statistics: [
'Average'
],
Unit: 'Count'
};
try {
const data = await cloudwatch.getMetricStatistics(params).promise();
if (!isUndefined(data.Datapoints)) {
const datapoints = data.Datapoints;
sugar.Array.sortBy(datapoints, (datapoint: any) => {
return datapoint.Timestamp;
});
return datapoints;
}
} catch (e) {
console.log(e);
return [];
}
}
async getBucketSizeBytes(bucket, storageType) {
const credentials = this.settings.getSettings();
const cloudwatch = new AWS.CloudWatch({region: credentials.awsRegion});
const today = new Date();
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const params = {
EndTime: today, /* required */
MetricName: 'BucketSizeBytes', /* required */
Namespace: 'AWS/S3', /* required */
Period: 86400, /* required */
StartTime: yesterday, /* required */
Dimensions: [
{
Name: 'BucketName', /* required */
Value: bucket /* required */
},
{
Name: 'StorageType',
Value: storageType
}
/* more items */
],
Statistics: [
'Average'
],
Unit: 'Bytes'
};
try {
const data = await cloudwatch.getMetricStatistics(params).promise();
if (!isUndefined(data.Datapoints[0].Average)) {
return sugar.Number.bytes(data.Datapoints[0].Average, 2);
}
} catch (e) {
console.log(e);
return '0KB';
}
}
async getBucketNumberOfObjects(bucket) {
const credentials = this.settings.getSettings();
const cloudwatch = new AWS.CloudWatch({region: credentials.awsRegion});
const today = new Date();
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const params = {
EndTime: today, /* required */
MetricName: 'NumberOfObjects', /* required */
Namespace: 'AWS/S3', /* required */
Period: 86400, /* required */
StartTime: yesterday, /* required */
Dimensions: [
{
Name: 'BucketName', /* required */
Value: bucket /* required */
},
{
Name: 'StorageType',
Value: 'AllStorageTypes'
}
/* more items */
],
Statistics: [
'Average'
],
Unit: 'Count'
};
try {
const data = await cloudwatch.getMetricStatistics(params).promise();
if (!isUndefined(data.Datapoints[0].Average)) {
return sugar.Number.abbr(data.Datapoints[0].Average, 1);
}
} catch (e) {
console.log(e);
return '0';
}
}
async listBuckets() {
const S3 = new AWS.S3();
try {
const data = await S3.listBuckets().promise();
return data.Buckets;
} catch (e) {
console.log(e);
return [];
}
}
async listObjects(bucket: string, pathDirectory: string) {
const S3 = new AWS.S3();
const param = {
Bucket: bucket,
Delimiter: '/',
Prefix: pathDirectory
};
try {
const data = await S3.listObjectsV2(param).promise();
data.CommonPrefixes.forEach(function (obj) {
obj['Name'] = sugar.Array.exclude(obj.Prefix.split('/'), '').pop();
});
data.Contents.forEach(function (obj) {
obj['Name'] = path.basename(obj.Key);
obj['LastUpdate'] = moment(obj.LastModified).format('DD/MM/YYYY HH:mm');
obj['SizeFormatted'] = sugar.Number.bytes(obj.Size);
});
return {
directories: data.CommonPrefixes,
files: data.Contents,
};
} catch (e) {
console.log(e);
return {};
}
}
async downloadObject(bucket: string, key: string) {
const S3 = new AWS.S3();
const param = {
Bucket: bucket,
Key: key
};
try {
const data = await S3.getObject(param).promise();
this.electron.remote.dialog.showSaveDialog({defaultPath: path.basename(key)}, (filePath) => {
if (filePath !== undefined) {
fse.writeFileSync(filePath, data.Body);
}
this.electron.remote.getCurrentWindow().blurWebView();
});
} catch (e) {
console.log(e);
return false;
}
}
} | the_stack |
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
forwardRef,
Inject,
Injector,
Input,
OnChanges,
QueryList,
SimpleChanges,
ViewChild,
ViewChildren
} from "@angular/core";
import {AbstractControl, ControlValueAccessor, FormArray, FormControl, FormGroup, NG_VALUE_ACCESSOR} from "@angular/forms";
import {InputParameterModel} from "cwlts/models/generic/InputParameterModel";
import {AppModelToken} from "../../core/factories/app-model-provider-factory";
import {ModalService} from "../../ui/modal/modal.service";
import {DirectiveBase} from "../../util/directive-base/directive-base";
import {FileMetadataModalComponent} from "../file-metadata-modal/file-metadata-modal.component";
import {NativeSystemService} from "../../native/system/native-system.service";
import {take, filter} from "rxjs/operators";
@Component({
selector: "ct-input-value-editor",
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: "./input-value-editor.component.html",
styleUrls: ["./input-value-editor.component.scss"],
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputValueEditorComponent),
multi: true
}]
})
export class InputValueEditorComponent extends DirectiveBase implements OnChanges, AfterViewInit, ControlValueAccessor {
@Input() readonly = false;
@Input() inputType: string;
@Input() inputArrayItemsType: string;
@Input() inputEnumSymbols: string[];
@Input() inputRecordFields: InputParameterModel[];
@Input() relativePathRoot?: string;
/**
* We might want to show a warning next to a field.
* This can happen for example if we encounter a mismatch between step value and the input type,
* for example, an input can by File[], and the step value can be just a plain string.
*/
warning: string;
secondaryFilesCount = 0;
metadataKeysCount = 0;
@ViewChildren("arrayItem", {read: InputValueEditorComponent})
private arrayElements: QueryList<InputValueEditorComponent>;
@ViewChild("input", {read: ElementRef})
private inputElement: ElementRef;
private propagateTouch: any;
private propagateChange: any;
private control: AbstractControl;
constructor(private cdr: ChangeDetectorRef,
private modal: ModalService,
private injector: Injector,
private native: NativeSystemService,
@Inject(AppModelToken) private appModel) {
super();
}
writeValue(value: any): void {
if (value === undefined) {
return;
}
const updateOptions = {emitEvent: false};
this.warning = undefined;
let update = value;
switch (this.inputType) {
case "record":
update = value instanceof Object ? value : {} as InputParameterModel;
const group = this.control as FormGroup;
if (!value) {
for (const key in group.controls) {
group.controls[key].setValue(null, updateOptions);
}
break;
}
this.control.patchValue(update, updateOptions);
break;
case "array":
if (this.inputType === "array" && !Array.isArray(value)) {
this.patchArrayValue([], updateOptions);
} else {
this.patchArrayValue(update, updateOptions);
}
break;
case "string":
this.control.setValue(update ? String(update) : "", updateOptions);
break;
case "float":
const float = parseFloat(update);
this.control.setValue(isNaN(float) ? 0 : float, updateOptions);
break;
case "int":
const int = parseInt(update);
this.control.setValue(isNaN(int) ? 0 : int, updateOptions);
break;
case "boolean":
this.control.setValue(Boolean(update), updateOptions);
break;
case "Directory":
update = value || {};
this.control.setValue({
class: this.inputType,
path: update.path || ""
}, updateOptions);
this.recalculateSecondaryFilesAndMetadataCounts();
break;
case "File":
update = value || {};
this.control.setValue({
class: this.inputType,
path: update.path || "",
secondaryFiles: Array.isArray(update.secondaryFiles) ? update.secondaryFiles : [],
metadata: Object.prototype.isPrototypeOf(update.metadata) ? update.metadata : {}
}, updateOptions);
this.recalculateSecondaryFilesAndMetadataCounts();
break;
default:
this.control.setValue(update, updateOptions);
break;
}
this.cdr.markForCheck();
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void {
this.propagateTouch = fn;
}
ngAfterViewInit() {
this.arrayElements.changes.subscribeTracked(this, list => {
const plainInputTypes = ["boolean", "float", "int", "string", "enum"];
if (plainInputTypes.indexOf(this.inputArrayItemsType) !== -1 && list.last) {
list.last.focus();
}
});
}
/**
* Whenever our inputs change, we should recreate form controls for this component
*/
ngOnChanges(changes: SimpleChanges): void {
if (changes.inputType || changes.inputRecordFields) {
this.setupFormControls();
}
if (changes.inputType) {
this.bindFileMetadataSyncOnControlChanges();
this.bindValuePropagationOnControlSetup();
}
if (changes.readonly) {
if (this.readonly) {
this.control.disable({onlySelf: true, emitEvent: false});
} else {
this.control.enable({onlySelf: true, emitEvent: false});
}
}
}
clear() {
this.control.setValue(null);
}
addArrayEntry(): void {
this.warning = undefined;
const control = this.makeControlForArray();
(this.control as FormArray).push(control);
}
deleteFromArray(index: number, control = this.control as FormArray): void {
control.removeAt(index);
}
focus(): void {
if (this.inputElement && this.inputElement.nativeElement) {
this.inputElement.nativeElement.focus();
}
}
setDisabledState(isDisabled: boolean): void {
if (isDisabled && this.control.enabled) {
this.control.disable();
} else if (!isDisabled && this.control.disabled) {
this.control.enable();
}
this.cdr.markForCheck();
}
promptFileMetadata() {
const {secondaryFiles, metadata} = this.control.value;
const allowDirectories = this.appModel.cwlVersion.indexOf("draft-2") === -1;
const relativePathRoot = this.relativePathRoot;
const comp = this.modal.fromComponent(FileMetadataModalComponent, "Secondary files and metadata", {
metadata,
secondaryFiles,
allowDirectories,
relativePathRoot
});
comp.submit.pipe(
take(1)
).subscribeTracked(this, (data) => {
this.modal.close();
this.control.patchValue(data);
this.cdr.markForCheck();
});
}
addArrayFileOrDirectory() {
const properties = ["multiSelections"] as any;
properties.push(this.inputArrayItemsType === "File" ? "openFile" : "openDirectory");
this.native.openFileChoiceDialog({properties}).then(filePaths => {
const fileOrDirEntries = filePaths.map(p => ({class: this.inputArrayItemsType, path: p}));
fileOrDirEntries.forEach(entry => (this.control as FormArray).push(new FormControl(entry)));
this.cdr.markForCheck();
}, () => void 0);
}
private bindFileMetadataSyncOnControlChanges() {
this.control.valueChanges.subscribeTracked(this, () => {
this.recalculateSecondaryFilesAndMetadataCounts();
});
}
private bindValuePropagationOnControlSetup() {
this.control.valueChanges.pipe(
// We this is called from ngOnChanges, so on first call propagateChange will not be set,
// therefore, we should not try to propagate the value right away
filter(() => this.control.status !== "DISABLED" && typeof this.propagateChange === "function")
).subscribeTracked(this, change => {
let typecheckedChange = change;
if (this.inputType === "int") {
typecheckedChange = parseInt(change, 10);
} else if (this.inputType === "float") {
typecheckedChange = isNaN(change) ? 0 : parseFloat(change);
}
this.propagateChange(typecheckedChange);
});
}
private setupFormControls(): void {
const disabled = this.readonly;
switch (this.inputType) {
case "array":
this.control = new FormArray([]);
disabled ? this.control.disable() : this.control.enable();
break;
case "record":
const controls = {};
for (const field of this.inputRecordFields) {
controls[field.id] = new FormControl({value: undefined, disabled});
}
this.control = new FormGroup(controls);
break;
case "File":
this.control = new FormGroup({
path: new FormControl({value: undefined, disabled}),
class: new FormControl({value: "File", disabled}),
metadata: new FormControl({value: {}, disabled}),
secondaryFiles: new FormControl({value: [], disabled}),
});
break;
case "Directory":
this.control = new FormGroup({
class: new FormControl("Directory"),
path: new FormControl({value: undefined, disabled})
});
break;
default:
this.control = new FormControl();
disabled ? this.control.disable() : this.control.enable();
break;
}
}
private patchArrayValue(update: any[], options: { onlySelf?: boolean, emitEvent?: boolean }) {
const updateIsSameSize = update.length === (this.control as FormArray).length;
const serializesEqually = () => JSON.stringify(update) === JSON.stringify(this.control.value);
const shouldNotEmit = options.emitEvent === false;
// This solves a problem that
if (updateIsSameSize && shouldNotEmit && serializesEqually()) {
return;
}
if (!updateIsSameSize) {
const ctrlArr = Array.apply(null, Array(update.length)).map(() => this.makeControlForArray());
this.control = new FormArray(ctrlArr);
this.readonly ? this.control.disable(options) : this.control.enable(options);
this.bindFileMetadataSyncOnControlChanges();
this.bindValuePropagationOnControlSetup();
}
this.control.setValue(update, options);
}
private makeControlForArray(): AbstractControl {
switch (this.inputArrayItemsType) {
case "array":
return new FormArray([]);
case "record":
return new FormControl({});
case "string":
return new FormControl("");
case "int":
case "float":
return new FormControl(0);
case "boolean":
return new FormControl(false);
case "Directory":
return new FormControl({
class: "Directory",
path: ""
});
case "File":
return new FormControl({
path: "",
class: "File",
metadata: {},
secondaryFiles: [],
});
default:
return new FormControl();
}
}
private recalculateSecondaryFilesAndMetadataCounts() {
const ctrlVal = Object.prototype.isPrototypeOf(this.control.value) ? this.control.value : {};
const {secondaryFiles, metadata} = ctrlVal;
this.secondaryFilesCount = Array.isArray(secondaryFiles) ? secondaryFiles.length : 0;
this.metadataKeysCount = Object.prototype.isPrototypeOf(metadata) ? Object.keys(metadata).length : 0;
}
} | the_stack |
import React, { useCallback, useState, useEffect } from 'react';
import classes from './Risk.module.scss';
import { ResponsivePie } from '@nivo/pie';
import { ResponsiveBar } from '@nivo/bar';
import { useAuthContext } from 'context';
import { makeStyles, Paper, Tooltip, Chip } from '@material-ui/core';
import { Pagination } from '@material-ui/lab';
import { geoCentroid } from 'd3-geo';
import {
ComposableMap,
Geographies,
Geography,
ZoomableGroup,
Marker,
Annotation
} from 'react-simple-maps';
import { scaleLinear } from 'd3-scale';
import { Link, useHistory } from 'react-router-dom';
import { Vulnerability } from 'types';
import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';
import { Button as USWDSButton } from '@trussworks/react-uswds';
interface Point {
id: string;
label: string;
value: number;
}
interface Stats {
domains: {
services: Point[];
ports: Point[];
numVulnerabilities: Point[];
total: number;
};
vulnerabilities: {
severity: Point[];
byOrg: Point[];
latestVulnerabilities: Vulnerability[];
mostCommonVulnerabilities: VulnerabilityCount[];
};
}
interface ApiResponse {
result: Stats;
}
interface VulnerabilityCount extends Vulnerability {
count: number;
}
interface VulnSeverities {
label: string;
sevList: string[];
disable?: boolean;
amount?: number;
}
// Color Scale used for map
let colorScale = scaleLinear<string>()
.domain([0, 1])
.range(['#c7e8ff', '#135787']);
export const getSeverityColor = ({ id }: { id: string }) => {
if (id === 'null' || id === '') return '#EFF1F5';
else if (id === 'Low') return '#F8DFE2';
else if (id === 'Medium') return '#F2938C';
else if (id === 'High') return '#B51D09';
else return '#540C03';
};
const Risk: React.FC = (props) => {
const history = useHistory();
const {
currentOrganization,
showAllOrganizations,
user,
apiPost
} = useAuthContext();
const [stats, setStats] = useState<Stats | undefined>(undefined);
const [labels, setLabels] = useState([
'',
'Low',
'Medium',
'High',
'Critical'
]);
const [domainsWithVulns, setDomainsWithVulns] = useState(0);
const [isLoading, setIsLoading] = useState(false);
const [current, setCurrent] = useState(1);
const cardClasses = useStyles(props);
const geoStateUrl = 'https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json';
const allColors = ['rgb(0, 111, 162)', 'rgb(0, 185, 227)'];
const resultsPerPage = 30;
const getSingleColor = () => {
return '#FFBC78';
};
const truncateText = (text: string, len: number) => {
if (text.length <= len) return text;
return text.substring(0, len) + '...';
};
const fetchStats = useCallback(
async (orgId?: string) => {
const { result } = await apiPost<ApiResponse>('/stats', {
body: {
filters:
(!orgId && showAllOrganizations) || !currentOrganization
? {}
: orgId || 'rootDomains' in currentOrganization
? {
organization: orgId ? orgId : currentOrganization?.id
}
: { tag: currentOrganization.id }
}
});
const max = Math.max(...result.vulnerabilities.byOrg.map((p) => p.value));
// Adjust color scale based on highest count
colorScale = scaleLinear<string>()
.domain([0, Math.log(max)])
.range(['#c7e8ff', '#135787']);
setStats(result);
},
[showAllOrganizations, apiPost, currentOrganization]
);
useEffect(() => {
fetchStats();
}, [fetchStats]);
const MyResponsivePie = ({
data,
colors,
type
}: {
data: Point[];
colors: any;
type: string;
}) => {
return (
<ResponsivePie
data={data as any}
innerRadius={0.5}
padAngle={0.7}
arcLabelsSkipAngle={10}
arcLinkLabelsSkipAngle={10}
colors={colors}
margin={{
left: 30,
right: 50,
top: 30,
bottom: 50
}}
onClick={(event) => {
if (type === 'vulns') {
history.push(`/inventory/vulnerabilities?severity=${event.id}`);
}
}}
/>
);
};
const MyResponsiveBar = ({
data,
xLabels,
type,
longXValues = false
}: {
data: Point[];
xLabels: string[];
type: string;
longXValues?: boolean;
}) => {
const keys = xLabels;
let dataVal: object[];
const pageStart = (current - 1) * resultsPerPage;
if (type === 'ports') {
dataVal = data.map((e) => ({ ...e, [xLabels[0]]: e.value })) as any;
} else {
// Separate count by severity
const domainToSevMap: any = {};
for (const point of data) {
const split = point.id.split('|');
const domain = split[0];
const severity = split[1];
if (labels.includes(severity)) {
if (!(domain in domainToSevMap)) domainToSevMap[domain] = {};
domainToSevMap[domain][severity] = point.value;
}
}
setDomainsWithVulns(Object.keys(domainToSevMap).length);
dataVal = Object.keys(domainToSevMap)
.map((key) => ({
label: key,
...domainToSevMap[key]
}))
.sort((a, b) => {
let diff = 0;
for (const label of xLabels) {
diff += (label in b ? b[label] : 0) - (label in a ? a[label] : 0);
}
return diff;
})
.slice(pageStart, Math.min(pageStart + 30, domainsWithVulns))
.reverse();
}
// create the total vuln labels for each domain
const totalLabels = ({ bars, width }: any) => {
const fullWidth = width + 5;
return bars.map(
({ data: { data, indexValue }, y, height, width }: any, i: number) => {
const total = Object.keys(data)
.filter((key) => key !== 'label')
.reduce((a, key) => a + data[key], 0);
if (i < dataVal.length) {
return (
<g
transform={`translate(${fullWidth}, ${y})`}
key={`${indexValue}-${i}`}
>
<text
x={10}
y={height / 2}
textAnchor="middle"
alignmentBaseline="central"
// add any style to the label here
style={{
fill: 'rgb(51, 51, 51)',
fontSize: 12
}}
>
{total}
</text>
</g>
);
}
return null;
}
);
};
return (
<ResponsiveBar
data={dataVal}
keys={keys}
layers={
type === 'ports'
? ['grid', 'axes', 'bars', 'markers', 'legends']
: ['grid', 'axes', 'bars', totalLabels, 'markers', 'legends']
}
indexBy="label"
margin={{
top: longXValues ? 10 : 30,
right: 40,
bottom: longXValues ? 150 : 75,
left: longXValues ? 260 : 100
}}
theme={{
fontSize: 12,
axis: {
legend: {
text: {
fontWeight: 'bold'
}
}
}
}}
onClick={(event) => {
if (type === 'vulns') {
history.push(
`/inventory/vulnerabilities?domain=${event.data.label}&severity=${event.id}`
);
} else if (type === 'ports') {
history.push(
`/inventory?filters[0][field]=services.port&filters[0][values][0]=n_${event.data.label}_n&filters[0][type]=any`
);
window.location.reload();
}
}}
padding={0.5}
colors={type === 'ports' ? getSingleColor : getSeverityColor}
borderColor={{ from: 'color', modifiers: [['darker', 1.6]] }}
axisTop={null}
axisRight={null}
axisBottom={{
tickSize: 0,
tickPadding: 5,
tickRotation: 0,
legend: type === 'ports' ? 'Count' : '',
legendPosition: 'middle',
legendOffset: 40
}}
axisLeft={{
tickSize: 0,
tickPadding: 20,
tickRotation: 0,
legend: type === 'ports' ? 'Port' : '',
legendPosition: 'middle',
legendOffset: -65
}}
animate={true}
enableLabel={false}
motionStiffness={90}
motionDamping={15}
layout={'horizontal'}
enableGridX={true}
enableGridY={false}
/>
);
};
const VulnerabilityCard = ({
title,
showLatest,
showCommon,
data
}: {
title: string;
showLatest: boolean;
showCommon: boolean;
data: VulnerabilityCount[];
}) => (
<Paper elevation={0} className={cardClasses.cardRoot}>
<div className={cardClasses.cardSmall}>
{showLatest && (
<div className={cardClasses.seeAll}>
<h4>
<Link to="/inventory/vulnerabilities?sort=createdAt&desc=false">
See All
</Link>
</h4>
</div>
)}
{showCommon && (
<div className={cardClasses.seeAll}>
<h4>
<Link to="/inventory/vulnerabilities/grouped">See All</Link>
</h4>
</div>
)}
<div className={cardClasses.header}>
<h2>{title}</h2>
</div>
<div className={cardClasses.body}>
{/* <h4 style={{ float: 'left' }}>Today:</h4> */}
<div>
{data.length === 0 && <h3>No open vulnerabilities</h3>}
{data.length > 0 &&
data.slice(0, 4).map((vuln) => (
<Tooltip
title={
<span style={{ fontSize: 14 }}>
{truncateText(vuln.description, 120)}
</span>
}
placement="right"
arrow
key={vuln.title}
>
<Paper
elevation={0}
className={cardClasses.miniCardRoot}
aria-label="view domain details"
onClick={() => {
history.push(
'/inventory/vulnerabilities?title=' +
vuln.title +
(vuln.domain ? '&domain=' + vuln.domain.name : '')
);
}}
>
<div className={cardClasses.cardInner}>
<div className={cardClasses.vulnCount}>{vuln.count}</div>
<div className={cardClasses.miniCardLeft}>
{vuln.title}
</div>
<div className={cardClasses.miniCardCenter}>
<p
className={cardClasses.underlined}
style={{
borderBottom: `6px solid ${getSeverityColor({
id: vuln.severity ?? ''
})}`
}}
>
{vuln.severity}
</p>
</div>
<button className={cardClasses.button}>DETAILS</button>
</div>
{
<hr
style={{
border: '1px solid #F0F0F0',
position: 'relative',
maxWidth: '90%'
}}
/>
}
</Paper>
</Tooltip>
))}
</div>
</div>
</div>
</Paper>
);
const offsets: any = {
Vermont: [50, -8],
'New Hampshire': [34, 2],
Massachusetts: [30, -1],
'Rhode Island': [28, 2],
Connecticut: [35, 10],
'New Jersey': [34, 1],
Delaware: [33, 0],
Maryland: [47, 10],
'District of Columbia': [49, 21]
};
const MapCard = ({
title,
geoUrl,
findFn,
type
}: {
title: string;
geoUrl: string;
findFn: (geo: any) => Point | undefined;
type: string;
}) => (
<Paper elevation={0} classes={{ root: cardClasses.cardRoot }}>
<div>
<div className={classes.chart}>
<div className={cardClasses.header}>
<h2>{title}</h2>
</div>
<ComposableMap
data-tip="hello world"
projection="geoAlbersUsa"
style={{
width: '90%',
display: 'block',
margin: 'auto'
}}
>
<ZoomableGroup zoom={1}>
<Geographies geography={geoUrl}>
{({ geographies }) =>
geographies.map((geo) => {
const cur = findFn(geo) as
| (Point & {
orgId: string;
})
| undefined;
const centroid = geoCentroid(geo);
const name: string = geo.properties.name;
return (
<React.Fragment key={geo.rsmKey}>
<Geography
geography={geo}
fill={colorScale(cur ? Math.log(cur.value) : 0)}
onClick={() => {
if (cur) fetchStats(cur.orgId);
}}
/>
<g>
{centroid[0] > -160 &&
centroid[0] < -67 &&
(Object.keys(offsets).indexOf(name) === -1 ? (
<Marker coordinates={centroid}>
<text y="2" fontSize={14} textAnchor="middle">
{cur ? cur.value : 0}
</text>
</Marker>
) : (
<Annotation
subject={centroid}
dx={offsets[name][0]}
dy={offsets[name][1]}
connectorProps={{}}
>
<text
x={4}
fontSize={14}
alignmentBaseline="middle"
>
{cur ? cur.value : 0}
</text>
</Annotation>
))}
</g>
</React.Fragment>
);
})
}
</Geographies>
</ZoomableGroup>
</ComposableMap>
{/* <ReactTooltip>{tooltipContent}</ReactTooltip> */}
</div>
</div>
</Paper>
);
// Group latest vulns together
const latestVulnsGrouped: {
[key: string]: VulnerabilityCount;
} = {};
if (stats) {
for (const vuln of stats.vulnerabilities.latestVulnerabilities) {
if (vuln.title in latestVulnsGrouped)
latestVulnsGrouped[vuln.title].count++;
else {
latestVulnsGrouped[vuln.title] = { ...vuln, count: 1 };
}
}
}
const latestVulnsGroupedArr = Object.values(latestVulnsGrouped).sort(
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
);
// Create severity object for Open Vulnerability chips
const severities: VulnSeverities[] = [
{ label: 'All', sevList: ['', 'Low', 'Medium', 'High', 'Critical'] },
{ label: 'Critical', sevList: ['Critical'] },
{ label: 'High', sevList: ['High'] },
{ label: 'Medium', sevList: ['Medium'] },
{ label: 'Low', sevList: ['Low'] }
];
if (stats) {
for (const sev of severities) {
if (
stats.domains.numVulnerabilities.some((i) =>
sev.sevList.includes(i.id.split('|')[1])
)
) {
sev.disable = false;
} else {
sev.disable = true;
}
}
}
const delay = (ms: number) => new Promise((res) => setTimeout(res, ms));
const generatePDF = async () => {
setIsLoading(true);
const input = document.getElementById('wrapper')!;
input.style.width = '1400px';
await delay(1);
await html2canvas(input, {
scrollX: 0,
scrollY: 0,
ignoreElements: function (element) {
if ('mapWrapper' === element.id) {
return true;
}
return false;
}
}).then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 190;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
const pdf = new jsPDF('p', 'mm');
pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight);
pdf.save('Crossfeed_Report.pdf');
});
input.style.removeProperty('width');
setIsLoading(false);
};
return (
<div className={classes.root}>
{isLoading && (
<div className="cisa-crossfeed-loading">
<div></div>
<div></div>
</div>
)}
<p>
<USWDSButton
outline
type="button"
onClick={() => {
generatePDF();
}}
>
Generate Report
</USWDSButton>
</p>
<div id="wrapper" className={cardClasses.contentWrapper}>
{stats && (
<div className={cardClasses.content}>
<div className={cardClasses.panel}>
<VulnerabilityCard
title={'Latest Vulnerabilities'}
data={latestVulnsGroupedArr}
showLatest={true}
showCommon={false}
></VulnerabilityCard>
{stats.domains.services.length > 0 && (
<Paper elevation={0} className={cardClasses.cardRoot}>
<div className={cardClasses.cardSmall}>
<div className={cardClasses.header}>
<h2>Most common services</h2>
</div>
<div className={cardClasses.chartSmall}>
<MyResponsivePie
data={stats.domains.services}
colors={allColors}
type={'services'}
/>
</div>
</div>
</Paper>
)}
{stats.domains.ports.length > 0 && (
<Paper elevation={0} classes={{ root: cardClasses.cardRoot }}>
<div className={cardClasses.cardSmall}>
<div className={cardClasses.header}>
<h2>Most common ports</h2>
</div>
<div className={cardClasses.chartSmall}>
<MyResponsiveBar
data={stats.domains.ports.slice(0, 5).reverse()}
type={'ports'}
xLabels={['Port']}
/>
</div>
</div>
</Paper>
)}
{stats.vulnerabilities.severity.length > 0 && (
<Paper elevation={0} classes={{ root: cardClasses.cardRoot }}>
<div className={cardClasses.cardSmall}>
<div className={cardClasses.header}>
<h2>Severity Levels</h2>
</div>
<div className={cardClasses.chartSmall}>
<MyResponsivePie
data={stats.vulnerabilities.severity}
colors={getSeverityColor}
type={'vulns'}
/>
</div>
</div>
</Paper>
)}
</div>
<div className={cardClasses.panel}>
<Paper elevation={0} classes={{ root: cardClasses.cardRoot }}>
<div>
{stats.domains.numVulnerabilities.length > 0 && (
<div className={cardClasses.cardBig}>
<div className={cardClasses.seeAll}>
<h4>
<Link to="/inventory/vulnerabilities">See All</Link>
</h4>
</div>
<div className={cardClasses.header}>
<h2>Open Vulnerabilities by Domain</h2>
</div>
<div className={cardClasses.chartLarge}>
{stats.domains.numVulnerabilities.length === 0 ? (
<h3>No open vulnerabilities</h3>
) : (
<>
<p className={cardClasses.note}>
*Top 50 domains with open vulnerabilities
</p>
<div className={cardClasses.chipWrapper}>
{severities.map(
(sevFilter: VulnSeverities, i: number) => (
<Chip
key={i}
className={cardClasses.chip}
disabled={sevFilter.disable}
label={sevFilter.label}
onClick={() => {
setLabels(sevFilter.sevList);
setCurrent(1);
}}
></Chip>
)
)}
</div>
<div className={cardClasses.chartHeader}>
<h5>Domain  Breakdown</h5>
<h5
style={{ textAlign: 'right', paddingLeft: 0 }}
>
Total
</h5>
</div>
<MyResponsiveBar
data={stats.domains.numVulnerabilities}
xLabels={labels}
type={'vulns'}
longXValues={true}
/>
</>
)}
</div>
<div className={cardClasses.footer}>
<span>
<strong>
{(domainsWithVulns === 0
? 0
: (current - 1) * resultsPerPage + 1
).toLocaleString()}{' '}
-{' '}
{Math.min(
(current - 1) * resultsPerPage + resultsPerPage,
domainsWithVulns
).toLocaleString()}
</strong>{' '}
of{' '}
<strong>{domainsWithVulns.toLocaleString()}</strong>
</span>
<Pagination
count={Math.ceil(domainsWithVulns / resultsPerPage)}
page={current}
onChange={(_, page) => setCurrent(page)}
color="primary"
size="small"
/>
</div>
</div>
)}
</div>
</Paper>
<VulnerabilityCard
title={'Most Common Vulnerabilities'}
data={stats.vulnerabilities.mostCommonVulnerabilities}
showLatest={false}
showCommon={true}
></VulnerabilityCard>
<div id="mapWrapper">
{user?.userType === 'globalView' ||
(user?.userType === 'globalAdmin' && (
<>
<MapCard
title={'State Vulnerabilities'}
geoUrl={geoStateUrl}
findFn={(geo) =>
stats?.vulnerabilities.byOrg.find(
(p) => p.label === geo.properties.name
)
}
type={'state'}
></MapCard>
<MapCard
title={'County Vulnerabilities'}
geoUrl={geoStateUrl}
findFn={(geo) =>
stats?.vulnerabilities.byOrg.find(
(p) => p.label === geo.properties.name + ' Counties'
)
}
type={'county'}
></MapCard>
</>
))}
</div>
</div>
</div>
)}
</div>
</div>
);
};
export default Risk;
const useStyles = makeStyles((theme) => ({
cardRoot: {
boxSizing: 'border-box',
marginBottom: '1rem',
border: '2px solid #DCDEE0',
boxShadow: 'none',
'& em': {
fontStyle: 'normal',
backgroundColor: 'yellow'
}
},
cardSmall: {
width: '100%',
height: '355px',
'& h3': {
textAlign: 'center'
},
overflow: 'hidden'
},
chartSmall: {
height: '85%'
},
chartLarge: {
height: '85.5%',
width: '90%'
},
chartHeader: {
display: 'flex',
justifyContent: 'space-between',
'& h5': {
paddingLeft: 190,
color: '#71767A',
margin: '10px 0 0 0',
fontSize: 14
}
},
cardBig: {
width: '100%',
height: '889px',
'& h3': {
textAlign: 'center'
},
overflow: 'hidden'
},
body: {
padding: '20px 30px'
},
header: {
height: '60px',
backgroundColor: '#F8F9FA',
top: 0,
width: '100%',
color: '#07648D',
fontWeight: 'bold',
paddingLeft: 20,
paddingTop: 1
},
footer: {
height: '60px',
backgroundColor: '#F8F9FA',
width: '100%',
color: '#3D4551',
paddingLeft: 255,
paddingTop: 20,
display: 'flex',
alignItems: 'center',
padding: '1rem 2rem',
'& > span': {
marginRight: '2rem'
},
'& *:focus': {
outline: 'none !important'
}
},
seeAll: {
float: 'right',
marginTop: '5px',
marginRight: '20px',
'& h4 a': {
color: '#71767A',
fontSize: '12px',
fontWeight: '400'
}
},
root: {
position: 'relative',
flex: '1',
width: '100%',
display: 'flex',
flexFlow: 'row nowrap',
alignItems: 'stretch',
margin: '0',
overflowY: 'hidden'
},
contentWrapper: {
position: 'relative',
flex: '1 1 auto',
height: '100%',
display: 'flex',
flexFlow: 'column nowrap',
overflowY: 'hidden',
marginTop: '1rem'
},
content: {
display: 'flex',
flexFlow: 'row nowrap',
alignItems: 'stretch',
flex: '1'
},
panel: {
position: 'relative',
height: '100%',
overflowY: 'auto',
padding: '0 1rem 2rem 1rem',
flex: '0 0 50%'
},
miniCardRoot: {
boxSizing: 'border-box',
marginBottom: '1rem',
'& em': {
fontStyle: 'normal',
backgroundColor: 'yellow'
},
'&:hover': {
background: '#FCFCFC',
boxShadow: '0px 0px 4px rgba(0, 0, 0, 0.15)',
borderRadius: '4px',
cursor: 'pointer'
},
'&:last-child hr': {
display: 'none'
},
height: 45,
width: '100%',
borderRadius: '4px'
},
cardInner: {
paddingLeft: 30,
paddingRight: 30,
display: 'flex',
alignItems: 'center',
'& div': {
display: 'inline',
fontSize: '14px',
fontWeight: 'bold'
},
'& button': {
justifyContent: 'flex-end'
},
height: 45
},
miniCardLeft: {
display: 'flex',
flex: 1,
justifyContent: 'flex-start',
color: '#3D4551'
},
miniCardCenter: {
display: 'flex',
flex: 1,
justifyContent: 'center'
},
button: {
outline: 'none',
border: 'none',
background: 'none',
color: '#07648D',
margin: '0 0.2rem',
cursor: 'pointer',
fontSize: '12px'
},
underlined: {
width: '80px',
fontWeight: 'normal'
},
vulnCount: {
color: '#B51D09',
flex: 0.5
},
chip: {
color: '#3D4551',
height: '26px',
fontSize: '12px',
textAlign: 'center',
background: '#FFFFFF',
border: '1px solid #DCDEE0',
boxSizing: 'border-box',
borderRadius: '22px',
marginRight: '10px',
'&:hover': {
background: '#F8DFE2',
border: '1px solid #D75B57'
},
'&:focus': {
background: '#F8DFE2',
border: '1px solid #D75B57',
outline: 0
},
'&:default': {
background: '#F8DFE2',
border: '1px solid #D75B57',
outline: 0
}
},
chipWrapper: {
display: 'flex',
flexDirection: 'row',
alignItems: 'flex-start',
padding: '5px 10px',
marginTop: '5px',
marginLeft: '15px'
},
note: {
font: '12px',
fontFamily: 'Public Sans',
margin: '10px 10px 10px 25px',
fontStyle: 'italic',
color: '#71767A'
}
})); | the_stack |
import { Category, toolbar, dialogAddons } from './annotations';
import Column, {
widthChanged,
labelChanged,
metaDataChanged,
dirty,
dirtyHeader,
dirtyValues,
rendererTypeChanged,
groupRendererChanged,
summaryRendererChanged,
visibilityChanged,
dirtyCaches,
} from './Column';
import {
defaultGroup,
IDataRow,
IGroup,
ECompareValueType,
IValueColumnDesc,
othersGroup,
ITypeFactory,
} from './interfaces';
import { missingGroup, isMissingValue } from './missing';
import type { dataLoaded } from './ValueColumn';
import ValueColumn from './ValueColumn';
import { equal, IEventListener, ISequence, isSeqEmpty } from '../internal';
import { integrateDefaults } from './internal';
export enum EAlignment {
left = 'left',
center = 'center',
right = 'right',
}
export enum EStringGroupCriteriaType {
value = 'value',
startsWith = 'startsWith',
regex = 'regex',
}
export interface IStringGroupCriteria {
type: EStringGroupCriteriaType;
values: (string | RegExp)[];
}
export interface IStringDesc {
/**
* column alignment: left, center, right
* @default left
*/
alignment?: EAlignment;
/**
* escape html tags
*/
escape?: boolean;
}
export declare type IStringColumnDesc = IStringDesc & IValueColumnDesc<string>;
export interface IStringFilter {
filter: string | RegExp | null;
filterMissing: boolean;
}
/**
* emitted when the filter property changes
* @asMemberOf StringColumn
* @event
*/
export declare function filterChanged_SC(previous: string | RegExp | null, current: string | RegExp | null): void;
/**
* emitted when the grouping property changes
* @asMemberOf StringColumn
* @event
*/
export declare function groupingChanged_SC(previous: (RegExp | string)[][], current: (RegExp | string)[][]): void;
/**
* a string column with optional alignment
*/
@toolbar('rename', 'clone', 'sort', 'sortBy', 'search', 'groupBy', 'sortGroupBy', 'filterString')
@dialogAddons('group', 'groupString')
@Category('string')
export default class StringColumn extends ValueColumn<string> {
static readonly EVENT_FILTER_CHANGED = 'filterChanged';
static readonly EVENT_GROUPING_CHANGED = 'groupingChanged';
//magic key for filtering missing ones
private static readonly FILTER_MISSING = '__FILTER_MISSING';
private currentFilter: IStringFilter | null = null;
readonly alignment: EAlignment;
readonly escape: boolean;
private currentGroupCriteria: IStringGroupCriteria = {
type: EStringGroupCriteriaType.startsWith,
values: [],
};
constructor(id: string, desc: Readonly<IStringColumnDesc>) {
super(
id,
integrateDefaults(desc, {
width: 200,
})
);
this.alignment = desc.alignment ?? EAlignment.left;
this.escape = desc.escape !== false;
}
protected createEventList() {
return super.createEventList().concat([StringColumn.EVENT_GROUPING_CHANGED, StringColumn.EVENT_FILTER_CHANGED]);
}
on(type: typeof StringColumn.EVENT_FILTER_CHANGED, listener: typeof filterChanged_SC | null): this;
on(type: typeof ValueColumn.EVENT_DATA_LOADED, listener: typeof dataLoaded | null): this;
on(type: typeof StringColumn.EVENT_GROUPING_CHANGED, listener: typeof groupingChanged_SC | null): this;
on(type: typeof Column.EVENT_WIDTH_CHANGED, listener: typeof widthChanged | null): this;
on(type: typeof Column.EVENT_LABEL_CHANGED, listener: typeof labelChanged | null): this;
on(type: typeof Column.EVENT_METADATA_CHANGED, listener: typeof metaDataChanged | null): this;
on(type: typeof Column.EVENT_DIRTY, listener: typeof dirty | null): this;
on(type: typeof Column.EVENT_DIRTY_HEADER, listener: typeof dirtyHeader | null): this;
on(type: typeof Column.EVENT_DIRTY_VALUES, listener: typeof dirtyValues | null): this;
on(type: typeof Column.EVENT_DIRTY_CACHES, listener: typeof dirtyCaches | null): this;
on(type: typeof Column.EVENT_RENDERER_TYPE_CHANGED, listener: typeof rendererTypeChanged | null): this;
on(type: typeof Column.EVENT_GROUP_RENDERER_TYPE_CHANGED, listener: typeof groupRendererChanged | null): this;
on(type: typeof Column.EVENT_SUMMARY_RENDERER_TYPE_CHANGED, listener: typeof summaryRendererChanged | null): this;
on(type: typeof Column.EVENT_VISIBILITY_CHANGED, listener: typeof visibilityChanged | null): this;
on(type: string | string[], listener: IEventListener | null): this; // required for correct typings in *.d.ts
on(type: string | string[], listener: IEventListener | null): this {
return super.on(type as any, listener);
}
getValue(row: IDataRow): string | null {
const v: any = super.getValue(row);
return isMissingValue(v) ? null : String(v);
}
getLabel(row: IDataRow) {
return this.getValue(row) || '';
}
dump(toDescRef: (desc: any) => any): any {
const r = super.dump(toDescRef);
if (this.currentFilter instanceof RegExp) {
r.filter = `REGEX:${(this.currentFilter as RegExp).source}`;
} else {
r.filter = this.currentFilter;
}
if (this.currentGroupCriteria) {
const { type, values } = this.currentGroupCriteria;
r.groupCriteria = {
type,
values: values.map((value) =>
value instanceof RegExp && type === EStringGroupCriteriaType.regex ? value.source : value
),
};
}
return r;
}
restore(dump: any, factory: ITypeFactory) {
super.restore(dump, factory);
if (dump.filter) {
const filter = dump.filter;
if (typeof filter === 'string') {
// compatibility case
if (filter.startsWith('REGEX:')) {
this.currentFilter = {
filter: new RegExp(filter.slice(6), 'm'),
filterMissing: false,
};
} else if (filter === StringColumn.FILTER_MISSING) {
this.currentFilter = {
filter: null,
filterMissing: true,
};
} else {
this.currentFilter = {
filter,
filterMissing: false,
};
}
} else {
this.currentFilter = {
filter:
filter.filter && (filter.filter as string).startsWith('REGEX:')
? new RegExp(filter.slice(6), 'm')
: filter.filter || '',
filterMissing: filter.filterMissing === true,
};
}
} else {
this.currentFilter = null;
}
// tslint:disable-next-line: early-exit
if (dump.groupCriteria) {
const { type, values } = dump.groupCriteria as IStringGroupCriteria;
this.currentGroupCriteria = {
type,
values: values.map((value) =>
type === EStringGroupCriteriaType.regex ? new RegExp(value as string, 'm') : value
),
};
}
}
isFiltered() {
return this.currentFilter != null;
}
filter(row: IDataRow) {
if (!this.isFiltered()) {
return true;
}
const r = this.getLabel(row);
const filter = this.currentFilter!;
const ff = filter.filter;
if (r == null || r.trim() === '') {
return !filter.filterMissing;
}
if (!ff) {
return true;
}
if (ff instanceof RegExp) {
return r !== '' && r.match(ff) != null; // You can not use RegExp.test(), because of https://stackoverflow.com/a/6891667
}
return r !== '' && r.toLowerCase().includes(ff.toLowerCase());
}
getFilter() {
return this.currentFilter;
}
setFilter(filter: IStringFilter | null) {
if (filter === this.currentFilter) {
return;
}
const current = this.currentFilter || { filter: null, filterMissing: false };
const target = filter || { filter: null, filterMissing: false };
if (
current.filterMissing === target.filterMissing &&
(current.filter === target.filter ||
(current.filter instanceof RegExp &&
target.filter instanceof RegExp &&
current.filter.source === target.filter.source))
) {
return;
}
this.fire(
[StringColumn.EVENT_FILTER_CHANGED, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY],
this.currentFilter,
(this.currentFilter = filter)
);
}
clearFilter() {
const was = this.isFiltered();
this.setFilter(null);
return was;
}
getGroupCriteria(): IStringGroupCriteria {
return this.currentGroupCriteria;
}
setGroupCriteria(value: IStringGroupCriteria) {
if (equal(this.currentGroupCriteria, value) || value == null) {
return;
}
const bak = this.getGroupCriteria();
this.currentGroupCriteria = value;
this.fire([StringColumn.EVENT_GROUPING_CHANGED, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY], bak, value);
}
group(row: IDataRow): IGroup {
if (this.getValue(row) == null) {
return Object.assign({}, missingGroup);
}
if (!this.currentGroupCriteria) {
return Object.assign({}, othersGroup);
}
const value = this.getLabel(row);
if (!value) {
return Object.assign({}, missingGroup);
}
const { type, values } = this.currentGroupCriteria;
if (type === EStringGroupCriteriaType.value) {
return {
name: value,
color: defaultGroup.color,
};
}
if (type === EStringGroupCriteriaType.startsWith) {
for (const groupValue of values) {
if (typeof groupValue !== 'string' || !value.startsWith(groupValue)) {
continue;
}
return {
name: groupValue,
color: defaultGroup.color,
};
}
return Object.assign({}, othersGroup);
}
for (const groupValue of values) {
if (!(groupValue instanceof RegExp) || !groupValue.test(value)) {
continue;
}
return {
name: groupValue.source,
color: defaultGroup.color,
};
}
return Object.assign({}, othersGroup);
}
toCompareValue(row: IDataRow) {
const v = this.getValue(row);
return v === '' || v == null ? null : v.toLowerCase();
}
toCompareValueType() {
return ECompareValueType.STRING;
}
toCompareGroupValue(rows: ISequence<IDataRow>, _group: IGroup, valueCache?: ISequence<any>) {
if (isSeqEmpty(rows)) {
return null;
}
// take the smallest one
if (valueCache) {
return valueCache.reduce((acc, v) => (acc == null || v < acc ? v : acc), null as null | string);
}
return rows.reduce((acc, d) => {
const v = this.getValue(d);
return acc == null || (v != null && v < acc) ? v : acc;
}, null as null | string);
}
toCompareGroupValueType() {
return ECompareValueType.STRING;
}
} | the_stack |
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { NgbPanelChangeEvent } from '@ng-bootstrap/ng-bootstrap';
import { timer } from 'rxjs';
import { debounce } from 'rxjs/operators';
import * as ynab from 'ynab';
import { YnabApiService } from '../../../ynab-api/ynab-api.service';
import { CalculateInput } from '../../models/calculate-input.model';
import { round } from '../../utilities/number-utility';
import CategoryUtility from './category-utility';
import NoteUtility from './note-utility';
@Component({
selector: 'app-ynab',
templateUrl: 'ynab.component.html',
styleUrls: ['./ynab.component.css']
})
export class YnabComponent implements OnInit {
@Output() calculateInputChange = new EventEmitter<CalculateInput>();
budgetForm: FormGroup;
displayContributionInfo = true;
currencyIsoCode = 'USD';
public safeWithdrawalRatePercentage = 4.00;
public expectedAnnualGrowthRate = 7.00;
public budgets: ynab.BudgetSummary[];
public budget: ynab.BudgetDetail;
public months: ynab.MonthDetail[];
public currentMonth: ynab.MonthDetail;
public selectedMonthA: ynab.MonthDetail;
public selectedMonthB: ynab.MonthDetail;
public categoryGroupsWithCategories: ynab.CategoryGroupWithCategories[];
public ynabNetWorth: number;
public netWorth: number;
public categoriesDisplay: any;
public monthlyExpenses: number;
public leanMonthlyExpenses: number;
public expenses: {
ynab: {
monthly: number,
annual: number
},
fi: {
monthly: number,
annual: number
},
leanFi: {
monthly: number,
annual: number
}
};
public contributionCategories: any;
public isUsingSampleData = false;
public accordionPanelActiveStates: any = {};
constructor(private ynabService: YnabApiService, private formBuilder: FormBuilder, private activatedRoute: ActivatedRoute) {
this.expenses = {
ynab: {
monthly: 0,
annual: 0
},
fi: {
monthly: 0,
annual: 0
},
leanFi: {
monthly: 0,
annual: 0
}
};
this.budgetForm = this.formBuilder.group({
selectedBudget: ['', [Validators.required]],
selectedMonthA: ['', [Validators.required]],
selectedMonthB: ['', [Validators.required]],
monthlyContribution: [0, [Validators.required]],
categoryGroups: this.formBuilder.array([]),
accounts: this.formBuilder.array([]),
safeWithdrawalRatePercentage: [this.safeWithdrawalRatePercentage,
[Validators.required, Validators.max(99.99), Validators.max(0.01)]],
expectedAnnualGrowthRate: [this.expectedAnnualGrowthRate,
[Validators.required, Validators.max(99.99), Validators.max(0.01)]],
});
}
get categoryGroups(): FormArray {
return this.budgetForm.get('categoryGroups') as FormArray;
}
get accounts(): FormArray {
return this.budgetForm.get('accounts') as FormArray;
}
async ngOnInit() {
this.isUsingSampleData = this.ynabService.isUsingSampleData();
const formChanges = this.budgetForm.valueChanges.pipe(debounce(() => timer(500)));
formChanges.subscribe(() => {
this.updateInput();
});
this.budgets = await this.ynabService.getBudgets();
const budgetId = this.setInitialSelectedBudget();
await this.selectBudget(budgetId);
}
async selectBudget(budgetId: string) {
this.calculateInputChange.emit(undefined);
this.budget = await this.ynabService.getBudgetById(budgetId);
window.localStorage.setItem('br4-selected-budget', this.budget.id);
this.months = this.budget.months;
this.currentMonth = await this.ynabService.getMonth(budgetId, 'current');
this.categoryGroupsWithCategories = await this.ynabService.getCategoryGroupsWithCategories(this.budget.id);
this.currencyIsoCode = this.budget.currency_format ? this.budget.currency_format.iso_code : 'USD';
await this.selectMonths(this.currentMonth.month, this.currentMonth.month);
}
async selectMonths(monthA: string, monthB: string) {
const months = this.setMonths(monthA, monthB);
const mappedAccounts = this.mapAccounts(this.budget.accounts);
const mappedCategoryGroups = CategoryUtility.mapCategoryGroups(this.categoryGroupsWithCategories, months);
const monthlyContribution = this.getMonthlyContribution(mappedCategoryGroups);
this.contributionCategories = monthlyContribution.categories;
this.resetForm(mappedCategoryGroups, monthlyContribution.value, mappedAccounts);
this.updateInput();
}
/* Chooses months based on common decisions. Options: All, Last calendar year, Last 12 months, Year to date, Current month. */
async quickChooseMonths(choice: string) {
// Get some etc facts that are shared by some of the buttons below.
const budgetId = window.localStorage.getItem('br4-selected-budget');
const currentMonth = this.currentMonth || await this.ynabService.getMonth(budgetId, 'current');
let currentMonthIdx = 0;
for (let i = 0; i < this.months.length; i++) {
if (currentMonth.month === this.months[i].month) {
currentMonthIdx = i;
}
}
switch (choice) {
case 'all':
await this.selectMonths(this.months[this.months.length - 1].month, this.months[0].month);
break;
case 'yr':
// Go to current month, work backwards to prev Dec, then calc from there.
for (let i = currentMonthIdx + 1; i < this.months.length; i++) { //Note: Adding 1 to current month, in case this is december. We would want last year's december
if (this.months[i].month.endsWith('-12-01')) {
let startMonthIdx = Math.min(i+11, this.months.length-1) //Don't go too far into past
await this.selectMonths(this.months[startMonthIdx].month, this.months[i].month);
break;
}
}
break;
case '12':
let startMonthIdx = Math.min(currentMonthIdx+11, this.months.length-1) //Don't go too far into past
await this.selectMonths(this.months[startMonthIdx].month, currentMonth.month);
break;
case 'ytd':
// Go to current month, work backwards to prev Jan.
for (let i = currentMonthIdx; i < this.months.length; i++) {
if (this.months[i].month.endsWith('-01-01')) {
await this.selectMonths(this.months[i].month, currentMonth.month);
break;
}
}
break;
case 'curr':
default:
await this.selectMonths(currentMonth.month, currentMonth.month);
break;
}
return;
}
updateInput() {
const selectedBudget = this.budgetForm.value.selectedBudget;
if (this.budget.id !== selectedBudget) {
this.selectBudget(selectedBudget);
return;
}
if (this.selectedMonthA.month !== this.budgetForm.value.selectedMonthA ||
this.selectedMonthB.month !== this.budgetForm.value.selectedMonthB) {
this.selectMonths(this.budgetForm.value.selectedMonthA, this.budgetForm.value.selectedMonthB);
return;
}
const fiMonthlyExpenses = this.getMonthlyExpenses(this.budgetForm.value.categoryGroups, 'fiBudget');
const leanMonthlyExpenses = this.getMonthlyExpenses(this.budgetForm.value.categoryGroups, 'leanFiBudget');
const retrievedBudgetedMonthlyExpenses = this.getMonthlyExpenses(this.budgetForm.value.categoryGroups, 'retrievedBudgeted');
this.setNetWorth();
this.expenses = {
ynab: {
monthly: retrievedBudgetedMonthlyExpenses,
annual: retrievedBudgetedMonthlyExpenses * 12
},
fi: {
monthly: fiMonthlyExpenses,
annual: fiMonthlyExpenses * 12
},
leanFi: {
monthly: leanMonthlyExpenses,
annual: leanMonthlyExpenses * 12
}
};
const result = new CalculateInput();
result.annualExpenses = this.expenses.fi.annual;
result.leanAnnualExpenses = this.expenses.leanFi.annual;
result.netWorth = this.netWorth;
result.monthlyContribution = this.budgetForm.value.monthlyContribution;
result.budgetCategoryGroups = this.budgetForm.value.categoryGroups;
result.currencyIsoCode = this.currencyIsoCode;
const safeWithdrawalRatePercentage = Number.parseFloat(this.budgetForm.value.safeWithdrawalRatePercentage);
if (!Number.isNaN(safeWithdrawalRatePercentage)) {
this.safeWithdrawalRatePercentage = safeWithdrawalRatePercentage;
result.annualSafeWithdrawalRate = Math.max(0, safeWithdrawalRatePercentage / 100);
}
const expectedAnnualGrowthRate = Number.parseFloat(this.budgetForm.value.expectedAnnualGrowthRate);
if (!Number.isNaN(expectedAnnualGrowthRate)) {
this.expectedAnnualGrowthRate = expectedAnnualGrowthRate;
result.expectedAnnualGrowthRate = Math.max(0, expectedAnnualGrowthRate / 100);
}
result.roundAll();
this.calculateInputChange.emit(result);
}
beforePanelChange($event: NgbPanelChangeEvent) {
this.accordionPanelActiveStates[$event.panelId] = $event.nextState;
}
private setInitialSelectedBudget(): string {
let selectedBudget = 'last-used';
const storageBudget = window.localStorage.getItem('br4-selected-budget');
if (storageBudget && this.budgets.some(b => b.id === storageBudget)) {
selectedBudget = storageBudget;
}
const queryBudget = this.activatedRoute.snapshot.queryParams['budgetId'];
if (queryBudget && this.budgets.some(b => b.id === queryBudget)) {
selectedBudget = queryBudget;
}
return selectedBudget;
}
private setMonths(monthA: string, monthB: string): ynab.MonthDetail[] {
const result = new Array<ynab.MonthDetail>();
let inRange = false;
for (let i = 0; i < this.months.length; i++) {
const month = this.months[i];
if (month.month === monthA || month.month === monthB) {
if (inRange) {
this.selectedMonthA = month;
result.push(month);
break;
}
this.selectedMonthB = month;
if (monthA === monthB) {
this.selectedMonthA = month;
result.push(month);
break;
}
inRange = true;
}
if (inRange) {
result.push(month);
}
}
return result;
}
private getMonthlyExpenses(categoryGroups, budgetPropertyName) {
const expenses = categoryGroups.map(categoryGroup => {
if (!categoryGroup.categories || !categoryGroup.categories.length) {
return 0;
}
return categoryGroup.categories.map(category => {
return category[budgetPropertyName];
}).reduce((prev, next) => {
return prev + next;
}, 0);
}).reduce((prev, next) => {
return prev + next;
}, 0);
return round(expenses);
}
private setNetWorth() {
let ynabNetWorth = 0;
let netWorth = 0;
this.accounts.controls.forEach(a => {
const ynabBalance = Number.parseFloat(a.value.ynabBalance);
if (!Number.isNaN(ynabBalance)) {
ynabNetWorth += ynabBalance;
}
const balance = Number.parseFloat(a.value.balance);
if (!Number.isNaN(balance)) {
netWorth += balance;
}
});
this.ynabNetWorth = ynabNetWorth;
this.netWorth = netWorth;
}
private mapAccounts(accounts: ynab.Account[]) {
const mapped = accounts.filter(a => !(a.closed || a.deleted))
.map(a => this.formBuilder.group(Object.assign({}, a, {
balance: this.getAccountBalance(a),
ynabBalance: ynab.utils.convertMilliUnitsToCurrencyAmount(a.balance)
})));
return mapped;
}
private getAccountBalance(account: ynab.Account) {
const balance = ynab.utils.convertMilliUnitsToCurrencyAmount(account.balance);
const overrides = NoteUtility.getNoteOverrides(account.note, balance);
if (overrides.contributionBudget !== undefined) {
return overrides.contributionBudget;
}
if (account.type === ynab.Account.TypeEnum.InvestmentAccount || account.type === ynab.Account.TypeEnum.OtherAsset) {
return balance;
}
return 0;
}
private getMonthlyContribution(categoryGroups) {
let contribution = 0;
const categories = [];
if (categoryGroups) {
categoryGroups.forEach(cg => {
cg.categories.forEach(c => {
if (c.contributionBudget) {
contribution += c.contributionBudget;
categories.push({
name: c.name,
value: c.contributionBudget,
info: c.info
});
}
});
});
}
return {
value: round(contribution),
categories
};
}
private resetForm(categoriesDisplay, monthlyContribution, mappedAccounts) {
this.budgetForm.reset({
selectedBudget: this.budget.id,
selectedMonthA: this.selectedMonthA.month,
selectedMonthB: this.selectedMonthB.month,
monthlyContribution,
expectedAnnualGrowthRate: this.expectedAnnualGrowthRate,
safeWithdrawalRatePercentage: this.safeWithdrawalRatePercentage
});
const categoryGroupFormGroups = categoriesDisplay.map(cg => this.formBuilder.group({
name: cg.name,
id: cg.id,
hidden: cg.id,
categories: this.formBuilder.array(cg.categories.map(c => this.formBuilder.group({
name: c.name,
retrievedBudgeted: c.retrievedBudgeted,
computedFiBudget: c.computedFiBudget,
computedLeanFiBudget: c.computedLeanFiBudget,
fiBudget: c.computedFiBudget,
leanFiBudget: c.computedLeanFiBudget,
info: c.info,
ignore: c.ignore
})))
}));
this.budgetForm.setControl('categoryGroups', this.formBuilder.array(categoryGroupFormGroups));
this.budgetForm.setControl('accounts', this.formBuilder.array(mappedAccounts));
}
} | the_stack |
import { Characteristic } from "../Characteristic";
import { Service } from "../Service";
/**
* Service "Access Code"
* @since iOS 15
*/
export class AccessCode extends Service {
public static readonly UUID: string = "00000260-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, AccessCode.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.AccessCodeControlPoint);
this.addCharacteristic(Characteristic.AccessCodeSupportedConfiguration);
this.addCharacteristic(Characteristic.ConfigurationState);
}
}
Service.AccessCode = AccessCode;
/**
* Service "Access Control"
*/
export class AccessControl extends Service {
public static readonly UUID: string = "000000DA-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, AccessControl.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.AccessControlLevel);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.PasswordSetting);
}
}
Service.AccessControl = AccessControl;
/**
* Service "Accessory Information"
*/
export class AccessoryInformation extends Service {
public static readonly UUID: string = "0000003E-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, AccessoryInformation.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Identify);
this.addCharacteristic(Characteristic.Manufacturer);
this.addCharacteristic(Characteristic.Model);
if (!this.testCharacteristic(Characteristic.Name)) { // workaround for Name characteristic collision in constructor
this.addCharacteristic(Characteristic.Name).updateValue("Unnamed Service");
}
this.addCharacteristic(Characteristic.SerialNumber);
this.addCharacteristic(Characteristic.FirmwareRevision);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.AccessoryFlags);
this.addOptionalCharacteristic(Characteristic.AppMatchingIdentifier);
this.addOptionalCharacteristic(Characteristic.ConfiguredName);
this.addOptionalCharacteristic(Characteristic.HardwareFinish);
this.addOptionalCharacteristic(Characteristic.HardwareRevision);
this.addOptionalCharacteristic(Characteristic.ProductData);
this.addOptionalCharacteristic(Characteristic.SoftwareRevision);
}
}
Service.AccessoryInformation = AccessoryInformation;
/**
* Service "Accessory Metrics"
*/
export class AccessoryMetrics extends Service {
public static readonly UUID: string = "00000270-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, AccessoryMetrics.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
}
}
Service.AccessoryMetrics = AccessoryMetrics;
/**
* Service "Accessory Runtime Information"
*/
export class AccessoryRuntimeInformation extends Service {
public static readonly UUID: string = "00000239-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, AccessoryRuntimeInformation.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Ping);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.ActivityInterval);
this.addOptionalCharacteristic(Characteristic.HeartBeat);
this.addOptionalCharacteristic(Characteristic.SleepInterval);
}
}
Service.AccessoryRuntimeInformation = AccessoryRuntimeInformation;
/**
* Service "Air Purifier"
*/
export class AirPurifier extends Service {
public static readonly UUID: string = "000000BB-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, AirPurifier.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
this.addCharacteristic(Characteristic.CurrentAirPurifierState);
this.addCharacteristic(Characteristic.TargetAirPurifierState);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.LockPhysicalControls);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.RotationSpeed);
this.addOptionalCharacteristic(Characteristic.SwingMode);
}
}
Service.AirPurifier = AirPurifier;
/**
* Service "Air Quality Sensor"
*/
export class AirQualitySensor extends Service {
public static readonly UUID: string = "0000008D-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, AirQualitySensor.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.AirQuality);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.NitrogenDioxideDensity);
this.addOptionalCharacteristic(Characteristic.OzoneDensity);
this.addOptionalCharacteristic(Characteristic.PM10Density);
this.addOptionalCharacteristic(Characteristic.PM2_5Density);
this.addOptionalCharacteristic(Characteristic.SulphurDioxideDensity);
this.addOptionalCharacteristic(Characteristic.VOCDensity);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusActive);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusLowBattery);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.AirQualitySensor = AirQualitySensor;
/**
* Service "Asset Update"
*/
export class AssetUpdate extends Service {
public static readonly UUID: string = "00000267-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, AssetUpdate.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.AssetUpdateReadiness);
this.addCharacteristic(Characteristic.SupportedAssetTypes);
}
}
Service.AssetUpdate = AssetUpdate;
/**
* Service "Assistant"
*/
export class Assistant extends Service {
public static readonly UUID: string = "0000026A-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Assistant.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
this.addCharacteristic(Characteristic.Identifier);
if (!this.testCharacteristic(Characteristic.Name)) { // workaround for Name characteristic collision in constructor
this.addCharacteristic(Characteristic.Name).updateValue("Unnamed Service");
}
}
}
Service.Assistant = Assistant;
/**
* Service "Audio Stream Management"
*/
export class AudioStreamManagement extends Service {
public static readonly UUID: string = "00000127-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, AudioStreamManagement.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.SupportedAudioStreamConfiguration);
this.addCharacteristic(Characteristic.SelectedAudioStreamConfiguration);
}
}
Service.AudioStreamManagement = AudioStreamManagement;
/**
* Service "Battery"
*/
export class Battery extends Service {
public static readonly UUID: string = "00000096-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Battery.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.StatusLowBattery);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.BatteryLevel);
this.addOptionalCharacteristic(Characteristic.ChargingState);
this.addOptionalCharacteristic(Characteristic.Name);
}
}
// noinspection JSDeprecatedSymbols
Service.BatteryService = Battery;
Service.Battery = Battery;
/**
* Service "Bridge Configuration"
* @deprecated Removed and not used anymore
*/
export class BridgeConfiguration extends Service {
public static readonly UUID: string = "000000A1-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, BridgeConfiguration.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.ConfigureBridgedAccessoryStatus);
this.addCharacteristic(Characteristic.DiscoverBridgedAccessories);
this.addCharacteristic(Characteristic.DiscoveredBridgedAccessories);
this.addCharacteristic(Characteristic.ConfigureBridgedAccessory);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
}
}
// noinspection JSDeprecatedSymbols
Service.BridgeConfiguration = BridgeConfiguration;
/**
* Service "Bridging State"
* @deprecated Removed and not used anymore
*/
export class BridgingState extends Service {
public static readonly UUID: string = "00000062-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, BridgingState.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Reachable);
this.addCharacteristic(Characteristic.LinkQuality);
this.addCharacteristic(Characteristic.AccessoryIdentifier);
this.addCharacteristic(Characteristic.Category);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
}
}
// noinspection JSDeprecatedSymbols
Service.BridgingState = BridgingState;
/**
* Service "Camera Control"
* @deprecated This service has no usage anymore and will be ignored by iOS
*/
export class CameraControl extends Service {
public static readonly UUID: string = "00000111-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, CameraControl.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.On);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.CurrentHorizontalTiltAngle);
this.addOptionalCharacteristic(Characteristic.CurrentVerticalTiltAngle);
this.addOptionalCharacteristic(Characteristic.TargetHorizontalTiltAngle);
this.addOptionalCharacteristic(Characteristic.TargetVerticalTiltAngle);
this.addOptionalCharacteristic(Characteristic.NightVision);
this.addOptionalCharacteristic(Characteristic.OpticalZoom);
this.addOptionalCharacteristic(Characteristic.DigitalZoom);
this.addOptionalCharacteristic(Characteristic.ImageRotation);
this.addOptionalCharacteristic(Characteristic.ImageMirroring);
this.addOptionalCharacteristic(Characteristic.Name);
}
}
// noinspection JSDeprecatedSymbols
Service.CameraControl = CameraControl;
/**
* Service "Camera Operating Mode"
*/
export class CameraOperatingMode extends Service {
public static readonly UUID: string = "0000021A-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, CameraOperatingMode.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.EventSnapshotsActive);
this.addCharacteristic(Characteristic.HomeKitCameraActive);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.CameraOperatingModeIndicator);
this.addOptionalCharacteristic(Characteristic.ManuallyDisabled);
this.addOptionalCharacteristic(Characteristic.NightVision);
this.addOptionalCharacteristic(Characteristic.PeriodicSnapshotsActive);
this.addOptionalCharacteristic(Characteristic.ThirdPartyCameraActive);
this.addOptionalCharacteristic(Characteristic.DiagonalFieldOfView);
}
}
Service.CameraOperatingMode = CameraOperatingMode;
/**
* Service "Camera Recording Management"
*/
export class CameraRecordingManagement extends Service {
public static readonly UUID: string = "00000204-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, CameraRecordingManagement.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
this.addCharacteristic(Characteristic.SupportedCameraRecordingConfiguration);
this.addCharacteristic(Characteristic.SupportedVideoRecordingConfiguration);
this.addCharacteristic(Characteristic.SupportedAudioRecordingConfiguration);
this.addCharacteristic(Characteristic.SelectedCameraRecordingConfiguration);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.RecordingAudioActive);
}
}
// noinspection JSDeprecatedSymbols
Service.CameraEventRecordingManagement = CameraRecordingManagement;
Service.CameraRecordingManagement = CameraRecordingManagement;
/**
* Service "Camera RTP Stream Management"
*/
export class CameraRTPStreamManagement extends Service {
public static readonly UUID: string = "00000110-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, CameraRTPStreamManagement.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.SelectedRTPStreamConfiguration);
this.addCharacteristic(Characteristic.SetupEndpoints);
this.addCharacteristic(Characteristic.StreamingStatus);
this.addCharacteristic(Characteristic.SupportedAudioStreamConfiguration);
this.addCharacteristic(Characteristic.SupportedRTPConfiguration);
this.addCharacteristic(Characteristic.SupportedVideoStreamConfiguration);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Active);
}
}
Service.CameraRTPStreamManagement = CameraRTPStreamManagement;
/**
* Service "Carbon Dioxide Sensor"
*/
export class CarbonDioxideSensor extends Service {
public static readonly UUID: string = "00000097-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, CarbonDioxideSensor.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CarbonDioxideDetected);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.CarbonDioxideLevel);
this.addOptionalCharacteristic(Characteristic.CarbonDioxidePeakLevel);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusActive);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusLowBattery);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.CarbonDioxideSensor = CarbonDioxideSensor;
/**
* Service "Carbon Monoxide Sensor"
*/
export class CarbonMonoxideSensor extends Service {
public static readonly UUID: string = "0000007F-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, CarbonMonoxideSensor.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CarbonMonoxideDetected);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.CarbonMonoxideLevel);
this.addOptionalCharacteristic(Characteristic.CarbonMonoxidePeakLevel);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusActive);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusLowBattery);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.CarbonMonoxideSensor = CarbonMonoxideSensor;
/**
* Service "Cloud Relay"
*/
export class CloudRelay extends Service {
public static readonly UUID: string = "0000005A-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, CloudRelay.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.RelayControlPoint);
this.addCharacteristic(Characteristic.RelayState);
this.addCharacteristic(Characteristic.RelayEnabled);
}
}
// noinspection JSDeprecatedSymbols
Service.Relay = CloudRelay;
Service.CloudRelay = CloudRelay;
/**
* Service "Contact Sensor"
*/
export class ContactSensor extends Service {
public static readonly UUID: string = "00000080-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, ContactSensor.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.ContactSensorState);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusActive);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusLowBattery);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.ContactSensor = ContactSensor;
/**
* Service "Data Stream Transport Management"
*/
export class DataStreamTransportManagement extends Service {
public static readonly UUID: string = "00000129-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, DataStreamTransportManagement.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.SetupDataStreamTransport);
this.addCharacteristic(Characteristic.SupportedDataStreamTransportConfiguration);
this.addCharacteristic(Characteristic.Version);
}
}
Service.DataStreamTransportManagement = DataStreamTransportManagement;
/**
* Service "Diagnostics"
*/
export class Diagnostics extends Service {
public static readonly UUID: string = "00000237-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Diagnostics.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.SupportedDiagnosticsSnapshot);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.SelectedDiagnosticsModes);
this.addOptionalCharacteristic(Characteristic.SupportedDiagnosticsModes);
}
}
Service.Diagnostics = Diagnostics;
/**
* Service "Door"
*/
export class Door extends Service {
public static readonly UUID: string = "00000081-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Door.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentPosition);
this.addCharacteristic(Characteristic.PositionState);
this.addCharacteristic(Characteristic.TargetPosition);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.ObstructionDetected);
this.addOptionalCharacteristic(Characteristic.HoldPosition);
}
}
Service.Door = Door;
/**
* Service "Doorbell"
*/
export class Doorbell extends Service {
public static readonly UUID: string = "00000121-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Doorbell.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.ProgrammableSwitchEvent);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Brightness);
this.addOptionalCharacteristic(Characteristic.Mute);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.OperatingStateResponse);
this.addOptionalCharacteristic(Characteristic.Volume);
}
}
Service.Doorbell = Doorbell;
/**
* Service "Fan"
*/
export class Fan extends Service {
public static readonly UUID: string = "00000040-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Fan.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.On);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.RotationDirection);
this.addOptionalCharacteristic(Characteristic.RotationSpeed);
}
}
Service.Fan = Fan;
/**
* Service "Fanv2"
*/
export class Fanv2 extends Service {
public static readonly UUID: string = "000000B7-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Fanv2.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.CurrentFanState);
this.addOptionalCharacteristic(Characteristic.TargetFanState);
this.addOptionalCharacteristic(Characteristic.LockPhysicalControls);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.RotationDirection);
this.addOptionalCharacteristic(Characteristic.RotationSpeed);
this.addOptionalCharacteristic(Characteristic.SwingMode);
}
}
Service.Fanv2 = Fanv2;
/**
* Service "Faucet"
*/
export class Faucet extends Service {
public static readonly UUID: string = "000000D7-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Faucet.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusFault);
}
}
Service.Faucet = Faucet;
/**
* Service "Filter Maintenance"
*/
export class FilterMaintenance extends Service {
public static readonly UUID: string = "000000BA-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, FilterMaintenance.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.FilterChangeIndication);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.FilterLifeLevel);
this.addOptionalCharacteristic(Characteristic.ResetFilterIndication);
this.addOptionalCharacteristic(Characteristic.Name);
}
}
Service.FilterMaintenance = FilterMaintenance;
/**
* Service "Garage Door Opener"
*/
export class GarageDoorOpener extends Service {
public static readonly UUID: string = "00000041-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, GarageDoorOpener.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentDoorState);
this.addCharacteristic(Characteristic.TargetDoorState);
this.addCharacteristic(Characteristic.ObstructionDetected);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.LockCurrentState);
this.addOptionalCharacteristic(Characteristic.LockTargetState);
this.addOptionalCharacteristic(Characteristic.Name);
}
}
Service.GarageDoorOpener = GarageDoorOpener;
/**
* Service "Heater-Cooler"
*/
export class HeaterCooler extends Service {
public static readonly UUID: string = "000000BC-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, HeaterCooler.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
this.addCharacteristic(Characteristic.CurrentHeaterCoolerState);
this.addCharacteristic(Characteristic.TargetHeaterCoolerState);
this.addCharacteristic(Characteristic.CurrentTemperature);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.LockPhysicalControls);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.RotationSpeed);
this.addOptionalCharacteristic(Characteristic.SwingMode);
this.addOptionalCharacteristic(Characteristic.CoolingThresholdTemperature);
this.addOptionalCharacteristic(Characteristic.HeatingThresholdTemperature);
this.addOptionalCharacteristic(Characteristic.TemperatureDisplayUnits);
}
}
Service.HeaterCooler = HeaterCooler;
/**
* Service "Humidifier-Dehumidifier"
*/
export class HumidifierDehumidifier extends Service {
public static readonly UUID: string = "000000BD-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, HumidifierDehumidifier.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
this.addCharacteristic(Characteristic.CurrentHumidifierDehumidifierState);
this.addCharacteristic(Characteristic.TargetHumidifierDehumidifierState);
this.addCharacteristic(Characteristic.CurrentRelativeHumidity);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.LockPhysicalControls);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.RelativeHumidityDehumidifierThreshold);
this.addOptionalCharacteristic(Characteristic.RelativeHumidityHumidifierThreshold);
this.addOptionalCharacteristic(Characteristic.RotationSpeed);
this.addOptionalCharacteristic(Characteristic.SwingMode);
this.addOptionalCharacteristic(Characteristic.WaterLevel);
}
}
Service.HumidifierDehumidifier = HumidifierDehumidifier;
/**
* Service "Humidity Sensor"
*/
export class HumiditySensor extends Service {
public static readonly UUID: string = "00000082-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, HumiditySensor.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentRelativeHumidity);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusActive);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusLowBattery);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.HumiditySensor = HumiditySensor;
/**
* Service "Input Source"
*/
export class InputSource extends Service {
public static readonly UUID: string = "000000D9-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, InputSource.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.ConfiguredName);
this.addCharacteristic(Characteristic.InputSourceType);
this.addCharacteristic(Characteristic.IsConfigured);
if (!this.testCharacteristic(Characteristic.Name)) { // workaround for Name characteristic collision in constructor
this.addCharacteristic(Characteristic.Name).updateValue("Unnamed Service");
}
this.addCharacteristic(Characteristic.CurrentVisibilityState);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Identifier);
this.addOptionalCharacteristic(Characteristic.InputDeviceType);
this.addOptionalCharacteristic(Characteristic.TargetVisibilityState);
}
}
Service.InputSource = InputSource;
/**
* Service "Irrigation-System"
*/
export class IrrigationSystem extends Service {
public static readonly UUID: string = "000000CF-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, IrrigationSystem.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
this.addCharacteristic(Characteristic.ProgramMode);
this.addCharacteristic(Characteristic.InUse);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.RemainingDuration);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusFault);
}
}
Service.IrrigationSystem = IrrigationSystem;
/**
* Service "Leak Sensor"
*/
export class LeakSensor extends Service {
public static readonly UUID: string = "00000083-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, LeakSensor.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.LeakDetected);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusActive);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusLowBattery);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.LeakSensor = LeakSensor;
/**
* Service "Lightbulb"
*/
export class Lightbulb extends Service {
public static readonly UUID: string = "00000043-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Lightbulb.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.On);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Brightness);
this.addOptionalCharacteristic(Characteristic.CharacteristicValueActiveTransitionCount);
this.addOptionalCharacteristic(Characteristic.CharacteristicValueTransitionControl);
this.addOptionalCharacteristic(Characteristic.ColorTemperature);
this.addOptionalCharacteristic(Characteristic.Hue);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.Saturation);
this.addOptionalCharacteristic(Characteristic.SupportedCharacteristicValueTransitionConfiguration);
}
}
Service.Lightbulb = Lightbulb;
/**
* Service "Light Sensor"
*/
export class LightSensor extends Service {
public static readonly UUID: string = "00000084-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, LightSensor.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentAmbientLightLevel);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusActive);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusLowBattery);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.LightSensor = LightSensor;
/**
* Service "Lock Management"
*/
export class LockManagement extends Service {
public static readonly UUID: string = "00000044-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, LockManagement.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.LockControlPoint);
this.addCharacteristic(Characteristic.Version);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.AdministratorOnlyAccess);
this.addOptionalCharacteristic(Characteristic.AudioFeedback);
this.addOptionalCharacteristic(Characteristic.CurrentDoorState);
this.addOptionalCharacteristic(Characteristic.LockManagementAutoSecurityTimeout);
this.addOptionalCharacteristic(Characteristic.LockLastKnownAction);
this.addOptionalCharacteristic(Characteristic.Logs);
this.addOptionalCharacteristic(Characteristic.MotionDetected);
}
}
Service.LockManagement = LockManagement;
/**
* Service "Lock Mechanism"
*/
export class LockMechanism extends Service {
public static readonly UUID: string = "00000045-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, LockMechanism.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.LockCurrentState);
this.addCharacteristic(Characteristic.LockTargetState);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
}
}
Service.LockMechanism = LockMechanism;
/**
* Service "Microphone"
*/
export class Microphone extends Service {
public static readonly UUID: string = "00000112-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Microphone.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Mute);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Volume);
}
}
Service.Microphone = Microphone;
/**
* Service "Motion Sensor"
*/
export class MotionSensor extends Service {
public static readonly UUID: string = "00000085-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, MotionSensor.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.MotionDetected);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusActive);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusLowBattery);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.MotionSensor = MotionSensor;
/**
* Service "NFC Access"
* @since iOS 15
*/
export class NFCAccess extends Service {
public static readonly UUID: string = "00000266-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, NFCAccess.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.ConfigurationState);
this.addCharacteristic(Characteristic.NFCAccessControlPoint);
this.addCharacteristic(Characteristic.NFCAccessSupportedConfiguration);
}
}
Service.NFCAccess = NFCAccess;
/**
* Service "Occupancy Sensor"
*/
export class OccupancySensor extends Service {
public static readonly UUID: string = "00000086-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, OccupancySensor.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.OccupancyDetected);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusActive);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusLowBattery);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.OccupancySensor = OccupancySensor;
/**
* Service "Outlet"
* @since iOS 13
*/
export class Outlet extends Service {
public static readonly UUID: string = "00000047-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Outlet.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.On);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.OutletInUse);
}
}
Service.Outlet = Outlet;
/**
* Service "Pairing"
*/
export class Pairing extends Service {
public static readonly UUID: string = "00000055-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Pairing.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.ListPairings);
this.addCharacteristic(Characteristic.PairSetup);
this.addCharacteristic(Characteristic.PairVerify);
this.addCharacteristic(Characteristic.PairingFeatures);
}
}
Service.Pairing = Pairing;
/**
* Service "Power Management"
*/
export class PowerManagement extends Service {
public static readonly UUID: string = "00000221-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, PowerManagement.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.WakeConfiguration);
}
}
Service.PowerManagement = PowerManagement;
/**
* Service "Protocol Information"
*/
export class ProtocolInformation extends Service {
public static readonly UUID: string = "000000A2-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, ProtocolInformation.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Version);
}
}
Service.ProtocolInformation = ProtocolInformation;
/**
* Service "Security System"
*/
export class SecuritySystem extends Service {
public static readonly UUID: string = "0000007E-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, SecuritySystem.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.SecuritySystemCurrentState);
this.addCharacteristic(Characteristic.SecuritySystemTargetState);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.SecuritySystemAlarmType);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.SecuritySystem = SecuritySystem;
/**
* Service "Service Label"
*/
export class ServiceLabel extends Service {
public static readonly UUID: string = "000000CC-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, ServiceLabel.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.ServiceLabelNamespace);
}
}
Service.ServiceLabel = ServiceLabel;
/**
* Service "Siri"
*/
export class Siri extends Service {
public static readonly UUID: string = "00000133-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Siri.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.SiriInputType);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.MultifunctionButton);
this.addOptionalCharacteristic(Characteristic.SiriEnable);
this.addOptionalCharacteristic(Characteristic.SiriEngineVersion);
this.addOptionalCharacteristic(Characteristic.SiriLightOnUse);
this.addOptionalCharacteristic(Characteristic.SiriListening);
this.addOptionalCharacteristic(Characteristic.SiriTouchToUse);
}
}
Service.Siri = Siri;
/**
* Service "Siri Endpoint"
*/
export class SiriEndpoint extends Service {
public static readonly UUID: string = "00000253-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, SiriEndpoint.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.SiriEndpointSessionStatus);
this.addCharacteristic(Characteristic.Version);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.ActiveIdentifier);
this.addOptionalCharacteristic(Characteristic.ManuallyDisabled);
}
}
Service.SiriEndpoint = SiriEndpoint;
/**
* Service "Slats"
*/
export class Slats extends Service {
public static readonly UUID: string = "000000B9-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Slats.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentSlatState);
this.addCharacteristic(Characteristic.SlatType);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.SwingMode);
this.addOptionalCharacteristic(Characteristic.CurrentTiltAngle);
this.addOptionalCharacteristic(Characteristic.TargetTiltAngle);
}
}
// noinspection JSDeprecatedSymbols
Service.Slat = Slats;
Service.Slats = Slats;
/**
* Service "Smart Speaker"
*/
export class SmartSpeaker extends Service {
public static readonly UUID: string = "00000228-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, SmartSpeaker.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentMediaState);
this.addCharacteristic(Characteristic.TargetMediaState);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.AirPlayEnable);
this.addOptionalCharacteristic(Characteristic.ConfiguredName);
this.addOptionalCharacteristic(Characteristic.Mute);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.Volume);
}
}
Service.SmartSpeaker = SmartSpeaker;
/**
* Service "Smoke Sensor"
*/
export class SmokeSensor extends Service {
public static readonly UUID: string = "00000087-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, SmokeSensor.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.SmokeDetected);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusActive);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusLowBattery);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.SmokeSensor = SmokeSensor;
/**
* Service "Speaker"
* @since iOS 10
*/
export class Speaker extends Service {
public static readonly UUID: string = "00000113-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Speaker.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Mute);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Active);
this.addOptionalCharacteristic(Characteristic.Volume);
}
}
Service.Speaker = Speaker;
/**
* Service "Stateful Programmable Switch"
*/
export class StatefulProgrammableSwitch extends Service {
public static readonly UUID: string = "00000088-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, StatefulProgrammableSwitch.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.ProgrammableSwitchEvent);
this.addCharacteristic(Characteristic.ProgrammableSwitchOutputState);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
}
}
Service.StatefulProgrammableSwitch = StatefulProgrammableSwitch;
/**
* Service "Stateless Programmable Switch"
*/
export class StatelessProgrammableSwitch extends Service {
public static readonly UUID: string = "00000089-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, StatelessProgrammableSwitch.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.ProgrammableSwitchEvent);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.ServiceLabelIndex);
}
}
Service.StatelessProgrammableSwitch = StatelessProgrammableSwitch;
/**
* Service "Switch"
*/
export class Switch extends Service {
public static readonly UUID: string = "00000049-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Switch.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.On);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
}
}
Service.Switch = Switch;
/**
* Service "Target Control"
*/
export class TargetControl extends Service {
public static readonly UUID: string = "00000125-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, TargetControl.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
this.addCharacteristic(Characteristic.ActiveIdentifier);
this.addCharacteristic(Characteristic.ButtonEvent);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
}
}
Service.TargetControl = TargetControl;
/**
* Service "Target Control Management"
*/
export class TargetControlManagement extends Service {
public static readonly UUID: string = "00000122-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, TargetControlManagement.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.TargetControlSupportedConfiguration);
this.addCharacteristic(Characteristic.TargetControlList);
}
}
Service.TargetControlManagement = TargetControlManagement;
/**
* Service "Television"
*/
export class Television extends Service {
public static readonly UUID: string = "000000D8-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Television.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
this.addCharacteristic(Characteristic.ActiveIdentifier);
this.addCharacteristic(Characteristic.ConfiguredName);
this.addCharacteristic(Characteristic.RemoteKey);
this.addCharacteristic(Characteristic.SleepDiscoveryMode);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Brightness);
this.addOptionalCharacteristic(Characteristic.ClosedCaptions);
this.addOptionalCharacteristic(Characteristic.DisplayOrder);
this.addOptionalCharacteristic(Characteristic.CurrentMediaState);
this.addOptionalCharacteristic(Characteristic.TargetMediaState);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.PictureMode);
this.addOptionalCharacteristic(Characteristic.PowerModeSelection);
}
}
Service.Television = Television;
/**
* Service "Television Speaker"
*/
export class TelevisionSpeaker extends Service {
public static readonly UUID: string = "00000113-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, TelevisionSpeaker.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Mute);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Active);
this.addOptionalCharacteristic(Characteristic.Volume);
this.addOptionalCharacteristic(Characteristic.VolumeControlType);
this.addOptionalCharacteristic(Characteristic.VolumeSelector);
}
}
Service.TelevisionSpeaker = TelevisionSpeaker;
/**
* Service "Temperature Sensor"
*/
export class TemperatureSensor extends Service {
public static readonly UUID: string = "0000008A-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, TemperatureSensor.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentTemperature);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.StatusActive);
this.addOptionalCharacteristic(Characteristic.StatusFault);
this.addOptionalCharacteristic(Characteristic.StatusLowBattery);
this.addOptionalCharacteristic(Characteristic.StatusTampered);
}
}
Service.TemperatureSensor = TemperatureSensor;
/**
* Service "Thermostat"
*/
export class Thermostat extends Service {
public static readonly UUID: string = "0000004A-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Thermostat.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentHeatingCoolingState);
this.addCharacteristic(Characteristic.TargetHeatingCoolingState);
this.addCharacteristic(Characteristic.CurrentTemperature);
this.addCharacteristic(Characteristic.TargetTemperature);
this.addCharacteristic(Characteristic.TemperatureDisplayUnits);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.CurrentRelativeHumidity);
this.addOptionalCharacteristic(Characteristic.TargetRelativeHumidity);
this.addOptionalCharacteristic(Characteristic.CoolingThresholdTemperature);
this.addOptionalCharacteristic(Characteristic.HeatingThresholdTemperature);
}
}
Service.Thermostat = Thermostat;
/**
* Service "Thread Transport"
*/
export class ThreadTransport extends Service {
public static readonly UUID: string = "00000701-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, ThreadTransport.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentTransport);
this.addCharacteristic(Characteristic.ThreadControlPoint);
this.addCharacteristic(Characteristic.ThreadNodeCapabilities);
this.addCharacteristic(Characteristic.ThreadStatus);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.CCAEnergyDetectThreshold);
this.addOptionalCharacteristic(Characteristic.CCASignalDetectThreshold);
this.addOptionalCharacteristic(Characteristic.EventRetransmissionMaximum);
this.addOptionalCharacteristic(Characteristic.EventTransmissionCounters);
this.addOptionalCharacteristic(Characteristic.MACRetransmissionMaximum);
this.addOptionalCharacteristic(Characteristic.MACTransmissionCounters);
this.addOptionalCharacteristic(Characteristic.ReceiverSensitivity);
this.addOptionalCharacteristic(Characteristic.ReceivedSignalStrengthIndication);
this.addOptionalCharacteristic(Characteristic.SignalToNoiseRatio);
this.addOptionalCharacteristic(Characteristic.ThreadOpenThreadVersion);
this.addOptionalCharacteristic(Characteristic.TransmitPower);
this.addOptionalCharacteristic(Characteristic.MaximumTransmitPower);
}
}
Service.ThreadTransport = ThreadTransport;
/**
* Service "Time Information"
* @deprecated Removed and not used anymore
*/
export class TimeInformation extends Service {
public static readonly UUID: string = "00000099-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, TimeInformation.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentTime);
this.addCharacteristic(Characteristic.DayoftheWeek);
this.addCharacteristic(Characteristic.TimeUpdate);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
}
}
// noinspection JSDeprecatedSymbols
Service.TimeInformation = TimeInformation;
/**
* Service "Transfer Transport Management"
*/
export class TransferTransportManagement extends Service {
public static readonly UUID: string = "00000203-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, TransferTransportManagement.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.SupportedTransferTransportConfiguration);
this.addCharacteristic(Characteristic.SetupTransferTransport);
}
}
Service.TransferTransportManagement = TransferTransportManagement;
/**
* Service "Tunnel"
*/
export class Tunnel extends Service {
public static readonly UUID: string = "00000056-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Tunnel.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.AccessoryIdentifier);
this.addCharacteristic(Characteristic.TunnelConnectionTimeout);
this.addCharacteristic(Characteristic.TunneledAccessoryAdvertising);
this.addCharacteristic(Characteristic.TunneledAccessoryConnected);
this.addCharacteristic(Characteristic.TunneledAccessoryStateNumber);
}
}
// noinspection JSDeprecatedSymbols
Service.TunneledBTLEAccessoryService = Tunnel;
Service.Tunnel = Tunnel;
/**
* Service "Valve"
*/
export class Valve extends Service {
public static readonly UUID: string = "000000D0-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Valve.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.Active);
this.addCharacteristic(Characteristic.InUse);
this.addCharacteristic(Characteristic.ValveType);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.IsConfigured);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.RemainingDuration);
this.addOptionalCharacteristic(Characteristic.ServiceLabelIndex);
this.addOptionalCharacteristic(Characteristic.SetDuration);
this.addOptionalCharacteristic(Characteristic.StatusFault);
}
}
Service.Valve = Valve;
/**
* Service "Wi-Fi Router"
*/
export class WiFiRouter extends Service {
public static readonly UUID: string = "0000020A-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, WiFiRouter.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.ConfiguredName);
this.addCharacteristic(Characteristic.ManagedNetworkEnable);
this.addCharacteristic(Characteristic.NetworkAccessViolationControl);
this.addCharacteristic(Characteristic.NetworkClientProfileControl);
this.addCharacteristic(Characteristic.NetworkClientStatusControl);
this.addCharacteristic(Characteristic.RouterStatus);
this.addCharacteristic(Characteristic.SupportedRouterConfiguration);
this.addCharacteristic(Characteristic.WANConfigurationList);
this.addCharacteristic(Characteristic.WANStatusList);
}
}
Service.WiFiRouter = WiFiRouter;
/**
* Service "Wi-Fi Satellite"
*/
export class WiFiSatellite extends Service {
public static readonly UUID: string = "0000020F-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, WiFiSatellite.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.WiFiSatelliteStatus);
}
}
Service.WiFiSatellite = WiFiSatellite;
/**
* Service "Wi-Fi Transport"
*/
export class WiFiTransport extends Service {
public static readonly UUID: string = "0000022A-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, WiFiTransport.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentTransport);
this.addCharacteristic(Characteristic.WiFiCapabilities);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.WiFiConfigurationControl);
}
}
Service.WiFiTransport = WiFiTransport;
/**
* Service "Window"
*/
export class Window extends Service {
public static readonly UUID: string = "0000008B-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, Window.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentPosition);
this.addCharacteristic(Characteristic.PositionState);
this.addCharacteristic(Characteristic.TargetPosition);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.ObstructionDetected);
this.addOptionalCharacteristic(Characteristic.HoldPosition);
}
}
Service.Window = Window;
/**
* Service "Window Covering"
*/
export class WindowCovering extends Service {
public static readonly UUID: string = "0000008C-0000-1000-8000-0026BB765291";
constructor(displayName?: string, subtype?: string) {
super(displayName, WindowCovering.UUID, subtype);
// Required Characteristics
this.addCharacteristic(Characteristic.CurrentPosition);
this.addCharacteristic(Characteristic.PositionState);
this.addCharacteristic(Characteristic.TargetPosition);
// Optional Characteristics
this.addOptionalCharacteristic(Characteristic.CurrentHorizontalTiltAngle);
this.addOptionalCharacteristic(Characteristic.TargetHorizontalTiltAngle);
this.addOptionalCharacteristic(Characteristic.Name);
this.addOptionalCharacteristic(Characteristic.ObstructionDetected);
this.addOptionalCharacteristic(Characteristic.HoldPosition);
this.addOptionalCharacteristic(Characteristic.CurrentVerticalTiltAngle);
this.addOptionalCharacteristic(Characteristic.TargetVerticalTiltAngle);
}
}
Service.WindowCovering = WindowCovering; | the_stack |
import * as fs from "fs-extra";
import * as Path from "path";
import {IConf, ISetting} from "../conf/interface";
import {EventEmitter} from "events";
import {IApi, APIRunningState} from "../core/api";
import {exitLog, genLogger, genMemCache, Logger} from "../utils";
import {timeoutPromise} from "kht/lib";
import * as getPort from "get-port";
import {Runtime} from "./runtime";
import {driverFactory} from "../core/driver/driverFactory";
import {IWorker, WorkerRunningState} from "../core/worker";
export class Turtle<IDrivers> {
protected initialed: boolean;
protected get log(): Logger {
if (this._log) {
return this._log;
}
return this._log = genLogger();
}
protected _log: Logger;
//
// public get runtime(): Runtime {
// return this._runtime.updateEnvInfo();
// }
public runtime: Runtime = new Runtime();
public readonly gCache: IMemCache = genMemCache();
public conf: IConf;
public rules<TRules = any>(): TRules {
return this.conf.rules as TRules;
}
public get setting(): ISetting {
return this.conf.setting || {};
}
public confPath: any;
public api: IApi;
public workers: IWorker[];
get serviceId() {
return `${this.conf.name}:${this.conf.id}`;
}
constructor() {
console.log(`
██████ ██ ██ ██████ ██████ ██ ██████
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ████ ██ ██ ██████
██ ██ ██ ██ ██ ██ ██ ██
██ ██████ ██ ██ ██ ██████ ██████ ` + chalk.grey(`@khgame
┌──────────────────────────────────────────────────────┐
│ - github - https://github.com/khgame/turtle │
│ - npm - https://www.npmjs.com/package/@khgame/turtle │
└──────────────────────────────────────────────────────┘
`));
}
public get drivers(): IDrivers {
return this._drivers as IDrivers;
}
public driver<TService>(name?: string) {
return name ? this._drivers[name] : undefined;
}
protected _drivers: { [key: string]: any };
public setConf(path: string, force: boolean) {
if (!force && this.conf) {
return;
}
this.loadConf(path);
}
public reloadConf() {
if (!this.confPath) {
throw new Error(`cannot reload conf cuz the conf path are not set`);
}
this.log.info(`config reloaded (${this.confPath}): ${JSON.stringify(this.conf)}`);
this.loadConf(this.confPath);
}
public loadConf(path?: string) {
if (!path) {
throw new Error(`cannot reload conf cuz the given path does not exist`);
}
path = Path.isAbsolute(path) ? path : Path.resolve(process.cwd(), path);
if (!fs.existsSync(path)) {
throw new Error(`conf file at path(${path}) cannot be found`);
}
let content = fs.readFileSync(path);
try {
this.conf = JSON.parse(content.toString());
} catch (e) {
throw new Error(`parse conf file at path(${path}) failed, content: ${content.toString()}`);
}
this.confPath = path;
}
public async initialDrivers(drivers: Array<string | Function>, cb?: (e: EventEmitter) => void) {
const results = await driverFactory.initAll(this.conf.drivers, drivers, cb);
try {
this._drivers = this._drivers ? {...this._drivers, ...results} : results; // override
}
catch (ex) {
console.error(`INITIAL DRIVERS FAILED, ${ex}`);
throw ex;
}
}
public async reload(sig?: string) {
if (sig) {
this.log.info(`★★ SIG ${sig} received, please hold ★★`);
} else {
this.log.info(`★★ internal hup command received, please hold ★★`);
}
this.reloadConf();
await driverFactory.reloadAll(this.conf.drivers);
}
public async shutdown(sig?: string) {
try {
if (sig) {
this.log.info(`★★ SIG ${sig} received, please hold ★★`);
} else {
this.log.info(`★★ internal shutdown command received, please hold ★★`);
}
await this.closeAll();
this.log.info(`★★ process exited ★★`);
await timeoutPromise(5000, exitLog());
process.exit(0);
} catch (err) {
process.exit(1);
}
}
protected async tryInitial(cmdControllers: Function[] = []) {
if (this.initialed) {
return;
}
const oldProcessAlive = this.runtime.checkProcessAlive();
if (oldProcessAlive) {
turtleVerbose(`PROCESS COLLISION DETECTED`, `pid: ${oldProcessAlive}`);
throw new Error(`process of name:${
this.conf.name} id:${
this.conf.id} is running (pid:${
oldProcessAlive}) in current dir (path:${
this.runtime.runtimeFilePath}) .`);
}
await this.runtime.listenCommands(cmdControllers);
process.on("SIGTERM", () => this.shutdown("SIGTERM"));
process.on("SIGINT", () => this.shutdown("SIGINT"));
process.on("SIGHUP", () => this.reload("SIGHUP"));
this.initialed = true;
turtleVerbose(`PROCESS INITIALED (pid: ${turtle.runtime.pid})`,
`cwd: ${turtle.runtime.cwd}`,
`env: ${turtle.runtime.node_env}`,
);
}
/**
* start the api
* @desc to start the api, the running state must be PREPARED|CLOSED, otherwise nothing will happen.
* in the error situation (shutdown failed or in wrong state), an Error will be thrown.
* @return {Promise<void>}
*/
protected async startApi(api: IApi): Promise<this> {
let port: number;
if (!turtle.conf.port) {
port = await getPort();
} else {
let ports: number[] = (typeof turtle.conf.port === "number") ? [turtle.conf.port] : turtle.conf.port;
port = await getPort({port: ports});
if (ports.indexOf(port) < 0) {
throw new Error(`startApi: ports are occupied, ${ports}. avaliable: ${port}`);
}
}
if (this.api && api !== this.api) {
this.log.warn(`there are another registered api, nothing will happen.`);
return this;
}
switch (api.runningState) {
case APIRunningState.NONE:
throw new Error(`api service hasn't prepared, cannot be start.`);
case APIRunningState.PREPARED:
if (await api.start(port)) {
this.log.info(`api service started.`);
} else {
this.log.error(`api service cannot be start.`);
}
break;
case APIRunningState.STARTING:
this.log.warn(`api service is in starting procedure, nothing changed.`);
break;
case APIRunningState.RUNNING:
this.log.warn(`api service is already in running procedure, nothing changed.`);
break;
case APIRunningState.CLOSING:
this.log.warn(`api service is in closing procedure, nothing changed.`);
break;
case APIRunningState.CLOSED:
this.log.info(`api service is already closed, try restart.`);
if (await api.start(port)) {
this.log.info(`api service restarted.`);
} else {
this.log.warn(`api service restart failed, is it restartable ?`);
}
break;
default:
throw new Error("unknown running state code.");
}
this.runtime.setPort(port);
this.api = api;
await driverFactory.triggerApiStart();
turtleVerbose("API STARTED", `serve at: http://${turtle.runtime.ip}:${turtle.runtime.port}`);
return this;
}
protected async startWorkers(workers: IWorker[],
options: {
shutdown_when_error?: boolean
} = {
shutdown_when_error: true
}): Promise<this> {
if (!workers) {
this.log.info(`there are no workers to start.`);
return this;
}
this.workers = this.workers || [];
workers.forEach(w => {
if (this.workers.indexOf(w) < 0) {
this.workers.push(w);
} else {
this.log.warn(`worker ${w.name} is already in the running list`);
}
});
const started = [];
const failed = [];
const error = [];
for (let i = 0; i < this.workers.length; i++) {
const worker = this.workers[i];
switch (worker.runningState) {
case WorkerRunningState.NONE:
throw new Error(`start worker ${i}:${worker.name} failed: it hasn't prepared.
Child classes of worker should set runningState to WorkerRunningState.RUNNING in it's constructor, after initiated.`);
case WorkerRunningState.PREPARED:
try {
if (await worker.start()) {
this.log.info(`worker ${i}:${worker.name} started.`);
started.push(worker.name);
} else {
this.log.error(`worker ${i}:${worker.name} cannot be start.`);
failed.push(worker.name);
}
} catch (e) {
this.log.info(`worker ${i}:${worker.name} start error. ${e}`);
error.push(worker.name);
}
break;
case WorkerRunningState.STARTING:
this.log.warn(`worker ${i}:${worker.name} is in starting procedure, nothing changed.`);
break;
case WorkerRunningState.RUNNING:
this.log.warn(`worker ${i}:${worker.name} is already in running procedure, nothing changed.`);
break;
case WorkerRunningState.CLOSING:
this.log.warn(`worker ${i}:${worker.name} is in closing procedure, nothing changed.`);
break;
case WorkerRunningState.CLOSED:
this.log.info(`worker ${i}:${worker.name} is already closed, try restart.`);
try {
if (await worker.start()) {
this.log.info(`worker ${i}:${worker.name} restarted.`);
started.push(worker.name);
} else {
this.log.warn(`worker ${i}:${worker.name} restart failed, is it restartable ?`);
failed.push(worker.name);
}
} catch (e) {
this.log.info(`worker ${i}:${worker.name} start error. ${e}`);
error.push(worker.name);
}
break;
default:
throw new Error(`start worker ${i}:${worker.name} failed: unknown running state code.`);
}
}
const logs = [];
if (started.length > 0) {
logs.push(started.reduce((p, n) => p + " " + n, "started:"));
}
if (failed.length > 0) {
logs.push(failed.reduce((p, n) => p + " " + n, "failed:"));
}
if (error.length > 0) {
logs.push(error.reduce((p, n) => p + " " + n, "error:"));
}
turtleVerbose("WORKERS STARTED", ...logs);
if (options && options.shutdown_when_error && error && error.length > 0) {
await this.shutdown("worker_error");
}
return this;
}
public async startAll(api: IApi, workers?: IWorker[], cmdControllers?: Function[]) {
await this.tryInitial(cmdControllers);
await this.startWorkers(workers);
await this.startApi(api);
}
/**
* shutdown the api
* @desc to shutdown the api, the running state must be STARTING|RUNNING, otherwise nothing will happen.
* in the error situation (shutdown failed or in wrong state), an Error will be thrown.
* @return {Promise<void>}
*/
public async closeApi() {
const api = this.api;
switch (api.runningState) {
case APIRunningState.NONE:
throw new Error(`api service hasn't prepared, cannot be stop.`);
case APIRunningState.PREPARED:
this.log.warn(`api service is in prepared but not running, nothing changed.`);
break;
case APIRunningState.STARTING:
if (await api.close()) {
this.log.info(`api service is closed at starting procedure.`);
} else {
this.log.warn(`close api service in starting procedure failed.`);
}
break;
case APIRunningState.RUNNING:
if (await api.close()) {
this.log.info(`api service is closed at running procedure.`);
} else {
this.log.error(`close api service in running procedure failed.`);
}
break;
case APIRunningState.CLOSING:
this.log.warn(`api service is already at closing procedure, nothing changed.`);
break;
case APIRunningState.CLOSED:
this.log.info(`api service is already closed, nothing changed.`);
break;
default:
throw new Error("unknown running state code.");
}
await driverFactory.triggerApiClose();
turtleVerbose("API CLOSED");
}
public async closeWorker() {
if (!this.workers) {
this.log.info(`there are no workers to close.`);
return;
}
const closedWorkerNames: string[] = [];
for (const i in this.workers) {
const worker = this.workers[i];
switch (worker.runningState) {
case WorkerRunningState.NONE:
throw new Error(`worker ${i} hasn't prepared, cannot be stop.`);
case WorkerRunningState.PREPARED:
this.log.warn(`worker ${i} is in prepared but not running, nothing changed.`);
break;
case WorkerRunningState.STARTING:
if (await worker.shutdown()) {
closedWorkerNames.push(worker.name);
this.log.info(`worker ${i} is closed at starting procedure.`);
} else {
this.log.warn(`close worker ${i} at starting procedure failed.`);
}
break;
case WorkerRunningState.RUNNING:
if (await worker.shutdown()) {
closedWorkerNames.push(worker.name);
this.log.info(`worker ${i} is closed at running procedure.`);
} else {
this.log.error(`close worker ${i} at running procedure failed.`);
}
break;
case WorkerRunningState.CLOSING:
this.log.warn(`worker ${i} is already at closing procedure, nothing changed.`);
break;
case WorkerRunningState.CLOSED:
this.log.info(`worker ${i} is already closed, nothing changed.`);
break;
default:
throw new Error("unknown running state code.");
}
}
await driverFactory.triggerWorkerClose();
turtleVerbose(`WORKERS CLOSED`, ...closedWorkerNames);
}
public async closeAll() {
await this.closeWorker();
await this.closeApi();
}
}
import {turtleVerbose} from "../core/utils/turtleVerbose";
import chalk from "chalk";
import {IMemCache} from "../utils/memCache";
if (require) {
try {
/* tslint:disable */
var _p = require("bluebird");
turtleVerbose(`GLOBAL EVENT`, "Promise: bluebird");
Promise = _p;
/* tslint:enable */
} catch (e) {
// ..
// console.log("load bluebird failed", e)
}
}
export const turtle = new Turtle<any>(); | the_stack |
import { ApplicationRef, Component, ViewChild } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { skip } from 'rxjs/operators';
import { NbCalendarRange, NbDatepickerDirective, NbTimepickerModule, NbDateTimePickerComponent } from '@nebular/theme';
import { NbDatepickerModule } from './datepicker.module';
import { NbThemeModule } from '../../theme.module';
import { NbLayoutModule } from '../layout/layout.module';
import { NbDatepickerComponent, NbRangepickerComponent } from './datepicker.component';
@Component({
selector: 'nb-datepicker-test',
template: `
<nb-layout>
<nb-layout-column>
<input [nbDatepicker]="datepicker">
<nb-datepicker #datepicker></nb-datepicker>
</nb-layout-column>
</nb-layout>
`,
})
export class NbDatepickerTestComponent {
@ViewChild(NbDatepickerComponent) datepicker: NbDatepickerComponent<Date>;
@ViewChild(NbDatepickerDirective) datepickerDirective: NbDatepickerDirective<Date>;
}
@Component({
selector: 'nb-rangepicker-test',
template: `
<nb-layout>
<nb-layout-column>
<input [nbDatepicker]="rangepicker">
<nb-rangepicker #rangepicker></nb-rangepicker>
</nb-layout-column>
</nb-layout>
`,
})
export class NbRangepickerTestComponent {
@ViewChild(NbRangepickerComponent) rangepicker: NbRangepickerComponent<Date>;
@ViewChild(NbDatepickerDirective) datepickerDirective: NbDatepickerDirective<Date>;
}
@Component({
selector: 'nb-date-timepicker-test',
template: `
<nb-layout>
<nb-layout-column>
<input [nbDatepicker]="rangepicker">
<nb-date-timepicker #rangepicker></nb-date-timepicker>
</nb-layout-column>
</nb-layout>
`,
})
export class NbDateTimepickerTestComponent {
@ViewChild(NbDateTimePickerComponent) dateTimepicker: NbDateTimePickerComponent<Date>;
@ViewChild(NbDatepickerDirective) datepickerDirective: NbDatepickerDirective<Date>;
}
describe('nb-datepicker', () => {
let fixture: ComponentFixture<NbDatepickerTestComponent>;
let appRef: ApplicationRef;
let datepicker: NbDatepickerComponent<Date>;
let datepickerDirective: NbDatepickerDirective<Date>;
let overlay: HTMLElement;
let input: HTMLInputElement;
const showDatepicker = () => {
datepicker.show();
appRef.tick();
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([]),
NbThemeModule.forRoot(),
NbLayoutModule,
NbDatepickerModule.forRoot(),
],
declarations: [NbDatepickerTestComponent],
});
fixture = TestBed.createComponent(NbDatepickerTestComponent);
appRef = TestBed.inject(ApplicationRef);
fixture.detectChanges();
});
beforeEach(() => {
datepicker = fixture.componentInstance.datepicker;
datepickerDirective = fixture.componentInstance.datepickerDirective;
overlay = fixture.nativeElement.querySelector('nb-layout');
input = fixture.nativeElement.querySelector('input');
});
it('should not throw when destroyed right after creation', () => {
const picker = TestBed.createComponent(NbDatepickerComponent).componentInstance;
expect(picker.ngOnDestroy.bind(picker)).not.toThrow();
});
it('should render calendar', () => {
showDatepicker();
const calendar = overlay.querySelector('nb-calendar');
expect(calendar).toBeTruthy();
});
it('should not render overlay on load', () => {
const datepickerContainer = overlay.querySelector('nb-datepicker-container');
expect(datepickerContainer).toBeNull();
});
it('should render overlay lazily', () => {
const datepickerContainer = overlay.querySelector('nb-datepicker-container');
expect(datepickerContainer).toBeNull();
showDatepicker();
const calendar = overlay.querySelector('nb-calendar');
expect(calendar).toBeTruthy();
});
it('should write selected date in the input', () => {
const date = new Date(2018, 8, 17);
datepicker.visibleDate = date;
showDatepicker();
datepicker.dateChange.subscribe(e => {
expect(e).toEqual(date);
expect(input.value).toEqual('Sep 17, 2018');
});
const cell = overlay.querySelectorAll('.day-cell')[22]; // it's visible date cell
cell.dispatchEvent(new Event('click'));
});
it('should start from date typed into the input', () => {
input.value = 'Sep 17, 2018';
input.dispatchEvent(new Event('input'));
showDatepicker();
appRef.tick();
const cell = overlay.querySelector('.day-cell.selected'); // it's input value date cell
expect(cell.textContent).toContain('17');
});
it('should start from current date if input is empty', () => {
showDatepicker();
appRef.tick();
expect(overlay.querySelector('.day-cell.today')).toBeDefined();
});
it('should start from current date if input value is invalid', () => {
input.value = 'definitely not a date';
input.dispatchEvent(new Event('input'));
showDatepicker();
appRef.tick();
expect(overlay.querySelector('.day-cell.today')).toBeDefined();
});
it('should update visible date if input value changed', () => {
const initialDate = new Date(2000, 0, 1);
datepicker.visibleDate = initialDate;
const date = 17;
const month = 8;
const year = 2018;
input.value = 'Sep 17, 2018';
input.dispatchEvent(new Event('input'));
showDatepicker();
appRef.tick();
expect(datepicker.visibleDate.getDate()).toEqual(date);
expect(datepicker.visibleDate.getMonth()).toEqual(month);
expect(datepicker.visibleDate.getFullYear()).toEqual(year);
});
it('should be valid if empty', () => {
expect(datepickerDirective.validate()).toBe(null);
});
it('should not be valid if empty contain incorrectly formatted date', () => {
input.value = 'somecurruptedinput';
input.dispatchEvent(new Event('input'));
showDatepicker();
expect(datepickerDirective.validate()).not.toBe(null);
});
});
describe('nb-rangepicker', () => {
let fixture: ComponentFixture<NbRangepickerTestComponent>;
let appRef: ApplicationRef;
let rangepicker: NbRangepickerComponent<Date>;
let datepickerDirective: NbDatepickerDirective<Date>;
let overlay: HTMLElement;
let input: HTMLInputElement;
const showRangepicker = () => {
rangepicker.show();
appRef.tick();
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([]),
NbThemeModule.forRoot(),
NbLayoutModule,
NbDatepickerModule.forRoot(),
],
declarations: [NbRangepickerTestComponent],
});
fixture = TestBed.createComponent(NbRangepickerTestComponent);
appRef = TestBed.inject(ApplicationRef);
fixture.detectChanges();
});
beforeEach(() => {
rangepicker = fixture.componentInstance.rangepicker;
datepickerDirective = fixture.componentInstance.datepickerDirective;
overlay = fixture.nativeElement.querySelector('nb-layout');
input = fixture.nativeElement.querySelector('input');
});
it('should render calendar', () => {
showRangepicker();
const calendar = overlay.querySelector('nb-calendar-range');
expect(calendar).toBeTruthy();
});
it('should not render overlay on load', () => {
const datepickerContainer = overlay.querySelector('nb-datepicker-container');
expect(datepickerContainer).toBeNull();
});
it('should render overlay lazily', () => {
const datepickerContainer = overlay.querySelector('nb-datepicker-container');
expect(datepickerContainer).toBeNull();
showRangepicker();
const calendar = overlay.querySelector('nb-calendar-range');
expect(calendar).toBeTruthy();
});
it('should emit rangeChange when selected start date', (done) => {
rangepicker.visibleDate = new Date(2018, 8, 17);
showRangepicker();
rangepicker.rangeChange.subscribe((range: NbCalendarRange<Date>) => {
expect(range.start.getFullYear()).toEqual(2018);
expect(range.start.getMonth()).toEqual(8);
expect(range.start.getDate()).toEqual(1);
expect(range.end).not.toBeDefined();
done();
});
// click on Sep 1
const startCell = overlay.querySelectorAll('.day-cell')[6];
(startCell as HTMLElement).click();
fixture.detectChanges();
}, 5000);
it('should emit rangeChange when selected start and end dates', (done) => {
rangepicker.visibleDate = new Date(2018, 8, 17);
showRangepicker();
rangepicker.rangeChange
.pipe(skip(1))
.subscribe((range: NbCalendarRange<Date>) => {
expect(range.start.getFullYear()).toEqual(2018);
expect(range.end.getFullYear()).toEqual(2018);
expect(range.start.getMonth()).toEqual(8);
expect(range.end.getMonth()).toEqual(8);
expect(range.start.getDate()).toEqual(1);
expect(range.end.getDate()).toEqual(3);
done();
});
// click on Sep 1
const startCell = overlay.querySelectorAll('.day-cell')[6];
(startCell as HTMLElement).click();
// click on Sep 3
const endCell = overlay.querySelectorAll('.day-cell')[8];
(endCell as HTMLElement).click();
fixture.detectChanges();
}, 5000);
it('should start from date typed into the input', () => {
input.value = 'Sep 17, 2018 - Sep 19, 2018';
input.dispatchEvent(new Event('input'));
showRangepicker();
appRef.tick();
const startCell = overlay.querySelector('.day-cell.in-range.start');
const endCell = overlay.querySelector('.day-cell.in-range.end');
expect(startCell.textContent).toContain('17');
expect(endCell.textContent).toContain('19');
});
it('should start from current date if input is empty', () => {
showRangepicker();
appRef.tick();
expect(overlay.querySelector('.day-cell.today')).toBeDefined();
});
it('should start from current date if input value is invalid', () => {
input.value = 'definitely not a date';
input.dispatchEvent(new Event('input'));
showRangepicker();
appRef.tick();
expect(overlay.querySelector('.day-cell.today')).toBeDefined();
});
it('should set visible date to start date if input value changed', () => {
const initialDate = new Date(2000, 0, 1);
rangepicker.visibleDate = initialDate;
const date = 17;
const month = 8;
const year = 2018;
input.value = 'Sep 17, 2018 - Sep 19, 2018';
input.dispatchEvent(new Event('input'));
appRef.tick();
showRangepicker();
expect(rangepicker.visibleDate.getDate()).toEqual(date);
expect(rangepicker.visibleDate.getMonth()).toEqual(month);
expect(rangepicker.visibleDate.getFullYear()).toEqual(year);
});
it('should be valid if empty', () => {
expect(datepickerDirective.validate()).toBe(null);
});
it('should not be valid if empty contain incorrectly formatted date', () => {
input.value = 'somecurruptedinput';
input.dispatchEvent(new Event('input'));
showRangepicker();
expect(datepickerDirective.validate()).not.toBe(null);
});
});
describe('nb-date-timepicker', () => {
let fixture: ComponentFixture<NbDateTimepickerTestComponent>;
let appRef: ApplicationRef;
let dateTimepicker: NbDateTimePickerComponent<Date>;
let datepickerDirective: NbDatepickerDirective<Date>;
let overlay: HTMLElement;
let input: HTMLInputElement;
const showDatTimepicker = () => {
dateTimepicker.show();
appRef.tick();
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([]),
NbThemeModule.forRoot(),
NbLayoutModule,
NbTimepickerModule.forRoot(),
NbDatepickerModule.forRoot(),
],
declarations: [NbDateTimepickerTestComponent],
});
fixture = TestBed.createComponent(NbDateTimepickerTestComponent);
appRef = TestBed.inject(ApplicationRef);
fixture.detectChanges();
});
beforeEach(() => {
dateTimepicker = fixture.componentInstance.dateTimepicker;
datepickerDirective = fixture.componentInstance.datepickerDirective;
overlay = fixture.nativeElement.querySelector('nb-layout');
input = fixture.nativeElement.querySelector('input');
});
it('should render calendar', () => {
showDatTimepicker();
const calendar = overlay.querySelector('nb-calendar-with-time');
expect(calendar).toBeTruthy();
});
it('should not render overlay on load', () => {
const datepickerContainer = overlay.querySelector('nb-datepicker-container');
expect(datepickerContainer).toBeNull();
});
it('should render overlay lazily', () => {
const datepickerContainer = overlay.querySelector('nb-datepicker-container');
expect(datepickerContainer).toBeNull();
showDatTimepicker();
const calendar = overlay.querySelector('nb-calendar-with-time');
expect(calendar).toBeTruthy();
});
}); | the_stack |
import * as tsUnit from './tsUnit';
export class RealClass {
public name = 'Real';
run() {
return false;
}
returnValue(): RealClass {
return this;
}
}
class SetUpTestClassStub extends tsUnit.TestClass {
public TestProperty: string = '';
setUp() {
this.TestProperty = 'SETUP';
}
testAfterInitialSetUp() {
this.areIdentical('SETUP', this.TestProperty);
this.TestProperty = 'OVERWRITE';
}
testOfSetUpWithFail() {
this.areIdentical('SETUP', this.TestProperty);
throw "Internal test error: Thrown by testOfSetUpWithFail";
}
testNextInStub() {
this.areIdentical('SETUP', this.TestProperty);
this.TestProperty = 'OVERWRITE';
}
}
class SetUpWithParametersTestClassStub extends tsUnit.TestClass {
public TestProperty: string = '';
constructor() {
super();
this.parameterizeUnitTest(this.testSum, [
[2, 1],
[3, 2],
[4, 3]
]);
}
setUp() {
this.TestProperty = 'SETUP';
}
testSum(a: number, b: number) {
this.areIdentical('SETUP', this.TestProperty);
this.areIdentical(a, b + 1);
this.TestProperty = 'OVERWRITE';
}
}
class TearDownTestClassStub extends tsUnit.TestClass {
public TestProperty: string = '';
testAfterInitialSetUp() {
this.areIdentical('', this.TestProperty);
this.TestProperty = 'OVERWRITE';
}
tearDown() {
this.TestProperty = 'TEARDOWN';
}
}
class TearDownWithFailingTestClassStub extends tsUnit.TestClass {
public TestProperty: string = '';
testWhichWillFail() {
this.areIdentical('', this.TestProperty);
this.TestProperty = 'OVERWRITE';
throw "Internal test error: Thrown by testWhichWillFail";
}
tearDown() {
this.TestProperty = 'TEARDOWN';
}
}
class TearDownTestWithParametersTestClassStub extends tsUnit.TestClass {
public tearDownCounter = 0;
constructor() {
super();
this.parameterizeUnitTest(this.testForTearDown, [
[0],
[1],
[2]
]);
}
testForTearDown(index: number) {
this.areIdentical(index, this.tearDownCounter);
}
tearDown() {
this.tearDownCounter++;
}
}
export class TearDownAndSetUpTests extends tsUnit.TestClass {
testOfSetUp() {
var stub = new SetUpTestClassStub();
var testPropertyOnBegin = stub.TestProperty;
var test = new tsUnit.Test();
test.addTestClass(stub, 'SetUpTestClassStub');
var results = test.run();
this.areIdentical(testPropertyOnBegin, '', "TestProperty should be empty on start");
this.isTrue((results.passes.length == 2) && (results.errors.length == 1), "All internal tests should passed (appertly setUp didn't work)");
}
testOfSetUpWithParameters() {
var stub = new SetUpWithParametersTestClassStub();
var testPropertyOnBegin = stub.TestProperty;
var test = new tsUnit.Test();
test.addTestClass(stub, 'SetUpWithParametersTestClassStub');
var results = test.run();
this.areIdentical(testPropertyOnBegin, '', "TestProperty should be empty on start");
this.isTrue((results.passes.length == 3) && (results.errors.length == 0), "All internal tests should passed (appertly setUp didn't work)");
}
testOfTearDown() {
var stub = new TearDownTestClassStub();
var testPropertyOnBegin = stub.TestProperty;
var test = new tsUnit.Test();
test.addTestClass(stub, 'TearDownTestClassStub');
test.run();
this.areIdentical(testPropertyOnBegin, '', "TestProperty should be empty on start");
this.areIdentical(stub.TestProperty, 'TEARDOWN', "TestProperty should be overwrite by TearDown method");
}
testTearDownWithFailedTest() {
var stub = new TearDownWithFailingTestClassStub();
var testPropertyOnBegin = stub.TestProperty;
var test = new tsUnit.Test();
test.addTestClass(stub, 'TearDownWithFailingTestClassStub');
test.run();
this.areIdentical(testPropertyOnBegin, '', "TestProperty should be empty on start");
this.areIdentical(stub.TestProperty, 'TEARDOWN', "TestProperty should be overwrite by TearDown method");
}
testTearDownWithParameters() {
var stub = new TearDownTestWithParametersTestClassStub();
var test = new tsUnit.Test();
test.addTestClass(stub, 'TearDownTestWithParametersTestClassStub');
var results = test.run();
this.areIdentical(3, stub.tearDownCounter);
this.isTrue((results.passes.length == 3) && (results.errors.length == 0), "All internal tests should passed (appertly setUp didn't work)");
}
}
export class FakeFactoryTests extends tsUnit.TestClass {
callDefaultFunctionOnFake() {
var target = tsUnit.FakeFactory.getFake<RealClass>(RealClass);
var result = target.run();
this.areIdentical(undefined, result);
}
callSubstituteFunctionOnFake() {
var target = tsUnit.FakeFactory.getFake<RealClass>(RealClass,
['run', function () { return true; }]
);
var result = target.run();
this.isTrue(result);
}
callSubstituteFunctionToObtainSecondFake() {
// We can use the FakeFactory to make the outer 'RealClass' return a fake 'RealClass'
// when the 'returnValue' method is called.
var target = tsUnit.FakeFactory.getFake<RealClass>(RealClass,
['returnValue', function () {
return tsUnit.FakeFactory.getFake<RealClass>(RealClass, ['run', function () { return true; }]);
}]
);
var interimResult = target.returnValue();
var result = interimResult.run();
this.isTrue(result);
}
callDefaultPropertyOnFake() {
var target = tsUnit.FakeFactory.getFake<RealClass>(RealClass);
var result = target.name;
this.areIdentical(undefined, result);
}
callSubstitutePropertyOnFake() {
var target = tsUnit.FakeFactory.getFake<RealClass>(RealClass,
['name', 'Test']
);
var result = target.name;
this.areIdentical('Test', result);
}
}
export class PrivateMembersOnly extends tsUnit.TestClass {
private _privateMethod() {
throw new Error('This should not be called as it is private, with the default prefix: _');
}
publicMethod() {
this.areIdentical(1, 1, "Public method called ok.");
}
}
export class AssertAreIdenticalTests extends tsUnit.TestClass {
withIdenticalNumbers() {
this.areIdentical(5, 5);
}
withDifferentNumbers() {
this.throws(function () {
this.areIdentical(5, 4);
});
}
withIdenticalStings() {
this.areIdentical('Hello', 'Hello');
}
withDifferentStrings() {
this.throws(function () {
this.areIdentical('Hello', 'Jello');
});
}
withSameInstance() {
var x = { test: 'Object' };
var y = x;
this.areIdentical(x, y);
}
withDifferentInstance() {
this.throws(function () {
var x = { test: 'Object' };
var y = { test: 'Object' };
this.areIdentical(x, y);
});
}
withDifferentTypes() {
this.throws(function () {
this.areIdentical('1', 1);
});
}
withIdenticalCollections() {
var x = [1, 2, 3, 5];
var y = [1, 2, 3, 5];
this.areCollectionsIdentical(x, y);
}
withDifferentCollections() {
var x = [1, 2, 3, 5];
var y = [1, 2, 4, 5];
this.throws(function () {
this.areCollectionsIdentical(x, y);
});
}
}
export class AssertAreNotIdenticalTests extends tsUnit.TestClass {
withIdenticalNumbers() {
this.throws(function () {
this.areNotIdentical(4, 4);
});
}
withDifferentNumbers() {
this.areNotIdentical(4, -4);
}
withIdenticalStrings() {
this.throws(function () {
this.areNotIdentical('Hello', 'Hello');
});
}
withDifferentStrings() {
this.areNotIdentical('Hello', 'Hella');
}
withSameInstance() {
this.throws(function () {
var x = { test: 'Object' };
var y = x;
this.areNotIdentical(x, y);
});
}
withDifferentInstance() {
var x = { test: 'Object' };
var y = { test: 'Object' };
this.areNotIdentical(x, y);
}
withDifferentTypes() {
this.areNotIdentical('1', 1);
}
withIdenticalCollections() {
var x = [1, 2, 3, 5];
var y = [1, 2, 3, 5];
this.throws(function () {
this.areCollectionsNotIdentical(x, y);
});
}
withDifferentCollections() {
var x = [1, 2, 3, 5];
var y = [1, 2, 4, 5];
this.areCollectionsNotIdentical(x, y);
}
}
export class IsTrueTests extends tsUnit.TestClass {
withBoolTrue() {
this.isTrue(true);
}
withBoolFalse() {
this.throws(function () {
this.isTrue(false);
});
}
}
export class IsFalseTests extends tsUnit.TestClass {
withBoolFalse() {
this.isFalse(false);
}
withBoolTrue() {
this.throws(function () {
this.isFalse(true);
});
}
}
export class IsTruthyTests extends tsUnit.TestClass {
withBoolTrue() {
this.isTruthy(true);
}
withNonEmptyString() {
this.isTruthy('Hello');
}
withTrueString() {
this.isTruthy('True');
}
with1() {
this.isTruthy(1);
}
withBoolFalse() {
this.throws(function () {
this.isTruthy(false);
});
}
withEmptyString() {
this.throws(function () {
this.isTruthy('');
});
}
withZero() {
this.throws(function () {
this.isTruthy(0);
});
}
withNull() {
this.throws(function () {
this.isTruthy(null);
});
}
withUndefined() {
this.throws(function () {
this.isTruthy(undefined);
});
}
}
export class IsFalseyTests extends tsUnit.TestClass {
withBoolFalse() {
this.isFalsey(false);
}
withEmptyString() {
this.isFalsey('');
}
withZero() {
this.isFalsey(0);
}
withNull() {
this.isFalsey(null);
}
withUndefined() {
this.isFalsey(undefined);
}
withBoolTrue() {
this.throws(function () {
this.isFalsey(true);
});
}
withNonEmptyString() {
this.throws(function () {
this.isFalsey('Hello');
});
}
withTrueString() {
this.throws(function () {
this.isFalsey('True');
});
}
with1() {
this.throws(function () {
this.isFalsey(1);
});
}
}
export class FailTests extends tsUnit.TestClass {
expectFails() {
this.throws(function () {
this.fail();
});
}
}
export class ExecutesWithinTests extends tsUnit.TestClass {
withFastFunction() {
this.executesWithin(() => {
var start = window.performance.now();
while ((window.performance.now() - start) < 20) { }
}, 100);
}
withSlowFunction() {
this.throws(() => {
this.executesWithin(() => {
var start = window.performance.now();
while ((window.performance.now() - start) < 101) {
}
}, 100);
});
}
withFailingFunction() {
this.throws(() => {
this.executesWithin(() => {
var start = window.performance.now();
throw 'Error';
}, 100);
});
}
}
export class ParameterizedTests extends tsUnit.TestClass {
constructor() {
super();
this.parameterizeUnitTest(this.sumTests, [
[1, 1, 2],
[2, 3, 5],
[4, 5, 9]
]);
this.parameterizeUnitTest(this.nonSumTests, [
[1, 1, 1],
[4, 5, 1]
]);
}
sumTests(a: number, b: number, sum: number) {
var c = a + b;
this.areIdentical(c, sum);
}
nonSumTests(a: number, b: number, notsum: number) {
var c = a + b;
this.areNotIdentical(c, notsum);
}
normalTest() {
this.isTrue(true);
}
}
export class ThrowsTests extends tsUnit.TestClass {
functionsFails() {
this.throws(() => {
throw Error('throw some error');
});
}
innerFunctionsDoesntFails() {
this.throws(
() => this.throws(
() => {
var a = 0;
})
);
}
functionsFailsWithSpecificErrorMessage() {
this.throws({
fn: () => {
throw Error('throw some error');
},
errorString: 'throw some error'
});
}
functionsDoesntFailsWithMessage() {
this.throws({
fn: () => this.throws({
fn: () => {
var a = 0;
},
message: 'with message'
}),
errorString: "did not throw an error. with message"
});
}
functionsFailsWithDifferentErrorMessage() {
this.throws({
fn: () => this.throws({
fn: () => this.throws({
fn: () => {
throw new Error('throw different error');
}
}),
errorString: 'throw some error'
})
});
}
functionsFailsWithUndefinedParam() {
this.throws(() => this.throws(undefined));
}
functionsFailsWithNullParam() {
this.throws(() => this.throws(null));
}
}
export class DoesNotThrowTests extends tsUnit.TestClass {
doesNotThrowPassingTest() {
this.doesNotThrow(() => {
console.log('Does not throw');
});
}
functionsFails() {
this.throws(() => {
// An error should be thrown
this.doesNotThrow(() => {
throw Error('throw some error');
});
});
}
} | the_stack |
import { core } from 'nexus'
import { GraphQLResolveInfo } from 'graphql'
import * as prisma from '../prisma-client'
declare global {
interface NexusPrismaGen extends NexusPrismaTypes {}
}
export interface NexusPrismaTypes {
objectTypes: {
fields: {
Query: QueryObject
User: UserObject
PasswordMeta: PasswordMetaObject
UserConnection: UserConnectionObject
PageInfo: PageInfoObject
UserEdge: UserEdgeObject
AggregateUser: AggregateUserObject
PasswordMetaConnection: PasswordMetaConnectionObject
PasswordMetaEdge: PasswordMetaEdgeObject
AggregatePasswordMeta: AggregatePasswordMetaObject
Mutation: MutationObject
BatchPayload: BatchPayloadObject
Subscription: SubscriptionObject
UserSubscriptionPayload: UserSubscriptionPayloadObject
UserPreviousValues: UserPreviousValuesObject
PasswordMetaSubscriptionPayload: PasswordMetaSubscriptionPayloadObject
PasswordMetaPreviousValues: PasswordMetaPreviousValuesObject
}
fieldsDetails: {
Query: QueryFieldDetails
User: UserFieldDetails
PasswordMeta: PasswordMetaFieldDetails
UserConnection: UserConnectionFieldDetails
PageInfo: PageInfoFieldDetails
UserEdge: UserEdgeFieldDetails
AggregateUser: AggregateUserFieldDetails
PasswordMetaConnection: PasswordMetaConnectionFieldDetails
PasswordMetaEdge: PasswordMetaEdgeFieldDetails
AggregatePasswordMeta: AggregatePasswordMetaFieldDetails
Mutation: MutationFieldDetails
BatchPayload: BatchPayloadFieldDetails
Subscription: SubscriptionFieldDetails
UserSubscriptionPayload: UserSubscriptionPayloadFieldDetails
UserPreviousValues: UserPreviousValuesFieldDetails
PasswordMetaSubscriptionPayload: PasswordMetaSubscriptionPayloadFieldDetails
PasswordMetaPreviousValues: PasswordMetaPreviousValuesFieldDetails
}
}
inputTypes: {
fields: {
UserWhereUniqueInput: UserWhereUniqueInputInputObject
UserWhereInput: UserWhereInputInputObject
PasswordMetaWhereInput: PasswordMetaWhereInputInputObject
PasswordMetaWhereUniqueInput: PasswordMetaWhereUniqueInputInputObject
UserCreateInput: UserCreateInputInputObject
PasswordMetaCreateOneInput: PasswordMetaCreateOneInputInputObject
PasswordMetaCreateInput: PasswordMetaCreateInputInputObject
UserUpdateInput: UserUpdateInputInputObject
PasswordMetaUpdateOneInput: PasswordMetaUpdateOneInputInputObject
PasswordMetaUpdateDataInput: PasswordMetaUpdateDataInputInputObject
PasswordMetaUpsertNestedInput: PasswordMetaUpsertNestedInputInputObject
UserUpdateManyMutationInput: UserUpdateManyMutationInputInputObject
PasswordMetaUpdateInput: PasswordMetaUpdateInputInputObject
PasswordMetaUpdateManyMutationInput: PasswordMetaUpdateManyMutationInputInputObject
UserSubscriptionWhereInput: UserSubscriptionWhereInputInputObject
PasswordMetaSubscriptionWhereInput: PasswordMetaSubscriptionWhereInputInputObject
}
}
enumTypes: {
UserRole: UserRoleValues,
UserOrderByInput: UserOrderByInputValues,
PasswordMetaOrderByInput: PasswordMetaOrderByInputValues,
MutationType: MutationTypeValues,
}
}
// Types for Query
type QueryObject =
| QueryFields
| { name: 'user', args?: QueryUserArgs[] | false, alias?: string }
| { name: 'users', args?: QueryUsersArgs[] | false, alias?: string }
| { name: 'usersConnection', args?: QueryUsersConnectionArgs[] | false, alias?: string }
| { name: 'passwordMeta', args?: QueryPasswordMetaArgs[] | false, alias?: string }
| { name: 'passwordMetas', args?: QueryPasswordMetasArgs[] | false, alias?: string }
| { name: 'passwordMetasConnection', args?: QueryPasswordMetasConnectionArgs[] | false, alias?: string }
type QueryFields =
| 'user'
| 'users'
| 'usersConnection'
| 'passwordMeta'
| 'passwordMetas'
| 'passwordMetasConnection'
type QueryUserArgs =
| 'where'
type QueryUsersArgs =
| 'where'
| 'orderBy'
| 'skip'
| 'after'
| 'before'
| 'first'
| 'last'
type QueryUsersConnectionArgs =
| 'where'
| 'orderBy'
| 'skip'
| 'after'
| 'before'
| 'first'
| 'last'
type QueryPasswordMetaArgs =
| 'where'
type QueryPasswordMetasArgs =
| 'where'
| 'orderBy'
| 'skip'
| 'after'
| 'before'
| 'first'
| 'last'
type QueryPasswordMetasConnectionArgs =
| 'where'
| 'orderBy'
| 'skip'
| 'after'
| 'before'
| 'first'
| 'last'
export interface QueryFieldDetails {
user: {
type: 'User'
args: Record<QueryUserArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"Query">,
args: { where: UserWhereUniqueInput } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.User | null> | prisma.User | null
}
users: {
type: 'User'
args: Record<QueryUsersArgs, core.NexusArgDef<string>>
description: string
list: true
nullable: false
resolve: (
root: core.RootValue<"Query">,
args: { where?: UserWhereInput | null, orderBy?: prisma.UserOrderByInput | null, skip?: number | null, after?: string | null, before?: string | null, first?: number | null, last?: number | null } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.User[]> | prisma.User[]
}
usersConnection: {
type: 'UserConnection'
args: Record<QueryUsersConnectionArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"Query">,
args: { where?: UserWhereInput | null, orderBy?: prisma.UserOrderByInput | null, skip?: number | null, after?: string | null, before?: string | null, first?: number | null, last?: number | null } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.UserConnection> | prisma.UserConnection
}
passwordMeta: {
type: 'PasswordMeta'
args: Record<QueryPasswordMetaArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"Query">,
args: { where: PasswordMetaWhereUniqueInput } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMeta | null> | prisma.PasswordMeta | null
}
passwordMetas: {
type: 'PasswordMeta'
args: Record<QueryPasswordMetasArgs, core.NexusArgDef<string>>
description: string
list: true
nullable: false
resolve: (
root: core.RootValue<"Query">,
args: { where?: PasswordMetaWhereInput | null, orderBy?: prisma.PasswordMetaOrderByInput | null, skip?: number | null, after?: string | null, before?: string | null, first?: number | null, last?: number | null } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMeta[]> | prisma.PasswordMeta[]
}
passwordMetasConnection: {
type: 'PasswordMetaConnection'
args: Record<QueryPasswordMetasConnectionArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"Query">,
args: { where?: PasswordMetaWhereInput | null, orderBy?: prisma.PasswordMetaOrderByInput | null, skip?: number | null, after?: string | null, before?: string | null, first?: number | null, last?: number | null } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMetaConnection> | prisma.PasswordMetaConnection
}
}
// Types for User
type UserObject =
| UserFields
| { name: 'id', args?: [] | false, alias?: string }
| { name: 'createdAt', args?: [] | false, alias?: string }
| { name: 'updatedAt', args?: [] | false, alias?: string }
| { name: 'email', args?: [] | false, alias?: string }
| { name: 'password', args?: [] | false, alias?: string }
| { name: 'role', args?: [] | false, alias?: string }
| { name: 'firstName', args?: [] | false, alias?: string }
| { name: 'lastName', args?: [] | false, alias?: string }
| { name: 'phone', args?: [] | false, alias?: string }
| { name: 'passwordMeta', args?: [] | false, alias?: string }
type UserFields =
| 'id'
| 'createdAt'
| 'updatedAt'
| 'email'
| 'password'
| 'role'
| 'firstName'
| 'lastName'
| 'phone'
| 'passwordMeta'
export interface UserFieldDetails {
id: {
type: 'ID'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
createdAt: {
type: 'DateTime'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
updatedAt: {
type: 'DateTime'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
email: {
type: 'String'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
password: {
type: 'String'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
role: {
type: 'UserRole'
args: {}
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"User">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.UserRole> | prisma.UserRole
}
firstName: {
type: 'String'
args: {}
description: string
list: undefined
nullable: true
resolve: undefined
}
lastName: {
type: 'String'
args: {}
description: string
list: undefined
nullable: true
resolve: undefined
}
phone: {
type: 'String'
args: {}
description: string
list: undefined
nullable: true
resolve: undefined
}
passwordMeta: {
type: 'PasswordMeta'
args: {}
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"User">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMeta | null> | prisma.PasswordMeta | null
}
}
// Types for PasswordMeta
type PasswordMetaObject =
| PasswordMetaFields
| { name: 'id', args?: [] | false, alias?: string }
| { name: 'createdAt', args?: [] | false, alias?: string }
| { name: 'updatedAt', args?: [] | false, alias?: string }
| { name: 'resetToken', args?: [] | false, alias?: string }
type PasswordMetaFields =
| 'id'
| 'createdAt'
| 'updatedAt'
| 'resetToken'
export interface PasswordMetaFieldDetails {
id: {
type: 'ID'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
createdAt: {
type: 'DateTime'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
updatedAt: {
type: 'DateTime'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
resetToken: {
type: 'String'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
}
// Types for UserConnection
type UserConnectionObject =
| UserConnectionFields
| { name: 'pageInfo', args?: [] | false, alias?: string }
| { name: 'edges', args?: [] | false, alias?: string }
| { name: 'aggregate', args?: [] | false, alias?: string }
type UserConnectionFields =
| 'pageInfo'
| 'edges'
| 'aggregate'
export interface UserConnectionFieldDetails {
pageInfo: {
type: 'PageInfo'
args: {}
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"UserConnection">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PageInfo> | prisma.PageInfo
}
edges: {
type: 'UserEdge'
args: {}
description: string
list: true
nullable: false
resolve: (
root: core.RootValue<"UserConnection">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.UserEdge[]> | prisma.UserEdge[]
}
aggregate: {
type: 'AggregateUser'
args: {}
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"UserConnection">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.AggregateUser> | prisma.AggregateUser
}
}
// Types for PageInfo
type PageInfoObject =
| PageInfoFields
| { name: 'hasNextPage', args?: [] | false, alias?: string }
| { name: 'hasPreviousPage', args?: [] | false, alias?: string }
| { name: 'startCursor', args?: [] | false, alias?: string }
| { name: 'endCursor', args?: [] | false, alias?: string }
type PageInfoFields =
| 'hasNextPage'
| 'hasPreviousPage'
| 'startCursor'
| 'endCursor'
export interface PageInfoFieldDetails {
hasNextPage: {
type: 'Boolean'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
hasPreviousPage: {
type: 'Boolean'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
startCursor: {
type: 'String'
args: {}
description: string
list: undefined
nullable: true
resolve: undefined
}
endCursor: {
type: 'String'
args: {}
description: string
list: undefined
nullable: true
resolve: undefined
}
}
// Types for UserEdge
type UserEdgeObject =
| UserEdgeFields
| { name: 'node', args?: [] | false, alias?: string }
| { name: 'cursor', args?: [] | false, alias?: string }
type UserEdgeFields =
| 'node'
| 'cursor'
export interface UserEdgeFieldDetails {
node: {
type: 'User'
args: {}
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"UserEdge">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.User> | prisma.User
}
cursor: {
type: 'String'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
}
// Types for AggregateUser
type AggregateUserObject =
| AggregateUserFields
| { name: 'count', args?: [] | false, alias?: string }
type AggregateUserFields =
| 'count'
export interface AggregateUserFieldDetails {
count: {
type: 'Int'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
}
// Types for PasswordMetaConnection
type PasswordMetaConnectionObject =
| PasswordMetaConnectionFields
| { name: 'pageInfo', args?: [] | false, alias?: string }
| { name: 'edges', args?: [] | false, alias?: string }
| { name: 'aggregate', args?: [] | false, alias?: string }
type PasswordMetaConnectionFields =
| 'pageInfo'
| 'edges'
| 'aggregate'
export interface PasswordMetaConnectionFieldDetails {
pageInfo: {
type: 'PageInfo'
args: {}
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"PasswordMetaConnection">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PageInfo> | prisma.PageInfo
}
edges: {
type: 'PasswordMetaEdge'
args: {}
description: string
list: true
nullable: false
resolve: (
root: core.RootValue<"PasswordMetaConnection">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMetaEdge[]> | prisma.PasswordMetaEdge[]
}
aggregate: {
type: 'AggregatePasswordMeta'
args: {}
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"PasswordMetaConnection">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.AggregatePasswordMeta> | prisma.AggregatePasswordMeta
}
}
// Types for PasswordMetaEdge
type PasswordMetaEdgeObject =
| PasswordMetaEdgeFields
| { name: 'node', args?: [] | false, alias?: string }
| { name: 'cursor', args?: [] | false, alias?: string }
type PasswordMetaEdgeFields =
| 'node'
| 'cursor'
export interface PasswordMetaEdgeFieldDetails {
node: {
type: 'PasswordMeta'
args: {}
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"PasswordMetaEdge">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMeta> | prisma.PasswordMeta
}
cursor: {
type: 'String'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
}
// Types for AggregatePasswordMeta
type AggregatePasswordMetaObject =
| AggregatePasswordMetaFields
| { name: 'count', args?: [] | false, alias?: string }
type AggregatePasswordMetaFields =
| 'count'
export interface AggregatePasswordMetaFieldDetails {
count: {
type: 'Int'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
}
// Types for Mutation
type MutationObject =
| MutationFields
| { name: 'createUser', args?: MutationCreateUserArgs[] | false, alias?: string }
| { name: 'updateUser', args?: MutationUpdateUserArgs[] | false, alias?: string }
| { name: 'updateManyUsers', args?: MutationUpdateManyUsersArgs[] | false, alias?: string }
| { name: 'upsertUser', args?: MutationUpsertUserArgs[] | false, alias?: string }
| { name: 'deleteUser', args?: MutationDeleteUserArgs[] | false, alias?: string }
| { name: 'deleteManyUsers', args?: MutationDeleteManyUsersArgs[] | false, alias?: string }
| { name: 'createPasswordMeta', args?: MutationCreatePasswordMetaArgs[] | false, alias?: string }
| { name: 'updatePasswordMeta', args?: MutationUpdatePasswordMetaArgs[] | false, alias?: string }
| { name: 'updateManyPasswordMetas', args?: MutationUpdateManyPasswordMetasArgs[] | false, alias?: string }
| { name: 'upsertPasswordMeta', args?: MutationUpsertPasswordMetaArgs[] | false, alias?: string }
| { name: 'deletePasswordMeta', args?: MutationDeletePasswordMetaArgs[] | false, alias?: string }
| { name: 'deleteManyPasswordMetas', args?: MutationDeleteManyPasswordMetasArgs[] | false, alias?: string }
type MutationFields =
| 'createUser'
| 'updateUser'
| 'updateManyUsers'
| 'upsertUser'
| 'deleteUser'
| 'deleteManyUsers'
| 'createPasswordMeta'
| 'updatePasswordMeta'
| 'updateManyPasswordMetas'
| 'upsertPasswordMeta'
| 'deletePasswordMeta'
| 'deleteManyPasswordMetas'
type MutationCreateUserArgs =
| 'data'
type MutationUpdateUserArgs =
| 'data'
| 'where'
type MutationUpdateManyUsersArgs =
| 'data'
| 'where'
type MutationUpsertUserArgs =
| 'where'
| 'create'
| 'update'
type MutationDeleteUserArgs =
| 'where'
type MutationDeleteManyUsersArgs =
| 'where'
type MutationCreatePasswordMetaArgs =
| 'data'
type MutationUpdatePasswordMetaArgs =
| 'data'
| 'where'
type MutationUpdateManyPasswordMetasArgs =
| 'data'
| 'where'
type MutationUpsertPasswordMetaArgs =
| 'where'
| 'create'
| 'update'
type MutationDeletePasswordMetaArgs =
| 'where'
type MutationDeleteManyPasswordMetasArgs =
| 'where'
export interface MutationFieldDetails {
createUser: {
type: 'User'
args: Record<MutationCreateUserArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"Mutation">,
args: { data: UserCreateInput } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.User> | prisma.User
}
updateUser: {
type: 'User'
args: Record<MutationUpdateUserArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"Mutation">,
args: { data: UserUpdateInput, where: UserWhereUniqueInput } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.User | null> | prisma.User | null
}
updateManyUsers: {
type: 'BatchPayload'
args: Record<MutationUpdateManyUsersArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"Mutation">,
args: { data: UserUpdateManyMutationInput, where?: UserWhereInput | null } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.BatchPayload> | prisma.BatchPayload
}
upsertUser: {
type: 'User'
args: Record<MutationUpsertUserArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"Mutation">,
args: { where: UserWhereUniqueInput, create: UserCreateInput, update: UserUpdateInput } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.User> | prisma.User
}
deleteUser: {
type: 'User'
args: Record<MutationDeleteUserArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"Mutation">,
args: { where: UserWhereUniqueInput } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.User | null> | prisma.User | null
}
deleteManyUsers: {
type: 'BatchPayload'
args: Record<MutationDeleteManyUsersArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"Mutation">,
args: { where?: UserWhereInput | null } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.BatchPayload> | prisma.BatchPayload
}
createPasswordMeta: {
type: 'PasswordMeta'
args: Record<MutationCreatePasswordMetaArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"Mutation">,
args: { data: PasswordMetaCreateInput } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMeta> | prisma.PasswordMeta
}
updatePasswordMeta: {
type: 'PasswordMeta'
args: Record<MutationUpdatePasswordMetaArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"Mutation">,
args: { data: PasswordMetaUpdateInput, where: PasswordMetaWhereUniqueInput } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMeta | null> | prisma.PasswordMeta | null
}
updateManyPasswordMetas: {
type: 'BatchPayload'
args: Record<MutationUpdateManyPasswordMetasArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"Mutation">,
args: { data: PasswordMetaUpdateManyMutationInput, where?: PasswordMetaWhereInput | null } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.BatchPayload> | prisma.BatchPayload
}
upsertPasswordMeta: {
type: 'PasswordMeta'
args: Record<MutationUpsertPasswordMetaArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"Mutation">,
args: { where: PasswordMetaWhereUniqueInput, create: PasswordMetaCreateInput, update: PasswordMetaUpdateInput } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMeta> | prisma.PasswordMeta
}
deletePasswordMeta: {
type: 'PasswordMeta'
args: Record<MutationDeletePasswordMetaArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"Mutation">,
args: { where: PasswordMetaWhereUniqueInput } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMeta | null> | prisma.PasswordMeta | null
}
deleteManyPasswordMetas: {
type: 'BatchPayload'
args: Record<MutationDeleteManyPasswordMetasArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"Mutation">,
args: { where?: PasswordMetaWhereInput | null } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.BatchPayload> | prisma.BatchPayload
}
}
// Types for BatchPayload
type BatchPayloadObject =
| BatchPayloadFields
| { name: 'count', args?: [] | false, alias?: string }
type BatchPayloadFields =
| 'count'
export interface BatchPayloadFieldDetails {
count: {
type: 'Long'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
}
// Types for Subscription
type SubscriptionObject =
| SubscriptionFields
| { name: 'user', args?: SubscriptionUserArgs[] | false, alias?: string }
| { name: 'passwordMeta', args?: SubscriptionPasswordMetaArgs[] | false, alias?: string }
type SubscriptionFields =
| 'user'
| 'passwordMeta'
type SubscriptionUserArgs =
| 'where'
type SubscriptionPasswordMetaArgs =
| 'where'
export interface SubscriptionFieldDetails {
user: {
type: 'UserSubscriptionPayload'
args: Record<SubscriptionUserArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"Subscription">,
args: { where?: UserSubscriptionWhereInput | null } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.UserSubscriptionPayload | null> | prisma.UserSubscriptionPayload | null
}
passwordMeta: {
type: 'PasswordMetaSubscriptionPayload'
args: Record<SubscriptionPasswordMetaArgs, core.NexusArgDef<string>>
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"Subscription">,
args: { where?: PasswordMetaSubscriptionWhereInput | null } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMetaSubscriptionPayload | null> | prisma.PasswordMetaSubscriptionPayload | null
}
}
// Types for UserSubscriptionPayload
type UserSubscriptionPayloadObject =
| UserSubscriptionPayloadFields
| { name: 'mutation', args?: [] | false, alias?: string }
| { name: 'node', args?: [] | false, alias?: string }
| { name: 'updatedFields', args?: [] | false, alias?: string }
| { name: 'previousValues', args?: [] | false, alias?: string }
type UserSubscriptionPayloadFields =
| 'mutation'
| 'node'
| 'updatedFields'
| 'previousValues'
export interface UserSubscriptionPayloadFieldDetails {
mutation: {
type: 'MutationType'
args: {}
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"UserSubscriptionPayload">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.MutationType> | prisma.MutationType
}
node: {
type: 'User'
args: {}
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"UserSubscriptionPayload">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.User | null> | prisma.User | null
}
updatedFields: {
type: 'String'
args: {}
description: string
list: true
nullable: false
resolve: undefined
}
previousValues: {
type: 'UserPreviousValues'
args: {}
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"UserSubscriptionPayload">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.UserPreviousValues | null> | prisma.UserPreviousValues | null
}
}
// Types for UserPreviousValues
type UserPreviousValuesObject =
| UserPreviousValuesFields
| { name: 'id', args?: [] | false, alias?: string }
| { name: 'createdAt', args?: [] | false, alias?: string }
| { name: 'updatedAt', args?: [] | false, alias?: string }
| { name: 'email', args?: [] | false, alias?: string }
| { name: 'password', args?: [] | false, alias?: string }
| { name: 'role', args?: [] | false, alias?: string }
| { name: 'firstName', args?: [] | false, alias?: string }
| { name: 'lastName', args?: [] | false, alias?: string }
| { name: 'phone', args?: [] | false, alias?: string }
type UserPreviousValuesFields =
| 'id'
| 'createdAt'
| 'updatedAt'
| 'email'
| 'password'
| 'role'
| 'firstName'
| 'lastName'
| 'phone'
export interface UserPreviousValuesFieldDetails {
id: {
type: 'ID'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
createdAt: {
type: 'DateTime'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
updatedAt: {
type: 'DateTime'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
email: {
type: 'String'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
password: {
type: 'String'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
role: {
type: 'UserRole'
args: {}
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"UserPreviousValues">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.UserRole> | prisma.UserRole
}
firstName: {
type: 'String'
args: {}
description: string
list: undefined
nullable: true
resolve: undefined
}
lastName: {
type: 'String'
args: {}
description: string
list: undefined
nullable: true
resolve: undefined
}
phone: {
type: 'String'
args: {}
description: string
list: undefined
nullable: true
resolve: undefined
}
}
// Types for PasswordMetaSubscriptionPayload
type PasswordMetaSubscriptionPayloadObject =
| PasswordMetaSubscriptionPayloadFields
| { name: 'mutation', args?: [] | false, alias?: string }
| { name: 'node', args?: [] | false, alias?: string }
| { name: 'updatedFields', args?: [] | false, alias?: string }
| { name: 'previousValues', args?: [] | false, alias?: string }
type PasswordMetaSubscriptionPayloadFields =
| 'mutation'
| 'node'
| 'updatedFields'
| 'previousValues'
export interface PasswordMetaSubscriptionPayloadFieldDetails {
mutation: {
type: 'MutationType'
args: {}
description: string
list: undefined
nullable: false
resolve: (
root: core.RootValue<"PasswordMetaSubscriptionPayload">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.MutationType> | prisma.MutationType
}
node: {
type: 'PasswordMeta'
args: {}
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"PasswordMetaSubscriptionPayload">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMeta | null> | prisma.PasswordMeta | null
}
updatedFields: {
type: 'String'
args: {}
description: string
list: true
nullable: false
resolve: undefined
}
previousValues: {
type: 'PasswordMetaPreviousValues'
args: {}
description: string
list: undefined
nullable: true
resolve: (
root: core.RootValue<"PasswordMetaSubscriptionPayload">,
args: { } ,
context: core.GetGen<"context">,
info?: GraphQLResolveInfo
) => Promise<prisma.PasswordMetaPreviousValues | null> | prisma.PasswordMetaPreviousValues | null
}
}
// Types for PasswordMetaPreviousValues
type PasswordMetaPreviousValuesObject =
| PasswordMetaPreviousValuesFields
| { name: 'id', args?: [] | false, alias?: string }
| { name: 'createdAt', args?: [] | false, alias?: string }
| { name: 'updatedAt', args?: [] | false, alias?: string }
| { name: 'resetToken', args?: [] | false, alias?: string }
type PasswordMetaPreviousValuesFields =
| 'id'
| 'createdAt'
| 'updatedAt'
| 'resetToken'
export interface PasswordMetaPreviousValuesFieldDetails {
id: {
type: 'ID'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
createdAt: {
type: 'DateTime'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
updatedAt: {
type: 'DateTime'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
resetToken: {
type: 'String'
args: {}
description: string
list: undefined
nullable: false
resolve: undefined
}
}
export interface UserWhereUniqueInput {
id?: string | null
email?: string | null
}
export type UserWhereUniqueInputInputObject =
| Extract<keyof UserWhereUniqueInput, string>
| { name: 'id', alias?: string }
| { name: 'email', alias?: string }
export interface UserWhereInput {
id?: string | null
id_not?: string | null
id_in?: string[]
id_not_in?: string[]
id_lt?: string | null
id_lte?: string | null
id_gt?: string | null
id_gte?: string | null
id_contains?: string | null
id_not_contains?: string | null
id_starts_with?: string | null
id_not_starts_with?: string | null
id_ends_with?: string | null
id_not_ends_with?: string | null
createdAt?: string | null
createdAt_not?: string | null
createdAt_in?: string[]
createdAt_not_in?: string[]
createdAt_lt?: string | null
createdAt_lte?: string | null
createdAt_gt?: string | null
createdAt_gte?: string | null
updatedAt?: string | null
updatedAt_not?: string | null
updatedAt_in?: string[]
updatedAt_not_in?: string[]
updatedAt_lt?: string | null
updatedAt_lte?: string | null
updatedAt_gt?: string | null
updatedAt_gte?: string | null
email?: string | null
email_not?: string | null
email_in?: string[]
email_not_in?: string[]
email_lt?: string | null
email_lte?: string | null
email_gt?: string | null
email_gte?: string | null
email_contains?: string | null
email_not_contains?: string | null
email_starts_with?: string | null
email_not_starts_with?: string | null
email_ends_with?: string | null
email_not_ends_with?: string | null
password?: string | null
password_not?: string | null
password_in?: string[]
password_not_in?: string[]
password_lt?: string | null
password_lte?: string | null
password_gt?: string | null
password_gte?: string | null
password_contains?: string | null
password_not_contains?: string | null
password_starts_with?: string | null
password_not_starts_with?: string | null
password_ends_with?: string | null
password_not_ends_with?: string | null
role?: prisma.UserRole | null
role_not?: prisma.UserRole | null
role_in?: prisma.UserRole[]
role_not_in?: prisma.UserRole[]
firstName?: string | null
firstName_not?: string | null
firstName_in?: string[]
firstName_not_in?: string[]
firstName_lt?: string | null
firstName_lte?: string | null
firstName_gt?: string | null
firstName_gte?: string | null
firstName_contains?: string | null
firstName_not_contains?: string | null
firstName_starts_with?: string | null
firstName_not_starts_with?: string | null
firstName_ends_with?: string | null
firstName_not_ends_with?: string | null
lastName?: string | null
lastName_not?: string | null
lastName_in?: string[]
lastName_not_in?: string[]
lastName_lt?: string | null
lastName_lte?: string | null
lastName_gt?: string | null
lastName_gte?: string | null
lastName_contains?: string | null
lastName_not_contains?: string | null
lastName_starts_with?: string | null
lastName_not_starts_with?: string | null
lastName_ends_with?: string | null
lastName_not_ends_with?: string | null
phone?: string | null
phone_not?: string | null
phone_in?: string[]
phone_not_in?: string[]
phone_lt?: string | null
phone_lte?: string | null
phone_gt?: string | null
phone_gte?: string | null
phone_contains?: string | null
phone_not_contains?: string | null
phone_starts_with?: string | null
phone_not_starts_with?: string | null
phone_ends_with?: string | null
phone_not_ends_with?: string | null
passwordMeta?: PasswordMetaWhereInput | null
AND?: UserWhereInput[]
OR?: UserWhereInput[]
NOT?: UserWhereInput[]
}
export type UserWhereInputInputObject =
| Extract<keyof UserWhereInput, string>
| { name: 'id', alias?: string }
| { name: 'id_not', alias?: string }
| { name: 'id_in', alias?: string }
| { name: 'id_not_in', alias?: string }
| { name: 'id_lt', alias?: string }
| { name: 'id_lte', alias?: string }
| { name: 'id_gt', alias?: string }
| { name: 'id_gte', alias?: string }
| { name: 'id_contains', alias?: string }
| { name: 'id_not_contains', alias?: string }
| { name: 'id_starts_with', alias?: string }
| { name: 'id_not_starts_with', alias?: string }
| { name: 'id_ends_with', alias?: string }
| { name: 'id_not_ends_with', alias?: string }
| { name: 'createdAt', alias?: string }
| { name: 'createdAt_not', alias?: string }
| { name: 'createdAt_in', alias?: string }
| { name: 'createdAt_not_in', alias?: string }
| { name: 'createdAt_lt', alias?: string }
| { name: 'createdAt_lte', alias?: string }
| { name: 'createdAt_gt', alias?: string }
| { name: 'createdAt_gte', alias?: string }
| { name: 'updatedAt', alias?: string }
| { name: 'updatedAt_not', alias?: string }
| { name: 'updatedAt_in', alias?: string }
| { name: 'updatedAt_not_in', alias?: string }
| { name: 'updatedAt_lt', alias?: string }
| { name: 'updatedAt_lte', alias?: string }
| { name: 'updatedAt_gt', alias?: string }
| { name: 'updatedAt_gte', alias?: string }
| { name: 'email', alias?: string }
| { name: 'email_not', alias?: string }
| { name: 'email_in', alias?: string }
| { name: 'email_not_in', alias?: string }
| { name: 'email_lt', alias?: string }
| { name: 'email_lte', alias?: string }
| { name: 'email_gt', alias?: string }
| { name: 'email_gte', alias?: string }
| { name: 'email_contains', alias?: string }
| { name: 'email_not_contains', alias?: string }
| { name: 'email_starts_with', alias?: string }
| { name: 'email_not_starts_with', alias?: string }
| { name: 'email_ends_with', alias?: string }
| { name: 'email_not_ends_with', alias?: string }
| { name: 'password', alias?: string }
| { name: 'password_not', alias?: string }
| { name: 'password_in', alias?: string }
| { name: 'password_not_in', alias?: string }
| { name: 'password_lt', alias?: string }
| { name: 'password_lte', alias?: string }
| { name: 'password_gt', alias?: string }
| { name: 'password_gte', alias?: string }
| { name: 'password_contains', alias?: string }
| { name: 'password_not_contains', alias?: string }
| { name: 'password_starts_with', alias?: string }
| { name: 'password_not_starts_with', alias?: string }
| { name: 'password_ends_with', alias?: string }
| { name: 'password_not_ends_with', alias?: string }
| { name: 'role', alias?: string }
| { name: 'role_not', alias?: string }
| { name: 'role_in', alias?: string }
| { name: 'role_not_in', alias?: string }
| { name: 'firstName', alias?: string }
| { name: 'firstName_not', alias?: string }
| { name: 'firstName_in', alias?: string }
| { name: 'firstName_not_in', alias?: string }
| { name: 'firstName_lt', alias?: string }
| { name: 'firstName_lte', alias?: string }
| { name: 'firstName_gt', alias?: string }
| { name: 'firstName_gte', alias?: string }
| { name: 'firstName_contains', alias?: string }
| { name: 'firstName_not_contains', alias?: string }
| { name: 'firstName_starts_with', alias?: string }
| { name: 'firstName_not_starts_with', alias?: string }
| { name: 'firstName_ends_with', alias?: string }
| { name: 'firstName_not_ends_with', alias?: string }
| { name: 'lastName', alias?: string }
| { name: 'lastName_not', alias?: string }
| { name: 'lastName_in', alias?: string }
| { name: 'lastName_not_in', alias?: string }
| { name: 'lastName_lt', alias?: string }
| { name: 'lastName_lte', alias?: string }
| { name: 'lastName_gt', alias?: string }
| { name: 'lastName_gte', alias?: string }
| { name: 'lastName_contains', alias?: string }
| { name: 'lastName_not_contains', alias?: string }
| { name: 'lastName_starts_with', alias?: string }
| { name: 'lastName_not_starts_with', alias?: string }
| { name: 'lastName_ends_with', alias?: string }
| { name: 'lastName_not_ends_with', alias?: string }
| { name: 'phone', alias?: string }
| { name: 'phone_not', alias?: string }
| { name: 'phone_in', alias?: string }
| { name: 'phone_not_in', alias?: string }
| { name: 'phone_lt', alias?: string }
| { name: 'phone_lte', alias?: string }
| { name: 'phone_gt', alias?: string }
| { name: 'phone_gte', alias?: string }
| { name: 'phone_contains', alias?: string }
| { name: 'phone_not_contains', alias?: string }
| { name: 'phone_starts_with', alias?: string }
| { name: 'phone_not_starts_with', alias?: string }
| { name: 'phone_ends_with', alias?: string }
| { name: 'phone_not_ends_with', alias?: string }
| { name: 'passwordMeta', alias?: string }
| { name: 'AND', alias?: string }
| { name: 'OR', alias?: string }
| { name: 'NOT', alias?: string }
export interface PasswordMetaWhereInput {
id?: string | null
id_not?: string | null
id_in?: string[]
id_not_in?: string[]
id_lt?: string | null
id_lte?: string | null
id_gt?: string | null
id_gte?: string | null
id_contains?: string | null
id_not_contains?: string | null
id_starts_with?: string | null
id_not_starts_with?: string | null
id_ends_with?: string | null
id_not_ends_with?: string | null
createdAt?: string | null
createdAt_not?: string | null
createdAt_in?: string[]
createdAt_not_in?: string[]
createdAt_lt?: string | null
createdAt_lte?: string | null
createdAt_gt?: string | null
createdAt_gte?: string | null
updatedAt?: string | null
updatedAt_not?: string | null
updatedAt_in?: string[]
updatedAt_not_in?: string[]
updatedAt_lt?: string | null
updatedAt_lte?: string | null
updatedAt_gt?: string | null
updatedAt_gte?: string | null
resetToken?: string | null
resetToken_not?: string | null
resetToken_in?: string[]
resetToken_not_in?: string[]
resetToken_lt?: string | null
resetToken_lte?: string | null
resetToken_gt?: string | null
resetToken_gte?: string | null
resetToken_contains?: string | null
resetToken_not_contains?: string | null
resetToken_starts_with?: string | null
resetToken_not_starts_with?: string | null
resetToken_ends_with?: string | null
resetToken_not_ends_with?: string | null
AND?: PasswordMetaWhereInput[]
OR?: PasswordMetaWhereInput[]
NOT?: PasswordMetaWhereInput[]
}
export type PasswordMetaWhereInputInputObject =
| Extract<keyof PasswordMetaWhereInput, string>
| { name: 'id', alias?: string }
| { name: 'id_not', alias?: string }
| { name: 'id_in', alias?: string }
| { name: 'id_not_in', alias?: string }
| { name: 'id_lt', alias?: string }
| { name: 'id_lte', alias?: string }
| { name: 'id_gt', alias?: string }
| { name: 'id_gte', alias?: string }
| { name: 'id_contains', alias?: string }
| { name: 'id_not_contains', alias?: string }
| { name: 'id_starts_with', alias?: string }
| { name: 'id_not_starts_with', alias?: string }
| { name: 'id_ends_with', alias?: string }
| { name: 'id_not_ends_with', alias?: string }
| { name: 'createdAt', alias?: string }
| { name: 'createdAt_not', alias?: string }
| { name: 'createdAt_in', alias?: string }
| { name: 'createdAt_not_in', alias?: string }
| { name: 'createdAt_lt', alias?: string }
| { name: 'createdAt_lte', alias?: string }
| { name: 'createdAt_gt', alias?: string }
| { name: 'createdAt_gte', alias?: string }
| { name: 'updatedAt', alias?: string }
| { name: 'updatedAt_not', alias?: string }
| { name: 'updatedAt_in', alias?: string }
| { name: 'updatedAt_not_in', alias?: string }
| { name: 'updatedAt_lt', alias?: string }
| { name: 'updatedAt_lte', alias?: string }
| { name: 'updatedAt_gt', alias?: string }
| { name: 'updatedAt_gte', alias?: string }
| { name: 'resetToken', alias?: string }
| { name: 'resetToken_not', alias?: string }
| { name: 'resetToken_in', alias?: string }
| { name: 'resetToken_not_in', alias?: string }
| { name: 'resetToken_lt', alias?: string }
| { name: 'resetToken_lte', alias?: string }
| { name: 'resetToken_gt', alias?: string }
| { name: 'resetToken_gte', alias?: string }
| { name: 'resetToken_contains', alias?: string }
| { name: 'resetToken_not_contains', alias?: string }
| { name: 'resetToken_starts_with', alias?: string }
| { name: 'resetToken_not_starts_with', alias?: string }
| { name: 'resetToken_ends_with', alias?: string }
| { name: 'resetToken_not_ends_with', alias?: string }
| { name: 'AND', alias?: string }
| { name: 'OR', alias?: string }
| { name: 'NOT', alias?: string }
export interface PasswordMetaWhereUniqueInput {
id?: string | null
}
export type PasswordMetaWhereUniqueInputInputObject =
| Extract<keyof PasswordMetaWhereUniqueInput, string>
| { name: 'id', alias?: string }
export interface UserCreateInput {
id?: string | null
email?: string
password?: string
role?: prisma.UserRole | null
firstName?: string | null
lastName?: string | null
phone?: string | null
passwordMeta?: PasswordMetaCreateOneInput | null
}
export type UserCreateInputInputObject =
| Extract<keyof UserCreateInput, string>
| { name: 'id', alias?: string }
| { name: 'email', alias?: string }
| { name: 'password', alias?: string }
| { name: 'role', alias?: string }
| { name: 'firstName', alias?: string }
| { name: 'lastName', alias?: string }
| { name: 'phone', alias?: string }
| { name: 'passwordMeta', alias?: string }
export interface PasswordMetaCreateOneInput {
create?: PasswordMetaCreateInput | null
connect?: PasswordMetaWhereUniqueInput | null
}
export type PasswordMetaCreateOneInputInputObject =
| Extract<keyof PasswordMetaCreateOneInput, string>
| { name: 'create', alias?: string }
| { name: 'connect', alias?: string }
export interface PasswordMetaCreateInput {
id?: string | null
resetToken?: string
}
export type PasswordMetaCreateInputInputObject =
| Extract<keyof PasswordMetaCreateInput, string>
| { name: 'id', alias?: string }
| { name: 'resetToken', alias?: string }
export interface UserUpdateInput {
email?: string | null
password?: string | null
role?: prisma.UserRole | null
firstName?: string | null
lastName?: string | null
phone?: string | null
passwordMeta?: PasswordMetaUpdateOneInput | null
}
export type UserUpdateInputInputObject =
| Extract<keyof UserUpdateInput, string>
| { name: 'email', alias?: string }
| { name: 'password', alias?: string }
| { name: 'role', alias?: string }
| { name: 'firstName', alias?: string }
| { name: 'lastName', alias?: string }
| { name: 'phone', alias?: string }
| { name: 'passwordMeta', alias?: string }
export interface PasswordMetaUpdateOneInput {
create?: PasswordMetaCreateInput | null
update?: PasswordMetaUpdateDataInput | null
upsert?: PasswordMetaUpsertNestedInput | null
delete?: boolean | null
disconnect?: boolean | null
connect?: PasswordMetaWhereUniqueInput | null
}
export type PasswordMetaUpdateOneInputInputObject =
| Extract<keyof PasswordMetaUpdateOneInput, string>
| { name: 'create', alias?: string }
| { name: 'update', alias?: string }
| { name: 'upsert', alias?: string }
| { name: 'delete', alias?: string }
| { name: 'disconnect', alias?: string }
| { name: 'connect', alias?: string }
export interface PasswordMetaUpdateDataInput {
resetToken?: string | null
}
export type PasswordMetaUpdateDataInputInputObject =
| Extract<keyof PasswordMetaUpdateDataInput, string>
| { name: 'resetToken', alias?: string }
export interface PasswordMetaUpsertNestedInput {
update?: PasswordMetaUpdateDataInput
create?: PasswordMetaCreateInput
}
export type PasswordMetaUpsertNestedInputInputObject =
| Extract<keyof PasswordMetaUpsertNestedInput, string>
| { name: 'update', alias?: string }
| { name: 'create', alias?: string }
export interface UserUpdateManyMutationInput {
email?: string | null
password?: string | null
role?: prisma.UserRole | null
firstName?: string | null
lastName?: string | null
phone?: string | null
}
export type UserUpdateManyMutationInputInputObject =
| Extract<keyof UserUpdateManyMutationInput, string>
| { name: 'email', alias?: string }
| { name: 'password', alias?: string }
| { name: 'role', alias?: string }
| { name: 'firstName', alias?: string }
| { name: 'lastName', alias?: string }
| { name: 'phone', alias?: string }
export interface PasswordMetaUpdateInput {
resetToken?: string | null
}
export type PasswordMetaUpdateInputInputObject =
| Extract<keyof PasswordMetaUpdateInput, string>
| { name: 'resetToken', alias?: string }
export interface PasswordMetaUpdateManyMutationInput {
resetToken?: string | null
}
export type PasswordMetaUpdateManyMutationInputInputObject =
| Extract<keyof PasswordMetaUpdateManyMutationInput, string>
| { name: 'resetToken', alias?: string }
export interface UserSubscriptionWhereInput {
mutation_in?: prisma.MutationType[]
updatedFields_contains?: string | null
updatedFields_contains_every?: string[]
updatedFields_contains_some?: string[]
node?: UserWhereInput | null
AND?: UserSubscriptionWhereInput[]
OR?: UserSubscriptionWhereInput[]
NOT?: UserSubscriptionWhereInput[]
}
export type UserSubscriptionWhereInputInputObject =
| Extract<keyof UserSubscriptionWhereInput, string>
| { name: 'mutation_in', alias?: string }
| { name: 'updatedFields_contains', alias?: string }
| { name: 'updatedFields_contains_every', alias?: string }
| { name: 'updatedFields_contains_some', alias?: string }
| { name: 'node', alias?: string }
| { name: 'AND', alias?: string }
| { name: 'OR', alias?: string }
| { name: 'NOT', alias?: string }
export interface PasswordMetaSubscriptionWhereInput {
mutation_in?: prisma.MutationType[]
updatedFields_contains?: string | null
updatedFields_contains_every?: string[]
updatedFields_contains_some?: string[]
node?: PasswordMetaWhereInput | null
AND?: PasswordMetaSubscriptionWhereInput[]
OR?: PasswordMetaSubscriptionWhereInput[]
NOT?: PasswordMetaSubscriptionWhereInput[]
}
export type PasswordMetaSubscriptionWhereInputInputObject =
| Extract<keyof PasswordMetaSubscriptionWhereInput, string>
| { name: 'mutation_in', alias?: string }
| { name: 'updatedFields_contains', alias?: string }
| { name: 'updatedFields_contains_every', alias?: string }
| { name: 'updatedFields_contains_some', alias?: string }
| { name: 'node', alias?: string }
| { name: 'AND', alias?: string }
| { name: 'OR', alias?: string }
| { name: 'NOT', alias?: string }
export type UserRoleValues =
| 'USER'
| 'ADMIN'
export type UserOrderByInputValues =
| 'id_ASC'
| 'id_DESC'
| 'createdAt_ASC'
| 'createdAt_DESC'
| 'updatedAt_ASC'
| 'updatedAt_DESC'
| 'email_ASC'
| 'email_DESC'
| 'password_ASC'
| 'password_DESC'
| 'role_ASC'
| 'role_DESC'
| 'firstName_ASC'
| 'firstName_DESC'
| 'lastName_ASC'
| 'lastName_DESC'
| 'phone_ASC'
| 'phone_DESC'
export type PasswordMetaOrderByInputValues =
| 'id_ASC'
| 'id_DESC'
| 'createdAt_ASC'
| 'createdAt_DESC'
| 'updatedAt_ASC'
| 'updatedAt_DESC'
| 'resetToken_ASC'
| 'resetToken_DESC'
export type MutationTypeValues =
| 'CREATED'
| 'UPDATED'
| 'DELETED' | the_stack |
import { DocumentColorProvider, TextDocument, CancellationToken, Range, Color, ColorPresentation, TextEdit, ColorInformation } from "vscode";
import { getCssRanges, isInCfOutput } from "../utils/contextUtil";
import { getDocumentStateContext, DocumentStateContext } from "../utils/documentUtil";
import { cssPropertyPattern } from "../entities/css/property";
import { cssDataManager, cssColors } from "../entities/css/languageFacts";
import { IPropertyData } from "../entities/css/cssLanguageTypes";
const rgbHexPattern = /#?#([0-9A-F]{3,4}|[0-9A-F]{6}|[0-9A-F]{8})\b/gi;
const rgbFuncPattern = /\brgba?\s*\(\s*([0-9%.]+)\s*,?\s*([0-9%.]+)\s*,?\s*([0-9%.]+)(?:\s*(?:,|\/)?\s*([0-9%.]+)\s*)?\)/gi;
const hslFuncPattern = /\bhsla?\s*\(\s*([0-9.]+)(deg|rad|grad|turn)?\s*,?\s*([0-9%.]+)\s*,?\s*([0-9%.]+)(?:\s*(?:,|\/)?\s*([0-9%.]+)\s*)?\)/gi;
const colorKeywordPattern = new RegExp(`(^|\\s+)(${Object.keys(cssColors).join("|")})(?:\\s+|$)`, "gi");
export default class CFMLDocumentColorProvider implements DocumentColorProvider {
/**
* Provide colors for the given document.
* @param document The document for which to provide the colors
* @param _token A cancellation token
*/
public async provideDocumentColors(document: TextDocument, _token: CancellationToken): Promise<ColorInformation[]> {
let result: ColorInformation[] = [];
const documentStateContext: DocumentStateContext = getDocumentStateContext(document);
const cssRanges: Range[] = getCssRanges(documentStateContext);
for (const cssRange of cssRanges) {
const rangeTextOffset: number = document.offsetAt(cssRange.start);
const rangeText: string = documentStateContext.sanitizedDocumentText.slice(rangeTextOffset, document.offsetAt(cssRange.end));
let propertyMatch: RegExpExecArray;
while (propertyMatch = cssPropertyPattern.exec(rangeText)) {
const propertyValuePrefix: string = propertyMatch[1];
const propertyName: string = propertyMatch[2];
const propertyValue: string = propertyMatch[3];
if (!cssDataManager.isKnownProperty(propertyName)) {
continue;
}
const cssProperty: IPropertyData = cssDataManager.getProperty(propertyName);
if (cssProperty.restrictions && cssProperty.restrictions.includes("color")) {
let colorMatch: RegExpExecArray;
// RGB hex
while (colorMatch = rgbHexPattern.exec(propertyValue)) {
const rgbHexValue: string = colorMatch[1];
const colorRange: Range = new Range(
document.positionAt(rangeTextOffset + propertyMatch.index + propertyValuePrefix.length + colorMatch.index),
document.positionAt(rangeTextOffset + propertyMatch.index + propertyValuePrefix.length + colorMatch.index + colorMatch[0].length)
);
result.push(new ColorInformation(colorRange, hexToColor(rgbHexValue)));
}
// RGB function
while (colorMatch = rgbFuncPattern.exec(propertyValue)) {
const r: string = colorMatch[1];
const g: string = colorMatch[2];
const b: string = colorMatch[3];
const a: string = colorMatch[4];
const colorRange: Range = new Range(
document.positionAt(rangeTextOffset + propertyMatch.index + propertyValuePrefix.length + colorMatch.index),
document.positionAt(rangeTextOffset + propertyMatch.index + propertyValuePrefix.length + colorMatch.index + colorMatch[0].length)
);
let red: number = r.includes("%") ? Number.parseFloat(r) / 100 : Number.parseInt(r) / 255;
let green: number = g.includes("%") ? Number.parseInt(g) / 100 : Number.parseFloat(g) / 255;
let blue: number = b.includes("%") ? Number.parseInt(b) / 100 : Number.parseFloat(b) / 255;
let alpha: number;
if (a) {
alpha = a.includes("%") ? Number.parseFloat(a) / 100 : Number.parseFloat(a);
} else {
alpha = 1;
}
result.push(new ColorInformation(colorRange, new Color(red, green, blue, alpha)));
}
// HSL function
while (colorMatch = hslFuncPattern.exec(propertyValue)) {
const h: string = colorMatch[1];
const hUnit: string = colorMatch[2];
const s: string = colorMatch[3];
const l: string = colorMatch[4];
const a: string = colorMatch[5];
const colorRange: Range = new Range(
document.positionAt(rangeTextOffset + propertyMatch.index + propertyValuePrefix.length + colorMatch.index),
document.positionAt(rangeTextOffset + propertyMatch.index + propertyValuePrefix.length + colorMatch.index + colorMatch[0].length)
);
let hue: number = Number.parseFloat(h);
let sat: number = Number.parseFloat(s);
let light: number = Number.parseFloat(l);
let alpha: number;
if (a) {
alpha = a.includes("%") ? Number.parseFloat(a) / 100 : Number.parseFloat(a);
} else {
alpha = 1;
}
const hueUnit = hUnit ? hUnit as "deg" | "rad" | "grad" | "turn" : "deg";
result.push(new ColorInformation(colorRange, colorFromHSL({ h: hue, s: sat, l: light, a: alpha }, hueUnit)));
}
// Color keywords
while (colorMatch = colorKeywordPattern.exec(propertyValue)) {
const keywordPrefix: string = colorMatch[1];
const colorKeyword: string = colorMatch[2].toLowerCase();
const colorRange: Range = new Range(
document.positionAt(rangeTextOffset + propertyMatch.index + propertyValuePrefix.length + colorMatch.index + keywordPrefix.length),
document.positionAt(rangeTextOffset + propertyMatch.index + propertyValuePrefix.length + colorMatch.index + keywordPrefix.length + colorKeyword.length)
);
result.push(new ColorInformation(colorRange, hexToColor(cssColors[colorKeyword])));
}
}
}
}
return result;
}
/**
* Provide representations for a color.
* @param color The color to show and insert
* @param context A context object with additional information
* @param _token A cancellation token
*/
public async provideColorPresentations(color: Color, context: { document: TextDocument, range: Range }, _token: CancellationToken | boolean): Promise<ColorPresentation[]> {
let result: ColorPresentation[] = [];
let red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
let label: string;
if (color.alpha === 1) {
label = `rgb(${red256}, ${green256}, ${blue256})`;
} else {
label = `rgba(${red256}, ${green256}, ${blue256}, ${color.alpha})`;
}
result.push({ label: label, textEdit: TextEdit.replace(context.range, label) });
const documentStateContext: DocumentStateContext = getDocumentStateContext(context.document);
const hexPrefix = isInCfOutput(documentStateContext, context.range.start) ? "##" : "#";
if (color.alpha === 1) {
label = `${hexPrefix}${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}`;
} else {
label = `${hexPrefix}${toTwoDigitHex(red256)}${toTwoDigitHex(green256)}${toTwoDigitHex(blue256)}${toTwoDigitHex(Math.round(color.alpha * 255))}`;
}
result.push({ label: label, textEdit: TextEdit.replace(context.range, label) });
const hsl = hslFromColor(color);
if (hsl.a === 1) {
label = `hsl(${hsl.h}, ${Math.round(hsl.s * 100)}%, ${Math.round(hsl.l * 100)}%)`;
} else {
label = `hsla(${hsl.h}, ${Math.round(hsl.s * 100)}%, ${Math.round(hsl.l * 100)}%, ${hsl.a})`;
}
result.push({ label: label, textEdit: TextEdit.replace(context.range, label) });
return result;
}
}
function toTwoDigitHex(n: number): string {
const r = n.toString(16);
return r.length !== 2 ? "0" + r : r;
}
function fromTwoDigitHex(hex: string): number {
return Number.parseInt(hex, 16);
}
function hexToColor(rgbHex: string): Color {
rgbHex = rgbHex.replace(/#/g, "");
let red: number;
let green: number;
let blue: number;
let alpha: number;
if (rgbHex.length === 3 || rgbHex.length === 4) {
red = fromTwoDigitHex(rgbHex.substr(0, 1).repeat(2)) / 255;
green = fromTwoDigitHex(rgbHex.substr(1, 1).repeat(2)) / 255;
blue = fromTwoDigitHex(rgbHex.substr(2, 1).repeat(2)) / 255;
alpha = rgbHex.length === 4 ? fromTwoDigitHex(rgbHex.substr(3, 1).repeat(2)) / 255 : 1;
} else if (rgbHex.length === 6 || rgbHex.length === 8) {
red = fromTwoDigitHex(rgbHex.substr(0, 2)) / 255;
green = fromTwoDigitHex(rgbHex.substr(2, 2)) / 255;
blue = fromTwoDigitHex(rgbHex.substr(4, 2)) / 255;
alpha = rgbHex.length === 8 ? fromTwoDigitHex(rgbHex.substr(6, 2)) / 255 : 1;
} else {
return undefined;
}
return new Color(red, green, blue, alpha);
}
interface HSLA { h: number; s: number; l: number; a: number; }
function hslFromColor(rgba: Color): HSLA {
const r = rgba.red;
const g = rgba.green;
const b = rgba.blue;
const a = rgba.alpha;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h = 0;
let s = 0;
const l = (min + max) / 2;
const chroma = max - min;
if (chroma > 0) {
s = Math.min((l <= 0.5 ? chroma / (2 * l) : chroma / (2 - (2 * l))), 1);
switch (max) {
case r: h = (g - b) / chroma + (g < b ? 6 : 0); break;
case g: h = (b - r) / chroma + 2; break;
case b: h = (r - g) / chroma + 4; break;
}
h *= 60;
h = Math.round(h);
}
return { h, s, l, a };
}
/**
* Converts HSLA values into `Color`
* @param hsla The hue, saturation, lightness, and alpha values. Hue is in units based on `hueUnit`. Saturation and lightness are percentages.
* @param hueUnit One of deg, rad, grad, turn
*/
function colorFromHSL(hsla: HSLA, hueUnit: "deg" | "rad" | "grad" | "turn" = "deg"): Color {
let hue: number;
switch (hueUnit) {
case "deg": hue = hsla.h / 60.0; break;
case "rad": hue = hsla.h * 3 / Math.PI; break;
case "grad": hue = hsla.h * 6 / 400; break;
case "turn": hue = hsla.h * 6; break;
}
const sat = hsla.s / 100;
const light = hsla.l / 100;
if (sat === 0) {
return new Color(light, light, light, hsla.a);
} else {
const hueToRgb = (t1: number, t2: number, h: number) => {
while (h < 0) { h += 6; }
while (h >= 6) { h -= 6; }
if (h < 1) { return (t2 - t1) * h + t1; }
if (h < 3) { return t2; }
if (h < 4) { return (t2 - t1) * (4 - h) + t1; }
return t1;
};
const t2 = light <= 0.5 ? (light * (sat + 1)) : (light + sat - (light * sat));
const t1 = light * 2 - t2;
return new Color(hueToRgb(t1, t2, hue + 2), hueToRgb(t1, t2, hue), hueToRgb(t1, t2, hue - 2), hsla.a);
}
} | the_stack |
import {HttpClient} from "@angular/common/http";
import {Component, Inject, Input, OnChanges, OnInit, SimpleChanges, ViewChild} from "@angular/core";
import {FormControl, FormGroup, ValidationErrors, Validators} from "@angular/forms";
import {MatAutocompleteSelectedEvent, MatAutocompleteTrigger} from "@angular/material/autocomplete";
import {MatDialog, MatDialogRef} from "@angular/material/dialog";
import {ProcessorRef, Property} from "@kylo/feed";
import {Observable} from "rxjs/Observable";
import {of} from "rxjs/observable/of";
import {catchError} from "rxjs/operators/catchError";
import {debounceTime} from "rxjs/operators/debounceTime";
import {distinctUntilChanged} from "rxjs/operators/distinctUntilChanged";
import {filter} from "rxjs/operators/filter";
import {map} from "rxjs/operators/map";
import {skip} from "rxjs/operators/skip";
import {switchMap} from "rxjs/operators/switchMap";
import {DescribeTableDialogComponent} from "./describe-table-dialog.component";
export class TableRef {
constructor(readonly fullName: string) {
}
get fullNameLower(): string {
return this.fullName.toLowerCase();
}
get schema(): string {
return this.fullName.substr(0, this.fullName.indexOf("."));
}
get tableName(): string {
return this.fullName.substr(this.fullName.indexOf(".") + 1);
}
}
@Component({
selector: "thinkbig-get-table-data-properties",
styleUrls: ["./table-properties.component.css"],
templateUrl: "./table-properties.component.html"
})
export class TablePropertiesComponent implements OnChanges, OnInit {
@Input()
connectionServiceKey: any;
@Input()
incrementalPropertyKey: any;
@Input()
loadStrategyKey: any;
/**
* Load strategies either passed in via the directive, or defaulted
*/
@Input()
loadStrategyOptions: any;
@Input()
processor: ProcessorRef;
@Input()
renderLoadStrategyOptions: any;
@Input()
useTableNameOnly = false;
readonly ARCHIVE_UNIT_PROPERTY_KEY = 'Minimum Time Unit';
readonly RETENTION_PERIOD_PROPERTY_KEY = 'Backoff Period';
readonly SOURCE_TABLE_PROPERTY_KEY = 'Source Table';
readonly SOURCE_FIELDS_PROPERTY_KEY = 'Source Fields';
/**
* Cache of the Table objects returned from the initial autocomplete call out
*/
allTables = {};
archiveUnitProperty: any;
/**
* Flag to indicate if the controller service has connection errors.
* if there are errors the UI will display input boxes for the user to defin the correct table name
*/
databaseConnectionError = false;
databaseConnectionErrorObject: any;
dbConnectionProperty: any;
deleteSourceProperty: any;
defaultLoadStrategyValue = 'INCREMENTAL';
describingTableSchema = false;
fieldsProperty: any;
filteredFieldDates: any = [];
form = new FormGroup({});
incrementalFieldProperty: any;
/**
* boolean flag to indicate we are initializing the controller
*/
initializing = true;
loadStrategyProperty: any;
model: any;
nonCustomProperties: any[];
/**
* property that stores the selected table fields and maps it to the hive table schema
*/
originalTableFields: any = [];
outputTypeProperty: any;
restrictIncrementalToDateOnly: boolean;
retentionPeriodProperty: any;
/**
* The object storing the table selected via the autocomplete
*/
selectedTable: any = null;
@ViewChild("tableAutoInput", {read: MatAutocompleteTrigger})
tableAutoTrigger: MatAutocompleteTrigger;
tableControl = new FormControl(null, [
Validators.required,
() => this.validate()
]);
tableItems: Observable<any[]>;
/**
* Cache of the fields related to the table selected
* This is used the the dropdown when showing the fields for the incremtal options
*/
tableFields: any = [];
tableFieldsDirty: boolean;
tableProperty: any;
/**
* The table Schema, parsed from the table autocomplete
*/
tableSchema: any = null;
catalogNiFiControllerServiceIds:string[] = null;
initialized:boolean = false;
constructor(private http: HttpClient, private dialog: MatDialog, @Inject("FeedService") private feedService: any, @Inject("DBCPTableSchemaService") private tableSchemaService: any) {
// Handle connection service changes
this.form.valueChanges.pipe(
filter(() => this.processor != null && this.processor.form.enabled),
map(value => (this.dbConnectionProperty != null) ? value[this.dbConnectionProperty.nameKey] : null),
filter(value => typeof value !== "undefined" && value != null),
distinctUntilChanged(),
skip(1)
).subscribe(() => this.onDbConnectionPropertyChanged());
// Handle output type changes
this.form.valueChanges.pipe(
filter(() => this.processor != null && this.processor.form.enabled),
map(value => (this.outputTypeProperty != null) ? value[this.outputTypeProperty.nameKey] : null),
filter(value => typeof value !== "undefined" && value != null),
distinctUntilChanged()
).subscribe(value => {
if (value == 'AVRO') {
this.model.table.feedFormat = 'STORED AS AVRO'
} else if (value == 'DELIMITED') {
this.model.table.feedFormat = this.feedService.getNewCreateFeedModel().table.feedFormat
}
});
// Add table control
this.form.addControl("table", this.tableControl);
this.tableItems = this.tableControl.valueChanges.pipe(
filter(value => value != null && value.length >= 2),
debounceTime(300),
switchMap(value => {
this.selectedTable = value;
return this.queryTablesSearch(value)
})
);
this.fetchCatalogJbdcSources();
}
updateDbConnectionPropertyOptions(){
if(this.dbConnectionProperty && this.catalogNiFiControllerServiceIds != null){
(this.dbConnectionProperty.propertyDescriptor.allowableValues as any[])
.filter((allowableValue: any) => allowableValue.displayName.indexOf("**") == -1 && this.catalogNiFiControllerServiceIds.indexOf(allowableValue.value) >=0)
.forEach((allowableValue:any) => {
allowableValue.catalogSource = true;
allowableValue.origName = allowableValue.displayName;
allowableValue.displayName +="**";
});
}
}
ngOnInit() {
if (typeof this.loadStrategyOptions === "undefined") {
this.loadStrategyOptions = [
{name: 'Full Load', type: 'SNAPSHOT', strategy: 'FULL_LOAD', hint: 'Replace entire table'},
{name: 'Incremental', type: 'DELTA', strategy: 'INCREMENTAL', hint: 'Incremental load based on a high watermark', incremental: true, restrictDates: true}
];
}
/**
* Default the property keys that are used to look up the
*/
if (typeof this.connectionServiceKey === "undefined") {
this.connectionServiceKey = 'Source Database Connection';
}
if (typeof this.loadStrategyKey === "undefined") {
this.loadStrategyKey = 'Load Strategy';
}
if (typeof this.incrementalPropertyKey === "undefined") {
this.incrementalPropertyKey = 'Date Field';
}
this.dbConnectionProperty = this.findProperty(this.connectionServiceKey, false);
//update the hint only when editing
const hintSuffix = " ** Indicates an existing catalog data source";
if(this.dbConnectionProperty) {
let desc = this.dbConnectionProperty.propertyDescriptor.origDescription || this.dbConnectionProperty.propertyDescriptor.description;
if (!this.processor.form.disabled) {
if(desc != undefined && desc.indexOf(hintSuffix) == -1){
this.dbConnectionProperty.propertyDescriptor.origDescription = desc;
this.dbConnectionProperty.propertyDescriptor.description = desc+hintSuffix;
}
else if (desc == undefined || desc == null){
this.dbConnectionProperty.propertyDescriptor.description = hintSuffix;
}
} else if(desc != undefined){
this.dbConnectionProperty.propertyDescriptor.description = desc;
}
}
/**
* Autocomplete objected used in the UI html page
*/
if (this.dbConnectionProperty.value == null) {
this.tableControl.disable();
}
/**
* lookup and find the respective Nifi Property objects that map to the custom property keys
*/
this.initPropertyLookup();
this.nonCustomProperties = this.processor.processor.properties.filter((property: any) => !this.isCustomProperty(property));
/**
* if we are editing or working with the cloned feed then get the selectedTable saved on this model.
*/
this.initializeAutoComplete();
if (this.processor.form.enabled) {
if (this.model.cloned == true) {
//if we are cloning and creating a new feed setup the autocomplete
this.setupClonedFeedTableFields();
} else {
this.editIncrementalLoadDescribeTable()
}
}
this.updateDbConnectionPropertyOptions();
this.initializing = false;
}
fetchCatalogJbdcSources(){
let url = "/proxy/v1/catalog/datasource/plugin-id?pluginIds=jdbc";
this.http.get(url).subscribe((responses:any[]) => {
this.catalogNiFiControllerServiceIds = responses.map((source:any) => source.nifiControllerServiceId);
this.updateDbConnectionPropertyOptions();
this.initialized = true;
},(error1:any) => this.initialized = true);
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.processor) {
if (this.processor != null) {
this.model = this.processor.feed;
this.processor.control = this.form;
} else {
this.model = null;
}
}
}
/**
* If there is a LOAD_STRATEGY property then watch for changes to show/hide additional options
*/
onLoadStrategyChange() {
let newVal = this.loadStrategyProperty.value;
this.loadStrategyProperty.displayValue = newVal;
if (newVal == 'FULL_LOAD') {
this.model.table.tableType = 'SNAPSHOT';
this.restrictIncrementalToDateOnly = false;
} else if (this.isIncrementalLoadStrategy(newVal)) {
this.model.table.tableType = 'DELTA';
//reset the date field
this.model.table.sourceTableIncrementalDateField = '';
let option = this.loadStrategyOptions.find((opt: any) => opt.strategy == newVal);
if (option) {
this.restrictIncrementalToDateOnly = option.restrictDates != undefined ? option.restrictDates : false;
}
this.editIncrementalLoadDescribeTable();
}
}
// TODO setupClonedFeedTableFields()
getTableName(table?: TableRef): string {
return table ? table.fullName : null;
}
/**
* lookup and find the respective Nifi Property objects that map to the custom property keys
*/
private initPropertyLookup() {
this.tableProperty = this.findProperty(this.SOURCE_TABLE_PROPERTY_KEY);
this.fieldsProperty = this.findProperty(this.SOURCE_FIELDS_PROPERTY_KEY);
this.loadStrategyProperty = this.findProperty(this.loadStrategyKey);
if (this.loadStrategyProperty && (this.loadStrategyProperty.value == null || this.loadStrategyProperty.value == undefined)) {
this.loadStrategyProperty.value = this.defaultLoadStrategyValue;
}
this.retentionPeriodProperty = this.findProperty(this.RETENTION_PERIOD_PROPERTY_KEY);
this.archiveUnitProperty = this.findProperty(this.ARCHIVE_UNIT_PROPERTY_KEY);
this.deleteSourceProperty = {value: 'false', key: 'Delete Source'};
this.incrementalFieldProperty = this.findProperty(this.incrementalPropertyKey);
this.outputTypeProperty = this.findProperty('Output Type');
}
/**
* Check to see if the property is in the list of custom ones.
* if so it will bypass the nifi-property directive for rendering
*/
isCustomProperty(property: any) {
let customPropertyKeys = [this.connectionServiceKey, this.SOURCE_TABLE_PROPERTY_KEY, this.SOURCE_FIELDS_PROPERTY_KEY, this.loadStrategyKey, this.incrementalPropertyKey, this.RETENTION_PERIOD_PROPERTY_KEY, this.ARCHIVE_UNIT_PROPERTY_KEY];
return customPropertyKeys.findIndex(value => value == property.key) != -1;
}
/**
* Determine if the incoming value or if the current selected LoadStrategy is of type incremental
* Incremental properties need additional option to define the field used for incrementing
*/
isIncrementalLoadStrategy(val?: any) {
let checkValue = val;
if (typeof checkValue === "undefined" || val === null) {
checkValue = (this.loadStrategyProperty) ? this.loadStrategyProperty.value : undefined;
}
return checkValue && this.loadStrategyOptions.find((v: any) => v.strategy == checkValue && v.incremental == true);
}
/**
* Watch for changes on the table to refresh the schema
*/
onTableSelected(event: MatAutocompleteSelectedEvent) {
this.selectedTable = event.option.value;
if (this.tableProperty && this.tableControl.value != null) {
let needsDescribe = (!this.model.cloned || this.model.table.feedDefinitionTableSchema.fields.length == 0);
if (this.useTableNameOnly) {
needsDescribe = needsDescribe || (this.model.cloned && this.tableProperty.value != this.tableControl.value.tableName);
this.tableProperty.value = this.tableControl.value.tableName;
} else {
needsDescribe = needsDescribe || (this.model.cloned && this.tableProperty.value != this.tableControl.value.fullName);
this.tableProperty.value = this.tableControl.value.fullName;
}
if (this.processor.form.enabled) {
//only describe on the Create as the Edit will be disabled and we dont want to change the field data.
//If we are working with a cloned feed we should attempt to get the field information from the cloned model
if (needsDescribe) {
this.describeTable();
}
}
}
}
private setupClonedFeedTableFields() {
this.databaseConnectionError = false;
this.tableSchema = this.model.table.feedDefinitionTableSchema;
this.tableFields = this.tableSchema.fields;
this.originalTableFields = this.model.table.sourceTableSchema;
this.tableFieldsDirty = false;
// FeedService.setTableFields(this.tableSchema.fields);
this.model.table.method = 'EXISTING_TABLE';
}
/**
* Change listener when the user changes the controller service in the UI
*/
private onDbConnectionPropertyChanged(): void {
this.selectedTable = undefined;
this.tableControl.setValue(null);
this.model.table.sourceTableIncrementalDateField = null;
this.databaseConnectionError = false;
}
/**
* Finds the correct NiFi processor Property associated with the incoming key.
*/
private findProperty(key: string, clone: boolean = false): Property {
//get all the props for this input
let matchingProperty = this.processor.processor.allProperties.find((property: any) => property.key == key);
//on edit mode the model only has the props saved for that type.
//need to find the prop associated against the other input type
if ((matchingProperty == undefined || matchingProperty == null) && this.model.allInputProcessorProperties != undefined) {
var props = this.model.allInputProcessorProperties[(this.processor.processor as any).processorId];
if (props) {
matchingProperty = props.find((property: any) => property.key == key);
}
}
if (matchingProperty == null) {
// console.log('UNABLE TO GET MATCHING PROPERTY FOR ',key,'model ',this.model, this.processor)
} else {
if (clone) {
return {...matchingProperty};
}
}
return matchingProperty;
}
/**
* match query term case insensitive
*/
private createFilterForTable(query: string) {
var lowercaseQuery = query.toLowerCase();
return function filterFn(item: any) {
return (item.fullNameLower.indexOf(lowercaseQuery) != -1);
};
}
/**
* return the list of tables for the selected Service ID
*/
private queryTablesSearch(query: string): Observable<any[]> {
if (this.dbConnectionProperty == null || this.dbConnectionProperty.value == null || this.dbConnectionProperty.value == "") {
return of([]);
} else if (this.dbConnectionProperty in this.allTables) {
return query ? this.allTables[this.dbConnectionProperty].filter(this.createFilterForTable(query)) : [];
} else {
let httpOptions: any = {params: {tableName: (query != null) ? "%" + query + "%" : "%"}};
if (Array.isArray(this.dbConnectionProperty.propertyDescriptor.allowableValues)) {
const service = (this.dbConnectionProperty.propertyDescriptor.allowableValues as any[])
.find((allowableValue: any) => allowableValue.value == this.dbConnectionProperty);
if (typeof service !== "undefined") {
let name = service.displayName;
if(service.catalogSource && service.origName){
name = service.origName;
}
httpOptions.params.serviceName = name
}
}
return this.http.get(this.tableSchemaService.LIST_TABLES_URL(this.dbConnectionProperty.value), httpOptions).pipe(
catchError((error: any) => {
return Observable.throw(error);
}),
map((data: any) => {
if (Array.isArray(data)) {
return data;
} else {
throw (data != null) ? data : new Error("service not available");
}
}),
map((data: any) => {
this.databaseConnectionError = false;
const tables = this.parseTableResponse(data);
// Dont cache .. uncomment to cache results
// this.allTables[serviceId] = parseTableResponse(response.data);
return query ? tables.filter(this.createFilterForTable(query)) : tables;
}),
catchError<any, any[]>((error: any) => {
this.setDatabaseConnectionError(error)
return Observable.throw(error);
})
);
}
}
private setDatabaseConnectionError(error:any){
if(error && error.error && error.error.message){
this.databaseConnectionErrorObject = error.error;
}
else if(error && error.message ){
this.databaseConnectionErrorObject = error;
}
else {
this.databaseConnectionErrorObject = {message:"Unable to connect to data source ",developerMessage:null};
}
this.databaseConnectionErrorObject.message +=". You can manually enter the table and fields below";
if(this.tableProperty){
this.tableProperty.value = "";
}
if(this.fieldsProperty) {
this.fieldsProperty.value = "";
}
this.databaseConnectionError = true;
}
/**
* Turn the schema.table string into an object for template display
*/
private parseTableResponse(response: any[]) {
if (response) {
return response.map(table => new TableRef(table));
} else {
return [];
}
}
private showDescribeTableSchemaDialog(tableDefinition: any): MatDialogRef<DescribeTableDialogComponent> {
const ref = this.dialog.open(DescribeTableDialogComponent, {data: tableDefinition});
ref.afterClosed().subscribe(() => this.tableAutoTrigger.closePanel());
return ref;
}
private hideDescribeTableSchemaDialog(ref: MatDialogRef<DescribeTableDialogComponent>): void {
ref.close();
}
private updateRestrictIncrementalToDateOnly(){
let newVal = this.loadStrategyProperty.value;
if (newVal == 'FULL_LOAD') {
this.restrictIncrementalToDateOnly = false;
} else if (this.isIncrementalLoadStrategy(newVal)) {
let option = this.loadStrategyOptions.find((opt: any) => opt.strategy == newVal);
if (option) {
this.restrictIncrementalToDateOnly = option.restrictDates != undefined ? option.restrictDates : false;
}
}
}
/**
* on edit describe the table for incremental load to populate the tableField options
*/
private editIncrementalLoadDescribeTable() {
//get the property that stores the DBCPController Service
let dbcpProperty = this.dbConnectionProperty;
if (dbcpProperty != null && dbcpProperty.value != null && this.selectedTable != null) {
this.updateRestrictIncrementalToDateOnly();
let serviceId = dbcpProperty.value;
let serviceName = '';
if (Array.isArray(dbcpProperty.propertyDescriptor.allowableValues)) {
let service = dbcpProperty.propertyDescriptor.allowableValues.find((allowableValue: any) => allowableValue.value == serviceId);
if(service != undefined) {
serviceName = service.displayName;
if (service.catalogSource && service.origName) {
serviceName = service.origName;
}
}
}
this.http.get(this.tableSchemaService.DESCRIBE_TABLE_URL(serviceId, this.selectedTable.tableName), {params: {schema: this.selectedTable.schema, serviceName: serviceName}})
.subscribe((response) => {
this.databaseConnectionError = false;
this.tableSchema = response;
this.tableFields = this.tableSchema.fields;
this.filteredFieldDates = this.tableFields.filter(this.filterFieldDates);
}, (error:any) => {
this.setDatabaseConnectionError(error);
console.error("error",error)
});
}
}
/**
* Describe the table
* This is called once a user selects a table from the autocomplete
* This will setup the model populating the destination table fields
*/
private describeTable() {
//get the property that stores the DBCPController Service
let dbcpProperty = this.dbConnectionProperty;
if (dbcpProperty != null && dbcpProperty.value != null && this.selectedTable != null) {
const dialogRef = this.showDescribeTableSchemaDialog(this.selectedTable);
this.describingTableSchema = true;
let serviceId = dbcpProperty.value;
let service = null;
let serviceName = '';
if (dbcpProperty.propertyDescriptor.allowableValues) {
service = dbcpProperty.propertyDescriptor.allowableValues.find((allowableValue: any) => allowableValue.value == serviceId);
}
if(service != undefined && service != null) {
serviceName = service.displayName;
if (service.catalogSource && service.origName) {
serviceName = service.origName;
}
}
this.http.get(this.tableSchemaService.DESCRIBE_TABLE_URL(serviceId, this.selectedTable.tableName), {params: {schema: this.selectedTable.schema, serviceName: serviceName}})
.subscribe((response) => {
this.databaseConnectionError = false;
this.tableSchema = response;
this.tableFields = this.tableSchema.fields;
this.originalTableFields = [...this.tableSchema.fields];
this.filteredFieldDates = this.tableFields.filter(this.filterFieldDates);
this.tableFieldsDirty = false;
this.model.table.sourceTableSchema.fields = this.originalTableFields;
this.model.table.setTableFields(this.tableSchema.fields)
//this.feedService.setTableFields(this.tableSchema.fields);
if(this.model.setTableMethod) {
this.model.setTableMethod('EXISTING_TABLE');
}
else {
this.model.table.method = 'EXISTING_TABLE';
}
if (this.tableSchema.schemaName != null) {
this.model.table.existingTableName = this.tableSchema.schemaName + "." + this.tableSchema.name;
}
else {
this.model.table.existingTableName = this.tableSchema.name;
}
this.model.table.sourceTableSchema.name = this.model.table.existingTableName;
this.describingTableSchema = false;
this.hideDescribeTableSchemaDialog(dialogRef);
}, (error:any) => {
this.setDatabaseConnectionError(error)
this.describingTableSchema = false;
this.hideDescribeTableSchemaDialog(dialogRef);
});
}
}
onManualTableNameChange() {
if (this.model.table.method != 'EXISTING_TABLE') {
this.model.table.method = 'EXISTING_TABLE';
}
this.model.table.sourceTableSchema.name = this.tableProperty.value;
this.model.table.existingTableName = this.tableProperty.value;
}
onManualFieldNameChange() {
if (this.model.table.method != 'EXISTING_TABLE') {
this.model.table.method = 'EXISTING_TABLE';
}
let fields: any[] = [];
let val: string = this.fieldsProperty.value;
let fieldNames: any[] = [];
val.split(",").forEach(field => {
let col = this.feedService.newTableFieldDefinition();
col.name = field.trim();
col.derivedDataType = 'string';
fields.push(col);
fieldNames.push(col.name);
});
this.model.table.sourceTableSchema.fields = [...fields];
this.model.table.setTableFields(fields)
this.model.table.sourceFieldsCommaString = fieldNames.join(",");
this.model.table.sourceFields = fieldNames.join("\n")
}
/**
* Filter for fields that are Date types
*/
private filterFieldDates(field: any): boolean {
return field.derivedDataType == 'date' || field.derivedDataType == 'timestamp';
}
onIncrementalDateFieldChange() {
let prop = this.incrementalFieldProperty;
if (prop != null) {
prop.value = this.model.table.sourceTableIncrementalDateField;
prop.displayValue = prop.value;
}
}
/**
* Validates the autocomplete has a selected table
*/
private validate(): ValidationErrors {
if (this.selectedTable == undefined) {
return {required: true};
} else {
if (this.describingTableSchema) {
return {};
} else {
return {};
}
}
}
private initializeAutoComplete() {
if (this.dbConnectionProperty != null && this.dbConnectionProperty.value != null && this.dbConnectionProperty.value != "") {
const processorTableName = this.model.table.existingTableName;
this.tableControl.setValue(processorTableName);
if (processorTableName != null) {
this.selectedTable = new TableRef(processorTableName);
this.tableControl.setValue(this.selectedTable);
}
}
}
} | the_stack |
import {GearIcon} from '../../../vectors';
import OptionsContainer from '../options-container';
import Select from './select';
import {ipcRenderer as ipc} from 'electron-better-ipc';
import useConversionIdContext from 'hooks/editor/use-conversion-id';
import useEditorWindowState from 'hooks/editor/use-editor-window-state';
import VideoTimeContainer from '../video-time-container';
import VideoControlsContainer from '../video-controls-container';
import useSharePlugins from 'hooks/editor/use-share-plugins';
import useEditorOptions from 'hooks/editor/use-editor-options';
const FormatSelect = () => {
const {formats, format, updateFormat} = OptionsContainer.useContainer();
const options = formats.map(format => ({label: format.prettyFormat, value: format.format}));
return <Select options={options} value={format} onChange={updateFormat}/>;
};
const PluginsSelect = () => {
const {menuOptions, label, onChange} = useSharePlugins();
return <Select options={menuOptions} customLabel={label} onChange={onChange}/>;
};
const EditPluginsControl = () => {
const {editServices, editPlugin, setEditPlugin} = OptionsContainer.useContainer();
if (editServices?.length === 0) {
return null;
}
if (!editPlugin) {
return (
<button
type="button" className="add-edit-plugin" onClick={() => {
setEditPlugin(editServices[0]);
}}
>
+
<style jsx>{`
button {
padding: 4px 8px;
background: rgba(255, 255, 255, 0.1);
font-size: 12px;
line-height: 12px;
color: white;
height: 24px;
border-radius: 4px;
text-align: center;
border: none;
box-shadow: inset 0px 1px 0px 0px rgba(255, 255, 255, 0.04), 0px 1px 2px 0px rgba(0, 0, 0, 0.2);
}
button:hover,
button:focus {
background: hsla(0, 0%, 100%, 0.2);
outline: none;
}
.add-edit-plugin {
width: max-content;
margin-right: 8px;
}
`}</style>
</button>
);
}
const openEditPluginConfig = () => {
ipc.callMain('open-edit-config', {
pluginName: editPlugin.pluginName,
serviceTitle: editPlugin.title
});
};
const options = editServices.map(service => ({label: service.title, value: service}));
return (
<>
{
editPlugin.hasConfig && (
<button type="button" className="add-edit-plugin" onClick={openEditPluginConfig}>
<GearIcon fill="#fff" hoverFill="#fff" size="12px"/>
</button>
)
}
<div className="edit-plugin">
<Select clearable options={options} value={editPlugin} onChange={setEditPlugin}/>
</div>
<style jsx>{`
button {
padding: 4px 8px;
background: rgba(255, 255, 255, 0.1);
font-size: 12px;
line-height: 12px;
color: white;
height: 24px;
border-radius: 4px;
text-align: center;
border: none;
box-shadow: inset 0px 1px 0px 0px rgba(255, 255, 255, 0.04), 0px 1px 2px 0px rgba(0, 0, 0, 0.2);
}
button:hover,
button:focus {
background: hsla(0, 0%, 100%, 0.2);
outline: none;
}
.add-edit-plugin {
width: max-content;
margin-right: 8px;
}
.edit-plugin {
height: 24px;
margin-right: 8px;
width: 128px;
}
`}</style>
</>
);
};
const ConvertButton = () => {
const {startConversion} = useConversionIdContext();
const options = OptionsContainer.useContainer();
const {filePath} = useEditorWindowState();
const {startTime, endTime} = VideoTimeContainer.useContainer();
const {isMuted} = VideoControlsContainer.useContainer();
const {updatePluginUsage} = useEditorOptions();
const onClick = () => {
const shouldCrop = true;
startConversion({
filePath,
conversionOptions: {
width: options.width,
height: options.height,
startTime,
endTime,
fps: options.fps,
shouldMute: isMuted,
shouldCrop,
editService: options.editPlugin ? {
pluginName: options.editPlugin.pluginName,
serviceTitle: options.editPlugin.title
} : undefined
},
format: options.format,
plugins: {
share: options.sharePlugin
}
});
updatePluginUsage({
format: options.format,
plugin: options.sharePlugin.pluginName
});
};
return (
<button type="button" className="start-export" onClick={onClick}>
Convert
<style jsx>{`
button {
padding: 4px 8px;
background: rgba(255, 255, 255, 0.1);
font-size: 12px;
line-height: 12px;
color: white;
height: 24px;
border-radius: 4px;
text-align: center;
border: none;
box-shadow: inset 0px 1px 0px 0px rgba(255, 255, 255, 0.04), 0px 1px 2px 0px rgba(0, 0, 0, 0.2);
}
button:hover,
button:focus {
background: hsla(0, 0%, 100%, 0.2);
outline: none;
}
.start-export {
width: 72px;
}
`}</style>
</button>
);
};
const RightOptions = () => {
return (
<div className="container">
<EditPluginsControl/>
<div className="format"><FormatSelect/></div>
<div className="plugin"><PluginsSelect/></div>
<ConvertButton/>
<style jsx>{`
.container {
height: 100%;
display: flex;
align-items: center;
}
.label {
font-size: 12px;
margin-right: 8px;
color: white;
}
.format {
height: 24px;
width: 112px;
margin-right: 8px;
}
.plugin {
height: 24px;
width: 128px;
margin-right: 8px;
}
`}</style>
</div>
);
};
export default RightOptions;
// Import electron from 'electron';
// import React from 'react';
// import PropTypes from 'prop-types';
// import {connect, EditorContainer} from '../../../containers';
// import Select from './select';
// import {GearIcon} from '../../../vectors';
// class RightOptions extends React.Component {
// render() {
// const {
// options,
// format,
// plugin,
// selectFormat,
// selectPlugin,
// startExport,
// openWithApp,
// selectOpenWithApp,
// selectEditPlugin,
// editOptions,
// editPlugin,
// openEditPluginConfig
// } = this.props;
// const formatOptions = options ? options.map(({format, prettyFormat}) => ({value: format, label: prettyFormat})) : [];
// const pluginOptions = options ? options.find(option => option.format === format).plugins.map(plugin => {
// if (plugin.apps) {
// const submenu = plugin.apps.map(app => ({
// label: app.isDefault ? `${app.name} (default)` : app.name,
// type: 'radio',
// checked: openWithApp && app.url === openWithApp.url,
// click: () => selectOpenWithApp(app),
// icon: electron.remote.nativeImage.createFromDataURL(app.icon).resize({width: 16, height: 16})
// }));
// if (plugin.apps[0].isDefault) {
// submenu.splice(1, 0, {type: 'separator'});
// }
// return {
// isBuiltIn: false,
// submenu,
// value: plugin.title,
// label: openWithApp ? openWithApp.name : ''
// };
// }
// return {
// type: openWithApp ? 'normal' : 'radio',
// value: plugin.title,
// label: plugin.title,
// isBuiltIn: plugin.pluginName.startsWith('_')
// };
// }) : [];
// if (pluginOptions.every(opt => opt.isBuiltIn)) {
// pluginOptions.push({
// separator: true
// }, {
// type: 'normal',
// label: 'Get Plugins…',
// value: 'open-plugins'
// });
// }
// const editPluginOptions = editOptions && editOptions.map(option => ({label: option.title, value: option}));
// const buttonAction = editPlugin ? openEditPluginConfig : () => selectEditPlugin(editOptions[0]);
// return (
// <div className="container">
// {
// editPluginOptions && editPluginOptions.length > 0 && (
// <>
// {
// (!editPlugin || editPlugin.hasConfig) && (
// <button key={editPlugin} type="button" className="add-edit-plugin" onClick={buttonAction}>
// {editPlugin ? <GearIcon fill="#fff" hoverFill="#fff" size="12px"/> : '+'}
// </button>
// )
// }
// {
// editPlugin && (
// <div className="edit-plugin">
// <Select clearable options={editPluginOptions} selected={editPlugin} onChange={selectEditPlugin}/>
// </div>
// )
// }
// </>
// )
// }
// <div className="format">
// <Select options={formatOptions} selected={format} onChange={selectFormat}/>
// </div>
// <div className="plugin">
// <Select options={pluginOptions} selected={plugin} onChange={selectPlugin}/>
// </div>
// <button type="button" className="start-export" onClick={startExport}>Export</button>
// <style jsx>{`
// .container {
// height: 100%;
// display: flex;
// align-items: center;
// }
// .label {
// font-size: 12px;
// margin-right: 8px;
// color: white;
// }
// .format {
// height: 24px;
// width: 96px;
// margin-right: 8px;
// }
// .edit-plugin {
// height: 24px;
// margin-right: 8px;
// width: 128px;
// }
// .plugin {
// height: 24px;
// width: 128px;
// margin-right: 8px;
// }
// button {
// padding: 4px 8px;
// background: rgba(255, 255, 255, 0.1);
// font-size: 12px;
// line-height: 12px;
// color: white;
// height: 24px;
// border-radius: 4px;
// text-align: center;
// border: none;
// box-shadow: inset 0px 1px 0px 0px rgba(255, 255, 255, 0.04), 0px 1px 2px 0px rgba(0, 0, 0, 0.2);
// }
// button:hover,
// button:focus {
// background: hsla(0, 0%, 100%, 0.2);
// outline: none;
// }
// .start-export {
// width: 72px;
// }
// .add-edit-plugin {
// width: max-content;
// margin-right: 8px;
// }
// `}</style>
// </div>
// );
// }
// }
// RightOptions.propTypes = {
// options: PropTypes.arrayOf(PropTypes.object),
// format: PropTypes.string,
// plugin: PropTypes.string,
// selectFormat: PropTypes.elementType,
// selectPlugin: PropTypes.elementType,
// startExport: PropTypes.elementType,
// openWithApp: PropTypes.object,
// selectOpenWithApp: PropTypes.elementType,
// editPlugin: PropTypes.object,
// editOptions: PropTypes.arrayOf(PropTypes.object),
// selectEditPlugin: PropTypes.elementType,
// openEditPluginConfig: PropTypes.elementType
// };
// export default connect(
// [EditorContainer],
// ({options, format, plugin, openWithApp, editOptions, editPlugin}) => ({options, format, plugin, openWithApp, editOptions, editPlugin}),
// ({selectFormat, selectPlugin, startExport, selectOpenWithApp, selectEditPlugin, openEditPluginConfig}) => ({selectFormat, selectPlugin, startExport, selectOpenWithApp, selectEditPlugin, openEditPluginConfig})
// )(RightOptions); | the_stack |
export enum lngKeys {
GeneralError = 'general.error',
GeneralCreate = 'general.create',
GeneralCancel = 'general.cancel',
GeneralUpdate = 'general.update',
GeneralAttachments = 'general.attachments',
GeneralArchive = 'general.archive',
GeneralSignin = 'general.signin',
GeneralSigningIn = 'general.signingin',
GeneralSignout = 'general.signout',
GeneralSave = 'general.save',
GeneralDefault = 'general.default',
GeneralDelete = 'general.delete',
GeneralDaily = 'general.daily',
GeneralWeekly = 'general.weekly',
GeneralNever = 'general.never',
GeneralTemplates = 'general.templates',
GeneralTitle = 'general.title',
GeneralDuplicate = 'general.duplicate',
GeneralUse = 'general.use',
GeneralChangeIcon = 'general.changeicon',
GeneralOwner = 'general.Owner',
GeneralAddVerb = 'general.Addverb',
GeneralSelectAll = 'general.Select.all',
GeneralSelectVerb = 'general.Select',
GeneralAll = 'general.All',
GeneralAny = 'general.Any',
GeneralPickYourDestination = 'general.Pick.your.destination',
GeneralOpenVerb = 'general.Openverb',
OpenInBrowser = 'general.open.in.browser',
GeneralCopyTheLink = 'general.Copy.the.link',
GeneralMoveVerb = 'general.Moveverb',
GeneralSource = 'general.Source',
GeneralDestination = 'general.Destination',
GeneralPrevious = 'general.Previous',
GeneralNext = 'general.Next',
GeneralContinueVerb = 'general.Continueverb',
GeneralShared = 'general.Shared',
GeneralDashboards = 'general.dashboards',
GeneralBookmarks = 'general.Bookmarks',
GeneralUnbookmarkVerb = 'general.Unbookmarkverb',
GeneralBookmarkVerb = 'general.Bookmarkverb',
GeneralWorkspaces = 'general.Workspaces',
GeneralPrivate = 'general.Private',
GeneralLabels = 'general.Labels',
GeneralMore = 'general.More',
GeneralStatus = 'general.Status',
GeneralEditTitle = 'general.EditTitle',
GeneralRenameVerb = 'general.Renameverb',
GeneralEditVerb = 'general.Editverb',
GeneralSettings = 'general.Settings',
GeneralImport = 'general.Import',
GeneralTimeline = 'general.Timeline',
GeneralSearchVerb = 'general.Searchverb',
GeneralHelp = 'general.Help',
GeneralThisSpace = 'general.This.space',
GeneralProfilePicture = 'general.Profile.picture',
GeneralName = 'general.Name',
GeneralLogo = 'general.Logo',
GeneralSpaces = 'general.Spaces',
GeneralTabs = 'general.Tabs',
GeneralUser = 'general.User',
GeneralSeeVerb = 'general.Seeverb',
GeneralAdmin = 'general.Admin',
GeneralMembers = 'general.Members',
GeneralMember = 'general.Member',
GeneralViewer = 'general.Viewer',
GeneralLeaveVerb = 'general.Leaveverb',
GeneralRemoveVerb = 'general.Remove',
GeneralCopyVerb = 'general.Copy',
GeneralCopied = 'general.Copied',
GeneralSendVerb = 'general.Sendverb',
GeneralPromoteVerb = 'general.Promoteverb',
GeneralDemoteVerb = 'general.Demoteverb',
GeneralEnableVerb = 'general.Enableverb',
GeneralDisableVerb = 'general.Disableverb',
GeneralSendMore = 'general.Send.more',
GeneralShowVerb = 'general.Showverb',
GeneralHideVerb = 'general.Hideverb',
GeneralSaveVerb = 'general.Saveverb',
GeneralCloseVerb = 'general.Closeverb',
GeneralToken = 'general.Token',
GeneralApplyVerb = 'general.Applyverb',
GeneralUpdateVerb = 'general.Updateverb',
GeneralLearnMore = 'general.Learn.more',
GeneralDoYouWishToProceed = 'general.Do.you.wish.to.proceed',
GeneralDays = 'general.Days',
GeneralHours = 'general.Hours',
GeneralMinutes = 'general.Minutes',
GeneralSeconds = 'general.Seconds',
GeneralFolders = 'general.Folders',
GeneralShowMore = 'general.Show.more',
GeneralDashboard = 'general.dashboard',
//settings
SettingsInfo = 'settings.info',
SettingsGeneral = 'settings.general',
SettingsNotifications = 'settings.notifications',
SettingsTitle = 'settings.title',
SettingsPersonalInfo = 'settings.personalInfo',
SettingsMarkdownPreview = 'settings.markdownPreview',
SettingsMarkdownPreviewShowcase = 'settings.markdownPreviewShowcase',
SettingsMarkdownPreviewCodeBlockTheme = 'settings.markdownPreviewCodeBlockTheme',
SettingsMarkdownPreviewStyleTitle = 'settings.markdownPreviewStyleTitle',
SettingsMarkdownPreviewStyleResetLabel = 'settings.markdownPreviewStyleResetLabel',
SettingsPreferences = 'settings.preferences',
SettingsPreferencesResetTitle = 'settings.preferencesResetTitle',
SettingsPreferencesResetLabel = 'settings.preferencesResetLabel',
SettingsTeamInfo = 'settings.teamInfo',
SettingsTeamUpgrade = 'settings.teamUpgrade',
SettingsTeamSubscription = 'settings.teamSubscription',
SettingsIntegrations = 'settings.integrations',
SettingsAppFeedback = 'settings.appFeedback',
SettingsAccount = 'settings.account',
SettingsAccountDelete = 'settings.account.delete',
SettingsUILanguage = 'settings.interfaceLanguage',
SettingsApplicationTheme = 'settings.applicationTheme',
SettingsEditorTheme = 'settings.editorTheme',
SettingsCodeBlockTheme = 'settings.codeblockTheme',
SettingsEditorKeyMap = 'settings.editorKeyMap',
SettingsEditorFontSize = 'settings.editorFontSize',
SettingsEditorFontFamily = 'settings.editorFontFamily',
SettingsLight = 'settings.light',
SettingsDark = 'settings.dark',
SettingsDracula = 'settings.dracula',
SettingsSolarizedDark = 'settings.solarizedDark',
SettingsSepia = 'settings.sepia',
SettingsMonokai = 'settings.monokai',
SettingsNotifFrequencies = 'settings.notificationsFrequency',
SettingsIndentType = 'settings.indentType',
SettingsShowEditorToolbar = 'settings.showEditorToolbar',
SettingsShowEditorLineNumbers = 'settings.showEditorLineNumbers',
SettingsEnableEditorSpellcheck = 'settings.enableSpellcheck',
SettingsIndentSize = 'settings.indentSize',
SettingsSpace = 'settings.space',
SettingsSpaceDelete = 'settings.space.delete',
SettingsSpaceDeleteWarning = 'settings.space.delete.warning',
SettingsBeta = 'settings.beta',
SettingsBetaAutomationAndIntegration = 'settings.beta.automationAndIntegration',
ManagePreferences = 'manage.preferences',
ManagePreferencesMarkdownPreview = 'manage.preferences.markdownPreview',
ManageProfile = 'manage.profile',
ManageSpaceSettings = 'manage.space.settings',
ManageTeamMembers = 'manage.team.members',
ManageIntegrations = 'manage.integrations',
CurrentMembers = 'members.current',
AddMembers = 'members.add',
MembersAccessLevel = 'members.access.level',
TeamCreate = 'team.create',
TeamCreateSubtitle = 'team.create.subtitle',
TeamName = 'team.name',
TeamDomain = 'team.domain',
SpaceName = 'space.name',
SpaceDomain = 'space.domain',
TeamDomainShow = 'team.domain.show',
TeamDomainWarning = 'team.domain.warning',
InviteAddWithLink = 'invite.url',
InviteEmail = 'invite.email',
InviteByEmailMore = 'invite.more.by.email',
InviteMembersDocAssignButton = 'invite.members.from.doc',
InviteFailError = 'invite.failed.invites',
InviteRoleDetails = 'invite.role.details.tooltip.',
RoleMemberDescription = 'role.member.description',
RoleAdminDescription = 'role.admin.description',
RoleViewerDescription = 'role.viewer.description',
RoleAdminPromote = 'role.admin.promote',
RoleMemberChange = 'role.member.change',
RoleViewerDemote = 'role.member.demote',
TeamLeave = 'team.leave',
TeamLeaveWarning = 'team.leave.warning',
RemovingMember = 'role.member.remove',
RemovingMemberWarning = 'role.member.remove.warning',
CancelInvite = 'invite.cancel',
CancelInviteOpenLinkMessage = 'invite.cancel.openlink.message',
CancelInviteEmailMessage = 'invite.cancel.email.message',
ExternalEntity = 'external.entity',
ExternalEntityOpenInBrowser = 'external.entity.open.browser',
ExternalEntityDescription = 'external.entity.description',
ExternalEntityRequest = 'external.entity.request',
CommunityFeedback = 'community.feedback',
CommunityFeatureRequests = 'community.feature.requests',
CommunityFeedbackSubtitle = 'community.feedback.subtitle',
CommunityBugReport = 'community.bug.report',
CommunityFeedbackSendError = 'community.feedback.send.error',
CommunityFeedbackSendSuccess = 'community.feedback.send.success',
CommunityFeedbackType = 'community.feedback.type',
CommunityFeedbackFreeForm = 'community.feedback.freeform',
ManageApi = 'manage.api',
AccessTokens = 'tokens.access',
CreateTokens = 'tokens.create',
TokensName = 'tokens.name.placeholder',
GenerateToken = 'tokens.generate',
TokensDocumentation = 'tokens.documentation',
SupportGuide = 'support.guide',
SendUsAMessage = 'send.us.a.message',
KeyboardShortcuts = 'keyboard.shortcuts',
SettingsSubLimitUsed = 'settings.sub.limit.used',
SettingsSubLimitTrialTitle = 'settings.sub.limit.trial.title',
SettingsSubLimitTrialDate = 'settings.sub.limit.trial.date',
SettingsSubLimitTrialUpgrade = 'settings.sub.limit.trial.upgrade',
SettingsSubLimitTrialEnd = 'settings.sub.limit.trial.end',
SettingsSubLimitUnderFreePlan = 'settings.sub.limit.free',
PlanChoose = 'plan.choose',
PlanDiscountUntil = 'plan.discount.until',
PlanDiscountDetail = 'plan.discount.detail',
PlanDiscountLabel = 'plan.discount.label',
PlanDiscountCouponWarning = 'plan.discount.coupon.warning',
PlanBusinessIntro = 'plan.business.intro',
PlanBusinessLink = 'plan.business.link',
PlanPerMember = 'plan.per.member',
PlanPerMonth = 'plan.per.month',
PlanPerYear = 'plan.per.year',
PlanFreePerk1 = 'plan.free.perk.1',
PlanFreePerk2 = 'plan.free.perk.2',
PlanFreePerk3 = 'plan.free.perk.3',
PlanStoragePerk = 'plan.storage.perk',
PlanStandardPerk1 = 'plan.standard.perk.1',
PlanStandardPerk2 = 'plan.standard.perk.2',
PlanStandardPerk3 = 'plan.standard.perk.3',
PlanStandardPerk4 = 'plan.standard.perk.4',
PlanProPerk1 = 'plan.pro.perk.1',
PlanProPerk2 = 'plan.pro.perk.2',
PlanProPerk3 = 'plan.pro.perk.3',
PlanProPerk4 = 'plan.pro.perk.4',
PlanTrial = 'plan.trial',
PlanInTrial = 'plan.in.trial',
PlanSizePerUpload = 'plan.upload.size',
PlanDashboardPerUser = 'plan.dashboard.user',
PlanSmartviewPerDashboard = 'plan.smartview.dashboard',
UpgradeSubtitle = 'plan.upgrade.subtitle',
Viewers = 'viewers',
Month = 'month',
Year = 'year',
TotalMonthlyPrice = 'plan.total.monthly',
PaymentMethod = 'payment.method',
TrialWillBeStopped = 'trial.stopped',
ApplyCoupon = 'coupon.apply',
PromoCode = 'coupon.code',
Subscribe = 'subscribe',
PaymentMethodJpy = 'plan.method.jpy',
UnlimitedViewers = 'viewers.unlimited',
BillingActionRequired = 'billing.action.required',
BillingHistory = 'billing.history',
BillingHistoryCheck = 'billing.history.check',
BillingCancelledAt = 'billing.cancelled.at',
BillingToCard = 'billing.card.to',
BillingEditCard = 'billing.card.edit',
BillingEmail = 'billing.email',
BillingEditEmail = 'billing.email.edit',
BillingCanSeeThe = 'billing.can.see',
BillingChangePlan = 'billing.plan.change',
BillingUpdateCard = 'billing.card.update',
BillingCurrentCard = 'billing.card.current',
BillingUpdateEmail = 'billing.email.update',
BillingCurrentEmail = 'billing.email.current',
BillingChangeJCB = 'billing.card.jcb',
BillingApplyPromoWarning = 'billing.promo.warning',
BillingApplyPromo = 'billing.promo',
BillingChangePlanDiscountStop = 'billing.plan.change.discount.stop',
BillingChangePlanFreeDisclaimer = 'billing.plan.change.free.disclaimer',
BillingChangePlanProDisclaimer = 'billing.plan.change.pro.disclaimer',
BillingChangePlanStandardDisclaimer = 'billing.plan.change.standard.disclaimer',
BillingChangePlanStripeProration = 'billing.plan.change.stripe.proration',
BillingChangePlanStripeProrationUpgradeDiscount = 'billing.plan.change.stripe.proration.discount.upgrade',
BillingChangePlanStripeProrationDowngradeDiscount = 'billing.plan.change.stripe.proration.discount.downgrade',
DiscountModalTitle = 'modals.discount.title',
DiscountModalAlreadySubscribed = 'modals.discount.subscribed',
DiscountModalTimeRemaining = 'modals.discount.remaining',
DiscountModalExpired = 'modals.discount.expired',
FreeTrialModalTitle = 'modals.trial.title',
FreeTrialModalBody = 'modals.trial.body',
FreeTrialModalDisclaimer = 'modals.trial.disclaimer',
FreeTrialModalCTA = 'modals.trial.cta',
LogOut = 'log.out',
CreateNewSpace = 'spaces.create',
DownloadDesktopApp = 'modals.spaces.download',
ToolbarTooltipsSpaces = 'toolbar.tooltips.spaces',
ToolbarTooltipsTree = 'toolbar.tooltips.tree',
ToolbarTooltipsDiscount = 'toolbar.tooltips.discount',
GeneralBack = 'general.Back',
FolderNamePlaceholder = 'placeholders.folder',
DocTitlePlaceholder = 'placeholders.doc',
SortLastUpdated = 'sort.last-updated',
SortTitleAZ = 'sort.a-z',
SortTitleZA = 'sort.z-a',
SortDragAndDrop = 'sort.drag',
CreateNewDoc = 'create.new.doc',
CreateNewCanvas = 'create.new.canvas',
UseATemplate = 'use.a.template',
RenameFolder = 'Rename.folder',
RenameDoc = 'Rename.doc',
ModalsCreateNewFolder = 'modals.create.folder',
ModalsCreateNewDocument = 'modals.create.doc',
ModalsDeleteWorkspaceTitle = 'modals.workspaces.delete.title',
ModalsDeleteWorkspaceDisclaimer = 'modals.workspaces.delete.disclaimer',
ModalsDeleteDocFolderTitle = 'modals.docs.folders.delete.title',
ModalsDeleteDocDisclaimer = 'modals.docs.delete.disclaimer',
ModalsDeleteCommentDisclaimer = 'modals.comment.delete.disclaimer',
ModalsDeleteThreadDisclaimer = 'modals.thread.delete.disclaimer',
ModalsDeleteFolderDisclaimer = 'modals.folders.delete.disclaimer',
ModalsWorkspaceCreateTitle = 'modals.workspaces.create.title',
ModalsWorkspaceEditTitle = 'modals.workspaces.edit.title',
ModalsWorkspaceMakePrivate = 'modals.workspaces.privatize',
ModalsWorkspaceAccess = 'modals.workspaces.access',
ModalsWorkspaceDefaultDisclaimer = 'modals.workspaces.default.disclaimer',
ModalsWorkspacePublicDisclaimer = 'modals.workspaces.public.disclaimer',
ModalsWorkspacePrivateDisclaimer = 'modals.workspaces.private.disclaimer',
ModalsWorkspacePrivateOwner = 'modals.workspaces.private.owner',
ModalsWorkspaceSetAccess = 'modals.workspaces.access.set',
ModalsWorkspacesSetAccessMembers = 'modals.workspaces.access.members',
ModalsWorkspacesWhoHasAcess = 'modals.workspaces.access.who',
ModalsWorkspacesNonOwnerDisclaimer = 'modals.workspaces.access.nonowner',
AttachmentsDeleteDisclaimer = 'attachments.delete.disclaimer',
AttachmentsLimitDisclaimer = 'attachments.limit.disclaimer',
AttachmentsPlanUpgradeDisclaimer = 'attachments.upgrade.disclaimer',
AttachmentsUpgradeLink = 'attachments.upgrade.link',
ModalsImportDestinationTitle = 'modals.import.destination.title',
ModalsImportDestinationDisclaimer = 'modals.import.destination.disclaimer',
ModalsImportDisclaimer = 'modals.import.disclaimer',
ModalsSmartViewCreateTitle = 'modals.sf.create.title',
ModalsSmartViewEditTitle = 'modals.sf.edit.title',
ModalsSmartViewPrivateDisclaimer = 'modals.sf.private.disclaimer',
ModalsSmartViewPublicDisclaimer = 'modals.sf.public.disclaimer',
EditorToolbarTooltipHeader = 'editor.toolbar.tooltips.header',
EditorToolbarTooltipAdmonition = 'editor.toolbar.tooltips.admonition',
EditorToolbarTooltipCodefence = 'editor.toolbar.tooltips.codefence',
EditorToolbarTooltipQuote = 'editor.toolbar.tooltips.quote',
EditorToolbarTooltipList = 'editor.toolbar.tooltips.list',
EditorToolbarTooltipNumberedList = 'editor.toolbar.tooltips.numberedlist',
EditorToolbarTooltipTaskList = 'editor.toolbar.tooltips.tasklist',
EditorToolbarTooltipBold = 'editor.toolbar.tooltips.bold',
EditorToolbarTooltipItalic = 'editor.toolbar.tooltips.italic',
EditorToolbarTooltipCode = 'editor.toolbar.tooltips.code',
EditorToolbarTooltipLink = 'editor.toolbar.tooltips.link',
EditorToolbarTooltipMath = 'editor.toolbar.tooltips.math',
EditorToolbarTooltipBrackets = 'editor.toolbar.tooltips.brackets',
EditorToolbarTooltipUpload = 'editor.toolbar.tooltips.upload',
EditorToolbarTooltipTemplate = 'editor.toolbar.tooltips.template',
EditorToolbarTooltipScrollSyncEnable = 'editor.toolbar.tooltips.scrollsync.enable',
EditorToolbarTooltipScrollSyncDisable = 'editor.toolbar.tooltips.scrollsync.disable',
EditorReconnectAttempt = 'editor.reconnect.attempt',
EditorReconnectAttempt1 = 'editor.reconnect.attempt1',
EditorReconnectAttempt2 = 'editor.reconnect.attempt2',
EditorReconnectDisconnected = 'editor.reconnect.reconnect',
EditorReconnectDisconnected1 = 'editor.reconnect.reconnect1',
EditorReconnectDisconnected2 = 'editor.reconnect.reconnect2',
EditorReconnectSyncing = 'editor.reconnect.syncing',
EditorReconnectSyncing1 = 'editor.reconnect.syncing1',
EditorReconnectSyncing2 = 'editor.reconnect.syncing2',
DocSaveAsTemplate = 'doc.save.as.template',
DocExportPdf = 'doc.export.pdf',
DocExportMarkdown = 'doc.export.markdown',
DocExportHtml = 'doc.export.html',
FolderFilter = 'Folder.Filter',
FolderInfo = 'Folder.Info',
DocInfo = 'Doc.Info',
Assignees = 'Assignees',
Unassigned = 'Unassigned',
DueDate = 'Due.Date',
AddDueDate = 'Add.due.date',
AddALabel = 'Add.a.label',
NoStatus = 'NoStatus',
CreationDate = 'Creation.Date',
UpdateDate = 'Update.Date',
CreatedBy = 'Created.By',
UpdatedBy = 'Updated.By',
Contributors = 'Contributors',
WordCount = 'Word.Count',
CharacterCount = 'Character.Count',
History = 'History',
Share = 'Share',
PublicSharing = 'Public.Sharing',
PublicSharingDisclaimer = 'Public.Sharing.Disclaimer',
SharingSettings = 'Sharing.settings',
SharingRegenerateLink = 'regenerate.link',
Regenerate = 'regenerate',
PasswordProtect = 'password.protect',
ExpirationDate = 'expiration.date',
SeeFullHistory = 'history.see.full',
SeeLimitedHistory = 'history.see.limited',
ThreadsTitle = 'threads.title',
ThreadPost = 'threads.Post',
ThreadFullDocLabel = 'threads.fulldoc.label',
ThreadCreate = 'threads.create',
ThreadOpen = 'threads.open',
ThreadClosed = 'threads.closed',
ThreadOutdated = 'threads.outdated',
ThreadReopen = 'threads.reopen',
ThreadReplies = 'threads.replies',
ModalsTemplatesDeleteDisclaimer = 'modals.templates.delete.disclaimer',
ModalsTemplatesSearchEmpty = 'modals.templates.search.empty',
ModalsTemplatesSelectTemplate = 'modals.templates.select.one',
ModalsTemplatesUseInDoc = 'modals.templates.use.indoc',
SettingsAccountDeleteWarning = 'settings.account.delete.warning',
FormSelectImage = 'form.image.select',
FormChangeImage = 'form.image.change',
SettingsReleaseNotes = 'settings.release.notes',
SidebarViewOptions = 'sidebar.view.options',
SidebarSettingsAndMembers = 'sidebar.settings.member',
SidebarNewUserDiscount = 'sidebar.discount',
GeneralOrdering = 'general.ordering',
GeneralInbox = 'general.inbox',
SettingsImportDescription = 'settings.import.description',
GeneralPassword = 'general.password',
CooperateTitle = 'cooperate.title',
CooperateSubtitle = 'cooperate.subtitle',
SpaceIntent = 'space.intent',
SpaceIntentPersonal = 'space.intent.personal',
SpaceIntentTeam = 'space.intent.team',
PictureAdd = 'picture.add.verb',
PictureChange = 'picture.change.verb',
PlanViewersMembersIntro = 'plan.viewersmembers.intro',
PlanViewersMembersLink = 'plan.viewersmembers.link',
SeeRoleDetails = 'settings.roles.see.details',
ViewerDisclaimerIntro = 'viewer.disclaimer.intro',
ViewerDisclaimerOutro = 'viewer.disclaimer.outro',
ViewerDisclaimerFolderOutro = 'viewer.disclaimer.outro.folder',
MemberRole = 'member.role',
GeneralInvite = 'general.invite',
SettingsRolesRestrictedTitle = 'settings.roles.restricted.title',
SettingsRolesRestrictedDescription = 'settings.roles.restricted.description',
GeneralDocuments = 'general.documents',
RequestAskMemberRole = 'request.ask.member.role',
RequestSent = 'request.requested',
UploadLimit = 'upload.limit',
OnboardingFolderSectionTitle = 'onboarding.folder.section.title',
OnboardingFolderSectionDisclaimer = 'onboarding.folder.section.disclaimer',
GeneralContent = 'general.content',
GeneralYes = 'general.yes',
GeneralNo = 'general.no',
ModalUnlockDashboardsTitle = 'modal.unlock.dashboard.title',
ModalUnlockDashboardsDescription = 'modal.unlock.dashboard.description',
ModalUnlockCheckDetails = 'modal.unlock.checj,details',
ModalUnlockSmartviewsTitle = 'modal.unlock.smartview.title',
ModalUnlockSmartviewsDescription = 'modal.unlock.smartview.description',
OverlimitDashboards = 'sub.limit.dashboards',
}
export type TranslationSource = {
[key in lngKeys]: string
} | the_stack |
import { setContext } from "svelte";
import { handleChromeAutofill } from "./chromeAutofill";
import { Form } from "./models/form";
import type { FormControl } from "./models/formControl";
import {
FormMember,
isFormMember,
isTextElement,
TextElement,
} from "./models/formMembers";
import type { FormProperties } from "./models/formProperties";
import { formReferences } from "./stores/formReferences";
interface EventListener {
node: HTMLElement;
event: string;
listener: EventListenerOrEventListenerObject;
}
/** Create a new form.
*
* You can either pass a default configuration for the form.
*
* ----
* ``` svelte
* <script>
* const form = useForm({
* firstName: { initial: "CACHED_NAME", validators: [required, maxLength(10)] }
* })
* </script>
*
* <input name="firstName />
* ```
* ----
* or handle everything directly in the form control
*
* ----
*
* ```svelte
* <script>
* const form = useForm();
* </script>
*
* <input name="firstName" value="CACHED_NAME" use:validators={[required, maxLength(10)]} />
* ```
*/
export function useForm(properties?: FormProperties) {
properties = properties ?? {};
const eventListeners: EventListener[] = [];
const subscribers = [];
let state: Form = new Form(properties, notifyListeners);
let observer: MutationObserver;
action.subscribe = subscribe;
action.set = set;
// Passing state via context to subcomponents like Hint
setContext("svelte-use-form_form", action);
/**
* ### The store and action of a form.
*
* Use the `$` prefix to access the state of the form;
*/
function action(node: HTMLFormElement) {
// Bootstrap form
setupForm(node);
// Add form reference to global internal store
formReferences.update((values) => [
...values,
{ node, form: state, notifyListeners },
]);
return {
update: () => {},
destroy: () => {
unmountEventListeners();
observer.disconnect();
},
};
}
function setupForm(node: HTMLFormElement) {
const inputElements = [...node.getElementsByTagName("input")];
const textareaElements = [...node.getElementsByTagName("textarea")];
const textElements = [...inputElements, ...textareaElements];
const selectElements = [...node.getElementsByTagName("select")];
setupTextElements(textElements);
setupSelectElements(selectElements);
hideNotRepresentedFormControls([...textElements, ...selectElements]);
setupFormObserver(node);
notifyListeners();
}
function setupTextElements(textElements: TextElement[]) {
for (const textElement of textElements) {
const name = textElement["name"];
if (!state[name]) {
let initial: string;
// Handle Radio button initial values
if (
textElement.type === "radio" &&
textElement instanceof HTMLInputElement
) {
initial = textElement.checked ? textElement.value : "";
} else if (
textElement.type === "checkbox" &&
textElement instanceof HTMLInputElement
) {
initial = textElement.checked ? "checked" : "";
} else {
initial = textElement.value;
}
state._addFormControl(name, initial, [], [textElement], {});
} else {
state[name].elements.push(textElement);
if (
textElement.type === "radio" &&
textElement instanceof HTMLInputElement &&
textElement.checked
) {
state[name].initial = textElement.value;
}
}
switch (textElement.type) {
case "checkbox":
case "radio":
mountEventListener(textElement, "click", handleBlurOrClick);
break;
default:
setInitialValue(textElement, state[name]);
handleAutofill(textElement, state[name]);
mountEventListener(textElement, "blur", handleBlurOrClick);
}
mountEventListener(textElement, "input", handleInput);
}
}
function setupSelectElements(selectElements: HTMLSelectElement[]) {
for (const selectElement of selectElements) {
const name = selectElement["name"];
if (!state[name]) {
const initial = selectElement.value;
state._addFormControl(name, initial, [], [selectElement], {});
} else {
state[name].elements.push(selectElement);
setInitialValue(selectElement, state[name]);
}
mountEventListener(selectElement, "input", handleInput);
mountEventListener(selectElement, "input", handleBlurOrClick);
mountEventListener(selectElement, "blur", handleBlurOrClick);
}
}
function setupFormObserver(form: HTMLFormElement) {
observer = new MutationObserver(observeForm);
observer.observe(form, { childList: true });
}
function observeForm(mutations: MutationRecord[]) {
for (const mutation of mutations) {
if (mutation.type === "childList") {
// If node gets removed
for (const node of mutation.removedNodes) {
if (node instanceof HTMLElement) {
const inputElements = [...node.getElementsByTagName("input")];
const textareaElements = [...node.getElementsByTagName("textarea")];
const selects = [...node.getElementsByTagName("select")];
const elements = [
...inputElements,
...textareaElements,
...selects,
];
if (isFormMember(node)) elements.push(node);
for (const element of elements) {
for (const eventListener of eventListeners) {
if (element === eventListener.node) {
delete state[element["name"]];
element.removeEventListener(
eventListener.event,
eventListener.listener
);
}
}
}
}
}
// If node gets added
for (const node of mutation.addedNodes) {
if (node instanceof HTMLElement) {
const inputElements = [...node.getElementsByTagName("input")];
const textareaElements = [...node.getElementsByTagName("textarea")];
const textElements = [...inputElements, ...textareaElements];
const selectElements = [...node.getElementsByTagName("select")];
if (isTextElement(node)) textElements.push(node);
else if (node instanceof HTMLSelectElement)
selectElements.push(node);
for (const element of [...textElements, ...selectElements]) {
const initialFormControlProperty = properties[element.name];
if (!state[element.name] && initialFormControlProperty) {
state._addFormControl(
element.name,
initialFormControlProperty.initial,
initialFormControlProperty.validators,
[element],
initialFormControlProperty.errorMap
);
}
}
setupTextElements(textElements);
setupSelectElements(selectElements);
}
}
}
}
notifyListeners();
}
function mountEventListener(
node: HTMLElement,
event: string,
listener: EventListenerOrEventListenerObject
) {
node.addEventListener(event, listener);
eventListeners.push({ node, event, listener });
}
function handleAutofill(textElement: TextElement, formControl: FormControl) {
// Chrome sometimes fills the input visually without actually writing a value to it, this combats it
handleChromeAutofill(textElement, formControl, notifyListeners);
// If the browser writes a value without triggering an event
function handleNoEventAutofilling() {
if (textElement.value !== formControl.initial) {
handleBlurOrClick({ target: textElement } as any);
return true;
}
return false;
}
const autofillingWithoutEventInstantly = handleNoEventAutofilling();
// In a SPA App the form is sometimes not filled instantly so we wait 100ms
if (!autofillingWithoutEventInstantly)
setTimeout(() => handleNoEventAutofilling(), 100);
}
function handleInput({ target: node }: Event) {
if (isFormMember(node)) {
const name = node["name"];
let value: string;
if (node.type === "checkbox" && node instanceof HTMLInputElement) {
value = node.checked ? "checked" : "";
} else {
value = node.value;
}
state[name].value = value;
notifyListeners();
}
}
function handleBlurOrClick({ target: node }: Event) {
if (isFormMember(node)) {
const control = state[node.name];
if (!control.touched) handleInput({ target: node } as any);
control.touched = true;
node.classList.add("touched");
notifyListeners();
}
}
function hideNotRepresentedFormControls(nodes: HTMLElement[]) {
for (const key of Object.keys(properties)) {
let isFormControlRepresentedInDom = false;
for (const node of nodes) {
if (key === node["name"]) isFormControlRepresentedInDom = true;
}
if (!isFormControlRepresentedInDom) delete state[key];
}
}
function setInitialValue(formMember: FormMember, formControl: FormControl) {
if (formControl.initial) formMember.value = formControl.initial;
}
function unmountEventListeners() {
for (const { node, event, listener } of eventListeners) {
node.removeEventListener(event, listener);
}
}
function notifyListeners() {
for (const callback of subscribers) callback(state);
}
function subscribe(callback: (form: Form) => void) {
subscribers.push(callback);
callback(state);
return { unsubscribe: () => unsubscribe(callback) };
}
function unsubscribe(subscriber: Function) {
const index = subscribers.indexOf(subscriber);
subscribers.splice(index, 1);
}
function set(value) {
state = value;
notifyListeners();
}
return action;
} | the_stack |
import { expect } from 'chai';
import chalk from 'chalk';
import { spy } from 'sinon';
import { ClientRequest } from 'http';
import nock from 'nock';
import {
extractProxy,
getHttpsTransport,
doFingerprintsMatch,
normalizeFingerprint,
applyCertPinning,
finishWatchJobStatusTask,
logJobStatus,
} from './package-deploy';
import { Socket } from 'net';
describe('package-deploy', () => {
beforeEach(() => {
nock.cleanAll();
});
describe('finishWatchJobStatusTask', () => {
it('with warnings', (done) => {
const consoleWarnSpy = spy(console, 'warn');
const consoleErrSpy = spy(console, 'error');
const warnings = ['w1', 'w2'];
const errors: string[] = [];
new Promise((resolve, reject) =>
finishWatchJobStatusTask({ warnings, errors, resolve, reject })
).then(() => {
expect(consoleWarnSpy.callCount).to.equal(1);
expect(consoleWarnSpy.getCall(0).args[0]).to.equal(
chalk.yellow('IMPORT WARNING(S) OCCURRED!')
);
expect(consoleErrSpy.callCount).to.equal(2);
expect(consoleErrSpy.getCall(0).args[0]).to.equal(chalk.yellow('w1'));
expect(consoleErrSpy.getCall(1).args[0]).to.equal(chalk.yellow('w2'));
consoleWarnSpy.restore();
consoleErrSpy.restore();
done();
});
});
it('with warnings and errors', (done) => {
const consoleWarnSpy = spy(console, 'warn');
const consoleErrSpy = spy(console, 'error');
const warnings = ['w1', 'w2'];
const errors = ['e1', 'e2'];
new Promise((resolve, reject) =>
finishWatchJobStatusTask({ warnings, errors, resolve, reject })
).catch(() => {
expect(consoleWarnSpy.callCount).to.equal(1);
expect(consoleWarnSpy.getCall(0).args[0]).to.equal(
chalk.yellow('IMPORT WARNING(S) OCCURRED!')
);
expect(consoleErrSpy.callCount).to.equal(5);
expect(consoleErrSpy.getCall(0).args[0]).to.equal(chalk.yellow('w1'));
expect(consoleErrSpy.getCall(1).args[0]).to.equal(chalk.yellow('w2'));
expect(consoleErrSpy.getCall(2).args[0]).to.equal(chalk.red('IMPORT ERROR(S) OCCURRED!'));
expect(consoleErrSpy.getCall(3).args[0]).to.equal(chalk.red('e1'));
expect(consoleErrSpy.getCall(4).args[0]).to.equal(chalk.red('e2'));
consoleWarnSpy.restore();
consoleErrSpy.restore();
done();
});
});
});
describe('logJobStatus', () => {
it('debug', () => {
const consoleSpy = spy(console, 'log');
const errors: string[] = [];
const warnings: string[] = [];
const entryLevel = 'DEBUG';
const message = 'Hello, I am debug message';
logJobStatus({ message, entryLevel, warnings, errors });
expect(errors.length).to.equal(0);
expect(warnings.length).to.equal(0);
expect(consoleSpy.callCount).to.equal(1);
expect(consoleSpy.getCall(0).args[0]).to.equal(chalk.white('Hello, I am debug message'));
consoleSpy.restore();
});
it('warning', () => {
const consoleSpy = spy(console, 'warn');
const errors: string[] = [];
const warnings: string[] = [];
const entryLevel = 'WARN';
const message = 'Hello, I am warning message';
logJobStatus({ message, entryLevel, warnings, errors });
expect(errors.length).to.equal(0);
expect(warnings).to.deep.equal(['Hello, I am warning message']);
expect(consoleSpy.callCount).to.equal(1);
expect(consoleSpy.getCall(0).args[0]).to.equal(chalk.yellow('Hello, I am warning message'));
consoleSpy.restore();
});
it('error', () => {
const consoleSpy = spy(console, 'error');
const errors: string[] = [];
const warnings: string[] = [];
const entryLevel = 'ERROR';
const message = 'Hello, I am error message';
logJobStatus({ message, entryLevel, warnings, errors });
expect(warnings.length).to.equal(0);
expect(errors).to.deep.equal(['Hello, I am error message']);
expect(consoleSpy.callCount).to.equal(1);
expect(consoleSpy.getCall(0).args[0]).to.equal(chalk.red('Hello, I am error message'));
consoleSpy.restore();
});
it('default', () => {
const consoleSpy = spy(console, 'log');
const errors: string[] = [];
const warnings: string[] = [];
const entryLevel = '';
const message = 'Hello, I am default message';
logJobStatus({ message, entryLevel, warnings, errors });
expect(errors.length).to.equal(0);
expect(warnings.length).to.equal(0);
expect(consoleSpy.callCount).to.equal(1);
expect(consoleSpy.getCall(0).args[0]).to.equal(chalk.green('Hello, I am default message'));
consoleSpy.restore();
});
});
describe('extractProxy', () => {
it('should return proxy object', () => {
expect(extractProxy('https://localhost:9999')).to.deep.equal({
protocol: 'https',
port: 9999,
host: 'localhost',
});
expect(extractProxy('http://myhostname:1234')).to.deep.equal({
protocol: 'http',
port: 1234,
host: 'myhostname',
});
});
it('should return undefined if proxy not provided', () => {
expect(extractProxy()).to.equal(undefined);
});
it('should return undefined if proxy is not valid url', () => {
process.exit = () => [] as never;
expect(extractProxy('test')).to.equal(undefined);
});
});
describe('applyCertPinning', () => {
it('should skip certs comparison', (done) => {
const req = ({
emit: spy(),
abort: spy(),
on: spy((ev: string, cb: (socket: Socket) => void) => {
expect(ev).to.equal('socket');
const socket = ({
on: spy((event: string, cb: () => void) => {
expect(event).to.equal('secureConnect');
// execute `secureConnect` event callback
cb();
expect((req.emit as any).called).to.equal(false);
expect((req.abort as any).called).to.equal(false);
expect((socket as any).getPeerCertificate.called).to.equal(true);
done();
}),
getPeerCertificate: spy(() => ({ fingerprint: 'TEST:TEST2:TEST3' })),
} as unknown) as Socket;
// execute `socket` event callback
cb(socket);
}),
} as unknown) as ClientRequest;
applyCertPinning(req, {
packagePath: 'aaa',
appName: 'bbb',
importServiceUrl: 'ccc',
secret: 'ddd',
});
});
it('should compare same certificates', (done) => {
const req = ({
emit: spy(),
abort: spy(),
on: spy((ev: string, cb: (socket: Socket) => void) => {
expect(ev).to.equal('socket');
const socket = ({
on: spy((event: string, cb: () => void) => {
expect(event).to.equal('secureConnect');
// execute `secureConnect` event callback
cb();
expect((req.emit as any).called).to.equal(false);
expect((req.abort as any).called).to.equal(false);
expect((socket as any).getPeerCertificate.called).to.equal(true);
done();
}),
getPeerCertificate: spy(() => ({ fingerprint: 'MY:SECRET:KEY' })),
} as unknown) as Socket;
// execute `socket` event callback
cb(socket);
}),
} as unknown) as ClientRequest;
applyCertPinning(req, {
packagePath: 'aaa',
appName: 'bbb',
importServiceUrl: 'ccc',
secret: 'ddd',
acceptCertificate: 'MY:SECRET:KEY',
});
});
it('should compare different certificates', (done) => {
const req = ({
emit: spy(),
abort: spy(),
on: spy((ev: string, cb: (socket: Socket) => void) => {
expect(ev).to.equal('socket');
const socket = ({
on: spy((event: string, cb: () => void) => {
expect(event).to.equal('secureConnect');
// execute `secureConnect` event callback
cb();
expect((req.emit as any).called).to.equal(true);
expect((req.emit as any).args[0][0]).to.equal('error');
expect((req.emit as any).args[0][1].message).to.deep.equal(
'Expected server SSL certificate to have thumbprint MY:SECRET:KEY111 from acceptCertificate, but got MY:SECRET:KEY222 from server. This may mean the certificate has changed, or that a malicious certificate is present.'
);
expect((req.abort as any).called).to.equal(true);
expect((socket as any).getPeerCertificate.called).to.equal(true);
done();
}),
getPeerCertificate: spy(() => ({ fingerprint: 'MY:SECRET:KEY222' })),
} as unknown) as Socket;
// execute `socket` event callback
cb(socket);
}),
} as unknown) as ClientRequest;
applyCertPinning(req, {
packagePath: 'aaa',
appName: 'bbb',
importServiceUrl: 'ccc',
secret: 'ddd',
acceptCertificate: 'MY:SECRET:KEY111',
});
});
});
describe('getHttpsTransport', () => {
it('should execute request', (done) => {
nock('https://superhost')
.get('/test')
.reply(200, {
success: true,
text: 'test',
});
const transport = getHttpsTransport({
packagePath: 'xxx',
appName: 'jssapp',
importServiceUrl: 'xxx',
secret: 'yyy',
});
const req = transport.request(
{ method: 'GET', hostname: 'superhost', path: '/test' },
(response) => {
let result = '';
response.on('data', (data) => {
result += data;
});
response.on('end', () => {
expect(result).to.equal('{"success":true,"text":"test"}');
done();
});
}
);
req.end();
});
});
describe('doFingerprintsMatch', () => {
it('should match', () => {
const fp = '5E:D1:5E:D4:D4:42:71:CC:30:A5:B6:A2:DA:A4:79:06:67:CB:F6:36';
expect(doFingerprintsMatch(fp, fp)).to.equal(true);
});
it('should not match', () => {
const fp1 = '11:D1:5E:D4:D4:42:71:CC:30:A5:B6:A2:DA:A4:79:06:67:CB:F6:36';
const fp2 = '5E:D1:5E:D4:D4:42:71:CC:30:A5:B6:A2:DA:A4:79:06:67:CB:F6:36';
expect(doFingerprintsMatch(fp1, fp2)).to.equal(false);
});
});
it('normalizeFingerprint', () => {
expect(
normalizeFingerprint('5E:D1:5E:D4:D4:42:71:CC:30:A5:B6:A2:DA:A4:79:06:67:CB:F6:36')
).to.equal('5ed15ed4d44271cc30a5b6a2daa4790667cbf636');
expect(
normalizeFingerprint('5e:d1:5e:d4:d4:42:71:cc:30:a5:b6:a2:da:a4:79:06:67:cb:F6:36')
).to.equal('5ed15ed4d44271cc30a5b6a2daa4790667cbf636');
expect(normalizeFingerprint('5ed15ed4d44271cc30a5b6a2daa4790667cbf636')).to.equal(
'5ed15ed4d44271cc30a5b6a2daa4790667cbf636'
);
});
}); | the_stack |
import { testTokenization } from '../test/testRunner';
testTokenization('dart', [
// Comments - single line
[
{
line: '//',
tokens: [{ startIndex: 0, type: 'comment.dart' }]
}
],
[
{
line: ' // a comment',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 4, type: 'comment.dart' }
]
}
],
// Broken nested tokens due to invalid comment tokenization
[
{
line: '/* //*/ a',
tokens: [
{ startIndex: 0, type: 'comment.dart' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'identifier.dart' }
]
}
],
[
{
line: '// a comment',
tokens: [{ startIndex: 0, type: 'comment.dart' }]
}
],
[
{
line: '//sticky comment',
tokens: [{ startIndex: 0, type: 'comment.dart' }]
}
],
[
{
line: '/almost a comment',
tokens: [
{ startIndex: 0, type: 'delimiter.dart' },
{ startIndex: 1, type: 'identifier.dart' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'identifier.dart' },
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'identifier.dart' }
]
}
],
[
{
line: '1 / 2; /* comment',
tokens: [
{ startIndex: 0, type: 'number.dart' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'delimiter.dart' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'number.dart' },
{ startIndex: 5, type: 'delimiter.dart' },
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'comment.dart' }
]
}
],
[
{
line: 'var x = 1; // my comment // is a nice one',
tokens: [
{ startIndex: 0, type: 'keyword.dart' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.dart' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'delimiter.dart' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'number.dart' },
{ startIndex: 9, type: 'delimiter.dart' },
{ startIndex: 10, type: '' },
{ startIndex: 11, type: 'comment.dart' }
]
}
],
// Comments - range comment, single line
[
{
line: '/* a simple comment */',
tokens: [{ startIndex: 0, type: 'comment.dart' }]
}
],
[
{
line: 'var x = /* a simple comment */ 1;',
tokens: [
{ startIndex: 0, type: 'keyword.dart' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.dart' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'delimiter.dart' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'comment.dart' },
{ startIndex: 30, type: '' },
{ startIndex: 31, type: 'number.dart' },
{ startIndex: 32, type: 'delimiter.dart' }
]
}
],
[
{
line: 'var x = /* comment */ 1; */',
tokens: [
{ startIndex: 0, type: 'keyword.dart' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.dart' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'delimiter.dart' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'comment.dart' },
{ startIndex: 21, type: '' },
{ startIndex: 22, type: 'number.dart' },
{ startIndex: 23, type: 'delimiter.dart' },
{ startIndex: 24, type: '' }
]
}
],
[
{
line: 'x = /**/;',
tokens: [
{ startIndex: 0, type: 'identifier.dart' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'delimiter.dart' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'comment.dart' },
{ startIndex: 8, type: 'delimiter.dart' }
]
}
],
[
{
line: 'x = /*/;',
tokens: [
{ startIndex: 0, type: 'identifier.dart' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'delimiter.dart' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'comment.dart' }
]
}
],
// Comments - range comment, multiple lines
[
{
line: '/* start of multiline comment',
tokens: [{ startIndex: 0, type: 'comment.dart' }]
},
{
line: 'a comment between without a star',
tokens: [{ startIndex: 0, type: 'comment.dart' }]
},
{
line: 'end of multiline comment*/',
tokens: [{ startIndex: 0, type: 'comment.dart' }]
}
],
[
{
line: 'var x = /* start a comment',
tokens: [
{ startIndex: 0, type: 'keyword.dart' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.dart' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'delimiter.dart' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'comment.dart' }
]
},
{
line: ' a ',
tokens: [{ startIndex: 0, type: 'comment.dart' }]
},
{
line: 'and end it */ 2;',
tokens: [
{ startIndex: 0, type: 'comment.dart' },
{ startIndex: 13, type: '' },
{ startIndex: 14, type: 'number.dart' },
{ startIndex: 15, type: 'delimiter.dart' }
]
}
],
// Keywords
[
{
line: 'var x = function() { };',
tokens: [
{ startIndex: 0, type: 'keyword.dart' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.dart' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'delimiter.dart' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'identifier.dart' },
{ startIndex: 16, type: 'delimiter.parenthesis.dart' },
{ startIndex: 18, type: '' },
{ startIndex: 19, type: 'delimiter.bracket.dart' },
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'delimiter.bracket.dart' },
{ startIndex: 22, type: 'delimiter.dart' }
]
}
],
[
{
line: ' var ',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 4, type: 'keyword.dart' },
{ startIndex: 7, type: '' }
]
}
],
// Numbers
[
{
line: '0',
tokens: [{ startIndex: 0, type: 'number.dart' }]
}
],
[
{
line: '0.10',
tokens: [{ startIndex: 0, type: 'number.float.dart' }]
}
],
[
{
line: '0x',
tokens: [
{ startIndex: 0, type: 'number.dart' },
{ startIndex: 1, type: 'identifier.dart' }
]
}
],
[
{
line: '0x123',
tokens: [{ startIndex: 0, type: 'number.hex.dart' }]
}
],
[
{
line: '0x5_2',
tokens: [{ startIndex: 0, type: 'number.hex.dart' }]
}
],
[
{
line: '0b1010_0101',
tokens: [{ startIndex: 0, type: 'number.binary.dart' }]
}
],
[
{
line: '0B001',
tokens: [{ startIndex: 0, type: 'number.binary.dart' }]
}
],
[
{
line: '10e3',
tokens: [{ startIndex: 0, type: 'number.float.dart' }]
}
],
[
{
line: '23.5',
tokens: [{ startIndex: 0, type: 'number.float.dart' }]
}
],
[
{
line: '23.5e3',
tokens: [{ startIndex: 0, type: 'number.float.dart' }]
}
],
[
{
line: '23.5e-3',
tokens: [{ startIndex: 0, type: 'number.float.dart' }]
}
],
[
{
line: '23.5E3',
tokens: [{ startIndex: 0, type: 'number.float.dart' }]
}
],
[
{
line: '23.5E-3',
tokens: [{ startIndex: 0, type: 'number.float.dart' }]
}
],
[
{
line: '0_52',
tokens: [{ startIndex: 0, type: 'number.dart' }]
}
],
[
{
line: '5_2',
tokens: [{ startIndex: 0, type: 'number.dart' }]
}
],
[
{
line: '5_______2',
tokens: [{ startIndex: 0, type: 'number.dart' }]
}
],
[
{
line: '3._1415F',
tokens: [
{ startIndex: 0, type: 'number.dart' },
{ startIndex: 1, type: 'delimiter.dart' },
{ startIndex: 2, type: 'identifier.dart' }
]
}
],
[
{
line: '999_99_9999_L',
tokens: [
{ startIndex: 0, type: 'number.dart' },
{ startIndex: 11, type: 'identifier.dart' }
]
}
],
[
{
line: '52_',
tokens: [
{ startIndex: 0, type: 'number.dart' },
{ startIndex: 2, type: 'identifier.dart' }
]
}
],
[
{
line: '0_x52',
tokens: [
{ startIndex: 0, type: 'number.dart' },
{ startIndex: 1, type: 'identifier.dart' }
]
}
],
[
{
line: '0x_52',
tokens: [
{ startIndex: 0, type: 'number.dart' },
{ startIndex: 1, type: 'identifier.dart' }
]
}
],
[
{
line: '0x52_',
tokens: [
{ startIndex: 0, type: 'number.hex.dart' },
{ startIndex: 4, type: 'identifier.dart' }
]
}
],
[
{
line: '052_',
tokens: [
{ startIndex: 0, type: 'number.octal.dart' },
{ startIndex: 3, type: 'identifier.dart' }
]
}
],
[
{
line: '23.5L',
tokens: [
{ startIndex: 0, type: 'number.float.dart' },
{ startIndex: 4, type: 'type.identifier.dart' }
]
}
],
[
{
line: '0+0',
tokens: [
{ startIndex: 0, type: 'number.dart' },
{ startIndex: 1, type: 'delimiter.dart' },
{ startIndex: 2, type: 'number.dart' }
]
}
],
[
{
line: '100+10',
tokens: [
{ startIndex: 0, type: 'number.dart' },
{ startIndex: 3, type: 'delimiter.dart' },
{ startIndex: 4, type: 'number.dart' }
]
}
],
[
{
line: '0 + 0',
tokens: [
{ startIndex: 0, type: 'number.dart' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'delimiter.dart' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'number.dart' }
]
}
],
// Strings
[
{
line: "var s = 's';",
tokens: [
{ startIndex: 0, type: 'keyword.dart' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.dart' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'delimiter.dart' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'string.dart' },
{ startIndex: 11, type: 'delimiter.dart' }
]
}
],
[
{
line: 'String s = "concatenated" + " String" ;',
tokens: [
{ startIndex: 0, type: 'type.identifier.dart' },
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'identifier.dart' },
{ startIndex: 8, type: '' },
{ startIndex: 9, type: 'delimiter.dart' },
{ startIndex: 10, type: '' },
{ startIndex: 11, type: 'string.dart' },
{ startIndex: 25, type: '' },
{ startIndex: 26, type: 'delimiter.dart' },
{ startIndex: 27, type: '' },
{ startIndex: 28, type: 'string.dart' },
{ startIndex: 37, type: '' },
{ startIndex: 38, type: 'delimiter.dart' }
]
}
],
[
{
line: '"quote in a string"',
tokens: [{ startIndex: 0, type: 'string.dart' }]
}
],
[
{
line: '"escaping \\"quotes\\" is cool"',
tokens: [
{ startIndex: 0, type: 'string.dart' },
{ startIndex: 10, type: 'string.escape.dart' },
{ startIndex: 12, type: 'string.dart' },
{ startIndex: 18, type: 'string.escape.dart' },
{ startIndex: 20, type: 'string.dart' }
]
}
],
[
{
line: '"\\"',
tokens: [{ startIndex: 0, type: 'string.invalid.dart' }]
}
],
// Annotations
[
{
line: '@',
tokens: [{ startIndex: 0, type: 'invalid.dart' }]
}
],
[
{
line: '@Override',
tokens: [{ startIndex: 0, type: 'annotation.dart' }]
}
]
]); | the_stack |
import { Form, Formik, FormikErrors } from "formik";
import React from "react";
import { Modal } from "react-bootstrap";
import { GetMessage, DEFAULT_EMAIL_CUSTOM_FIELD } from "src/common/helpers";
import TextField from "src/options/components/common/TextField";
import DataTypeSelectField from "src/options/components/custom-fields/DataTypeSelectField";
import AlphanumericOptions from "src/options/components/custom-fields/data-types/AlphanumericOptions";
import DateOptions from "src/options/components/custom-fields/data-types/DateOptions";
import EmailOptions from "src/options/components/custom-fields/data-types/EmailOptions";
import NumberOptions from "src/options/components/custom-fields/data-types/NumberOptions";
import RandomizedListOptions from "src/options/components/custom-fields/data-types/RandomizedListOptions";
import RegExOptions from "src/options/components/custom-fields/data-types/RegExOptions";
import TelephoneOptions from "src/options/components/custom-fields/data-types/TelephoneOptions";
import TextOptions from "src/options/components/custom-fields/data-types/TextOptions";
import { ICustomFieldForm, ICustomField } from "src/types";
const validate = (values: ICustomFieldForm): FormikErrors<ICustomFieldForm> => {
const errors: FormikErrors<ICustomFieldForm> = {};
let hasValidType = true;
if (!values.type) {
errors.type = GetMessage("customFields_validation_missingType");
hasValidType = false;
}
if (!values.name || values.name.trim().length === 0) {
errors.name = GetMessage("customFields_validation_missingName");
}
if (!values.match || values.match.trim().length === 0) {
errors.match = GetMessage("customFields_validation_missingMatch");
}
if (hasValidType) {
if (values.type === "telephone" && (!values.telephoneTemplate || values.telephoneTemplate.trim().length === 0)) {
errors.telephoneTemplate = GetMessage("customFields_validation_missingTelephoneTemplate");
}
if (values.type === "number") {
const minValue = parseInt(values.numberMin, 10);
if (Number.isNaN(minValue)) {
errors.numberMin = GetMessage("customFields_validation_missingMinValue");
}
if (!values.numberMax) {
errors.numberMax = GetMessage("customFields_validation_missingMaxValue");
}
if (values.numberMin && values.numberMax && parseInt(values.numberMax, 10) < parseInt(values.numberMin, 10)) {
errors.numberMax = GetMessage("customFields_validation_invalidMinMaxValue");
}
const decimalValue = parseInt(values.numberDecimalPlaces, 10);
if (Number.isNaN(decimalValue)) {
errors.numberDecimalPlaces = GetMessage("customFields_validation_missingDecimalPlaces");
}
}
if (values.type === "text") {
if (!values.textMin) {
errors.textMin = GetMessage("customFields_validation_missingMinValue");
}
if (!values.textMax) {
errors.textMax = GetMessage("customFields_validation_missingMaxValue");
}
if (!values.textMaxLength) {
errors.textMaxLength = GetMessage("customFields_validation_missingMaxLength");
}
if (values.textMin && parseInt(values.textMin, 10) < 1) {
errors.textMin = GetMessage("customFields_validation_invalidMaxValue");
}
if (values.textMin && values.textMax && parseInt(values.textMax, 10) < parseInt(values.textMin, 10)) {
errors.textMax = GetMessage("customFields_validation_invalidMinMaxValue");
}
if (values.textMaxLength && parseInt(values.textMaxLength, 10) < 1) {
errors.textMaxLength = GetMessage("customFields_validation_invalidMaxLengthValue");
}
}
if (values.type === "date") {
if (!values.dateTemplate || values.dateTemplate.trim().length === 0) {
errors.dateTemplate = GetMessage("customFields_validation_missingDateTemplate");
}
const dateMin = parseInt(values.dateMin, 10);
const dateMax = parseInt(values.dateMax, 10);
const dateMinDate = Date.parse(values.dateMinDate);
const dateMaxDate = Date.parse(values.dateMaxDate);
if (!Number.isNaN(dateMin) && !Number.isNaN(dateMinDate)) {
errors.dateMinDate = GetMessage("customFields_validation_onlyOneValueInGroup");
}
if (!Number.isNaN(dateMax) && !Number.isNaN(dateMaxDate)) {
errors.dateMaxDate = GetMessage("customFields_validation_onlyOneValueInGroup");
}
if (Number.isNaN(dateMin) && Number.isNaN(dateMinDate)) {
errors.dateMinDate = GetMessage("customFields_validation_atLeastOneValueInGroup");
}
if (Number.isNaN(dateMax) && Number.isNaN(dateMaxDate)) {
errors.dateMaxDate = GetMessage("customFields_validation_atLeastOneValueInGroup");
}
if (!Number.isNaN(dateMin) && !Number.isNaN(dateMax) && dateMin > dateMax) {
errors.dateMax = GetMessage("customFields_validation_invalidMinMaxValue");
}
if (!Number.isNaN(dateMinDate) && !Number.isNaN(dateMaxDate) && dateMinDate > dateMaxDate) {
errors.dateMaxDate = GetMessage("customFields_validation_invalidMinMaxValue");
}
}
if (values.type === "email") {
if (!values.emailUsername) {
errors.emailUsername = GetMessage("customFields_validation_invalidEmailUsername");
} else if (
values.emailUsername === "list" &&
(!values.emailUsernameList || values.emailUsernameList.trim().length === 0)
) {
errors.emailUsernameList = GetMessage("customFields_validation_missingEmailUsernameList");
} else if (
values.emailUsername === "regex" &&
(!values.emailUsernameRegEx || values.emailUsernameRegEx.trim().length === 0)
) {
errors.emailUsernameRegEx = GetMessage("customFields_validation_missingEmailUsernameRegEx");
}
if (!values.emailHostname) {
errors.emailHostname = GetMessage("customFields_validation_invalidEmailHostname");
} else if (
values.emailHostname === "list" &&
(!values.emailHostnameList || values.emailHostnameList.trim().length === 0)
) {
errors.emailHostnameList = GetMessage("customFields_validation_missingEmailHostnameList");
}
}
if (
values.type === "alphanumeric" &&
(!values.alphanumericTemplate || values.alphanumericTemplate.trim().length === 0)
) {
errors.alphanumericTemplate = GetMessage("customFields_validation_missingAlNumTemplate");
}
if (values.type === "regex" && (!values.regexTemplate || values.regexTemplate.trim().length === 0)) {
errors.regexTemplate = GetMessage("customFields_validation_missingRegEx");
}
if (values.type === "randomized-list" && (!values.list || values.list.trim().length === 0)) {
errors.list = GetMessage("customFields_validation_missingRandomItems");
}
}
return errors;
};
type Props = {
customField: ICustomField | null;
isOpen: boolean;
onClose: () => void;
onSave: (formValues: ICustomFieldForm) => void;
};
const CustomFieldModal = (props: Props) => {
const { customField } = props;
const initialValues: Partial<ICustomFieldForm> = {
match: "",
name: "",
numberMin: "",
numberMax: "",
numberDecimalPlaces: "",
textMin: "",
textMax: "",
textMaxLength: "",
telephoneTemplate: "",
dateTemplate: "",
dateMin: "",
dateMax: "",
dateMinDate: "",
dateMaxDate: "",
alphanumericTemplate: "",
regexTemplate: "",
list: "",
emailPrefix: "",
emailHostname: "list",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
emailHostnameList: DEFAULT_EMAIL_CUSTOM_FIELD.emailHostnameList!.join(", "),
emailUsername: "random",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
emailUsernameList: DEFAULT_EMAIL_CUSTOM_FIELD.emailUsernameList!.join(", "),
emailUsernameRegEx: "",
};
if (customField) {
initialValues.name = customField.name;
initialValues.type = customField.type;
initialValues.match = customField.match.join(", ");
switch (initialValues.type) {
case "alphanumeric":
initialValues.alphanumericTemplate = customField.template || "";
break;
case "date":
initialValues.dateTemplate = customField.template || "";
if (!Number.isNaN(Number(customField.min))) {
initialValues.dateMin = String(customField.min);
}
if (!Number.isNaN(Number(customField.max))) {
initialValues.dateMax = String(customField.max);
}
if (customField.minDate) {
initialValues.dateMinDate = customField.minDate;
}
if (customField.maxDate) {
initialValues.dateMaxDate = customField.maxDate;
}
break;
case "email": {
initialValues.emailPrefix = customField.emailPrefix || "";
initialValues.emailHostname = customField.emailHostname || "list";
initialValues.emailHostnameList = customField.emailHostnameList
? customField.emailHostnameList.join(", ")
: initialValues.emailHostnameList;
initialValues.emailUsername = customField.emailUsername || "list";
initialValues.emailUsernameRegEx = customField.emailUsernameRegEx || "";
initialValues.emailUsernameList = customField.emailUsernameList
? customField.emailUsernameList.join(", ")
: initialValues.emailUsernameList;
break;
}
case "number":
initialValues.numberMax = String(customField.max);
initialValues.numberMin = String(customField.min);
initialValues.numberDecimalPlaces = String(customField.decimalPlaces);
break;
case "randomized-list":
initialValues.list = customField.list ? customField.list.join("\n") : "";
break;
case "regex":
initialValues.regexTemplate = customField.template || "";
break;
case "telephone":
initialValues.telephoneTemplate = customField.template || "";
break;
case "text":
initialValues.textMax = String(customField.max);
initialValues.textMin = String(customField.min);
initialValues.textMaxLength = String(customField.maxLength);
break;
default:
break;
}
}
return (
<Modal size="lg" show={props.isOpen} onHide={props.onClose}>
<Formik initialValues={initialValues as ICustomFieldForm} validate={validate} onSubmit={props.onSave}>
{({ values, isSubmitting, isValid }) => (
<Form>
<Modal.Header closeButton>
<Modal.Title>{GetMessage("customFieldDetails_title")}</Modal.Title>
</Modal.Header>
<Modal.Body>
<DataTypeSelectField />
<TextField name="name" label={GetMessage("customFields_label_friendlyName")} />
<TextField
name="match"
label={GetMessage("customFields_label_match")}
placeholder={GetMessage("customFields_label_match_placeholder")}
helpText={GetMessage("customFields_label_match_helpText")}
/>
{values.type === "alphanumeric" && <AlphanumericOptions />}
{values.type === "date" && <DateOptions />}
{values.type === "email" && <EmailOptions {...values} />}
{values.type === "number" && <NumberOptions />}
{values.type === "randomized-list" && <RandomizedListOptions />}
{values.type === "regex" && <RegExOptions regexTemplate={values.regexTemplate} />}
{values.type === "telephone" && <TelephoneOptions />}
{values.type === "text" && <TextOptions />}
</Modal.Body>
<Modal.Footer>
<button type="button" className="btn btn-outline-secondary" onClick={props.onClose}>
{GetMessage("Cancel")}
</button>
<button type="submit" className="btn btn-primary" disabled={isSubmitting || !isValid}>
{GetMessage("Save")}
</button>
</Modal.Footer>
</Form>
)}
</Formik>
</Modal>
);
};
export default CustomFieldModal; | the_stack |
import { Button } from '@chakra-ui/react';
import { css } from '@emotion/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { isBrowser } from '@unly/utils';
import React, {
MutableRefObject,
useEffect,
useState,
} from 'react';
import {
Canvas,
CanvasRef,
EdgeProps,
NodeProps,
UndoRedoEvent,
useUndo,
} from 'reaflow';
import { useRecoilState } from 'recoil';
import { useDebouncedCallback } from 'use-debounce';
import { v1 as uuid } from 'uuid';
import { usePreviousValue } from '../../hooks/usePreviousValue';
import useRenderingTrace from '../../hooks/useTraceUpdate';
import { useUserSession } from '../../hooks/useUserSession';
import settings from '../../settings';
import { blockPickerMenuSelector } from '../../states/blockPickerMenuState';
import { canvasDatasetSelector } from '../../states/canvasDatasetSelector';
import { selectedEdgesSelector } from '../../states/selectedEdgesState';
import { selectedNodesSelector } from '../../states/selectedNodesState';
import { UserSession } from '../../types/auth/UserSession';
import BaseNodeData from '../../types/BaseNodeData';
import { CanvasDataset } from '../../types/CanvasDataset';
import { QueueCanvasDatasetMutation } from '../../types/CanvasDatasetMutation';
import { TypeOfRef } from '../../types/faunadb/TypeOfRef';
import {
applyPendingMutations,
mutationsQueue,
} from '../../utils/canvasDatasetMutationsQueue';
import {
onInit,
onUpdate,
updateUserCanvas,
} from '../../utils/canvasStream';
import { isOlderThan } from '../../utils/date';
import { createEdge } from '../../utils/edges';
import {
createNodeFromDefaultProps,
getDefaultNodePropsWithFallback,
} from '../../utils/nodes';
import {
getDefaultFromPort,
getDefaultToPort,
} from '../../utils/ports';
import canvasUtilsContext from '../context/canvasUtilsContext';
import BaseEdge from '../edges/BaseEdge';
import FaunaDBCanvasStream from '../FaunaDBCanvasStream';
import NodeRouter from '../nodes/NodeRouter';
type Props = {
canvasRef: MutableRefObject<CanvasRef | null>;
}
/**
* Canvas container.
*
* All nodes and edges are drawn within the <Canvas> element.
* Handles undo/redo.
* Handles selection of nodes/edges. (one at a time, multi-select isn't supported)
*
* Positioned in absolute position and takes all the spaces of its parent element (PlaygroundContainer).
*
* @see https://github.com/reaviz/reaflow
* @see https://reaflow.dev/?path=/story/docs-getting-started-basics--page
*/
const CanvasContainer: React.FunctionComponent<Props> = (props): JSX.Element | null => {
if (!isBrowser()) {
return null;
}
const {
canvasRef,
} = props;
const userSession = useUserSession();
/**
* The canvas ref contains useful properties (xy, scroll, etc.) and functions (zoom, centerCanvas, etc.)
*
* @see https://reaflow.dev/?path=/story/docs-advanced-refs--page
*/
useEffect(() => {
canvasRef?.current?.fitCanvas?.();
}, [canvasRef]);
const [blockPickerMenu, setBlockPickerMenu] = useRecoilState(blockPickerMenuSelector);
const [canvasDataset, setCanvasDataset] = useRecoilState(canvasDatasetSelector);
const [selectedNodes, setSelectedNodes] = useRecoilState(selectedNodesSelector);
const [selectedEdges, setSelectedEdges] = useRecoilState(selectedEdgesSelector);
const selections = selectedNodes; // TODO merge selected nodes and edges
const [hasClearedUndoHistory, setHasClearedUndoHistory] = useState<boolean>(false);
const [cursorXY, setCursorXY] = useState<[number, number]>([0, 0]);
const [isStreaming, setIsStreaming] = useState<boolean>(false);
const [canvasDocRef, setCanvasDocRef] = useState<TypeOfRef | undefined>(undefined); // We store the document ref to avoid fetching it for every change
const [mutationsCounter, setMutationsCounter] = useState<number>(0);
useRenderingTrace('CanvasContainer', {
...props,
blockPickerMenu,
canvasDataset,
selectedNodes,
selectedEdges,
hasClearedUndoHistory,
cursorXY,
isStreaming,
canvasDocRef,
mutationsCounter,
});
const nodes = canvasDataset?.nodes;
const edges = canvasDataset?.edges;
const previousCanvasDataset: CanvasDataset | undefined = usePreviousValue<CanvasDataset>(canvasDataset);
/**
* Applies all mutations that haven't been applied yet.
*/
useEffect(() => {
applyPendingMutations({ nodes, edges, mutationsCounter, setCanvasDataset });
});
/**
* Adds a new patch to apply to the existing queue.
*
* @param patch
* @param stateUpdateDelay (ms)
*/
const queueCanvasDatasetMutation: QueueCanvasDatasetMutation = (patch, stateUpdateDelay = 0) => {
mutationsQueue.push({
status: 'pending',
id: uuid(),
elementId: patch.elementId,
elementType: patch.elementType,
operationType: patch.operationType,
changes: patch.changes,
});
// Updating the mutations counter will re-render the component
if (stateUpdateDelay) {
setTimeout(() => {
setMutationsCounter(mutationsCounter + 1);
}, stateUpdateDelay);
} else {
setMutationsCounter(mutationsCounter + 1);
}
};
/**
* Debounces the database update invocation call.
*
* Helps avoid multiple DB updates and group them into one (by only considering the last one, which is the one that really matters).
*
* Due to debouncing, multiple database updates are avoided (when they happen in a close time-related burst),
* which is really important in a real-time context because it'll greatly reduce update events received by ALL subscribed clients.
*
* By eliminating burst updates and only considering the latest update, we greatly reduce the stream of updates sent to the DB.
* By ensuring those updates happen at most every 1 second (maxWait), which syncs the work being done locally with the remote,
* we ensure the work being done locally doesn't fall behind what's done on the remote.
*
* XXX Because we handle nodes/edges using different states, without debouncing then adding/removing a node would trigger 2 updates:
* - One for adding/removing the node
* - One for adding/removing the edge
* Thanks to debouncing, there is only one actual DB update.
*/
const debouncedUpdateUserCanvas = useDebouncedCallback(
(canvasRef: TypeOfRef | undefined, user: Partial<UserSession>, newCanvasDataset: CanvasDataset, previousCanvasDataset: CanvasDataset | undefined) => {
updateUserCanvas(canvasDocRef, user, canvasDataset, previousCanvasDataset);
},
100, // Wait 100ms for other changes to happen, if no change happen then invoke the update
{ maxWait: 1000 }, // In any case, wait for no more than 1 second, at most
);
/**
* When nodes or edges are modified, updates the persisted data in FaunaDB.
*
* Persisted data are automatically loaded when the stream is initialized.
*/
useEffect(() => {
// Only save changes once the stream has started, to avoid saving anything until the initial canvas dataset was initialized
if (isStreaming) {
debouncedUpdateUserCanvas(canvasDocRef, userSession, canvasDataset, previousCanvasDataset);
}
}, [canvasDataset]);
/**
* Uses Reaflow Undo/Redo helpers.
*
* Automatically binds shortcuts (cmd+z/cmd+shift+z).
*
* TODO Doesn't handle massive undos through shortcut (cmd+z) very well - See https://github.com/reaviz/reaflow/issues/60
*
* @see https://reaflow.dev/?path=/story/demos-undo-redo
*/
const {
undo,
redo,
canUndo,
canRedo,
clear,
} = useUndo({
nodes,
edges,
onUndoRedo: (state: UndoRedoEvent) => {
console.log('Undo / Redo', state);
setCanvasDataset({
nodes: state?.nodes || [],
edges: state?.edges || [],
});
},
maxHistory: Infinity,
});
/**
* Ensures the "start" node and "end" node are always present.
*
* Will automatically create the start/end nodes, even when all the nodes have been deleted.
* Disabled until the stream has started to avoid creating the start node even before we got the initial canvas dataset from the stream.
*/
useEffect(() => {
const existingStartNode: BaseNodeData | undefined = nodes?.find((node: BaseNodeData) => node?.data?.type === 'start');
const existingEndNode: BaseNodeData | undefined = nodes?.find((node: BaseNodeData) => node?.data?.type === 'end');
if ((!existingStartNode || !existingEndNode) && isStreaming) {
console.groupCollapsed('Creating default canvas dataset');
console.info(`No "start" or "end" node found. Creating them automatically.`, nodes, edges, existingStartNode, existingEndNode);
const startNode: BaseNodeData = createNodeFromDefaultProps(getDefaultNodePropsWithFallback('start'));
const endNode: BaseNodeData = createNodeFromDefaultProps(getDefaultNodePropsWithFallback('end'));
const newNodes = [
startNode,
endNode,
];
const newEdges = [
createEdge(startNode, endNode, getDefaultFromPort(startNode), getDefaultToPort(endNode)),
];
setCanvasDataset({
nodes: newNodes,
edges: newEdges,
});
// Clearing the undo/redo history to avoid allowing the editor to "undo" the creation of the "start" node
// If the "start" node creation step is "undoed" then it'd be re-created automatically, which would erase the whole history
// See https://github.com/reaviz/reaflow/issues/60#issuecomment-780499761
// Doing it only once after a reset to avoid infinite loop rendering
if (!hasClearedUndoHistory) {
console.info('Clearing undo/redo history to start from a clean state.');
clear();
setHasClearedUndoHistory(true);
}
console.groupEnd();
}
}, [nodes]);
/**
* When clicking on the canvas:
* - Unselect all elements (nodes, edges)
* - Hide the block menu picker, unless it was opened through targeting the canvas itself
* (avoids closing the menu when dropping an edge on the canvas)
*
* XXX Sometimes, it is triggered even though the click doesn't target the canvas itself specifically.
* For instance, it might be triggered when clicking on an SVG displayed within a <foreignObject>.
*/
const onCanvasClick = (event: React.MouseEvent<SVGGElement, MouseEvent>): void => {
if (event.target === canvasRef?.current?.svgRef?.current) {
// Unselecting all selected elements (nodes, edges)
if (selectedNodes?.length > 0) {
setSelectedNodes([]);
}
if (selectedEdges?.length > 0) {
setSelectedEdges([]);
}
console.log('onCanvasClick event', event);
let isBlockPickerMenuTargetingCanvas = false;
if (typeof blockPickerMenu?.eventTarget !== 'undefined') {
isBlockPickerMenuTargetingCanvas = blockPickerMenu?.eventTarget === canvasRef?.current?.svgRef?.current;
}
// Automatically hide the blockPickerMenu when clicking on the canvas, if it is displayed and was created more than a second ago
// Using a delay is a workaround, because when dropping the edge onto the canvas, it counts as a click
// If we weren't using a delay, the blockPickerMenu would be displayed and then automatically hidden
if (blockPickerMenu?.isDisplayed && (!isBlockPickerMenuTargetingCanvas || isOlderThan(blockPickerMenu?.at, 1000))) {
setBlockPickerMenu({
isDisplayed: false,
});
}
setCursorXY([event?.clientX, event?.clientY]);
}
};
/**
* Node component. All nodes will render trough this component.
*
* Uses the NodeRouter component which will render a different node layout, depending on the node "type".
*/
const Node = (nodeProps: NodeProps) => {
return (
<NodeRouter
nodeProps={nodeProps}
queueCanvasDatasetMutation={queueCanvasDatasetMutation}
/>
);
};
/**
* Edge component. All edges will render trough this component.
*
* All edges render the same way, no matter to which node they're linked to.
* (There is no "EdgeRouter", unlike with nodes)
*/
const Edge = (edgeProps: EdgeProps) => {
return (
<BaseEdge
{...edgeProps}
queueCanvasDatasetMutation={queueCanvasDatasetMutation}
/>
);
};
/**
* Those options will be forwarded to elkLayout under the "options" property.
*
* @see https://github.com/reaviz/reaflow/blob/master/src/layout/elkLayout.ts Default values applied by Reaflow
* @see https://github.com/kieler/elkjs#api
* @see https://www.eclipse.org/elk/reference.html
* @see https://www.eclipse.org/elk/reference/options.html
*/
const elkLayoutOptions = {
'elk.algorithm': 'layered',
};
return (
<div
className={'canvas-container'}
css={css`
// Positioned in absolute position and takes all the spaces of its parent element (PlaygroundContainer)
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
// CSS rules applied to the whole <Canvas> (global rules, within the <Canvas>)
.reaflow-canvas {
// Make all edges display an infinite dash animation
.edge-svg-graph {
stroke: ${settings.canvas.edges.strokeColor};
stroke-dasharray: 5;
animation: dashdraw .5s linear infinite;
stroke-width: 1;
&.is-selected {
stroke: ${settings.canvas.edges.selected.strokeColor};
stroke-dasharray: 0;
animation: none;
}
}
.port {
// Ports are being highlighted during edge dragging, to make it obvious what are the possible destination ports
&.is-highlighted {
stroke: blue !important;
}
// Make all output ports used by IfNode display differently to distinguish them easily
&.port-if {
&-true {
stroke: green !important;
}
&-false {
stroke: red !important;
}
}
}
@keyframes dashdraw {
0% {
stroke-dashoffset: 10;
}
}
}
`}
>
<div
style={{ position: 'absolute', top: 10, left: 20, zIndex: 999 }}
>
<Button
variant="primary"
onClick={undo}
disabled={!canUndo}
>
Undo
</Button>
<Button
variant="primary"
onClick={redo}
disabled={!canRedo}
>
Redo
</Button>
</div>
<div
style={{ position: 'absolute', top: 10, right: 20, zIndex: 999 }}
>
<Button
variant="primary"
onClick={() => {
if (confirm(`Remove all nodes and edges?`)) {
setHasClearedUndoHistory(false); // Reset to allow clearing history even if the option is used several times in the same session
setCanvasDataset({
nodes: [],
edges: [],
});
}
}}
>
Clear all
</Button>
</div>
<div
style={{ position: 'absolute', bottom: 10, right: 20, zIndex: 999 }}
>
<Button
variant="primary"
onClick={canvasRef?.current?.zoomOut}
>
<FontAwesomeIcon
icon={['fas', 'search-minus']}
/>
</Button>
<Button
variant="primary"
onClick={canvasRef?.current?.zoomIn}
>
<FontAwesomeIcon
icon={['fas', 'search-plus']}
/>
</Button>
<Button
variant="primary"
onClick={canvasRef?.current?.centerCanvas}
>
<FontAwesomeIcon
icon={['fas', 'bullseye']}
/>
</Button>
<Button
variant="primary"
onClick={canvasRef?.current?.fitCanvas}
>
<FontAwesomeIcon
icon={['fas', 'compress-arrows-alt']}
/>
</Button>
</div>
<div
style={{ position: 'absolute', bottom: 10, left: 20, zIndex: 999 }}
>
X: {cursorXY?.[0]} | Y: {cursorXY?.[1]}
</div>
<canvasUtilsContext.Provider
value={{
containerRef: canvasRef?.current?.containerRef,
centerCanvas: canvasRef?.current?.centerCanvas,
fitCanvas: canvasRef?.current?.fitCanvas,
setZoom: canvasRef?.current?.setZoom,
zoomIn: canvasRef?.current?.zoomIn,
zoomOut: canvasRef?.current?.zoomOut,
}}
>
<Canvas
ref={canvasRef}
className={'reaflow-canvas'}
direction={settings.canvas.direction}
onCanvasClick={onCanvasClick}
maxWidth={settings.canvas.maxWidth}
maxHeight={settings.canvas.maxHeight}
nodes={nodes}
edges={edges}
selections={selections}
node={Node}
edge={Edge}
onLayoutChange={layout => console.log('Layout', layout)}
layoutOptions={elkLayoutOptions}
/>
{/* Handles the real-time stream */}
<FaunaDBCanvasStream
onInit={(canvasDataset: CanvasDataset) => {
onInit(canvasDataset);
// Mark the stream has running
setIsStreaming(true);
}}
onUpdate={onUpdate}
setCanvasDocRef={setCanvasDocRef}
/>
</canvasUtilsContext.Provider>
</div>
);
};
export default CanvasContainer; | the_stack |
import ChangeListeners from './ChangeListeners';
import {hint} from './Console';
import EventObject from './EventObject';
import {EventsClass} from './Events';
import Listeners from './Listeners';
import {PropertyTypes, types} from './property-types';
import * as symbols from './symbols';
import {notify} from './symbols';
import {allowOnlyKeys, allowOnlyValues, equals} from './util';
export default abstract class NativeObject extends EventsClass {
static defineProperties<T extends NativeObject>(target: T, definitions: PropertyDefinitions<T>) {
for (const name in definitions) {
NativeObject.defineProperty(target, name as keyof T & string, definitions[name]);
}
}
static defineProperty<T extends NativeObject>(
target: T,
name: keyof T & string,
property: TabrisProp<any, unknown, any>
) {
const def = normalizeProperty(property);
Object.defineProperty(target, '$prop_' + name, {
enumerable: false,
writable: false,
value: def
});
Object.defineProperty(target, name, {
set(value) {
this.$setProperty(name, value);
},
get() {
return this.$getProperty(name);
}
});
if (!def.const) {
this.defineChangeEvent(target, name);
}
}
static defineEvents<T extends NativeObject>(target: T, definitions: EventDefinitions) {
for (const name in definitions) {
NativeObject.defineEvent(target, name as any, definitions[name]);
}
}
static defineEvent<T extends NativeObject>(
target: T,
name: string,
definition: EventDefinition | true
) {
const property = 'on' + name.charAt(0).toUpperCase() + name.slice(1);
const $property = '$' + property;
const $eventProperty = '$event_' + name as keyof T;
if (target[$eventProperty]) {
throw new Error('Event already defined');
}
const def = (target as any)[$eventProperty] = normalizeEvent.call(this.prototype, name, definition);
if (def.changes) {
this.synthesizeChangeEvents(target, name, def);
}
Object.defineProperty(target, property, {
get() {
if (!this[$property]) {
this[$property] = new Listeners(this, name);
}
return this[$property];
}
});
}
static defineChangeEvents<T extends NativeObject>(target: T, properties: Array<keyof T & string>) {
properties.forEach(property => this.defineChangeEvent(target, property));
}
static defineChangeEvent<T>(target: T, property: keyof T & string) {
const listenersProperty = 'on' + property.charAt(0).toUpperCase() + property.slice(1) + 'Changed';
const $listenersProperty = '$' + property + 'Changed';
Object.defineProperty(target, listenersProperty, {
get() {
if (!this[$listenersProperty]) {
this[$listenersProperty] = new ChangeListeners(this, property);
}
return this[$listenersProperty];
}
});
}
static synthesizeChangeEvents<T extends NativeObject>(
target: T,
sourceEvent: string,
sourceDef: EventDefinition
) {
const name = sourceDef.changes + 'Changed';
const changeListener = function(this: NativeObject, ev: EventObject) {
const changeValue = sourceDef.changeValue as ((arg: EventObject) => any);
this.$trigger(name, {value: changeValue(ev)});
};
const $changeEventProperty = '$event_' + name as keyof T;
const changeEventDef: EventDefinition
= (target as any)[$changeEventProperty]
= target[$changeEventProperty] || {listen: []};
changeEventDef.listen?.push((instance, listening) => {
instance._onoff(sourceEvent, listening, changeListener);
});
if (sourceDef.nativeObservable !== false) {
target[symbols.nativeObservables] = (target[symbols.nativeObservables] || []).concat();
target[symbols.nativeObservables]!.push(name);
}
}
static extend(nativeType: string, superType = NativeObject) {
return class extends superType {
get _nativeType() { return nativeType; }
};
}
readonly cid: string = '';
_isDisposed?: boolean;
_inDispose?: boolean;
_disposedToStringValue?: string;
[symbols.nativeObservables]?: string[];
private $props?: Partial<this> | null;
constructor(param?: object | boolean) {
super();
// TODO: Use decorators to make non-enumerable properties
Object.defineProperty(this, '$props', {
enumerable: false,
writable: true,
value: {}
});
this._nativeCreate(param);
}
set(properties: Props<this>) {
if (arguments.length === 0) {
throw new Error('Not enough arguments');
}
if (arguments.length > 1) {
throw new Error('Too many arguments');
}
this._reorderProperties(Object.keys(properties || {}))
.forEach(name => setExistingProperty.call(this, name, properties[name as keyof typeof properties]));
return this;
}
dispose() {
this._dispose();
}
isDisposed() {
return !!this._isDisposed;
}
toString() {
return this.constructor.name;
}
[symbols.toXML]() {
if (this._isDisposed) {
return `<${this._getXMLElementName()} cid='${this.cid}' disposed='true'/>`;
}
const content = this._getXMLContent();
if (!content.length) {
return this._getXMLHeader(false);
}
return `${this._getXMLHeader(true)}\n${content.join('\n')}\n${this._getXMLFooter(true)}`;
}
_dispose(skipNative?: boolean) {
if (!this._isDisposed && !this._inDispose) {
Object.defineProperties(this, {
_inDispose: {enumerable: false, writable: false, value: true},
_disposedToStringValue: {enumerable: false, writable: false, value: this.toString()}
});
this.toString = () => this._disposedToStringValue + ' (disposed)';
this._trigger('dispose');
this._release();
if (!skipNative) {
tabris._nativeBridge!.destroy(this.cid);
}
tabris._nativeObjectRegistry!.remove(this.cid);
this.$props = null;
Object.defineProperty(
this, '_isDisposed', {enumerable: false, writable: false, value: true}
);
}
}
$getProperty(name: PropName<this>) {
if (this._isDisposed) {
hint(this, 'Cannot get property "' + name + '" on disposed object');
return;
}
const def = this._getPropertyDefinition(name);
if (def.nocache) {
const nativeValue = this._nativeGet(name);
return def.type?.decode ? def.type.decode.call(null, nativeValue, this) : nativeValue;
}
const storedValue = this._getStoredProperty(name);
if (storedValue !== undefined) {
return storedValue;
}
if (def.default !== undefined) {
return def.default;
}
const value = this._nativeGet(name);
const decodedValue = def.type?.decode ? def.type.decode.call(this, value, this) : value;
this._storeProperty(name, decodedValue);
return decodedValue;
}
$setProperty<Name extends PropName<this>>(name: Name, value: unknown) {
if (this._isDisposed) {
hint(this, 'Cannot set property "' + name + '" on disposed object');
return;
}
const def = this._getPropertyDefinition(name);
if (def.readonly) {
hint(this, `Can not set read-only property "${name}"`);
return;
} else if (def.const && this._wasSet(name)) {
hint(this, `Can not set const property "${name}"`);
return;
}
let convertedValue: this[Name];
try {
convertedValue = this._convertValue(def, value, value);
} catch (ex) {
this._printPropertyWarning(name, ex);
return;
}
const encodedValue = def.type?.encode?.call(null, convertedValue, this);
if (def.nocache) {
this._beforePropertyChange(name, convertedValue);
this._nativeSet(name, encodedValue);
if (!def.const) {
this._triggerChangeEvent(name, convertedValue);
}
} else if (!equals(this._getStoredProperty(name), convertedValue) || !this._wasSet(name)) {
this._beforePropertyChange(name, convertedValue);
this._nativeSet(name, encodedValue);// TODO should not happen if changing from unset to default
this._storeProperty(name, convertedValue, def.const);
}
}
_convertValue(def: Partial<PropertyDefinition>, value: unknown, convertedValue: any) {
if (!def.nullable || value !== null) {
// TODO: ensure convert has no write-access to the NativeObject instance via proxy
convertedValue = allowOnlyValues(def.type?.convert?.call(null, value, this), def.choice);
}
return convertedValue;
}
_printPropertyWarning(name: string, ex: Error) {
hint(this, 'Ignored unsupported value for property "' + name + '": ' + ex.message);
}
_storeProperty<Name extends PropName<this>>(
name: Name,
newValue: this[Name],
noChangeEvent: boolean = false
) {
if ((newValue as any) === this._getStoredProperty(name) && this._wasSet(name)) {
return false;
}
if (newValue === undefined) {
return false;
} else {
this.$props![name] = newValue;
}
if (!noChangeEvent) {
this._triggerChangeEvent(name, newValue);
}
return true;
}
_getStoredProperty(name: PropName<this>) {
let result = (this.$props ? this.$props[name] : undefined);
if (result === undefined) {
result = this._getPropertyDefinition(name).default;
}
return result;
}
_wasSet(name: PropName<this>) {
return name in (this.$props || {});
}
_getPropertyDefinition(propertyName: PropName<this>): Partial<PropertyDefinition> {
const defKey = '$prop_' + propertyName as keyof this;
return this[defKey] || {};
}
_decodeProperty(typeDef: TypeDef<any, any, this>, value: any) {
return (typeDef && typeDef.decode) ? typeDef.decode.call(null, value, this) : value;
}
_triggerChangeEvent(propertyName: PropName<this>, value: any) {
this.$trigger(propertyName + 'Changed', {value});
}
get _nativeType(): string {
throw new Error('Can not create instance of abstract class ' + this.constructor.name);
}
_nativeCreate(param: any) {
this._register();
tabris._nativeBridge!.create(this.cid, this._nativeType);
if (param instanceof Object) {
this.set(param);
}
}
_register() {
if (typeof tabris === 'undefined' || !tabris._nativeBridge) {
throw new Error('tabris.js not started');
}
const cid = tabris._nativeObjectRegistry!.register(this);
Object.defineProperty(this, 'cid', {value: cid});
}
_reorderProperties(properties: string[]): string[] {
return properties;
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
_release() {}
/**
* Called when a property is about to be changed, past conversion and all
* other pre-checks. May have side-effects. Exceptions will not be catched.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
_beforePropertyChange(name: string, value: any) {}
_listen(name: string, listening: boolean) {
const defKey = '$event_' + name as keyof this;
const eventDef = this[defKey] as EventDefinition;
if (eventDef) {
eventDef.listen?.forEach(listen => listen(this, listening));
}
}
_nativeListen(event: string, state: boolean) {
this._checkDisposed();
tabris._nativeBridge!.listen(this.cid, event, state);
}
_trigger(name: string, eventData = {}) {
return this.$trigger(name, eventData);
}
$trigger(name: string, eventData: {[data: string]: unknown} = {}) {
const dispatchObject = this[notify](name, eventData, false);
return !!(dispatchObject as any)?.defaultPrevented;
}
_onoff(name: string, listening: boolean, listener: Function) {
if (listening) {
this.on(name, listener);
} else {
this.off(name, listener);
}
}
_checkDisposed() {
if (this._isDisposed) {
throw new Error('Object is disposed');
}
}
_nativeSet(name: string, value: unknown) {
this._checkDisposed();
tabris._nativeBridge!.set(this.cid, name, value === undefined ? null : value);
}
_nativeGet(name: string) {
this._checkDisposed();
return tabris._nativeBridge!.get(this.cid, name);
}
_nativeCall(method: string, parameters?: NativeProps) {
this._checkDisposed();
return tabris._nativeBridge!.call(this.cid, method, parameters as any);
}
_getXMLHeader(hasChild: boolean) {
const attributes = this._getXMLAttributes()
.map(entry => `${entry[0]}='${('' + entry[1]).replace(/'/g, '\\\'').replace(/\n/g, '\\n')}'`)
.join(' ');
return `<${this._getXMLElementName()} ${attributes}${!hasChild ? '/' : ''}>`;
}
_getXMLFooter(hasChild: boolean) {
return hasChild ? `</${this._getXMLElementName()}>` : '';
}
_getXMLElementName() {
return this.constructor.name;
}
_getXMLAttributes() {
return [['cid', this.cid]];
}
_getXMLContent(): string[] {
return [];
}
}
export default interface NativeObject {
onDispose: Listeners & Listeners['addListener'];
}
NativeObject.defineEvents(NativeObject.prototype, {
dispose: true
});
function setExistingProperty<Target extends NativeObject>(this: Target, name: string, value: any) {
if (!(name in this)) {
hint(this, 'There is no setter for property "' + name + '"');
}
this[name as keyof Target] = value;
}
function normalizeProperty(config: TabrisProp<any, any, any>): PropertyDefinition {
const def = {
type: normalizeType(config.type || {}),
default: config.default,
nullable: !!config.nullable,
const: !!config.const,
nocache: !!config.nocache,
readonly: !!config.readonly,
choice: config.choice
};
if (def.readonly && (def.default !== undefined)) {
throw new Error('Can not combine "nocache" with "readonly"');
}
if (def.readonly && def.nullable) {
throw new Error('Can not combine "nullable" with "readonly"');
}
if (def.readonly && def.choice) {
throw new Error('Can not combine "choice" with "readonly"');
}
if (def.choice && def.choice.length < 2) {
throw new Error('"choice" needs at least two entries');
}
if ((def.default === undefined) && !def.nocache && !def.readonly) {
throw new Error('"default" must be given unless "nocache" or "readonly" is true.');
}
allowOnlyKeys(config, Object.keys(def));
return def;
}
function normalizeEvent(this: NativeObject, name: string, definition: EventDefinition|true): EventDefinition {
const result: EventDefinition = {listen: []};
if (definition === true) {
return result;
}
Object.assign(result, definition);
if (definition.native) {
result.listen?.push((target, listening) => {
target._nativeListen(name, listening);
});
}
const changes = result.changes;
if(changes) {
const changeValue = result.changeValue;
if (typeof changeValue === 'string') {
result.changeValue = (ev: EventObject & {[key: string]: any}) => ev[changeValue];
} else if (!changeValue) {
result.changeValue = (ev: EventObject & {[key: string]: any}) => ev[changes];
}
}
return result;
}
function normalizeType(
config: keyof PropertyTypes | TypeDef<any, any, any> | Constructor<NativeObject>
): TypeDef<any, any, any> {
if (config instanceof Function) {
if (!(config.prototype instanceof NativeObject)) {
throw new Error('not a constructor of NativeObject');
}
return {
convert(value) {
if (!(value instanceof config)) {
throw new Error('Not an instance of ' + config.name);
}
return value;
},
encode(value) {
return value ? value.cid : null;
},
decode(value) {
return value ? tabris._nativeObjectRegistry!.find(value) : null;
}
};
}
const def = typeof config === 'string' ? types[config] : config;
allowOnlyKeys(def, ['convert', 'encode', 'decode']);
return {
convert: def.convert || (v => v),
encode: def.encode || (v => v),
decode: def.decode || (v => v)
};
} | the_stack |
import xs, {Stream} from 'xstream';
import concat from 'xstream/extra/concat';
import sampleCombine from 'xstream/extra/sampleCombine';
import debounce from 'xstream/extra/debounce';
import {Reducer, Lens} from '@cycle/state';
import {Platform} from 'react-native';
import {AsyncStorageSource} from 'cycle-native-asyncstorage';
import {Image} from 'react-native-image-crop-picker';
import {MsgId, FeedId} from 'ssb-typescript';
import {SSBSource, MentionSuggestion} from '../../drivers/ssb';
import {State as TopBarState} from './top-bar';
import {Props} from './index';
interface Selection {
start: number;
end: number;
}
export interface State {
postText: string;
postTextOverride: string;
postTextSelection: Selection;
mentionQuery: string;
mentionSuggestions: Array<MentionSuggestion & {imageUrl?: string}>;
mentionChoiceTimestamp: number;
contentWarning: string;
contentWarningPreviewOpened: boolean;
selfFeedId: FeedId;
selfAvatarUrl?: string;
selfName: string | undefined;
previewing: boolean;
root: MsgId | undefined;
fork: MsgId | undefined;
branch: MsgId | undefined;
authors: Array<FeedId>;
}
const MAX_SUGGESTIONS = Platform.OS === 'web' ? 6 : 4;
export const topBarLens: Lens<State, TopBarState> = {
get: (parent: State): TopBarState => {
return {
enabled: parent.postText.length > 0,
previewing: parent.previewing,
isReply: !!parent.root,
};
},
// Ignore writes from the child
set: (parent: State, child: TopBarState): State => {
return parent;
},
};
export function isPost(state: State): boolean {
return !state.root;
}
export function isReply(state: State): boolean {
return !!state.root;
}
export function isTextEmpty(state: State): boolean {
return !state.postText;
}
export function hasText(state: State): boolean {
return state.postText.length > 0;
}
function parseMention(postText: string, selection: Selection): string | null {
if (selection.start !== selection.end) return null;
const results = /(^| )@(\w+)$/gm.exec(postText.substr(0, selection.start));
return results?.[2] ?? null;
}
function appendToPostText(postText: string, other: string) {
let separator = '';
if (postText.trim().length > 0) {
// Count how many new lines are already at the end of the postText
const res = /(\n+)$/g.exec(postText);
const prevLines = !res || !res[0] ? 0 : res[0].split('\n').length - 1;
// Count how many new lines to add, in order to create space
const addLines = Math.max(2 - prevLines, 0);
separator = Array(addLines + 1).join('\n');
}
return postText + separator + other + '\n\n';
}
export interface Actions {
updatePostText$: Stream<string>;
updateSelection$: Stream<Selection>;
chooseMention$: Stream<FeedId>;
cancelMention$: Stream<any>;
updateContentWarning$: Stream<string>;
toggleContentWarningPreview$: Stream<any>;
disablePreview$: Stream<any>;
enablePreview$: Stream<any>;
addAudio$: Stream<string>;
addPictureWithCaption$: Stream<{caption: string; image: Image}>;
}
export default function model(
props$: Stream<Props>,
actions: Actions,
state$: Stream<State>,
asyncStorageSource: AsyncStorageSource,
ssbSource: SSBSource,
): Stream<Reducer<State>> {
const propsReducer$ = props$.take(1).map(
(props) =>
function propsReducer(): State {
return {
postText: props.text ?? '',
postTextOverride: props.text ?? '',
postTextSelection: props.text
? {start: props.text.length, end: props.text.length}
: {start: 0, end: 0},
mentionQuery: '',
mentionSuggestions: [],
mentionChoiceTimestamp: 0,
root: props.root,
fork: props.fork,
branch: props.branch,
authors: props.authors ?? [],
contentWarning: '',
contentWarningPreviewOpened: true,
selfAvatarUrl: props.selfAvatarUrl,
selfFeedId: props.selfFeedId,
selfName: undefined,
previewing: false,
};
},
);
const selfNameReducer$ = props$
.take(1)
.map((props) => ssbSource.profileAboutLive$(props.selfFeedId))
.flatten()
.map(
(about) =>
function aboutReducer(prev: State): State {
if (!!about.name && about.name !== about.id) {
return {...prev, selfName: about.name};
} else {
return prev;
}
},
);
const updatePostTextReducer$ = actions.updatePostText$.map(
(postText) =>
function updatePostTextReducer(prev: State): State {
return {...prev, postText};
},
);
const selectionAndState$ = actions.updateSelection$
.compose(sampleCombine(state$))
.compose(debounce(100));
const openMentionSuggestionsReducer$ = selectionAndState$
.map(([selection, state]) => {
const mentionQuery = parseMention(state.postText, selection);
if (!mentionQuery) return xs.never();
return ssbSource
.getMentionSuggestions(mentionQuery, state.authors)
.map(
(suggestions) =>
[suggestions, selection] as [Array<MentionSuggestion>, Selection],
);
})
.flatten()
.map(
([mentionSuggestions, prevSelection]) =>
function openMentionSuggestionsReducer(prev: State): State {
let mentionQuery = parseMention(prev.postText, prevSelection);
const cursor = prevSelection.start;
if (mentionSuggestions.length && mentionQuery) {
mentionQuery = '@' + mentionQuery;
const postTextSelection = {
start: cursor - mentionQuery.length,
end: cursor - mentionQuery.length,
};
return {
...prev,
postTextSelection,
mentionQuery,
mentionSuggestions: mentionSuggestions.slice(0, MAX_SUGGESTIONS),
};
} else {
return {
...prev,
mentionSuggestions: mentionSuggestions.slice(0, MAX_SUGGESTIONS),
};
}
},
);
const ignoreMentionSuggestionsReducer$ = selectionAndState$.map(
([selection, state]) =>
function ignoreMentionSuggestionsReducer(prev: State): State {
const mentionQuery = parseMention(state.postText, selection);
if (!mentionQuery && prev.mentionSuggestions.length > 0) {
return {...prev, mentionSuggestions: []};
} else {
return prev;
}
},
);
const chooseMentionReducer$ = actions.chooseMention$.map(
(chosenId) =>
function chooseMentionReducer(prev: State): State {
const cursor = prev.postTextSelection.start;
const preMention = prev.postText.substr(0, cursor);
const postMention = prev.postText
.substr(cursor)
.replace(prev.mentionQuery, '');
const chosen = prev.mentionSuggestions.find((x) => x.id === chosenId);
if (!chosen) return prev;
const mention = `[@${chosen.name}](${chosen.id}) `;
const postText = preMention + mention + postMention;
const postTextSelection = {
start: cursor + mention.length,
end: cursor + mention.length,
};
return {
...prev,
postText,
postTextOverride: postText,
postTextSelection,
mentionQuery: '',
mentionSuggestions: [],
mentionChoiceTimestamp: Date.now(),
};
},
);
const cancelMentionReducer$ = actions.cancelMention$.mapTo(
function cancelMentionReducer(prev: State): State {
const cursor = prev.postTextSelection.start;
const preMention = prev.postText.substr(0, cursor);
const postMention = prev.postText.substr(cursor);
const mention = prev.mentionQuery + ' ';
const postText = preMention + mention + postMention;
const postTextSelection = {
start: cursor + mention.length,
end: cursor + mention.length,
};
return {
...prev,
postText,
postTextOverride: postText,
postTextSelection,
mentionQuery: '',
mentionSuggestions: [],
mentionChoiceTimestamp: Date.now(),
};
},
);
const addPictureReducer$ = actions.addPictureWithCaption$
.map(({caption, image}) =>
ssbSource.addBlobFromPath$(image.path.replace('file://', '')).map(
(blobId) =>
function addPictureReducer(prev: State): State {
const imgMarkdown = ``;
const postText = appendToPostText(prev.postText, imgMarkdown);
const postTextSelection = {
start: postText.length,
end: postText.length,
};
return {
...prev,
postText,
postTextOverride: postText,
postTextSelection,
};
},
),
)
.flatten();
const addAudioReducer$ = actions.addAudio$.map(
(blobId) =>
function addAudioReducer(prev: State): State {
const audioMarkdown = ``;
const postText = appendToPostText(prev.postText, audioMarkdown);
const postTextSelection = {
start: postText.length,
end: postText.length,
};
return {
...prev,
postText,
postTextOverride: postText,
postTextSelection,
};
},
);
const updateContentWarningReducer$ = actions.updateContentWarning$.map(
(contentWarning) =>
function updateContentWarningReducer(prev: State): State {
return {
...prev,
contentWarning,
contentWarningPreviewOpened: contentWarning.length === 0,
};
},
);
const enablePreviewReducer$ = actions.enablePreview$.mapTo(
function enablePreviewReducer(prev: State): State {
return {...prev, previewing: true};
},
);
const disablePreviewReducer$ = actions.disablePreview$.mapTo(
function disablePreviewReducer(prev: State): State {
return {
...prev,
previewing: false,
postTextOverride: prev.postText,
postTextSelection: {
start: prev.postText.length,
end: prev.postText.length,
},
};
},
);
const toggleContentWarningPreviewReducer$ = actions.toggleContentWarningPreview$.mapTo(
function toggleContentWarningPreviewReducer(prev: State): State {
return {
...prev,
contentWarningPreviewOpened: !prev.contentWarningPreviewOpened,
};
},
);
const getComposeDraftReducer$ = asyncStorageSource
.getItem('composeDraft')
.filter((str) => !!str)
.map(
(composeDraft) =>
function getComposeDraftReducer(prev: State): State {
if (prev.root) {
return prev;
} else {
return {
...prev,
postText: composeDraft!,
postTextOverride: composeDraft!,
postTextSelection: {
start: composeDraft!.length,
end: composeDraft!.length,
},
};
}
},
);
return concat(
propsReducer$,
xs.merge(
selfNameReducer$,
updatePostTextReducer$,
openMentionSuggestionsReducer$,
ignoreMentionSuggestionsReducer$,
chooseMentionReducer$,
cancelMentionReducer$,
addPictureReducer$,
addAudioReducer$,
updateContentWarningReducer$,
enablePreviewReducer$,
disablePreviewReducer$,
toggleContentWarningPreviewReducer$,
getComposeDraftReducer$,
),
);
} | the_stack |
import React, { ReactNode, useState, useEffect } from "react";
import { ThemeableElement, useTheme } from "@devtools-ds/themes";
import makeClass from "clsx";
import TreeContext from "./TreeContext";
import styles from "./Tree.css";
export interface TreeProps extends ThemeableElement<"ul"> {
/** The label for this node */
label: string | ReactNode;
/** Whether this node is open */
open: boolean;
/** Whether to add hover styles to children */
hover: boolean;
/** Send state updates so parent can track them */
onUpdate?: (value: boolean) => void;
/**
* Called when the given node is selected/focused
* For nodes w/ children, this is equivalent to them updating their state
*/
onSelect?: () => void;
}
/** A keyboard accessible expanding tree view. */
export const Tree = (props: TreeProps) => {
const {
theme,
hover,
colorScheme,
children,
label,
className,
onUpdate,
onSelect,
open,
...html
} = props;
const { themeClass, currentTheme } = useTheme({ theme, colorScheme }, styles);
const [isOpen, setOpen] = useState(open);
// For some reason the useState above default doesn't work, so useEffect is needed
useEffect(() => {
setOpen(open);
}, [open]);
/** Update state and call callback */
const updateState = (value: boolean) => {
setOpen(value);
if (onUpdate) onUpdate(value);
};
const hasChildren = React.Children.count(children) > 0;
/** Set focus and aria-selected onto a new <li>, unselect old if provided */
const updateFocus = (
newNode: HTMLLIElement,
previousNode?: HTMLLIElement
) => {
if (newNode.isSameNode(previousNode || null)) return;
const focusableNode = newNode.querySelector<HTMLLIElement>(
'[tabindex="-1"]'
);
focusableNode?.focus();
newNode.setAttribute("aria-selected", "true");
previousNode?.removeAttribute("aria-selected");
};
/**
* Find a parent DOM node with a given role.
*
* @param node - Current HTMLElement
*/
const getParent = (
node: HTMLElement,
role: "tree" | "group" | "treeitem"
) => {
let parent = node;
while (parent && parent.parentElement) {
// Find the top of the tree
if (parent.getAttribute("role") === role) {
return parent;
}
// Move up the tree after, in case the node provided is the tree
parent = parent.parentElement;
}
return null;
};
/** Get all list elements for the current tree. */
const getListElements = (node: HTMLElement) => {
const tree = getParent(node, "tree");
if (!tree) return [];
return Array.from(tree.querySelectorAll<HTMLLIElement>("li"));
};
/** Move focus up to the tree node above */
const moveBack = (node: HTMLElement) => {
const group = getParent(node, "group");
const toggle = group?.previousElementSibling;
if (toggle && toggle.getAttribute("tabindex") === "-1") {
const toggleParent = toggle.parentElement as HTMLLIElement;
const nodeParent = node.parentElement as HTMLLIElement;
updateFocus(toggleParent, nodeParent);
}
};
/** Move the focus to the start or end of the tree */
const moveHome = (node: HTMLElement, direction: "start" | "end") => {
const elements = getListElements(node);
elements.forEach((element) => {
element.removeAttribute("aria-selected");
});
if (direction === "start" && elements[0]) {
updateFocus(elements[0]);
}
if (direction === "end" && elements[elements.length - 1]) {
updateFocus(elements[elements.length - 1]);
}
};
/** Move focus up or down a level from the provided Element */
const moveFocusAdjacent = (node: HTMLElement, direction: "up" | "down") => {
const elements = getListElements(node) || [];
for (let i = 0; i < elements.length; i++) {
// Go through each <li> and look for the currently selected node
const currentNode = elements[i];
if (currentNode.getAttribute("aria-selected") === "true") {
if (direction === "up" && elements[i - 1]) {
// Move focus to the <li> above
updateFocus(elements[i - 1], currentNode);
} else if (direction === "down" && elements[i + 1]) {
// Move focus to the <li> below
updateFocus(elements[i + 1], currentNode);
}
return;
}
}
// Select first node if one isn't currently selected
updateFocus(elements[0]);
};
/** Handle all keyboard events from tree nodes */
const handleKeypress = (event: React.KeyboardEvent, isChild?: boolean) => {
const node = event.target as HTMLElement;
// Handle open/close toggle
if (event.key === "Enter" || event.key === " ") {
updateState(!isOpen);
}
if (event.key === "ArrowRight" && isOpen && !isChild) {
moveFocusAdjacent(node, "down");
} else if (event.key === "ArrowRight") {
updateState(true);
}
if (event.key === "ArrowLeft" && (!isOpen || isChild)) {
moveBack(node);
} else if (event.key === "ArrowLeft") {
updateState(false);
}
if (event.key === "ArrowDown") {
moveFocusAdjacent(node, "down");
}
if (event.key === "ArrowUp") {
moveFocusAdjacent(node, "up");
}
if (event.key === "Home") {
moveHome(node, "start");
}
if (event.key === "End") {
moveHome(node, "end");
}
};
/** Set selected and focus states on click events */
const handleClick = (event: React.MouseEvent, isChild?: boolean) => {
const node = event.target as HTMLElement;
const parent = getParent(node, "treeitem") as HTMLLIElement;
// We need to check if another node was selected and move it
const elements = getListElements(node) || [];
let found = false;
for (let i = 0; i < elements.length; i++) {
// Go through each <li> and look for the currently selected node
const currentNode = elements[i];
if (currentNode.getAttribute("aria-selected") === "true") {
// Move selected to clicked LI
if (parent) {
found = true;
updateFocus(parent, currentNode);
}
break;
}
}
// If we didn't find an existing one select the new one
if (!found && parent) {
updateFocus(parent);
}
// Toggle open state if needed
if (!isChild) {
updateState(!isOpen);
}
};
/** When the tree is blurred make it focusable again */
const handleBlur = (event: React.FocusEvent) => {
const node = event.currentTarget;
if (
!node.contains(document.activeElement) &&
node.getAttribute("role") === "tree"
) {
node.setAttribute("tabindex", "0");
}
};
/** Move focus back to the selected tree node, or focus the first one */
const handleFocus = (event: React.FocusEvent) => {
const node = event.target;
if (node.getAttribute("role") === "tree") {
const selected = node.querySelector<HTMLLIElement>(
'[aria-selected="true"]'
);
if (selected) {
// Move to previously selected node
updateFocus(selected);
} else {
// Focus the first node
moveFocusAdjacent(node as HTMLElement, "down");
}
//
node.setAttribute("tabindex", "-1");
}
};
/** Detect when a button has been focused */
const handleButtonFocus = () => {
onSelect?.();
};
/** Get the styles for padding based on depth */
const getPaddingStyles = (depth: number) => {
const space = depth * 0.9 + 0.3;
return {
paddingLeft: `${space}em`,
width: `calc(100% - ${space}em)`,
};
};
// The first node needs role "tree", while sub-trees need role "group"
// This is tracked through context to be flexible to elements in the subtree.
const { isChild, depth, hasHover } = React.useContext(TreeContext);
const showHover = hasHover ? hover : false;
// Tree root node
// Needs to have role tree and one top level UL
// https://dequeuniversity.com/library/aria/tabpanels-accordions/sf-tree-view
if (!isChild) {
return (
<ul
role="tree"
tabIndex={0}
className={makeClass(styles.tree, styles.group, themeClass, className)}
onFocus={handleFocus}
onBlur={handleBlur}
{...html}
>
<TreeContext.Provider
value={{ isChild: true, depth: 0, hasHover: showHover }}
>
<Tree {...props} />
</TreeContext.Provider>
</ul>
);
}
// Leaf nodes that don't expand, but still highlight and focus.
if (!hasChildren) {
return (
<li role="treeitem" className={styles.item} {...(html as any)}>
<div
role="button"
className={makeClass(styles.label, {
[styles.hover]: showHover,
[styles.focusWhite]: currentTheme === "firefox",
})}
tabIndex={-1}
style={getPaddingStyles(depth)}
onKeyDown={(e) => {
handleKeypress(e, isChild);
}}
onClick={(e) => handleClick(e, true)}
onFocus={handleButtonFocus}
>
<span>{label}</span>
</div>
</li>
);
}
// Child tree node with children
const arrowClass = makeClass(styles.arrow, { [styles.open]: isOpen });
return (
<li role="treeitem" aria-expanded={isOpen} className={styles.item}>
<div
role="button"
tabIndex={-1}
className={makeClass(styles.label, {
[styles.hover]: showHover,
[styles.focusWhite]: currentTheme === "firefox",
})}
style={getPaddingStyles(depth)}
onClick={(e) => handleClick(e)}
onKeyDown={(e) => handleKeypress(e)}
onFocus={handleButtonFocus}
>
<span>
<span aria-hidden className={arrowClass} />
<span>{label}</span>
</span>
</div>
<ul role="group" className={makeClass(className, styles.group)} {...html}>
{isOpen &&
React.Children.map(children, (child) => {
return (
<TreeContext.Provider
value={{ isChild: true, depth: depth + 1, hasHover: showHover }}
>
{child}
</TreeContext.Provider>
);
})}
</ul>
</li>
);
};
Tree.defaultProps = {
open: false,
hover: true,
}; | the_stack |
/// <reference path="models/models.ts" />
/// <reference path="typings/window-options.d.ts" />
/// <reference path="typings/draggabilly.d.ts" />
/// <reference path="typings/packery.d.ts" />
/// <reference path="typings/packery.jquery.d.ts" />
/// <reference path="../../node_modules/@aspnet/signalr/dist/esm/index.d.ts" />
/// <reference path="tiles/tilemap.ts" />
/// <reference path="PageFunctions.ts" />
type TilePos = {
x: number,
y: number,
index: number,
name: string
};
// Debug info - has to be one of the first things because if we fail on "class" then this won't display
if (window.location.search.toUpperCase().indexOf("DEBUG=1") > -1 && !window.location.pathname.toUpperCase().startsWith('/ADMIN'))
{
Utils.displayDebugInfo();
}
class CommandCenter
{
private conn: HAConnection;
private pk: Packery;
private pageIsDirty: boolean;
private tileConn: signalR.HubConnection;
private tiles: Tile[];
private initHandle: number;
constructor()
{
this.tiles = [];
$(() => this.init());
}
private init(): void
{
window.ccOptions.mode == PageMode.Admin
? this.initAdmin()
: this.initUser();
this.initializeMdiPreview();
this.initializeColorPreview();
this.initializeNightlyRefresh();
}
private initAdmin(): void
{
$(window).on('beforeunload', e =>
{
if (this.pageIsDirty && $((e.target as any).activeElement).prop('type') !== 'submit')
{
return 'You have unsaved changes. Are you sure you want to leave?';
}
});
$('#importTheme, #importConfig').click(() =>
{
if (confirm('WARNING: This will OVERWRITE your current settings. Export first if you want to save what you have now! Continue?'))
{
$('#importBrowser').click();
}
});
$('#importBrowser').change(() =>
{
$('#importForm').submit();
});
$('#resetConfig').click(e =>
{
if (!confirm("WARNING: This will COMPLETELY RESET your HACC installation and PERMANENTLY DELETE all of your tiles, themes, and settings. Are you sure you want to reset your config?"))
{
e.preventDefault();
return false;
}
return true;
})
$('.ui.accordion').accordion();
$('.ui.checkbox').checkbox();
$('.ui.dropdown').not('.no-placeholder').dropdown({ fullTextSearch: true });
$('.ui.no-placeholder.dropdown').dropdown({ placeholder: false });
// Font dropdown with real font previews.
$('#Page_PageFontFace option').each(function (_, e)
{
$(e).parent().siblings('.menu').find('.item[data-value="' + $(e).text() + '"]').css('font-family', $(e).text());
});
// Only init Packery stuff if we detect we have the preview grid on the page
if ($('.preview-layout-grid').length)
{
$('#auto-layout').click(() =>
{
if (confirm('This will reset the layout for this page and attempt to automatically arrange all tiles evenly.\n\nYour tiles will all probably change locations. You have been warned. :)\n\nAre you sure you want to reset the layout?'))
{
this.pk.layout();
}
});
// For some reason Draggabilly takes the first element as the grid size, so inject a temporary invisible "fake" one
$('.preview-layout-grid').prepend(`<div class="preview-layout-item" style="opacity: 0; position: absolute; top: ${window.ccOptions.tilePreviewPadding}px; left: ${window.ccOptions.tilePreviewPadding}px; width: ${window.ccOptions.tilePreviewSize}px; height: ${window.ccOptions.tilePreviewSize}px;" id="grid__tmp"></div>`);
if (window.ccOptions)
{
this.pk = new Packery('.preview-layout-grid', {
itemSelector: '.preview-layout-item',
columnWidth: window.ccOptions.tilePreviewSize,
rowHeight: window.ccOptions.tilePreviewSize,
gutter: window.ccOptions.tilePreviewPadding,
initLayout: false
});
}
else
{
this.pk = new Packery('.preview-layout-grid', {
itemSelector: '.preview-layout-item',
columnWidth: '.preview-layout-item',
rowHeight: '.preview-layout-item',
gutter: window.ccOptions.tilePreviewPadding,
initLayout: false
});
}
this.pk.on('layoutComplete', () => this.writeItemLayout());
this.pk.on('dragItemPositioned', () =>
{
// Things get kinda glitchy if we don't add a slight pause
setTimeout(() =>
{
this.writeItemLayout();
this.pageIsDirty = true;
}, 25);
});
this.writeItemLayout();
if (typeof Draggabilly === 'function')
{
$('.preview-layout-item').each((_, e) => this.pk.bindDraggabillyEvents(new Draggabilly(e, { containment: '.preview-layout-grid' })));
}
else
{
console.warn("Draggabilly is not available - drag and drop interface will not work.");
}
$('#grid__tmp').remove();
this.pk.initShiftLayout(Array.from(document.querySelectorAll('.preview-layout-grid > .preview-layout-item')));
}
}
private initUser(): void
{
// Websocket setup and events
if (window.ccOptions.socketUrl)
{
this.conn = new HAConnection(window.ccOptions.socketUrl);
}
else
{
$('#alerts').show().find('.alert-message').text('[E] HA connection not defined...');
}
this.conn.OnConnectionStateChanged.on(state =>
{
if (state == HAConnectionState.Closed)
{
$('#alerts').show().find('.alert-message').text('[H] Connection lost, reconnecting...');
}
else if (state == HAConnectionState.Open)
{
$('#alerts').hide();
// Request a refresh of state data
this.conn.refreshAllStates();
}
});
this.conn.OnStateChanged.on(state =>
{
var tiles = this.findTilesByEntityId(state.data.entity_id);
for (var t of tiles)
{
t.updateState(state.data);
console.info(`Updating tile for entity "${state.data.entity_id}" to state "${state.data.new_state.state}".`);
}
});
// SignalR Hub Connection
this.tileConn = new signalR.HubConnectionBuilder().withUrl('/hubs/tile').build();
this.tileConn.onclose(e =>
{
$('#alerts').show().find('.alert-message').text('[S] Connection lost, reconnecting...');
window.setTimeout(() =>
{
window.location.reload();
}, 10000);
});
this.tileConn.start().then(() =>
{
$('.tiles .tile').each((_, e) =>
{
try
{
let tile: Tile = new TileMap.ClassMap[$(e).data('tile-type').toString()](window.ccOptions.pageId, $(e).data('tile-name'), this.tileConn, this.conn);
this.tiles.push(tile);
}
catch (ex)
{
console.error('Error instantiating class "' + ($(e).data('tile-type') || '__MISSING__') + 'Tile". Was it added to the tile type map?', ex, e);
}
});
if (!this.initHandle)
{
this.initHandle = window.setInterval(() => this.waitAndPerformInit(), 25)
}
if (window.ccOptions.autoReturn > 0)
{
window.setTimeout(() => window.location.href = '/d/', window.ccOptions.autoReturn * 1000);
}
});
}
private waitAndPerformInit()
{
// Only connect to HA once our tiles are all initialized
if (this.tiles.filter(t => t.loaded).length !== this.tiles.length)
return;
// And now fire up the websocket connection
this.conn.initialize();
window.clearInterval(this.initHandle);
}
private findTilesByEntityId(entityId: string): Tile[]
{
return this.tiles.filter(t =>
{
let definedIds = t.getEntityIds();
return definedIds.some(e => e.toLowerCase() === entityId.toLowerCase());
});
}
protected initializeNightlyRefresh(): void
{
// Workaround to get around SignalR hub being kinda crappy :/
window.setInterval(() =>
{
if (new Date().getHours() == 2)
{
window.setTimeout(() =>
{
window.location.reload();
}, 3600000); // 1 hour
}
}, 3500000) // ~58 minutes
}
protected initializeMdiPreview(): void
{
$('.mdi-icon-placeholder + input').each((_, e) =>
{
$(e).keyup((el) =>
{
this.refreshDynamicIcon(el.currentTarget);
});
this.refreshDynamicIcon(e);
});
}
protected refreshDynamicIcon(target: HTMLElement): void
{
$(target).parent().children('.mdi-icon-placeholder').attr('class', 'large icon mdi-icon-placeholder').addClass(`mdi mdi-${$(target).val()}`);
}
protected initializeColorPreview(): void
{
$('.color-preview + input').each((_, e) =>
{
$(e).keyup((el) =>
{
this.refreshDynamicColor(el.currentTarget);
});
this.refreshDynamicColor(e);
});
}
protected refreshDynamicColor(target: HTMLElement): void
{
$(target).parent().children('.color-preview').css('color', `${$(target).val()}`);
}
private writeItemLayout(): void
{
var positions: TilePos[] = [];
var tiles = this.pk.getItemElements();
for (let i = 0; i < tiles.length; i++)
{
let $tile = $(tiles[i]);
positions.push({
index: i,
x: parseInt($tile.css('left').replace('px', '')),
y: parseInt($tile.css('top').replace('px', '')),
name: $tile.data('tile-name')
});
}
$('#layout-serialized').val(JSON.stringify(positions));
}
}
var __app = new CommandCenter(); | the_stack |
import type { TSESTree } from '@typescript-eslint/types';
import assert from 'assert';
import { createTextDocument, CSpellSettings, DocumentValidator, ValidationIssue, TextDocument } from 'cspell-lib';
import type { Rule } from 'eslint';
// eslint-disable-next-line node/no-missing-import
import type { Comment, Identifier, Literal, Node, TemplateElement, ImportSpecifier } from 'estree';
import { format } from 'util';
import { normalizeOptions } from './options';
import optionsSchema from './_auto_generated_/options.schema.json';
const schema = optionsSchema as unknown as Rule.RuleMetaData['schema'];
interface PluginRules {
['spellchecker']: Rule.RuleModule;
}
const messages = {
wordUnknown: 'Unknown word: "{{word}}"',
wordForbidden: 'Forbidden word: "{{word}}"',
suggestWord: '{{word}}',
} as const;
type Messages = typeof messages;
type MessageIds = keyof Messages;
const meta: Rule.RuleMetaData = {
docs: {
description: 'CSpell spellchecker',
category: 'Possible Errors',
recommended: false,
},
messages,
hasSuggestions: true,
schema: [schema],
};
type ASTNode = (Node | Comment) & Partial<Rule.NodeParentExtension>;
const defaultSettings: CSpellSettings = {
patterns: [
// @todo: be able to use cooked / transformed strings.
// {
// // Do not block unicode escape sequences.
// name: 'js-unicode-escape',
// pattern: /$^/g,
// },
],
};
let isDebugMode = false;
function log(...args: Parameters<typeof console.log>) {
if (!isDebugMode) return;
console.log(...args);
}
function create(context: Rule.RuleContext): Rule.RuleListener {
const options = normalizeOptions(context.options[0]);
const toIgnore = new Set<string>();
const importedIdentifiers = new Set<string>();
isDebugMode = options.debugMode || false;
isDebugMode && logContext(context);
const validator = getDocValidator(context);
validator.prepareSync();
function checkLiteral(node: Literal & Rule.NodeParentExtension) {
if (!options.checkStrings) return;
if (typeof node.value === 'string') {
debugNode(node, node.value);
if (options.ignoreImports && isImportOrRequired(node)) return;
if (options.ignoreImportProperties && isImportedProperty(node)) return;
checkNodeText(node, node.value);
}
}
function checkTemplateElement(node: TemplateElement & Rule.NodeParentExtension) {
if (!options.checkStringTemplates) return;
debugNode(node, node.value);
// console.log('Template: %o', node.value);
checkNodeText(node, node.value.cooked || node.value.raw);
}
function checkIdentifier(node: Identifier & Rule.NodeParentExtension) {
debugNode(node, node.name);
if (options.ignoreImports) {
if (isRawImportIdentifier(node)) {
toIgnore.add(node.name);
return;
}
if (isImportIdentifier(node)) {
importedIdentifiers.add(node.name);
if (isLocalImportIdentifierUnique(node)) {
checkNodeText(node, node.name);
}
return;
} else if (options.ignoreImportProperties && isImportedProperty(node)) {
return;
}
}
if (!options.checkIdentifiers) return;
if (toIgnore.has(node.name) && !isObjectProperty(node)) return;
if (skipCheckForRawImportIdentifiers(node)) return;
checkNodeText(node, node.name);
}
function checkComment(node: Comment) {
if (!options.checkComments) return;
debugNode(node, node.value);
checkNodeText(node, node.value);
}
function checkNodeText(node: ASTNode, text: string) {
if (!node.range) return;
const adj = node.type === 'Literal' ? 1 : 0;
const range = [node.range[0] + adj, node.range[1] - adj] as const;
const scope: string[] = calcScope(node);
const result = validator.checkText(range, text, scope);
result.forEach((issue) => reportIssue(issue));
}
function calcScope(_node: ASTNode): string[] {
// inheritance(node);
return [];
}
function isImportIdentifier(node: ASTNode): boolean {
const parent = node.parent;
if (node.type !== 'Identifier' || !parent) return false;
return (
(parent.type === 'ImportSpecifier' ||
parent.type === 'ImportNamespaceSpecifier' ||
parent.type === 'ImportDefaultSpecifier') &&
parent.local === node
);
}
function isRawImportIdentifier(node: ASTNode): boolean {
const parent = node.parent;
if (node.type !== 'Identifier' || !parent) return false;
return (
(parent.type === 'ImportSpecifier' && parent.imported === node) ||
(parent.type === 'ExportSpecifier' && parent.local === node)
);
}
function isLocalImportIdentifierUnique(node: ASTNode): boolean {
const parent = getImportParent(node);
if (!parent) return true;
const { imported, local } = parent;
if (imported.name !== local.name) return true;
return imported.range?.[0] !== local.range?.[0] && imported.range?.[1] !== local.range?.[1];
}
function getImportParent(node: ASTNode): ImportSpecifier | undefined {
const parent = node.parent;
return parent?.type === 'ImportSpecifier' ? parent : undefined;
}
function skipCheckForRawImportIdentifiers(node: ASTNode): boolean {
if (options.ignoreImports) return false;
const parent = getImportParent(node);
return !!parent && parent.imported === node && !isLocalImportIdentifierUnique(node);
}
function isImportedProperty(node: ASTNode): boolean {
const obj = findOriginObject(node);
return !!obj && obj.type === 'Identifier' && importedIdentifiers.has(obj.name);
}
function isObjectProperty(node: ASTNode): boolean {
return node.parent?.type === 'MemberExpression';
}
function reportIssue(issue: ValidationIssue) {
const messageId: MessageIds = issue.isFlagged ? 'wordForbidden' : 'wordUnknown';
const data = {
word: issue.text,
};
const code = context.getSourceCode();
const start = issue.offset;
const end = issue.offset + (issue.length || issue.text.length);
const startPos = code.getLocFromIndex(start);
const endPos = code.getLocFromIndex(end);
const loc = { start: startPos, end: endPos };
function fixFactory(word: string): Rule.ReportFixer {
return (fixer) => fixer.replaceTextRange([start, end], word);
}
function createSug(word: string): Rule.SuggestionReportDescriptor {
const data = { word };
const messageId: MessageIds = 'suggestWord';
return {
messageId,
data,
fix: fixFactory(word),
};
}
log('Suggestions: %o', issue.suggestions);
const suggest: Rule.ReportDescriptorOptions['suggest'] = issue.suggestions?.map(createSug);
const des: Rule.ReportDescriptor = {
messageId,
data,
loc,
suggest,
};
context.report(des);
}
context
.getSourceCode()
.getAllComments()
.forEach(function (commentNode) {
checkComment(commentNode);
});
return {
Literal: checkLiteral,
TemplateElement: checkTemplateElement,
Identifier: checkIdentifier,
};
function mapNode(node: ASTNode | TSESTree.Node, index: number, nodes: ASTNode[]): string {
const child = nodes[index + 1];
if (node.type === 'ImportSpecifier') {
const extra = node.imported === child ? '.imported' : node.local === child ? '.local' : '';
return node.type + extra;
}
if (node.type === 'ImportDeclaration') {
const extra = node.source === child ? '.source' : '';
return node.type + extra;
}
if (node.type === 'ExportSpecifier') {
const extra = node.exported === child ? '.exported' : node.local === child ? '.local' : '';
return node.type + extra;
}
if (node.type === 'ExportNamedDeclaration') {
const extra = node.source === child ? '.source' : '';
return node.type + extra;
}
if (node.type === 'Property') {
const extra = node.key === child ? 'key' : node.value === child ? 'value' : '';
return [node.type, node.kind, extra].join('.');
}
if (node.type === 'MemberExpression') {
const extra = node.property === child ? 'property' : node.object === child ? 'object' : '';
return node.type + '.' + extra;
}
if (node.type === 'ArrowFunctionExpression') {
const extra = node.body === child ? 'body' : 'param';
return node.type + '.' + extra;
}
if (node.type === 'FunctionDeclaration') {
const extra = node.id === child ? 'id' : node.body === child ? 'body' : 'params';
return node.type + '.' + extra;
}
if (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') {
const extra = node.id === child ? 'id' : node.body === child ? 'body' : 'superClass';
return node.type + '.' + extra;
}
if (node.type === 'CallExpression') {
const extra = node.callee === child ? 'callee' : 'arguments';
return node.type + '.' + extra;
}
if (node.type === 'Literal') {
return tagLiteral(node);
}
if (node.type === 'Block') {
return node.value[0] === '*' ? 'Comment.docBlock' : 'Comment.block';
}
if (node.type === 'Line') {
return 'Comment.line';
}
return node.type;
}
function inheritance(node: ASTNode) {
const a = [...context.getAncestors(), node];
return a.map(mapNode);
}
function inheritanceSummary(node: ASTNode) {
return inheritance(node).join(' ');
}
/**
* find the origin of a member expression
*/
function findOriginObject(node: ASTNode): ASTNode | undefined {
const parent = node.parent;
if (parent?.type !== 'MemberExpression' || parent.property !== node) return undefined;
let obj = parent.object;
while (obj.type === 'MemberExpression') {
obj = obj.object;
}
return obj;
}
function isFunctionCall(node: ASTNode | undefined, name: string): boolean {
return node?.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === name;
}
function isRequireCall(node: ASTNode | undefined) {
return isFunctionCall(node, 'require');
}
function isImportOrRequired(node: ASTNode) {
return isRequireCall(node.parent) || (node.parent?.type === 'ImportDeclaration' && node.parent.source === node);
}
function debugNode(node: ASTNode, value: unknown) {
if (!isDebugMode) return;
const val = format('%o', value);
log(`${inheritanceSummary(node)}: ${val}`);
}
}
function tagLiteral(node: ASTNode | TSESTree.Node): string {
assert(node.type === 'Literal');
const kind = typeof node.value;
const extra =
kind === 'string'
? node.raw?.[0] === '"'
? 'string.double'
: 'string.single'
: node.value === null
? 'null'
: kind;
return node.type + '.' + extra;
}
export const rules: PluginRules = {
spellchecker: {
meta,
create,
},
};
function logContext(context: Rule.RuleContext) {
log('\n\n************************');
// log(context.getSourceCode().text);
log(`
id: ${context.id}
cwd: ${context.getCwd()}
filename: ${context.getFilename()}
physicalFilename: ${context.getPhysicalFilename()}
scope: ${context.getScope().type}
`);
}
export const configs = {
recommended: {
plugins: ['@cspell'],
rules: {
'@cspell/spellchecker': ['warn', {}],
},
},
debug: {
plugins: ['@cspell'],
rules: {
'@cspell/spellchecker': ['warn', { debugMode: true }],
},
},
};
interface CachedDoc {
filename: string;
doc: TextDocument;
}
const cache: { lastDoc: CachedDoc | undefined } = { lastDoc: undefined };
const docValCache = new WeakMap<TextDocument, DocumentValidator>();
function getDocValidator(context: Rule.RuleContext): DocumentValidator {
const text = context.getSourceCode().getText();
const doc = getTextDocument(context.getFilename(), text);
const cachedValidator = docValCache.get(doc);
if (cachedValidator) {
cachedValidator.updateDocumentText(text);
return cachedValidator;
}
const options = normalizeOptions(context.options[0]);
isDebugMode = options.debugMode || false;
isDebugMode && logContext(context);
const validator = new DocumentValidator(doc, options, defaultSettings);
docValCache.set(doc, validator);
return validator;
}
function getTextDocument(filename: string, content: string): TextDocument {
if (cache.lastDoc?.filename === filename) {
return cache.lastDoc.doc;
}
const doc = createTextDocument({ uri: filename, content });
// console.error(`CreateTextDocument: ${doc.uri}`);
cache.lastDoc = { filename, doc };
return doc;
} | the_stack |
/// <reference types="./passport-totp" />
import * as crypto from 'crypto';
import * as util from 'util';
import * as jwt from 'jsonwebtoken';
import assert from 'assert';
import { Request, } from 'express';
import '../types';
import * as db from './db';
import * as model from '../model/user';
import * as secret from './secret_key';
import { ForbiddenError } from './errors';
import * as userUtils from './user';
import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';
import { Strategy as GoogleOAuthStrategy } from 'passport-google-oauth20';
import { Strategy as GitHubStrategy } from 'passport-github';
import { Strategy as BearerStrategy } from 'passport-http-bearer';
import { BasicStrategy } from 'passport-http';
import { Strategy as TotpStrategy } from 'passport-totp';
import * as EngineManager from '../almond/enginemanagerclient';
import { OAUTH_REDIRECT_ORIGIN, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GITHUB_CLIENT_SECRET, GITHUB_CLIENT_ID } from '../config';
const TOTP_PERIOD = 30; // duration in second of TOTP code
function makeRandom(size = 32) {
return crypto.randomBytes(size).toString('hex');
}
function makeUsername(email : string) {
// use the local part of the email as the username (up to a + if present)
let username = email.substring(0, email.indexOf('@'));
if (username.indexOf('+') >= 0)
username = username.substring(0, username.indexOf('+'));
return username;
}
async function autoAdjustUsername(dbClient : db.Client, username : string) : Promise<string> {
if (username.length > userUtils.MAX_USERNAME_LENGTH)
username = username.substring(0, userUtils.MAX_USERNAME_LENGTH);
username = username.replace(/[^\w.-]/g, '_');
if (!userUtils.validateUsername(username))
username = username + '_';
assert(userUtils.validateUsername(username));
// check if this username is already being used
// if not, we're good to go
let rows = await model.getByName(dbClient, username);
if (rows.length === 0)
return username;
let attempts = 5;
let addednumber = false;
while (attempts > 0) {
if (addednumber)
username = username.substring(0, username.length - 1) + (5-attempts+1);
else
username = username + (5-attempts+1);
addednumber = true;
rows = await model.getByName(dbClient, username);
if (rows.length === 0)
return username;
attempts --;
}
return username;
}
function authenticateGoogle(req : Request, accessToken : string, refreshToken : string|undefined, profile : any,
done : (err ?: Error|null, user ?: Express.User) => void) {
db.withTransaction(async (dbClient) : Promise<Express.User> => {
const rows = await model.getByGoogleAccount(dbClient, profile.id);
if (rows.length > 0) {
await model.recordLogin(dbClient, rows[0].id);
return rows[0];
}
// check if we already have an user with this email address
// if so, and the email was verified, we update the entry to associate the google account
// if the email was not verified, we report an error instead
// (otherwise one can hijack google accounts by squatting emails, which would be bad)
const byEmail = await model.getByEmail(dbClient, profile.emails[0].value);
if (byEmail.length > 0) {
if (!byEmail[0].email_verified)
throw new ForbiddenError(req._("A user with this email already exist, but the email was not verified before."));
await model.update(dbClient, byEmail[0].id, { google_id: profile.id });
await model.recordLogin(dbClient, byEmail[0].id);
byEmail[0].google_id = profile.id;
return byEmail[0];
}
const username = await autoAdjustUsername(dbClient, profile.username || makeUsername(profile.emails[0].value));
const row = await model.create(dbClient, {
username: username,
email: profile.emails[0].value,
// we assume the email associated with a Google account is valid
// and we don't need extra validation
email_verified: true,
locale: 'en-US',
timezone: 'America/Los_Angeles',
google_id: profile.id,
human_name: profile.displayName,
cloud_id: makeRandom(8),
auth_token: makeRandom(),
storage_key: makeRandom() });
// read back the full user record (including the defaults set by the database)
const user : Express.User = await model.get(dbClient, row.id);
user.newly_created = true;
return user;
}).then(async (user) : Promise<Express.User> => {
if (!user.newly_created)
return user;
// NOTE: we must start the user here because if we do it earlier we're
// still inside the transaction, and the master process (which uses a different
// database connection) will not see the new user in the database
return EngineManager.get().startUser(user.id).then(() => {
// asynchronously inject google-account device
EngineManager.get().getEngine(user.id).then((engine : any /* FIXME */) => {
return engine.createDeviceAndReturnInfo({
kind: 'com.google',
profileId: profile.id,
accessToken: accessToken,
refreshToken: refreshToken
});
});
return user;
});
}).then((user) => done(null, user), done);
}
function associateGoogle(user : Express.User, accessToken : string, refreshToken : string|undefined, profile : any,
done : (err ?: Error|null, user ?: Express.User) => void) {
db.withTransaction((dbClient) => {
return model.update(dbClient, user.id, { google_id: profile.id }).then(() => {
// asynchronously inject google-account device
EngineManager.get().getEngine(user.id).then((engine : any /* FIXME */) => {
return engine.createDeviceAndReturnInfo({
kind: 'com.google',
profileId: profile.id,
accessToken: accessToken,
refreshToken: refreshToken
});
});
return user;
});
}).then((user) => done(null, user), done);
}
function authenticateGithub(req : Request, accessToken : string, refreshToken : string|undefined, profile : any,
done : (err ?: Error|null, user ?: Express.User) => void) {
db.withTransaction(async (dbClient) => {
const rows = await model.getByGithubAccount(dbClient, profile.id);
if (rows.length > 0) {
await model.recordLogin(dbClient, rows[0].id);
return rows[0];
}
const email = profile.emails ? profile.emails[0].value : null;
// check if we already have an user with this email address
// if so, and the email was verified, we update the entry to associate the google account
// if the email was not verified, we report an error instead
// (otherwise one can hijack google accounts by squatting emails, which would be bad)
const byEmail = await model.getByEmail(dbClient, email);
if (byEmail.length > 0) {
if (!byEmail[0].email_verified)
throw new ForbiddenError(req._("A user with this email already exist, but the email was not verified before."));
await model.update(dbClient, byEmail[0].id, { github_id: profile.id });
await model.recordLogin(dbClient, byEmail[0].id);
byEmail[0].github_id = profile.id;
return byEmail[0];
}
const row = await model.create(dbClient, {
username: await autoAdjustUsername(dbClient, profile.username),
email: email,
// we assume the email associated with a Github account is valid
// and we don't need extra validation
email_verified: !!email,
locale: 'en-US',
timezone: 'America/Los_Angeles',
github_id: profile.id,
human_name: profile.displayName,
cloud_id: makeRandom(8),
auth_token: makeRandom(),
storage_key: makeRandom() });
// read back the full user record (including the defaults set by the database)
const user : Express.User = await model.get(dbClient, row.id);
user.newly_created = true;
return user;
}).then((user) => done(null, user), done);
}
const jwtVerify = util.promisify<string, jwt.Secret | jwt.GetPublicKeyOrSecret, jwt.VerifyOptions, any>(jwt.verify);
export function initialize() {
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser<number>((id, done) => {
db.withClient((client) => model.get(client, id)).then((user) => done(null, user), done);
});
passport.use(new BearerStrategy(async (accessToken, done) => {
try {
const decoded = await jwtVerify(accessToken, secret.getJWTSigningKey(), {
algorithms: ['HS256'],
audience: 'oauth2',
clockTolerance: 30,
});
const scope = decoded.scope || ['profile'];
const [user, options] = await db.withClient(async (dbClient) : Promise<[Express.User|boolean, Express.AuthInfo|null]> => {
const rows = await model.getByCloudId(dbClient, decoded.sub);
if (rows.length < 1)
return [false, null];
await model.recordLogin(dbClient, rows[0].id);
return [rows[0], { scope, authMethod: 'oauth2' }];
});
done(null, user, options!);
} catch(err) {
done(err);
}
}));
passport.use(new BasicStrategy((username, password, done) => {
db.withClient((dbClient) : Promise<Express.User|boolean> => {
return model.getByCloudId(dbClient, username).then((rows) => {
if (rows.length < 1 || rows[0].auth_token !== password)
return false;
return model.recordLogin(dbClient, rows[0].id).then(() => rows[0]);
});
}).then((res) => done(null, res), (err) => done(err));
}));
passport.use(new LocalStrategy((username, password, done) => {
db.withClient((dbClient) : Promise<[Express.User|boolean, string]> => {
return model.getByName(dbClient, username).then((rows) => {
if (rows.length < 1)
return [false, "Invalid username or password"];
if (!rows[0].salt)
return [false, "Password not configured"];
return userUtils.hashPassword(rows[0].salt, password).then((hash) => {
if (hash !== rows[0].password)
return [false, "Invalid username or password"];
return model.recordLogin(dbClient, rows[0].id).then(() => {
return [rows[0], ''];
});
});
});
}).then((result) => {
done(null, result[0], { message: result[1] });
}, (err) => {
done(err);
});
}));
if (GOOGLE_CLIENT_ID) {
assert(GOOGLE_CLIENT_SECRET);
passport.use(new GoogleOAuthStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: OAUTH_REDIRECT_ORIGIN + '/user/oauth2/google/callback',
passReqToCallback: true,
}, (req, accessToken, refreshToken, profile, done) => {
if (!req.user) {
// authenticate the user
authenticateGoogle(req, accessToken, refreshToken, profile, done);
} else {
associateGoogle(req.user, accessToken, refreshToken, profile, done);
}
}));
}
if (GITHUB_CLIENT_ID) {
assert(GITHUB_CLIENT_SECRET);
passport.use(new GitHubStrategy({
clientID: GITHUB_CLIENT_ID,
clientSecret: GITHUB_CLIENT_SECRET,
callbackURL: OAUTH_REDIRECT_ORIGIN + '/user/oauth2/github/callback',
passReqToCallback: true,
}, authenticateGithub));
}
passport.use(new TotpStrategy((user, done) => {
if (user.totp_key === null)
done(new Error('2-factor authentication not setup'));
else
done(null, secret.decrypt(user.totp_key), TOTP_PERIOD);
}));
} | the_stack |
import type {Mutable, ObserverType} from "@swim/util";
import type {FastenerOwner} from "@swim/component";
import type {GestureInputType} from "./GestureInput";
import {GestureMethod, GestureInit, GestureClass, Gesture} from "./Gesture";
import {PositionGestureInput} from "./PositionGestureInput";
import {MousePositionGesture} from "./"; // forward import
import {TouchPositionGesture} from "./"; // forward import
import {PointerPositionGesture} from "./"; // forward import
import type {View} from "../view/View";
/** @public */
export interface PositionGestureInit<V extends View = View> extends GestureInit<V> {
extends?: {prototype: PositionGesture<any, any>} | string | boolean | null;
willStartHovering?(): void;
didStartHovering?(): void;
willStopHovering?(): void;
didStopHovering?(): void;
willBeginHover?(input: PositionGestureInput, event: Event | null): void;
didBeginHover?(input: PositionGestureInput, event: Event | null): void;
willEndHover?(input: PositionGestureInput, event: Event | null): void;
didEndHover?(input: PositionGestureInput, event: Event | null): void;
willStartPressing?(): void;
didStartPressing?(): void;
willStopPressing?(): void;
didStopPressing?(): void;
willBeginPress?(input: PositionGestureInput, event: Event | null): boolean | void;
didBeginPress?(input: PositionGestureInput, event: Event | null): void;
willMovePress?(input: PositionGestureInput, event: Event | null): void;
didMovePress?(input: PositionGestureInput, event: Event | null): void;
willEndPress?(input: PositionGestureInput, event: Event | null): void;
didEndPress?(input: PositionGestureInput, event: Event | null): void;
willCancelPress?(input: PositionGestureInput, event: Event | null): void;
didCancelPress?(input: PositionGestureInput, event: Event | null): void;
willPress?(input: PositionGestureInput, event: Event | null): void;
didPress?(input: PositionGestureInput, event: Event | null): void;
willLongPress?(input: PositionGestureInput): void;
didLongPress?(input: PositionGestureInput): void;
}
/** @public */
export type PositionGestureDescriptor<O = unknown, V extends View = View, I = {}> = ThisType<PositionGesture<O, V> & I> & PositionGestureInit<V> & Partial<I>;
/** @public */
export interface PositionGestureClass<G extends PositionGesture<any, any> = PositionGesture<any, any>> extends GestureClass<G> {
}
/** @public */
export interface PositionGestureFactory<G extends PositionGesture<any, any> = PositionGesture<any, any>> extends PositionGestureClass<G> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): PositionGestureFactory<G> & I;
specialize(method: GestureMethod): PositionGestureFactory | null;
define<O, V extends View = View>(className: string, descriptor: PositionGestureDescriptor<O, V>): PositionGestureFactory<PositionGesture<any, V>>;
define<O, V extends View = View>(className: string, descriptor: {observes: boolean} & PositionGestureDescriptor<O, V, ObserverType<V>>): PositionGestureFactory<PositionGesture<any, V>>;
define<O, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown} & PositionGestureDescriptor<O, V, I>): PositionGestureFactory<PositionGesture<any, V> & I>;
define<O, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & PositionGestureDescriptor<O, V, I & ObserverType<V>>): PositionGestureFactory<PositionGesture<any, V> & I>;
<O, V extends View = View>(descriptor: PositionGestureDescriptor<O, V>): PropertyDecorator;
<O, V extends View = View>(descriptor: {observes: boolean} & PositionGestureDescriptor<O, V, ObserverType<V>>): PropertyDecorator;
<O, V extends View = View, I = {}>(descriptor: {implements: unknown} & PositionGestureDescriptor<O, V, I>): PropertyDecorator;
<O, V extends View = View, I = {}>(descriptor: {implements: unknown; observes: boolean} & PositionGestureDescriptor<O, V, I & ObserverType<V>>): PropertyDecorator;
}
/** @public */
export interface PositionGesture<O = unknown, V extends View = View> extends Gesture<O, V> {
/** @internal @protected @override */
attachEvents(view: V): void;
/** @internal @protected @override */
detachEvents(view: V): void;
/** @internal @protected */
attachHoverEvents(view: V): void;
/** @internal @protected */
detachHoverEvents(view: V): void;
/** @internal @protected */
attachPressEvents(view: V): void;
/** @internal @protected */
detachPressEvents(view: V): void;
/** @internal @override */
readonly inputs: {readonly [inputId: string]: PositionGestureInput | undefined};
/** @override */
getInput(inputId: string | number): PositionGestureInput | null;
/** @internal @override */
createInput(inputId: string, inputType: GestureInputType, isPrimary: boolean,
x: number, y: number, t: number): PositionGestureInput;
/** @internal */
getOrCreateInput(inputId: string | number, inputType: GestureInputType, isPrimary: boolean,
x: number, y: number, t: number): PositionGestureInput;
/** @internal @override */
clearInput(input: PositionGestureInput): void;
/** @internal @override */
clearInputs(): void;
readonly hoverCount: number;
get hovering(): boolean;
/** @internal */
startHovering(): void;
/** @protected */
willStartHovering(): void;
/** @protected */
onStartHovering(): void;
/** @protected */
didStartHovering(): void;
/** @internal */
stopHovering(): void;
/** @protected */
willStopHovering(): void;
/** @protected */
onStopHovering(): void;
/** @protected */
didStopHovering(): void;
/** @internal */
beginHover(input: PositionGestureInput, event: Event | null): void;
/** @protected */
willBeginHover(input: PositionGestureInput, event: Event | null): void;
/** @protected */
onBeginHover(input: PositionGestureInput, event: Event | null): void;
/** @protected */
didBeginHover(input: PositionGestureInput, event: Event | null): void;
/** @internal */
endHover(input: PositionGestureInput, event: Event | null): void;
/** @protected */
willEndHover(input: PositionGestureInput, event: Event | null): void;
/** @protected */
onEndHover(input: PositionGestureInput, event: Event | null): void;
/** @protected */
didEndHover(input: PositionGestureInput, event: Event | null): void;
readonly pressCount: number;
get pressing(): boolean
/** @internal */
startPressing(): void;
/** @protected */
willStartPressing(): void;
/** @protected */
onStartPressing(): void;
/** @protected */
didStartPressing(): void;
/** @internal */
stopPressing(): void;
/** @protected */
willStopPressing(): void;
/** @protected */
onStopPressing(): void;
/** @protected */
didStopPressing(): void;
/** @internal */
beginPress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
willBeginPress(input: PositionGestureInput, event: Event | null): boolean | void;
/** @protected */
onBeginPress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
didBeginPress(input: PositionGestureInput, event: Event | null): void;
/** @internal */
movePress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
willMovePress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
onMovePress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
didMovePress(input: PositionGestureInput, event: Event | null): void;
/** @internal */
endPress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
willEndPress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
onEndPress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
didEndPress(input: PositionGestureInput, event: Event | null): void;
/** @internal */
cancelPress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
willCancelPress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
onCancelPress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
didCancelPress(input: PositionGestureInput, event: Event | null): void;
/** @internal */
press(input: PositionGestureInput, event: Event | null): void;
/** @protected */
willPress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
onPress(input: PositionGestureInput, event: Event | null): void;
/** @protected */
didPress(input: PositionGestureInput, event: Event | null): void;
/** @internal */
longPress(input: PositionGestureInput): void;
/** @protected */
willLongPress(input: PositionGestureInput): void;
/** @protected */
onLongPress(input: PositionGestureInput): void;
/** @protected */
didLongPress(input: PositionGestureInput): void;
}
/** @public */
export const PositionGesture = (function (_super: typeof Gesture) {
const PositionGesture: PositionGestureFactory = _super.extend("PositionGesture");
PositionGesture.prototype.attachEvents = function (this: PositionGesture, view: View): void {
Gesture.prototype.attachEvents.call(this, view);
this.attachHoverEvents(view);
};
PositionGesture.prototype.detachEvents = function (this: PositionGesture, view: View): void {
this.detachPressEvents(view);
this.detachHoverEvents(view);
Gesture.prototype.detachEvents.call(this, view);
};
PositionGesture.prototype.attachHoverEvents = function (this: PositionGesture, view: View): void {
// hook
};
PositionGesture.prototype.detachHoverEvents = function (this: PositionGesture, view: View): void {
// hook
};
PositionGesture.prototype.attachPressEvents = function (this: PositionGesture, view: View): void {
// hook
};
PositionGesture.prototype.detachPressEvents = function (this: PositionGesture, view: View): void {
// hook
};
PositionGesture.prototype.createInput = function (this: PositionGesture, inputId: string, inputType: GestureInputType, isPrimary: boolean,
x: number, y: number, t: number): PositionGestureInput {
return new PositionGestureInput(inputId, inputType, isPrimary, x, y, t);
};
PositionGesture.prototype.clearInput = function (this: PositionGesture, input: PositionGestureInput): void {
if (!input.hovering && !input.pressing) {
Gesture.prototype.clearInput.call(this, input);
}
};
PositionGesture.prototype.clearInputs = function (this: PositionGesture): void {
Gesture.prototype.clearInputs.call(this);
(this as Mutable<typeof this>).hoverCount = 0;
(this as Mutable<typeof this>).pressCount = 0;
};
Object.defineProperty(PositionGesture.prototype, "hovering", {
get(this: PositionGesture): boolean {
return this.hoverCount !== 0;
},
configurable: true,
})
PositionGesture.prototype.startHovering = function (this: PositionGesture): void {
this.willStartHovering();
this.onStartHovering();
this.didStartHovering();
};
PositionGesture.prototype.willStartHovering = function (this: PositionGesture): void {
// hook
};
PositionGesture.prototype.onStartHovering = function (this: PositionGesture): void {
// hook
};
PositionGesture.prototype.didStartHovering = function (this: PositionGesture): void {
// hook
};
PositionGesture.prototype.stopHovering = function (this: PositionGesture): void {
this.willStopHovering();
this.onStopHovering();
this.didStopHovering();
};
PositionGesture.prototype.willStopHovering = function (this: PositionGesture): void {
// hook
};
PositionGesture.prototype.onStopHovering = function (this: PositionGesture): void {
// hook
};
PositionGesture.prototype.didStopHovering = function (this: PositionGesture): void {
// hook
};
PositionGesture.prototype.beginHover = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
if (!input.hovering) {
this.willBeginHover(input, event);
input.hovering = true;
(this as Mutable<typeof this>).hoverCount += 1;
this.onBeginHover(input, event);
this.didBeginHover(input, event);
if (this.hoverCount === 1) {
this.startHovering();
}
}
};
PositionGesture.prototype.willBeginHover = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.onBeginHover = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.didBeginHover = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.endHover = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
if (input.hovering) {
this.willEndHover(input, event);
input.hovering = false;
(this as Mutable<typeof this>).hoverCount -= 1;
this.onEndHover(input, event);
this.didEndHover(input, event);
if (this.hoverCount === 0) {
this.stopHovering();
}
this.clearInput(input);
}
};
PositionGesture.prototype.willEndHover = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.onEndHover = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.didEndHover = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
Object.defineProperty(PositionGesture.prototype, "pressing", {
get(this: PositionGesture): boolean {
return this.pressCount !== 0;
},
configurable: true,
})
PositionGesture.prototype.startPressing = function (this: PositionGesture): void {
this.willStartPressing();
this.onStartPressing();
this.didStartPressing();
};
PositionGesture.prototype.willStartPressing = function (this: PositionGesture): void {
// hook
};
PositionGesture.prototype.onStartPressing = function (this: PositionGesture): void {
this.attachPressEvents(this.view!);
};
PositionGesture.prototype.didStartPressing = function (this: PositionGesture): void {
// hook
};
PositionGesture.prototype.stopPressing = function (this: PositionGesture): void {
this.willStopPressing();
this.onStopPressing();
this.didStopPressing();
};
PositionGesture.prototype.willStopPressing = function (this: PositionGesture): void {
// hook
};
PositionGesture.prototype.onStopPressing = function (this: PositionGesture): void {
this.detachPressEvents(this.view!);
};
PositionGesture.prototype.didStopPressing = function (this: PositionGesture): void {
// hook
};
PositionGesture.prototype.beginPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
if (!input.pressing) {
let allowPress = this.willBeginPress(input, event);
if (allowPress === void 0) {
allowPress = true;
}
if (allowPress) {
input.pressing = true;
input.defaultPrevented = false;
(this as Mutable<typeof this>).pressCount += 1;
this.onBeginPress(input, event);
input.setHoldTimer(this.longPress.bind(this, input));
this.didBeginPress(input, event);
if (this.pressCount === 1) {
this.startPressing();
}
}
}
};
PositionGesture.prototype.willBeginPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): boolean | void {
// hook
};
PositionGesture.prototype.onBeginPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
input.x0 = input.x;
input.y0 = input.y;
input.t0 = input.t;
input.dx = 0;
input.dy = 0;
input.dt = 0;
};
PositionGesture.prototype.didBeginPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.movePress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
if (input.pressing) {
this.willMovePress(input, event);
this.onMovePress(input, event);
this.didMovePress(input, event);
}
};
PositionGesture.prototype.willMovePress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.onMovePress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.didMovePress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.endPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
input.clearHoldTimer();
if (input.pressing) {
this.willEndPress(input, event);
input.pressing = false;
(this as Mutable<typeof this>).pressCount -= 1;
this.onEndPress(input, event);
this.didEndPress(input, event);
if (this.pressCount === 0) {
this.stopPressing();
}
this.clearInput(input);
}
};
PositionGesture.prototype.willEndPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.onEndPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.didEndPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.cancelPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
input.clearHoldTimer();
if (input.pressing) {
this.willCancelPress(input, event);
input.pressing = false;
(this as Mutable<typeof this>).pressCount -= 1;
this.onCancelPress(input, event);
this.didCancelPress(input, event);
if (this.pressCount === 0) {
this.stopPressing();
}
this.clearInput(input);
}
};
PositionGesture.prototype.willCancelPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.onCancelPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.didCancelPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.press = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
this.willPress(input, event);
this.onPress(input, event);
this.didPress(input, event);
};
PositionGesture.prototype.willPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.onPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.didPress = function (this: PositionGesture, input: PositionGestureInput, event: Event | null): void {
// hook
};
PositionGesture.prototype.longPress = function (this: PositionGesture, input: PositionGestureInput): void {
input.clearHoldTimer();
const dt = performance.now() - input.t0;
if (dt < 1.5 * input.holdDelay && input.pressing) {
this.willLongPress(input);
this.onLongPress(input);
this.didLongPress(input);
}
};
PositionGesture.prototype.willLongPress = function (this: PositionGesture, input: PositionGestureInput): void {
// hook
};
PositionGesture.prototype.onLongPress = function (this: PositionGesture, input: PositionGestureInput): void {
const t = performance.now();
input.dt = t - input.t;
input.t = t;
};
PositionGesture.prototype.didLongPress = function (this: PositionGesture, input: PositionGestureInput): void {
// hook
};
PositionGesture.construct = function <G extends PositionGesture<any, any>>(gestureClass: {prototype: G}, gesture: G | null, owner: FastenerOwner<G>): G {
gesture = _super.construct(gestureClass, gesture, owner) as G;
(gesture as Mutable<typeof gesture>).hoverCount = 0;
(gesture as Mutable<typeof gesture>).pressCount = 0;
return gesture;
};
PositionGesture.specialize = function (method: GestureMethod): PositionGestureFactory | null {
if (method === "pointer") {
return PointerPositionGesture;
} else if (method === "touch") {
return TouchPositionGesture;
} else if (method === "mouse") {
return MousePositionGesture;
} else if (typeof PointerEvent !== "undefined") {
return PointerPositionGesture;
} else if (typeof TouchEvent !== "undefined") {
return TouchPositionGesture;
} else {
return MousePositionGesture;
}
};
PositionGesture.define = function <O, V extends View>(className: string, descriptor: PositionGestureDescriptor<O, V>): PositionGestureFactory<PositionGesture<any, V>> {
let superClass = descriptor.extends as PositionGestureFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
let method = descriptor.method;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
delete descriptor.method;
if (descriptor.key === true) {
Object.defineProperty(descriptor, "key", {
value: className,
configurable: true,
});
} else if (descriptor.key === false) {
Object.defineProperty(descriptor, "key", {
value: void 0,
configurable: true,
});
}
if (method === void 0) {
method = "auto";
}
if (superClass === void 0 || superClass === null) {
superClass = PositionGesture.specialize(method);
}
if (superClass === null) {
superClass = this;
}
const gestureClass = superClass.extend(className, descriptor);
gestureClass.construct = function (gestureClass: {prototype: PositionGesture<any, any>}, gesture: PositionGesture<O, V> | null, owner: O): PositionGesture<O, V> {
gesture = superClass!.construct(gestureClass, gesture, owner);
if (affinity !== void 0) {
gesture.initAffinity(affinity);
}
if (inherits !== void 0) {
gesture.initInherits(inherits);
}
return gesture;
};
return gestureClass;
};
return PositionGesture;
})(Gesture); | the_stack |
import * as test from 'tape';
import {
MuSchema,
MuASCII,
MuFixedASCII,
MuUTF8,
MuBoolean,
MuFloat32,
MuFloat64,
MuInt8,
MuInt16,
MuInt32,
MuUint8,
MuUint16,
MuUint32,
MuVarint,
MuRelativeVarint,
MuStruct,
MuArray,
MuSortedArray,
MuDictionary,
MuVector,
MuUnion,
MuDate,
MuJSON,
MuBytes,
MuOption,
} from '../index';
test('primitive.assign()', (t) => {
const bool = new MuBoolean();
t.equal(bool.assign(true, true), true);
t.equal(bool.assign(true, false), false);
t.equal(bool.assign(false, true), true);
t.equal(bool.assign(false, false), false);
const float32 = new MuFloat32();
t.equal(float32.assign(1, 2), 2);
t.end();
});
test('array.assign()', (t) => {
const array = new MuArray(new MuFloat32(), Infinity);
const aSrc = array.alloc();
const aDst = array.alloc();
aSrc.push(0);
t.is(array.assign(aDst, aSrc), aDst);
t.deepEqual(aDst, [0]);
aSrc.push(0.5);
array.assign(aDst, aSrc);
t.deepEqual(aDst, [0, 0.5]);
aDst.push(1);
array.assign(aDst, aSrc);
t.deepEqual(aDst, [0, 0.5]);
const nestedArray = new MuArray(
new MuArray(new MuFloat32(), Infinity),
Infinity,
);
const naSrc = nestedArray.alloc();
const naDst = nestedArray.alloc();
naSrc.push([]);
t.is(nestedArray.assign(naDst, naSrc), naDst);
t.deepEqual(naDst, [[]]);
t.isNot(naDst[0], naSrc[0]);
naSrc.push([0, 0.5]);
nestedArray.assign(naDst, naSrc);
t.deepEqual(naDst, [[], [0, 0.5]]);
t.isNot(naDst[1], naSrc[1]);
t.end();
});
test('sortedArray.assign()', (t) => {
const array = new MuSortedArray(new MuFloat32(), Infinity);
const aSrc = array.alloc();
const aDst = array.alloc();
aSrc.push(0);
t.is(array.assign(aDst, aSrc), aDst);
t.deepEqual(aDst, [0]);
aSrc.push(0.5);
array.assign(aDst, aSrc);
t.deepEqual(aDst, [0, 0.5]);
aDst.push(1);
array.assign(aDst, aSrc);
t.deepEqual(aDst, [0, 0.5]);
const nestedArray = new MuSortedArray(
new MuSortedArray(new MuFloat32(), Infinity),
Infinity,
);
const naSrc = nestedArray.alloc();
const naDst = nestedArray.alloc();
naSrc.push([]);
t.is(nestedArray.assign(naDst, naSrc), naDst);
t.deepEqual(naDst, [[]]);
t.isNot(naDst[0], naSrc[0]);
naSrc.push([0, 0.5]);
nestedArray.assign(naDst, naSrc);
t.deepEqual(naDst, [[], [0, 0.5]]);
t.isNot(naDst[1], naSrc[1]);
t.end();
});
test('struct.assign()', (t) => {
const struct = new MuStruct({
struct: new MuStruct({
ascii: new MuASCII(),
fixed: new MuFixedASCII(1),
utf8: new MuUTF8(),
bool: new MuBoolean(),
float32: new MuFloat32(),
float64: new MuFloat64(),
int8: new MuInt8(),
int16: new MuInt16(),
int32: new MuInt32(),
uint8: new MuUint8(),
uint16: new MuUint16(),
uint32: new MuUint32(),
varint: new MuVarint(),
rvarint: new MuRelativeVarint(),
array: new MuArray(new MuFloat32(), Infinity),
sorted: new MuSortedArray(new MuFloat32(), Infinity),
dict: new MuDictionary(new MuFloat32(), Infinity),
vector: new MuVector(new MuFloat32(), 3),
union: new MuUnion({
b: new MuBoolean(),
f: new MuFloat32(),
}),
}),
});
const s0 = struct.alloc();
const s1 = struct.alloc();
s1.struct.ascii = 'a';
t.equals(struct.assign(s0, s1), s0);
t.notEquals(struct.assign(s0, s1), s1);
t.deepEquals(struct.assign(s0, s1), s1);
t.notEquals(struct.assign(s0, s1).struct, s1.struct);
s1.struct.fixed = 'a';
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.utf8 = 'Iñtërnâtiônàlizætiøn☃💩';
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.bool = true;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.float32 = 0.5;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.float64 = 0.5;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.int8 = -1;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.int16 = -1;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.int32 = -1;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.uint8 = 1;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.uint16 = 1;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.uint32 = 1;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.varint = 1;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.rvarint = -1;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.array.push(0);
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.sorted.push(0);
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.dict['a'] = 0.5;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.vector[0] = 0.5;
t.deepEquals(struct.assign(s0, s1), s1);
s1.struct.union.type = 'b';
s1.struct.union.data = false;
t.deepEquals(struct.assign(s0, s1), s1);
t.end();
});
test('union.assign()', (t) => {
const stringOrFloat = new MuUnion({
u: new MuUTF8(),
f: new MuFloat32(),
});
const src = stringOrFloat.alloc();
const dst = stringOrFloat.alloc();
src.type = 'u';
src.data = 'Iñtërnâtiônàlizætiøn☃💩';
t.is(stringOrFloat.assign(dst, src), dst);
t.deepEqual(dst, {type: 'u', data: 'Iñtërnâtiônàlizætiøn☃💩'});
dst.data = 'Internationalization';
stringOrFloat.assign(dst, src);
t.deepEqual(dst, {type: 'u', data: 'Iñtërnâtiônàlizætiøn☃💩'});
src.type = 'f';
src.data = 0.5;
stringOrFloat.assign(dst, src);
t.deepEqual(dst, {type: 'f', data: 0.5});
stringOrFloat.assign(dst, stringOrFloat.alloc());
t.deepEqual(dst, stringOrFloat.alloc());
const union = new MuUnion({
us: new MuStruct({
u: new MuUTF8(),
}),
fs: new MuStruct({
f: new MuFloat32(),
}),
}, 'us');
const uSrc = union.alloc();
const uDst = union.alloc();
uSrc.type = 'fs';
uSrc.data = union.muData.fs.alloc();
t.is(union.assign(uDst, uSrc), uDst);
t.deepEqual(uDst, {type: 'fs', data: {f: 0}});
t.isNot(uDst.data, uSrc.data);
t.end();
});
test('bytes.assign()', (t) => {
const bytes = new MuBytes();
const src = new Uint8Array(3);
const dst = new Uint8Array(3);
src[1] = 1;
src[2] = 255;
t.is(bytes.assign(dst, src), dst);
t.deepEqual(dst, new Uint8Array([0, 1, 255]));
t.end();
});
test('dictionary.assign()', (t) => {
const dictionary = new MuDictionary(new MuFloat32(), Infinity);
const dSrc = dictionary.alloc();
const dDst = dictionary.alloc();
dSrc.a = 0.5;
t.is(dictionary.assign(dDst, dSrc), dDst);
t.deepEqual(dDst, {a: 0.5});
dSrc.b = 1.5;
dictionary.assign(dDst, dSrc);
t.deepEqual(dDst, {a: 0.5, b: 1.5});
dDst.c = 1;
dictionary.assign(dDst, dSrc);
t.deepEqual(dDst, {a: 0.5, b: 1.5});
const nestedDictionary = new MuDictionary(
new MuDictionary(new MuFloat32(), Infinity),
Infinity,
);
const ndSrc = nestedDictionary.alloc();
const ndDst = nestedDictionary.alloc();
ndSrc.a = {};
t.is(nestedDictionary.assign(ndDst, ndSrc), ndDst);
t.deepEqual(ndDst, {a: {}});
t.isNot(ndDst.a, ndSrc.a);
ndSrc.b = {c: 0.5, d: 1.5};
nestedDictionary.assign(ndDst, ndSrc);
t.deepEqual(ndDst, {a: {}, b: {c: 0.5, d: 1.5}});
ndDst.c = {e: 2.5};
nestedDictionary.assign(ndDst, ndSrc);
t.deepEqual(ndDst, {a: {}, b: {c: 0.5, d: 1.5}});
t.end();
});
test('vector.assign()', (t) => {
const vector = new MuVector(new MuFloat32(), 2);
const src = vector.alloc();
const dst = vector.alloc();
src[0] = 0.5;
src[1] = 1.5;
t.is(vector.assign(dst, src), dst);
t.deepEqual(dst, new Float32Array([0.5, 1.5]));
t.end();
});
test('option.assign()', (t) => {
function doTest<T extends MuSchema<any>>(
opt:MuOption<T>,
modify:(x:T['identity']) => T['identity'],
) {
// value to value
let src = opt.alloc();
let dst = opt.alloc();
src = modify(src);
dst = opt.assign(dst, src);
t.deepEqual(dst, src);
// value to undefined
src = opt.alloc();
dst = opt.alloc();
src = undefined;
dst = opt.assign(dst, src);
t.deepEqual(dst, src);
// undefined to value
src = opt.alloc();
dst = undefined;
dst = opt.assign(dst, src);
t.deepEqual(dst, src);
// undefined to undefined
src = undefined;
dst = undefined;
dst = opt.assign(dst, src);
t.deepEqual(dst, src);
}
const innerPrimitive = new MuFloat32();
const optPrimitive = new MuOption(innerPrimitive);
doTest(optPrimitive, (x) => 20);
const innerFunctor = new MuVector(innerPrimitive, 2);
const optFunctor = new MuOption(innerFunctor);
doTest(optFunctor, (x) => {
x[0] = 0.5;
x[1] = 1.5;
return x;
});
// Ensure functor identity is preserved
const idSrc = optFunctor.alloc();
let idDst = optFunctor.alloc();
idSrc[0] = 0.5;
idSrc[1] = 1.5;
const idDstOld = idDst;
idDst = optFunctor.assign(idDst, idSrc);
t.is(idDst, idDstOld);
t.deepEqual(idDst, idDstOld);
t.end();
});
test('date.assign()', (t) => {
const date = new MuDate();
const src = date.alloc();
const dst = date.alloc();
dst.setTime(0);
t.is(date.assign(dst, src), dst);
t.deepEqual(dst, src);
t.end();
});
test('json.assign', (t) => {
const json = new MuJSON();
const o = {a: 0, b: 1};
const p = {a: {b: {c: [0]}}};
t.is(json.assign(o, p), o);
t.deepEqual(o, {a: {b: {c: [0]}}});
t.isNot(o.a, p.a);
const q = [0, 1, 2];
const r = [{}, {}];
t.is(json.assign(q, r), q);
t.deepEqual(q, [{}, {}]);
t.isNot(q[0], r[0]);
t.end();
});
class MuReference<T> implements MuSchema<T|null> {
public muType = 'reference';
public identity:T|null = null;
public muData = { type: 'reference' };
public json = { type: 'reference' };
constructor () { }
public alloc () : T|null { return null; }
public free () { }
public assign (dst:T|null, src:T|null) : T|null { return src; }
public clone (x) { return x; }
public equal (a, b) { return a === b; }
public diff () : never { throw new TypeError('cannot serialize reference'); }
public patch () : never { throw new TypeError('cannot serialize reference'); }
public toJSON () : never { throw new TypeError('cannot serialize reference'); }
public fromJSON () : never { throw new TypeError('cannot serialize reference'); }
}
test('when dst is not reference', (t) => {
const Human = new MuStruct({
name: new MuUTF8(),
power: new MuReference<{
name:string,
description:string,
}>(),
});
const mortal = Human.alloc();
mortal.name = 'Logan';
const mutant = Human.alloc();
mutant.name = 'Wolverine';
mutant.power = {
name: 'regenerative healing factor',
description: 'ability to regenerate damaged tissue insanely fast',
};
Human.assign(mortal, mutant);
t.deepEqual(mortal, mutant);
t.equal(mortal.power, mutant.power);
t.end();
}); | the_stack |
import * as Path from "path";
import * as FS from "fs";
import {Mutable, Proto, Equals} from "@swim/util";
import {FastenerOwner, FastenerFlags, FastenerInit, FastenerClass, Fastener} from "@swim/component";
/** @internal */
export type FileRelationValue<F extends FileRelation<any, any>> =
F extends FileRelation<any, infer T> ? T : never;
/** @public */
export interface FileRelationInit<T = unknown> extends FastenerInit {
extends?: {prototype: FileRelation<any, any>} | string | boolean | null;
baseDir?: string;
resolves?: boolean;
getBaseDir?(): string | undefined;
willSetBaseDir?(newBaseDir: string | undefined, oldBaseDir: string | undefined): void;
didSetBaseDir?(newBaseDir: string | undefined, oldBaseDir: string | undefined): void;
resolveFile?(baseDir: string | undefined, fileName: string | undefined): Promise<string | undefined>;
exists?(path: string): boolean;
readFile?(path: string): Promise<T>;
writeFile?(path: string, value: T): Promise<void>;
willSetValue?(path: string, newValue: T, oldValue: T): void;
didSetValue?(path: string, newValue: T, oldValue: T): void;
equalValues?(newValue: T, oldValue: T): boolean;
}
/** @public */
export type FileRelationDescriptor<O = unknown, T = unknown, I = {}> = ThisType<FileRelation<O, T> & I> & FileRelationInit<T> & Partial<I>;
/** @public */
export interface FileRelationClass<F extends FileRelation<any, any> = FileRelation<any, any>> extends FastenerClass<F> { /** @internal */
readonly ResolvesFlag: FastenerFlags;
/** @internal @override */
readonly FlagShift: number;
/** @internal @override */
readonly FlagMask: FastenerFlags;
}
/** @public */
export interface FileRelationFactory<F extends FileRelation<any, any> = FileRelation<any, any>> extends FileRelationClass<F> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): FileRelationFactory<F> & I;
define<O, T = unknown>(className: string, descriptor: FileRelationDescriptor<O, T>): FileRelationFactory<FileRelation<any, T>>;
define<O, T = unknown, I = {}>(className: string, descriptor: {implements: unknown} & FileRelationDescriptor<O, T, I>): FileRelationFactory<FileRelation<any, T> & I>;
<O, T = unknown>(descriptor: FileRelationDescriptor<O, T>): PropertyDecorator;
<O, T = unknown, I = {}>(descriptor: {implements: unknown} & FileRelationDescriptor<O, T, I>): PropertyDecorator;
}
/** @public */
export interface FileRelation<O = unknown, T = unknown> extends Fastener<O> {
/** @override */
get fastenerType(): Proto<FileRelation<any, any>>;
readonly baseDir: string | undefined;
getBaseDir(): string | undefined;
/** @internal */
initBaseDir(baseDir: string | undefined): void;
setBaseDir(baseDir: string | undefined): void;
/** @protected */
willSetBaseDir(newBaseDir: string | undefined, oldBaseDir: string | undefined): void;
/** @protected */
onSetBaseDir(newBaseDir: string | undefined, oldBaseDir: string | undefined): void;
/** @protected */
didSetBaseDir(newBaseDir: string | undefined, oldBaseDir: string | undefined): void;
get resolves(): boolean;
setResolves(resolves: boolean): void;
/** @internal */
initResolves(resolves: boolean): void;
/** @internal */
resolveFile(baseDir: string | undefined, fileName: string | undefined): Promise<string | undefined>;
/** @internal */
exists(path: string): boolean;
/** @internal */
readFile(path: string): Promise<T>;
/** @internal */
writeFile(path: string, value: T): Promise<void>;
/** @protected */
willSetValue(path: string, newValue: T, oldValue: T): void;
/** @protected */
onSetValue(path: string, newValue: T, oldValue: T): void;
/** @protected */
didSetValue(path: string, newValue: T, oldValue: T): void;
/** @internal */
equalValues(newValue: T, oldValue: T): boolean;
/** @internal @override */
get lazy(): boolean; // prototype property
/** @internal @override */
get static(): string | boolean; // prototype property
}
/** @public */
export const FileRelation = (function (_super: typeof Fastener) {
const FileRelation: FileRelationFactory = _super.extend("FileRelation");
Object.defineProperty(FileRelation.prototype, "fastenerType", {
get: function (this: FileRelation): Proto<FileRelation<any, any>> {
return FileRelation;
},
configurable: true,
});
FileRelation.prototype.getBaseDir = function (this: FileRelation): string | undefined {
let baseDir = this.baseDir;
if (baseDir === void 0) {
baseDir = process.cwd();
}
return baseDir;
};
FileRelation.prototype.initBaseDir = function (this: FileRelation, baseDir: string | undefined): void {
(this as Mutable<typeof this>).baseDir = baseDir;
};
FileRelation.prototype.setBaseDir = function (this: FileRelation, newBaseDir: string | undefined): void {
const oldBaseDir = this.baseDir;
if (newBaseDir !== oldBaseDir) {
this.willSetBaseDir(newBaseDir, oldBaseDir);
(this as Mutable<typeof this>).baseDir = newBaseDir;
this.onSetBaseDir(newBaseDir, oldBaseDir);
this.didSetBaseDir(newBaseDir, oldBaseDir);
}
};
FileRelation.prototype.willSetBaseDir = function (this: FileRelation, newBaseDir: string | undefined, oldBaseDir: string | undefined): void {
// hook
};
FileRelation.prototype.onSetBaseDir = function (this: FileRelation, newBaseDir: string | undefined, oldBaseDir: string | undefined): void {
// hook
};
FileRelation.prototype.didSetBaseDir = function (this: FileRelation, newBaseDir: string | undefined, oldBaseDir: string | undefined): void {
// hook
};
Object.defineProperty(FileRelation.prototype, "resolves", {
get: function (this: FileRelation): boolean {
return (this.flags & FileRelation.ResolvesFlag) !== 0;
},
configurable: true,
});
FileRelation.prototype.setResolves = function (this: FileRelation, resolves: boolean): void {
if (resolves) {
(this as Mutable<typeof this>).flags |= FileRelation.ResolvesFlag;
} else {
(this as Mutable<typeof this>).flags &= ~FileRelation.ResolvesFlag;
}
};
FileRelation.prototype.initResolves = function (this: FileRelation, resolves: boolean): void {
if (resolves) {
(this as Mutable<typeof this>).flags |= FileRelation.ResolvesFlag;
} else {
(this as Mutable<typeof this>).flags &= ~FileRelation.ResolvesFlag;
}
};
FileRelation.prototype.resolveFile = async function (this: FileRelation, baseDir: string | undefined, fileName: string | undefined): Promise<string | undefined> {
if (fileName !== void 0) {
if (baseDir === void 0) {
baseDir = process.cwd();
}
const resolves = this.resolves;
do {
const path = Path.resolve(baseDir, fileName);
if (this.exists(path)) {
return path;
}
if (resolves === true) {
const parentDir = Path.dirname(baseDir);
if (baseDir !== parentDir) {
baseDir = parentDir;
continue;
}
}
break;
} while (true);
}
return void 0;
};
FileRelation.prototype.exists = function (this: FileRelation, path: string): boolean {
return FS.existsSync(path);
};
FileRelation.prototype.readFile = async function <T>(this: FileRelation<unknown, T>, path: string): Promise<T> {
const buffer = await FS.promises.readFile(path, "utf8");
return JSON.parse(buffer);
};
FileRelation.prototype.writeFile = async function <T>(this: FileRelation<unknown, T>, path: string, value: T): Promise<void> {
const buffer = JSON.stringify(value, void 0, 2) + "\n";
await FS.promises.writeFile(path, buffer, "utf8");
};
FileRelation.prototype.willSetValue = function <T>(this: FileRelation<unknown, T>, path: string, newValue: T, oldValue: T): void {
// hook
};
FileRelation.prototype.onSetValue = function <T>(this: FileRelation<unknown, T>, path: string, newValue: T, oldValue: T): void {
// hook
};
FileRelation.prototype.didSetValue = function <T>(this: FileRelation<unknown, T>, path: string, newValue: T, oldValue: T): void {
// hook
};
FileRelation.prototype.equalValues = function <T>(this: FileRelation<unknown, T>, newValue: T, oldValue: T): boolean {
return Equals(newValue, oldValue);
};
Object.defineProperty(FileRelation.prototype, "lazy", {
get: function (this: FileRelation): boolean {
return false;
},
configurable: true,
});
Object.defineProperty(FileRelation.prototype, "static", {
get: function (this: FileRelation): string | boolean {
return true;
},
configurable: true,
});
FileRelation.construct = function <F extends FileRelation<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F {
fastener = _super.construct(fastenerClass, fastener, owner) as F;
(fastener as Mutable<typeof fastener>).baseDir = void 0;
return fastener;
};
FileRelation.define = function <O, T>(className: string, descriptor: FileRelationDescriptor<O, T>): FileRelationFactory<FileRelation<any, T>> {
let superClass = descriptor.extends as FileRelationFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
const baseDir = descriptor.baseDir;
const resolves = descriptor.resolves;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
delete descriptor.baseDir;
delete descriptor.resolves;
if (superClass === void 0 || superClass === null) {
superClass = this;
}
const fastenerClass = superClass.extend(className, descriptor);
fastenerClass.construct = function (fastenerClass: {prototype: FileRelation<any, any>}, fastener: FileRelation<O, T> | null, owner: O): FileRelation<O, T> {
fastener = superClass!.construct(fastenerClass, fastener, owner);
if (affinity !== void 0) {
fastener.initAffinity(affinity);
}
if (inherits !== void 0) {
fastener.initInherits(inherits);
}
if (baseDir !== void 0) {
fastener.initBaseDir(baseDir);
}
if (resolves !== void 0) {
fastener.initResolves(resolves);
}
return fastener;
};
return fastenerClass;
};
(FileRelation as Mutable<typeof FileRelation>).ResolvesFlag = 1 << (_super.FlagShift + 0);
(FileRelation as Mutable<typeof FileRelation>).FlagShift = _super.FlagShift + 1;
(FileRelation as Mutable<typeof FileRelation>).FlagMask = (1 << FileRelation.FlagShift) - 1;
return FileRelation;
})(Fastener); | the_stack |
namespace LiteMol.Viewer.PDBe.SequenceAnnotation {
import Entity = Bootstrap.Entity;
import Transformer = Bootstrap.Entity.Transformer;
import Query = LiteMol.Core.Structure.Query;
export interface Annotations extends Entity<{ data: any }> { }
export const Annotations = Entity.create<{ data: any }>({ name: 'PDBe Sequence Annotations', typeClass: 'Data', shortName: 'SA', description: 'Represents PDBe sequence annotation data.' });
export interface Annotation extends Entity<{ query: Query.Source; color: Visualization.Color; }> { }
export const Annotation = Entity.create<{ query: Query.Source; color: Visualization.Color; }>({ name: 'PDBe Sequence Annotation', typeClass: 'Object', shortName: 'SA', description: 'Represents PDBe sequence annotation.' }, { isSilent: true, isFocusable: true });
export interface Behaviour extends Entity<Entity.Behaviour.Props<Interactivity.Behaviour>> { }
export const Behaviour = Entity.create<Entity.Behaviour.Props<Interactivity.Behaviour>>({ name: 'PDBe Sequence Annotation Behaviour', typeClass: 'Behaviour', shortName: 'SA', description: 'Represents PDBe sequence annoation behaviour.' });
export namespace Interactivity {
export class Behaviour implements Bootstrap.Behaviour.Dynamic {
private node: Entity.Behaviour.Any = <any>void 0;
private current: Annotation | undefined = void 0;
private subs: Bootstrap.Rx.IDisposable[] = [];
private toHighlight: Entity.Any | undefined = void 0;
private isHighlightOn = false;
dispose() {
this.resetTheme();
for (let sub of this.subs) {
sub.dispose();
}
this.subs = [];
this.node = <any>void 0;
}
register(behaviour: Entity.Behaviour.Any) {
this.node = behaviour;
this.subs.push(this.context.behaviours.currentEntity.subscribe(e => this.update(e)));
this.subs.push(Bootstrap.Command.Entity.Highlight.getStream(this.context).subscribe(e => {
if (e.data.entities.length === 1) {
let a = e.data.entities[0];
if (a.type !== Annotation) return;
this.toHighlight = a;
this.isHighlightOn = e.data.isOn;
this.__highlight();
}
}));
this.subs.push(Bootstrap.Command.Entity.Focus.getStream(this.context).subscribe(e => {
if (e.data.length === 1) {
let a = e.data[0];
if (a.type !== Annotation) return;
this.focus(a as Annotation);
}
}));
}
private __highlight = LiteMol.Core.Utils.debounce(() => this.highlight(), 33);
get molecule() {
return Bootstrap.Utils.Molecule.findMolecule(this.node)
}
private resetTheme() {
let molecule = this.molecule;
if (molecule) {
Bootstrap.Command.Visual.ResetTheme.dispatch(this.context, { selection: Bootstrap.Tree.Selection.byValue(molecule).subtree() });
}
}
private getCached(a: Annotation, model: Entity.Molecule.Model) {
return this.context.entityCache.get(a, `theme-${model.id}`) as Visualization.Theme;
}
private setCached(a: Annotation, model: Entity.Molecule.Model, theme: Visualization.Theme) {
this.context.entityCache.set(a, `theme-${model.id}`, theme);
}
private highlight() {
let e = this.toHighlight;
this.toHighlight = void 0;
if (!e || e.type !== Annotation) return;
let a = e as Annotation;
if (!this.isHighlightOn) {
if (this.current) {
this.update(this.current);
} else {
this.resetTheme();
}
} else {
this.apply(a);
}
}
private focus(a: Annotation) {
let molecule = this.molecule;
if (!molecule) return;
let model = this.context.select(Bootstrap.Tree.Selection.byValue(molecule).subtree().ofType(Bootstrap.Entity.Molecule.Model))[0] as Bootstrap.Entity.Molecule.Model;
if (!model) return;
Bootstrap.Command.Molecule.FocusQuery.dispatch(this.context, { model, query: a.props.query });
Bootstrap.Command.Entity.SetCurrent.dispatch(this.context, a);
}
private apply(a: Annotation) {
let molecule = this.molecule;
if (!molecule) return;
let visuals = this.context.select(Bootstrap.Tree.Selection.byValue(molecule).subtree().ofType(Bootstrap.Entity.Molecule.Visual));
for (let v of visuals) {
let model = Bootstrap.Utils.Molecule.findModel(v);
if (!model) continue;
let theme = this.getCached(a, model);
if (!theme) {
theme = Theme.create(model, a.props.query, a.props.color);
this.setCached(a, model, theme);
}
Bootstrap.Command.Visual.UpdateBasicTheme.dispatch(this.context, { visual: v as any, theme });
}
}
private update(e: Entity.Any | undefined) {
if (!e || e.type !== Annotation) {
if (this.current) this.resetTheme();
this.current = void 0;
return;
}
this.current = e as Annotation;
this.apply(this.current);
}
constructor(public context: Bootstrap.Context) {
}
}
}
namespace Theme {
const defaultColor = <LiteMol.Visualization.Color>{ r: 1, g: 1, b: 1 };
const selectionColor = Visualization.Theme.Default.SelectionColor;
const highlightColor = Visualization.Theme.Default.HighlightColor;
function createResidueMap(model: LiteMol.Core.Structure.Molecule.Model, fs: Query.FragmentSeq) {
let map = new Uint8Array(model.data.residues.count);
let residueIndex = model.data.atoms.residueIndex;
for (let f of fs.fragments) {
for (let i of f.atomIndices) {
map[residueIndex[i]] = 1;
}
}
return map;
}
export function create(entity: Bootstrap.Entity.Molecule.Model, query: Query.Source, color: Visualization.Color) {
let model = entity.props.model;
let q = Query.Builder.toQuery(query);
let fs = q(model.queryContext);
let map = createResidueMap(model, fs);
let colors = Core.Utils.FastMap.create<string, LiteMol.Visualization.Color>();
colors.set('Uniform', defaultColor);
colors.set('Bond', defaultColor);
colors.set('Selection', selectionColor);
colors.set('Highlight', highlightColor);
let colorMap = Core.Utils.FastMap.create<number, Visualization.Color>();
colorMap.set(1, color);
let residueIndex = model.data.atoms.residueIndex;
let mapping = Visualization.Theme.createColorMapMapping(i => map[residueIndex[i]], colorMap, defaultColor);
return Visualization.Theme.createMapping(mapping, { colors, interactive: true, transparency: { alpha: 1.0 } });
}
}
function buildAnnotations(parent: Annotations, id: string, data: any) {
let action = Bootstrap.Tree.Transform.build();
if (!data) {
return action;
}
let baseColor = Visualization.Color.fromHex(0xFA6900);
for (let g of ["Pfam", "InterPro", "CATH", "SCOP", "UniProt"]) {
let ans = data[g];
if (!ans) continue;
let entries = Object.keys(ans).filter(a => Object.prototype.hasOwnProperty.call(ans, a))
if (!entries.length) continue;
let group = action.add(parent, Transformer.Basic.CreateGroup, { label: g, isCollapsed: true }, { isBinding: true });
for (let a of entries) {
group.then(CreateSingle, { data: ans[a], id: a, color: baseColor });
}
}
action.add(parent, CreateBehaviour, {}, { isHidden: true });
return action;
}
function getInsCode(v: string) {
if (v.length === 0) return null;
return v;
}
export interface CreateSingleProps { id?: string, data?: any, color?: Visualization.Color }
export const CreateSingle = Bootstrap.Tree.Transformer.create<Entity.Group, Annotation, CreateSingleProps>({
id: 'pdbe-sequence-annotations-create-single',
name: 'PDBe Sequence Annotation',
description: 'Create a sequence annotation object.',
from: [], // this is empty because we only want to show it as an update
to: [Annotation],
defaultParams: () => ({ }),
isUpdatable: true
}, (context, a, t) => {
return Bootstrap.Task.create<Annotation>(`Sequence Annotation`, 'Background', async ctx => {
let data = t.params.data;
let query =
Query.or.apply(null, data.mappings.map((m: any) =>
Query.sequence(
m.entity_id.toString(), m.struct_asym_id,
{ seqNumber: m.start.residue_number, insCode: getInsCode(m.start.author_insertion_code) },
{ seqNumber: m.end.residue_number, insCode: getInsCode(m.end.author_insertion_code) })))
.union();
return Annotation.create(t, { label: data.identifier, description: t.params.id, query, color: t.params.color! });
});
}
);
const Parse = Bootstrap.Tree.Transformer.create<Entity.Data.String, Annotations, { }>({
id: 'pdbe-sequence-annotations-parse',
name: 'PDBe Sequence Annotations',
description: 'Parse sequence annotation JSON.',
from: [Entity.Data.String],
to: [Annotations],
defaultParams: () => ({})
}, (context, a, t) => {
return Bootstrap.Task.create<Annotations>(`Sequence Annotations`, 'Normal', async ctx => {
await ctx.updateProgress('Parsing...');
let data = JSON.parse(a.props.data);
return Annotations.create(t, { label: 'Sequence Annotations', data });
}).setReportTime(true);
}
);
const CreateBehaviour = Bootstrap.Tree.Transformer.create<Annotations, Behaviour, { }>({
id: 'pdbe-sequence-annotations-create-behaviour',
name: 'PDBe Sequence Annotation Behaviour',
description: 'Create sequence annotation behaviour.',
from: [Annotations],
to: [Behaviour],
defaultParams: () => ({})
}, (context, a, t) => {
return Bootstrap.Task.resolve<Behaviour>(`Sequence Annotations`, 'Background', Behaviour.create(t, { label: 'Sequence Annotations', behaviour: new Interactivity.Behaviour(context) }))
}
);
const Build = Bootstrap.Tree.Transformer.action<Annotations, Entity.Action, { }>({
id: 'pdbe-sequence-annotations-build',
name: 'PDBe Sequence Annotations',
description: 'Build sequence validations behaviour.',
from: [Annotations],
to: [Entity.Action],
defaultParams: () => ({})
}, (context, a, t) => {
let data = a.props.data;
let keys = Object.keys(data);
return buildAnnotations(a, keys[0], data[keys[0]]);
}, "Sequence annotations downloaded. Selecting or hovering an annotation in the tree will color the visuals."
);
export const DownloadAndCreate = Bootstrap.Tree.Transformer.action<Entity.Molecule.Molecule, Entity.Action, { }>({
id: 'pdbe-sequence-annotations-download-and-create',
name: 'PDBe Sequence Annotations',
description: 'Download Sequence Annotations from PDBe',
from: [Entity.Molecule.Molecule],
to: [Entity.Action],
defaultParams: () => ({})
}, (context, a, t) => {
let id = a.props.molecule.id.trim().toLocaleLowerCase();
return Bootstrap.Tree.Transform.build()
.add(a, Transformer.Data.Download, { url: `https://www.ebi.ac.uk/pdbe/api/mappings/${id}`, type: 'String', id, description: 'Annotation Data', title: 'Annotation' })
.then(Parse, { }, { isBinding: true })
.then(Build, { }, { isBinding: true });
});
} | the_stack |
import { BarcodeGenerator } from "../../../src/barcode/barcode";
import { createElement } from "@syncfusion/ej2-base";
let barcode: BarcodeGenerator;
let ele: HTMLElement;
describe('Barcode Control', () => {
describe('Checking the general rendering of bar code', () => {
beforeAll((): void => {
ele = createElement('div', { id: 'barcode1' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
value: 'BARCODE'
});
barcode.appendTo('#barcode1');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('Checking the general rendering of bar code', (done: Function) => {
let value = barcode.value
done();
});
});
describe('Checking background color of the bar code', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode2' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
backgroundColor: 'red',
value: 'BARCODE'
});
barcode.appendTo('#barcode2');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('Checking the general rendering of bar code', (done: Function) => {
let value = barcode.value
done();
});
});
describe('rendering of bar code with widen width', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode3' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '500px', height: '150px',
type: 'Code39',
value: 'BARCODE'
});
barcode.appendTo('#barcode3');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('rendering of bar code with widen width', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking of invalid character', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode4' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '500px', height: '150px',
type: 'Code39',
value: 'BAR~CODE',
});
barcode.appendTo('#barcode4');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking of invalid character', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking the rendering of larger barcode value', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode5' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '300px', height: '150px',
type: 'Code39',
value: 'BARCODEBARCODE',
});
barcode.appendTo('#barcode5');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking the rendering of larger barcode value', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking the rendering of fore color of the display text', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode6' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '300px', height: '150px',
type: 'Code39',
foreColor: 'green',
value: 'BARCODEBARCODE',
});
barcode.appendTo('#barcode6');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking the rendering of fore color of the display text', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking the text property of the display text of the bar code ', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode7' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '300px', height: '150px',
type: 'Code39',
foreColor: 'green',
displayText: { text: 'ABCD' },
value: 'BARCODEBARCODE',
});
barcode.appendTo('#barcode7');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking the text property of the display text of the bar code ', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking the visibility property of the display text of the bar code', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode8' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '300px', height: '150px',
type: 'Code39',
foreColor: 'green',
displayText: { text: 'ABCD', visibility: false },
value: 'BARCODEBARCODE',
});
barcode.appendTo('#barcode8');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking the visibility property of the display text of the bar code', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking the font style property of the display text of the bar code', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode10' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
foreColor: 'green',
displayText: { text: 'ABCD', font: 'Bold' },
value: 'BARCODE',
});
barcode.appendTo('#barcode10');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking the font style property of the display text of the bar code', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking the left margin property of the display text of the bar code', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode11' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
foreColor: 'green',
displayText: { text: 'ABCD', margin: { left: 100 } },
value: 'BARCODE',
});
barcode.appendTo('#barcode11');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking the left margin property of the display text of the bar code', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking the right margin property of the display text of the bar code', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode12' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
foreColor: 'green',
displayText: { text: 'ABCD', margin: { right: 100 } },
value: 'BARCODE',
});
barcode.appendTo('#barcode12');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking the right margin property of the display text of the bar code', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking the top margin property of the display text of the bar code', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode13' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
foreColor: 'green',
displayText: { text: 'ABCD', margin: { top: 50 } },
value: 'BARCODE',
});
barcode.appendTo('#barcode13');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking the top margin property of the display text of the bar code', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking the bottom margin property of the display text of the bar code', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode14' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
foreColor: 'green',
displayText: { text: 'ABCD', margin: { bottom: 50 } },
value: 'BARCODE',
});
barcode.appendTo('#barcode14');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking the bottom margin property of the display text of the bar code', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking left margin of the barcode', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode15' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
margin: { left: 30 },
value: 'BARCODE',
});
barcode.appendTo('#barcode15');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking left margin of the barcode', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking right margin of the barcode', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode16' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
margin: { right: 30 },
value: 'BARCODE',
});
barcode.appendTo('#barcode16');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking left marging of the barcode', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking bottom margin of the barcode', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode17' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
margin: { bottom: 50 },
value: 'BARCODE',
});
barcode.appendTo('#barcode17');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking left marging of the barcode', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking bottom margin of the barcode', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode18' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
margin: { top: 50 },
value: 'BARCODE',
});
barcode.appendTo('#barcode18');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking left marging of the barcode', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking left , right , top , bottom margin', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode19' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
value: 'BARCODE',
margin: { right: 20, left: 20, top: 20, bottom: 20 },
});
barcode.appendTo('#barcode19');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking left , right , top , bottom margin', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking displaytext greater than available width', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode20' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
value: 'BARCODE',
displayText: { text: 'ABCDABCDABCDABCDABCDABCDABCDABCDABCD' }
});
barcode.appendTo('#barcode20');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking left , right , top , bottom margin', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking displaytext with all the display text margin', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode20' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
value: 'BARCODE',
displayText: {
text: 'BARCODEBARCODE',
margin:{top:30,bottom:30,left:30,right:30}
},
});
barcode.appendTo('#barcode20');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking left , right , top , bottom margin', (done: Function) => {
let value = barcode.value
done();
});
});
describe('checking bar code when 100% width is given', () => {
//let barcode: BarcodeGenerator;
//let barcode: BarcodeGenerator;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode20' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Code39',
value: 'BARCODE',
displayText: {
text: 'BARCODEBARCODE',
margin:{top:30,bottom:30,left:30,right:30}
},
});
barcode.appendTo('#barcode20');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking left , right , top , bottom margin', (done: Function) => {
let value = barcode.value
done();
});
});
}); | the_stack |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { registerComponent, Components } from '../../lib/vulcan-lib';
import { userUseMarkdownPostEditor } from '../../lib/collections/users/helpers';
import { editorStyles, ckEditorStyles } from '../../themes/stylePiping'
import withUser from '../common/withUser';
import classNames from 'classnames';
import Input from '@material-ui/core/Input';
import { getLSHandlers } from '../async/localStorageHandlers'
import { EditorState, convertFromRaw, convertToRaw } from 'draft-js'
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import withErrorBoundary from '../common/withErrorBoundary';
import { editableCollectionsFieldOptions } from '../../lib/editor/make_editable';
import { userHasCkCollaboration, userCanCreateCommitMessages } from '../../lib/betas';
import * as _ from 'underscore';
import { isClient } from '../../lib/executionEnvironment';
import { forumTypeSetting } from '../../lib/instanceSettings';
import FormLabel from '@material-ui/core/FormLabel';
const postEditorHeight = 250;
const questionEditorHeight = 150;
const commentEditorHeight = 100;
const postEditorHeightRows = 15;
const commentEditorHeightRows = 5;
const styles = (theme: ThemeType): JssStyles => ({
label: {
display: 'block',
fontSize: 10,
marginBottom: 6
},
editor: {
position: 'relative',
},
markdownEditor: {
fontFamily: "inherit",
fontSize: "inherit",
},
postBodyStyles: {
...editorStyles(theme),
cursor: "text",
padding: 0,
'& li .public-DraftStyleDefault-block': {
margin: 0
}
},
answerStyles: {
...editorStyles(theme),
cursor: "text",
maxWidth:620,
'& li .public-DraftStyleDefault-block': {
margin: 0
}
},
commentBodyStyles: {
...editorStyles(theme),
cursor: "text",
marginTop: 0,
marginBottom: 0,
padding: 0,
pointerEvents: 'auto'
},
ckEditorStyles: {
...ckEditorStyles(theme),
},
questionWidth: {
width: 640,
[theme.breakpoints.down('sm')]: {
width: '100%'
}
},
postEditorHeight: {
minHeight: postEditorHeight,
'& .ck.ck-content': {
minHeight: postEditorHeight,
},
'& .ck-sidebar .ck-content': {
minHeight: "unset"
}
},
commentEditorHeight: {
minHeight: commentEditorHeight,
'& .ck.ck-content': {
minHeight: commentEditorHeight,
}
},
questionEditorHeight: {
minHeight: questionEditorHeight,
'& .ck.ck-content': {
minHeight: questionEditorHeight,
}
},
maxHeight: {
maxHeight: "calc(100vh - 450px)",
overflowY: "scroll"
},
clickHereColor: {
color: theme.palette.primary.main
},
select: {
marginRight: theme.spacing.unit*1.5
},
placeholder: {
position: "absolute",
top: 0,
color: theme.palette.grey[500],
// Dark Magick
// https://giphy.com/gifs/psychedelic-art-phazed-12GGadpt5aIUQE
// Without this code, there's a weird thing where if you try to click the placeholder text, instead of focusing on the editor element, it... doesn't. This is overriding something habryka did to make spoiler tags work. We discussed this for awhile and this seemed like the best option.
pointerEvents: "none",
"& *": {
pointerEvents: "none",
}
},
placeholderCollaborationSpacing: {
top: 60
},
changeDescriptionRow: {
display: "flex",
alignItems: "center",
},
changeDescriptionLabel: {
marginLeft: 8,
marginRight: 8,
...theme.typography.commentStyle,
color: theme.palette.text.normal,
},
changeDescriptionInput: {
flexGrow: 1,
},
markdownImgErrText: {
margin: `${theme.spacing.unit * 3}px 0`,
color: theme.palette.error.main,
},
lastEditedWarning: {
color: theme.palette.error.main,
},
})
const autosaveInterval = 3000; //milliseconds
const checkImgErrsInterval = 500; //milliseconds
const ckEditorName = forumTypeSetting.get() === 'EAForum' ? 'EA Forum Docs' : 'LessWrong Docs'
const editorTypeToDisplay = {
html: {name: 'HTML', postfix: '[Admin Only]'},
ckEditorMarkup: {name: ckEditorName, postfix: '[Beta]'},
markdown: {name: 'Markdown'},
draftJS: {name: 'Draft-JS'},
}
const nonAdminEditors = ['ckEditorMarkup', 'markdown', 'draftJS']
const adminEditors = ['html', 'ckEditorMarkup', 'markdown', 'draftJS']
interface EditorFormComponentProps extends WithUserProps, WithStylesProps {
form: any,
formType: any,
formProps: any,
document: any,
name: any,
fieldName: any,
value: any,
hintText: string,
placeholder: string,
label: string,
commentStyles: boolean,
collectionName: string
}
interface EditorFormComponentState {
editorOverride: any,
ckEditorLoaded: any,
updateType: string,
commitMessage: string,
ckEditorReference: any,
loading: boolean,
draftJSValue: any,
ckEditorValue: any,
markdownValue: any,
htmlValue: any,
markdownImgErrs: boolean
}
class EditorFormComponent extends Component<EditorFormComponentProps,EditorFormComponentState> {
hasUnsavedData: boolean
throttledSaveBackup: any
throttledSetCkEditor: any
debouncedCheckMarkdownImgErrs: any
unloadEventListener: any
ckEditor: any
constructor(props: EditorFormComponentProps) {
super(props)
const editorType = this.getCurrentEditorType()
this.state = {
editorOverride: null,
ckEditorLoaded: null,
updateType: 'minor',
commitMessage: "",
ckEditorReference: null,
loading: true,
...this.getEditorStatesFromType(editorType),
markdownImgErrs: false
}
this.hasUnsavedData = false;
this.throttledSaveBackup = _.throttle(this.saveBackup, autosaveInterval, {leading:false});
this.throttledSetCkEditor = _.throttle(this.setCkEditor, autosaveInterval);
this.debouncedCheckMarkdownImgErrs = _.debounce(this.checkMarkdownImgErrs, checkImgErrsInterval);
}
async componentDidMount() {
const { form } = this.props
this.context.addToSubmitForm(this.submitData);
this.context.addToSuccessForm((result) => {
this.resetEditor();
return result;
});
if (isClient && window) {
this.unloadEventListener = (ev) => {
if (this.hasUnsavedData) {
ev.preventDefault();
ev.returnValue = 'Are you sure you want to close?';
return ev.returnValue
}
}
window.addEventListener("beforeunload", this.unloadEventListener );
}
let EditorModule = await (form?.commentEditor ? import('../async/CKCommentEditor') : import('../async/CKPostEditor'))
const Editor = EditorModule.default
this.ckEditor = Editor
this.setState({ckEditorLoaded: true})
if (isClient) {
this.restoreFromLocalStorage();
this.setState({loading: false})
}
}
getEditorStatesFromType = (editorType: string, contents?: any) => {
const { document, fieldName, value } = this.props
const { editorOverride } = this.state || {} // Provide default value, since we can call this before state is initialized
// if contents are manually specified, use those:
const newValue = contents || value
// Initialize the editor to whatever the canonicalContent is
if (newValue?.originalContents?.data
&& !editorOverride
&& editorType === newValue.originalContents.type)
{
return {
draftJSValue: editorType === "draftJS" ? this.initializeDraftJS(newValue.originalContents.data) : null,
markdownValue: editorType === "markdown" ? newValue.originalContents.data : null,
htmlValue: editorType === "html" ? newValue.originalContents.data : null,
ckEditorValue: editorType === "ckEditorMarkup" ? newValue.originalContents.data : null
}
}
// Otherwise, just set it to the value of the document
const { draftJS, html, markdown, ckEditorMarkup } = document[fieldName] || {}
return {
draftJSValue: editorType === "draftJS" ? this.initializeDraftJS(draftJS) : null,
markdownValue: editorType === "markdown" ? markdown : null,
htmlValue: editorType === "html" ? html : null,
ckEditorValue: editorType === "ckEditorMarkup" ? ckEditorMarkup : null
}
}
getEditorStatesFromLocalStorage = (editorType: string): any => {
const { document, name } = this.props;
const savedState = this.getStorageHandlers().get({doc: document, name, prefix:this.getLSKeyPrefix(editorType)})
if (!savedState) return null;
if (editorType === "draftJS") {
try {
// eslint-disable-next-line no-console
console.log("Restoring saved document state: ", savedState);
const contentState = convertFromRaw(savedState)
if (contentState.hasText()) {
return {
draftJSValue: EditorState.createWithContent(contentState)
};
} else {
// eslint-disable-next-line no-console
console.log("Not restoring empty document state: ", contentState)
}
} catch(e) {
// eslint-disable-next-line no-console
console.error(e)
}
return null;
} else {
return {
draftJSValue: editorType === "draftJS" ? savedState : null,
markdownValue: editorType === "markdown" ? savedState : null,
htmlValue: editorType === "html" ? savedState : null,
ckEditorValue: editorType === "ckEditorMarkup" ? savedState : null
}
}
}
restoreFromLocalStorage = () => {
const savedState = this.getEditorStatesFromLocalStorage(this.getCurrentEditorType());
if (savedState) {
this.setState(savedState);
}
}
isEmpty = (): boolean => {
switch(this.getCurrentEditorType()) {
case "draftJS": {
const draftJSValue = this.state.draftJSValue;
if (!draftJSValue) return true;
const draftJScontent = draftJSValue.getCurrentContent()
return !draftJScontent.hasText();
}
case "markdown": {
const markdownValue = this.state.markdownValue;
if (!markdownValue) return true;
return markdownValue.trim() === "";
}
case "html": {
const htmlValue = this.state.htmlValue;
if (!htmlValue) return true;
return htmlValue.trim() === "";
}
case "ckEditorMarkup": {
const ckEditorValue = this.state.ckEditorValue;
if (!ckEditorValue) return true;
return ckEditorValue.trim() === "";
}
default:
throw new Error("Invalid editor type");
}
}
getStorageHandlers = () => {
const { fieldName, form } = this.props
const collectionName = form.collectionName;
const getLocalStorageId = editableCollectionsFieldOptions[collectionName][fieldName].getLocalStorageId;
return getLSHandlers(getLocalStorageId)
}
initializeDraftJS = (draftJS) => {
const { document } = this.props
// Initialize from the database state
if (draftJS) {
try {
return EditorState.createWithContent(convertFromRaw(draftJS));
} catch(e) {
// eslint-disable-next-line no-console
console.error("Invalid document content", document);
}
}
// And lastly, if the field is empty, create an empty draftJS object
return EditorState.createEmpty();
}
submitData = (submission) => {
const { fieldName } = this.props
let data: any = null
const { draftJSValue, markdownValue, htmlValue, updateType, commitMessage, ckEditorReference } = this.state
const type = this.getCurrentEditorType()
switch(type) {
case "draftJS":
const draftJS = draftJSValue.getCurrentContent()
data = draftJS.hasText() ? convertToRaw(draftJS) : null
break
case "markdown":
data = markdownValue
break
case "html":
data = htmlValue
break
case "ckEditorMarkup":
if (!ckEditorReference) throw Error("Can't submit ckEditorMarkup without attached CK Editor")
if (!this.isDocumentCollaborative()) {
this.context.addToSuccessForm((s) => {
this.state.ckEditorReference.setData('')
})
}
data = ckEditorReference.getData()
break
default:
// eslint-disable-next-line no-console
console.error(`Unrecognized editor type: ${type}`);
data = "";
break;
}
return {
...submission,
[fieldName]: data ? {
originalContents: {type, data},
commitMessage, updateType,
} : undefined
}
}
resetEditor = () => {
const { name, document } = this.props;
// On Form submit, create a new empty editable
this.getStorageHandlers().reset({doc: document, name, prefix:this.getLSKeyPrefix()})
this.setState({
draftJSValue: EditorState.createEmpty(),
htmlValue: null,
markdownValue: null,
editorOverride: null,
ckEditorValue: null
});
}
componentWillUnmount() {
if (this.unloadEventListener) {
window.removeEventListener("beforeunload", this.unloadEventListener);
}
}
setEditorType = (editorType) => {
if (!editorType) throw new Error("Missing argument to setEditorType: editorType");
const targetEditorType = editorType;
this.setState({
editorOverride: targetEditorType,
...this.getEditorStatesFromType(targetEditorType)
})
this.restoreFromLocalStorage();
}
setDraftJS = (value) => { // Takes in an editorstate
const { draftJSValue } = this.state
const currentContent = draftJSValue.getCurrentContent()
const newContent = value.getCurrentContent()
this.setState({draftJSValue: value})
if (currentContent !== newContent) {
this.afterChange();
}
}
setHtml = (value) => {
if (this.state.htmlValue !== value) {
this.setState({htmlValue: value});
this.afterChange();
}
}
setMarkdown = (value) => {
if (this.state.markdownValue !== value) {
this.setState({markdownValue: value})
this.debouncedCheckMarkdownImgErrs()
this.afterChange();
}
}
setCkEditor = (editor) => {
const newContent = editor.getData()
if (this.state.ckEditorValue !== newContent) {
this.setState({ckEditorValue: newContent})
this.afterChange();
}
}
afterChange = () => {
this.hasUnsavedData = true;
this.throttledSaveBackup();
}
saveBackup = () => {
const { document, name } = this.props;
if (this.isEmpty()) {
this.getStorageHandlers().reset({
doc: document,
name,
prefix: this.getLSKeyPrefix()
});
this.hasUnsavedData = false;
} else {
const serialized = this.editorContentsToJson();
const success = this.getStorageHandlers().set({
state: serialized,
doc: document,
name,
prefix: this.getLSKeyPrefix()
});
if (success) {
this.hasUnsavedData = false;
}
}
}
// Take the editor contents (whichever editor you're using), and return
// something JSON (ie, a JSON object or a string) which represents the
// content and can be saved to localStorage.
editorContentsToJson = () => {
switch(this.getCurrentEditorType()) {
case "draftJS":
const draftJScontent = this.state.draftJSValue.getCurrentContent()
return convertToRaw(draftJScontent);
case "markdown":
return this.state.markdownValue;
case "html":
return this.state.htmlValue;
case "ckEditorMarkup":
return this.state.ckEditorValue;
}
}
// Get an editor-type-specific prefix to use on localStorage keys, to prevent
// drafts written with different editors from having conflicting names.
getLSKeyPrefix = (editorType?: string): string => {
switch(editorType || this.getCurrentEditorType()) {
default:
case "draftJS": return "";
case "markdown": return "md_";
case "html": return "html_";
case "ckEditorMarkup": return "ckeditor_";
}
}
renderEditorWarning = () => {
const { currentUser, classes } = this.props
const type = this.getInitialEditorType();
const defaultType = this.getUserDefaultEditor(currentUser)
return <div>
<Components.Typography variant="body2" className={classes.lastEditedWarning}>
This document was last edited in {editorTypeToDisplay[type].name} format. Showing the{' '}
{editorTypeToDisplay[this.getCurrentEditorType()].name} editor.{' '}
<a
className={classes.clickHereColor}
onClick={() => this.setEditorType(defaultType)}
>
Click here
</a>
{' '}to switch to the {editorTypeToDisplay[defaultType].name} editor (your default editor).
</Components.Typography>
<br/>
</div>
}
getCurrentEditorType = () => {
// Tags can only be edited via CKEditor
if (this.props.collectionName === 'Tags') return "ckEditorMarkup"
const { editorOverride } = this.state || {} // Provide default since we can call this function before we initialize state
// If there is an override, return that
if (editorOverride)
return editorOverride;
return this.getInitialEditorType();
}
getInitialEditorType = () => {
const { document, currentUser, fieldName, value } = this.props
// Check whether we are directly passed a value in the form context, with a type (as a default value for example)
if (value?.originalContents?.type) {
return value.originalContents.type
}
// Next check whether the document came with a field value with a type specified
const originalType = document?.[fieldName]?.originalContents?.type
if (originalType) return originalType;
// Finally pick the editor type from the user's config
return this.getUserDefaultEditor(currentUser)
}
getUserDefaultEditor = (user) => {
if (userUseMarkdownPostEditor(user)) return "markdown"
if (user?.reenableDraftJs) return "draftJS"
return "ckEditorMarkup"
}
handleUpdateTypeSelect = (e) => {
this.setState({ updateType: e.target.value })
}
renderUpdateTypeSelect = () => {
const { currentUser, formType, classes, form } = this.props
if (form.hideControls) return null
if (!currentUser || !currentUser.isAdmin || formType !== "edit") { return null }
return <Select
value={this.state.updateType}
onChange={this.handleUpdateTypeSelect}
className={classes.select}
disableUnderline
>
<MenuItem value={'major'}>Major Update</MenuItem>
<MenuItem value={'minor'}>Minor Update</MenuItem>
<MenuItem value={'patch'}>Patch</MenuItem>
</Select>
}
renderCommitMessageInput = () => {
const { currentUser, formType, fieldName, form, classes } = this.props
const collectionName = form.collectionName;
if (!currentUser || (!userCanCreateCommitMessages(currentUser) && collectionName !== "Tags") || formType !== "edit") { return null }
const fieldHasCommitMessages = editableCollectionsFieldOptions[collectionName][fieldName].revisionsHaveCommitMessages;
if (!fieldHasCommitMessages) return null;
if (form.hideControls) return null
return <div className={classes.changeDescriptionRow}>
<span className={classes.changeDescriptionLabel}>Edit summary (Briefly describe your changes):{" "}</span>
<Input
className={classes.changeDescriptionInput}
value={this.state.commitMessage}
onChange={(ev) => {
this.setState({ commitMessage: ev.target.value });
}}
/>
</div>
}
renderEditorTypeSelect = () => {
const { collectionName, currentUser, classes, form } = this.props
const { LWTooltip } = Components
if (form.hideControls) return null
if (!currentUser?.reenableDraftJs && !currentUser?.isAdmin) return null
const editors = currentUser?.isAdmin ? adminEditors : nonAdminEditors
const tooltip = collectionName === 'Tags' ? `Tags can only be edited in the ${ckEditorName} editor` : "Warning! Changing format will erase your content"
return (
<LWTooltip title={tooltip} placement="left">
<Select
className={classes.select}
value={this.getCurrentEditorType()}
onChange={(e) => this.setEditorType(e.target.value)}
disableUnderline
disabled={collectionName === 'Tags'}
>
{editors.map((editorType, i) =>
<MenuItem value={editorType} key={i}>
{editorTypeToDisplay[editorType].name} {editorTypeToDisplay[editorType].postfix}
</MenuItem>
)}
</Select>
</LWTooltip>
)
}
getBodyStyles = (): {className: string, contentType: "comment"|"answer"|"post"} => {
const { classes, commentStyles, document } = this.props
if (commentStyles && document.answer) {
return {
className: classes.answerStyles,
contentType: "answer",
}
}
if (commentStyles) {
return {
className: classes.commentBodyStyles,
contentType: "comment",
}
}
return {
className: classes.postBodyStyles,
contentType: "post",
}
}
renderEditorComponent = (currentEditorType) => {
switch (currentEditorType) {
case "ckEditorMarkup":
return this.renderCkEditor()
case "draftJS":
return this.renderDraftJSEditor()
case "markdown":
return this.renderPlaintextEditor(currentEditorType)
case "html":
return this.renderPlaintextEditor(currentEditorType)
}
}
renderPlaceholder = (showPlaceholder, collaboration) => {
const { classes, formProps, hintText, placeholder } = this.props
const {className, contentType} = this.getBodyStyles();
if (showPlaceholder) {
return <Components.ContentStyles contentType={contentType} className={classNames(className, classes.placeholder, {[classes.placeholderCollaborationSpacing]: collaboration})}>
{ formProps?.editorHintText || hintText || placeholder }
</Components.ContentStyles>
}
}
isDocumentCollaborative = () => {
const { document, fieldName, currentUser } = this.props
return userHasCkCollaboration(currentUser) && document?._id && document?.shareWithUsers && (fieldName === "contents")
}
renderCkEditor = () => {
const { ckEditorValue, ckEditorReference } = this.state
const { document, currentUser, formType, classes } = this.props
const { Loading } = Components
const CKEditor = this.ckEditor
const value = ckEditorValue || ckEditorReference?.getData()
if (!this.state.ckEditorLoaded || !CKEditor) {
return <Loading />
} else {
const editorProps = {
data: value,
documentId: document?._id,
formType: formType,
userId: currentUser?._id,
onChange: (event, editor) => this.throttledSetCkEditor(editor),
onInit: editor => this.setState({ckEditorReference: editor})
}
// if document is shared with at least one user, it will render the collaborative ckEditor (note: this costs a small amount of money per document)
//
// requires _id because before the draft is saved, ckEditor loses track of what you were writing when turning collaborate on and off (and, meanwhile, you can't actually link people to a shared draft before it's saved anyhow)
// TODO: figure out a better solution to this problem.
const collaboration = this.isDocumentCollaborative()
return <div className={classNames(this.getHeightClass(), this.getMaxHeightClass(), classes.ckEditorStyles)}>
{ this.renderPlaceholder(!value, collaboration)}
{ collaboration ?
<CKEditor key="ck-collaborate" { ...editorProps } collaboration />
:
<CKEditor key="ck-default" { ...editorProps } />}
</div>
}
}
checkMarkdownImgErrs = () => {
const { markdownValue } = this.state
// match markdown image tags of the form
// 
// 
const httpImageRE = /!\[[^\]]*?\]\(http:/g
this.setState({
markdownImgErrs: httpImageRE.test(markdownValue)
})
}
renderPlaintextEditor = (editorType) => {
const { markdownValue, htmlValue, markdownImgErrs } = this.state
const { classes, document, form: { commentStyles } } = this.props
const value = (editorType === "html" ? htmlValue : markdownValue) || ""
const {className, contentType} = this.getBodyStyles();
return <div>
{ this.renderPlaceholder(!value, false) }
<Components.ContentStyles contentType={contentType}>
<Input
className={classNames(classes.markdownEditor, className, {[classes.questionWidth]: document.question})}
value={value}
onChange={(ev) => {
if (editorType === "html")
this.setHtml(ev.target.value);
else
this.setMarkdown(ev.target.value);
}}
multiline={true}
rows={commentStyles ? commentEditorHeightRows : postEditorHeightRows}
rowsMax={99999}
fullWidth={true}
disableUnderline={true}
/>
</Components.ContentStyles>
{markdownImgErrs && editorType === 'markdown' && <Components.Typography component='aside' variant='body2' className={classes.markdownImgErrText}>
Your Markdown contains at least one link to an image served over an insecure HTTP{' '}
connection. You should update all links to images so that they are served over a{' '}
secure HTTPS connection (i.e. the links should start with <em>https://</em>).
</Components.Typography>}
</div>
}
renderDraftJSEditor = () => {
const { draftJSValue } = this.state
const { document, form, classes } = this.props
const showPlaceholder = !(draftJSValue?.getCurrentContent && draftJSValue.getCurrentContent().hasText())
const {className, contentType} = this.getBodyStyles();
return <div>
{ this.renderPlaceholder(showPlaceholder, false) }
{draftJSValue && <Components.ContentStyles contentType={contentType}>
<Components.DraftJSEditor
editorState={draftJSValue}
onChange={this.setDraftJS}
commentEditor={form?.commentEditor}
className={classNames(className, this.getHeightClass(), this.getMaxHeightClass(), {[classes.questionWidth]: document.question})}
/>
</Components.ContentStyles>}
</div>
}
getMaxHeightClass = () => {
const { classes, formProps } = this.props
return formProps?.maxHeight ? classes.maxHeight : null
}
getHeightClass = () => {
const { document, classes, form: { commentStyles } } = this.props
if (commentStyles) {
return classes.commentEditorHeight
} else if (document.question) {
return classes.questionEditorHeight;
} else {
return classes.postEditorHeight
}
}
render() {
const { editorOverride, loading } = this.state
const { document, currentUser, formType, classes, collectionName, label } = this.props
const { Loading, ContentStyles } = Components
const currentEditorType = this.getCurrentEditorType()
const {className, contentType} = this.getBodyStyles();
if (!document) return null;
const editorWarning =
!editorOverride
&& formType !== "new"
&& collectionName !== 'Tags'
&& this.getInitialEditorType() !== this.getUserDefaultEditor(currentUser)
&& this.renderEditorWarning()
return <div>
{ label && <FormLabel className={classes.label}>{label}</FormLabel>}
{ editorWarning }
<ContentStyles contentType={contentType} className={classNames(classes.editor, className)}>
{ loading ? <Loading/> : this.renderEditorComponent(currentEditorType) }
{ this.renderUpdateTypeSelect() }
{ this.renderEditorTypeSelect() }
</ContentStyles>
{ this.renderCommitMessageInput() }
</div>
}
};
(EditorFormComponent as any).contextTypes = {
addToSubmitForm: PropTypes.func,
addToSuccessForm: PropTypes.func
};
export const EditorFormComponentComponent = registerComponent(
'EditorFormComponent', EditorFormComponent, {
styles,
hocs: [withUser, withErrorBoundary]
}
);
declare global {
interface ComponentTypes {
EditorFormComponent: typeof EditorFormComponentComponent
}
} | the_stack |
'use strict';
import * as assert from 'assert';
import { Deferred } from 'ts-deferred';
import * as component from '../common/component';
import { Database, DataStore, MetricData, MetricDataRecord, MetricType,
TrialJobEvent, TrialJobEventRecord, TrialJobInfo, HyperParameterFormat,
ExportedDataFormat } from '../common/datastore';
import { NNIError } from '../common/errors';
import { getExperimentId, isNewExperiment } from '../common/experimentStartupInfo';
import { getLogger, Logger } from '../common/log';
import { ExperimentProfile, TrialJobStatistics } from '../common/manager';
import { TrialJobDetail, TrialJobStatus } from '../common/trainingService';
import { getDefaultDatabaseDir, mkDirP } from '../common/utils';
class NNIDataStore implements DataStore {
private db: Database = component.get(Database);
private log: Logger = getLogger();
private initTask!: Deferred<void>;
private multiPhase: boolean | undefined;
public init(): Promise<void> {
if (this.initTask !== undefined) {
return this.initTask.promise;
}
this.initTask = new Deferred<void>();
// TODO support specify database dir
const databaseDir: string = getDefaultDatabaseDir();
if(isNewExperiment()) {
mkDirP(databaseDir).then(() => {
this.db.init(true, databaseDir).then(() => {
this.log.info('Datastore initialization done');
this.initTask.resolve();
}).catch((err: Error) => {
this.initTask.reject(err);
});
}).catch((err: Error) => {
this.initTask.reject(err);
});
} else {
this.db.init(false, databaseDir).then(() => {
this.log.info('Datastore initialization done');
this.initTask.resolve();
}).catch((err: Error) => {
this.initTask.reject(err);
});
}
return this.initTask.promise;
}
public async close(): Promise<void> {
await this.db.close();
}
public async storeExperimentProfile(experimentProfile: ExperimentProfile): Promise<void> {
try {
await this.db.storeExperimentProfile(experimentProfile);
} catch (err) {
throw NNIError.FromError(err, 'Datastore error: ');
}
}
public getExperimentProfile(experimentId: string): Promise<ExperimentProfile> {
return this.db.queryLatestExperimentProfile(experimentId);
}
public storeTrialJobEvent(
event: TrialJobEvent, trialJobId: string, hyperParameter?: string, jobDetail?: TrialJobDetail): Promise<void> {
this.log.debug(`storeTrialJobEvent: event: ${event}, data: ${hyperParameter}, jobDetail: ${JSON.stringify(jobDetail)}`);
// Use the timestamp in jobDetail as TrialJobEvent timestamp for different events
let timestamp: number | undefined;
if (event === 'WAITING' && jobDetail) {
timestamp = jobDetail.submitTime;
} else if (event === 'RUNNING' && jobDetail) {
timestamp = jobDetail.startTime;
} else if (['EARLY_STOPPED', 'SUCCEEDED', 'FAILED', 'USER_CANCELED', 'SYS_CANCELED'].includes(event) && jobDetail) {
timestamp = jobDetail.endTime;
}
// Use current time as timestamp if timestamp is not assigned from jobDetail
if (timestamp === undefined) {
timestamp = Date.now();
}
return this.db.storeTrialJobEvent(event, trialJobId, timestamp, hyperParameter, jobDetail).catch(
(err: Error) => {
throw NNIError.FromError(err, 'Datastore error: ');
}
);
}
public async getTrialJobStatistics(): Promise<any[]> {
const result: TrialJobStatistics[] = [];
const jobs: TrialJobInfo[] = await this.listTrialJobs();
const map: Map<TrialJobStatus, number> = new Map();
jobs.forEach((value: TrialJobInfo) => {
let n: number|undefined = map.get(value.status);
if (!n) {
n = 0;
}
map.set(value.status, n + 1);
});
map.forEach((value: number, key: TrialJobStatus) => {
const statistics: TrialJobStatistics = {
trialJobStatus: key,
trialJobNumber: value
};
result.push(statistics);
});
return result;
}
public listTrialJobs(status?: TrialJobStatus): Promise<TrialJobInfo[]> {
return this.queryTrialJobs(status);
}
public async getTrialJob(trialJobId: string): Promise<TrialJobInfo> {
const trialJobs: TrialJobInfo[] = await this.queryTrialJobs(undefined, trialJobId);
assert(trialJobs.length <= 1);
return trialJobs[0];
}
public async storeMetricData(trialJobId: string, data: string): Promise<void> {
const metrics: MetricData = JSON.parse(data);
// REQUEST_PARAMETER is used to request new parameters for multiphase trial job,
// it is not metrics, so it is skipped here.
if (metrics.type === 'REQUEST_PARAMETER') {
return;
}
assert(trialJobId === metrics.trial_job_id);
try {
await this.db.storeMetricData(trialJobId, JSON.stringify({
trialJobId: metrics.trial_job_id,
parameterId: metrics.parameter_id,
type: metrics.type,
sequence: metrics.sequence,
data: metrics.value,
timestamp: Date.now()
}));
} catch (err) {
throw NNIError.FromError(err, 'Datastore error');
}
}
public getMetricData(trialJobId?: string, metricType?: MetricType): Promise<MetricDataRecord[]> {
return this.db.queryMetricData(trialJobId, metricType);
}
public async exportTrialHpConfigs(): Promise<string> {
const jobs: TrialJobInfo[] = await this.listTrialJobs();
const exportedData: ExportedDataFormat[] = [];
for (const job of jobs) {
if (job.hyperParameters && job.finalMetricData) {
if (job.hyperParameters.length === 1 && job.finalMetricData.length === 1) {
// optimization for non-multi-phase case
const parameters: HyperParameterFormat = <HyperParameterFormat>JSON.parse(job.hyperParameters[0]);
const oneEntry: ExportedDataFormat = {
parameter: parameters.parameters,
value: JSON.parse(job.finalMetricData[0].data),
id: job.id
};
exportedData.push(oneEntry);
} else {
const paraMap: Map<number, Record<string, any>> = new Map();
const metricMap: Map<number, Record<string, any>> = new Map();
for (const eachPara of job.hyperParameters) {
const parameters: HyperParameterFormat = <HyperParameterFormat>JSON.parse(eachPara);
paraMap.set(parameters.parameter_id, parameters.parameters);
}
for (const eachMetric of job.finalMetricData) {
const value: Record<string, any> = JSON.parse(eachMetric.data);
metricMap.set(Number(eachMetric.parameterId), value);
}
paraMap.forEach((value: Record<string, any>, key: number) => {
const metricValue: Record<string, any> | undefined = metricMap.get(key);
if (metricValue) {
const oneEntry: ExportedDataFormat = {
parameter: value,
value: metricValue,
id: job.id
};
exportedData.push(oneEntry);
}
});
}
}
}
return JSON.stringify(exportedData);
}
public async getImportedData(): Promise<string[]> {
const importedData: string[] = [];
const importDataEvents: TrialJobEventRecord[] = await this.db.queryTrialJobEvent(undefined, 'IMPORT_DATA');
for (const event of importDataEvents) {
if (event.data) {
importedData.push(event.data);
}
}
return importedData;
}
private async queryTrialJobs(status?: TrialJobStatus, trialJobId?: string): Promise<TrialJobInfo[]> {
const result: TrialJobInfo[] = [];
const trialJobEvents: TrialJobEventRecord[] = await this.db.queryTrialJobEvent(trialJobId);
if (trialJobEvents === undefined) {
return result;
}
const map: Map<string, TrialJobInfo> = this.getTrialJobsByReplayEvents(trialJobEvents);
const finalMetricsMap: Map<string, MetricDataRecord[]> = await this.getFinalMetricData(trialJobId);
for (const key of map.keys()) {
const jobInfo: TrialJobInfo | undefined = map.get(key);
if (jobInfo === undefined) {
continue;
}
if (!(status !== undefined && jobInfo.status !== status)) {
if (jobInfo.status === 'SUCCEEDED') {
jobInfo.finalMetricData = finalMetricsMap.get(jobInfo.id);
}
result.push(jobInfo);
}
}
return result;
}
private async getFinalMetricData(trialJobId?: string): Promise<Map<string, MetricDataRecord[]>> {
const map: Map<string, MetricDataRecord[]> = new Map();
const metrics: MetricDataRecord[] = await this.getMetricData(trialJobId, 'FINAL');
const multiPhase: boolean = await this.isMultiPhase();
for (const metric of metrics) {
const existMetrics: MetricDataRecord[] | undefined = map.get(metric.trialJobId);
if (existMetrics !== undefined) {
if (!multiPhase) {
this.log.error(`Found multiple FINAL results for trial job ${trialJobId}, metrics: ${JSON.stringify(metrics)}`);
} else {
existMetrics.push(metric);
}
} else {
map.set(metric.trialJobId, [metric]);
}
}
return map;
}
private async isMultiPhase(): Promise<boolean> {
if (this.multiPhase === undefined) {
const expProfile: ExperimentProfile = await this.getExperimentProfile(getExperimentId());
if (expProfile !== undefined) {
this.multiPhase = expProfile.params.multiPhase;
} else {
return false;
}
}
if (this.multiPhase !== undefined) {
return this.multiPhase;
} else {
return false;
}
}
private getJobStatusByLatestEvent(oldStatus: TrialJobStatus, event: TrialJobEvent): TrialJobStatus {
switch (event) {
case 'USER_TO_CANCEL':
return 'USER_CANCELED';
case 'ADD_CUSTOMIZED':
return 'WAITING';
case 'ADD_HYPERPARAMETER':
return oldStatus;
default:
}
return <TrialJobStatus>event;
}
private parseHyperParameter(hParamStr: string): any {
let hParam: any;
try {
hParam = JSON.parse(hParamStr);
return hParam;
} catch (err) {
this.log.error(`Hyper parameter needs to be in json format: ${hParamStr}`);
return undefined;
}
}
private getTrialJobsByReplayEvents(trialJobEvents: TrialJobEventRecord[]): Map<string, TrialJobInfo> {
this.log.debug('getTrialJobsByReplayEvents begin');
const map: Map<string, TrialJobInfo> = new Map();
const hParamIdMap: Map<string, Set<number>> = new Map();
// assume data is stored by time ASC order
for (const record of trialJobEvents) {
let jobInfo: TrialJobInfo | undefined;
if (record.trialJobId === undefined || record.trialJobId.length < 1) {
continue;
}
if (map.has(record.trialJobId)) {
jobInfo = map.get(record.trialJobId);
} else {
jobInfo = {
id: record.trialJobId,
status: this.getJobStatusByLatestEvent('UNKNOWN', record.event),
hyperParameters: []
};
}
if (!jobInfo) {
throw new Error('Empty JobInfo');
}
/* eslint-disable no-fallthrough */
switch (record.event) {
case 'RUNNING':
if (record.timestamp !== undefined) {
jobInfo.startTime = record.timestamp;
}
case 'WAITING':
if (record.logPath !== undefined) {
jobInfo.logPath = record.logPath;
}
// Initially assign WAITING timestamp as job's start time,
// If there is RUNNING state event, it will be updated as RUNNING state timestamp
if (jobInfo.startTime === undefined && record.timestamp !== undefined) {
jobInfo.startTime = record.timestamp;
}
break;
case 'SUCCEEDED':
case 'FAILED':
case 'USER_CANCELED':
case 'SYS_CANCELED':
case 'EARLY_STOPPED':
if (record.logPath !== undefined) {
jobInfo.logPath = record.logPath;
}
jobInfo.endTime = record.timestamp;
if (jobInfo.startTime === undefined && record.timestamp !== undefined) {
jobInfo.startTime = record.timestamp;
}
default:
}
/* eslint-enable no-fallthrough */
jobInfo.status = this.getJobStatusByLatestEvent(jobInfo.status, record.event);
if (record.data !== undefined && record.data.trim().length > 0) {
const newHParam: any = this.parseHyperParameter(record.data);
if (newHParam !== undefined) {
if (jobInfo.hyperParameters !== undefined) {
let hParamIds: Set<number> | undefined = hParamIdMap.get(jobInfo.id);
if (hParamIds === undefined) {
hParamIds = new Set();
}
if (!hParamIds.has(newHParam.parameter_index)) {
jobInfo.hyperParameters.push(JSON.stringify(newHParam));
hParamIds.add(newHParam.parameter_index);
hParamIdMap.set(jobInfo.id, hParamIds);
}
} else {
assert(false, 'jobInfo.hyperParameters is undefined');
}
}
}
if (record.sequenceId !== undefined && jobInfo.sequenceId === undefined) {
jobInfo.sequenceId = record.sequenceId;
}
map.set(record.trialJobId, jobInfo);
}
this.log.debug('getTrialJobsByReplayEvents done');
return map;
}
}
export { NNIDataStore }; | the_stack |
import { isArray } from '../common/types';
import {
makeStruts,
parseLatex,
Atom,
coalesce,
Box,
Context,
adjustInterAtomSpacing,
DEFAULT_FONT_SIZE,
getMacros,
} from '../core/core';
import { getKeybindingsForCommand } from './keybindings';
import { attachButtonHandlers } from '../editor-mathfield/buttons';
import {
getCaretPoint,
getSharedElement,
releaseSharedElement,
} from '../editor-mathfield/utils';
import type { MathfieldPrivate } from '../editor-mathfield/mathfield-private';
import { typeset } from '../core/typeset';
import { getDefaultRegisters } from '../core/registers';
import { throwIfNotInBrowser } from '../common/capabilities';
import { hashCode } from '../common/hash-code';
import { Stylesheet, inject as injectStylesheet } from '../common/stylesheet';
// @ts-ignore-error
import POPOVER_STYLESHEET from '../../css/popover.less';
// @ts-ignore-error
import CORE_STYLESHEET from '../../css/core.less';
let POPOVER_STYLESHEET_HASH: string | undefined = undefined;
let gPopoverStylesheet: Stylesheet | null = null;
let gCoreStylesheet: Stylesheet | null = null;
// A textual description of a LaTeX command.
// The value can be either a single string, or an array of string
// in order to provide alternatives or additional context.
// In that case, the first string in the array should be appropriate
// to be spoken for accessibility.
export const NOTES = {
'\\text': 'roman text',
'\\textrm': 'roman text',
'\\textnormal': 'roman text',
'\\textit': 'italic text',
'\\textbf': 'bold text',
'\\texttt': 'monospaced text',
'\\textsf': 'sans-serif text',
'\\mathrm': ['roman', '(upright)'],
'\\mathbf': 'bold',
'\\bf': 'bold',
'\\bold': 'bold',
'\\mathit': 'italic',
'\\mathbb': 'blackboard',
'\\mathscr': 'script',
'\\mathtt': ['typewriter', '(monospaced)'],
'\\mathsf': 'sans-serif',
'\\mathcal': 'caligraphic',
'\\frak': ['fraktur', '(gothic)'],
'\\mathfrak': ['fraktur', '(gothic)'],
'\\textcolor': 'text color',
'\\color': 'color',
'\\forall': 'for all',
'\\exists': 'there exists',
'\\nexists': 'there does not exist',
'\\frac': 'fraction',
'\\dfrac': 'display fraction',
'\\cfrac': 'continuous fraction',
'\\tfrac': 'text fraction',
'\\binom': 'binomial coefficient',
'\\dbinom': 'display binomial coefficient',
'\\tbinom': 'text binomial coefficient',
'\\pdiff': 'partial differential',
'\\vec': 'vector',
'\\check': 'caron',
'\\acute': 'acute',
'\\breve': 'breve',
'\\tilde': 'tilde',
'\\dot': 'dot',
'\\hat': ['hat', 'circumflex'],
'\\ddot': 'double dot',
'\\bar': 'bar',
'\\prime': 'prime',
'\\doubleprime': 'double prime',
'\\varnothing': 'empty set',
'\\emptyset': 'empty set',
'\\subseteq': 'subset of or <br>equal to',
'\\supseteq': 'superset of or <br>equal to',
'\\supset': 'superset of',
'\\subset': 'subset of',
'\\partial': 'partial derivative',
'\\bigcup': 'union',
'\\bigcap': 'intersection',
'\\approx': 'approximately equal to',
'\\notin': 'not an element of',
'\\in': ['element of', 'included in'],
'\\infty': 'infinity',
'\\land': 'logical and',
'\\sqrt': 'square root',
'\\prod': 'product',
'\\sum': 'summation',
'\\amalg': ['amalgamation', 'coproduct', 'free product', 'disjoint union'],
'\\cup': 'union with',
'\\cap': 'intersection with',
'\\int': 'integral',
'\\iint': 'surface integral',
'\\oint': 'curve integral',
'\\iiint': 'volume integral',
'\\iff': 'if and only if',
'\\ln': 'natural logarithm',
'\\boldsymbol': 'bold',
'\\setminus': 'set subtraction',
'\\stackrel': 'relation with symbol above',
'\\stackbin': 'operator with symbol above',
'\\underset': 'symbol with annotation below',
'\\overset': 'symbol with annotation above',
'\\hslash': ['h-bar', 'Planck constant'],
'\\gtrsim': 'greater than or <br>similar to',
'\\propto': 'proportional to',
'\\equiv': 'equivalent to',
'\\!': ['negative thin space', '(-3 mu)'],
'\\ ': ['space', '(6 mu)'],
'\\,': ['thin space', '(3 mu)'],
'\\:': ['medium space', '(4 mu)'],
'\\;': ['thick space', '(5 mu)'],
'\\quad': ['1 em space', '(18 mu)'],
'\\qquad': ['2 em space', '(36 mu)'],
'\\enskip': ['½ em space', '(9 mu)'],
'\\mp': 'minus or plus',
'\\pm': 'plus or minus',
'\\Im': 'Imaginary part of',
'\\Re': 'Real part of',
'\\gothicCapitalR': 'Real part of',
'\\gothicCapitalI': 'Imaginary part part of',
'\\differentialD': 'differential d',
'\\aleph': [
'aleph',
'infinite cardinal',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Cardinal_number">Wikipedia <big>›</big></a>',
],
'\\beth': [
'beth',
'beth number',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Beth_number">Wikipedia <big>›</big></a>',
],
'\\gimel': [
'gimel',
'gimel function',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Gimel_function">Wikipedia <big>›</big></a>',
],
'\\O': 'empty set',
'\\N': 'set of <br>natural numbers',
'\\Z': 'set of <br>integers',
'\\Q': 'set of <br>rational numbers',
'\\C': 'set of <br>complex numbers',
'\\R': 'set of <br>real numbers',
'\\P': 'set of <br>prime numbers',
'\\lesseqqgtr': 'less than, equal to or<br> greater than',
'\\gnapprox': 'greater than and <br>not approximately',
'\\lnapprox': 'lesser than and <br>not approximately',
'\\j': 'dotless j',
'\\i': 'dotless i',
'\\cdot': 'centered dot',
'\\lmoustache': 'left moustache',
'\\rmoustache': 'right moustache',
'\\nabla': ['nabla', 'del', 'differential vector operator'],
'\\square': [
'square',
'd’Alembert operator',
'<a target="_blank" href="https://en.wikipedia.org/wiki/D%27Alembert_operator">Wikipedia <big>›</big></a>',
],
'\\blacksquare': [
'black square',
'end of proof',
'tombstone',
'Halmos symbol',
],
'\\Box': 'end of proof',
'\\colon': ['such that', 'ratio'],
'\\coloneq': ['is defined by', 'is assigned'],
'\\Colon': ['is defined by', 'as'],
'\\_': ['underbar', 'underscore'],
'\\ll': 'much less than',
'\\gg': 'much greater than',
'\\doteq': 'approximately equal to',
'\\Doteq': 'approximately equal to',
'\\doteqdot': 'approximately equal to',
'\\cong': ['isomorphism of', '(for algebras, modules...)'],
'\\det': ['determinant of', '(of a matrix)'],
'\\dotplus': 'Cartesian product algebra',
'\\otimes': [
'tensor product',
'(of algebras)',
'Kronecker product',
'(of matrices)',
],
'\\oplus': ['direct sum', '(of modules)'],
'\\lb': 'base-2 logarithm',
'\\lg': 'base-10 logarithm',
'\\wp': [
'Weierstrass P',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Weierstrass%27s_elliptic_functions">Wikipedia <big>›</big></a>',
],
'\\wr': [
'wreath product',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Wreath_product">Wikipedia <big>›</big></a>',
],
'\\top': ['tautology', 'Proposition P is universally true'],
'\\bot': ['contradiction', 'Proposition P is contradictory'],
'\\mid': ['probability', 'of event A given B'],
'\\mho': [
'Siemens',
'electrical conductance in SI unit',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Siemens_(unit)">Wikipedia <big>›</big></a>',
],
'\\Longrightarrow': 'implies',
'\\Longleftrightarrow': 'if, and only if,',
'\\prec': 'precedes',
'\\preceq': 'precedes or is equal to',
'\\succ': 'succeedes',
'\\succeq': 'succeedes or is equal to',
'\\perp': ['is perpendicular to', 'is independent of'],
'\\models': [
'entails',
'double-turnstyle, models',
'is a semantic consequence of',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Double_turnstile">Wikipedia <big>›</big></a>',
],
'\\vdash': [
'satisfies',
'turnstyle, assertion sign',
'syntactic inference',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Turnstile_(symbol)">Wikipedia <big>›</big></a>',
],
'\\implies': ['implies', 'logical consequence'],
'\\impliedby': ['implied by', 'logical consequence'],
'\\surd': ['surd', 'root of', 'checkmark'],
'\\ltimes': [
'semi direct product',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Semidirect_product">Wikipedia <big>›</big></a>',
],
'\\rtimes': [
'semi direct product',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Semidirect_product">Wikipedia <big>›</big></a>',
],
'\\leftthreetimes': [
'semi direct product',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Semidirect_product">Wikipedia <big>›</big></a>',
],
'\\rightthreetimes': [
'semi direct product',
'<a target="_blank" href="https://en.wikipedia.org/wiki/Semidirect_product">Wikipedia <big>›</big></a>',
],
'\\divideontimes': ['divide on times'],
'\\curlywedge': 'nor',
'\\curlyvee': 'nand',
'\\simeq': 'is group isomorphic with',
'\\vartriangleleft': ['is a normal subgroup of', 'is an ideal ring of'],
'\\circ': ['circle', 'ring', 'function composition'],
'\\rlap': ['overlap right', '\\rlap{x}o'],
'\\llap': ['overlap left', 'o\\llap{/}'],
'\\colorbox': ['color box', '\\colorbox{#fbc0bd}{...}'],
'\\ast': ['asterisk', 'reflexive closure (as a superscript)'],
'\\bullet': 'bullet',
'\\lim': 'limit',
};
function getNote(symbol: string): string {
let result = NOTES[symbol] ?? '';
if (isArray(result)) {
result = result.join('<br>');
}
return result;
}
function latexToMarkup(latex: string): string {
const root = new Atom('root', { mode: 'math' });
root.body = typeset(
parseLatex(latex, {
parseMode: 'math',
macros: getMacros(),
registers: getDefaultRegisters(),
})
);
const box = coalesce(
adjustInterAtomSpacing(
new Box(
root.render(
new Context(
{
macros: getMacros(),
registers: getDefaultRegisters(),
smartFence: false,
},
{
fontSize: DEFAULT_FONT_SIZE,
},
'displaystyle'
)
),
{ classes: 'ML__base' }
)
)
);
return makeStruts(box, { classes: 'ML__mathlive' }).toMarkup();
}
export function showPopoverWithLatex(
mf: MathfieldPrivate,
latex: string,
displayArrows: boolean
): void {
if (!latex || latex.length === 0) {
hidePopover(mf);
return;
}
const command = latex;
const commandMarkup = latexToMarkup(latex);
const commandNote = getNote(command);
const keybinding = getKeybindingsForCommand(mf.keybindings, command).join(
'<br>'
);
let template = displayArrows
? '<div class="ML__popover__prev-shortcut" role="button" aria-label="Previous suggestion"><span><span>▲</span></span></div>'
: '';
template += '<span class="ML__popover__content" role="button">';
template += '<div class="ML__popover__command">' + commandMarkup + '</div>';
if (commandNote) {
template += '<div class="ML__popover__note">' + commandNote + '</div>';
}
if (keybinding) {
template += '<div class="ML__popover__shortcut">' + keybinding + '</div>';
}
template += '</span>';
template += displayArrows
? '<div class="ML__popover__next-shortcut" role="button" aria-label="Next suggestion"><span><span>▼</span></span></div>'
: '';
mf.popover = createPopover(mf, template);
let element = mf.popover.querySelectorAll<HTMLElement>(
'.ML__popover__content'
);
if (element && element.length > 0) {
attachButtonHandlers((command) => mf.executeCommand(command), element[0], {
default: ['complete', 'accept-suggestion'],
});
}
element = mf.popover.querySelectorAll('.ML__popover__prev-shortcut');
if (element && element.length > 0) {
attachButtonHandlers(
(command) => mf.executeCommand(command),
element[0],
'previousSuggestion'
);
}
element = mf.popover.querySelectorAll('.ML__popover__next-shortcut');
if (element && element.length > 0) {
attachButtonHandlers(
(command) => mf.executeCommand(command),
element[0],
'nextSuggestion'
);
}
setTimeout(() => {
const caretPoint = getCaretPoint(mf.field!);
if (caretPoint) setPopoverPosition(mf, caretPoint);
if (mf.popover) {
mf.popover.classList.add('is-visible');
mf.popoverVisible = true;
}
}, 32);
}
export function updatePopoverPosition(
mf: MathfieldPrivate,
options?: { deferred: boolean }
): void {
// Check that the mathfield is still valid
// (we're calling ourselves from requestAnimationFrame() and the mathfield
// could have gotten destroyed
if (!mf.element || mf.element.mathfield !== mf) return;
if (!mf.popover || !mf.popoverVisible) return;
// If the popover pane is visible...
if (options?.deferred) {
// Call ourselves again later, typically after the
// rendering/layout of the DOM has been completed
// (don't do it on next frame, it might be too soon)
setTimeout(() => updatePopoverPosition(mf), 100);
return;
}
if (mf.model.at(mf.model.position)?.type !== 'latex') {
hidePopover(mf);
} else {
// ... get the caret position
const caretPoint = getCaretPoint(mf.field!);
if (caretPoint) setPopoverPosition(mf, caretPoint);
}
}
function setPopoverPosition(
mf: MathfieldPrivate,
position: { x: number; y: number; height: number }
): void {
throwIfNotInBrowser();
if (!mf.popover || !mf.popoverVisible) return;
// Get screen width & height (browser compatibility)
const screenHeight =
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
const screenWidth =
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
// Get scrollbar size. This would be 0 in mobile device (also no needed).
const scrollbarWidth =
window.innerWidth - document.documentElement.clientWidth;
const scrollbarHeight =
window.innerHeight - document.documentElement.clientHeight;
const virtualkeyboardHeight = mf.virtualKeyboard!.height;
// Prevent screen overflow horizontal.
if (position.x + mf.popover.offsetWidth / 2 > screenWidth - scrollbarWidth) {
mf.popover.style.left = `${
screenWidth - mf.popover.offsetWidth - scrollbarWidth
}px`;
} else if (position.x - mf.popover.offsetWidth / 2 < 0) {
mf.popover.style.left = '0';
} else {
mf.popover.style.left = `${position.x - mf.popover.offsetWidth / 2}px`;
}
// And position the popover right below or above the caret
if (
position.y + mf.popover.offsetHeight + 5 >
screenHeight - scrollbarHeight - virtualkeyboardHeight
) {
mf.popover.classList.add('ML__popover--reverse-direction');
mf.popover.style.top = `${
position.y - position.height - mf.popover.offsetHeight - 5
}px`;
} else {
mf.popover.classList.remove('ML__popover--reverse-direction');
mf.popover.style.top = `${position.y + 5}px`;
}
}
export function hidePopover(mf: MathfieldPrivate): void {
mf.suggestionIndex = 0;
mf.popoverVisible = false;
if (mf.popover) {
mf.popover.classList.remove('is-visible');
mf.popover.innerHTML = '';
}
}
export function createPopover(mf: MathfieldPrivate, html: string): HTMLElement {
if (mf.popover) {
mf.popover.innerHTML = mf.options.createHTML(html);
return mf.popover;
}
mf.popover = getSharedElement('mathlive-popover-panel');
if (POPOVER_STYLESHEET_HASH === undefined) {
POPOVER_STYLESHEET_HASH = hashCode(POPOVER_STYLESHEET).toString(36);
}
gPopoverStylesheet = injectStylesheet(
null,
POPOVER_STYLESHEET,
POPOVER_STYLESHEET_HASH
);
gCoreStylesheet = injectStylesheet(
null,
CORE_STYLESHEET,
hashCode(CORE_STYLESHEET).toString(36)
);
mf.popover.innerHTML = mf.options.createHTML(html);
return mf.popover;
}
export function disposePopover(mf: MathfieldPrivate): void {
releaseSharedElement(mf.popover);
if (gPopoverStylesheet) gPopoverStylesheet.release();
if (gCoreStylesheet) gCoreStylesheet.release();
delete mf.popover;
} | the_stack |
import { resolveNameBank } from '../../../util';
import itemID from '../../../util/itemID';
import { Plant } from '../../types';
const herbPlants: Plant[] = [
{
level: 9,
plantXp: 0,
checkXp: 11,
harvestXp: 12.5,
name: 'Guam',
aliases: ['guam weed', 'guam'],
inputItems: resolveNameBank({ 'Guam seed': 1 }),
outputCrop: itemID('Grimy guam leaf'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 25,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 14,
plantXp: 0,
checkXp: 13.5,
harvestXp: 15,
name: 'Marrentill',
aliases: ['marrentill weed', 'marrentill'],
inputItems: resolveNameBank({ 'Marrentill seed': 1 }),
outputCrop: itemID('Grimy marrentill'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 28,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 19,
plantXp: 0,
checkXp: 16,
harvestXp: 18,
name: 'Tarromin',
aliases: ['tarromin weed', 'tarromin'],
inputItems: resolveNameBank({ 'Tarromin seed': 1 }),
outputCrop: itemID('Grimy tarromin'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 31,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 26,
plantXp: 0,
checkXp: 21.5,
harvestXp: 24,
name: 'Harralander',
aliases: ['harralander weed', 'harralander'],
inputItems: resolveNameBank({ 'Harralander seed': 1 }),
outputCrop: itemID('Grimy harralander'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 36,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 32,
plantXp: 0,
checkXp: 27,
harvestXp: 30.5,
name: 'Ranarr',
aliases: ['ranarr weed', 'ranarr'],
inputItems: resolveNameBank({ 'Ranarr seed': 1 }),
outputCrop: itemID('Grimy ranarr weed'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 39,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 38,
plantXp: 0,
checkXp: 34,
harvestXp: 38.5,
name: 'Toadflax',
aliases: ['toadflax weed', 'toadflax'],
inputItems: resolveNameBank({ 'Toadflax seed': 1 }),
outputCrop: itemID('Grimy toadflax'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 43,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 44,
plantXp: 0,
checkXp: 43,
harvestXp: 48.5,
name: 'Irit',
aliases: ['irit weed', 'irit'],
inputItems: resolveNameBank({ 'Irit seed': 1 }),
outputCrop: itemID('Grimy irit leaf'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 46,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 50,
plantXp: 0,
checkXp: 54.5,
harvestXp: 61.5,
name: 'Avantoe',
aliases: ['avantoe weed', 'avantoe'],
inputItems: resolveNameBank({ 'Avantoe seed': 1 }),
outputCrop: itemID('Grimy avantoe'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 50,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 56,
plantXp: 0,
checkXp: 69,
harvestXp: 78,
name: 'Kwuarm',
aliases: ['kwuarm weed', 'kwuarm'],
inputItems: resolveNameBank({ 'Kwuarm seed': 1 }),
outputCrop: itemID('Grimy kwuarm'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 54,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 62,
plantXp: 0,
checkXp: 87.5,
harvestXp: 98.5,
name: 'Snapdragon',
aliases: ['snapdragon weed', 'snapdragon'],
inputItems: resolveNameBank({ 'Snapdragon seed': 1 }),
outputCrop: itemID('Grimy snapdragon'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 57,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 67,
plantXp: 0,
checkXp: 106.5,
harvestXp: 120,
name: 'Cadantine',
aliases: ['cadantine weed', 'cadantine'],
inputItems: resolveNameBank({ 'Cadantine seed': 1 }),
outputCrop: itemID('Grimy cadantine'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 60,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 73,
plantXp: 0,
checkXp: 134.5,
harvestXp: 151.5,
name: 'Lantadyme',
aliases: ['lantadyme weed', 'lantadyme'],
inputItems: resolveNameBank({ 'Lantadyme seed': 1 }),
outputCrop: itemID('Grimy lantadyme'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 64,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 79,
plantXp: 0,
checkXp: 170.5,
harvestXp: 192,
name: 'Dwarf weed',
aliases: ['dwarf weed', 'dwarf'],
inputItems: resolveNameBank({ 'Dwarf weed seed': 1 }),
outputCrop: itemID('Grimy dwarf weed'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 67,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
},
{
level: 85,
plantXp: 0,
checkXp: 199.5,
harvestXp: 224.5,
name: 'Torstol',
aliases: ['torstol weed', 'torstol'],
inputItems: resolveNameBank({ 'Torstol seed': 1 }),
outputCrop: itemID('Grimy torstol'),
petChance: 98_364,
seedType: 'herb',
growthTime: 80,
numOfStages: 4,
chance1: 71,
chance99: 80,
chanceOfDeath: 28,
needsChopForHarvest: false,
fixedOutput: false,
givesLogs: false,
givesCrops: true,
defaultNumOfPatches: 4,
canPayFarmer: false,
canCompostPatch: true,
canCompostandPay: false,
// [QP, Patches Gained]
additionalPatchesByQP: [
[1, 1], // Canifs Patches (1)
[10, 2], // Troll Stronghold (1)
[15, 3], // Harmony Island Patch (1)
[31, 4] // Weiss Patch (1)
],
// [Farm Lvl, Patches Gained]
additionalPatchesByFarmLvl: [],
additionalPatchesByFarmGuildAndLvl: [
[65, 1] // Farming Guild Med (1)
],
timePerPatchTravel: 20,
timePerHarvest: 10
}
];
export default herbPlants; | the_stack |
import { Approx } from '@basemaps/test';
import { round } from '@basemaps/test/build/rounding.js';
import o from 'ospec';
import { Point } from '../bounds.js';
import { Epsg } from '../epsg.js';
import { QuadKey } from '../quad.key.js';
import { TileMatrixSet } from '../tile.matrix.set.js';
import { TileMatrixSets } from '../tms/index.js';
import { GoogleTms } from '../tms/google.js';
import { Nztm2000QuadTms, Nztm2000Tms } from '../tms/nztm2000.js';
const TileSize = 256;
const A = 6378137.0;
/** EPSG:3857 origin shift */
const OriginShift = (2 * Math.PI * A) / 2.0;
const InitialResolution = (2 * Math.PI * A) / TileSize;
function getResolution(zoom: number): number {
return InitialResolution / (1 << zoom);
}
function getPixelsFromMeters(tX: number, tY: number, zoom: number): Point {
const res = getResolution(zoom);
const pX = (tX + OriginShift) / res;
const pY = (tY + OriginShift) / res;
return { x: pX, y: pY };
}
o.spec('TileMatrixSet', () => {
o.spec('load', () => {
o('should guess the projection', () => {
o(GoogleTms.projection).equals(Epsg.Google);
});
o('should load all of the zoom levels', () => {
for (let i = 0; i < GoogleTms.def.tileMatrix.length; i++) {
o(GoogleTms.pixelScale(i) > 0).equals(true);
}
});
});
o('extent', () => {
o(GoogleTms.extent.toBbox()).deepEquals([-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892]);
const { lowerCorner, upperCorner } = Nztm2000Tms.def.boundingBox;
o(Nztm2000Tms.extent.toBbox()).deepEquals([274000, 3087000, 3327000, 7173000]);
o(Nztm2000Tms.extent.toBbox()).deepEquals([
lowerCorner[Nztm2000Tms.indexX],
lowerCorner[Nztm2000Tms.indexY],
upperCorner[Nztm2000Tms.indexX],
upperCorner[Nztm2000Tms.indexY],
]);
});
o('should have correct maxZoom', () => {
o(GoogleTms.maxZoom).equals(24);
o(GoogleTms.pixelScale(24) > 0).equals(true);
o(Nztm2000Tms.maxZoom).equals(16);
o(Nztm2000Tms.pixelScale(16) > 0).equals(true);
});
o.spec('pixelScale', () => {
o('should match the old projection logic', () => {
for (let i = 0; i < 25; i++) {
Approx.equal(getResolution(i), GoogleTms.pixelScale(i), `${i}`);
}
});
});
o.spec('sourceToPixels', () => {
o('should match the old projection logic', () => {
for (let i = 0; i < 10; i++) {
const oldP = getPixelsFromMeters(i, i, i);
const newP = GoogleTms.sourceToPixels(i, i, i);
Approx.equal(oldP.x, newP.x, `x_${i}`, 0.1);
Approx.equal(oldP.y, newP.y, `y_${i}`, 0.1);
}
});
});
o.spec('pixelsToSource', () => {
o('should round trip', () => {
for (let i = 3; i < 1000; i += 13) {
const z = i % 20;
const pixels = GoogleTms.sourceToPixels(i, i, z);
const source = GoogleTms.pixelsToSource(pixels.x, pixels.y, z);
Approx.equal(source.x, i, `x${i}_z${z}`, 1e-5);
Approx.equal(source.y, i, `y${i}_z${z}`, 1e-5);
}
});
o(`should pixelsToSource ${Epsg.Google.toEpsgString()}`, () => {
const tileSize = 256;
const googleBound = 20037508.3427892;
for (let i = 0; i < 1; i++) {
const extentPx = tileSize * 2 ** i;
const centerPx = extentPx / 2;
Approx.point(GoogleTms.pixelsToSource(centerPx, centerPx, i), { x: 0, y: 0 }, 'center');
Approx.point(GoogleTms.pixelsToSource(extentPx, centerPx, i), { x: googleBound, y: 0 }, 'extentX');
Approx.point(GoogleTms.pixelsToSource(centerPx, extentPx, i), { x: 0, y: -googleBound });
Approx.point(GoogleTms.pixelsToSource(extentPx, extentPx, i), { x: googleBound, y: -googleBound });
Approx.point(GoogleTms.pixelsToSource(0, centerPx, i), { x: -googleBound, y: 0 });
Approx.point(GoogleTms.pixelsToSource(centerPx, 0, i), { x: 0, y: googleBound });
}
Approx.point(GoogleTms.pixelsToSource(0, 0, 0), { x: -googleBound, y: googleBound }, 'z0:extent:ul');
Approx.point(GoogleTms.pixelsToSource(256, 256, 0), { x: googleBound, y: -googleBound }, 'z0:extent:lr');
});
o(`should pixelsToSource ${Epsg.Nztm2000.toEpsgString()}`, () => {
// Points looked at up in QGIS
Approx.point(Nztm2000Tms.sourceToPixels(1293759.997, 5412479.999, 0), { x: 256, y: 512 });
Approx.point(Nztm2000Tms.pixelsToSource(256, 512, 0), { x: 1293760, y: 5412480 });
Approx.point(Nztm2000Tms.sourceToPixels(2440639.955, 5412480.092, 1), { x: 768, y: 1024 });
Approx.point(Nztm2000Tms.pixelsToSource(256 * 3, 256 * 4, 1), { x: 2440640, y: 5412480 });
});
});
[Nztm2000Tms, GoogleTms].forEach((tms) => {
tms.def.tileMatrix.slice(0, 2).forEach((tm, z) => {
o(`should sourceToPixels -> pixelsToSource ${tms.projection} z:${tm.identifier}`, () => {
const startX = tm.topLeftCorner[tms.indexX];
const startY = tm.topLeftCorner[tms.indexY];
const scale = tms.pixelScale(z) * tm.tileWidth;
for (let y = 0; y < tm.matrixHeight; y++) {
for (let x = 0; x < tm.matrixWidth; x++) {
const sX = startX + x * scale;
const sY = startY - y * scale;
const pixels = tms.sourceToPixels(sX, sY, z);
Approx.equal(pixels.x, x * 256, 'sourceToPixels:x');
Approx.equal(pixels.y, y * 256, 'sourceToPixels:y');
const tile = tms.pixelsToSource(pixels.x, pixels.y, z);
Approx.equal(tile.x, sX, 'pixelsToSource:x');
Approx.equal(tile.y, sY, 'pixelsToSource:x');
}
}
});
});
});
o.spec('tileToPixels', () => {
o('should convert to pixels', () => {
o(GoogleTms.tileToPixels(1, 1)).deepEquals({ x: 256, y: 256 });
o(GoogleTms.tileToPixels(2, 2)).deepEquals({ x: 512, y: 512 });
o(GoogleTms.tileToPixels(4, 0)).deepEquals({ x: 1024, y: 0 });
o(GoogleTms.tileToPixels(0, 4)).deepEquals({ x: 0, y: 1024 });
o(Nztm2000Tms.tileToPixels(1, 1)).deepEquals({ x: 256, y: 256 });
o(Nztm2000Tms.tileToPixels(2, 2)).deepEquals({ x: 512, y: 512 });
o(Nztm2000Tms.tileToPixels(4, 0)).deepEquals({ x: 1024, y: 0 });
o(Nztm2000Tms.tileToPixels(0, 4)).deepEquals({ x: 0, y: 1024 });
});
});
o.spec('pixelsToTile', () => {
o('should round trip', () => {
for (let i = 3; i < 1000; i += 13) {
const pixels = GoogleTms.tileToPixels(i, i);
const tile = GoogleTms.pixelsToTile(pixels.x, pixels.y, i);
o(tile).deepEquals({ x: i, y: i, z: i });
}
});
});
o.spec('tileToSource', () => {
o('should convert to source units', () => {
o(GoogleTms.tileToSource({ x: 0, y: 0, z: 0 })).deepEquals({
x: -20037508.3427892,
y: 20037508.3427892,
});
o(GoogleTms.tileToSource({ x: 1, y: 1, z: 0 })).deepEquals({
x: 20037508.342789236,
y: -20037508.342789236,
});
o(GoogleTms.tileToSource(QuadKey.toTile('311331222'))).deepEquals({
x: 19411336.207076784,
y: -4304933.433020964,
});
});
});
o.spec('convertZoomLevel', () => {
o('should match the zoom levels from nztm2000', () => {
for (let i = 0; i < Nztm2000Tms.maxZoom; i++) {
o(TileMatrixSet.convertZoomLevel(i, Nztm2000Tms, Nztm2000Tms)).equals(i);
}
});
o('should match the zoom levels from google', () => {
for (let i = 0; i < GoogleTms.maxZoom; i++) {
o(TileMatrixSet.convertZoomLevel(i, GoogleTms, GoogleTms)).equals(i);
}
});
o('should round trip from Google to NztmQuad', () => {
for (let i = 0; i < Nztm2000QuadTms.maxZoom; i++) {
const nztmToGoogle = TileMatrixSet.convertZoomLevel(i, Nztm2000QuadTms, GoogleTms);
const googleToNztm = TileMatrixSet.convertZoomLevel(nztmToGoogle, GoogleTms, Nztm2000QuadTms);
o(googleToNztm).equals(i);
}
});
// Some example current zooms we use for configuration
const CurrentZooms = [
{ google: 13, nztm: 9, name: 'rural' },
{ google: 14, nztm: 10, name: 'urban' },
];
o('should convert google to nztm', () => {
for (const zoom of CurrentZooms) {
const googleToNztm = TileMatrixSet.convertZoomLevel(zoom.google, GoogleTms, Nztm2000Tms);
const googleToNztmQuad = TileMatrixSet.convertZoomLevel(zoom.google, GoogleTms, Nztm2000QuadTms);
o(googleToNztm).equals(zoom.nztm)(`Converting ${zoom.name} from ${zoom.google} to ${zoom.nztm}`);
o(googleToNztmQuad).equals(zoom.google - 2);
}
});
o('should match zoom levels outside of the range of the target z', () => {
o(TileMatrixSet.convertZoomLevel(22, Nztm2000QuadTms, Nztm2000Tms)).equals(16);
o(TileMatrixSet.convertZoomLevel(21, Nztm2000QuadTms, Nztm2000Tms)).equals(16);
o(TileMatrixSet.convertZoomLevel(20, Nztm2000QuadTms, Nztm2000Tms)).equals(16);
});
o('should match the zoom levels from nztm2000 when using nztm2000quad', () => {
o(TileMatrixSet.convertZoomLevel(13, Nztm2000QuadTms, Nztm2000Tms)).equals(11);
o(TileMatrixSet.convertZoomLevel(12, Nztm2000QuadTms, Nztm2000Tms)).equals(10);
o(TileMatrixSet.convertZoomLevel(6, Nztm2000QuadTms, Nztm2000Tms)).equals(4);
});
o('should correctly convert Nztm2000 into Nztm2000Qud for rural and urban', () => {
// Gebco turns on at 0
o(TileMatrixSet.convertZoomLevel(0, Nztm2000Tms, Nztm2000QuadTms)).equals(0);
// Rural turns on at 9
o(TileMatrixSet.convertZoomLevel(9, Nztm2000Tms, Nztm2000QuadTms)).equals(12);
// Urban turns on at 10
o(TileMatrixSet.convertZoomLevel(10, Nztm2000Tms, Nztm2000QuadTms)).equals(13);
// Most things turn off at 17
o(TileMatrixSet.convertZoomLevel(17, Nztm2000Tms, Nztm2000QuadTms)).equals(Nztm2000QuadTms.maxZoom);
});
});
o.spec('tileToSourceBounds', () => {
o('should convert to source bounds', () => {
o(round(GoogleTms.tileToSourceBounds({ x: 0, y: 0, z: 0 }).toJson(), 4)).deepEquals({
x: -20037508.3428,
y: -20037508.3428,
width: 40075016.6856,
height: 40075016.6856,
});
o(round(GoogleTms.tileToSourceBounds(QuadKey.toTile('311331222')).toJson(), 4)).deepEquals({
x: 19411336.2071,
y: -4383204.95,
width: 78271.517,
height: 78271.517,
});
});
});
o.spec('topLevelTiles', () => {
o('should return covering tiles of level 0 extent', () => {
o(Array.from(GoogleTms.topLevelTiles())).deepEquals([{ x: 0, y: 0, z: 0 }]);
o(Array.from(Nztm2000Tms.topLevelTiles())).deepEquals([
{ x: 0, y: 0, z: 0 },
{ x: 1, y: 0, z: 0 },
{ x: 0, y: 1, z: 0 },
{ x: 1, y: 1, z: 0 },
{ x: 0, y: 2, z: 0 },
{ x: 1, y: 2, z: 0 },
{ x: 0, y: 3, z: 0 },
{ x: 1, y: 3, z: 0 },
]);
});
});
o.spec('tileToName nameToTile', () => {
o('should make a name of the tile z,x,y', () => {
o(TileMatrixSet.tileToName({ x: 4, y: 5, z: 6 })).equals('6-4-5');
o(TileMatrixSet.nameToTile('6-4-5')).deepEquals({ x: 4, y: 5, z: 6 });
});
});
o.spec('findBestZoom', () => {
o('should find a similar scale', () => {
o(GoogleTms.findBestZoom(GoogleTms.def.tileMatrix[1].scaleDenominator)).equals(1);
o(GoogleTms.findBestZoom(GoogleTms.def.tileMatrix[10].scaleDenominator)).equals(10);
o(GoogleTms.findBestZoom(GoogleTms.def.tileMatrix[15].scaleDenominator)).equals(15);
o(Nztm2000Tms.findBestZoom(Nztm2000Tms.def.tileMatrix[1].scaleDenominator)).equals(1);
o(Nztm2000Tms.findBestZoom(Nztm2000Tms.def.tileMatrix[10].scaleDenominator)).equals(10);
o(Nztm2000Tms.findBestZoom(Nztm2000Tms.def.tileMatrix[15].scaleDenominator)).equals(15);
o(Nztm2000QuadTms.findBestZoom(Nztm2000QuadTms.def.tileMatrix[1].scaleDenominator)).equals(1);
o(Nztm2000QuadTms.findBestZoom(Nztm2000QuadTms.def.tileMatrix[10].scaleDenominator)).equals(10);
o(Nztm2000QuadTms.findBestZoom(Nztm2000QuadTms.def.tileMatrix[15].scaleDenominator)).equals(15);
});
o('should find similar scales across tile matrix sets', () => {
for (let i = 0; i < Nztm2000QuadTms.maxZoom; i++) {
o(GoogleTms.findBestZoom(Nztm2000QuadTms.def.tileMatrix[i].scaleDenominator)).equals(i + 2);
}
o(Nztm2000QuadTms.findBestZoom(Nztm2000Tms.def.tileMatrix[0].scaleDenominator)).equals(2);
});
o('should map test urban/rural scales correctly', () => {
o(Nztm2000Tms.findBestZoom(GoogleTms.zooms[13].scaleDenominator)).equals(9);
o(Nztm2000Tms.findBestZoom(GoogleTms.zooms[14].scaleDenominator)).equals(10);
o(Nztm2000QuadTms.findBestZoom(GoogleTms.zooms[13].scaleDenominator)).equals(11);
o(Nztm2000QuadTms.findBestZoom(GoogleTms.zooms[14].scaleDenominator)).equals(12);
});
});
o.spec('coverTile', () => {
o('should return covering tiles of level n extent', () => {
o(Array.from(GoogleTms.coverTile({ x: 2, y: 3, z: 3 }))).deepEquals([
{ x: 4, y: 6, z: 4 },
{ x: 5, y: 6, z: 4 },
{ x: 4, y: 7, z: 4 },
{ x: 5, y: 7, z: 4 },
]);
o(Array.from(Nztm2000Tms.coverTile({ x: 2, y: 3, z: 8 }))).deepEquals([
{ x: 4, y: 6, z: 9 },
{ x: 5, y: 6, z: 9 },
{ x: 4, y: 7, z: 9 },
{ x: 5, y: 7, z: 9 },
]);
o(Array.from(Nztm2000Tms.coverTile({ x: 2, y: 3, z: 7 }))).deepEquals([
{ x: 5, y: 7, z: 8 },
{ x: 6, y: 7, z: 8 },
{ x: 7, y: 7, z: 8 },
{ x: 5, y: 8, z: 8 },
{ x: 6, y: 8, z: 8 },
{ x: 7, y: 8, z: 8 },
{ x: 5, y: 9, z: 8 },
{ x: 6, y: 9, z: 8 },
{ x: 7, y: 9, z: 8 },
]);
o(Array.from(Nztm2000Tms.coverTile({ x: 3, y: 2, z: 7 }))).deepEquals([
{ x: 7, y: 5, z: 8 },
{ x: 8, y: 5, z: 8 },
{ x: 9, y: 5, z: 8 },
{ x: 7, y: 6, z: 8 },
{ x: 8, y: 6, z: 8 },
{ x: 9, y: 6, z: 8 },
{ x: 7, y: 7, z: 8 },
{ x: 8, y: 7, z: 8 },
{ x: 9, y: 7, z: 8 },
]);
});
});
o.spec('TileMatrixSets', () => {
o('should find by epsg', () => {
o(TileMatrixSets.find('epsg:2193')?.identifier).equals(Nztm2000Tms.identifier);
o(TileMatrixSets.find('2193')?.identifier).equals(Nztm2000Tms.identifier);
o(TileMatrixSets.find('epsg:3857')?.identifier).equals(GoogleTms.identifier);
o(TileMatrixSets.find('3857')?.identifier).equals(GoogleTms.identifier);
});
o('should find by name', () => {
o(TileMatrixSets.find(Nztm2000Tms.identifier)?.identifier).equals(Nztm2000Tms.identifier);
o(TileMatrixSets.find(Nztm2000QuadTms.identifier)?.identifier).equals(Nztm2000QuadTms.identifier);
o(TileMatrixSets.find(GoogleTms.identifier)?.identifier).equals(GoogleTms.identifier);
});
});
}); | the_stack |
import { Heading, Icon } from "@kaizen/component-library"
import { Checkbox, CheckedStatus } from "@kaizen/draft-form"
import classNames from "classnames"
import * as React from "react"
import sortAscendingIcon from "@kaizen/component-library/icons/sort-ascending.icon.svg"
import sortDescendingIcon from "@kaizen/component-library/icons/sort-descending.icon.svg"
import exclamationIcon from "@kaizen/component-library/icons/exclamation.icon.svg"
import { Tooltip } from "@kaizen/draft-tooltip"
import styles from "./styles.scss"
type TableContainer = React.FunctionComponent<TableContainerProps>
type TableContainerProps = {
variant?: "compact" | "default" | "data"
}
export const TableContainer: TableContainer = ({
variant = "compact",
children,
...otherProps
}) => (
<div
role="table"
className={classNames(styles.container, {
[styles.defaultSpacing]: variant === "default",
[styles.dataVariant]: variant === "data",
})}
{...otherProps}
>
{children}
</div>
)
/**
* @deprecated backgroundColor is deprecated. Header props now have transparet backgrounds
*/
export type AllowedTableHeaderBackgroundColors = "ash" | "white"
type TableHeader = React.FunctionComponent<{
backgroundColor?: AllowedTableHeaderBackgroundColors
}>
export const TableHeader: TableHeader = ({
backgroundColor,
children,
...otherProps
}) => {
if (backgroundColor) {
// eslint-disable-next-line no-console
console.warn(
"DEPRECATED(table): backgroundColor is deprecated - this prop has no effect"
)
}
return (
<div role="rowgroup" {...otherProps}>
{children}
</div>
)
}
type TableHeaderRow = React.FunctionComponent
export const TableHeaderRow: TableHeaderRow = ({ children, ...otherProps }) => (
<div className={classNames(styles.row)} role="rowheader" {...otherProps}>
{children}
</div>
)
const ratioToPercent = (width?: number) =>
width != null ? `${width * 100}%` : width
/**
* @param width value between 1 and 0, to be calculated as a percentage
* @param flex CSS flex shorthand as a string. Be sure to specify the flex grow,
* shrink, and basis, due to IE11 compatibility. eg. use "1 1 auto"
* instead of just "1".
*/
type TableHeaderRowCell = React.FunctionComponent<{
labelText: string
automationId?: string
onClick?:
| ((e: React.MouseEvent<HTMLButtonElement>) => any)
| ((e: React.MouseEvent<HTMLAnchorElement>) => any)
href?: string
width?: number
flex?: string
icon?: React.SVGAttributes<SVGSymbolElement>
checkable?: boolean
checkedStatus?: CheckedStatus
onCheck?: (event: React.ChangeEvent<HTMLInputElement>) => any
reversed?: boolean
/**
* This boolean would show a "sort by" icon in the table cell header.
* The problem was that the arrow was pointing in the descending direction only.
* Please use `sorting` prop instead.
* @deprecated
*/
active?: boolean
/**
* Shows an up or down arrow, to show that the column is sorted.
*/
sorting?: "ascending" | "descending"
wrapping?: "nowrap" | "wrap"
align?: "start" | "center" | "end"
tooltipInfo?: string
sortingArrowsOnHover?: "ascending" | "descending" | undefined
}>
export const TableHeaderRowCell: TableHeaderRowCell = ({
labelText,
automationId,
onClick,
href,
width,
flex,
icon,
checkable,
checkedStatus,
onCheck,
reversed,
active,
sorting: sortingRaw,
// I can't say for certain why "nowrap" was the default value. Normally you wouldn't
// want to clip off information because it doesn't fit on one line.
// My assumption is that because since the cell width rows are decoupled, a heading
// cell with a word longer than the column width would push the columns out of
// alignment? I'm not sure.
// Anyway, we can override this default behaviour by setting wrapping to "wrap".
wrapping = "nowrap",
align = "start",
tooltipInfo,
// if set, this will show the arrow in the direction provided
// when the header cell is hovered over.
sortingArrowsOnHover,
// There aren't any other props in the type definition, so I'm unsure why we
// have this spread.
...otherProps
}) => {
// `active` is the legacy prop
const sorting = sortingRaw || (active ? "descending" : undefined)
const [isHovered, setIsHovered] = React.useState(false)
const updateHoverState = (hoverState: boolean) => {
if (sortingArrowsOnHover && hoverState != isHovered)
setIsHovered(hoverState)
}
const headerColor = !!reversed
? "white-reduced-opacity"
: "dark-reduced-opacity"
const hoveredHeaderColor = !!reversed ? "white" : "dark"
// For this "cellContents" variable, we start at the inner most child, and
// wrap it elements, depending on what the props dictate.
let cellContents = (
<div className={styles.headerRowCellLabelAndIcons}>
{icon && (
<span className={styles.headerRowCellIcon}>
<Icon icon={icon} title={labelText} />
</span>
)}
{checkable && (
<div className={styles.headerRowCellCheckbox}>
<Checkbox
automationId={`${automationId}-checkbox`}
checkedStatus={checkedStatus}
onCheck={onCheck}
/>
</div>
)}
{tooltipInfo != null ? (
<div className={styles.headerRowCellTooltipIcon}>
<Icon icon={exclamationIcon} role="presentation" />
</div>
) : null}
{/* If an "icon" is supplied, the label is displayed inside the icon aria title instead */}
{!icon ? (
<div className={styles.headerRowCellLabel}>
<Heading
tag="div"
variant="heading-6"
color={sorting || isHovered ? hoveredHeaderColor : headerColor}
>
{labelText}
</Heading>
</div>
) : null}
{(sorting || (isHovered && sortingArrowsOnHover)) && (
<div
className={classNames({
[styles.headerRowCellIconAlignCenter]: align === "center",
[styles.headerRowCellIconAlignEnd]: align === "end",
})}
>
<Icon
icon={
sorting === "ascending" || sortingArrowsOnHover === "ascending"
? sortAscendingIcon
: sortDescendingIcon
}
role="presentation"
/>
</div>
)}
</div>
)
cellContents = href ? (
<a
data-automation-id={automationId}
className={classNames(styles.headerRowCellButton, {
[styles.headerRowCellButtonReversed]: !!reversed,
})}
href={href}
onClick={
onClick as (e: React.MouseEvent<HTMLAnchorElement>) => any | undefined
}
onMouseEnter={() => updateHoverState(true)}
onFocus={() => updateHoverState(true)}
onMouseLeave={() => updateHoverState(false)}
onBlur={() => updateHoverState(false)}
>
{cellContents}
</a>
) : onClick ? (
<button
data-automation-id={automationId}
className={classNames(styles.headerRowCellButton, {
[styles.headerRowCellButtonReversed]: !!reversed,
})}
onClick={onClick as (e: React.MouseEvent<HTMLButtonElement>) => any}
onMouseEnter={() => updateHoverState(true)}
onFocus={() => updateHoverState(true)}
onMouseLeave={() => updateHoverState(false)}
onBlur={() => updateHoverState(false)}
>
{cellContents}
</button>
) : (
// This div wrapper probably isn't needed, but it's a bit easier
// for this flex positioning, to have the dom tree depth match for
// each permutation.
<div className={styles.headerRowCellNoButton}>{cellContents}</div>
)
cellContents =
tooltipInfo != null ? (
<Tooltip
text={tooltipInfo}
classNameAndIHaveSpokenToDST={styles.headerRowCellTooltip}
>
{cellContents}
</Tooltip>
) : (
// Again, this wrapper is just to make the dom tree consistent between
// different permutations.
<div className={styles.headerRowCellTooltip}>{cellContents}</div>
)
return (
<div
className={classNames(styles.headerRowCell, {
[styles.headerRowCellNoWrap]: wrapping === "nowrap",
[styles.headerRowCellAlignCenter]: align === "center",
[styles.headerRowCellAlignEnd]: align === "end",
[styles.headerRowCellActive]: !!sorting,
})}
style={{
width: ratioToPercent(width),
flex,
}}
data-automation-id={automationId}
role="columnheader"
{...otherProps}
>
{cellContents}
</div>
)
}
type ButtonClickEvent = (e: React.MouseEvent<HTMLButtonElement>) => void
type AnchorClickEvent = (e: React.MouseEvent<HTMLAnchorElement>) => void
/**
* As the Card examples in Storybook take a TableRow,
* I opted to give the child the role="row" tag. That being
* said, while TableHeader has a role="rowgroup" as given
* in an example on the accessibility docs, I couldn't justify
* adding the same here as all rows look to be wrapped in the
* TableCard.
*
* It may mean that the consumer needs to add their own container
* around with the role="row". We could also just add it as a
* very simple component similar to TableHeader.
*
* @see https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/Table_Role
*/
type TableCard = React.FunctionComponent<{
onClick?: ButtonClickEvent | AnchorClickEvent
expanded?: boolean
expandedStyle?: "well" | "popout"
href?: string
// Despite there being no onClick or href, still show a hover state on the
// rows. An example use case is when you might want to handle click events
// at a cell level, instead of the full row level.
forceHoverState?: boolean
}>
export const TableCard: TableCard = ({
children,
expanded,
expandedStyle = "well",
onClick,
href,
forceHoverState = false,
...otherProps
}) => {
const className = classNames(styles.card, {
[styles.expanded]: expanded,
[styles[expandedStyle]]: expanded,
[styles.hasHoverState]: forceHoverState || onClick != null || href != null,
})
return href != null ? (
<a
href={href}
className={className}
onClick={onClick as AnchorClickEvent}
{...otherProps}
>
{children}
</a>
) : onClick ? (
<button
className={className}
onClick={onClick as ButtonClickEvent}
{...otherProps}
>
{children}
</button>
) : (
<div className={className} {...otherProps}>
{children}
</div>
)
}
/**
* Aria roles like aria-rowindex can be added from
* the component consumer.
*
* @param {*} { children, ...otherProps }
*/
type TableRow = React.FunctionComponent
export const TableRow: TableRow = ({ children, ...otherProps }) => (
<div className={styles.row} role="row" {...otherProps}>
{children}
</div>
)
/**
* @param width value between 1 and 0, to be calculated as a percentage
* @param flex CSS flex shorthand as a string. Be sure to specify the flex grow,
* shrink, and basis, due to IE11 compatibility. eg. use "1 1 auto"
* instead of just "1".
*/
type TableRowCell = React.FunctionComponent<{
width?: number
flex?: string
href?: string
}>
export const TableRowCell: TableRowCell = ({
children,
width,
flex,
href,
...otherProps
}) =>
href != null ? (
<a
role="cell"
style={{
width: ratioToPercent(width),
flex,
}}
className={styles.rowCell}
href={href}
{...otherProps}
>
{children}
</a>
) : (
<div
role="cell"
style={{
width: ratioToPercent(width),
flex,
}}
className={styles.rowCell}
{...otherProps}
>
{children}
</div>
) | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.