text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import wkx from 'wkx';
// @ts-ignore
import reproject from 'reproject';
import pointToLineDistance from '@turf/point-to-line-distance';
import polygonToLine from '@turf/polygon-to-line';
import booleanPointInPolygon from '@turf/boolean-point-in-polygon';
// @ts-ignore
import pointDistance from '@turf/distance';
import * as helpers from '@turf/helpers';
import proj4 from 'proj4';
import * as defs from './proj4Defs';
import { Feature, FeatureCollection, Geometry, LineString, MultiPolygon, Point, Polygon } from 'geojson';
import { GeometryData } from './geom/geometryData';
import { GeoPackageConnection } from './db/geoPackageConnection';
import { CrsWktExtension } from './extension/crsWkt';
import { RelatedTablesExtension } from './extension/relatedTables';
import { FeatureStyleExtension } from './extension/style';
import { ContentsIdExtension } from './extension/contents';
import { TileScalingExtension } from './extension/scale';
import { SpatialReferenceSystemDao } from './core/srs/spatialReferenceSystemDao';
import { GeometryColumnsDao } from './features/columns/geometryColumnsDao';
import { FeatureDao } from './features/user/featureDao';
import { FeatureTableReader } from './features/user/featureTableReader';
import { ContentsDao } from './core/contents/contentsDao';
import { TileMatrixSetDao } from './tiles/matrixset/tileMatrixSetDao';
import { TileMatrixDao } from './tiles/matrix/tileMatrixDao';
import { DataColumnsDao } from './dataColumns/dataColumnsDao';
import { DataColumnConstraintsDao } from './dataColumnConstraints/dataColumnConstraintsDao';
import { MetadataDao } from './metadata/metadataDao';
import { MetadataReferenceDao } from './metadata/reference/metadataReferenceDao';
import { ExtensionDao } from './extension/extensionDao';
import { TableIndexDao } from './extension/index/tableIndexDao';
import { GeometryIndexDao } from './extension/index/geometryIndexDao';
import { ExtendedRelationDao } from './extension/relatedTables/extendedRelationDao';
import { AttributesDao } from './attributes/attributesDao';
import { TileDao } from './tiles/user/tileDao';
import { ContentsIdDao } from './extension/contents/contentsIdDao';
import { TileScalingDao } from './extension/scale/tileScalingDao';
import { AttributesTable } from './attributes/attributesTable';
import { TileTableReader } from './tiles/user/tileTableReader';
import { AttributesTableReader } from './attributes/attributesTableReader';
import { FeatureTable } from './features/user/featureTable';
import { StyleMappingTable } from './extension/style/styleMappingTable';
import { TileTable } from './tiles/user/tileTable';
import { Contents } from './core/contents/contents';
import { GeoPackageDataType } from './db/geoPackageDataType';
import { SchemaExtension } from './extension/schema';
import { GeometryColumns } from './features/columns/geometryColumns';
import { TableCreator } from './db/tableCreator';
import { TileMatrix } from './tiles/matrix/tileMatrix';
import { TileBoundingBoxUtils } from './tiles/tileBoundingBoxUtils';
import { BoundingBox } from './boundingBox';
import { TileMatrixSet } from './tiles/matrixset/tileMatrixSet';
import { UserColumn } from './user/userColumn';
import { DataColumns } from './dataColumns/dataColumns';
import { AttributesRow } from './attributes/attributesRow';
import { SpatialReferenceSystem } from './core/srs/spatialReferenceSystem';
import { FeatureRow } from './features/user/featureRow';
import { GeoPackageValidate, GeoPackageValidationError } from './validate/geoPackageValidate';
import { FeatureColumn } from './features/user/featureColumn';
import { DBValue } from './db/dbAdapter';
import { MediaDao } from './extension/relatedTables/mediaDao';
import { MediaRow } from './extension/relatedTables/mediaRow';
import { MediaTable } from './extension/relatedTables/mediaTable';
import { ExtendedRelation } from './extension/relatedTables/extendedRelation';
import { RelationType } from './extension/relatedTables/relationType';
import { SimpleAttributesDao } from './extension/relatedTables/simpleAttributesDao';
import { SimpleAttributesRow } from './extension/relatedTables/simpleAttributesRow';
import { SimpleAttributesTable } from './extension/relatedTables/simpleAttributesTable';
import { TileRow } from './tiles/user/tileRow';
import { FeatureTiles } from './tiles/features';
import { GeoPackageTileRetriever } from './tiles/retriever';
import { TileScaling } from './extension/scale/tileScaling';
import { TileScalingType } from './extension/scale/tileScalingType';
import { AttributesColumn } from './attributes/attributesColumn';
import { AlterTable } from './db/alterTable';
import { GeoPackageExtensions } from './extension/geoPackageExtensions';
import { ContentsDataType } from './core/contents/contentsDataType';
import { UserMappingTable } from './extension/relatedTables/userMappingTable';
import { GeometryType } from './features/user/geometryType';
import { Constraints } from './db/table/constraints';
type ColumnMap = {
[key: string]: {
index: number;
name: string;
max?: number;
min?: number;
notNull?: boolean;
primaryKey?: boolean;
dataType?: GeoPackageDataType;
displayName: string;
dataColumn?: DataColumns;
};
};
export interface ClosestFeature {
feature_count: number;
coverage: boolean;
gp_table: string;
gp_name: string;
distance?: number;
}
const anyDefs = defs as any;
for (const def in anyDefs) {
if (anyDefs[def]) {
proj4.defs(def, anyDefs[def]);
}
}
/**
* A `GeoPackage` instance is the interface to a physical GeoPackage SQLite
* database.
*/
export class GeoPackage {
/** name of the GeoPackage */
name: string;
/** path to the GeoPackage */
path: string;
connection: GeoPackageConnection;
tableCreator: TableCreator;
private _spatialReferenceSystemDao: SpatialReferenceSystemDao;
private _contentsDao: ContentsDao;
private _tileMatrixSetDao: TileMatrixSetDao;
private _tileMatrixDao: TileMatrixDao;
private _dataColumnsDao: DataColumnsDao;
private _extensionDao: ExtensionDao;
private _tableIndexDao: TableIndexDao;
private _geometryColumnsDao: GeometryColumnsDao;
private _dataColumnConstraintsDao: DataColumnConstraintsDao;
private _metadataReferenceDao: MetadataReferenceDao;
private _metadataDao: MetadataDao;
private _extendedRelationDao: ExtendedRelationDao;
private _contentsIdDao: ContentsIdDao;
private _tileScalingDao: TileScalingDao;
private _contentsIdExtension: ContentsIdExtension;
private _tileScalingExtension: TileScalingExtension;
private _featureStyleExtension: FeatureStyleExtension;
private _relatedTablesExtension: RelatedTablesExtension;
/**
* Construct a new GeoPackage object
* @param name name to give to this GeoPackage
* @param path path to the GeoPackage
* @param connection database connection to the GeoPackage
*/
constructor(name: string, path: string, connection: GeoPackageConnection) {
this.name = name;
this.path = path;
this.connection = connection;
this.tableCreator = new TableCreator(this);
}
close(): void {
this.connection.close();
}
get database(): GeoPackageConnection {
return this.connection;
}
async export(): Promise<any> {
return this.connection.export();
}
validate(): GeoPackageValidationError[] {
let errors: GeoPackageValidationError[] = [];
errors = errors.concat(GeoPackageValidate.validateMinimumTables(this));
return errors;
}
/**
* @returns {module:core/srs~SpatialReferenceSystemDao} the DAO to access the [SRS table]{@link module:core/srs~SpatialReferenceSystem} in this `GeoPackage`
*/
get spatialReferenceSystemDao(): SpatialReferenceSystemDao {
return this._spatialReferenceSystemDao || (this._spatialReferenceSystemDao = new SpatialReferenceSystemDao(this));
}
/**
* @returns {module:core/contents~ContentsDao} the DAO to access the [contents table]{@link module:core/contents~Contents} in this `GeoPackage`
*/
get contentsDao(): ContentsDao {
return this._contentsDao || (this._contentsDao = new ContentsDao(this));
}
/**
* @returns {module:tiles/matrixset~TileMatrixSetDao} the DAO to access the [tile matrix set]{@link module:tiles/matrixset~TileMatrixSet} in this `GeoPackage`
*/
get tileMatrixSetDao(): TileMatrixSetDao {
return this._tileMatrixSetDao || (this._tileMatrixSetDao = new TileMatrixSetDao(this));
}
/**
* @returns {module:tiles/matrixset~TileMatrixDao} the DAO to access the [tile matrix]{@link module:tiles/matrixset~TileMatrix} in this `GeoPackage`
*/
get tileMatrixDao(): TileMatrixDao {
return this._tileMatrixDao || (this._tileMatrixDao = new TileMatrixDao(this));
}
get dataColumnsDao(): DataColumnsDao {
return this._dataColumnsDao || (this._dataColumnsDao = new DataColumnsDao(this));
}
get extensionDao(): ExtensionDao {
return this._extensionDao || (this._extensionDao = new ExtensionDao(this));
}
get tableIndexDao(): TableIndexDao {
return this._tableIndexDao || (this._tableIndexDao = new TableIndexDao(this));
}
get geometryColumnsDao(): GeometryColumnsDao {
return this._geometryColumnsDao || (this._geometryColumnsDao = new GeometryColumnsDao(this));
}
get dataColumnConstraintsDao(): DataColumnConstraintsDao {
return this._dataColumnConstraintsDao || (this._dataColumnConstraintsDao = new DataColumnConstraintsDao(this));
}
get metadataReferenceDao(): MetadataReferenceDao {
return this._metadataReferenceDao || (this._metadataReferenceDao = new MetadataReferenceDao(this));
}
get metadataDao(): MetadataDao {
return this._metadataDao || (this._metadataDao = new MetadataDao(this));
}
get extendedRelationDao(): ExtendedRelationDao {
return this._extendedRelationDao || (this._extendedRelationDao = new ExtendedRelationDao(this));
}
get contentsIdDao(): ContentsIdDao {
return this._contentsIdDao || (this._contentsIdDao = new ContentsIdDao(this));
}
get tileScalingDao(): TileScalingDao {
return this._tileScalingDao || (this._tileScalingDao = new TileScalingDao(this));
}
get contentsIdExtension(): ContentsIdExtension {
return this._contentsIdExtension || (this._contentsIdExtension = new ContentsIdExtension(this));
}
get featureStyleExtension(): FeatureStyleExtension {
return this._featureStyleExtension || (this._featureStyleExtension = new FeatureStyleExtension(this));
}
getTileScalingExtension(tableName: string): TileScalingExtension {
return this._tileScalingExtension || (this._tileScalingExtension = new TileScalingExtension(this, tableName));
}
getGeometryIndexDao(featureDao: FeatureDao<FeatureRow>): GeometryIndexDao {
return new GeometryIndexDao(this, featureDao);
}
get relatedTablesExtension(): RelatedTablesExtension {
return this._relatedTablesExtension || (this._relatedTablesExtension = new RelatedTablesExtension(this));
}
getSrs(srsId: number): SpatialReferenceSystem {
const dao = this.spatialReferenceSystemDao;
return dao.queryForId(srsId);
}
createRequiredTables(): GeoPackage {
this.tableCreator.createRequired();
return this;
}
createSupportedExtensions(): GeoPackage {
const crs = new CrsWktExtension(this);
crs.getOrCreateExtension();
const schema = new SchemaExtension(this);
schema.getOrCreateExtension();
return this;
}
/**
* Get a Tile DAO
* @returns {FeatureDao}
* @param table
*/
getTileDao(table: string | Contents | TileMatrixSet): TileDao<TileRow> {
if (table instanceof Contents) {
table = this.contentsDao.getTileMatrixSet(table);
} else if (!(table instanceof TileMatrixSet)) {
const tms = this.tileMatrixSetDao;
const results = tms.queryForAllEq(TileMatrixSetDao.COLUMN_TABLE_NAME, table);
if (results.length > 1) {
throw new Error(
'Unexpected state. More than one Tile Matrix Set matched for table name: ' +
table +
', count: ' +
results.length,
);
} else if (results.length === 0) {
throw new Error('No Tile Matrix found for table name: ' + table);
}
table = tms.createObject(results[0]);
}
if (!table) {
throw new Error('Non null TileMatrixSet is required to create Tile DAO');
}
const tileMatrices: TileMatrix[] = [];
const tileMatrixDao = this.tileMatrixDao;
const results = tileMatrixDao.queryForAllEq(
TileMatrixDao.COLUMN_TABLE_NAME,
table.table_name,
null,
null,
TileMatrixDao.COLUMN_ZOOM_LEVEL +
' ASC, ' +
TileMatrixDao.COLUMN_PIXEL_X_SIZE +
' DESC, ' +
TileMatrixDao.COLUMN_PIXEL_Y_SIZE +
' DESC',
);
results.forEach(function(result) {
const tm = tileMatrixDao.createObject(result);
// verify first that there are actual tiles at this zoom level due to QGIS doing weird things and
// creating tile matrix entries for zoom levels that have no tiles
if (tileMatrixDao.tileCount(tm)) {
tileMatrices.push(tm);
}
});
const tableReader = new TileTableReader(table);
const tileTable = tableReader.readTileTable(this);
return new TileDao(this, tileTable, table, tileMatrices);
}
/**
* Return a hash containing arrays of table names grouped under keys `features`,
* `tiles`, and `attributes`.
* @return {{features: string[], tiles: string[], attributes: string[]}}
*/
getTables(): { features: string[]; tiles: string[]; attributes: string[] };
getTables(
fullInformation = false,
):
| { features: Contents[]; tiles: Contents[]; attributes: Contents[] }
| { features: string[]; tiles: string[]; attributes: string[] } {
if (!fullInformation) {
const tables = {
features: this.getFeatureTables(),
tiles: this.getTileTables(),
attributes: this.getAttributesTables(),
};
return tables;
} else {
const tables = {
features: this.contentsDao.getContentsForTableType(ContentsDataType.FEATURES),
tiles: this.contentsDao.getContentsForTableType(ContentsDataType.TILES),
attributes: this.contentsDao.getContentsForTableType(ContentsDataType.ATTRIBUTES),
};
return tables;
}
}
getAttributesTables(): string[] {
return this.contentsDao.getTables(ContentsDataType.ATTRIBUTES);
}
hasAttributeTable(attributeTableName: string): boolean {
const tables = this.getAttributesTables();
return tables && tables.indexOf(attributeTableName) != -1;
}
/**
* Get the tile tables
* @returns {String[]} tile table names
*/
getTileTables(): string[] {
const cd = this.contentsDao;
if (!cd.isTableExists()) {
return [];
}
return cd.getTables(ContentsDataType.TILES);
}
/**
* Checks if the tile table exists in the GeoPackage
* @param {String} tileTableName name of the table to query for
* @returns {Boolean} indicates the existence of the tile table
*/
hasTileTable(tileTableName: string): boolean {
const tables = this.getTileTables();
return tables && tables.indexOf(tileTableName) !== -1;
}
/**
* Checks if the feature table exists in the GeoPackage
* @param {String} featureTableName name of the table to query for
* @returns {Boolean} indicates the existence of the feature table
*/
hasFeatureTable(featureTableName: string): boolean {
const tables = this.getFeatureTables();
return tables && tables.indexOf(featureTableName) != -1;
}
/**
* Get the feature tables
* @returns {String[]} feature table names
*/
getFeatureTables(): string[] {
const cd = this.contentsDao;
if (!cd.isTableExists()) {
return [];
}
return cd.getTables(ContentsDataType.FEATURES);
}
isTable(tableName: string): boolean {
return !!this.connection.tableExists(tableName);
}
isTableType(type: string, tableName: string): boolean {
return type === this.getTableType(tableName);
}
getTableType(tableName: string): string {
const contents = this.getTableContents(tableName);
if (contents) {
return contents.data_type;
}
}
getTableContents(tableName: string): Contents {
return this.contentsDao.queryForId(tableName);
}
dropTable(tableName: string): boolean {
return this.connection.dropTable(tableName);
}
/**
* {@inheritDoc}
*/
deleteTable(table: string) {
GeoPackageExtensions.deleteTableExtensions(this, table);
this.contentsDao.deleteTable(table);
}
/**
* {@inheritDoc}
*/
deleteTableQuietly(tableName: string) {
try {
this.deleteTable(tableName);
} catch (e) {
// eat
}
}
getTableCreator(): TableCreator {
return this.tableCreator;
}
async index(): Promise<boolean> {
const tables = this.getFeatureTables();
for (let i = 0; i < tables.length; i++) {
if (!(await this.indexFeatureTable(tables[i]))) {
throw new Error('Unable to index table ' + tables[i]);
}
}
return true;
}
async indexFeatureTable(table: string, progress?: Function): Promise<boolean> {
const featureDao = this.getFeatureDao(table);
const fti = featureDao.featureTableIndex;
if (fti.isIndexed()) {
return true;
}
return await fti.index(progress);
}
/**
* Get a Feature DAO from Contents
* @returns {FeatureDao}
* @param table
*/
getFeatureDao(table: string | Contents | GeometryColumns): FeatureDao<FeatureRow> {
if (table instanceof Contents) {
table = this.contentsDao.getGeometryColumns(table);
} else if (!(table instanceof GeometryColumns)) {
table = this.geometryColumnsDao.queryForTableName(table);
}
if (!table) {
throw new Error('Non null Geometry Columns is required to create Feature DAO');
}
const tableReader = new FeatureTableReader(table);
const featureTable = tableReader.readFeatureTable(this);
return new FeatureDao(this, featureTable, table, this.metadataDao);
}
/**
* Queries for GeoJSON features in a feature table
* @param {String} tableName Table name to query
* @param {BoundingBox} boundingBox BoundingBox to query
* @returns {Object[]} array of GeoJSON features
*/
queryForGeoJSONFeaturesInTable(tableName: string, boundingBox: BoundingBox): Feature[] {
const featureDao = this.getFeatureDao(tableName);
const features = [];
const iterator = featureDao.queryForGeoJSONIndexedFeaturesWithBoundingBox(boundingBox);
for (const feature of iterator) {
features.push(feature);
}
return features;
}
/**
* Create the Geometry Columns table if it does not already exist
* @returns {Promise}
*/
createGeometryColumnsTable(): boolean {
if (this.geometryColumnsDao.isTableExists()) {
return true;
}
return this.tableCreator.createGeometryColumns();
}
/**
* Get a Attribute DAO
* @param {Contents} contents Contents
* @returns {AttributesDao}
*/
getAttributeDao(table: Contents | string): AttributesDao<AttributesRow> {
if (!(table instanceof Contents)) {
table = this.contentsDao.queryForId(table);
}
if (!table) {
throw new Error('Non null Contents is required to create an Attributes DAO');
}
const reader = new AttributesTableReader(table.table_name);
const attributeTable: AttributesTable = reader.readTable(this.connection) as AttributesTable;
attributeTable.setContents(table);
return new AttributesDao(this, attributeTable);
}
/**
* Create AttributesTable from properties
* @param tableName
* @param properties
*/
createAttributesTableFromProperties(
tableName: string,
properties: {
name: string;
dataType: string;
dataColumn?: {
table_name: string;
column_name: string;
name?: string;
title?: string;
description?: string;
mime_type?: string;
constraint_name?: string;
};
}[]
): boolean {
let attributeColumns: AttributesColumn[] = [];
let columnNumber = 0;
let dataColumns = [];
attributeColumns.push(UserColumn.createPrimaryKeyColumn(columnNumber++, 'id'));
for (let i = 0; i < properties.length; i++) {
const property = properties[i] as {
name: string;
dataType: string;
dataColumn?: {
table_name: string;
column_name: string;
name?: string;
title?: string;
description?: string;
mime_type?: string;
constraint_name?: string;
};
};
attributeColumns.push(
UserColumn.createColumn(columnNumber++, property.name, GeoPackageDataType.fromName(property.dataType)),
);
if (property.dataColumn) {
const dc = new DataColumns();
dc.table_name = property.dataColumn.table_name;
dc.column_name = property.dataColumn.column_name;
dc.name = property.dataColumn.name;
dc.title = property.dataColumn.title;
dc.description = property.dataColumn.description;
dc.mime_type = property.dataColumn.mime_type;
dc.constraint_name = property.dataColumn.constraint_name;
dataColumns.push(dc);
}
}
return this.createAttributesTable(tableName, attributeColumns, new Constraints(), dataColumns);
}
/**
* Create attributes table for these columns, will add id column if no primary key column is defined
* @param tableName
* @param additionalColumns
* @param constraints
* @param dataColumns
*/
createAttributesTable(tableName: string, additionalColumns: AttributesColumn[], constraints?: Constraints, dataColumns?: DataColumns[]): boolean {
let columns = [];
// Check for primary key field
if (additionalColumns.findIndex(c => c.isPrimaryKey()) === -1) {
columns.push(AttributesColumn.createPrimaryKeyColumn(AttributesColumn.NO_INDEX, 'id'))
}
additionalColumns.forEach(c => {
columns.push(c.copy());
});
// Build the user attributes table
let table = new AttributesTable(tableName, columns);
// Add unique constraints
if (constraints !== null && constraints !== undefined) {
table.addConstraints(constraints);
}
// Create the user attributes table
this.tableCreator.createUserTable(table);
try {
// Create the contents
let contents = new Contents();
contents.table_name = tableName;
contents.data_type = ContentsDataType.ATTRIBUTES;
contents.identifier = tableName;
contents.last_change = new Date().toISOString();
this.contentsDao.create(contents);
table.setContents(contents);
// create passed in data columns
if (dataColumns && dataColumns.length) {
this.createDataColumns();
const dataColumnsDao = this.dataColumnsDao;
dataColumns.forEach(dataColumn => {
dataColumnsDao.create(dataColumn);
});
}
} catch (e) {
this.deleteTableQuietly(tableName);
throw new Error("Failed to create table and metadata: " + tableName);
}
return true;
}
/**
* Create a media table with the properties specified. These properties are added to the required columns
* @param {module:geoPackage~GeoPackage} geopackage the geopackage object
* @param {Object[]} properties properties to create columns from
* @param {string} properties.name name of the column
* @param {string} properties.dataType name of the data type
* @return {Promise}
*/
createMediaTable(
tableName: string,
properties: { name: string; dataType: string; notNull?: boolean; defaultValue?: DBValue; max?: number }[],
): MediaDao<MediaRow> {
const relatedTables = this.relatedTablesExtension;
const columns = [];
let columnNumber = MediaTable.numRequiredColumns();
if (properties) {
for (let i = 0; i < properties.length; i++) {
const property = properties[i];
columns.push(
UserColumn.createColumn(
columnNumber++,
property.name,
GeoPackageDataType.fromName(property.dataType),
property.notNull,
property.defaultValue,
property.max,
),
);
}
}
const mediaTable = MediaTable.create(tableName, columns);
relatedTables.createRelatedTable(mediaTable);
return relatedTables.getMediaDao(mediaTable);
}
linkMedia(baseTableName: string, baseId: number, mediaTableName: string, mediaId: number): number {
return this.linkRelatedRows(baseTableName, baseId, mediaTableName, mediaId, RelationType.MEDIA);
}
/**
* Links related rows together
* @param baseId
* @param baseTableName
* @param relatedId
* @param relatedTableName
* @param {string} relationType relation type
* @param {string|UserMappingTable} [mappingTable] mapping table
* @param {module:dao/columnValues~ColumnValues} [mappingColumnValues] column values
* @return {number}
*/
linkRelatedRows(
baseTableName: string,
baseId: number,
relatedTableName: string,
relatedId: number,
relationType: RelationType,
mappingTable?: string | UserMappingTable,
mappingColumnValues?: Record<string, any>,
): number {
const rte = this.relatedTablesExtension;
const relationship = rte
.getRelationshipBuilder()
.setBaseTableName(baseTableName)
.setRelatedTableName(relatedTableName)
.setRelationType(relationType);
let mappingTableName: string;
if (!mappingTable || typeof mappingTable === 'string') {
mappingTable = mappingTable || baseTableName + '_' + relatedTableName;
relationship.setMappingTableName(mappingTable);
mappingTableName = mappingTable as string;
} else {
relationship.setUserMappingTable(mappingTable);
mappingTableName = mappingTable.getTableName();
}
rte.addRelationship(relationship);
const userMappingDao = rte.getMappingDao(mappingTableName);
const userMappingRow = userMappingDao.newRow();
userMappingRow.baseId = baseId;
userMappingRow.relatedId = relatedId;
for (const column in mappingColumnValues) {
userMappingRow.setValueWithColumnName(column, mappingColumnValues[column]);
}
return userMappingDao.create(userMappingRow);
}
getLinkedMedia(baseTableName: string, baseId: number): MediaRow[] {
const relationships = this.getRelatedRows(baseTableName, baseId);
const mediaRelationships = [];
for (let i = 0; i < relationships.length; i++) {
const relationship = relationships[i];
if (relationship.relation_name === RelationType.MEDIA.name) {
for (let r = 0; r < relationship.mappingRows.length; r++) {
const row = relationship.mappingRows[r].row;
mediaRelationships.push(row);
}
}
}
return mediaRelationships;
}
/**
* Adds a GeoJSON feature to the GeoPackage
* @param {module:geoPackage~GeoPackage} geopackage open GeoPackage object
* @param {object} feature GeoJSON feature to add
* @param {string} tableName name of the table that will store the feature
* @param {boolean} index updates the FeatureTableIndex extension if it exists
*/
addGeoJSONFeatureToGeoPackage(feature: Feature, tableName: string, index = false): number {
const featureDao = this.getFeatureDao(tableName);
const srs = featureDao.srs;
const featureRow = featureDao.newRow();
const geometryData = new GeometryData();
geometryData.setSrsId(srs.srs_id);
if (!(srs.organization === 'EPSG' && srs.organization_coordsys_id === 4326)) {
feature = reproject.reproject(feature, 'EPSG:4326', featureDao.projection);
}
const featureGeometry = typeof feature.geometry === 'string' ? JSON.parse(feature.geometry) : feature.geometry;
if (featureGeometry !== null) {
const geometry = wkx.Geometry.parseGeoJSON(featureGeometry);
geometryData.setGeometry(geometry);
} else {
const temp = wkx.Geometry.parse('POINT EMPTY');
geometryData.setGeometry(temp);
}
featureRow.geometry = geometryData;
for (const propertyKey in feature.properties) {
if (Object.prototype.hasOwnProperty.call(feature.properties, propertyKey)) {
featureRow.setValueWithColumnName(propertyKey, feature.properties[propertyKey]);
}
}
const id = featureDao.create(featureRow);
if (index) {
const fti = featureDao.featureTableIndex;
const tableIndex = fti.tableIndex;
if (!tableIndex) return id;
fti.indexRow(tableIndex, id, geometryData);
fti.updateLastIndexed(tableIndex);
}
return id;
}
addAttributeRow(tableName: string, row: Record<string, DBValue>): number {
const attributeDao = this.getAttributeDao(tableName);
const attributeRow = attributeDao.getRow(row);
return attributeDao.create(attributeRow);
}
/**
* Create a simple attributes table with the properties specified.
* @param {Object[]} properties properties to create columns from
* @param {string} properties.name name of the column
* @param {string} properties.dataType name of the data type
* @return {Promise}
*/
createSimpleAttributesTable(
tableName: string,
properties: { name: string; dataType: string }[],
): SimpleAttributesDao<SimpleAttributesRow> {
const relatedTables = this.relatedTablesExtension;
const columns = [];
let columnNumber = SimpleAttributesTable.numRequiredColumns();
if (properties) {
for (let i = 0; i < properties.length; i++) {
const property = properties[i];
columns.push(
UserColumn.createColumn(columnNumber++, property.name, GeoPackageDataType.fromName(property.dataType), true),
);
}
}
const simpleAttributesTable = SimpleAttributesTable.create(tableName, columns);
relatedTables.createRelatedTable(simpleAttributesTable);
return relatedTables.getSimpleAttributesDao(simpleAttributesTable);
}
addMedia(
tableName: string,
dataBuffer: Buffer,
contentType: string,
additionalProperties?: Record<string, DBValue>,
): number {
const relatedTables = this.relatedTablesExtension;
const mediaDao = relatedTables.getMediaDao(tableName);
const row = mediaDao.newRow();
row.contentType = contentType;
row.data = dataBuffer;
for (const key in additionalProperties) {
row.setValueWithColumnName(key, additionalProperties[key]);
}
return mediaDao.create(row);
}
getRelatedRows(baseTableName: string, baseId: number): ExtendedRelation[] {
return this.relatedTablesExtension.getRelatedRows(baseTableName, baseId);
}
/**
* Create the given {@link module:features/user/featureTable~FeatureTable}
* @param {FeatureTable} featureTable feature table
*/
createUserFeatureTable(featureTable: FeatureTable): { lastInsertRowid: number; changes: number } {
return this.tableCreator.createUserTable(featureTable);
}
createFeatureTableFromProperties(
tableName: string,
properties: { name: string; dataType: string }[],
): boolean {
const geometryColumn = new GeometryColumns();
geometryColumn.table_name = tableName;
geometryColumn.column_name = 'geometry';
geometryColumn.geometry_type_name = 'GEOMETRY';
geometryColumn.z = 0;
geometryColumn.m = 0;
const columns: UserColumn[] = [];
let columnNumber = 0;
columns.push(FeatureColumn.createPrimaryKeyColumn(columnNumber++, 'id'));
columns.push(
FeatureColumn.createGeometryColumn(
columnNumber++,
geometryColumn.column_name,
GeometryType.GEOMETRY,
false,
null,
),
);
for (let i = 0; properties && i < properties.length; i++) {
const property = properties[i] as { name: string; dataType: string };
columns.push(FeatureColumn.createColumn(columnNumber++, property.name, GeoPackageDataType.fromName(property.dataType)));
}
return this.createFeatureTable(tableName, geometryColumn, columns);
}
createFeatureTable(
tableName: string,
geometryColumns?: GeometryColumns,
featureColumns?: UserColumn[] | { name: string; dataType: string }[],
boundingBox: BoundingBox = new BoundingBox(-180, 180, -90, 90),
srsId = 4326,
dataColumns?: DataColumns[],
): boolean {
this.createGeometryColumnsTable();
let geometryColumn;
if (geometryColumns) {
geometryColumn = geometryColumns;
} else {
geometryColumn = new GeometryColumns();
geometryColumn.table_name = tableName;
geometryColumn.column_name = 'geometry';
geometryColumn.geometry_type_name = 'GEOMETRY';
geometryColumn.z = 0;
geometryColumn.m = 0;
}
let columns: FeatureColumn[] = [];
if (featureColumns && featureColumns.length > 0 && featureColumns[0] instanceof UserColumn) {
columns = featureColumns as FeatureColumn[];
} else {
let columnNumber = 0;
columns.push(FeatureColumn.createPrimaryKeyColumn(columnNumber++, 'id'));
columns.push(FeatureColumn.createGeometryColumn(columnNumber++, geometryColumn.column_name, GeometryType.GEOMETRY, false, null));
for (let i = 0; featureColumns && i < featureColumns.length; i++) {
const property = featureColumns[i] as { name: string; dataType: string };
columns.push(FeatureColumn.createColumn(columnNumber++, property.name, GeoPackageDataType.fromName(property.dataType)));
}
}
const featureTable = new FeatureTable(geometryColumn.table_name, geometryColumn.column_name, columns);
this.createUserFeatureTable(featureTable);
const contents = new Contents();
contents.table_name = geometryColumn.table_name;
contents.data_type = ContentsDataType.FEATURES;
contents.identifier = geometryColumn.table_name;
contents.last_change = new Date().toISOString();
contents.min_x = boundingBox.minLongitude;
contents.min_y = boundingBox.minLatitude;
contents.max_x = boundingBox.maxLongitude;
contents.max_y = boundingBox.maxLatitude;
contents.srs_id = srsId;
this.contentsDao.create(contents);
geometryColumn.srs_id = srsId;
this.geometryColumnsDao.create(geometryColumn);
if (dataColumns) {
this.createDataColumns();
const dataColumnsDao = this.dataColumnsDao;
dataColumns.forEach(function(dataColumn) {
dataColumnsDao.create(dataColumn);
});
}
return true;
}
/**
* Create the Tile Matrix Set table if it does not already exist
* @returns {Promise} resolves when the table is created
*/
createTileMatrixSetTable(): boolean {
if (this.tileMatrixSetDao.isTableExists()) {
return true;
}
return this.tableCreator.createTileMatrixSet();
}
/**
* Create the Tile Matrix table if it does not already exist
* @returns {Promise} resolves when the table is created
*/
createTileMatrixTable(): boolean {
if (this.tileMatrixDao.isTableExists()) {
return true;
}
return this.tableCreator.createTileMatrix();
}
/**
* Create the given tile table in this GeoPackage.
*
* @param {module:tiles/user/tileTable~TileTable} tileTable
* @return {object} the result of {@link module:db/geoPackageConnection~GeoPackageConnection#run}
*/
createTileTable(tileTable: TileTable): { lastInsertRowid: number; changes: number } {
return this.tableCreator.createUserTable(tileTable);
}
/**
* Create a new [tile table]{@link module:tiles/user/tileTable~TileTable} in this GeoPackage.
*
* @param {String} tableName tile table name
* @param {BoundingBox} contentsBoundingBox bounding box of the contents table
* @param {Number} contentsSrsId srs id of the contents table
* @param {BoundingBox} tileMatrixSetBoundingBox bounding box of the matrix set
* @param {Number} tileMatrixSetSrsId srs id of the matrix set
* @returns {TileMatrixSet} `Promise` of the created {@link module:tiles/matrixset~TileMatrixSet}
*/
createTileTableWithTableName(
tableName: string,
contentsBoundingBox: BoundingBox,
contentsSrsId: number,
tileMatrixSetBoundingBox: BoundingBox,
tileMatrixSetSrsId: number,
): TileMatrixSet {
const columns = TileTable.createRequiredColumns(0);
const tileTable = new TileTable(tableName, columns);
const contents = new Contents();
contents.table_name = tableName;
contents.data_type = ContentsDataType.TILES;
contents.identifier = tableName;
contents.last_change = new Date().toISOString();
contents.min_x = contentsBoundingBox.minLongitude;
contents.min_y = contentsBoundingBox.minLatitude;
contents.max_x = contentsBoundingBox.maxLongitude;
contents.max_y = contentsBoundingBox.maxLatitude;
contents.srs_id = contentsSrsId;
const tileMatrixSet = new TileMatrixSet();
tileMatrixSet.contents = contents;
tileMatrixSet.srs_id = tileMatrixSetSrsId;
tileMatrixSet.min_x = tileMatrixSetBoundingBox.minLongitude;
tileMatrixSet.min_y = tileMatrixSetBoundingBox.minLatitude;
tileMatrixSet.max_x = tileMatrixSetBoundingBox.maxLongitude;
tileMatrixSet.max_y = tileMatrixSetBoundingBox.maxLatitude;
this.createTileMatrixSetTable();
this.createTileMatrixTable();
this.createTileTable(tileTable);
this.contentsDao.create(contents);
this.tileMatrixSetDao.create(tileMatrixSet);
return tileMatrixSet;
}
/**
* Create the [tables and rows](https://www.geopackage.org/spec121/index.html#tiles)
* necessary to store tiles according to the ubiquitous [XYZ web/slippy-map tiles](https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames) scheme.
* The extent for the [contents table]{@link module:core/contents~Contents} row,
* `contentsBoundingBox`, is [informational only](https://www.geopackage.org/spec121/index.html#gpkg_contents_cols),
* and need not match the [tile matrix set]{@link module:tiles/matrixset~TileMatrixSet}
* extent, `tileMatrixSetBoundingBox`, which should be the precise bounding box
* used to calculate the tile row and column coordinates of all tiles in the
* tile set. The two SRS ID parameters, `contentsSrsId` and `tileMatrixSetSrsId`,
* must match, however. See {@link module:tiles/matrixset~TileMatrixSet} for
* more information about how GeoPackage consumers use the bouding boxes for a
* tile set.
*
* @param {string} tableName the name of the table that will store the tiles
* @param {BoundingBox} contentsBoundingBox the bounds stored in the [`gpkg_contents`]{@link module:core/contents~Contents} table row for the tile matrix set
* @param {SRSRef} contentsSrsId the ID of a [spatial reference system]{@link module:core/srs~SpatialReferenceSystem}; must match `tileMatrixSetSrsId`
* @param {BoundingBox} tileMatrixSetBoundingBox the bounds stored in the [`gpkg_tile_matrix_set`]{@link module:tiles/matrixset~TileMatrixSet} table row
* @param {SRSRef} tileMatrixSetSrsId the ID of a [spatial reference system]{@link module:core/srs~SpatialReferenceSystem}
* for the [tile matrix set](https://www.geopackage.org/spec121/index.html#_tile_matrix_set) table; must match `contentsSrsId`
* @param {number} minZoom the zoom level of the lowest resolution [tile matrix]{@link module:tiles/matrix~TileMatrix} in the tile matrix set
* @param {number} maxZoom the zoom level of the highest resolution [tile matrix]{@link module:tiles/matrix~TileMatrix} in the tile matrix set
* @param tileSize the width and height in pixels of the tile images; defaults to 256
* @returns {TileMatrixSet} the created {@link module:tiles/matrixset~TileMatrixSet} object, or rejects with an `Error`
*
* @todo make `tileMatrixSetSrsId` optional because it always has to be the same anyway
*/
createStandardWebMercatorTileTable(
tableName: string,
contentsBoundingBox: BoundingBox,
contentsSrsId: number,
tileMatrixSetBoundingBox: BoundingBox,
tileMatrixSetSrsId: number,
minZoom: number,
maxZoom: number,
tileSize = 256,
): TileMatrixSet {
const webMercatorSrsId = this.spatialReferenceSystemDao.getByOrganizationAndCoordSysId('EPSG', 3857).srs_id;
if (contentsSrsId !== webMercatorSrsId) {
const srsDao = new SpatialReferenceSystemDao(this);
const from = srsDao.getBySrsId(contentsSrsId).projection;
contentsBoundingBox = contentsBoundingBox.projectBoundingBox(from, 'EPSG:3857');
}
if (tileMatrixSetSrsId !== webMercatorSrsId) {
const srsDao = new SpatialReferenceSystemDao(this);
const from = srsDao.getBySrsId(tileMatrixSetSrsId).projection;
tileMatrixSetBoundingBox = tileMatrixSetBoundingBox.projectBoundingBox(from, 'EPSG:3857');
}
const tileMatrixSet = this.createTileTableWithTableName(
tableName,
contentsBoundingBox,
webMercatorSrsId,
tileMatrixSetBoundingBox,
webMercatorSrsId,
);
this.createStandardWebMercatorTileMatrix(tileMatrixSetBoundingBox, tileMatrixSet, minZoom, maxZoom, tileSize);
return tileMatrixSet;
}
/**
* Create the [tables and rows](https://www.geopackage.org/spec121/index.html#tiles)
* necessary to store tiles according to the ubiquitous [XYZ web/slippy-map tiles](https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames) scheme.
* The extent for the [contents table]{@link module:core/contents~Contents} row,
* `contentsBoundingBox`, is [informational only](https://www.geopackage.org/spec121/index.html#gpkg_contents_cols),
* and need not match the [tile matrix set]{@link module:tiles/matrixset~TileMatrixSet}
* extent, `tileMatrixSetBoundingBox`, which should be the precise bounding box
* used to calculate the tile row and column coordinates of all tiles in the
* tile set.
*
* @param {string} tableName the name of the table that will store the tiles
* @param {BoundingBox} contentsBoundingBox the bounds stored in the [`gpkg_contents`]{@link module:core/contents~Contents} table row for the tile matrix set. MUST BE EPSG:3857
* @param {BoundingBox} tileMatrixSetBoundingBox the bounds stored in the [`gpkg_tile_matrix_set`]{@link module:tiles/matrixset~TileMatrixSet} table row. MUST BE EPSG:3857
* @param {Set<number>} zoomLevels create tile of all resolutions in the set.
* @param tileSize the width and height in pixels of the tile images; defaults to 256
* @returns {Promise} a `Promise` that resolves with the created {@link module:tiles/matrixset~TileMatrixSet} object, or rejects with an `Error`
*
* @todo make `tileMatrixSetSrsId` optional because it always has to be the same anyway
*/
async createStandardWebMercatorTileTableWithZoomLevels(
tableName: string,
contentsBoundingBox: BoundingBox,
tileMatrixSetBoundingBox: BoundingBox,
zoomLevels: Set<number>,
tileSize = 256,
): Promise<TileMatrixSet> {
const webMercatorSrsId = this.spatialReferenceSystemDao.getByOrganizationAndCoordSysId('EPSG', 3857).srs_id;
const tileMatrixSet = await this.createTileTableWithTableName(
tableName,
contentsBoundingBox,
webMercatorSrsId,
tileMatrixSetBoundingBox,
webMercatorSrsId,
);
this.createStandardWebMercatorTileMatrixWithZoomLevels(
tileMatrixSetBoundingBox,
tileMatrixSet,
zoomLevels,
tileSize,
);
return tileMatrixSet;
}
/**
* Create the tables and rows necessary to store tiles in a {@link module:tiles/matrixset~TileMatrixSet}.
* This will create a [tile matrix row]{@link module:tiles/matrix~TileMatrix}
* for every integral zoom level in the range `[minZoom..maxZoom]`.
*
* @param {BoundingBox} epsg3857TileBoundingBox
* @param {TileMatrixSet} tileMatrixSet
* @param {number} minZoom
* @param {number} maxZoom
* @param {number} [tileSize=256] optional tile size in pixels
* @returns {module:geoPackage~GeoPackage} `this` `GeoPackage`
*/
createStandardWebMercatorTileMatrix(
epsg3857TileBoundingBox: BoundingBox,
tileMatrixSet: TileMatrixSet,
minZoom: number,
maxZoom: number,
tileSize = 256,
): GeoPackage {
tileSize = tileSize || 256;
const tileMatrixDao = this.tileMatrixDao;
for (let zoom = minZoom; zoom <= maxZoom; zoom++) {
this.createTileMatrixRow(epsg3857TileBoundingBox, tileMatrixSet, tileMatrixDao, zoom, tileSize);
}
return this;
}
/**
* Create the tables and rows necessary to store tiles in a {@link module:tiles/matrixset~TileMatrixSet}.
* This will create a [tile matrix row]{@link module:tiles/matrix~TileMatrix}
* for every item in the set zoomLevels.
*
* @param {BoundingBox} epsg3857TileBoundingBox
* @param {TileMatrixSet} tileMatrixSet
* @param {Set<number>} zoomLevels
* @param {number} [tileSize=256] optional tile size in pixels
* @returns {module:geoPackage~GeoPackage} `this` `GeoPackage`
*/
createStandardWebMercatorTileMatrixWithZoomLevels(
epsg3857TileBoundingBox: BoundingBox,
tileMatrixSet: TileMatrixSet,
zoomLevels: Set<number>,
tileSize = 256,
): GeoPackage {
tileSize = tileSize || 256;
const tileMatrixDao = this.tileMatrixDao;
zoomLevels.forEach(zoomLevel => {
this.createTileMatrixRow(epsg3857TileBoundingBox, tileMatrixSet, tileMatrixDao, zoomLevel, tileSize);
});
return this;
}
/**
* Adds row to tileMatrixDao
*
* @param {BoundingBox} epsg3857TileBoundingBox
* @param {TileMatrixSet} tileMatrixSet
* @param {TileMatrixDao} tileMatrixDao
* @param {number} zoomLevel
* @param {number} [tileSize=256]
* @returns {number}
* @memberof GeoPackage
*/
createTileMatrixRow(
epsg3857TileBoundingBox: BoundingBox,
tileMatrixSet: TileMatrixSet,
tileMatrixDao: TileMatrixDao,
zoomLevel: number,
tileSize = 256,
): number {
const box = TileBoundingBoxUtils.webMercatorTileBox(epsg3857TileBoundingBox, zoomLevel);
const matrixWidth = box.maxLongitude - box.minLongitude + 1;
const matrixHeight = box.maxLatitude - box.minLatitude + 1;
const pixelXSize =
(epsg3857TileBoundingBox.maxLongitude - epsg3857TileBoundingBox.minLongitude) / matrixWidth / tileSize;
const pixelYSize =
(epsg3857TileBoundingBox.maxLatitude - epsg3857TileBoundingBox.minLatitude) / matrixHeight / tileSize;
const tileMatrix = new TileMatrix();
tileMatrix.table_name = tileMatrixSet.table_name;
tileMatrix.zoom_level = zoomLevel;
tileMatrix.matrix_width = matrixWidth;
tileMatrix.matrix_height = matrixHeight;
tileMatrix.tile_width = tileSize;
tileMatrix.tile_height = tileSize;
tileMatrix.pixel_x_size = pixelXSize;
tileMatrix.pixel_y_size = pixelYSize;
return tileMatrixDao.create(tileMatrix);
}
/**
* Adds a tile to the GeoPackage
* @param {object} tileStream Byte array or Buffer containing the tile bytes
* @param {String} tableName Table name to add the tile to
* @param {Number} zoom zoom level of this tile
* @param {Number} tileRow row of this tile
* @param {Number} tileColumn column of this tile
*/
addTile(tileStream: any, tableName: string, zoom: number, tileRow: number, tileColumn: number): number {
const tileDao = this.getTileDao(tableName);
const newRow = tileDao.newRow();
newRow.zoomLevel = zoom;
newRow.tileColumn = tileColumn;
newRow.tileRow = tileRow;
newRow.tileData = tileStream;
return tileDao.create(newRow);
}
/**
* Gets a tile from the specified table
* @param {string} table name of the table to get the tile from
* @param {Number} zoom zoom level of the tile
* @param {Number} tileRow row of the tile
* @param {Number} tileColumn column of the tile
*
* @todo jsdoc return value
*/
getTileFromTable(table: string, zoom: number, tileRow: number, tileColumn: number): TileRow {
const tileDao = this.getTileDao(table);
return tileDao.queryForTile(tileColumn, tileRow, zoom);
}
/**
* Gets the tiles in the EPSG:4326 bounding box
* @param {module:geoPackage~GeoPackage} geopackage open GeoPackage object
* @param {string} table name of the tile table
* @param {Number} zoom Zoom of the tiles to query for
* @param {Number} west EPSG:4326 western boundary
* @param {Number} east EPSG:4326 eastern boundary
* @param {Number} south EPSG:4326 southern boundary
* @param {Number} north EPSG:4326 northern boundary
*/
getTilesInBoundingBox(
table: string,
zoom: number,
west: number,
east: number,
south: number,
north: number,
): {
columns: {
index: number;
name: string;
max?: number;
min?: number;
notNull?: boolean;
primaryKey?: boolean;
}[];
srs: SpatialReferenceSystem;
tiles: {
tableName: string;
id: number;
minLongitude: number;
maxLongitude: number;
minLatitude: number;
maxLatitude: number;
projection: string;
values: string[];
}[];
west?: string;
east?: string;
south?: string;
north?: string;
zoom?: number;
} {
const tiles = {
columns: [],
srs: undefined,
tiles: [],
west: undefined,
east: undefined,
south: undefined,
north: undefined,
zoom: undefined,
} as {
columns: {
index: number;
name: string;
max: number;
min: number;
notNull: boolean;
primaryKey: boolean;
}[];
srs: SpatialReferenceSystem;
tiles: {
tableName: string;
id: number;
minLongitude: number;
maxLongitude: number;
minLatitude: number;
maxLatitude: number;
projection: string;
values: string[];
}[];
west?: string;
east?: string;
south?: string;
north?: string;
zoom?: number;
};
const tileDao = this.getTileDao(table);
if (zoom < tileDao.minZoom || zoom > tileDao.maxZoom) {
return;
}
for (let i = 0; i < tileDao.table.getUserColumns().getColumns().length; i++) {
const column = tileDao.table.getUserColumns().getColumns()[i];
tiles.columns.push({
index: column.index,
name: column.name,
max: column.max,
min: column.min,
notNull: column.notNull,
primaryKey: column.primaryKey,
});
}
const srs = tileDao.srs;
tiles.srs = srs;
tiles.tiles = [];
const tms = tileDao.tileMatrixSet;
const tm = tileDao.getTileMatrixWithZoomLevel(zoom);
if (!tm) {
return tiles;
}
let mapBoundingBox = new BoundingBox(Math.max(-180, west), Math.min(east, 180), south, north);
tiles.west = Math.max(-180, west).toFixed(2);
tiles.east = Math.min(east, 180).toFixed(2);
tiles.south = south.toFixed(2);
tiles.north = north.toFixed(2);
tiles.zoom = zoom;
mapBoundingBox = mapBoundingBox.projectBoundingBox(
'EPSG:4326',
tileDao.srs.organization.toUpperCase() + ':' + tileDao.srs.organization_coordsys_id,
);
const grid = TileBoundingBoxUtils.getTileGridWithTotalBoundingBox(
tms.boundingBox,
tm.matrix_width,
tm.matrix_height,
mapBoundingBox,
);
const iterator = tileDao.queryByTileGrid(grid, zoom);
for (const row of iterator) {
const tile = {} as {
tableName: string;
id: number;
minLongitude: number;
maxLongitude: number;
minLatitude: number;
maxLatitude: number;
projection: string;
values: string[];
} & Record<string, any>;
tile.tableName = table;
tile.id = row.id;
const tileBB = TileBoundingBoxUtils.getTileBoundingBox(tms.boundingBox, tm, row.tileColumn, row.row);
tile.minLongitude = tileBB.minLongitude;
tile.maxLongitude = tileBB.maxLongitude;
tile.minLatitude = tileBB.minLatitude;
tile.maxLatitude = tileBB.maxLatitude;
tile.projection = tileDao.srs.organization.toUpperCase() + ':' + tileDao.srs.organization_coordsys_id;
tile.values = [];
for (let i = 0; i < tiles.columns.length; i++) {
const value = row.values[tiles.columns[i].name];
if (tiles.columns[i].name === 'tile_data') {
tile.values.push('data');
} else if (value === null || value === 'null') {
tile.values.push('');
} else {
tile.values.push(value.toString());
tile[tiles.columns[i].name] = value;
}
}
tiles.tiles.push(tile);
}
return tiles;
}
/**
* Gets the tiles in the EPSG:4326 bounding box
* @param {module:geoPackage~GeoPackage} geopackage open GeoPackage object
* @param {string} table name of the tile table
* @param {Number} webZoom Zoom of the tiles to query for
* @param {Number} west EPSG:4326 western boundary
* @param {Number} east EPSG:4326 eastern boundary
* @param {Number} south EPSG:4326 southern boundary
* @param {Number} north EPSG:4326 northern boundary
*/
getTilesInBoundingBoxWebZoom(
table: string,
webZoom: number,
west: number,
east: number,
south: number,
north: number,
): {
columns: {
index: number;
name: string;
max?: number;
min?: number;
notNull?: boolean;
primaryKey?: boolean;
}[];
srs: SpatialReferenceSystem;
tiles: {
tableName: string;
id: number;
minLongitude: number;
maxLongitude: number;
minLatitude: number;
maxLatitude: number;
projection: string;
values: string[];
}[];
west?: string;
east?: string;
south?: string;
north?: string;
zoom?: number;
} {
const tiles = {
columns: [],
srs: undefined,
tiles: [],
west: undefined,
east: undefined,
south: undefined,
north: undefined,
zoom: undefined,
} as {
columns: {
index: number;
name: string;
max: number;
min: number;
notNull: boolean;
primaryKey: boolean;
}[];
srs: SpatialReferenceSystem;
tiles: {
tableName: string;
id: number;
minLongitude: number;
maxLongitude: number;
minLatitude: number;
maxLatitude: number;
projection: string;
values: string[];
}[];
west?: string;
east?: string;
south?: string;
north?: string;
zoom?: number;
};
const tileDao = this.getTileDao(table);
if (webZoom < tileDao.minWebMapZoom || webZoom > tileDao.maxWebMapZoom) {
return;
}
tiles.columns = [];
for (let i = 0; i < tileDao.table.getUserColumns().getColumns().length; i++) {
const column = tileDao.table.getUserColumns().getColumns()[i];
tiles.columns.push({
index: column.index,
name: column.name,
max: column.max,
min: column.min,
notNull: column.notNull,
primaryKey: column.primaryKey,
});
}
const srs = tileDao.srs;
tiles.srs = srs;
tiles.tiles = [];
const zoom = tileDao.webZoomToGeoPackageZoom(webZoom);
const tms = tileDao.tileMatrixSet;
const tm = tileDao.getTileMatrixWithZoomLevel(zoom);
if (!tm) {
return tiles;
}
let mapBoundingBox = new BoundingBox(Math.max(-180, west), Math.min(east, 180), south, north);
tiles.west = Math.max(-180, west).toFixed(2);
tiles.east = Math.min(east, 180).toFixed(2);
tiles.south = south.toFixed(2);
tiles.north = north.toFixed(2);
tiles.zoom = zoom;
mapBoundingBox = mapBoundingBox.projectBoundingBox(
'EPSG:4326',
tileDao.srs.organization.toUpperCase() + ':' + tileDao.srs.organization_coordsys_id,
);
const grid = TileBoundingBoxUtils.getTileGridWithTotalBoundingBox(
tms.boundingBox,
tm.matrix_width,
tm.matrix_height,
mapBoundingBox,
);
const iterator = tileDao.queryByTileGrid(grid, zoom);
for (const row of iterator) {
const tile = {
tableName: undefined,
id: undefined,
minLongitude: undefined,
maxLongitude: undefined,
minLatitude: undefined,
maxLatitude: undefined,
projection: undefined as string,
values: [],
} as {
tableName: string;
id: number;
minLongitude: number;
maxLongitude: number;
minLatitude: number;
maxLatitude: number;
projection: string;
values: any[];
} & Record<string, any>;
tile.tableName = table;
tile.id = row.id;
const tileBB = TileBoundingBoxUtils.getTileBoundingBox(tms.boundingBox, tm, row.tileColumn, row.row);
tile.minLongitude = tileBB.minLongitude;
tile.maxLongitude = tileBB.maxLongitude;
tile.minLatitude = tileBB.minLatitude;
tile.maxLatitude = tileBB.maxLatitude;
tile.projection = tileDao.srs.organization.toUpperCase() + ':' + tileDao.srs.organization_coordsys_id;
tile.values = [];
for (let i = 0; i < tiles.columns.length; i++) {
const value = row.values[tiles.columns[i].name];
if (tiles.columns[i].name === 'tile_data') {
tile.values.push('data');
} else if (value === null || value === 'null') {
tile.values.push('');
} else {
tile.values.push(value.toString());
tile[tiles.columns[i].name] = value;
}
}
tiles.tiles.push(tile);
}
return tiles;
}
async getFeatureTileFromXYZ(
table: string,
x: number,
y: number,
z: number,
width: number,
height: number,
): Promise<any> {
x = Number(x);
y = Number(y);
z = Number(z);
width = Number(width);
height = Number(height);
const featureDao = this.getFeatureDao(table);
if (!featureDao) return;
const ft = new FeatureTiles(featureDao, width, height);
return ft.drawTile(x, y, z);
}
getClosestFeatureInXYZTile(
table: string,
x: number,
y: number,
z: number,
latitude: number,
longitude: number,
): Feature & ClosestFeature {
x = Number(x);
y = Number(y);
z = Number(z);
const featureDao = this.getFeatureDao(table);
if (!featureDao) return;
const ft = new FeatureTiles(featureDao, 256, 256);
const tileCount = ft.getFeatureCountXYZ(x, y, z);
let boundingBox = TileBoundingBoxUtils.getWebMercatorBoundingBoxFromXYZ(x, y, z);
boundingBox = boundingBox.projectBoundingBox('EPSG:3857', 'EPSG:4326');
if (tileCount > 10000) {
// too many, send back the entire tile
// add the goepackage name and table
const gj = boundingBox.toGeoJSON() as Feature & ClosestFeature;
gj.feature_count = tileCount;
gj.coverage = true;
gj.gp_table = table;
gj.gp_name = this.name;
return gj;
}
const ne = [boundingBox.maxLongitude, boundingBox.maxLatitude];
const sw = [boundingBox.minLongitude, boundingBox.minLatitude];
const width = ne[0] - sw[0];
const widthPerPixel = width / 256;
const tolerance = 10 * widthPerPixel;
boundingBox.maxLongitude = longitude + tolerance;
boundingBox.minLongitude = longitude - tolerance;
boundingBox.maxLatitude = latitude + tolerance;
boundingBox.minLatitude = latitude - tolerance;
const iterator = featureDao.queryForGeoJSONIndexedFeaturesWithBoundingBox(boundingBox);
const features = [];
let closestDistance = 100000000000;
let closest: ClosestFeature & Feature;
const centerPoint = helpers.point([longitude, latitude]);
for (const feature of iterator) {
feature.type = 'Feature';
const distance = GeoPackage.determineDistance(centerPoint.geometry, feature);
if (distance < closestDistance) {
closest = feature as ClosestFeature & Feature;
closestDistance = distance;
} else if (distance === closestDistance && closest.geometry.type !== 'Point') {
closest = feature as ClosestFeature & Feature;
closestDistance = distance;
}
features.push(feature);
}
if (closest) {
closest.gp_table = table;
closest.gp_name = this.name;
closest.distance = closestDistance;
}
return closest;
}
static determineDistance(point: Point, feature: Feature | FeatureCollection): number {
if (feature.type === 'FeatureCollection') {
feature.features.forEach(feature => {
GeoPackage.determineDistance(point, feature);
});
} else {
const geometry: Geometry = feature.geometry;
if (geometry.type === 'Point') {
return pointDistance(point, geometry);
}
if (geometry.type === 'LineString') {
return this.determineDistanceFromLine(point, geometry);
}
if (geometry.type === 'MultiLineString') {
let distance = Number.MAX_SAFE_INTEGER;
geometry.coordinates.forEach(lineStringCoordinate => {
const lineString: Feature = helpers.lineString(lineStringCoordinate);
distance = Math.min(distance, GeoPackage.determineDistance(point, lineString));
});
return distance;
}
if (geometry.type === 'Polygon') {
return GeoPackage.determineDistanceFromPolygon(point, geometry);
}
if (geometry.type === 'MultiPolygon') {
return GeoPackage.determineDistanceFromPolygon(point, geometry);
}
return Number.MAX_SAFE_INTEGER;
}
}
static determineDistanceFromLine(point: Point, lineString: LineString): number {
return pointToLineDistance(point, lineString);
}
static determineDistanceFromPolygon(point: Point, polygon: Polygon | MultiPolygon): number {
if (booleanPointInPolygon(point, polygon)) {
return 0;
}
return GeoPackage.determineDistance(point, polygonToLine(polygon));
}
/**
* Create the Data Columns table if it does not already exist
*/
createDataColumns(): boolean {
if (this.dataColumnsDao.isTableExists()) {
return true;
}
return this.tableCreator.createDataColumns();
}
/**
* Create the Data Column Constraints table if it does not already exist
*/
createDataColumnConstraintsTable(): boolean {
if (this.dataColumnConstraintsDao.isTableExists()) {
return true;
}
return this.tableCreator.createDataColumnConstraints();
}
createMetadataTable(): boolean {
if (this.metadataDao.isTableExists()) {
return true;
}
return this.tableCreator.createMetadata();
}
createMetadataReferenceTable(): boolean {
if (this.metadataReferenceDao.isTableExists()) {
return true;
}
return this.tableCreator.createMetadataReference();
}
createExtensionTable(): boolean {
if (this.extensionDao.isTableExists()) {
return true;
}
return this.tableCreator.createExtensions();
}
createTableIndexTable(): boolean {
if (this.tableIndexDao.isTableExists()) {
return true;
}
return this.tableCreator.createTableIndex();
}
createGeometryIndexTable(): boolean {
const dao = this.getGeometryIndexDao(null);
if (dao.isTableExists()) {
return true;
}
return this.tableCreator.createGeometryIndex();
}
createStyleMappingTable(
tableName: string,
columns?: UserColumn[],
dataColumns?: DataColumns[],
): boolean {
const attributeTable = new StyleMappingTable(tableName, columns, null);
this.tableCreator.createUserTable(attributeTable);
const contents = new Contents();
contents.table_name = tableName;
contents.data_type = ContentsDataType.ATTRIBUTES;
contents.identifier = tableName;
contents.last_change = new Date().toISOString();
this.contentsDao.create(contents);
if (dataColumns) {
this.createDataColumns();
const dataColumnsDao = this.dataColumnsDao;
dataColumns.forEach(function(dataColumn) {
dataColumnsDao.create(dataColumn);
});
}
return true;
}
/**
* Get the application id of the GeoPackage
* @returns {string} application id
*/
getApplicationId(): string {
return this.database.getApplicationId();
}
static createDataColumnMap(featureDao: FeatureDao<FeatureRow>): ColumnMap {
const columnMap: Record<string, any> = {};
const dcd = new DataColumnsDao(featureDao.geoPackage);
featureDao.table.getUserColumns().getColumns().forEach(
function(column: UserColumn): void {
const dataColumn = dcd.getDataColumns(featureDao.table.getTableName(), column.name);
columnMap[column.name] = {
index: column.index,
name: column.name,
max: column.max,
min: column.min,
notNull: column.notNull,
primaryKey: column.primaryKey,
dataType: column.dataType ? GeoPackageDataType.nameFromType(column.dataType) : '',
displayName: dataColumn && dataColumn.name ? dataColumn.name : column.name,
dataColumn: dataColumn,
};
}.bind(this),
);
return columnMap;
}
iterateGeoJSONFeatures(
tableName: string,
boundingBox?: BoundingBox,
): IterableIterator<Feature> & { srs: SpatialReferenceSystem; featureDao: FeatureDao<FeatureRow> } {
const featureDao = this.getFeatureDao(tableName);
return featureDao.queryForGeoJSONIndexedFeaturesWithBoundingBox(boundingBox);
}
/**
* Gets a GeoJSON feature from the table by id
* @param {module:geoPackage~GeoPackage} geopackage open GeoPackage object
* @param {string} table name of the table to get the feature from
* @param {Number} featureId ID of the feature
*/
getFeature(table: string, featureId: number): Feature {
const featureDao = this.getFeatureDao(table);
const srs = featureDao.srs;
let feature = featureDao.queryForId(featureId) as FeatureRow;
if (!feature) {
let features = featureDao.queryForAllEq('_feature_id', featureId);
if (features.length) {
feature = featureDao.getRow(features[0]) as FeatureRow;
} else {
features = featureDao.queryForAllEq('_properties_id', featureId);
if (features.length) {
feature = featureDao.getRow(features[0]) as FeatureRow;
}
}
}
if (feature) {
return GeoPackage.parseFeatureRowIntoGeoJSON(feature, srs);
}
}
// eslint-disable-next-line complexity
static parseFeatureRowIntoGeoJSON(
featureRow: FeatureRow,
srs: SpatialReferenceSystem,
columnMap?: ColumnMap,
): Feature {
const geoJson: Feature = {
type: 'Feature',
properties: {},
id: undefined,
geometry: undefined,
};
const geometry = featureRow.geometry;
if (geometry && geometry.geometry) {
let geoJsonGeom = geometry.geometry.toGeoJSON() as Geometry;
if (
srs.definition &&
srs.definition !== 'undefined' &&
srs.organization.toUpperCase() + ':' + srs.organization_coordsys_id !== 'EPSG:4326'
) {
geoJsonGeom = reproject.reproject(geoJsonGeom, srs.projection, 'EPSG:4326');
}
geoJson.geometry = geoJsonGeom;
}
for (const key in featureRow.values) {
if (
Object.prototype.hasOwnProperty.call(featureRow.values, key) &&
key !== featureRow.geometryColumn.name &&
key !== 'id'
) {
if (key.toLowerCase() === '_feature_id') {
geoJson.id = featureRow.values[key] as string | number;
} else if (key.toLowerCase() === '_properties_id') {
geoJson.properties[key.substring(12)] = featureRow.values[key];
} else if (columnMap && columnMap[key]) {
geoJson.properties[columnMap[key].displayName] = featureRow.values[key];
} else {
geoJson.properties[key] = featureRow.values[key];
}
} else if (featureRow.geometryColumn.name === key) {
// geoJson.properties[key] = geometry && !geometry.geometryError ? 'Valid' : geometry.geometryError;
}
}
geoJson.id = geoJson.id || featureRow.id;
return geoJson;
}
/**
* Gets the features in the EPSG:3857 tile
* @param {string} table name of the feature table
* @param {Number} x x tile number
* @param {Number} y y tile number
* @param {Number} z z tile number
* @param {Boolean} [skipVerification] skip the extra verification to determine if the feature really is within the tile
*/
async getGeoJSONFeaturesInTile(
table: string,
x: number,
y: number,
z: number,
skipVerification = false,
): Promise<Feature[]> {
const webMercatorBoundingBox = TileBoundingBoxUtils.getWebMercatorBoundingBoxFromXYZ(x, y, z);
const bb = webMercatorBoundingBox.projectBoundingBox('EPSG:3857', 'EPSG:4326');
await this.indexFeatureTable(table);
const featureDao = this.getFeatureDao(table);
if (!featureDao) return;
const features = [];
const iterator = featureDao.queryForGeoJSONIndexedFeaturesWithBoundingBox(bb, skipVerification);
for (const feature of iterator) {
features.push(feature);
}
return features;
}
/**
* Gets the features in the EPSG:4326 bounding box
* @param {string} table name of the feature table
* @param {Number} west EPSG:4326 western boundary
* @param {Number} east EPSG:4326 eastern boundary
* @param {Number} south EPSG:4326 southern boundary
* @param {Number} north EPSG:4326 northern boundary
*/
async getFeaturesInBoundingBox(
table: string,
west: number,
east: number,
south: number,
north: number,
): Promise<IterableIterator<FeatureRow>> {
await this.indexFeatureTable(table);
const featureDao = this.getFeatureDao(table);
if (!featureDao) throw new Error('Unable to find table ' + table);
const bb = new BoundingBox(west, east, south, north);
const iterator = featureDao.queryIndexedFeaturesWithBoundingBox(bb);
return iterator;
}
/**
* Get the standard 3857 XYZ tile from the GeoPackage. If a canvas is provided, the tile will be drawn in the canvas
* @param {string} table name of the table containing the tiles
* @param {Number} x x index of the tile
* @param {Number} y y index of the tile
* @param {Number} z zoom level of the tile
* @param {Number} width width of the resulting tile
* @param {Number} height height of the resulting tile
* @param {any} canvas canvas element to draw the tile into
*/
async xyzTile(table: string, x: number, y: number, z: number, width = 256, height = 256, canvas?: any): Promise<any> {
width = Number(width);
height = Number(height);
const tileDao = this.getTileDao(table);
const retriever = new GeoPackageTileRetriever(tileDao, width, height);
if (this.getTileScalingExtension(table).has()) {
const tileScaling = this.getTileScalingExtension(table).dao.queryForTableName(table);
if (tileScaling) {
retriever.setScaling(tileScaling);
}
}
if (!canvas) {
return retriever.getTile(x, y, z);
} else {
return retriever.drawTileIn(x, y, z, canvas);
}
}
/**
* Get the standard 3857 XYZ tile from the GeoPackage. If a canvas is provided, the tile will be drawn in the canvas
* @param {string} table name of the table containing the tiles
* @param {Number} x x index of the tile
* @param {Number} y y index of the tile
* @param {Number} z zoom level of the tile
* @param {Number} width width of the resulting tile
* @param {Number} height height of the resulting tile
* @param {any} canvas canvas element to draw the tile into
*/
async xyzTileScaled(
table: string,
x: number,
y: number,
z: number,
width = 256,
height = 256,
canvas?: any,
zoomIn?: 2,
zoomOut?: 2,
): Promise<any> {
width = Number(width);
height = Number(height);
const tileDao = this.getTileDao(table);
const retriever = new GeoPackageTileRetriever(tileDao, width, height);
await this.getTileScalingExtension(table).getOrCreateExtension();
const tileScaling = this.getTileScalingExtension(table).dao.queryForTableName(table);
if (tileScaling) {
retriever.setScaling(tileScaling);
} else {
// } else {
const tileScaling = new TileScaling();
tileScaling.zoom_in = zoomIn;
tileScaling.zoom_out = zoomOut;
tileScaling.table_name = table;
tileScaling.scaling_type = TileScalingType.CLOSEST_IN_OUT;
const tileScalingExtension = this.getTileScalingExtension(table);
// await tileScalingExtension.getOrCreateExtension();
tileScalingExtension.createOrUpdate(tileScaling);
retriever.setScaling(tileScaling);
}
if (!canvas) {
return retriever.getTile(x, y, z);
} else {
return retriever.drawTileIn(x, y, z, canvas);
}
}
/**
* Draws a tile projected into the specified projection, bounded by the specified by the bounds in EPSG:4326 into the canvas or the image is returned if no canvas is passed in
* @param {string} table name of the table containing the tiles
* @param {Number} minLat minimum latitude bounds of tile
* @param {Number} minLon minimum longitude bounds of tile
* @param {Number} maxLat maximum latitude bounds of tile
* @param {Number} maxLon maximum longitude bounds of tile
* @param {Number} z zoom level of the tile
* @param {Number} width width of the resulting tile
* @param {Number} height height of the resulting tile
* @param {any} canvas canvas element to draw the tile into
*/
async projectedTile(
table: string,
minLat: number,
minLon: number,
maxLat: number,
maxLon: number,
z: number,
projection: 'EPSG:4326',
width = 256,
height = 256,
canvas?: any,
): Promise<any> {
const tileDao = this.getTileDao(table);
const retriever = new GeoPackageTileRetriever(tileDao, width, height);
const bounds = new BoundingBox(minLon, maxLon, minLat, maxLat);
return retriever.getTileWithWgs84BoundsInProjection(bounds, z, projection, canvas);
}
getInfoForTable(tableDao: TileDao<TileRow> | FeatureDao<FeatureRow>): any {
const info = {
tableName: tableDao.table_name,
tableType: tableDao.table.tableType,
count: tableDao.getCount(),
geometryColumns: undefined as {
tableName: string;
geometryColumn: string;
geometryTypeName: string;
z?: number;
m?: number;
},
minZoom: undefined as number,
maxZoom: undefined as number,
minWebMapZoom: undefined as number,
maxWebMapZoom: undefined as number,
zoomLevels: undefined as number,
tileMatrixSet: undefined as {
srsId: number;
minX: number;
maxX: number;
minY: number;
maxY: number;
},
contents: undefined as {
tableName: string;
dataType: string;
identifier: string;
description: string;
lastChange: string;
minX: number;
maxX: number;
minY: number;
maxY: number;
srs: {
name: string;
id: number;
organization: string;
organization_coordsys_id: number;
definition: string;
description: string;
};
},
srs: undefined as {
name: string;
id: number;
organization: string;
organization_coordsys_id: number;
definition: string;
description: string;
},
columns: undefined as {
index: number;
name: string;
max?: number;
min?: number;
notNull?: boolean;
primaryKey?: boolean;
dataType?: GeoPackageDataType;
displayName: string;
dataColumn?: DataColumns;
}[],
columnMap: undefined as ColumnMap,
};
if (tableDao instanceof FeatureDao) {
info.geometryColumns = {
tableName: tableDao.geometryColumns.table_name,
geometryColumn: tableDao.geometryColumns.column_name,
geometryTypeName: tableDao.geometryColumns.geometry_type_name,
z: tableDao.geometryColumns.z,
m: tableDao.geometryColumns.m,
};
}
if (tableDao instanceof TileDao) {
info.minZoom = tableDao.minZoom;
info.maxZoom = tableDao.maxZoom;
info.minWebMapZoom = tableDao.minWebMapZoom;
info.maxWebMapZoom = tableDao.maxWebMapZoom;
info.zoomLevels = tableDao.tileMatrices.length;
}
let contents: Contents;
if (tableDao instanceof FeatureDao) {
contents = this.geometryColumnsDao.getContents(tableDao.geometryColumns);
} else if (tableDao instanceof TileDao) {
contents = this.tileMatrixSetDao.getContents(tableDao.tileMatrixSet);
info.tileMatrixSet = {
srsId: tableDao.tileMatrixSet.srs_id,
minX: tableDao.tileMatrixSet.min_x,
maxX: tableDao.tileMatrixSet.max_x,
minY: tableDao.tileMatrixSet.min_y,
maxY: tableDao.tileMatrixSet.max_y,
};
}
const contentsSrs = this.contentsDao.getSrs(contents);
info.contents = {
tableName: contents.table_name,
dataType: contents.data_type,
identifier: contents.identifier,
description: contents.description,
lastChange: contents.last_change,
minX: contents.min_x,
maxX: contents.max_x,
minY: contents.min_y,
maxY: contents.max_y,
srs: {
name: contentsSrs.srs_name,
id: contentsSrs.srs_id,
organization: contentsSrs.organization,
organization_coordsys_id: contentsSrs.organization_coordsys_id,
definition: contentsSrs.definition,
description: contentsSrs.description,
},
};
info.contents.srs = {
name: contentsSrs.srs_name,
id: contentsSrs.srs_id,
organization: contentsSrs.organization,
organization_coordsys_id: contentsSrs.organization_coordsys_id,
definition: contentsSrs.definition,
description: contentsSrs.description,
};
const srs = tableDao.srs;
info.srs = {
name: srs.srs_name,
id: srs.srs_id,
organization: srs.organization,
organization_coordsys_id: srs.organization_coordsys_id,
definition: srs.definition,
description: srs.description,
};
info.columns = [];
info.columnMap = {};
const dcd = this.dataColumnsDao;
tableDao.table.getUserColumns().getColumns().forEach(
function(column: UserColumn): any {
const dataColumn = dcd.getDataColumns(tableDao.table.getTableName(), column.name);
info.columns.push({
index: column.index,
name: column.name,
max: column.max,
min: column.min,
notNull: column.notNull,
primaryKey: column.primaryKey,
dataType: column.dataType,
displayName: dataColumn && dataColumn.name ? dataColumn.name : column.name,
dataColumn: dataColumn,
});
info.columnMap[column.name] = info.columns[info.columns.length - 1];
}.bind(this),
);
return info;
}
static loadProjections(items: string[]): void {
if (!items) throw new Error('Invalid array of projections');
for (let i = 0; i < items.length; i++) {
if (!anyDefs[items[i]]) throw new Error('Projection not found');
this.addProjection(items[i], anyDefs[items[i]]);
}
}
static addProjection(name: string, definition: string): void {
if (!name || !definition) throw new Error('Invalid projection name/definition');
proj4.defs('' + name, '' + definition);
}
static hasProjection(name: string): proj4.ProjectionDefinition {
return proj4.defs('' + name);
}
renameTable (tableName, newTableName) {
const tableDataType = this.getTableDataType(tableName);
if (tableDataType !== null && tableDataType !== undefined) {
this.copyTableAndExtensions(tableName, newTableName);
this.deleteTable(tableName);
} else {
AlterTable.renameTable(this.connection, tableName, newTableName)
}
}
copyTableAndExtensions (tableName, newTableName) {
this.copyTable(tableName, newTableName, true, true);
}
copyTableNoExtensions (tableName, newTableName) {
this.copyTable(tableName, newTableName, true, false);
}
copyTableAsEmpty (tableName, newTableName) {
this.copyTable(tableName, newTableName, false, false)
}
getTableDataType (tableName) {
let tableType = null;
const contentsDao = this.contentsDao;
const contents = contentsDao.queryForId(tableName);
if (contents !== null && contents !== undefined) {
tableType = contents.data_type;
}
return tableType;
}
/**
* Copy the table
* @param tableName table name
* @param newTableName new table name
* @param transferContent transfer content flag
* @param extensions extensions copy flag
*/
copyTable (tableName, newTableName, transferContent, extensions) {
const dataType = this.getTableDataType(tableName);
if (dataType !== null && dataType !== undefined) {
switch (dataType) {
case ContentsDataType.ATTRIBUTES:
this.copyAttributeTable(tableName, newTableName, transferContent);
break;
case ContentsDataType.FEATURES:
this.copyFeatureTable(tableName, newTableName, transferContent);
break;
case ContentsDataType.TILES:
this.copyTileTable(tableName, newTableName, transferContent);
break;
default:
throw new Error('Unsupported data type: ' + dataType);
}
} else {
this.copyUserTable(tableName, newTableName, transferContent, false);
}
// Copy extensions
if (extensions) {
GeoPackageExtensions.copyTableExtensions(this, tableName, newTableName)
}
}
/**
* Copy the attribute table
* @param tableName table name
* @param newTableName new table name
* @param transferContent transfer content flag
*/
copyAttributeTable (tableName, newTableName, transferContent) {
this.copyUserTable(tableName, newTableName, transferContent);
}
/**
* Copy the feature table
* @param tableName table name
* @param newTableName new table name
* @param transferContent transfer content flag
*/
copyFeatureTable (tableName, newTableName, transferContent) {
const geometryColumnsDao = this.geometryColumnsDao;
let geometryColumns = null;
try {
geometryColumns = geometryColumnsDao.queryForTableName(tableName);
} catch (e) {
throw new Error('Failed to retrieve table geometry columns: ' + tableName)
}
if (geometryColumns === null || geometryColumns === undefined) {
throw new Error('No geometry columns for table: ' + tableName);
}
const contents = this.copyUserTable(tableName, newTableName, transferContent);
geometryColumns.setContents(contents);
try {
geometryColumnsDao.create(geometryColumns);
} catch (e) {
throw new Error('Failed to create geometry columns for feature table: ' + newTableName);
}
}
/**
* Copy the tile table
* @param tableName table name
* @param newTableName new table name
* @param transferContent transfer content flag
*/
copyTileTable(tableName, newTableName, transferContent) {
const tileMatrixSetDao = this.tileMatrixSetDao;
let tileMatrixSet = null;
try {
tileMatrixSet = tileMatrixSetDao.queryForId(tableName);
} catch (e) {
throw new Error('Failed to retrieve table tile matrix set: ' + tableName);
}
if (tileMatrixSet == null) {
throw new Error('No tile matrix set for table: ' + tableName);
}
const tileMatrixDao = this.tileMatrixDao;
let tileMatrixes = null;
try {
tileMatrixes = tileMatrixDao.queryForAllEq(TileMatrixDao.COLUMN_TABLE_NAME, tableName);
} catch (e) {
throw new Error('Failed to retrieve table tile matrixes: ' + tableName);
}
let contents = this.copyUserTable(tableName, newTableName, transferContent);
tileMatrixSet.setContents(contents);
try {
tileMatrixSetDao.create(tileMatrixSet);
} catch (e) {
throw new Error('Failed to create tile matrix set for tile table: ' + newTableName);
}
tileMatrixes.forEach(tileMatrix => {
tileMatrix.setContents(contents);
try {
tileMatrixDao.create(tileMatrix);
} catch (e) {
throw new Error('Failed to create tile matrix for tile table: ' + newTableName);
}
});
}
/**
* Copy the user table
*
* @param tableName table name
* @param newTableName new table name
* @param transferContent transfer user table content flag
* @param validateContents true to validate a contents was copied
* @return copied contents
* @since 3.3.0
*/
copyUserTable(tableName, newTableName, transferContent, validateContents = true) {
AlterTable.copyTableWithName(this.database, tableName, newTableName, transferContent);
let contents = this.copyContents(tableName, newTableName);
if ((contents === null || contents === undefined) && validateContents) {
throw new Error('No table contents found for table: ' + tableName);
}
return contents;
}
/**
* Copy the contents
* @param tableName table name
* @param newTableName new table name
* @return copied contents
*/
copyContents(tableName: string, newTableName: string): Contents {
let contents = this.getTableContents(tableName);
if (contents !== null && contents !== undefined) {
contents.table_name = newTableName;
contents.identifier = newTableName;
try {
this.contentsDao.create(contents);
} catch (e) {
throw new Error('Failed to create contents for table: ' + newTableName + ', copied from table: ' + tableName);
}
}
return contents;
}
} | the_stack |
import React, {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useRef,
useState,
} from 'react';
import { assert, translate as $t, useKresusState } from '../../helpers';
import { get } from '../../store';
import { DEFAULT_CHART_PERIOD, DEFAULT_CHART_TYPE } from '../../../shared/settings';
import DiscoveryMessage from '../ui/discovery-message';
import BarChart from './category-barchart';
import PieChart, { PieChartWithHelp } from './category-pie-chart';
import AmountKindSelect from './amount-select';
import { Category, Operation } from '../../models';
import { Hideable } from './hidable-chart';
import { DateRange, Form, PredefinedDateRanges } from '../ui';
import moment from 'moment';
interface AllPieChartsProps {
getCategoryById: (id: number) => Category;
rawIncomeOps: Operation[];
rawSpendingOps: Operation[];
netIncomeOps: Operation[];
netSpendingOps: Operation[];
}
const AllPieCharts = forwardRef<Hideable, AllPieChartsProps>((props, ref) => {
const refRawIncome = React.createRef<Hideable>();
const refRawSpendings = React.createRef<Hideable>();
const refNetIncome = React.createRef<Hideable>();
const refNetSpendings = React.createRef<Hideable>();
useImperativeHandle(ref, () => ({
show() {
assert(!!refRawIncome.current, 'must be mounted');
assert(!!refRawSpendings.current, 'must be mounted');
assert(!!refNetIncome.current, 'must be mounted');
assert(!!refNetSpendings.current, 'must be mounted');
refRawIncome.current.show();
refRawSpendings.current.show();
refNetIncome.current.show();
refNetSpendings.current.show();
},
hide() {
assert(!!refRawIncome.current, 'must be mounted');
assert(!!refRawSpendings.current, 'must be mounted');
assert(!!refNetIncome.current, 'must be mounted');
assert(!!refNetSpendings.current, 'must be mounted');
refRawIncome.current.hide();
refRawSpendings.current.hide();
refNetIncome.current.hide();
refNetSpendings.current.hide();
},
}));
return (
<div className="pie-charts">
<PieChartWithHelp
chartId="rawIncomePie"
helpKey="client.charts.help_raw_income"
titleKey="client.charts.raw_income"
getCategoryById={props.getCategoryById}
transactions={props.rawIncomeOps}
ref={refRawIncome}
/>
<PieChartWithHelp
chartId="rawSpendingsPie"
helpKey="client.charts.help_raw_spendings"
titleKey="client.charts.raw_spendings"
getCategoryById={props.getCategoryById}
transactions={props.rawSpendingOps}
ref={refRawSpendings}
/>
<PieChartWithHelp
chartId="netIncomePie"
helpKey="client.charts.help_net_income"
titleKey="client.charts.net_income"
getCategoryById={props.getCategoryById}
transactions={props.netIncomeOps}
ref={refNetIncome}
/>
<PieChartWithHelp
chartId="netSpendingsPie"
helpKey="client.charts.help_net_spendings"
titleKey="client.charts.net_spendings"
getCategoryById={props.getCategoryById}
transactions={props.netSpendingOps}
ref={refNetSpendings}
/>
</div>
);
});
const CategorySection = (props: { transactions: Operation[] }) => {
const defaultAmountKind = useKresusState(state => get.setting(state, DEFAULT_CHART_TYPE));
const defaultPeriod = useKresusState(state => get.setting(state, DEFAULT_CHART_PERIOD));
const getCategoryById = useKresusState(state => (id: number) => get.categoryById(state, id));
const [amountKind, setAmountKind] = useState(defaultAmountKind);
// What to display in the date range picker?
const [dateRange, setDateRange] = useState<[Date, Date] | [Date] | undefined>(undefined);
// How to filter transactions, based on the value in the date range picker?
const [filterDate, setFilterDate] = useState<null | ((t: Operation) => boolean)>(null);
const onChangePeriod = useCallback(
(dates: [Date, Date?] | null) => {
if (dates === null) {
setDateRange(undefined);
setFilterDate(null);
} else if (dates.length === 2) {
if (typeof dates[1] === 'undefined') {
setDateRange([dates[0]]);
setFilterDate(
() => (t: Operation) =>
t.date.setHours(0, 0, 0, 0) === dates[0].setHours(0, 0, 0, 0)
);
} else {
setDateRange([dates[0], dates[1]]);
// Note: When React sees a functor, React calls it; hence the
// double function-wrapping here.
const d1 = dates[1];
setFilterDate(() => (t: Operation) => t.date >= dates[0] && t.date <= d1);
}
}
},
[setDateRange, setFilterDate]
);
// Only on mount.
useEffect(() => {
switch (defaultPeriod) {
case 'all':
return; // do nothing
case 'current-month':
return onChangePeriod([
moment().startOf('month').toDate(),
moment().endOf('month').toDate(),
]);
case 'last-month':
return onChangePeriod([
moment().subtract(1, 'month').startOf('month').toDate(),
moment().subtract(1, 'month').endOf('month').toDate(),
]);
case '3-months':
return onChangePeriod([
moment().subtract(2, 'month').startOf('month').toDate(),
moment().endOf('month').toDate(),
]);
case '6-months':
return onChangePeriod([
moment().subtract(5, 'month').startOf('month').toDate(),
moment().endOf('month').toDate(),
]);
case 'current-year':
return onChangePeriod([
moment().startOf('year').toDate(),
moment().endOf('year').toDate(),
]);
case 'last-year':
return onChangePeriod([
moment().subtract(1, 'year').startOf('year').toDate(),
moment().subtract(1, 'year').endOf('year').toDate(),
]);
default:
assert(false, 'unknown period');
}
}, [onChangePeriod, defaultPeriod]);
const refBarchart = useRef<Hideable>(null);
const refPiecharts = useRef<Hideable>(null);
const handleShowAll = useCallback(() => {
assert(!!refBarchart.current, 'component mounted');
assert(!!refPiecharts.current, 'component mounted');
refBarchart.current.show();
refPiecharts.current.show();
}, []);
const handleHideAll = useCallback(() => {
assert(!!refBarchart.current, 'component mounted');
assert(!!refPiecharts.current, 'component mounted');
refBarchart.current.hide();
refPiecharts.current.hide();
}, []);
let allTransactions = props.transactions;
// Filter by kind.
const onlyPositive = amountKind === 'positive';
const onlyNegative = amountKind === 'negative';
if (onlyNegative) {
allTransactions = allTransactions.filter(op => op.amount < 0);
} else if (onlyPositive) {
allTransactions = allTransactions.filter(op => op.amount > 0);
}
let pies = null;
const transactionsInPeriod =
filterDate !== null
? allTransactions.filter((t: Operation) => filterDate(t))
: allTransactions;
if (onlyPositive || onlyNegative) {
pies = (
<PieChart
chartId="piechart"
getCategoryById={getCategoryById}
transactions={transactionsInPeriod}
ref={refPiecharts}
/>
);
} else {
// Compute raw income/spending.
const rawIncomeOps = transactionsInPeriod.filter(op => op.amount > 0);
const rawSpendingOps = transactionsInPeriod.filter(op => op.amount < 0);
// Compute net income/spending.
const catMap = new Map<number, Operation[]>();
for (const op of transactionsInPeriod) {
if (!catMap.has(op.categoryId)) {
catMap.set(op.categoryId, []);
}
const e = catMap.get(op.categoryId);
assert(typeof e !== 'undefined', 'just created');
e.push(op);
}
let netIncomeOps: Operation[] = [];
let netSpendingOps: Operation[] = [];
for (const categoryTransactions of catMap.values()) {
if (categoryTransactions.reduce((acc, op) => acc + op.amount, 0) > 0) {
netIncomeOps = netIncomeOps.concat(categoryTransactions);
} else {
netSpendingOps = netSpendingOps.concat(categoryTransactions);
}
}
pies = (
<AllPieCharts
getCategoryById={getCategoryById}
rawIncomeOps={rawIncomeOps}
netIncomeOps={netIncomeOps}
rawSpendingOps={rawSpendingOps}
netSpendingOps={netSpendingOps}
ref={refPiecharts}
/>
);
}
return (
<>
<DiscoveryMessage message={$t('client.charts.by_category_desc')} />
<Form center={true}>
<Form.Input id="amount-type" label={$t('client.charts.amount_type')}>
<AmountKindSelect defaultValue={amountKind} onChange={setAmountKind} />
</Form.Input>
<Form.Input
id="period"
label={$t('client.charts.period')}
sub={
<PredefinedDateRanges
onChange={onChangePeriod}
includeWeeks={true}
includeMonths={true}
includeYears={true}
/>
}>
<DateRange onSelect={onChangePeriod} value={dateRange} />
</Form.Input>
<Form.Input
id="categories"
dontPropagateId={true}
label={$t('client.menu.categories')}>
<p className="buttons-group" role="group" aria-label="Show/Hide categories">
<button type="button" className="btn" onClick={handleHideAll}>
{$t('client.general.unselect_all')}
</button>
<button type="button" className="btn" onClick={handleShowAll}>
{$t('client.general.select_all')}
</button>
</p>
</Form.Input>
</Form>
<hr />
<BarChart
transactions={transactionsInPeriod}
getCategoryById={getCategoryById}
invertSign={onlyNegative}
chartId="barchart"
ref={refBarchart}
/>
{pies}
</>
);
};
CategorySection.displayName = 'CategorySection';
export default CategorySection; | the_stack |
/// <reference path="../../elements.d.ts" />
import { CodeEditBehaviorScriptInstance, CodeEditBehaviorStylesheetInstance, CodeEditBehavior } from "../editpages/code-edit-pages/code-edit-behavior";
import { DividerEdit } from '../editpages/divider-edit/divider-edit';
import { Polymer } from '../../../../tools/definitions/polymer';
import { LinkEdit } from '../editpages/link-edit/link-edit';
import { MenuEdit } from '../editpages/menu-edit/menu-edit';
import { I18NKeys } from "../../../_locales/i18n-keys";
namespace NodeEditBehaviorNamespace {
interface NodeEditBehaviorProperties {
pageContentSelected: boolean;
linkContentSelected: boolean;
selectionContentSelected: boolean;
imageContentSelected: boolean;
videoContentSelected: boolean;
audioContentSelected: boolean;
}
export const nodeEditBehaviorProperties: NodeEditBehaviorProperties = {
/**
* The new settings object, to be written on save
*/
newSettings: {
type: Object,
notify: true,
value: {}
},
/**
* Whether the indicator for content type "page" should be selected
*/
pageContentSelected: {
type: Boolean,
notify: true
},
/**
* Whether the indicator for content type "link" should be selected
*/
linkContentSelected: {
type: Boolean,
notify: true
},
/**
* Whether the indicator for content type "selection" should be selected
*/
selectionContentSelected: {
type: Boolean,
notify: true
},
/**
* Whether the indicator for content type "image" should be selected
*/
imageContentSelected: {
type: Boolean,
notify: true
},
/**
* Whether the indicator for content type "video" should be selected
*/
videoContentSelected: {
type: Boolean,
notify: true
},
/**
* Whether the indicator for content type "audio" should be selected
*/
audioContentSelected: {
type: Boolean,
notify: true
}
} as any;
export class NEB {
static properties = nodeEditBehaviorProperties;
static getContentTypeLaunchers(this: NodeEditBehaviorInstance, resultStorage: Partial<CRM.Node>) {
const containers = this.$.showOnContentIconsContainer.children;
resultStorage.onContentTypes = Array.prototype.slice.apply(containers).map((item: Element) => {
return item.querySelector('paper-checkbox').checked;
});
};
static getTriggers(this: NodeEditBehaviorInstance, resultStorage: Partial<CRM.Node>) {
const containers = this.shadowRoot.querySelectorAll('.executionTrigger');
const triggers = [];
for (let i = 0; i < containers.length; i++) {
triggers[i] = {
url: containers[i].querySelector('paper-input').$$('input').value,
not: (containers[i].querySelector('.executionTriggerNot') as HTMLPaperCheckboxElement).checked
};
}
resultStorage.triggers = triggers;
};
static cancel(this: NodeEditBehaviorInstance) {
if ((<NodeEditBehaviorScriptInstance|NodeEditBehaviorStylesheetInstance>this).cancelChanges) {
//This made the compiler angry
((<NodeEditBehaviorScriptInstance|NodeEditBehaviorStylesheetInstance>this).cancelChanges as any)();
}
window.crmEditPage.animateOut();
};
static save(this: NodeEditBehaviorInstance, _event?: Polymer.ClickEvent, resultStorage?: Partial<CRM.Node>|MouseEvent) {
const revertPoint = window.app.uploading.createRevertPoint(false);
let usesDefaultStorage = false;
if (resultStorage === null || resultStorage === undefined ||
typeof (resultStorage as MouseEvent).x === 'number') {
resultStorage = window.app.nodesById.get(this.item.id);
usesDefaultStorage = true;
}
const newSettings = this.newSettings;
if ((<NodeEditBehaviorScriptInstance|NodeEditBehaviorStylesheetInstance>this).saveChanges) {
//Also made the compiler angry
((<NodeEditBehaviorScriptInstance|NodeEditBehaviorStylesheetInstance>this).saveChanges as any)(newSettings);
}
this.getContentTypeLaunchers(newSettings);
this.getTriggers(newSettings);
window.crmEditPage.animateOut();
const itemInEditPage = window.app.editCRM.getCRMElementFromPath(this.item.path, false);
newSettings.name = this.$.nameInput.$$('input').value;
itemInEditPage.itemName = newSettings.name;
if (!window.app.util.arraysOverlap(newSettings.onContentTypes, window.app.crmTypes)) {
window.app.editCRM.build({
setItems: window.app.editCRM.setMenus
});
}
if (newSettings.value && newSettings.type !== 'link') {
if ((newSettings as CRM.ScriptNode|CRM.StylesheetNode).value.launchMode !== undefined &&
(newSettings as CRM.ScriptNode|CRM.StylesheetNode).value.launchMode !== 0) {
(newSettings as CRM.ScriptNode|CRM.StylesheetNode).onContentTypes = [true, true, true, true, true, true];
} else {
if (!window.app.util.arraysOverlap(newSettings.onContentTypes, window.app.crmTypes)) {
window.app.editCRM.build({
setItems: window.app.editCRM.setMenus
});
}
}
}
window.app.templates.mergeObjectsWithoutAssignment(resultStorage, newSettings);
if (usesDefaultStorage) {
window.app.upload();
window.app.uploading.showRevertPointToast(revertPoint);
}
};
static inputKeyPress(this: NodeEditBehaviorInstance, e: KeyboardEvent) {
e.keyCode === 27 && this.cancel();
e.keyCode === 13 && this.save();
window.setTimeout(() => {
const value = this.$.nameInput.$$('input').value;
if (this.item.type === 'script') {
window.app.$.ribbonScriptName.innerText = value;
} else if (this.item.type === 'stylesheet') {
window.app.$.ribbonStylesheetName.innerText = value;
}
}, 0);
};
static assignContentTypeSelectedValues(this: NodeEditBehaviorInstance) {
let i;
const arr = [
'pageContentSelected', 'linkContentSelected', 'selectionContentSelected',
'imageContentSelected', 'videoContentSelected', 'audioContentSelected'
];
for (i = 0; i < 6; i++) {
this[arr[i] as keyof NodeEditBehaviorProperties] = this.item.onContentTypes[i];
}
};
static checkToggledIconAmount(this: NodeEditBehaviorInstance, e: {
path?: HTMLElement[];
Aa?: HTMLElement[];
target: HTMLElement;
}) {
const target = e.target;
this.async(() => {
const selectedCheckboxes: {
onContentTypes: CRM.ContentTypes;
} = {
onContentTypes: [false, false, false, false, false, false]
};
this.getContentTypeLaunchers(selectedCheckboxes);
if (selectedCheckboxes.onContentTypes.filter(item => item).length === 0) {
const element = window.app.util.findElementWithTagname({
path: e.path,
Aa: e.Aa,
target: target
}, 'paper-checkbox');
if (!element) return;
element.checked = true;
window.doc.contentTypeToast.show();
}
}, 10);
};
static toggleIcon(this: NodeEditBehaviorScriptInstance, e: Polymer.ClickEvent) {
if (this.editorMode && this.editorMode === 'background') {
return;
}
const element = window.app.util.findElementWithClassName(e, 'showOnContentItemCont');
const checkbox = $(element).find('paper-checkbox')[0] as unknown as HTMLPaperCheckboxElement;
checkbox.checked = !checkbox.checked;
if (!checkbox.checked) {
this.checkToggledIconAmount({
path: [checkbox],
target: checkbox
});
}
};
/**
* Clears the trigger that is currently clicked on
*/
static clearTrigger(this: NodeEditBehaviorInstance, event: Polymer.ClickEvent) {
let target = event.target;
if (target.tagName === 'PAPER-ICON-BUTTON') {
target = target.children[0] as Polymer.PolymerElement;
}
const element = window.app.util.findElementWithTagname(event, 'paper-icon-button')
if (!element) {
return;
}
const triggers = this.querySelectorAll('.executionTrigger');
const index = (Array.prototype.slice.apply(triggers) as HTMLElement[]).indexOf(element.parentElement)
// $(target.parentNode.parentNode).remove();
this.splice('newSettings.triggers', index, 1);
};
/**
* Adds a trigger to the list of triggers for the node
*/
static addTrigger(this: NodeEditBehaviorInstance) {
this.push('newSettings.triggers', {
not: false,
url: '*://example.com/*'
});
};
/**
* Returns the pattern that triggers need to follow for the current launch mode
*/
static _getPattern(this: NodeEditBehaviorScriptInstance|NodeEditBehaviorStylesheetInstance) {
Array.prototype.slice.apply(this.querySelectorAll('.triggerInput')).forEach(function(triggerInput: HTMLPaperInputElement) {
triggerInput.invalid = false;
});
//Execute when visiting specified, aka globbing etc
if (this.newSettings.value.launchMode !== 3) {
return '(/(.+)/)|.+';
} else {
return '(file:\\/\\/\\/.*|(\\*|http|https|file|ftp)://(\\*\\.[^/]+|\\*|([^/\\*]+.[^/\\*]+))(/(.*))?|(<all_urls>))';
}
};
/**
* Returns the label that a trigger needs to have for the current launchMode
*/
static _getLabel(this: NodeEditBehaviorScriptInstance|NodeEditBehaviorStylesheetInstance,
lang: string, langReady: boolean) {
if (this.newSettings.value.launchMode === 2) {
return this.__(lang, langReady, I18NKeys.options.nodeEditBehavior.globPattern);
} else {
return this.__(lang, langReady, I18NKeys.options.nodeEditBehavior.matchPattern);
}
};
static animateTriggers(this: CodeEditBehavior, show: boolean): Promise<void> {
return new Promise<void>((resolve) => {
const element = this.$.executionTriggersContainer
element.style.height = 'auto';
if (show) {
element.style.display = 'block';
element.style.marginLeft = '-110%';
element.style.height = '0';
$(element).animate({
height: element.scrollHeight
}, 300, function (this: HTMLElement) {
$(this).animate({
marginLeft: 0
}, 200, function(this: HTMLElement) {
this.style.height = 'auto';
resolve(null);
});
});
} else {
element.style.marginLeft = '0';
element.style.height = element.scrollHeight + '';
$(element).animate({
marginLeft: '-110%'
}, 200, function (this: HTMLElement) {
$(this).animate({
height: 0
}, 300, function () {
element.style.display = 'none';
resolve(null);
});
});
}
this.showTriggers = show;
});
}
static animateContentTypeChooser(this: CodeEditBehavior<{}>, show: boolean) {
const element = this.$.showOnContentContainer;
if (show) {
element.style.height = '0';
element.style.display = 'block';
element.style.marginLeft = '-110%';
$(element).animate({
height: element.scrollHeight
}, 300, () => {
$(element).animate({
marginLeft: 0
}, 200, () => {
element.style.height = 'auto';
});
});
} else {
element.style.marginLeft = '0';
element.style.height = element.scrollHeight + '';
$(element).animate({
marginLeft: '-110%'
}, 200, () => {
$(element).animate({
height: 0
}, 300, () => {
element.style.display = 'none';
});
});
}
this.showContentTypeChooser = show;
}
/**
* Is triggered when the option in the dropdown menu changes animates in what's needed
*/
static async selectorStateChange(this: CodeEditBehavior, prevState: number, state: number) {
const newStates = {
showContentTypeChooser: (state === 0 || state === 3),
showTriggers: (state > 1 && state !== 4),
showInsteadOfExecute: (state === 3)
};
const oldStates = {
showContentTypeChooser: (prevState === 0 || prevState === 3),
showTriggers: (prevState > 1 && prevState !== 4),
showInsteadOfExecute: (prevState === 3)
};
if (oldStates.showTriggers !== newStates.showTriggers) {
await this.animateTriggers(newStates.showTriggers);
}
if (oldStates.showContentTypeChooser !== newStates.showContentTypeChooser) {
this.animateContentTypeChooser(newStates.showContentTypeChooser);
}
if (newStates.showInsteadOfExecute !== oldStates.showInsteadOfExecute) {
((this.$ as any)['showOrExecutetxt'] as HTMLSpanElement).innerText =
(newStates.showInsteadOfExecute ?
await this.___(I18NKeys.options.editPages.code.showOn) :
await this.___(I18NKeys.options.editPages.code.executeOn));
}
this.async(() => {
if (this.editorManager) {
this.editorManager.editor.layout();
}
}, 500);
};
static matchesTypeScheme(this: NodeEditBehaviorInstance, type: CRM.NodeType,
data: CRM.LinkVal|CRM.ScriptVal|CRM.StylesheetVal|null): boolean {
switch (type) {
case 'link':
if (Array.isArray(data)) {
let objects = true;
data.forEach(function(linkItem) {
if (typeof linkItem !== 'object' || Array.isArray(linkItem)) {
objects = false;
}
});
if (objects) {
return true;
}
}
break;
case 'script':
case 'stylesheet':
return typeof data === 'object' && !Array.isArray(data);
case 'divider':
case 'menu':
return data === null;
}
return false;
};
static _doTypeChange(this: NodeEditBehaviorInstance, type: CRM.NodeType) {
const revertPoint = window.app.uploading.createRevertPoint(false);
const item = window.app.nodesById.get(this.item.id);
const prevType = item.type;
const editCrmEl = window.app.editCRM.getCRMElementFromPath(this.item.path, true);
if (prevType === 'menu') {
item.menuVal = item.children;
delete item.children;
} else {
item[prevType + 'Val' as ('menuVal'|'linkVal'|'scriptVal'|'stylesheetVal')] =
item.value as any;
}
item.type = this.item.type = type;
if (type === 'menu') {
item.children = [];
}
if (item[type + 'Val' as ('menuVal'|'linkVal'|'scriptVal'|'stylesheetVal')] &&
this.matchesTypeScheme(type, item[type + 'Val' as ('menuVal'|'linkVal'|'scriptVal'|'stylesheetVal')] as any)) {
item.value = item[type + 'Val' as ('menuVal'|'linkVal'|'scriptVal'|'stylesheetVal')];
} else {
let triggers;
switch (item.type) {
case 'link':
item.triggers = item.triggers || [{
url: '*://*.example.com/*',
not: false
}];
item.value = [{
url: 'https://www.example.com',
newTab: true
}];
break;
case 'script':
triggers = triggers || item.triggers || [{
url: '*://*.example.com/*',
not: false
}];
item.value = window.app.templates.getDefaultScriptValue();
break;
case 'divider':
item.value = null;
item.triggers = item.triggers || [{
url: '*://*.example.com/*',
not: false
}];
break;
case 'menu':
item.value = null;
item.triggers = item.triggers || [{
url: '*://*.example.com/*',
not: false
}];
break;
case 'stylesheet':
triggers = triggers || item.triggers || [{
url: '*://*.example.com/*',
not: false
}];
item.value = window.app.templates.getDefaultStylesheetValue();
break;
}
}
editCrmEl.item = item;
editCrmEl.type = type;
editCrmEl.calculateType();
const typeSwitcher = editCrmEl.shadowRoot.querySelector('type-switcher');
typeSwitcher.onReady();
const typeChoices = Array.prototype.slice.apply(typeSwitcher.shadowRoot.querySelectorAll('.typeSwitchChoice'));
for (let i = 0; i < typeSwitcher.remainingTypes.length; i++) {
typeChoices[i].setAttribute('type', typeSwitcher.remainingTypes[i]);
}
if (prevType === 'menu') {
//Turn children into "shadow items"
const column = (typeSwitcher.parentElement.parentElement.parentNode as ShadowRoot).host.parentElement as HTMLElement & {
index: number;
};
let columnCont = column.parentElement.parentElement;
columnCont = $(columnCont).next()[0];
typeSwitcher.shadowColumns(columnCont, false);
window.app.shadowStart = column.index + 1;
}
window.app.uploading.showRevertPointToast(revertPoint, 15000);
window.app.upload();
}
static async _changeType(this: NodeEditBehaviorInstance, type: CRM.NodeType) {
this._doTypeChange(type);
const { id } = this.item;
//Close this dialog
this.cancel();
//Re-open the dialog
await window.app.util.wait(2000);
const editCrmEl = window.app.editCRM.getCRMElementFromPath(
window.app.nodesById.get(id).path, false);
editCrmEl.openEditPage();
}
static changeTypeToLink(this: NodeEditBehaviorInstance) {
this._changeType('link');
}
static changeTypeToScript(this: NodeEditBehaviorInstance) {
this._changeType('script');
}
static changeTypeToStylesheet(this: NodeEditBehaviorInstance) {
this._changeType('stylesheet');
}
static changeTypeToMenu(this: NodeEditBehaviorInstance) {
this._changeType('menu');
}
static changeTypeToDivider(this: NodeEditBehaviorInstance) {
this._changeType('divider');
}
static initDropdown(this: CodeEditBehavior) {
this.showTriggers = (this.item.value.launchMode > 1 && this.item.value.launchMode !== 4);
this.showContentTypeChooser = (this.item.value.launchMode === 0 || this.item.value.launchMode === 3);
if (this.showTriggers) {
this.$.executionTriggersContainer.style.display = 'block';
this.$.executionTriggersContainer.style.marginLeft = '0';
this.$.executionTriggersContainer.style.height = 'auto';
} else {
this.$.executionTriggersContainer.style.display = 'none';
this.$.executionTriggersContainer.style.marginLeft = '-110%';
this.$.executionTriggersContainer.style.height = '0';
}
if (this.showContentTypeChooser) {
this.$.showOnContentContainer.style.display = 'block';
this.$.showOnContentContainer.style.marginLeft = '0';
this.$.showOnContentContainer.style.height = 'auto';
} else {
this.$.showOnContentContainer.style.display = 'none';
this.$.showOnContentContainer.style.marginLeft = '-110%';
this.$.showOnContentContainer.style.height = '0';
}
this.$.dropdownMenu._addListener(this.selectorStateChange, 'dropdownMenu', this);
if (this.editorManager) {
this.editorManager.destroy();
this.editorManager = null;
}
};
static _init(this: NodeEditBehaviorInstance) {
this.newSettings = JSON.parse(JSON.stringify(this.item));
window.crmEditPage.nodeInfo = this.newSettings.nodeInfo;
this.assignContentTypeSelectedValues();
setTimeout(() => {
this.$.nameInput.focus();
const value = this.$.nameInput.$$('input').value;
if (this.item.type === 'script') {
window.app.$.ribbonScriptName.innerText = value;
} else if (this.item.type === 'stylesheet') {
window.app.$.ribbonStylesheetName.innerText = value;
}
}, 350);
}
}
window.Polymer.NodeEditBehavior = window.Polymer.NodeEditBehavior || NodeEditBehaviorNamespace.NEB as NodeEditBehaviorBase;
}
export type NodeEditBehaviorBase = Polymer.El<'node-edit-behavior',
typeof NodeEditBehaviorNamespace.NEB & typeof NodeEditBehaviorNamespace.nodeEditBehaviorProperties>;
export type NodeEditBehavior<T> = T & NodeEditBehaviorBase;
export type NodeEditBehaviorScriptInstance = NodeEditBehavior<CodeEditBehaviorScriptInstance & {
newSettings: Partial<CRM.ScriptNode>
}>;
export type NodeEditBehaviorStylesheetInstance = NodeEditBehavior<CodeEditBehaviorStylesheetInstance & {
newSettings: Partial<CRM.StylesheetNode>;
}>;
export type NodeEditBehaviorLinkInstance = NodeEditBehavior<LinkEdit & {
newSettings: Partial<CRM.LinkNode>;
}>;
export type NodeEditBehaviorMenuInstance = NodeEditBehavior<MenuEdit & {
newSettings: Partial<CRM.MenuNode>;
}>;
export type NodeEditBehaviorDividerInstance = NodeEditBehavior<DividerEdit & {
newSettings: Partial<CRM.DividerNode>;
}>;
export type NodeEditBehaviorInstance = NodeEditBehaviorScriptInstance|
NodeEditBehaviorStylesheetInstance|NodeEditBehaviorLinkInstance|
NodeEditBehaviorMenuInstance|NodeEditBehaviorDividerInstance; | the_stack |
'use strict';
import {
window, ExtensionContext, Uri, ViewColumn, WebviewPanel, commands, Disposable, workspace, TextEditorRevealType, TextEditor, Range, Webview
} from 'vscode';
import * as path from 'path';
import { showError, ensureAbsoluteGlobalStoragePath } from '../utils';
import { StateResolver } from './StateResolver';
import { ProblemInfo, DomainInfo, utils, search, Happening } from 'pddl-workspace';
import { CONF_PDDL, DEFAULT_EPSILON, VAL_STEP_PATH, VAL_VERBOSE } from '../configuration/configuration';
import { getDomainVisualizationConfigurationDataForPlan } from '../planView/DomainVisualization';
import { PlanEvaluator } from 'ai-planning-val';
import { FinalStateData } from '../planView/model';
import { handleValStepError } from '../planView/valStepErrorHandler';
import { getWebViewHtml } from '../webviewUtils';
export class SearchDebuggerView {
private webViewPanel: WebviewPanel | undefined;
private subscriptions: Disposable[] = [];
private search: StateResolver | undefined;
private stateChangedWhileViewHidden = false;
private stateLogFile: Uri | undefined;
private stateLogEditor: TextEditor | undefined;
private stateLogLineCache = new Map<string, number>();
private domain: DomainInfo | undefined;
private problem: ProblemInfo | undefined;
private serializableDomain: DomainInfo | undefined;
private serializableProblem: ProblemInfo | undefined;
// cached values
private debuggerState: boolean | undefined;
private port: number | undefined;
constructor(private context: ExtensionContext) {
}
isVisible(): boolean {
return this.webViewPanel !== undefined && this.webViewPanel.visible;
}
observe(search: StateResolver): void {
this.search = search;
// first unsubscribe from previous search
this.subscriptions.forEach(subscription => subscription.dispose());
this.subscriptions = [];
this.subscriptions.push(search.onStateAdded(newState => this.addState(newState)));
this.subscriptions.push(search.onStateUpdated(newState => this.update(newState)));
this.subscriptions.push(search.onBetterState(betterState => this.displayBetterState(betterState)));
this.subscriptions.push(search.onPlanFound(planStates => this.displayPlan(planStates)));
}
setDomainAndProblem(domain: DomainInfo, problem: ProblemInfo): void {
this.domain = domain;
this.problem = problem;
this.serializableDomain = undefined;
this.serializableProblem = undefined;
}
getSerializableDomain(): DomainInfo | undefined {
return this.serializableDomain ?? (this.serializableDomain = this.domain && utils.serializationUtils.makeSerializable(this.domain));
}
getSerializableProblem(): ProblemInfo | undefined {
return this.serializableProblem ?? (this.serializableProblem = this.problem && utils.serializationUtils.makeSerializable(this.problem));
}
async showDebugView(): Promise<void> {
if (this.webViewPanel !== undefined) {
this.webViewPanel.reveal();
}
else {
await this.createDebugView(false);
}
}
async createDebugView(showOnTop: boolean): Promise<void> {
const iconUri = this.context.asAbsolutePath('images/icon.png');
this.webViewPanel = window.createWebviewPanel(
"pddl.SearchDebugger",
"Search Debugger",
{
viewColumn: ViewColumn.Active,
preserveFocus: !showOnTop
},
{
retainContextWhenHidden: true,
enableFindWidget: true,
enableCommandUris: true,
enableScripts: true,
localResourceRoots: [Uri.file(this.context.asAbsolutePath("views"))]
}
);
const html = await this.getHtml(this.webViewPanel.webview);
this.webViewPanel.webview.html = html;
this.webViewPanel.iconPath = Uri.file(iconUri);
this.webViewPanel.onDidDispose(() => this.webViewPanel = undefined, undefined, this.context.subscriptions);
this.webViewPanel.webview.onDidReceiveMessage(message => this.handleMessage(message), undefined, this.context.subscriptions);
this.webViewPanel.onDidChangeViewState(event => this.changedViewState(event.webviewPanel));
this.context.subscriptions.push(this.webViewPanel); // todo: this may not be necessary
}
changedViewState(webViewPanel: WebviewPanel): void {
if (webViewPanel.visible) {
this.showDebuggerState();
if (this.stateChangedWhileViewHidden) {
// re-send all states
this.showAllStates();
}
// reset the state
this.stateChangedWhileViewHidden = false;
}
}
async handleMessage(message: CommandMessage): Promise<void> {
console.log(`Message received from the webview: ${message.command}`);
switch (message.command) {
case 'onload':
this.showDebuggerState();
break;
case 'stateSelected':
const stateMessage = message as StateMessage;
try {
this.showStatePlan(stateMessage.stateId);
this.scrollStateLog(stateMessage.stateId);
}
catch (ex) {
window.showErrorMessage("Error while displaying state-plan: " + ex);
}
break;
case 'finalStateDataRequest':
const stateMessage1 = message as StateMessage;
this.getFinalStateData(stateMessage1.stateId).catch(showError);
break;
case 'startDebugger':
commands.executeCommand("pddl.searchDebugger.start");
this.stateLogLineCache.clear();
break;
case 'stopDebugger':
commands.executeCommand("pddl.searchDebugger.stop");
break;
case 'reset':
commands.executeCommand("pddl.searchDebugger.reset");
break;
case 'toggleStateLog':
this.toggleStateLog();
break;
case 'revealAction':
const actionMessage = message as ActionMessage;
this.domain && commands.executeCommand("pddl.revealAction", this.domain.fileUri, actionMessage.action);
break;
default:
console.warn('Unexpected command: ' + message.command);
}
}
readonly VIEWS = "views";
readonly STATIC_CONTENT_FOLDER = path.join(this.VIEWS, "searchview", "static");
readonly COMMON_FOLDER = path.join(this.VIEWS, "common");
async getHtml(webview: Webview): Promise<string> {
const googleCharts = Uri.parse("https://www.gstatic.com/charts/");
return getWebViewHtml(this.context, {
relativePath: this.STATIC_CONTENT_FOLDER, htmlFileName: 'search.html',
externalImages: [Uri.parse('data:')],
allowUnsafeInlineScripts: true, // todo: false?
allowUnsafeEval: true,
externalScripts: [googleCharts],
externalStyles: [googleCharts],
fonts: [
Uri.file(path.join("..", "..", "..", this.COMMON_FOLDER, "codicon.ttf"))
]
}, webview);
}
setDebuggerState(on: boolean, port: number): void {
this.debuggerState = on;
this.port = port;
this.showDebuggerState();
}
private showDebuggerState(): void {
this.postMessage({
command: "debuggerState", state: {
running: this.debuggerState ? 'on' : 'off',
port: this.port
}
});
}
addState(newState: search.SearchState): void {
new Promise(() => this.postMessage({ command: 'stateAdded', state: newState }))
.catch(reason => console.log(reason));
}
update(state: search.SearchState): void {
new Promise(() => this.postMessage({ command: 'stateUpdated', state: state }))
.catch(reason => console.log(reason));
}
showAllStates(): void {
const allStates = this.search?.getStates() ?? [];
new Promise(() => this.postMessage({ command: 'showAllStates', state: allStates }))
.catch(reason => console.log(reason));
}
displayBetterState(state: search.SearchState): void {
try {
this.showStatePlan(state.id);
} catch (ex: unknown) {
window.showErrorMessage((ex as Error).message ?? ex);
}
}
displayPlan(planStates: search.SearchState[]): void {
new Promise(() => this.postMessage({ command: 'showPlan', state: planStates }))
.catch(reason => console.log(reason));
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private postMessage(message: { command: string; state: any }): void {
if (this.webViewPanel !== undefined) {
this.webViewPanel.webview.postMessage(message);
if (!this.webViewPanel.visible) {
this.stateChangedWhileViewHidden = true;
}
}
}
async showStatePlan(stateId: number): Promise<void> {
if (this.search === undefined) { return void 0; }
if (stateId === null) { return void 0; }
const state = this.search.getState(stateId);
if (!state || !this.webViewPanel) { return; }
const statePlan = new search.SearchStateToPlan(this.getSerializableDomain(),
this.getSerializableProblem(), DEFAULT_EPSILON).convert(state);
const plansData = await getDomainVisualizationConfigurationDataForPlan(statePlan);
this.postMessage({
command: 'showStatePlan', state: plansData
});
}
async getFinalStateData(stateId: number | null | undefined): Promise<void> {
if (this.search === undefined) { return void 0; }
if (stateId === null || stateId === undefined) { return void 0; }
const state = this.search.getState(stateId);
if (!state || !this.webViewPanel) { return; }
const valStepPath = ensureAbsoluteGlobalStoragePath(workspace.getConfiguration(CONF_PDDL).get<string>(VAL_STEP_PATH), this.context);
const valVerbose = workspace.getConfiguration(CONF_PDDL).get<boolean>(VAL_VERBOSE, false);
const happenings = state.planHead.map(searchHappening => toHappening(searchHappening));
if (this.domain && this.problem) {
try {
const finalStateValues = await new PlanEvaluator().evaluateHappenings(this.domain, this.problem, happenings, { valStepPath, verbose: valVerbose });
if (finalStateValues) {
const data: FinalStateData = {
finalState: finalStateValues.map(tvv => tvv.getVariableValue()),
planIndex: stateId
};
this.postMessage({
"command": "visualizeFinalState",
"state": data
});
}
} catch (err) {
console.error(err);
if (valStepPath) {
handleValStepError(err, valStepPath);
}
}
}
}
clear(): void {
this.postMessage({ command: 'clear', state: 'n/a' });
this.stateLogLineCache.clear();
this.domain = undefined;
this.problem = undefined;
}
async toggleStateLog(): Promise<void> {
if (this.stateLogFile !== undefined) {
this.postMessage({ command: 'stateLog', state: null });
}
else {
const selectedUri = await window.showOpenDialog({ canSelectMany: false, defaultUri: this.stateLogFile, canSelectFolders: false });
if (!selectedUri) { return; }
this.stateLogFile = selectedUri[0];
this.stateLogEditor = await window.showTextDocument(await workspace.openTextDocument(this.stateLogFile), { preserveFocus: true, viewColumn: ViewColumn.Beside });
this.postMessage({ command: 'stateLog', state: this.stateLogFile.fsPath });
}
}
async scrollStateLog(stateId: number): Promise<void> {
if (!this.stateLogFile || !this.stateLogEditor || !this.search) { return; }
const state = this.search.getState(stateId);
if (!state) { return; }
if (this.stateLogEditor.document.isClosed) {
this.stateLogEditor = await window.showTextDocument(this.stateLogEditor.document, ViewColumn.Beside);
}
if (this.stateLogLineCache.has(state.origId)) {
const cachedLineId = this.stateLogLineCache.get(state.origId);
if (cachedLineId) {
this.stateLogEditor.revealRange(new Range(cachedLineId, 0, cachedLineId + 1, 0), TextEditorRevealType.AtTop);
}
return;
}
const pattern = workspace.getConfiguration("pddlSearchDebugger").get<string>("stateLogPattern", "");
for (let lineIdx = 0; lineIdx < this.stateLogEditor.document.lineCount; lineIdx++) {
const logLine = this.stateLogEditor.document.lineAt(lineIdx);
const patternMatch = logLine.text.match(new RegExp(pattern));
if (patternMatch && patternMatch[1] === state.origId) {
this.stateLogEditor.revealRange(logLine.range, TextEditorRevealType.AtTop);
this.stateLogLineCache.set(state.origId, lineIdx);
break;
}
}
}
}
/**
* Converts `SearchHappening` to `Happening`.
* @param searchHappening plan happening that was created as a search state progression
*/
function toHappening(searchHappening: search.SearchHappening): Happening {
return new Happening(searchHappening.earliestTime, searchHappening.kind,
searchHappening.actionName, searchHappening.shotCounter);
}
interface CommandMessage {
command: string;
}
interface StateMessage extends CommandMessage {
stateId: number;
}
interface ActionMessage extends CommandMessage {
action: string;
}
// todo: handle Home / End keyboard buttons to move to initial state and goal state (when there are multiple goal states, perhaps we can iterate through them upon repetitive <end> key presses). | the_stack |
import { Matrix } from './matrix'
import { Vector3 } from './vector3'
export class Quaternion {
/** The internal elements for this type. */
public v: Float32Array
/** Creates a new Quaternion */
constructor(x: number, y: number, z: number, w: number) {
this.v = new Float32Array(4)
this.v[0] = x
this.v[1] = y
this.v[2] = z
this.v[3] = w
}
/** Returns the string representation of this object. */
public toString(): string {
return `[${this.v[0]}, ${this.v[1]}, ${this.v[2]}, ${this.v[3]}]`
}
/** Returns the kind of this object. */
public kind(): string {
return 'Quaternion'
}
/** Returns a clone of this quaternion. */
public clone(): Quaternion {
return Quaternion.clone(this)
}
public get x(): number {
return this.v[0]
}
public get y(): number {
return this.v[1]
}
public get z(): number {
return this.v[2]
}
public get w(): number {
return this.v[3]
}
public set x(value: number) {
this.v[0] = value
}
public set y(value: number) {
this.v[1] = value
}
public set z(value: number) {
this.v[2] = value
}
public set w(value: number) {
this.v[3] = value
}
/** Returns the length of this quaternion. */
public length(): number {
return Quaternion.getLength(this)
}
/** Returns the length squared of this quaternion. */
public lengthSq(): number {
return Quaternion.getLengthSq(this)
}
/** Returns this quaternion normalized. */
public normalize(): Quaternion {
return Quaternion.normalize(this)
}
/** Returns the dot product between this and the given quaternion. */
public dot(v0: Quaternion): number {
return Quaternion.dot(this, v0)
}
/** Concatinates with the given quaternion. */
public concat(q0: Quaternion): Quaternion {
return Quaternion.concat(this, q0)
}
/** Returns the addition between this and the given quaternion. */
public add(q0: Quaternion): Quaternion {
return Quaternion.add(this, q0)
}
/** Returns the subtraction between this and the given quaternion. */
public sub(q0: Quaternion): Quaternion {
return Quaternion.sub(this, q0)
}
/** Returns the multiplication between this and the given vector. */
public mul(q0: Quaternion): Quaternion {
return Quaternion.mul(this, q0)
}
/** Returns the division between this and the given vector. */
public div(q0: Quaternion): Quaternion {
return Quaternion.div(this, q0)
}
/** Compares the left and right quaternions for equality. */
public static equals(q0: Quaternion, q1: Quaternion): boolean {
return (
q0.v[0] === q1.v[0] &&
q0.v[1] === q1.v[1] &&
q0.v[2] === q1.v[2] &&
q0.v[3] === q1.v[3]
)
}
/** Returns the length of the given quaternion. */
public static getLength(q0: Quaternion): number {
return Math.sqrt(
(q0.v[0] * q0.v[0]) +
(q0.v[1] * q0.v[1]) +
(q0.v[2] * q0.v[2]) +
(q0.v[3] * q0.v[3])
)
}
/** Returns the square length of the given vector. */
public static getLengthSq(q0: Quaternion): number {
return (
(q0.v[0] * q0.v[0]) +
(q0.v[1] * q0.v[1]) +
(q0.v[2] * q0.v[2]) +
(q0.v[3] * q0.v[3])
)
}
/** Returns a normalized quaternion from the given quaternion. */
public static normalize(q0: Quaternion): Quaternion {
const len = 1.0 / Math.sqrt(
(q0.v[0] * q0.v[0]) +
(q0.v[1] * q0.v[1]) +
(q0.v[2] * q0.v[2]) +
(q0.v[3] * q0.v[3])
)
return new Quaternion(
q0.v[0] * len,
q0.v[1] * len,
q0.v[2] * len,
q0.v[3] * len
)
}
/** Returns the dot product for the given two quaternions. */
public static dot(q0: Quaternion, q1: Quaternion): number {
return (
(q0.v[0] * q1.v[0]) +
(q0.v[1] * q1.v[1]) +
(q0.v[2] * q1.v[2]) +
(q0.v[3] * q1.v[3])
)
}
/** Returns the conjugate of the given quaternion. */
public static conjugate(q0: Quaternion): Quaternion {
return new Quaternion(
-q0.v[0],
-q0.v[1],
-q0.v[2],
q0.v[3]
)
}
/** Returns the inverse for the given quaternion. */
public static inverse(q0: Quaternion): Quaternion {
const n0 = ((
(q0.v[0] * q0.v[0]) +
(q0.v[1] * q0.v[1])) +
(q0.v[2] * q0.v[2])) +
(q0.v[3] * q0.v[3])
const n1 = 1.0 / n0
return new Quaternion(
-q0.v[0] * n1,
-q0.v[1] * n1,
-q0.v[2] * n1,
-q0.v[3] * n1
)
}
/** Returns the spherical linear interpolation between the given two quaternions. */
public static slerp(q0: Quaternion, q1: Quaternion, amount: number): Quaternion {
let n0 = 0.0
let n1 = 0.0
const n2 = amount
let n3 = ((
(q0.v[0] * q1.v[0]) +
(q0.v[1] * q1.v[1])) +
(q0.v[2] * q1.v[2])) +
(q0.v[3] * q1.v[3])
let flag = false
if (n3 < 0.0) {
flag = true;
n3 = -n3;
}
if (n3 > 0.999999) {
n1 = 1.0 - n2
n0 = flag ? -n2 : n2
}
else {
const n4 = Math.acos(n3)
const n5 = 1.0 / Math.sin(n4)
n1 = Math.sin(((1.0 - n2) * n4)) * n5
n0 = flag ? (-Math.sin(n2 * n4) * n5) : (Math.sin(n2 * n4) * n5)
}
return new Quaternion(
(n1 * q0.v[0]) + (n0 * q1.v[0]),
(n1 * q0.v[1]) + (n0 * q1.v[1]),
(n1 * q0.v[2]) + (n0 * q1.v[2]),
(n1 * q0.v[3]) + (n0 * q1.v[3])
)
}
/** Returns the linear interpolation between the given two quaternions. */
public static lerp(q0: Quaternion, q1: Quaternion, amount: number): Quaternion {
const q2 = Quaternion.zero()
const n0 = amount
const n1 = 1.0 - n0
const n2 = (((q0.v[0] * q1.v[0]) +
(q0.v[1] * q1.v[1])) +
(q0.v[2] * q1.v[2])) +
(q0.v[3] * q1.v[3])
if (n2 >= 0.0) {
q2.v[0] = (n1 * q0.v[0]) + (n0 * q1.v[0])
q2.v[1] = (n1 * q0.v[1]) + (n0 * q1.v[1])
q2.v[2] = (n1 * q0.v[2]) + (n0 * q1.v[2])
q2.v[3] = (n1 * q0.v[3]) + (n0 * q1.v[3])
}
else {
q2.v[0] = (n1 * q0.v[0]) - (n0 * q1.v[0])
q2.v[1] = (n1 * q0.v[1]) - (n0 * q1.v[1])
q2.v[2] = (n1 * q0.v[2]) - (n0 * q1.v[2])
q2.v[3] = (n1 * q0.v[3]) - (n0 * q1.v[3])
}
const n3 = (((q2.v[0] * q2.v[0]) +
(q2.v[1] * q2.v[1])) +
(q2.v[2] * q2.v[2])) +
(q2.v[3] * q2.v[3])
const n4 = 1.0 / Math.sqrt(n3)
q2.v[0] *= n4
q2.v[1] *= n4
q2.v[2] *= n4
q2.v[3] *= n4
return q2
}
/** Creates a quaternion from the given axis and angle. */
public static fromAxisAngle(v0: Vector3, angle: number): Quaternion {
const n0 = angle * 0.5
const n1 = Math.sin(n0)
const n2 = Math.cos(n0)
return new Quaternion(
v0.v[0] * n1,
v0.v[1] * n1,
v0.v[2] * n1,
n2
)
}
/** Creates a quaternion from the given Matrix. */
public static fromMatrix(m0: Matrix): Quaternion {
const n0 = (m0.v[0] + m0.v[5]) + m0.v[10]
if (n0 > 0.0) {
const n1 = Math.sqrt(n0 + 1.0)
const n2 = 0.5 / n1
return new Quaternion(
(m0.v[6] - m0.v[9]) * n2,
(m0.v[8] - m0.v[2]) * n2,
(m0.v[1] - m0.v[4]) * n2,
n1 * 0.5
)
}
else if ((m0.v[0] >= m0.v[5]) && (m0.v[0] >= m0.v[10])) {
const n1 = Math.sqrt(((1.0 + m0.v[0]) - m0.v[5]) - m0.v[10])
const n2 = 0.5 / n1
return new Quaternion(
0.5 * n1,
(m0.v[1] + m0.v[4]) * n2,
(m0.v[2] + m0.v[8]) * n2,
(m0.v[6] - m0.v[9]) * n2
)
}
else if (m0.v[5] > m0.v[10]) {
const n1 = Math.sqrt(((1.0 + m0.v[5]) - m0.v[0]) - m0.v[10])
const n2 = 0.5 / n1
return new Quaternion(
(m0.v[4] + m0.v[1]) * n2,
0.5 * n1,
(m0.v[9] + m0.v[6]) * n2,
(m0.v[8] - m0.v[2]) * n2
)
}
else {
const n1 = Math.sqrt(((1.0 + m0.v[10]) - m0.v[0]) - m0.v[5])
const n2 = 0.5 / n1
return new Quaternion(
(m0.v[8] + m0.v[2]) * n2,
(m0.v[9] + m0.v[6]) * n2,
0.5 * n1,
(m0.v[1] - m0.v[4]) * n2
)
}
}
/** Concatinates the given quaternions. */
public static concat(q0: Quaternion, q1: Quaternion): Quaternion {
const n0 = q1.v[0]
const n1 = q1.v[1]
const n2 = q1.v[2]
const n3 = q1.v[3]
const n4 = q0.v[0]
const n5 = q0.v[1]
const n6 = q0.v[2]
const n7 = q0.v[3]
const n8 = (n1 * n6) - (n2 * n5)
const n9 = (n2 * n4) - (n0 * n6)
const n10 = (n0 * n5) - (n1 * n4)
const n11 = ((n0 * n4) + (n1 * n5)) + (n2 * n6)
return new Quaternion(
((n0 * n7) + (n4 * n3)) + n8,
((n1 * n7) + (n5 * n3)) + n9,
((n2 * n7) + (n6 * n3)) + n10,
(n3 * n7) - n11
)
}
/** Returns the addition of the given quaternions. */
public static add(q0: Quaternion, q1: Quaternion): Quaternion {
return new Quaternion(
q0.v[0] + q1.v[0],
q0.v[1] + q1.v[1],
q0.v[2] + q1.v[2],
q0.v[3] + q1.v[3]
)
}
/** Returns the subtraction of the given quaternions. */
public static sub(q0: Quaternion, q1: Quaternion): Quaternion {
return new Quaternion(
q0.v[0] - q1.v[0],
q0.v[1] - q1.v[1],
q0.v[2] - q1.v[2],
q0.v[3] - q1.v[3]
)
}
/** Returns the multiplication of the given quaternions. */
public static mul(q0: Quaternion, q1: Quaternion): Quaternion {
const n0 = q0.v[0]
const n1 = q0.v[1]
const n2 = q0.v[2]
const n3 = q0.v[3]
const n4 = q1.v[0]
const n5 = q1.v[1]
const n6 = q1.v[2]
const n7 = q1.v[3]
const n8 = (n1 * n6) - (n2 * n5)
const n9 = (n2 * n4) - (n0 * n6)
const n10 = (n0 * n5) - (n1 * n4)
const n11 = ((n0 * n4) + (n1 * n5)) + (n2 * n6)
return new Quaternion(
((n0 * n7) + (n4 * n3)) + n8,
((n1 * n7) + (n5 * n3)) + n9,
((n2 * n7) + (n6 * n3)) + n10,
(n3 * n7) - n11
)
}
/** Returns the division of the given quaternions. */
public static div(q0: Quaternion, q1: Quaternion): Quaternion {
const n0 = q0.v[0]
const n1 = q0.v[1]
const n2 = q0.v[2]
const n3 = q0.v[3]
const n4 = (((q1.v[0] * q1.v[0]) +
(q1.v[1] * q1.v[1])) +
(q1.v[2] * q1.v[2])) +
(q1.v[3] * q1.v[3])
const n5 = 1.0 / n4
const n6 = -q1.v[0] * n5
const n7 = -q1.v[1] * n5
const n8 = -q1.v[2] * n5
const n9 = q1.v[3] * n5
const n10 = (n1 * n8) - (n2 * n7)
const n11 = (n2 * n6) - (n0 * n8)
const n12 = (n0 * n7) - (n1 * n6)
const n13 = ((n0 * n6) + (n1 * n7)) + (n2 * n8)
return new Quaternion(
((n0 * n9) + (n6 * n3)) + n10,
((n1 * n9) + (n7 * n3)) + n11,
((n2 * n9) + (n8 * n3)) + n12,
(n3 * n9) - n13
)
}
/** Negates the given quaternion. */
public static negate(q0: Quaternion): Quaternion {
return new Quaternion(
-q0.v[0],
-q0.v[1],
-q0.v[2],
-q0.v[3]
)
}
/** Returns a clone of the given quaternion. */
public static clone(q0: Quaternion): Quaternion {
return new Quaternion(
q0.v[0],
q0.v[1],
q0.v[2],
q0.v[3]
)
}
/** Creates a new quatenion with all elements set to 0. */
public static zero(): Quaternion {
return new Quaternion(0, 0, 0, 0)
}
/** Creates a new quaternion. */
public static create(x: number, y: number, z: number, w: number): Quaternion {
return new Quaternion(x, y, z, w)
}
} | the_stack |
import { Widgets } from "../../@types/blessed.d";
import { strWidth, charWidth } from "neo-blessed/lib/unicode";
import * as unicode from "neo-blessed/lib/unicode";
import { Widget } from "./widget/Widget";
import { Logger } from "../common/Logger";
import { StringUtils } from "../common/StringUtils";
import { ColorConfig } from "../config/ColorConfig";
import { Reader } from "../common/Reader";
import { KeyMapping, RefreshType, IHelpService } from "../config/KeyMapConfig";
import { KeyMappingInfo } from "../config/KeyMapConfig";
import { IBlessedView } from "./IBlessedView";
import { messageBox } from "./widget/MessageBox";
import { inputBox } from "./widget/InputBox";
import { Editor, IViewBuffer, EDIT_MODE } from "../editor/Editor";
import { Color } from "../common/Color";
import mainFrame from "./MainFrame";
const log = Logger( "BlassedEditor" );
@KeyMapping(KeyMappingInfo.Editor)
export class BlessedEditor extends Editor implements IBlessedView, IHelpService {
colorEdit: Color = null;
colorStat: Color = null;
colorEditInfo: Color = null;
colorEditInfoA: Color = null;
baseWidget: Widget = null;
editor: Widget = null;
header: Widget = null;
tailer: Widget = null;
reader: Reader = null;
isCursorDraw: boolean = false;
isBoxDraw: boolean = false;
cursor = { x: -1, y: -1 };
constructor(opts: Widgets.BoxOptions | any, reader: Reader = null) {
super();
this.colorStat = ColorConfig.instance().getBaseColor("stat");
this.colorEdit = ColorConfig.instance().getBaseColor("edit");
this.colorEditInfo = ColorConfig.instance().getBaseColor("edit_info");
this.colorEditInfoA = ColorConfig.instance().getBaseColor("edit_info_a");
this.baseWidget = new Widget({ ...opts });
this.reader = reader;
this.editor = new Widget({
parent: this.baseWidget,
border: "line",
left: 0,
top: 1,
width: "100%",
height: "100%-2"
});
this.header = new Widget({
parent: this.baseWidget,
left: 0,
top: 0,
width: "100%",
height: 1,
style: {
bg: this.colorStat.back,
fg: this.colorStat.font
}
});
this.tailer = new Widget({
parent: this.baseWidget,
left: 0,
top: "100%-1",
width: "100%",
height: 1,
style: {
bg: this.colorStat.back,
fg: this.colorStat.font
}
});
this.header.on("prerender", () => {
log.debug( "header prerender !!! - Start %d", this.baseWidget._viewCount );
this.header.setContent(this.title);
});
this.tailer.on("prerender", () => {
log.debug( "tailer prerender !!! - Start %d", this.baseWidget._viewCount );
let status1 = "";
status1 = this.lastDoInfoLength !== this.doInfo.length ? "[" + new Color(2).fontBlessFormat("Change") + "]" : status1;
status1 = this.isReadOnly ? "[" + new Color(2).fontBlessFormat("ReadOnly") + "]" : status1;
let status2 = "";
status2 = this.isDosMode ? "[" + new Color(2).fontBlessFormat("DOS") + "]" : status2;
let status3 = "[" + new Color(2).fontBlessFormat(this.isInsert ? "Ins" : "Ovr") + "]";
status3 = this.editMode === EDIT_MODE.SELECT ? "[" + new Color(2).fontBlessFormat("Select") + "]" : status3;
this.tailer.setContentFormat(" %-10s{|}Line {bold}%3d{/bold}({bold}%3d{/bold}) Col {bold}%-3d{/bold} [%s]%s%s",
status1, this.curLine + 1, this.buffers.length, this.curColumn + 1, this.encoding.toUpperCase(), status2, status3);
});
this.editor.on("detach", () => {
if ( !this.isCursorDraw ) {
this.editor.box.screen.program.hideCursor();
}
});
this.editor.on("render", () => {
if ( !this.isCursorDraw ) {
if ( this.editor.screen.program.cursorHidden ) {
this.editor.screen.program.showCursor();
}
}
});
this.editor.on("resize", () => {
process.nextTick(() => {
this.column = this.editor.width as number - (this.hasBoxDraw() ? 2 : 0);
this.line = this.editor.height as number - (this.hasBoxDraw() ? 2 : 0);
});
});
(this.editor.box as any).render = () => {
this._render();
};
}
setBoxDraw( boxDraw: boolean ) {
this.editor.setBorderLine( boxDraw );
}
hasBoxDraw(): boolean {
return this.editor.hasBorderLine();
}
setViewTitle( title ) {
this.title = StringUtils.ellipsis( title, this.editor.width as number);
}
keyWrite( keyInfo ): RefreshType {
if ( keyInfo && keyInfo.name !== "return" ) {
const ch = keyInfo.sequence || keyInfo.ch;
const chlen = charWidth( ch );
log.debug( "keywrite : [%j] charlen [%d]", keyInfo, chlen );
if ( chlen > 0 ) {
this.inputData( ch );
}
return RefreshType.OBJECT;
} else {
log.debug( "NOT - pty write : [%j]", keyInfo );
}
return RefreshType.NONE;
}
postLoad(): void {
// TODO: editor file highlight
}
postUpdateLines(_line?: number, _height?: number): void {
// TODO: editor file highlight
}
inputBox(title: string, text: string, inputedText?: string, buttons?: string[]): Promise<string[]> {
return inputBox({
parent: this.baseWidget.screen,
title: title,
button: buttons,
defaultText: inputedText
});
}
messageBox(title: any, text: any, buttons?: string[]): Promise<string> {
return messageBox({
parent: this.baseWidget.screen,
title: title,
msg: text,
button: buttons
});
}
setReader(reader: Reader) {
this.reader = reader;
}
getReader(): Reader {
return this.reader;
}
destroy() {
super.destory();
this.baseWidget.destroy();
this.baseWidget = null;
}
getWidget(): Widget {
return this.baseWidget;
}
setFocus() {
this.baseWidget.setFocus();
}
hasFocus(): boolean {
return this.baseWidget.hasFocus();
}
hide() {
this.baseWidget.hide();
}
show() {
this.baseWidget.show();
}
render() {
this.baseWidget.render();
}
viewName(): string {
return "Editor";
}
_cursorCheck() {
const viewLines = this.viewBuffers.filter( item => item.textLine === this.curLine );
let x = this.curColumn;
let length = 0;
let y = 0;
let n = 0;
for ( n = 0; n < viewLines.length; n++ ) {
const strLen = strWidth(viewLines[n].text);
length += strLen;
if ( length >= this.curColumn ) {
y = viewLines[n].viewLine;
if ( viewLines[n].isNext && x === this.column ) {
y++;
x = 0;
}
break;
}
x -= strLen;
}
if ( viewLines[n] && viewLines[n].text && viewLines[n].text.length > 0 ) {
log.info( "cursor textlen [%d] width [%d] curColumn [%d] x [%d] y [%d] isNext [%s]", viewLines[n].text.length, this.column, this.curColumn, x, y, viewLines[n].isNext );
}
// x = strWidth(viewLines[n].text.substr(0, x));
return { y, x };
}
_render(startRow = -1, endRow = -1) {
const box: any = this.editor.box as Widgets.BoxElement;
const screen = this.editor.screen as any;
let ret = null;
try {
ret = (box as any)._render();
} catch( e ) {
log.error( e );
this.cursor = { x: -1, y: -1 };
return;
}
if (!ret) {
this.cursor = { x: -1, y: -1 };
return;
}
box.dattr = box.sattr(box.style);
// eslint-disable-next-line prefer-const
let xi = ret.xi + box.ileft, xl = ret.xl - box.iright, yi = ret.yi + box.itop, yl = ret.yl - box.ibottom, cursor;
this.line = box.height - 2;
this.column = box.width - 2;
this.screenMemSave( this.line, this.column );
const { x: curX, y: curY } = this._cursorCheck();
this.cursor = { x: xi + curX, y: yi + curY };
// log.debug( "[%d/%d] cursor : [%d] [%d] [%d] [%d]", this.line, this.column, this.curColumn, curX, curY, cursor );
for (let y = Math.max(yi, 0); y < yl; y++) {
const line = screen.lines[y];
if (!line) break;
if (curY === y - yi && this.hasFocus() ) {
cursor = xi + curX;
} else {
cursor = -1;
}
const bufferLine: IViewBuffer = this.viewBuffers[y - yi];
//log.debug( "line : %d, [%d] [%s]", y - yi, bufferLine.viewLine, bufferLine.text );
let tpos = 0;
for (let x = Math.max(xi, 0); x < xl; x++) {
if (!line[x]) break;
line[x][0] = (box as any).sattr({
bold: false,
underline: false,
blink: false,
inverse: false,
invisible: false,
bg: box.style.bg,
fg: box.style.fg,
});
if ( this.isCursorDraw && x === cursor) {
line[x][0] = (box as any).sattr({
bold: false,
underline: false,
blink: false,
inverse: false,
invisible: false,
bg: box.style.bg,
fg: box.style.fg
}) | (8 << 18);
}
line[x][1] = " ";
if ( x - xi > -1 && bufferLine && bufferLine.text && tpos < bufferLine.text.length ) {
if ( bufferLine.selectInfo ) {
const { all, start, end } = bufferLine.selectInfo;
let select = all;
if ( !select && tpos >= start ) {
if ( end === -1 || end >= tpos ) {
select = true;
}
}
if ( select ) {
line[x][0] = (box as any).sattr({
bold: false,
underline: false,
blink: false,
inverse: false,
invisible: false,
bg: box.style.bg,
fg: box.style.fg
}) | (8 << 18);
}
}
let ch = bufferLine.text[tpos++];
const chSize = unicode.charWidth( ch );
if (chSize === 0 ) {
ch = "";
} else {
line[x][1] = ch;
if ( chSize > 1 ) {
if ( ch === "\t" ) {
line[x][1] = " ";
}
for ( let i = 1; i < chSize; i++ ) {
line[x+i][0] = (box as any).sattr({
bold: false,
underline: false,
blink: false,
inverse: false,
invisible: false,
bg: box.style.bg,
fg: box.style.fg,
});
line[x+i][1] = " ";
}
x += chSize - 1;
}
}
}
}
line.dirty = true;
screen.lines[y] = line;
}
if ( startRow !== -1 && endRow !== -1 ) {
screen.draw(yi + startRow, yi + endRow);
}
return ret;
}
updateCursor() {
if ( !this.isCursorDraw ) {
const { x, y } = this.cursor;
if ( x > -1 && y > -1 ) {
log.debug( "updateCursor: Row %d/ Col %d", y, x);
this.editor.screen.program.cursorPos( y, x );
}
}
}
async quitEditorPromise() {
const result = await super.quitPromise();
if ( result ) {
await mainFrame().editorPromise(); // quit
}
}
} | the_stack |
import { createToken, Lexer, TokenType } from 'chevrotain';
export interface TokenVocabulary {
[vocab: string]: TokenType;
}
export const ReservedKeyword = createToken({
name: 'KeywordReserved',
pattern: Lexer.NA,
});
export const Keyword = createToken({
name: 'Keyword',
pattern: Lexer.NA,
});
export const DateFunction = createToken({
name: 'DateFunction',
pattern: Lexer.NA,
});
export const AggregateFunction = createToken({
name: 'AggregateFunction',
pattern: Lexer.NA,
});
export const LocationFunction = createToken({
name: 'LocationFunction',
pattern: Lexer.NA,
});
export const FieldsFunction = createToken({
name: 'FieldsFunction',
pattern: Lexer.NA,
});
export const FieldsFunctionParamIdentifier = createToken({
name: 'FieldsFunctionParamIdentifier',
pattern: Lexer.NA,
});
export const OtherFunction = createToken({
name: 'OtherFunction',
pattern: Lexer.NA,
});
export const DateLiteral = createToken({
name: 'DateLiteral',
pattern: Lexer.NA,
});
export const DateLiteralNotIdentifier = createToken({
name: 'DateLiteralNotIdentifier',
pattern: Lexer.NA,
});
export const DateNLiteral = createToken({
name: 'DateNLiteral',
pattern: Lexer.NA,
});
export const RelationalOperator = createToken({
name: 'RelationalOperator',
pattern: Lexer.NA,
});
export const SymbolIdentifier = createToken({
name: 'SymbolIdentifier',
pattern: Lexer.NA,
});
export const DateIdentifier = createToken({
name: 'DateIdentifier',
pattern: Lexer.NA,
});
export const NumberIdentifier = createToken({
name: 'NumberIdentifier',
pattern: Lexer.NA,
});
export const DecimalNumberIdentifier = createToken({
name: 'DecimalNumberIdentifier',
pattern: Lexer.NA,
});
export const IntegerNumberIdentifier = createToken({
name: 'IntegerNumberIdentifier',
pattern: Lexer.NA,
});
export const IdentifierNotKeyword = createToken({
name: 'IdentifierNotKeyword',
pattern: Lexer.NA,
});
export const UsingScopeEnumeration = createToken({
name: 'UsingScopeEnumeration',
pattern: Lexer.NA,
});
// This is a token that will be invoked to force a parsing error if there is a paren mismatch
export const RParenMismatch = createToken({
name: 'RParenMismatch',
pattern: Lexer.NA,
});
const identifierRegex = /[a-zA-Z][a-zA-Z0-9_.]*/y;
/**
* Ensure we do not allow two decimal places in a row
* @param text
* @param startOffset
*/
function matchIdentifier(text: string, startOffset: number) {
// // using 'y' sticky flag (Note it is not supported on IE11...)
// // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky
identifierRegex.lastIndex = startOffset;
const execResult = identifierRegex.exec(text);
if (execResult && execResult[0].includes('..')) {
return null;
}
return execResult;
}
// export const Identifier = createToken({ name: 'Identifier', pattern: /[a-zA-Z][a-zA-Z0-9_.]*/, categories: [IdentifierNotKeyword] });
export const Identifier = createToken({
name: 'Identifier',
pattern: matchIdentifier,
line_breaks: false,
categories: [IdentifierNotKeyword],
start_chars_hint: [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z',
],
});
export const StringIdentifier = createToken({ name: 'StringIdentifier', line_breaks: true, pattern: /(')(?:(?=(\\?))\2.)*?\1/ });
export const WhiteSpace = createToken({
name: 'WhiteSpace',
pattern: /\s+/,
group: Lexer.SKIPPED,
});
// // GROUPS
// export const LITERAL = createToken({ name: 'LITERAL', pattern: Lexer.NA });
// export const RELATIONAL_OPERATOR = createToken({ name: 'RELATIONAL_OPERATOR', pattern: Lexer.NA });
// export const EQUALITY_OPERATOR = createToken({ name: 'EQUALITY_OPERATOR', pattern: Lexer.NA });
// export const PRINT = createToken({ name: 'PRINT', pattern: Lexer.NA });
// RESERVED KEYWORDS
// We specify the "longer_alt" property to resolve keywords vs identifiers ambiguity.
// See: https://github.com/SAP/chevrotain/blob/master/examples/lexer/keywords_vs_identifiers/keywords_vs_identifiers.js
export const And = createToken({ name: 'AND', pattern: /AND/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const As = createToken({ name: 'AS', pattern: /AS/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Desc = createToken({ name: 'DESC', pattern: /DESC/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Asc = createToken({ name: 'ASC', pattern: /ASC/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
// FIXME: split into two tokens, BY is a reserved keyword, order is not
export const OrderBy = createToken({ name: 'ORDER_BY', pattern: /ORDER BY/i, longer_alt: Identifier });
export const Cube = createToken({ name: 'CUBE', pattern: /CUBE/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Else = createToken({ name: 'ELSE', pattern: /ELSE/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Excludes = createToken({
name: 'EXCLUDES',
pattern: /EXCLUDES/i,
longer_alt: Identifier,
categories: [Keyword, ReservedKeyword],
});
export const False = createToken({ name: 'FALSE', pattern: /FALSE/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const First = createToken({ name: 'FIRST', pattern: /FIRST/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const From = createToken({ name: 'FROM', pattern: /FROM/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
// FIXME: split into two tokens, BY is a reserved keyword, group is not
export const GroupBy = createToken({ name: 'GROUP_BY', pattern: /GROUP BY/i, longer_alt: Identifier });
export const Having = createToken({ name: 'HAVING', pattern: /HAVING/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const In = createToken({ name: 'IN', pattern: /IN/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
// FIXME: split into two tokens, NOT is a reserved keyword, IN is not
export const NotIn = createToken({ name: 'NOT_IN', pattern: /NOT IN/i, longer_alt: Identifier });
export const Includes = createToken({
name: 'INCLUDES',
pattern: /INCLUDES/i,
longer_alt: Identifier,
categories: [Keyword, ReservedKeyword],
});
export const Last = createToken({ name: 'LAST', pattern: /LAST/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Like = createToken({ name: 'LIKE', pattern: /LIKE/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Limit = createToken({ name: 'LIMIT', pattern: /LIMIT/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Not = createToken({ name: 'NOT', pattern: /NOT/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Null = createToken({ name: 'NULL', pattern: /NULL/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Nulls = createToken({ name: 'NULLS', pattern: /NULLS/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Or = createToken({ name: 'OR', pattern: /OR/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Rollup = createToken({ name: 'ROLLUP', pattern: /ROLLUP/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Select = createToken({ name: 'SELECT', pattern: /SELECT/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const True = createToken({ name: 'TRUE', pattern: /TRUE/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Using = createToken({ name: 'USING', pattern: /USING/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Where = createToken({ name: 'WHERE', pattern: /WHERE/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const With = createToken({ name: 'WITH', pattern: /WITH/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const For = createToken({ name: 'FOR', pattern: /FOR/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
export const Update = createToken({ name: 'UPDATE', pattern: /UPDATE/i, longer_alt: Identifier, categories: [Keyword, ReservedKeyword] });
// NON-RESERVED KEYWORDS
export const Above = createToken({ name: 'ABOVE', pattern: /ABOVE/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const AboveOrBelow = createToken({
name: 'ABOVE_OR_BELOW',
pattern: /ABOVE_OR_BELOW/i,
longer_alt: Identifier,
categories: [Keyword, Identifier],
});
export const ApexNew = createToken({ name: 'new', pattern: /new/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const At = createToken({ name: 'AT', pattern: /AT/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const Below = createToken({ name: 'BELOW', pattern: /BELOW/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const DataCategory = createToken({
name: 'DATA_CATEGORY',
pattern: /DATA CATEGORY/i,
longer_alt: Identifier,
categories: [Keyword],
});
export const End = createToken({ name: 'END', pattern: /END/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const Offset = createToken({ name: 'OFFSET', pattern: /OFFSET/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const Reference = createToken({
name: 'REFERENCE',
pattern: /REFERENCE/i,
longer_alt: Identifier,
categories: [Keyword, Identifier],
});
export const Scope = createToken({ name: 'SCOPE', pattern: /SCOPE/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const Tracking = createToken({ name: 'TRACKING', pattern: /TRACKING/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const Then = createToken({ name: 'THEN', pattern: /THEN/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const Typeof = createToken({ name: 'TYPEOF', pattern: /TYPEOF/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const View = createToken({ name: 'VIEW', pattern: /VIEW/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const Viewstat = createToken({ name: 'VIEWSTAT', pattern: /VIEWSTAT/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const When = createToken({ name: 'WHEN', pattern: /WHEN/i, longer_alt: Identifier, categories: [Keyword, Identifier] });
export const SecurityEnforced = createToken({
name: 'SECURITY_ENFORCED',
pattern: /SECURITY_ENFORCED/i,
longer_alt: Identifier,
categories: [Keyword, Identifier],
});
// DATE FUNCTIONS
export const CalendarMonth = createToken({
name: 'CALENDAR_MONTH',
pattern: /CALENDAR_MONTH/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const CalendarQuarter = createToken({
name: 'CALENDAR_QUARTER',
pattern: /CALENDAR_QUARTER/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const CalendarYear = createToken({
name: 'CALENDAR_YEAR',
pattern: /CALENDAR_YEAR/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const DayInMonth = createToken({
name: 'DAY_IN_MONTH',
pattern: /DAY_IN_MONTH/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const DayInWeek = createToken({
name: 'DAY_IN_WEEK',
pattern: /DAY_IN_WEEK/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const DayInYear = createToken({
name: 'DAY_IN_YEAR',
pattern: /DAY_IN_YEAR/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const DayOnly = createToken({
name: 'DAY_ONLY',
pattern: /DAY_ONLY/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const FiscalMonth = createToken({
name: 'FISCAL_MONTH',
pattern: /FISCAL_MONTH/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const FiscalQuarter = createToken({
name: 'FISCAL_QUARTER',
pattern: /FISCAL_QUARTER/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const FiscalYear = createToken({
name: 'FISCAL_YEAR',
pattern: /FISCAL_YEAR/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const HourInDay = createToken({
name: 'HOUR_IN_DAY',
pattern: /HOUR_IN_DAY/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const WeekInMonth = createToken({
name: 'WEEK_IN_MONTH',
pattern: /WEEK_IN_MONTH/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
export const WeekInYear = createToken({
name: 'WEEK_IN_YEAR',
pattern: /WEEK_IN_YEAR/i,
longer_alt: Identifier,
categories: [DateFunction, Identifier],
});
// AGGREGATE FUNCTIONS
export const Avg = createToken({ name: 'AVG', pattern: /AVG/i, longer_alt: Identifier, categories: [AggregateFunction, Identifier] });
export const Count = createToken({ name: 'COUNT', pattern: /COUNT/i, longer_alt: Identifier, categories: [AggregateFunction, Identifier] });
export const CountDistinct = createToken({
name: 'COUNT_DISTINCT',
pattern: /COUNT_DISTINCT/i,
longer_alt: Identifier,
categories: [AggregateFunction, Identifier],
});
export const Min = createToken({ name: 'MIN', pattern: /MIN/i, longer_alt: Identifier, categories: [AggregateFunction, Identifier] });
export const Max = createToken({ name: 'MAX', pattern: /MAX/i, longer_alt: Identifier, categories: [AggregateFunction, Identifier] });
export const Sum = createToken({ name: 'SUM', pattern: /SUM/i, longer_alt: Identifier, categories: [AggregateFunction, Identifier] });
// LOCATION FUNCTIONS
export const Distance = createToken({
name: 'DISTANCE',
pattern: /DISTANCE/i,
longer_alt: Identifier,
categories: [LocationFunction, Identifier],
});
export const Geolocation = createToken({
name: 'GEOLOCATION',
pattern: /GEOLOCATION/i,
longer_alt: Identifier,
categories: [LocationFunction, Identifier],
});
// FIELDS FUNCTIONS
export const Fields = createToken({
name: 'FIELDS',
pattern: /FIELDS/i,
longer_alt: Identifier,
categories: [FieldsFunction, Identifier],
});
// OTHER FUNCTIONS
export const Format = createToken({
name: 'FORMAT',
pattern: /FORMAT/i,
longer_alt: Identifier,
categories: [OtherFunction, Identifier],
});
export const Tolabel = createToken({
name: 'toLabel',
pattern: /TOLABEL/i,
longer_alt: Identifier,
categories: [OtherFunction, Identifier],
});
export const ConvertTimeZone = createToken({
name: 'convertTimezone',
pattern: /CONVERTTIMEZONE/i,
longer_alt: Identifier,
categories: [OtherFunction, Identifier],
});
export const ConvertCurrency = createToken({
name: 'convertCurrency',
pattern: /CONVERTCURRENCY/i,
longer_alt: Identifier,
categories: [OtherFunction, Identifier],
});
export const Grouping = createToken({
name: 'GROUPING',
pattern: /GROUPING/i,
longer_alt: Identifier,
categories: [OtherFunction, Identifier],
});
// FIELDS() PARAMETERS
export const All = createToken({
name: 'ALL',
pattern: /ALL/i,
longer_alt: Identifier,
categories: [FieldsFunctionParamIdentifier, Identifier],
});
export const Custom = createToken({
name: 'CUSTOM',
pattern: /CUSTOM/i,
longer_alt: Identifier,
categories: [FieldsFunctionParamIdentifier, Identifier],
});
export const Standard = createToken({
name: 'STANDARD',
pattern: /STANDARD/i,
longer_alt: Identifier,
categories: [FieldsFunctionParamIdentifier, Identifier],
});
// DATE LITERALS
export const Yesterday = createToken({
name: 'YESTERDAY',
pattern: /YESTERDAY/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const Today = createToken({
name: 'TODAY',
pattern: /TODAY/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const Tomorrow = createToken({
name: 'TOMORROW',
pattern: /TOMORROW/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const LastWeek = createToken({
name: 'LAST_WEEK',
pattern: /LAST_WEEK/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const ThisWeek = createToken({
name: 'THIS_WEEK',
pattern: /THIS_WEEK/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const NextWeek = createToken({
name: 'NEXT_WEEK',
pattern: /NEXT_WEEK/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const LastMonth = createToken({
name: 'LAST_MONTH',
pattern: /LAST_MONTH/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const ThisMonth = createToken({
name: 'THIS_MONTH',
pattern: /THIS_MONTH/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const NextMonth = createToken({
name: 'NEXT_MONTH',
pattern: /NEXT_MONTH/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const Last90_days = createToken({
name: 'LAST_90_DAYS',
pattern: /LAST_90_DAYS/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const Next90_days = createToken({
name: 'NEXT_90_DAYS',
pattern: /NEXT_90_DAYS/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const ThisQuarter = createToken({
name: 'THIS_QUARTER',
pattern: /THIS_QUARTER/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const LastQuarter = createToken({
name: 'LAST_QUARTER',
pattern: /LAST_QUARTER/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const NextQuarter = createToken({
name: 'NEXT_QUARTER',
pattern: /NEXT_QUARTER/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const ThisYear = createToken({
name: 'THIS_YEAR',
pattern: /THIS_YEAR/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const LastYear = createToken({
name: 'LAST_YEAR',
pattern: /LAST_YEAR/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const NextYear = createToken({
name: 'NEXT_YEAR',
pattern: /NEXT_YEAR/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const ThisFiscalQuarter = createToken({
name: 'THIS_FISCAL_QUARTER',
pattern: /THIS_FISCAL_QUARTER/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const LastFiscalQuarter = createToken({
name: 'LAST_FISCAL_QUARTER',
pattern: /LAST_FISCAL_QUARTER/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const NextFiscalQuarter = createToken({
name: 'NEXT_FISCAL_QUARTER',
pattern: /NEXT_FISCAL_QUARTER/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const ThisFiscalYear = createToken({
name: 'THIS_FISCAL_YEAR',
pattern: /THIS_FISCAL_YEAR/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const LastFiscalYear = createToken({
name: 'LAST_FISCAL_YEAR',
pattern: /LAST_FISCAL_YEAR/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
export const NextFiscalYear = createToken({
name: 'NEXT_FISCAL_YEAR',
pattern: /NEXT_FISCAL_YEAR/i,
longer_alt: Identifier,
categories: [DateLiteral, Identifier, DateLiteralNotIdentifier],
});
// DATE_N_LITERALS
export const NextNDays = createToken({
name: 'NEXT_N_DAYS',
pattern: /NEXT_N_DAYS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const LastNDays = createToken({
name: 'LAST_N_DAYS',
pattern: /LAST_N_DAYS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NDaysAgo = createToken({
name: 'N_DAYS_AGO',
pattern: /N_DAYS_AGO/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NextNWeeks = createToken({
name: 'NEXT_N_WEEKS',
pattern: /NEXT_N_WEEKS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const LastNWeeks = createToken({
name: 'LAST_N_WEEKS',
pattern: /LAST_N_WEEKS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NWeeksAgo = createToken({
name: 'N_WEEKS_AGO',
pattern: /N_WEEKS_AGO/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NextNMonths = createToken({
name: 'NEXT_N_MONTHS',
pattern: /NEXT_N_MONTHS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const LastNMonths = createToken({
name: 'LAST_N_MONTHS',
pattern: /LAST_N_MONTHS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NMonthsAgo = createToken({
name: 'N_MONTHS_AGO',
pattern: /N_MONTHS_AGO/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NextNQuarters = createToken({
name: 'NEXT_N_QUARTERS',
pattern: /NEXT_N_QUARTERS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const LastNQuarters = createToken({
name: 'LAST_N_QUARTERS',
pattern: /LAST_N_QUARTERS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NQuartersAgo = createToken({
name: 'N_QUARTERS_AGO',
pattern: /N_QUARTERS_AGO/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NextNYears = createToken({
name: 'NEXT_N_YEARS',
pattern: /NEXT_N_YEARS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const LastNYears = createToken({
name: 'LAST_N_YEARS',
pattern: /LAST_N_YEARS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NYearsAgo = createToken({
name: 'N_YEARS_AGO',
pattern: /N_YEARS_AGO/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NextNFiscalQuarters = createToken({
name: 'NEXT_N_FISCAL_QUARTERS',
pattern: /NEXT_N_FISCAL_QUARTERS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const LastNFiscalQuarters = createToken({
name: 'LAST_N_FISCAL_QUARTERS',
pattern: /LAST_N_FISCAL_QUARTERS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NFiscalQuartersAgo = createToken({
name: 'N_FISCAL_QUARTERS_AGO',
pattern: /N_FISCAL_QUARTERS_AGO/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NextNFiscalYears = createToken({
name: 'NEXT_N_FISCAL_YEARS',
pattern: /NEXT_N_FISCAL_YEARS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const LastNFiscalYears = createToken({
name: 'LAST_N_FISCAL_YEARS',
pattern: /LAST_N_FISCAL_YEARS/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
export const NFiscalYearsAgo = createToken({
name: 'N_FISCAL_YEARS_AGO',
pattern: /N_FISCAL_YEARS_AGO/i,
longer_alt: Identifier,
categories: [DateNLiteral, Identifier],
});
// RELATIONAL OPERATORS
export const Equal = createToken({ name: 'EQUAL', pattern: '=', categories: [RelationalOperator] });
export const NotEqual = createToken({ name: 'NOT_EQUAL', pattern: /!=|<>/, categories: [RelationalOperator] });
export const LessThan = createToken({ name: 'LESS_THAN', pattern: '<', categories: [RelationalOperator] });
export const LessThanOrEqual = createToken({ name: 'LESS_THAN_OR_EQUAL', pattern: '<=', categories: [RelationalOperator] });
export const GreaterThan = createToken({ name: 'GREATER_THAN', pattern: '>', categories: [RelationalOperator] });
export const GreaterThanOrEqual = createToken({ name: 'GREATER_THAN_OR_EQUAL', pattern: '>=', categories: [RelationalOperator] });
// SYMBOLS
export const Decimal = createToken({ name: 'DECIMAL', pattern: '.', categories: [SymbolIdentifier] });
export const Colon = createToken({ name: 'COLON', pattern: ':', categories: [SymbolIdentifier] });
export const Semicolon = createToken({ name: 'SEMICOLON', pattern: ';', categories: [SymbolIdentifier] });
export const Comma = createToken({ name: 'COMMA', pattern: ',', categories: [SymbolIdentifier] });
export const Asterisk = createToken({ name: 'ASTERISK', pattern: '*', categories: [SymbolIdentifier] });
export const LParen = createToken({ name: 'L_PAREN', pattern: '(', categories: [SymbolIdentifier] });
export const RParen = createToken({ name: 'R_PAREN', pattern: ')', categories: [SymbolIdentifier] });
export const LSquareBracket = createToken({ name: 'L_SQUARE_BRACKET', pattern: '[', categories: [SymbolIdentifier] });
export const RSquareBracket = createToken({ name: 'R_SQUARE_BRACKET', pattern: ']', categories: [SymbolIdentifier] });
export const Plus = createToken({ name: 'PLUS', pattern: '+', categories: [SymbolIdentifier] });
export const Minus = createToken({ name: 'MINUS', pattern: '-', categories: [SymbolIdentifier] });
export const DateTime = createToken({
name: 'DATETIME',
pattern: /[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?(\Z|\.[0-9]+Z|\+[0-9]{2}:[0-9]{2}|\-[0-9]{2}:[0-9]{2}|\+[0-9]{4}|\-[0-9]{4})/i,
categories: [DateIdentifier],
});
export const DateToken = createToken({ name: 'DATE', pattern: /[0-9]{4}-[0-9]{2}-[0-9]{2}/, categories: [DateIdentifier] });
export const CurrencyPrefixedDecimal = createToken({
name: 'CURRENCY_PREFIXED_DECIMAL',
pattern: /[a-zA-Z]{3}[0-9]+\.\d+/,
longer_alt: Identifier,
categories: [DecimalNumberIdentifier],
});
export const SignedDecimal = createToken({
name: 'SIGNED_DECIMAL',
pattern: /(\-|\+)[0-9]*\.\d+/,
categories: [NumberIdentifier, DecimalNumberIdentifier],
});
export const UnsignedDecimal = createToken({
name: 'UNSIGNED_DECIMAL',
pattern: /[0-9]*\.\d+/,
categories: [NumberIdentifier, DecimalNumberIdentifier],
});
export const CurrencyPrefixedInteger = createToken({
name: 'CURRENCY_PREFIXED_INTEGER',
pattern: /[a-zA-Z]{3}[0-9]+/,
longer_alt: Identifier,
categories: [DecimalNumberIdentifier, Identifier],
});
export const SignedInteger = createToken({
name: 'SIGNED_INTEGER',
pattern: /(\-|\+)[0-9]+/,
categories: [NumberIdentifier, IntegerNumberIdentifier],
});
export const GeolocationUnit = createToken({
name: 'GEOLOCATION_UNIT',
pattern: /'(mi|km)'/i,
longer_alt: Identifier,
categories: [Identifier],
});
export const UnsignedInteger = createToken({
name: 'UNSIGNED_INTEGER',
pattern: /0|[1-9]\d*/,
categories: [NumberIdentifier, IntegerNumberIdentifier],
});
// Using Scope enumeration values
// https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_using_scope.htm?search_text=format()
// export const UsingScopeEnumeration = createToken({
// name: 'UsingScopeEnumeration',
// pattern: /DELEGATED|EVERYTHING|MINEANDMYGROUPS|MINE|MY_TERRITORY|MY_TEAM_TERRITORY|TEAM|ALLPRIVATE/i,
// longer_alt: Identifier,
// categories: [Identifier],
// start_chars_hint: ['A', 'D', 'E', 'M', 'T', 'a', 'd', 'e', 'm', 't'],
// });
export const Delegated = createToken({
name: 'Delegated',
pattern: /DELEGATED/i,
longer_alt: Identifier,
categories: [UsingScopeEnumeration, Identifier],
start_chars_hint: ['D', 'd'],
});
export const Everything = createToken({
name: 'Everything',
pattern: /EVERYTHING/i,
longer_alt: Identifier,
categories: [UsingScopeEnumeration, Identifier],
start_chars_hint: ['E', 'e'],
});
export const MineAndMyGroups = createToken({
name: 'MineAndMyGroups',
pattern: /MINEANDMYGROUPS/i,
longer_alt: Identifier,
categories: [UsingScopeEnumeration, Identifier],
start_chars_hint: ['M', 'm'],
});
export const Mine = createToken({
name: 'Mine',
pattern: /MINE/i,
longer_alt: Identifier,
categories: [UsingScopeEnumeration, Identifier],
start_chars_hint: ['M', 'm'],
});
export const MyTerritory = createToken({
name: 'MyTerritory',
pattern: /MY_TERRITORY/i,
longer_alt: Identifier,
categories: [UsingScopeEnumeration, Identifier],
start_chars_hint: ['M', 'm'],
});
export const MyTeamTerritory = createToken({
name: 'MyTeamTerritory',
pattern: /MY_TEAM_TERRITORY/i,
longer_alt: Identifier,
categories: [UsingScopeEnumeration, Identifier],
start_chars_hint: ['M', 'm'],
});
export const Team = createToken({
name: 'Team',
pattern: /TEAM/i,
longer_alt: Identifier,
categories: [UsingScopeEnumeration, Identifier],
start_chars_hint: ['T', 't'],
});
export const AllPrivate = createToken({
name: 'AllPrivate',
pattern: /ALLPRIVATE/i,
longer_alt: Identifier,
categories: [UsingScopeEnumeration, Identifier],
start_chars_hint: ['A', 'a'],
});
export const allTokens = [
// we place WhiteSpace first as it is very common thus it will speed up the lexer.
WhiteSpace,
// "keywords" appear before the Identifier
And,
Asc,
As,
OrderBy,
Cube,
Desc,
Else,
Excludes,
False,
First,
From,
Grouping,
GroupBy,
Having,
Includes,
Like,
Limit,
Nulls,
Null,
Rollup,
Select,
True,
Using,
Where,
With,
Update,
// https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_using_scope.htm?search_text=format()
Delegated,
Everything,
MineAndMyGroups,
Mine,
MyTerritory,
MyTeamTerritory,
Team,
AllPrivate, // https://help.salesforce.com/articleView?id=000334863&language=en_US&type=1&mode=1
AboveOrBelow,
Above,
ApexNew,
At,
Below,
DataCategory,
End,
Offset,
Reference,
Scope,
Tracking,
Then,
Typeof,
Viewstat,
View,
When,
SecurityEnforced,
CalendarMonth,
CalendarQuarter,
CalendarYear,
DayInMonth,
DayInWeek,
DayInYear,
DayOnly,
FiscalMonth,
FiscalQuarter,
FiscalYear,
HourInDay,
WeekInMonth,
WeekInYear,
Avg,
CountDistinct,
Count,
Min,
Max,
Sum,
Distance,
Geolocation,
Fields,
Format,
Tolabel,
ConvertTimeZone,
ConvertCurrency,
Yesterday,
Today,
Tomorrow,
LastWeek,
ThisWeek,
NextWeek,
LastMonth,
ThisMonth,
NextMonth,
Last90_days,
Next90_days,
ThisQuarter,
LastQuarter,
NextQuarter,
ThisYear,
LastYear,
NextYear,
ThisFiscalQuarter,
LastFiscalQuarter,
NextFiscalQuarter,
ThisFiscalYear,
LastFiscalYear,
NextFiscalYear,
NextNDays,
LastNDays,
NDaysAgo,
NextNWeeks,
LastNWeeks,
NWeeksAgo,
NextNMonths,
LastNMonths,
NMonthsAgo,
NextNQuarters,
LastNQuarters,
NQuartersAgo,
NextNYears,
LastNYears,
NYearsAgo,
NextNFiscalQuarters,
LastNFiscalQuarters,
NFiscalQuartersAgo,
NextNFiscalYears,
LastNFiscalYears,
NFiscalYearsAgo,
GeolocationUnit,
All,
Custom,
Standard,
In,
NotIn,
For,
Or,
Last,
Not,
// The Identifier must appear after the keywords because all keywords are valid identifiers.
CurrencyPrefixedDecimal,
CurrencyPrefixedInteger,
StringIdentifier,
Identifier,
DateTime,
DateToken,
SignedDecimal,
UnsignedDecimal,
UnsignedInteger,
SignedInteger,
Equal,
NotEqual,
LessThanOrEqual,
LessThan,
GreaterThanOrEqual,
GreaterThan,
Decimal,
Colon,
Semicolon,
Comma,
Asterisk,
LParen,
RParen,
LSquareBracket,
RSquareBracket,
Plus,
Minus,
];
const SoqlLexer = new Lexer(allTokens, { ensureOptimizations: true, skipValidations: false });
export function lex(soql: string) {
return SoqlLexer.tokenize(soql);
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { ApplicationOperations } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { BatchManagementClient } from "../batchManagementClient";
import {
Application,
ApplicationListNextOptionalParams,
ApplicationListOptionalParams,
ApplicationCreateOptionalParams,
ApplicationCreateResponse,
ApplicationDeleteOptionalParams,
ApplicationGetOptionalParams,
ApplicationGetResponse,
ApplicationUpdateOptionalParams,
ApplicationUpdateResponse,
ApplicationListResponse,
ApplicationListNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing ApplicationOperations operations. */
export class ApplicationOperationsImpl implements ApplicationOperations {
private readonly client: BatchManagementClient;
/**
* Initialize a new instance of the class ApplicationOperations class.
* @param client Reference to the service client
*/
constructor(client: BatchManagementClient) {
this.client = client;
}
/**
* Lists all of the applications in the specified account.
* @param resourceGroupName The name of the resource group that contains the Batch account.
* @param accountName The name of the Batch account.
* @param options The options parameters.
*/
public list(
resourceGroupName: string,
accountName: string,
options?: ApplicationListOptionalParams
): PagedAsyncIterableIterator<Application> {
const iter = this.listPagingAll(resourceGroupName, accountName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(resourceGroupName, accountName, options);
}
};
}
private async *listPagingPage(
resourceGroupName: string,
accountName: string,
options?: ApplicationListOptionalParams
): AsyncIterableIterator<Application[]> {
let result = await this._list(resourceGroupName, accountName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(
resourceGroupName,
accountName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
resourceGroupName: string,
accountName: string,
options?: ApplicationListOptionalParams
): AsyncIterableIterator<Application> {
for await (const page of this.listPagingPage(
resourceGroupName,
accountName,
options
)) {
yield* page;
}
}
/**
* Adds an application to the specified Batch account.
* @param resourceGroupName The name of the resource group that contains the Batch account.
* @param accountName The name of the Batch account.
* @param applicationName The name of the application. This must be unique within the account.
* @param options The options parameters.
*/
create(
resourceGroupName: string,
accountName: string,
applicationName: string,
options?: ApplicationCreateOptionalParams
): Promise<ApplicationCreateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, applicationName, options },
createOperationSpec
);
}
/**
* Deletes an application.
* @param resourceGroupName The name of the resource group that contains the Batch account.
* @param accountName The name of the Batch account.
* @param applicationName The name of the application. This must be unique within the account.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
accountName: string,
applicationName: string,
options?: ApplicationDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, applicationName, options },
deleteOperationSpec
);
}
/**
* Gets information about the specified application.
* @param resourceGroupName The name of the resource group that contains the Batch account.
* @param accountName The name of the Batch account.
* @param applicationName The name of the application. This must be unique within the account.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
accountName: string,
applicationName: string,
options?: ApplicationGetOptionalParams
): Promise<ApplicationGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, applicationName, options },
getOperationSpec
);
}
/**
* Updates settings for the specified application.
* @param resourceGroupName The name of the resource group that contains the Batch account.
* @param accountName The name of the Batch account.
* @param applicationName The name of the application. This must be unique within the account.
* @param parameters The parameters for the request.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
accountName: string,
applicationName: string,
parameters: Application,
options?: ApplicationUpdateOptionalParams
): Promise<ApplicationUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, applicationName, parameters, options },
updateOperationSpec
);
}
/**
* Lists all of the applications in the specified account.
* @param resourceGroupName The name of the resource group that contains the Batch account.
* @param accountName The name of the Batch account.
* @param options The options parameters.
*/
private _list(
resourceGroupName: string,
accountName: string,
options?: ApplicationListOptionalParams
): Promise<ApplicationListResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
listOperationSpec
);
}
/**
* ListNext
* @param resourceGroupName The name of the resource group that contains the Batch account.
* @param accountName The name of the Batch account.
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
resourceGroupName: string,
accountName: string,
nextLink: string,
options?: ApplicationListNextOptionalParams
): Promise<ApplicationListNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, nextLink, options },
listNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const createOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Application
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.parameters5,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.accountName1,
Parameters.applicationName
],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.accountName1,
Parameters.applicationName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.Application
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.accountName1,
Parameters.applicationName
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.Application
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.parameters6,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.accountName1,
Parameters.applicationName
],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const listOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ListApplicationsResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion, Parameters.maxresults],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.accountName1
],
headerParameters: [Parameters.accept],
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ListApplicationsResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion, Parameters.maxresults],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.accountName1,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import * as cdk from '@aws-cdk/core';
import * as cfn_parse from '@aws-cdk/core/lib/cfn-parse';
/**
* Properties for defining a `AWS::EFS::AccessPoint`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html
* @external
*/
export interface CfnAccessPointProps {
/**
* `AWS::EFS::AccessPoint.FileSystemId`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-filesystemid
* @external
*/
readonly fileSystemId: string;
/**
* `AWS::EFS::AccessPoint.AccessPointTags`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-accesspointtags
* @external
*/
readonly accessPointTags?: Array<CfnAccessPoint.AccessPointTagProperty | cdk.IResolvable> | cdk.IResolvable;
/**
* `AWS::EFS::AccessPoint.ClientToken`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-clienttoken
* @external
*/
readonly clientToken?: string;
/**
* `AWS::EFS::AccessPoint.PosixUser`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-posixuser
* @external
*/
readonly posixUser?: CfnAccessPoint.PosixUserProperty | cdk.IResolvable;
/**
* `AWS::EFS::AccessPoint.RootDirectory`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-rootdirectory
* @external
*/
readonly rootDirectory?: CfnAccessPoint.RootDirectoryProperty | cdk.IResolvable;
}
/**
* A CloudFormation `AWS::EFS::AccessPoint`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html
* @external
* @cloudformationResource AWS::EFS::AccessPoint
*/
export declare class CfnAccessPoint extends cdk.CfnResource implements cdk.IInspectable {
/**
* The CloudFormation resource type name for this resource class.
*
* @external
*/
static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EFS::AccessPoint";
/**
* A factory method that creates a new instance of this class from an object
* containing the CloudFormation properties of this resource.
* Used in the @aws-cdk/cloudformation-include module.
*
* @internal
*/
static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnAccessPoint;
/**
* @external
* @cloudformationAttribute AccessPointId
*/
readonly attrAccessPointId: string;
/**
* @external
* @cloudformationAttribute Arn
*/
readonly attrArn: string;
/**
* `AWS::EFS::AccessPoint.FileSystemId`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-filesystemid
* @external
*/
fileSystemId: string;
/**
* `AWS::EFS::AccessPoint.AccessPointTags`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-accesspointtags
* @external
*/
accessPointTags: Array<CfnAccessPoint.AccessPointTagProperty | cdk.IResolvable> | cdk.IResolvable | undefined;
/**
* `AWS::EFS::AccessPoint.ClientToken`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-clienttoken
* @external
*/
clientToken: string | undefined;
/**
* `AWS::EFS::AccessPoint.PosixUser`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-posixuser
* @external
*/
posixUser: CfnAccessPoint.PosixUserProperty | cdk.IResolvable | undefined;
/**
* `AWS::EFS::AccessPoint.RootDirectory`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-rootdirectory
* @external
*/
rootDirectory: CfnAccessPoint.RootDirectoryProperty | cdk.IResolvable | undefined;
/**
* Create a new `AWS::EFS::AccessPoint`.
*
* @param scope - scope in which this resource is defined.
* @param id - scoped id of the resource.
* @param props - resource properties.
* @external
*/
constructor(scope: cdk.Construct, id: string, props: CfnAccessPointProps);
/**
* (experimental) Examines the CloudFormation resource and discloses attributes.
*
* @param inspector - tree inspector to collect and process attributes.
* @experimental
*/
inspect(inspector: cdk.TreeInspector): void;
/**
* @external
*/
protected get cfnProperties(): {
[key: string]: any;
};
/**
* @external
*/
protected renderProperties(props: {
[key: string]: any;
}): {
[key: string]: any;
};
}
/**
* A CloudFormation `AWS::EFS::AccessPoint`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html
* @external
* @cloudformationResource AWS::EFS::AccessPoint
*/
export declare namespace CfnAccessPoint {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-accesspointtag.html
* @external
*/
interface AccessPointTagProperty {
/**
* `CfnAccessPoint.AccessPointTagProperty.Key`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-accesspointtag.html#cfn-efs-accesspoint-accesspointtag-key
* @external
*/
readonly key?: string;
/**
* `CfnAccessPoint.AccessPointTagProperty.Value`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-accesspointtag.html#cfn-efs-accesspoint-accesspointtag-value
* @external
*/
readonly value?: string;
}
}
/**
* A CloudFormation `AWS::EFS::AccessPoint`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html
* @external
* @cloudformationResource AWS::EFS::AccessPoint
*/
export declare namespace CfnAccessPoint {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-creationinfo.html
* @external
*/
interface CreationInfoProperty {
/**
* `CfnAccessPoint.CreationInfoProperty.OwnerGid`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-creationinfo.html#cfn-efs-accesspoint-creationinfo-ownergid
* @external
*/
readonly ownerGid: string;
/**
* `CfnAccessPoint.CreationInfoProperty.OwnerUid`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-creationinfo.html#cfn-efs-accesspoint-creationinfo-owneruid
* @external
*/
readonly ownerUid: string;
/**
* `CfnAccessPoint.CreationInfoProperty.Permissions`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-creationinfo.html#cfn-efs-accesspoint-creationinfo-permissions
* @external
*/
readonly permissions: string;
}
}
/**
* A CloudFormation `AWS::EFS::AccessPoint`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html
* @external
* @cloudformationResource AWS::EFS::AccessPoint
*/
export declare namespace CfnAccessPoint {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-posixuser.html
* @external
*/
interface PosixUserProperty {
/**
* `CfnAccessPoint.PosixUserProperty.Gid`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-posixuser.html#cfn-efs-accesspoint-posixuser-gid
* @external
*/
readonly gid: string;
/**
* `CfnAccessPoint.PosixUserProperty.SecondaryGids`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-posixuser.html#cfn-efs-accesspoint-posixuser-secondarygids
* @external
*/
readonly secondaryGids?: string[];
/**
* `CfnAccessPoint.PosixUserProperty.Uid`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-posixuser.html#cfn-efs-accesspoint-posixuser-uid
* @external
*/
readonly uid: string;
}
}
/**
* A CloudFormation `AWS::EFS::AccessPoint`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html
* @external
* @cloudformationResource AWS::EFS::AccessPoint
*/
export declare namespace CfnAccessPoint {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-rootdirectory.html
* @external
*/
interface RootDirectoryProperty {
/**
* `CfnAccessPoint.RootDirectoryProperty.CreationInfo`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-rootdirectory.html#cfn-efs-accesspoint-rootdirectory-creationinfo
* @external
*/
readonly creationInfo?: CfnAccessPoint.CreationInfoProperty | cdk.IResolvable;
/**
* `CfnAccessPoint.RootDirectoryProperty.Path`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-accesspoint-rootdirectory.html#cfn-efs-accesspoint-rootdirectory-path
* @external
*/
readonly path?: string;
}
}
/**
* Properties for defining a `AWS::EFS::FileSystem`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html
* @external
*/
export interface CfnFileSystemProps {
/**
* `AWS::EFS::FileSystem.BackupPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-backuppolicy
* @external
*/
readonly backupPolicy?: CfnFileSystem.BackupPolicyProperty | cdk.IResolvable;
/**
* `AWS::EFS::FileSystem.Encrypted`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-encrypted
* @external
*/
readonly encrypted?: boolean | cdk.IResolvable;
/**
* `AWS::EFS::FileSystem.FileSystemPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-filesystempolicy
* @external
*/
readonly fileSystemPolicy?: any | cdk.IResolvable;
/**
* `AWS::EFS::FileSystem.FileSystemTags`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-filesystemtags
* @external
*/
readonly fileSystemTags?: CfnFileSystem.ElasticFileSystemTagProperty[];
/**
* `AWS::EFS::FileSystem.KmsKeyId`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-kmskeyid
* @external
*/
readonly kmsKeyId?: string;
/**
* `AWS::EFS::FileSystem.LifecyclePolicies`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-lifecyclepolicies
* @external
*/
readonly lifecyclePolicies?: Array<CfnFileSystem.LifecyclePolicyProperty | cdk.IResolvable> | cdk.IResolvable;
/**
* `AWS::EFS::FileSystem.PerformanceMode`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-performancemode
* @external
*/
readonly performanceMode?: string;
/**
* `AWS::EFS::FileSystem.ProvisionedThroughputInMibps`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-provisionedthroughputinmibps
* @external
*/
readonly provisionedThroughputInMibps?: number;
/**
* `AWS::EFS::FileSystem.ThroughputMode`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-throughputmode
* @external
*/
readonly throughputMode?: string;
}
/**
* A CloudFormation `AWS::EFS::FileSystem`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html
* @external
* @cloudformationResource AWS::EFS::FileSystem
*/
export declare class CfnFileSystem extends cdk.CfnResource implements cdk.IInspectable {
/**
* The CloudFormation resource type name for this resource class.
*
* @external
*/
static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EFS::FileSystem";
/**
* A factory method that creates a new instance of this class from an object
* containing the CloudFormation properties of this resource.
* Used in the @aws-cdk/cloudformation-include module.
*
* @internal
*/
static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnFileSystem;
/**
* @external
* @cloudformationAttribute Arn
*/
readonly attrArn: string;
/**
* @external
* @cloudformationAttribute FileSystemId
*/
readonly attrFileSystemId: string;
/**
* `AWS::EFS::FileSystem.BackupPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-backuppolicy
* @external
*/
backupPolicy: CfnFileSystem.BackupPolicyProperty | cdk.IResolvable | undefined;
/**
* `AWS::EFS::FileSystem.Encrypted`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-encrypted
* @external
*/
encrypted: boolean | cdk.IResolvable | undefined;
/**
* `AWS::EFS::FileSystem.FileSystemPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-filesystempolicy
* @external
*/
fileSystemPolicy: any | cdk.IResolvable | undefined;
/**
* `AWS::EFS::FileSystem.FileSystemTags`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-filesystemtags
* @external
*/
readonly tags: cdk.TagManager;
/**
* `AWS::EFS::FileSystem.KmsKeyId`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-kmskeyid
* @external
*/
kmsKeyId: string | undefined;
/**
* `AWS::EFS::FileSystem.LifecyclePolicies`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-lifecyclepolicies
* @external
*/
lifecyclePolicies: Array<CfnFileSystem.LifecyclePolicyProperty | cdk.IResolvable> | cdk.IResolvable | undefined;
/**
* `AWS::EFS::FileSystem.PerformanceMode`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-performancemode
* @external
*/
performanceMode: string | undefined;
/**
* `AWS::EFS::FileSystem.ProvisionedThroughputInMibps`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-provisionedthroughputinmibps
* @external
*/
provisionedThroughputInMibps: number | undefined;
/**
* `AWS::EFS::FileSystem.ThroughputMode`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-throughputmode
* @external
*/
throughputMode: string | undefined;
/**
* Create a new `AWS::EFS::FileSystem`.
*
* @param scope - scope in which this resource is defined.
* @param id - scoped id of the resource.
* @param props - resource properties.
* @external
*/
constructor(scope: cdk.Construct, id: string, props?: CfnFileSystemProps);
/**
* (experimental) Examines the CloudFormation resource and discloses attributes.
*
* @param inspector - tree inspector to collect and process attributes.
* @experimental
*/
inspect(inspector: cdk.TreeInspector): void;
/**
* @external
*/
protected get cfnProperties(): {
[key: string]: any;
};
/**
* @external
*/
protected renderProperties(props: {
[key: string]: any;
}): {
[key: string]: any;
};
}
/**
* A CloudFormation `AWS::EFS::FileSystem`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html
* @external
* @cloudformationResource AWS::EFS::FileSystem
*/
export declare namespace CfnFileSystem {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-filesystem-backuppolicy.html
* @external
*/
interface BackupPolicyProperty {
/**
* `CfnFileSystem.BackupPolicyProperty.Status`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-filesystem-backuppolicy.html#cfn-efs-filesystem-backuppolicy-status
* @external
*/
readonly status: string;
}
}
/**
* A CloudFormation `AWS::EFS::FileSystem`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html
* @external
* @cloudformationResource AWS::EFS::FileSystem
*/
export declare namespace CfnFileSystem {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-filesystem-elasticfilesystemtag.html
* @external
*/
interface ElasticFileSystemTagProperty {
/**
* `CfnFileSystem.ElasticFileSystemTagProperty.Key`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-filesystem-elasticfilesystemtag.html#cfn-efs-filesystem-elasticfilesystemtag-key
* @external
*/
readonly key: string;
/**
* `CfnFileSystem.ElasticFileSystemTagProperty.Value`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-filesystem-elasticfilesystemtag.html#cfn-efs-filesystem-elasticfilesystemtag-value
* @external
*/
readonly value: string;
}
}
/**
* A CloudFormation `AWS::EFS::FileSystem`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html
* @external
* @cloudformationResource AWS::EFS::FileSystem
*/
export declare namespace CfnFileSystem {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-filesystem-lifecyclepolicy.html
* @external
*/
interface LifecyclePolicyProperty {
/**
* `CfnFileSystem.LifecyclePolicyProperty.TransitionToIA`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-filesystem-lifecyclepolicy.html#cfn-efs-filesystem-lifecyclepolicy-transitiontoia
* @external
*/
readonly transitionToIa: string;
}
}
/**
* Properties for defining a `AWS::EFS::MountTarget`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html
* @external
*/
export interface CfnMountTargetProps {
/**
* `AWS::EFS::MountTarget.FileSystemId`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-filesystemid
* @external
*/
readonly fileSystemId: string;
/**
* `AWS::EFS::MountTarget.SecurityGroups`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-securitygroups
* @external
*/
readonly securityGroups: string[];
/**
* `AWS::EFS::MountTarget.SubnetId`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-subnetid
* @external
*/
readonly subnetId: string;
/**
* `AWS::EFS::MountTarget.IpAddress`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-ipaddress
* @external
*/
readonly ipAddress?: string;
}
/**
* A CloudFormation `AWS::EFS::MountTarget`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html
* @external
* @cloudformationResource AWS::EFS::MountTarget
*/
export declare class CfnMountTarget extends cdk.CfnResource implements cdk.IInspectable {
/**
* The CloudFormation resource type name for this resource class.
*
* @external
*/
static readonly CFN_RESOURCE_TYPE_NAME = "AWS::EFS::MountTarget";
/**
* A factory method that creates a new instance of this class from an object
* containing the CloudFormation properties of this resource.
* Used in the @aws-cdk/cloudformation-include module.
*
* @internal
*/
static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnMountTarget;
/**
* @external
* @cloudformationAttribute IpAddress
*/
readonly attrIpAddress: string;
/**
* `AWS::EFS::MountTarget.FileSystemId`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-filesystemid
* @external
*/
fileSystemId: string;
/**
* `AWS::EFS::MountTarget.SecurityGroups`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-securitygroups
* @external
*/
securityGroups: string[];
/**
* `AWS::EFS::MountTarget.SubnetId`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-subnetid
* @external
*/
subnetId: string;
/**
* `AWS::EFS::MountTarget.IpAddress`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-ipaddress
* @external
*/
ipAddress: string | undefined;
/**
* Create a new `AWS::EFS::MountTarget`.
*
* @param scope - scope in which this resource is defined.
* @param id - scoped id of the resource.
* @param props - resource properties.
* @external
*/
constructor(scope: cdk.Construct, id: string, props: CfnMountTargetProps);
/**
* (experimental) Examines the CloudFormation resource and discloses attributes.
*
* @param inspector - tree inspector to collect and process attributes.
* @experimental
*/
inspect(inspector: cdk.TreeInspector): void;
/**
* @external
*/
protected get cfnProperties(): {
[key: string]: any;
};
/**
* @external
*/
protected renderProperties(props: {
[key: string]: any;
}): {
[key: string]: any;
};
} | the_stack |
const { round } = Math;
/** Gnome libs imports */
import * as Clutter from 'clutter';
import * as Cogl from 'cogl';
import * as GObject from 'gobject';
import * as Meta from 'meta';
import { MsWindow } from 'src/layout/msWorkspace/msWindow';
import { Portion, PortionBorder } from 'src/layout/msWorkspace/portion';
import { BaseTilingLayout } from 'src/layout/msWorkspace/tilingLayouts/baseTiling';
import { FocusEffectEnum } from 'src/manager/msThemeManager';
import { Rectangular } from 'src/types/mod';
import { assert } from 'src/utils/assert';
import { registerGObjectClass } from 'src/utils/gjs';
import * as St from 'st';
import { MsWorkspace, Tileable } from '../msWorkspace';
/** Extension imports */
const Me = imports.misc.extensionUtils.getCurrentExtension();
const BORDER_WIDTH = 2;
@registerGObjectClass
export class BaseResizeableTilingLayout<
S extends { key: string }
> extends BaseTilingLayout<S> {
mainPortion: Portion;
currentFocusEffect: number;
borderContainer: Clutter.Actor | undefined;
borderActorList: Clutter.Actor[] | undefined;
constructor(
msWorkspace: MsWorkspace,
state: Partial<S> & { mainPortion?: Portion }
) {
super(msWorkspace, state);
this.mainPortion = new Portion();
if (state.mainPortion) {
this.mainPortion.state = state.mainPortion;
delete state.mainPortion;
}
Me.layoutManager.connect('gap-changed', this.onGapChange.bind(this));
this.currentFocusEffect = Me.msThemeManager.focusEffect;
this.onGapChange();
Me.msThemeManager.connect(
'focus-effect-changed',
this.onFocusEffectChanged.bind(this)
);
}
get state() {
return Object.assign({}, this._state, {
mainPortion: this.mainPortion.state,
});
}
onGapChange() {
if (!Me.layoutManager.someGap) {
if (!this.borderContainer) {
this.borderActorList = [];
this.borderContainer = new Clutter.Actor();
this.msWorkspace.msWorkspaceActor.add_child(
this.borderContainer
);
this.updateBordersActor();
}
} else {
if (this.borderContainer) {
this.borderContainer.destroy();
delete this.borderContainer;
delete this.borderActorList;
}
}
}
getTileableIndex(tileable: Tileable): number {
return this.tileableListVisible.indexOf(tileable);
}
getTileablePortionRatio(tileable: Tileable): Rectangular | undefined {
const index = this.getTileableIndex(tileable);
if (index < 0) {
return;
}
return this.mainPortion.getRatioForIndex(index);
}
getTileableBorder(
tileable: Tileable,
vertical = false,
after = false
): PortionBorder | undefined {
const index = this.getTileableIndex(tileable);
if (index < 0) {
return;
}
return this.mainPortion.getBorderForIndex(index, vertical, after);
}
applyBoxRatio(box: Clutter.ActorBox, ratio: Rectangular): Rectangular {
return {
x: round(box.x1 + ratio.x * box.get_width()),
y: round(box.y1 + ratio.y * box.get_height()),
width: round(ratio.width * box.get_width()),
height: round(ratio.height * box.get_height()),
};
}
applyBoxRatioAndGaps(
box: Clutter.ActorBox,
ratio: Rectangular
): Rectangular {
const { x, y, width, height } = this.applyBoxRatio(box, ratio);
return this.applyGaps(x, y, width, height);
}
tileTileable(tileable: Tileable, box: Clutter.ActorBox) {
const ratio = this.getTileablePortionRatio(tileable);
if (!ratio) {
return;
}
const { x, y, width, height } = this.applyBoxRatioAndGaps(box, ratio);
tileable.x = x;
tileable.y = y;
tileable.width = width;
tileable.height = height;
}
applyGaps(
x: number,
y: number,
width: number,
height: number
): Rectangular {
const gap = Me.layoutManager.gap || BORDER_WIDTH;
const screenGap = Me.layoutManager.useScreenGap
? Me.layoutManager.screenGap
: Me.layoutManager.gap;
return super.applyGaps(x, y, width, height, screenGap, gap);
}
updateMainPortionLength(length: number) {
while (this.mainPortion.portionLength > length) {
this.mainPortion.pop();
}
while (length > 1 && this.mainPortion.portionLength < length) {
this.mainPortion.push();
}
}
tileAll(box?: Clutter.ActorBox) {
box = this.resolveBox(box);
this.updateMainPortionLength(this.tileableListVisible.length);
if (this.borderContainer) {
this.updateBordersActor();
this.updateBordersPosition(box);
}
super.tileAll(box);
}
updateBordersActor() {
assert(this.borderActorList !== undefined, 'Layout has no borders');
assert(this.borderContainer !== undefined, 'Layout has no borders');
const borderLength = this.mainPortion.concatBorders.length;
if (this.borderActorList.length < borderLength) {
for (
let i = 0;
i <= borderLength - this.borderActorList.length;
i++
) {
const actor = new ResizableBorderActor();
this.borderActorList.push(actor);
this.borderContainer.add_child(actor);
}
} else if (this.borderActorList.length > borderLength) {
this.borderActorList
.splice(
borderLength,
this.borderActorList.length - borderLength
)
.forEach((actor) => {
actor.destroy();
});
}
}
updateBordersPosition(box: Clutter.ActorBox) {
const borderActorList = this.borderActorList;
assert(borderActorList !== undefined, 'Layout has no borders');
this.mainPortion.concatBorders.forEach((portionBorder, index) => {
const actor = borderActorList[index] as Clutter.Actor & {
portionBorder?: PortionBorder;
};
actor.portionBorder = portionBorder;
const ratio = this.mainPortion.getRatioForPortion(
portionBorder.firstPortion
);
const { x, y, width, height } = this.applyBoxRatio(box, ratio);
if (portionBorder.vertical) {
actor.x = x + width - BORDER_WIDTH / 2;
actor.y = y;
actor.height = height;
actor.width = BORDER_WIDTH;
} else {
actor.x = x;
actor.y = y + height - BORDER_WIDTH / 2;
actor.height = BORDER_WIDTH;
actor.width = width;
}
});
}
initializeTileable(tileable: Tileable) {
this.addUnFocusEffect(
tileable,
this.currentFocusEffect,
tileable === this.msWorkspace.tileableFocused
);
super.initializeTileable(tileable);
}
restoreTileable(tileable: Tileable) {
this.removeUnFocusEffect(tileable, this.currentFocusEffect);
super.restoreTileable(tileable);
}
onFocusEffectChanged() {
const oldFocusEffect = this.currentFocusEffect;
this.currentFocusEffect = Me.msThemeManager.focusEffect;
this.msWorkspace.tileableList.forEach((tileable) => {
this.removeUnFocusEffect(tileable, oldFocusEffect);
this.addUnFocusEffect(
tileable,
this.currentFocusEffect,
tileable === this.msWorkspace.tileableFocused
);
});
}
onFocusChanged(tileable: Tileable, oldTileable: Tileable | null) {
this.setUnFocusEffect(tileable, this.currentFocusEffect, true);
if (oldTileable) {
if (
oldTileable instanceof MsWindow &&
oldTileable.metaWindow &&
oldTileable.metaWindow.fullscreen
) {
oldTileable.metaWindow.unmake_fullscreen();
}
this.setUnFocusEffect(oldTileable, this.currentFocusEffect, false);
}
super.onFocusChanged(tileable, oldTileable);
}
addUnFocusEffect(tileable: Tileable, effect: number, focused: boolean) {
if (!tileable || tileable.focusEffects) return;
if (effect === FocusEffectEnum.DEFAULT) {
tileable.focusEffects = {
dimmer: new Clutter.BrightnessContrastEffect({
name: 'dimmer',
brightness: focused
? Clutter.Color.new(127, 127, 127, 255)
: Clutter.Color.new(100, 100, 100, 255),
}),
};
tileable.add_effect(tileable.focusEffects.dimmer!);
} else if (effect === FocusEffectEnum.BORDER) {
tileable.focusEffects = {
border: new PrimaryBorderEffect({
name: 'border',
opacity: focused ? 1.0 : 0.0,
}),
};
tileable.add_effect(tileable.focusEffects.border!);
}
}
removeUnFocusEffect(tileable: Tileable, effect: number) {
if (!tileable || !tileable.focusEffects) return;
tileable.remove_all_transitions();
if (effect === FocusEffectEnum.DEFAULT) {
assert(
tileable.focusEffects.dimmer !== undefined,
"Tilable doesn't have the dimmer effect"
);
tileable.remove_effect(tileable.focusEffects.dimmer);
} else if (effect === FocusEffectEnum.BORDER) {
assert(
tileable.focusEffects.border !== undefined,
"Tilable doesn't have the border effect"
);
tileable.remove_effect(tileable.focusEffects.border);
}
delete tileable.focusEffects;
}
setUnFocusEffect(tileable: Tileable, effect: number, focused: boolean) {
if (!tileable) return;
if (effect === FocusEffectEnum.DEFAULT) {
if (!focused) {
this.addUnFocusEffect(tileable, effect, !focused);
if (tileable.get_effect('dimmer')) {
tileable.ease_property(
'@effects.dimmer.brightness',
Clutter.Color.new(100, 100, 100, 255),
{
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
duration: 150,
}
);
}
} else {
if (tileable.get_effect('dimmer')) {
tileable.ease_property(
'@effects.dimmer.brightness',
Clutter.Color.new(127, 127, 127, 255),
{
duration: 150,
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
onComplete: () => {
// If we don't remove the effect it's can cause some issue with caching texture which lead to window flickering showing old texture
this.removeUnFocusEffect(tileable, effect);
},
}
);
}
}
} else if (effect === FocusEffectEnum.BORDER) {
if (focused) {
this.addUnFocusEffect(tileable, effect, focused);
} else {
this.removeUnFocusEffect(tileable, effect);
}
}
}
onDestroy() {
if (this.borderContainer) {
this.borderContainer.destroy();
}
super.onDestroy();
}
}
@registerGObjectClass
export class ResizableBorderActor extends St.Widget {
static metaInfo: GObject.MetaInfo = {
GTypeName: 'ResizableBorderActor',
Signals: {
'drag-start': {},
},
};
constructor() {
super({ reactive: true, track_hover: true });
this.set_background_color(
new Clutter.Color({ red: 10, green: 10, blue: 10, alpha: 255 })
);
this.connect('event', (actor, event) => {
const eventType = event.type();
switch (eventType) {
case Clutter.EventType.BUTTON_PRESS:
case Clutter.EventType.TOUCH_BEGIN: {
const border = (
this as Clutter.Actor & {
portionBorder?: PortionBorder;
}
).portionBorder;
assert(border !== undefined, 'Actor has no border');
Me.msWindowManager.msResizeManager.startResize(border);
break;
}
case Clutter.EventType.ENTER:
global.display.set_cursor(
Meta.Cursor.MOVE_OR_RESIZE_WINDOW
);
break;
case Clutter.EventType.LEAVE:
global.display.set_cursor(Meta.Cursor.DEFAULT);
break;
}
});
}
get vertical() {
return this.height > this.width;
}
}
@registerGObjectClass
export class PrimaryBorderEffect extends Clutter.Effect {
static metaInfo: GObject.MetaInfo = {
GTypeName: 'PrimaryBorderEffect',
Properties: {
opacity: GObject.ParamSpec.float(
'opacity',
'opacity',
'opacity',
GObject.ParamFlags.READWRITE,
0,
1,
1
),
},
};
private _pipeline: Cogl.Pipeline | null;
color: Cogl.Color;
// Note: Default value set by GObject due to the metaInfo declaration above
opacity!: number;
constructor(params: Partial<Clutter.Effect.ConstructorProperties>) {
super(params);
this._pipeline = null;
this.color = new Cogl.Color();
}
vfunc_paint_node(
node: Clutter.PaintNode,
paintContext: Clutter.PaintContext
) {
const framebuffer = paintContext.get_framebuffer();
const coglContext = framebuffer.get_context();
const actor = this.get_actor();
actor.continue_paint(paintContext);
if (!this._pipeline) {
this._pipeline = new Cogl.Pipeline(coglContext);
}
if (this.color !== Me.msThemeManager.primaryColor) {
this.color = Me.msThemeManager.primaryColor;
const c = this.color.copy();
c.set_alpha_float(this.opacity);
c.premultiply();
this._pipeline.set_color(c);
}
const alloc = actor.get_allocation_box();
const width = 2;
const allocWidth = alloc.get_width();
const allocHeight = alloc.get_height();
// clockwise order
framebuffer.draw_rectangle(this._pipeline, 0, 0, allocWidth, width);
framebuffer.draw_rectangle(
this._pipeline,
allocWidth - width,
width,
allocWidth,
allocHeight
);
framebuffer.draw_rectangle(
this._pipeline,
0,
allocHeight,
allocWidth - width,
allocHeight - width
);
framebuffer.draw_rectangle(
this._pipeline,
0,
allocHeight - width,
width,
width
);
}
} | the_stack |
import assert from "assert";
import { CharCode } from "../core/charcode.js";
import { formatDiagnostic, logDiagnostics, logVerboseTestOutput } from "../core/diagnostics.js";
import { hasParseError, NodeFlags, parse, visitChildren } from "../core/parser.js";
import { CadlScriptNode, Node, SourceFile, SyntaxKind } from "../core/types.js";
describe("compiler: syntax", () => {
describe("import statements", () => {
parseEach(['import "x";']);
parseErrorEach([
['namespace Foo { import "x"; }', [/Imports must be top-level/]],
['namespace Foo { } import "x";', [/Imports must come prior/]],
['model Foo { } import "x";', [/Imports must come prior/]],
]);
});
describe("empty script", () =>
parseEach([["", (n) => assert.strictEqual(n.statements.length, 0)]]));
describe("model statements", () => {
parseEach([
"model Car { };",
`@foo()
model Car { };`,
`model Car {
prop1: number,
prop2: string
};`,
`model Car {
optional?: number;
withDefault?: string = "mydefault";
};`,
`model Car {
prop1: number;
prop2: string;
}`,
`model Car {
engine: V6
}
model V6 {
name: string
}`,
`model Car {
@foo.bar(a, b)
prop1: number,
@foo.baz(10, "hello")
prop2: string
};`,
`model Car {
@foo()
"prop-1": number;
}`,
`
@Foo()
model Car {
@Foo.bar(10, "hello")
prop1: number,
@Foo.baz(a, b)
prop2: string
};`,
`@doc("""
Documentation
""")
model Car {
@doc("first")
prop1: number;
@doc("second")
prop2: number;
}`,
'model Foo { "strKey": number, "😂😂😂": string }',
"model Foo<A, B> { }",
"model Car { @foo @bar x: number }",
"model Car { ... A, ... B, c: number, ... D, e: string }",
"model Car { ... A.B, ... C<D> }",
"model Car is Vehicle { }",
]);
parseErrorEach([
["model Car is { }", [/Identifier expected/]],
["model Car is Foo extends Bar { }", [/'{' expected/]],
["model Car extends Bar is Foo { }", [/'{' expected/]],
["model Car { withDefaultMissing?: string = }", [/Expression expected/]],
[
`model Car { withDefaultButNotOptional: string = "foo" }`,
[/Cannot use default with non optional properties/],
],
["model", [/Identifier expected/]],
]);
});
describe("model extends statements", () => {
parseEach([
"model foo extends bar { }",
"model foo extends bar.baz { }",
"model foo extends bar<T> { }",
"model foo<T> extends bar<T> { }",
"model foo<T> extends bar.baz<T> { }",
]);
parseErrorEach([
["model foo extends { }", [/Identifier expected/]],
["model foo extends bar, baz { }", [/\'{' expected/]],
["model foo extends = { }", [/Identifier expected/]],
["model foo extends bar = { }", [/'{' expected/]],
]);
});
describe("model = statements", () => {
parseErrorEach([
["model x = y;", [/'{' expected/]],
["model foo = bar | baz;", [/'{' expected/]],
["model bar<a, b> = a | b;", [/'{' expected/]],
]);
});
describe("interface statements", () => {
parseEach([
"interface Foo { }",
"interface Foo<T> { }",
"interface Foo<T> mixes Bar<T> { }",
"interface Foo mixes Bar, Baz<T> { }",
"interface Foo { foo(): int32; }",
"interface Foo { foo(): int32; bar(): int32; }",
]);
});
describe("model expressions", () => {
parseEach(['model Car { engine: { type: "v8" } }']);
});
describe("tuple model expressions", () => {
parseEach(['namespace A { op b(param: [number, string]): [1, "hi"]; }']);
});
describe("array expressions", () => {
parseEach(["model A { foo: B[] }", "model A { foo: B[][] }"]);
});
describe("union expressions", () => {
parseEach(["model A { foo: B | C }", "model A { foo: B | C & D }", "model A { foo: | B | C }"]);
});
describe("union declarations", () => {
parseEach([
"union A { x: number, y: number } ",
"@dec union A { @dec a: string }",
"union A<T, V> { a: T; none: {} }",
`union A { "hi there": string }`,
]);
parseErrorEach([
[
'union A { @dec "x" x: number, y: string }',
[/':' expected/],
(n) => assert(!n.printable, "should not be printable"),
],
]);
});
describe("template instantiations", () => {
parseEach(["model A { x: Foo<number, string>; }", "model B { x: Foo<number, string>[]; }"]);
});
describe("intersection expressions", () => {
parseEach(["model A { foo: B & C }", "model A { foo: & B & C }"]);
});
describe("parenthesized expressions", () => {
parseEach(["model A { x: ((B | C) & D)[]; }"]);
});
describe("namespace statements", () => {
parseEach([
"namespace Store {}",
"namespace Store { op read(): int32; }",
"namespace Store { op read(): int32; op write(v: int32): {}; }",
"namespace Store.Read { op read(): int32; }",
"@foo namespace Store { @dec op read(): number; @dec op write(n: number): {}; }",
"@foo @bar namespace Store { @foo @bar op read(): number; }",
"namespace Store { namespace Read { op read(): int32; } namespace Write { op write(v: int32): {}; } }",
"namespace Store.Read { }",
"namespace Store;",
"namespace Store.Read;",
"@foo namespace Store.Read;",
"@foo namespace Store.Read { };",
]);
parseErrorEach([
["namespace Foo { namespace Store; }", [/Blockless namespace can only be top-level/]],
["namespace Store; namespace Store2;", [/Cannot use multiple blockless namespaces/]],
["model Foo { }; namespace Store;", [/Blockless namespaces can't follow other/]],
["namespace Foo { }; namespace Store;", [/Blockless namespaces can't follow other/]],
]);
});
describe("using statements", () => {
parseEach(["using A;", "using A.B;", "namespace Foo { using A; }"]);
});
describe("multiple statements", () => {
parseEach([
`
model A { };
model B { }
;
namespace I {
op foo(): number;
}
namespace J {
}
`,
]);
});
describe("comments", () => {
parseEach([
`
// Comment
model A { /* Another comment */
/*
and
another
*/
property /* 👀 */ : /* 👍 */ int32; // one more
}
`,
]);
});
describe("empty statements", () => {
parseEach([`;;;;`, `namespace Foo { model Car { }; };`, `model Car { };;;;`]);
});
describe("recovery", () => {
parseErrorEach([
[`model M { ]`, [/Property expected/]],
[
`
@dec1 @dec2 import "foo";
banana
model Foo
`,
[
/Cannot decorate import/,
/Cannot decorate import/,
/Statement expected/,
/'{', '=', 'extends', or 'is' expected/,
],
],
["model M {}; This is not a valid statement", [/Statement expected/]],
["model M {}; @dec ;", [/Cannot decorate empty statement/]],
]);
});
describe("BOM", () => {
parseEach(["\u{FEFF}/*<--BOM*/ model M {}"]);
parseErrorEach([["model\u{FEFF}/*<--BOM*/ M {}", [/Statement expected/]]]);
});
describe("unterminated tokens", () => {
parseErrorEach([["/* Yada yada yada", [/Unterminated multi-line comment/]]]);
const strings = [
'"banana',
'"banana\\',
'"banana\r"',
'"banana\n"',
'"banana\r\n"',
'"""\nbanana',
'"""\nbanana\\',
];
parseErrorEach(
Array.from(strings.entries()).map((e) => [
`alias ${String.fromCharCode(CharCode.A + e[0])} = ${e[1]}`,
[/Unterminated string literal/],
(node) => {
const statement = node.statements[0];
assert(statement.kind === SyntaxKind.AliasStatement, "alias statement expected");
const value = statement.value;
assert(value.kind === SyntaxKind.StringLiteral, "string literal expected");
assert.strictEqual(value.value, "banana");
},
])
);
});
describe("terminated tokens at EOF", () => {
parseErrorEach([
["alias X = 0x10101", [/';' expected/]],
["alias X = 0xBEEF", [/';' expected/]],
["alias X = 123", [/';' expected/]],
["alias X = 123e45", [/';' expected/]],
["alias X = 123.45", [/';' expected/]],
["alias X = 123.45e2", [/';' expected/]],
["alias X = Banana", [/';' expected/]],
['alias X = "Banana"', [/';' expected/]],
['alias X = """\nBanana\n"""', [/';' expected/]],
]);
});
describe("numeric literals", () => {
const good: [string, number][] = [
// Some questions remain here: https://github.com/Azure/adl/issues/506
["-0", -0],
["1e9999", Infinity],
["1e-9999", 0],
["-1e-9999", -0],
["-1e9999", -Infinity],
// NOTE: No octal in Cadl
["077", 77],
["+077", 77],
["-077", -77],
["0xABCD", 0xabcd],
["0xabcd", 0xabcd],
["0x1010", 0x1010],
["0b1010", 0b1010],
["0", 0],
["+0", 0],
["0.0", 0.0],
["+0.0", 0],
["-0.0", -0.0],
["123", 123],
["+123", 123],
["-123", -123],
["123.123", 123.123],
["+123.123", 123.123],
["-123.123", -123.123],
["789e42", 789e42],
["+789e42", 789e42],
["-789e42", -789e42],
["654.321e9", 654.321e9],
["+654.321e9", 654.321e9],
["-654.321e9", -654.321e9],
];
const bad: [string, RegExp][] = [
["123.", /Digit expected/],
["123.0e", /Digit expected/],
["123e", /Digit expected/],
["0b", /Binary digit expected/],
["0b2", /Binary digit expected/],
["0x", /Hexadecimal digit expected/],
["0xG", /Hexadecimal digit expected/],
];
parseEach(good.map((c) => [`alias M = ${c[0]};`, (node) => isNumericLiteral(node, c[1])]));
parseErrorEach(bad.map((c) => [`alias M = ${c[0]};`, [c[1]]]));
function isNumericLiteral(node: CadlScriptNode, value: number) {
const statement = node.statements[0];
assert(statement.kind === SyntaxKind.AliasStatement, "alias statement expected");
const assignment = statement.value;
assert(assignment?.kind === SyntaxKind.NumericLiteral, "numeric literal expected");
assert.strictEqual(assignment.value, value);
}
});
describe("identifiers", () => {
const good = [
"short",
"short42",
"lowercaseandlong",
"lowercaseandlong42",
"camelCase",
"camelCase42",
"PascalCase",
"PascalCase42",
"has_underscore",
"has_$dollar",
"_startsWithUnderscore",
"$startsWithDollar",
"Incompréhensible",
"incompréhensible",
"IncomprÉhensible",
"incomprÉhensible",
// normalization
["e\u{0301}toile", "étoile"],
// leading astral character
"𐌰𐌲",
// continuing astral character
"Banana𐌰𐌲42Banana",
"banana𐌰𐌲42banana",
// ZWNJ
"deaf\u{200c}ly",
// ZWJ
"क्ष",
// Leading emoji
"😁Yay",
// Continuing emoji
"Hi✋There",
];
const bad: [string, RegExp][] = [
["\u{D800}", /Invalid character/], // unpaired surrogate
["\u{E000}", /Invalid character/], // private use
["\u{FDD0}", /Invalid character/], // non-character
["\u{244B}", /Invalid character/], // unassigned
["\u{009F}", /Invalid character/], // control
["#", /Identifier expected/], // directive
["42", /Identifier expected/],
["true", /Keyword cannot be used as identifier/],
];
parseEach(
good.map((entry) => {
const input = typeof entry === "string" ? entry : entry[0];
const expected = typeof entry === "string" ? entry : entry[1];
return [
`model ${input} {}`,
(node) => {
const statement = node.statements[0];
assert(statement.kind === SyntaxKind.ModelStatement, "Model statement expected.");
assert.strictEqual(statement.id.sv, expected);
},
];
})
);
parseErrorEach(bad.map((e) => [`model ${e[0]} {}`, [e[1]]]));
});
// smaller repro of previous regen-samples baseline failures
describe("sample regressions", () => {
parseEach([
[
`/* \\n <-- before string! */ @pattern("\\\\w") model M {}`,
(node) => {
assert(node.statements[0].kind === SyntaxKind.ModelStatement);
assert(node.statements[0].decorators[0].arguments[0].kind === SyntaxKind.StringLiteral);
assert.strictEqual(node.statements[0].decorators[0].arguments[0].value, "\\w");
},
],
]);
});
describe("enum statements", () => {
parseEach([
"enum Foo { }",
"enum Foo { a, b }",
'enum Foo { a: "hi", c: 10 }',
"@foo enum Foo { @bar a, @baz b: 10 }",
]);
parseErrorEach([
["enum Foo { a: number }", [/Expected numeric or string literal/]],
["enum Foo { a: [number] }", [/Expected numeric or string literal/]],
["enum Foo { a: ; b: ; }", [/Expression expected/, /Expression expected/]],
["enum Foo { ;+", [/Enum member expected/]],
["enum { }", [/Identifier expected/]],
]);
});
describe("alias statements", () => {
parseEach(["alias X = 1;", "alias X = A | B;", "alias MaybeUndefined<T> = T | undefined;"]);
parseErrorEach([
["@foo alias Bar = 1;", [/Cannot decorate alias statement/]],
["alias Foo =", [/Expression expected/]],
["alias Foo<> =", [/Identifier expected/, /Expression expected/]],
["alias Foo<T> = X |", [/Expression expected/]],
["alias =", [/Identifier expected/]],
]);
});
});
type Callback = (node: CadlScriptNode) => void;
function parseEach(cases: (string | [string, Callback])[]) {
for (const each of cases) {
const code = typeof each === "string" ? each : each[0];
const callback = typeof each === "string" ? undefined : each[1];
it("parses `" + shorten(code) + "`", () => {
logVerboseTestOutput("=== Source ===");
logVerboseTestOutput(code);
logVerboseTestOutput("\n=== Parse Result ===");
const astNode = parse(code);
if (callback) {
callback(astNode);
}
dumpAST(astNode);
logVerboseTestOutput("\n=== Diagnostics ===");
if (astNode.parseDiagnostics.length > 0) {
const diagnostics = astNode.parseDiagnostics.map(formatDiagnostic).join("\n");
assert.strictEqual(
hasParseError(astNode),
astNode.parseDiagnostics.some((e) => e.severity === "error"),
"root node claims to have no parse errors, but these were reported:\n" +
diagnostics +
"\n(If you've added new AST nodes or properties, make sure you implemented the new visitors)"
);
assert.fail("Unexpected parse errors in test:\n" + diagnostics);
}
assert(astNode.printable, "Parse tree with no errors should be printable");
checkPositioning(astNode, astNode.file);
});
}
}
function checkPositioning(node: Node, file: SourceFile) {
visitChildren(node, (child) => {
if (child.pos < node.pos || child.end > node.end) {
logVerboseTestOutput("Parent: ");
dumpAST(node, file);
logVerboseTestOutput("Child: ");
dumpAST(child, file);
assert.fail("child node positioned outside parent node");
}
checkPositioning(child, file);
});
}
function parseErrorEach(cases: [string, RegExp[], Callback?][], significantWhitespace = false) {
for (const [code, matches, callback] of cases) {
it(`doesn't parse ${shorten(code)}`, () => {
logVerboseTestOutput("=== Source ===");
logVerboseTestOutput(code);
const astNode = parse(code);
if (callback) {
callback(astNode);
}
logVerboseTestOutput("\n=== Parse Result ===");
dumpAST(astNode);
logVerboseTestOutput("\n=== Diagnostics ===");
logVerboseTestOutput((log) => logDiagnostics(astNode.parseDiagnostics, log));
assert.notStrictEqual(astNode.parseDiagnostics.length, 0, "no diagnostics reported");
let i = 0;
for (const match of matches) {
assert.match(astNode.parseDiagnostics[i++].message, match);
}
assert(
hasParseError(astNode),
"node claims to have no parse errors, but above were reported."
);
assert(
!astNode.printable ||
!astNode.parseDiagnostics.some((d) => !/^'[,;:{}()]' expected\.$/.test(d.message)),
"parse tree with errors other than missing punctuation should not be printable"
);
checkPositioning(astNode, astNode.file);
});
}
}
function dumpAST(astNode: Node, file?: SourceFile) {
if (!file && astNode.kind === SyntaxKind.CadlScript) {
file = astNode.file;
}
logVerboseTestOutput((log) => {
hasParseError(astNode); // force flags to initialize
const json = JSON.stringify(astNode, replacer, 2);
log.log({ level: "info", message: json });
});
function replacer(key: string, value: any) {
if (key === "kind") {
// swap numeric kind for readable name
return SyntaxKind[value];
}
if (file && (key === "pos" || key === "end")) {
// include line and column numbers
const pos = file.getLineAndCharacterOfPosition(value);
const line = pos.line + 1;
const col = pos.character + 1;
return `${value} (line ${line}, column ${col})`;
}
if (key === "parseDiagnostics" || key === "file") {
// these will be logged separately in more readable form
return undefined;
}
if (key === "locals" && value.size === 0) {
// this will be an empty symbol table after parsing, hide it
return undefined;
}
if (Array.isArray(value) && value.length === 0) {
// hide empty arrays too
return undefined;
}
if (key === "flags") {
return [
value & NodeFlags.DescendantErrorsExamined ? "DescendantErrorsExamined" : "",
value & NodeFlags.ThisNodeHasError ? "ThisNodeHasError" : "",
value & NodeFlags.DescendantHasError ? "DescendantHasError" : "",
].join(",");
}
if (value && typeof value === "object" && !Array.isArray(value)) {
// Show the text of the given node
if (file && "pos" in value && "end" in value) {
value.source = shorten(file.text.substring(value.pos, value.end));
}
// sort properties by type so that the short ones can be read without
// scrolling past the long ones and getting disoriented.
const sorted: any = {};
for (const prop of sortKeysByType(value)) {
sorted[prop] = value[prop];
}
return sorted;
}
return value;
}
function sortKeysByType(o: any) {
const score = {
undefined: 0,
string: 1,
boolean: 2,
number: 3,
bigint: 4,
symbol: 5,
function: 6,
object: 7,
};
return Object.keys(o).sort((x, y) => score[typeof o[x]] - score[typeof o[y]]);
}
}
function shorten(code: string) {
return code.replace(/\s+/g, " ");
} | the_stack |
import React from 'react'
import ReactDOM from 'react-dom/server'
import tap from 'tap'
import {PortableText} from '../src/react-portable-text'
import {
PortableTextReactComponents,
PortableTextMarkComponent,
PortableTextProps,
MissingComponentHandler,
} from '../src/types'
import * as fixtures from './fixtures'
const render = (props: PortableTextProps) =>
ReactDOM.renderToStaticMarkup(<PortableText onMissingComponent={false} {...props} />)
tap.test('builds empty tree on empty block', (t) => {
const {input, output} = fixtures.emptyBlock
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds simple one-node tree on single, markless span', (t) => {
const {input, output} = fixtures.singleSpan
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds simple multi-node tree on markless spans', (t) => {
const {input, output} = fixtures.multipleSpans
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds annotated span on simple mark', (t) => {
const {input, output} = fixtures.basicMarkSingleSpan
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds annotated, joined span on adjacent, equal marks', (t) => {
const {input, output} = fixtures.basicMarkMultipleAdjacentSpans
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds annotated, nested spans in tree format', (t) => {
const {input, output} = fixtures.basicMarkNestedMarks
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds annotated spans with expanded marks on object-style marks', (t) => {
const {input, output} = fixtures.linkMarkDef
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds correct structure from advanced, nested mark structure', (t) => {
const {input, output} = fixtures.messyLinkText
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds bullet lists in parent container', (t) => {
const {input, output} = fixtures.basicBulletList
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds numbered lists in parent container', (t) => {
const {input, output} = fixtures.basicNumberedList
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds nested lists', (t) => {
const {input, output} = fixtures.nestedLists
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds all basic marks as expected', (t) => {
const {input, output} = fixtures.allBasicMarks
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('builds weirdly complex lists without any issues', (t) => {
const {input, output} = fixtures.deepWeirdLists
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('renders all default block styles', (t) => {
const {input, output} = fixtures.allDefaultBlockStyles
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('sorts marks correctly on equal number of occurences', (t) => {
const {input, output} = fixtures.marksAllTheWayDown
const marks: PortableTextReactComponents['marks'] = {
highlight: ({value, children}) => (
<span style={{border: `${value?.thickness}px solid`}}>{children}</span>
),
}
const result = render({value: input, components: {marks}})
t.same(result, output)
t.end()
})
tap.test('handles keyless blocks/spans', (t) => {
const {input, output} = fixtures.keyless
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('handles empty arrays', (t) => {
const {input, output} = fixtures.emptyArray
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('handles lists without level', (t) => {
const {input, output} = fixtures.listWithoutLevel
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('handles inline non-span nodes', (t) => {
const {input, output} = fixtures.inlineNodes
const result = render({
value: input,
components: {
types: {
rating: ({value}) => {
return <span className={`rating type-${value.type} rating-${value.rating}`} />
},
},
},
})
t.same(result, output)
t.end()
})
tap.test('handles hardbreaks', (t) => {
const {input, output} = fixtures.hardBreaks
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('can disable hardbreak component', (t) => {
const {input, output} = fixtures.hardBreaks
const result = render({value: input, components: {hardBreak: false}})
t.same(result, output.replace(/<br\/>/g, '\n'))
t.end()
})
tap.test('can customize hardbreak component', (t) => {
const {input, output} = fixtures.hardBreaks
const hardBreak = () => <br className="dat-newline" />
const result = render({value: input, components: {hardBreak}})
t.same(result, output.replace(/<br\/>/g, '<br class="dat-newline"/>'))
t.end()
})
tap.test('can nest marks correctly in block/marks context', (t) => {
const {input, output} = fixtures.inlineObjects
const result = render({
value: input,
components: {
types: {
localCurrency: ({value}) => {
// in the real world we'd look up the users local currency,
// do some rate calculations and render the result. Obviously.
const rates: Record<string, number> = {USD: 8.82, DKK: 1.35, EUR: 10.04}
const rate = rates[value.sourceCurrency] || 1
return <span className="currency">~{Math.round(value.sourceAmount * rate)} NOK</span>
},
},
},
})
t.same(result, output)
t.end()
})
tap.test('can render inline block with text property', (t) => {
const {input, output} = fixtures.inlineBlockWithText
const result = render({
value: input,
components: {types: {button: (props) => <button type="button">{props.value.text}</button>}},
})
t.same(result, output)
t.end()
})
tap.test('can render styled list items', (t) => {
const {input, output} = fixtures.styledListItems
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('can render custom list item styles with fallback', (t) => {
const {input, output} = fixtures.customListItemType
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('can render custom list item styles with provided list style component', (t) => {
const {input} = fixtures.customListItemType
const result = render({
value: input,
components: {list: {square: ({children}) => <ul className="list-squared">{children}</ul>}},
})
t.same(
result,
'<ul class="list-squared"><li>Square 1</li><li>Square 2<ul><li>Dat disc</li></ul></li><li>Square 3</li></ul>'
)
t.end()
})
tap.test('can render custom list item styles with provided list style component', (t) => {
const {input} = fixtures.customListItemType
const result = render({
value: input,
components: {
listItem: {
square: ({children}) => <li className="item-squared">{children}</li>,
},
},
})
t.same(
result,
'<ul><li class="item-squared">Square 1</li><li class="item-squared">Square 2<ul><li>Dat disc</li></ul></li><li class="item-squared">Square 3</li></ul>'
)
t.end()
})
tap.test('warns on missing list style component', (t) => {
const {input} = fixtures.customListItemType
const result = render({
value: input,
components: {list: {}},
})
t.same(
result,
'<ul><li>Square 1</li><li>Square 2<ul><li>Dat disc</li></ul></li><li>Square 3</li></ul>'
)
t.end()
})
tap.test('can render styled list items with custom list item component', (t) => {
const {input, output} = fixtures.styledListItems
const result = render({
value: input,
components: {
listItem: ({children}) => {
return <li>{children}</li>
},
},
})
t.same(result, output)
t.end()
})
tap.test('can specify custom component for custom block types', (t) => {
const {input, output} = fixtures.customBlockType
const types: Partial<PortableTextReactComponents>['types'] = {
code: ({renderNode, ...props}) => {
t.same(props, {
value: {
_key: '9a15ea2ed8a2',
_type: 'code',
code: input[0]?.code,
language: 'javascript',
},
index: 0,
isInline: false,
})
return (
<pre data-language={props.value.language}>
<code>{props.value.code}</code>
</pre>
)
},
}
const result = render({value: input, components: {types}})
t.same(result, output)
t.end()
})
tap.test('can specify custom components for custom marks', (t) => {
const {input, output} = fixtures.customMarks
const highlight: PortableTextMarkComponent<{_type: 'highlight'; thickness: number}> = ({
value,
children,
}) => <span style={{border: `${value?.thickness}px solid`}}>{children}</span>
const result = render({value: input, components: {marks: {highlight}}})
t.same(result, output)
t.end()
})
tap.test('can specify custom components for defaults marks', (t) => {
const {input, output} = fixtures.overrideDefaultMarks
const link: PortableTextMarkComponent<{_type: 'link'; href: string}> = ({value, children}) => (
<a className="mahlink" href={value?.href}>
{children}
</a>
)
const result = render({value: input, components: {marks: {link}}})
t.same(result, output)
t.end()
})
tap.test('falls back to default component for missing mark components', (t) => {
const {input, output} = fixtures.missingMarkComponent
const result = render({value: input})
t.same(result, output)
t.end()
})
tap.test('can register custom `missing component` handler', (t) => {
let warning = '<never called>'
const onMissingComponent: MissingComponentHandler = (message) => {
warning = message
}
const {input} = fixtures.missingMarkComponent
render({value: input, onMissingComponent})
t.same(
warning,
'Unknown mark type "abc", specify a component for it in the `components.marks` prop'
)
t.end()
}) | the_stack |
import { SideDimensions, Dimensions } from "../scripts/itemTypeHelpers";
export const sideViewDimensions1: SideDimensions[] = [
{
itemId: 0,
name: "The Void",
side: "none",
dimensions: { x: 0, y: 0, width: 0, height: 0 },
},
{
itemId: 1,
name: "Camo Hat",
side: "back",
dimensions: { x: 15, y: 2, width: 34, height: 12 },
},
{
itemId: 1,
name: "Camo Hat",
side: "left",
dimensions: { x: 14, y: 2, width: 30, height: 12 },
},
{
itemId: 1,
name: "Camo Hat",
side: "right",
dimensions: { x: 20, y: 2, width: 30, height: 12 },
},
{
itemId: 2,
name: "Camo Pant",
side: "back",
dimensions: { x: 15, y: 41, width: 34, height: 14 },
},
{
itemId: 2,
name: "Camo Pant",
side: "left",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 2,
name: "Camo Pant",
side: "right",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 3,
name: "MK2 Grenade",
side: "back",
dimensions: { x: 5, y: 31, width: 8, height: 11 },
},
{
itemId: 3,
name: "MK2 Grenade",
side: "left",
dimensions: { x: 25, y: 31, width: 5, height: 11 },
},
{
itemId: 3,
name: "MK2 Grenade",
side: "right",
dimensions: { x: 34, y: 31, width: 5, height: 11 },
},
{
itemId: 4,
name: "Snow Camo Hat",
side: "back",
dimensions: { x: 15, y: 2, width: 34, height: 12 },
},
{
itemId: 4,
name: "Snow Camo Hat",
side: "left",
dimensions: { x: 14, y: 2, width: 30, height: 12 },
},
{
itemId: 4,
name: "Snow Camo Hat",
side: "right",
dimensions: { x: 20, y: 2, width: 30, height: 12 },
},
{
itemId: 5,
name: "Snow Camo Pant",
side: "back",
dimensions: { x: 15, y: 41, width: 34, height: 14 },
},
{
itemId: 5,
name: "Snow Camo Pant",
side: "left",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 5,
name: "Snow Camo Pant",
side: "right",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 6,
name: "M67 Grenade",
side: "back",
dimensions: { x: 4, y: 31, width: 9, height: 11 },
},
{
itemId: 6,
name: "M67 Grenade",
side: "left",
dimensions: { x: 23, y: 31, width: 7, height: 11 },
},
{
itemId: 6,
name: "M67 Grenade",
side: "right",
dimensions: { x: 34, y: 31, width: 7, height: 11 },
},
{
itemId: 7,
name: "Marine Cap",
side: "back",
dimensions: { x: 13, y: 1, width: 39, height: 27 },
},
{
itemId: 7,
name: "Marine Cap",
side: "left",
dimensions: { x: 19, y: 1, width: 26, height: 19 },
},
{
itemId: 7,
name: "Marine Cap",
side: "right",
dimensions: { x: 19, y: 1, width: 26, height: 26 },
},
{
itemId: 8,
name: "Marine Jacket",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 22 },
},
{
itemId: 8,
name: "Marine Jacket",
side: "left",
dimensions: { x: 11, y: 33, width: 24, height: 22 },
},
{
itemId: 8,
name: "Marine Jacket",
side: "right",
dimensions: { x: 10, y: 33, width: 24, height: 22 },
},
{
itemId: 8,
name: "Marine Jacket",
side: "left back up",
dimensions: { x: 9, y: 32, width: 3, height: 9 },
},
{
itemId: 8,
name: "Marine Jacket",
side: "left back",
dimensions: { x: 9, y: 32, width: 3, height: 10 },
},
{
itemId: 8,
name: "Marine Jacket",
side: "left up",
dimensions: { x: 17, y: 33, width: 12, height: 5 },
},
{
itemId: 8,
name: "Marine Jacket",
side: "left",
dimensions: { x: 20, y: 32, width: 5, height: 12 },
},
{
itemId: 8,
name: "Marine Jacket",
side: "right back up",
dimensions: { x: 46, y: 32, width: 3, height: 9 },
},
{
itemId: 8,
name: "Marine Jacket",
side: "right back",
dimensions: { x: 46, y: 32, width: 3, height: 10 },
},
{
itemId: 8,
name: "Marine Jacket",
side: "right up",
dimensions: { x: 16, y: 33, width: 12, height: 5 },
},
{
itemId: 8,
name: "Marine Jacket",
side: "right",
dimensions: { x: 20, y: 32, width: 5, height: 12 },
},
{
itemId: 9,
name: "Walkie Talkie",
side: "back",
dimensions: { x: 3, y: 31, width: 7, height: 15 },
},
{
itemId: 9,
name: "Walkie Talkie",
side: "right",
dimensions: { x: 37, y: 31, width: 7, height: 15 },
},
{
itemId: 9,
name: "Walkie Talkie",
side: "left",
dimensions: { x: 24, y: 31, width: 7, height: 15 },
},
{
itemId: 10,
name: "Link White Hat",
side: "back",
dimensions: { x: 9, y: 1, width: 46, height: 14 },
},
{
itemId: 10,
name: "Link White Hat",
side: "left",
dimensions: { x: 12, y: 2, width: 36, height: 19 },
},
{
itemId: 10,
name: "Link White Hat",
side: "right",
dimensions: { x: 16, y: 2, width: 39, height: 19 },
},
{
itemId: 11,
name: "Mess Dress",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 11,
name: "Mess Dress",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 11,
name: "Mess Dress",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 22 },
},
{
itemId: 11,
name: "Mess Dress",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 11,
name: "Mess Dress",
side: "left back",
dimensions: { x: 12, y: 32, width: 3, height: 10 },
},
{
itemId: 11,
name: "Mess Dress",
side: "left up",
dimensions: { x: 26, y: 33, width: 12, height: 5 },
},
{
itemId: 11,
name: "Mess Dress",
side: "left",
dimensions: { x: 20, y: 32, width: 5, height: 12 },
},
{
itemId: 11,
name: "Mess Dress",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 11,
name: "Mess Dress",
side: "right back",
dimensions: { x: 49, y: 32, width: 3, height: 10 },
},
{
itemId: 11,
name: "Mess Dress",
side: "right up",
dimensions: { x: 26, y: 33, width: 12, height: 5 },
},
{
itemId: 11,
name: "Mess Dress",
side: "right",
dimensions: { x: 20, y: 32, width: 5, height: 12 },
},
{
itemId: 12,
name: "Link Bubbly",
side: "back",
dimensions: { x: 5, y: 25, width: 5, height: 19 },
},
{
itemId: 12,
name: "Link Bubbly",
side: "left",
dimensions: { x: 23, y: 25, width: 5, height: 19 },
},
{
itemId: 12,
name: "Link Bubbly",
side: "right",
dimensions: { x: 36, y: 25, width: 5, height: 19 },
},
{
itemId: 13,
name: "Sergey Beard",
side: "back",
dimensions: { x: 15, y: 6, width: 34, height: 27 },
},
{
itemId: 13,
name: "Sergey Beard",
side: "left",
dimensions: { x: 19, y: 6, width: 25, height: 32 },
},
{
itemId: 13,
name: "Sergey Beard",
side: "right",
dimensions: { x: 20, y: 6, width: 25, height: 32 },
},
{
itemId: 14,
name: "Sergey Eyes",
side: "left",
dimensions: { x: 20, y: 22, width: 3, height: 8 },
},
{
itemId: 14,
name: "Sergey Eyes",
side: "right",
dimensions: { x: 41, y: 22, width: 3, height: 8 },
},
{
itemId: 15,
name: "Red Plaid",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 15,
name: "Red Plaid",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 15,
name: "Red Plaid",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 24 },
},
{
itemId: 15,
name: "Red Plaid",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 15,
name: "Red Plaid",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 15,
name: "Red Plaid",
side: "left up",
dimensions: { x: 26, y: 32, width: 9, height: 6 },
},
{
itemId: 15,
name: "Red Plaid",
side: "left",
dimensions: { x: 20, y: 32, width: 6, height: 9 },
},
{
itemId: 15,
name: "Red Plaid",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 15,
name: "Red Plaid",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 15,
name: "Red Plaid",
side: "right up",
dimensions: { x: 29, y: 32, width: 9, height: 6 },
},
{
itemId: 15,
name: "Red Plaid",
side: "right",
dimensions: { x: 20, y: 32, width: 6, height: 9 },
},
{
itemId: 16,
name: "Blue Plaid",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 16,
name: "Blue Plaid",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 16,
name: "Blue Plaid",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 24 },
},
{
itemId: 16,
name: "Blue Plaid",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 16,
name: "Blue Plaid",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 16,
name: "Blue Plaid",
side: "left up",
dimensions: { x: 26, y: 32, width: 9, height: 6 },
},
{
itemId: 16,
name: "Blue Plaid",
side: "left",
dimensions: { x: 20, y: 32, width: 6, height: 9 },
},
{
itemId: 16,
name: "Blue Plaid",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 16,
name: "Blue Plaid",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 16,
name: "Blue Plaid",
side: "right up",
dimensions: { x: 29, y: 32, width: 9, height: 6 },
},
{
itemId: 16,
name: "Blue Plaid",
side: "right",
dimensions: { x: 20, y: 32, width: 6, height: 9 },
},
{
itemId: 17,
name: "Link Cube",
side: "back",
dimensions: { x: 1, y: 31, width: 12, height: 16 },
},
{
itemId: 17,
name: "Link Cube",
side: "right",
dimensions: { x: 32, y: 31, width: 12, height: 16 },
},
{
itemId: 17,
name: "Link Cube",
side: "left",
dimensions: { x: 20, y: 31, width: 12, height: 16 },
},
{
itemId: 18,
name: "Aave Hero Mask",
side: "back",
dimensions: { x: 15, y: 20, width: 34, height: 12 },
},
{
itemId: 18,
name: "Aave Hero Mask",
side: "left",
dimensions: { x: 19, y: 19, width: 29, height: 13 },
},
{
itemId: 18,
name: "Aave Hero Mask",
side: "right",
dimensions: { x: 16, y: 19, width: 29, height: 13 },
},
{
itemId: 19,
name: "Aave Hero Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 19 },
},
{
itemId: 19,
name: "Aave Hero Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 19 },
},
{
itemId: 19,
name: "Aave Hero Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 19 },
},
{
itemId: 19,
name: "Aave Hero Shirt",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 19,
name: "Aave Hero Shirt",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 19,
name: "Aave Hero Shirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 19,
name: "Aave Hero Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 19,
name: "Aave Hero Shirt",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 19,
name: "Aave Hero Shirt",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 19,
name: "Aave Hero Shirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 19,
name: "Aave Hero Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 20,
name: "Aave Plush",
side: "back",
dimensions: { x: 1, y: 32, width: 13, height: 13 },
},
{
itemId: 20,
name: "Aave Plush",
side: "right",
dimensions: { x: 37, y: 32, width: 2, height: 13 },
},
{
itemId: 20,
name: "Aave Plush",
side: "left",
dimensions: { x: 25, y: 32, width: 2, height: 13 },
},
{
itemId: 21,
name: "Captain Aave Mask",
side: "back",
dimensions: { x: 11, y: 6, width: 42, height: 27 },
},
{
itemId: 21,
name: "Captain Aave Mask",
side: "left",
dimensions: { x: 20, y: 6, width: 24, height: 27 },
},
{
itemId: 21,
name: "Captain Aave Mask",
side: "right",
dimensions: { x: 20, y: 6, width: 24, height: 27 },
},
{
itemId: 22,
name: "Captain Aave Suit",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 22,
name: "Captain Aave Suit",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 22,
name: "Captain Aave Suit",
side: "back",
dimensions: { x: 7, y: 31, width: 34, height: 22 },
},
{
itemId: 22,
name: "Captain Aave Suit",
side: "left back up",
dimensions: { x: 7, y: 31, width: 8, height: 10 },
},
{
itemId: 22,
name: "Captain Aave Suit",
side: "left back",
dimensions: { x: 7, y: 33, width: 8, height: 10 },
},
{
itemId: 22,
name: "Captain Aave Suit",
side: "left up",
dimensions: { x: 25, y: 28, width: 10, height: 9 },
},
{
itemId: 22,
name: "Captain Aave Suit",
side: "left",
dimensions: { x: 20, y: 28, width: 9, height: 10 },
},
{
itemId: 22,
name: "Captain Aave Suit",
side: "right back up",
dimensions: { x: 49, y: 31, width: 8, height: 10 },
},
{
itemId: 22,
name: "Captain Aave Suit",
side: "right back",
dimensions: { x: 49, y: 33, width: 8, height: 10 },
},
{
itemId: 22,
name: "Captain Aave Suit",
side: "right up",
dimensions: { x: 29, y: 28, width: 10, height: 9 },
},
{
itemId: 22,
name: "Captain Aave Suit",
side: "right",
dimensions: { x: 20, y: 28, width: 9, height: 10 },
},
{
itemId: 23,
name: "Captain Aave Shield",
side: "back",
dimensions: { x: 3, y: 32, width: 20, height: 20 },
},
{
itemId: 23,
name: "Captain Aave Shield",
side: "right",
dimensions: { x: 37, y: 31, width: 5, height: 20 },
},
{
itemId: 23,
name: "Captain Aave Shield",
side: "left",
dimensions: { x: 22, y: 31, width: 5, height: 20 },
},
{
itemId: 24,
name: "Thaave Helmet",
side: "back",
dimensions: { x: 9, y: 6, width: 46, height: 24 },
},
{
itemId: 24,
name: "Thaave Helmet",
side: "left",
dimensions: { x: 20, y: 6, width: 24, height: 24 },
},
{
itemId: 24,
name: "Thaave Helmet",
side: "right",
dimensions: { x: 20, y: 6, width: 24, height: 24 },
},
{
itemId: 25,
name: "Thaave Suit",
side: "left",
dimensions: { x: 20, y: 34, width: 30, height: 21 },
},
{
itemId: 25,
name: "Thaave Suit",
side: "right",
dimensions: { x: 14, y: 34, width: 30, height: 21 },
},
{
itemId: 25,
name: "Thaave Suit",
side: "back",
dimensions: { x: 9, y: 33, width: 46, height: 22 },
},
{
itemId: 25,
name: "Thaave Suit",
side: "left up",
dimensions: { x: 28, y: 37, width: 8, height: 1 },
},
{
itemId: 25,
name: "Thaave Suit",
side: "left",
dimensions: { x: 20, y: 33, width: 1, height: 8 },
},
{
itemId: 25,
name: "Thaave Suit",
side: "right up",
dimensions: { x: 28, y: 37, width: 8, height: 1 },
},
{
itemId: 25,
name: "Thaave Suit",
side: "right",
dimensions: { x: 14, y: 33, width: 1, height: 8 },
},
{
itemId: 26,
name: "Thaave Hammer",
side: "back",
dimensions: { x: 0, y: 28, width: 14, height: 14 },
},
{
itemId: 26,
name: "Thaave Hammer",
side: "left",
dimensions: { x: 20, y: 29, width: 12, height: 12 },
},
{
itemId: 26,
name: "Thaave Hammer",
side: "right back",
dimensions: { x: 0, y: 28, width: 14, height: 14 },
},
{
itemId: 26,
name: "Thaave Hammer",
side: "right",
dimensions: { x: 32, y: 29, width: 12, height: 12 },
},
{
itemId: 27,
name: "Marc Hair",
side: "back",
dimensions: { x: 15, y: 6, width: 34, height: 22 },
},
{
itemId: 27,
name: "Marc Hair",
side: "left",
dimensions: { x: 20, y: 6, width: 24, height: 22 },
},
{
itemId: 27,
name: "Marc Hair",
side: "right",
dimensions: { x: 20, y: 6, width: 24, height: 22 },
},
{
itemId: 28,
name: "Marc Outfit",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 28,
name: "Marc Outfit",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 28,
name: "Marc Outfit",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 22 },
},
{
itemId: 28,
name: "Marc Outfit",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 28,
name: "Marc Outfit",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 28,
name: "Marc Outfit",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 28,
name: "Marc Outfit",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 28,
name: "Marc Outfit",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 28,
name: "Marc Outfit",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 28,
name: "Marc Outfit",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 28,
name: "Marc Outfit",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 29,
name: "REKT Sign",
side: "back",
dimensions: { x: 0, y: 24, width: 12, height: 25 },
},
{
itemId: 29,
name: "REKT Sign",
side: "right",
dimensions: { x: 37, y: 24, width: 1, height: 23 },
},
{
itemId: 30,
name: "Jordan Hair",
side: "back",
dimensions: { x: 7, y: 0, width: 50, height: 36 },
},
{
itemId: 30,
name: "Jordan Hair",
side: "left",
dimensions: { x: 23, y: 2, width: 28, height: 32 },
},
{
itemId: 30,
name: "Jordan Hair",
side: "right",
dimensions: { x: 13, y: 2, width: 28, height: 32 },
},
{
itemId: 31,
name: "Jordan Suit",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 31,
name: "Jordan Suit",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 31,
name: "Jordan Suit",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 22 },
},
{
itemId: 31,
name: "Jordan Suit",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 31,
name: "Jordan Suit",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 31,
name: "Jordan Suit",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 31,
name: "Jordan Suit",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 31,
name: "Jordan Suit",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 31,
name: "Jordan Suit",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 31,
name: "Jordan Suit",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 31,
name: "Jordan Suit",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 32,
name: "Aave Flag",
side: "back",
dimensions: { x: 0, y: 24, width: 12, height: 25 },
},
{
itemId: 32,
name: "Aave Flag",
side: "left",
dimensions: { x: 26, y: 24, width: 1, height: 25 },
},
{
itemId: 32,
name: "Aave Flag",
side: "right back",
dimensions: { x: 0, y: 24, width: 12, height: 25 },
},
{
itemId: 32,
name: "Aave Flag",
side: "right",
dimensions: { x: 37, y: 24, width: 1, height: 25 },
},
{
itemId: 33,
name: "Stani Hair",
side: "back",
dimensions: { x: 15, y: 6, width: 34, height: 20 },
},
{
itemId: 33,
name: "Stani Hair",
side: "left",
dimensions: { x: 19, y: 6, width: 26, height: 21 },
},
{
itemId: 33,
name: "Stani Hair",
side: "right",
dimensions: { x: 19, y: 6, width: 26, height: 21 },
},
{
itemId: 34,
name: "Stani Vest",
side: "back",
dimensions: { x: 15, y: 33, width: 34, height: 16 },
},
{
itemId: 34,
name: "Stani Vest",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 16 },
},
{
itemId: 34,
name: "Stani Vest",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 16 },
},
{
itemId: 35,
name: "Aave Boat Front",
side: "front",
dimensions: { x: 12, y: 45, width: 40, height: 16 },
},
{
itemId: 35,
name: "Aave Boat",
side: "back",
dimensions: { x: 12, y: 45, width: 40, height: 16 },
},
{
itemId: 35,
name: "Aave Boat",
side: "left",
dimensions: { x: 2, y: 46, width: 57, height: 15 },
},
{
itemId: 35,
name: "Aave Boat",
side: "right",
dimensions: { x: 5, y: 46, width: 57, height: 15 },
},
{
itemId: 36,
name: "ETH Maxi Glasses",
side: "back",
dimensions: { x: 15, y: 23, width: 34, height: 2 },
},
{
itemId: 36,
name: "ETH Maxi Glasses",
side: "left",
dimensions: { x: 14, y: 19, width: 30, height: 13 },
},
{
itemId: 36,
name: "ETH Maxi Glasses",
side: "right",
dimensions: { x: 20, y: 19, width: 30, height: 13 },
},
{
itemId: 37,
name: "ETH Tshirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 19 },
},
{
itemId: 37,
name: "ETH Tshirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 19 },
},
{
itemId: 37,
name: "ETH Tshirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 19 },
},
{
itemId: 37,
name: "ETH Tshirt",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 37,
name: "ETH Tshirt",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 37,
name: "ETH Tshirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 37,
name: "ETH Tshirt",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 37,
name: "ETH Tshirt",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 37,
name: "ETH Tshirt",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 37,
name: "ETH Tshirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 37,
name: "ETH Tshirt",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 38,
name: "32 ETH Coin",
side: "back",
dimensions: { x: 1, y: 31, width: 14, height: 14 },
},
{
itemId: 38,
name: "32 ETH Coin",
side: "right",
dimensions: { x: 37, y: 31, width: 2, height: 14 },
},
{
itemId: 38,
name: "32 ETH Coin",
side: "left",
dimensions: { x: 25, y: 31, width: 2, height: 14 },
},
{
itemId: 39,
name: "Foxy Mask",
side: "back",
dimensions: { x: 15, y: 2, width: 34, height: 40 },
},
{
itemId: 39,
name: "Foxy Mask",
side: "left up",
dimensions: { x: 29, y: 35, width: 6, height: 5 },
},
{
itemId: 39,
name: "Foxy Mask",
side: "left",
dimensions: { x: 31, y: 35, width: 5, height: 6 },
},
{
itemId: 39,
name: "Foxy Mask",
side: "left",
dimensions: { x: 18, y: 2, width: 26, height: 40 },
},
{
itemId: 39,
name: "Foxy Mask",
side: "right up",
dimensions: { x: 29, y: 35, width: 6, height: 5 },
},
{
itemId: 39,
name: "Foxy Mask",
side: "right",
dimensions: { x: 28, y: 35, width: 5, height: 6 },
},
{
itemId: 39,
name: "Foxy Mask",
side: "right",
dimensions: { x: 20, y: 2, width: 26, height: 40 },
},
{
itemId: 40,
name: "Foxy Tail",
side: "back",
dimensions: { x: 23, y: 27, width: 9, height: 14 },
},
{
itemId: 40,
name: "Foxy Tail",
side: "left",
dimensions: { x: 44, y: 22, width: 19, height: 27 },
},
{
itemId: 40,
name: "Foxy Tail",
side: "right",
dimensions: { x: 1, y: 22, width: 19, height: 27 },
},
{
itemId: 41,
name: "Trezor Wallet",
side: "back",
dimensions: { x: 4, y: 31, width: 9, height: 14 },
},
{
itemId: 41,
name: "Trezor Wallet",
side: "left",
dimensions: { x: 25, y: 31, width: 2, height: 14 },
},
{
itemId: 41,
name: "Trezor Wallet",
side: "right back",
dimensions: { x: 51, y: 31, width: 9, height: 14 },
},
{
itemId: 41,
name: "Trezor Wallet",
side: "right",
dimensions: { x: 37, y: 31, width: 2, height: 14 },
},
{
itemId: 42,
name: "Nogara Eagle Mask",
side: "back",
dimensions: { x: 5, y: 6, width: 54, height: 20 },
},
{
itemId: 42,
name: "Nogara Eagle Mask",
side: "left",
dimensions: { x: 17, y: 6, width: 27, height: 26 },
},
{
itemId: 42,
name: "Nogara Eagle Mask",
side: "right",
dimensions: { x: 20, y: 6, width: 27, height: 26 },
},
{
itemId: 43,
name: "Nogara Eagle Armor",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 43,
name: "Nogara Eagle Armor",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 43,
name: "Nogara Eagle Armor",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 22 },
},
{
itemId: 43,
name: "Nogara Eagle Armor",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 43,
name: "Nogara Eagle Armor",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 43,
name: "Nogara Eagle Armor",
side: "left up",
dimensions: { x: 26, y: 33, width: 11, height: 5 },
},
{
itemId: 43,
name: "Nogara Eagle Armor",
side: "left",
dimensions: { x: 20, y: 33, width: 5, height: 11 },
},
{
itemId: 43,
name: "Nogara Eagle Armor",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 43,
name: "Nogara Eagle Armor",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 43,
name: "Nogara Eagle Armor",
side: "right up",
dimensions: { x: 27, y: 33, width: 11, height: 5 },
},
{
itemId: 43,
name: "Nogara Eagle Armor",
side: "right",
dimensions: { x: 20, y: 33, width: 5, height: 11 },
},
{
itemId: 44,
name: "DAO Egg",
side: "back",
dimensions: { x: 0, y: 27, width: 16, height: 22 },
},
{
itemId: 44,
name: "DAO Egg",
side: "right",
dimensions: { x: 32, y: 27, width: 16, height: 22 },
},
{
itemId: 44,
name: "DAO Egg",
side: "left",
dimensions: { x: 16, y: 27, width: 16, height: 22 },
},
{
itemId: 45,
name: "Ape Mask",
side: "back",
dimensions: { x: 11, y: 6, width: 42, height: 27 },
},
{
itemId: 45,
name: "Ape Mask",
side: "left",
dimensions: { x: 18, y: 6, width: 26, height: 34 },
},
{
itemId: 45,
name: "Ape Mask",
side: "right",
dimensions: { x: 20, y: 6, width: 26, height: 34 },
},
{
itemId: 46,
name: "Half Rekt Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 19 },
},
{
itemId: 46,
name: "Half Rekt Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 19 },
},
{
itemId: 46,
name: "Half Rekt Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 19 },
},
{
itemId: 46,
name: "Half Rekt Shirt",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 46,
name: "Half Rekt Shirt",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 46,
name: "Half Rekt Shirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 46,
name: "Half Rekt Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 46,
name: "Half Rekt Shirt",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 46,
name: "Half Rekt Shirt",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 46,
name: "Half Rekt Shirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 46,
name: "Half Rekt Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 47,
name: "Waifu Pillow",
side: "back",
dimensions: { x: 0, y: 23, width: 17, height: 30 },
},
{
itemId: 47,
name: "Waifu Pillow",
side: "left",
dimensions: { x: 18, y: 23, width: 14, height: 30 },
},
{
itemId: 47,
name: "Waifu Pillow",
side: "right",
dimensions: { x: 32, y: 23, width: 14, height: 30 },
},
{
itemId: 48,
name: "Xibot Mohawk",
side: "back",
dimensions: { x: 27, y: 0, width: 10, height: 22 },
},
{
itemId: 48,
name: "Xibot Mohawk",
side: "left",
dimensions: { x: 20, y: 0, width: 24, height: 19 },
},
{
itemId: 48,
name: "Xibot Mohawk",
side: "right",
dimensions: { x: 20, y: 0, width: 24, height: 19 },
},
{
itemId: 49,
name: "Coderdan Shade",
side: "back",
dimensions: { x: 15, y: 24, width: 34, height: 2 },
},
{
itemId: 49,
name: "Coderdan Shade",
side: "left",
dimensions: { x: 19, y: 19, width: 25, height: 12 },
},
{
itemId: 49,
name: "Coderdan Shade",
side: "right",
dimensions: { x: 20, y: 19, width: 25, height: 12 },
},
{
itemId: 50,
name: "Gldn Xross Robe",
side: "left",
dimensions: { x: 20, y: 31, width: 24, height: 22 },
},
{
itemId: 50,
name: "Gldn Xross Robe",
side: "right",
dimensions: { x: 20, y: 31, width: 24, height: 22 },
},
{
itemId: 50,
name: "Gldn Xross Robe",
side: "back",
dimensions: { x: 10, y: 32, width: 34, height: 22 },
},
{
itemId: 50,
name: "GldnXross Robe",
side: "left back up",
dimensions: { x: 10, y: 31, width: 5, height: 19 },
},
{
itemId: 50,
name: "GldnXross Robe",
side: "left back",
dimensions: { x: 10, y: 33, width: 5, height: 18 },
},
{
itemId: 50,
name: "GldnXross Robe",
side: "left up",
dimensions: { x: 25, y: 31, width: 10, height: 6 },
},
{
itemId: 50,
name: "GldnXross Robe",
side: "left",
dimensions: { x: 20, y: 31, width: 6, height: 10 },
},
{
itemId: 50,
name: "GldnXross Robe",
side: "right back up",
dimensions: { x: 49, y: 31, width: 5, height: 19 },
},
{
itemId: 50,
name: "GldnXross Robe",
side: "right back",
dimensions: { x: 49, y: 33, width: 5, height: 18 },
},
{
itemId: 50,
name: "GldnXross Robe",
side: "right up",
dimensions: { x: 29, y: 31, width: 10, height: 6 },
},
{
itemId: 50,
name: "GldnXross Robe",
side: "right",
dimensions: { x: 20, y: 31, width: 6, height: 10 },
},
{
itemId: 51,
name: "Mudgen Diamond",
side: "back",
dimensions: { x: 0, y: 33, width: 13, height: 10 },
},
{
itemId: 51,
name: "Mudgen Diamond",
side: "left",
dimensions: { x: 20, y: 33, width: 11, height: 9 },
},
{
itemId: 51,
name: "Mudgen Diamond",
side: "right back",
dimensions: { x: 49, y: 33, width: 13, height: 10 },
},
{
itemId: 51,
name: "Mudgen Diamond",
side: "right",
dimensions: { x: 33, y: 33, width: 11, height: 9 },
},
{
itemId: 52,
name: "Galaxy Brain",
side: "back",
dimensions: { x: 11, y: 1, width: 42, height: 25 },
},
{
itemId: 52,
name: "Galaxy Brain",
side: "left",
dimensions: { x: 16, y: 1, width: 32, height: 22 },
},
{
itemId: 52,
name: "Galaxy Brain",
side: "right",
dimensions: { x: 16, y: 1, width: 32, height: 22 },
},
{
itemId: 53,
name: "All Seeing Eyes",
side: "left",
dimensions: { x: 20, y: 19, width: 6, height: 12 },
},
{
itemId: 53,
name: "All Seeing Eyes",
side: "right",
dimensions: { x: 38, y: 19, width: 6, height: 12 },
},
{
itemId: 54,
name: "Llamacorn Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 21 },
},
{
itemId: 54,
name: "Llamacorn Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 21 },
},
{
itemId: 54,
name: "Llamacorn Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 21 },
},
{
itemId: 54,
name: "Llamacorn Shirt",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 54,
name: "Llamacorn Shirt",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 54,
name: "Llamacorn Shirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 54,
name: "Llamacorn Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 54,
name: "Llamacorn Shirt",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 54,
name: "Llamacorn Shirt",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 54,
name: "Llamacorn Shirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 54,
name: "Llamacorn Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 55,
name: "Aagent Headset",
side: "back",
dimensions: { x: 13, y: 25, width: 3, height: 7 },
},
{
itemId: 55,
name: "Aagent Headset",
side: "left",
dimensions: { x: 32, y: 25, width: 3, height: 7 },
},
{
itemId: 56,
name: "Aagent Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 19 },
},
{
itemId: 56,
name: "Aagent Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 19 },
},
{
itemId: 56,
name: "Aagent Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 19 },
},
{
itemId: 56,
name: "Aagent Shirt",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 56,
name: "Aagent Shirt",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 56,
name: "Aagent Shirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 56,
name: "Aagent Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 56,
name: "Aagent Shirt",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 56,
name: "Aagent Shirt",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 56,
name: "Aagent Shirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 56,
name: "Aagent Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 57,
name: "Aagent Shades",
side: "back",
dimensions: { x: 15, y: 22, width: 34, height: 2 },
},
{
itemId: 57,
name: "Aagent Shades",
side: "left",
dimensions: { x: 19, y: 22, width: 25, height: 9 },
},
{
itemId: 57,
name: "Aagent Shades",
side: "right",
dimensions: { x: 20, y: 22, width: 25, height: 9 },
},
{
itemId: 58,
name: "Aagent Pistol",
side: "left back",
dimensions: { x: 2, y: 34, width: 9, height: 7 },
},
{
itemId: 58,
name: "Aagent Pistol",
side: "left",
dimensions: { x: 20, y: 36, width: 9, height: 7 },
},
{
itemId: 58,
name: "Aagent Pistol",
side: "back",
dimensions: { x: 2, y: 34, width: 9, height: 7 },
},
{
itemId: 58,
name: "Aagent Pistol",
side: "right",
dimensions: { x: 35, y: 36, width: 9, height: 7 },
},
{
itemId: 59,
name: "Aagent Fedora Hat",
side: "back",
dimensions: { x: 11, y: 4, width: 42, height: 17 },
},
{
itemId: 59,
name: "Aagent Fedora Hat",
side: "left",
dimensions: { x: 16, y: 4, width: 32, height: 17 },
},
{
itemId: 59,
name: "Aagent Fedora Hat",
side: "right",
dimensions: { x: 16, y: 4, width: 32, height: 17 },
},
{
itemId: 60,
name: "Wizard Hat",
side: "back",
dimensions: { x: 11, y: 0, width: 42, height: 22 },
},
{
itemId: 60,
name: "Wizard Hat",
side: "left",
dimensions: { x: 15, y: 0, width: 34, height: 22 },
},
{
itemId: 60,
name: "Wizard Hat",
side: "right",
dimensions: { x: 15, y: 0, width: 34, height: 22 },
},
{
itemId: 61,
name: "Wizard Hat Legendary",
side: "back",
dimensions: { x: 11, y: 0, width: 42, height: 22 },
},
{
itemId: 61,
name: "Wizard Hat Legendary",
side: "left",
dimensions: { x: 15, y: 0, width: 34, height: 22 },
},
{
itemId: 61,
name: "Wizard Hat Legendary",
side: "right",
dimensions: { x: 15, y: 0, width: 34, height: 22 },
},
{
itemId: 62,
name: "Wizard Hat Mythical",
side: "back",
dimensions: { x: 11, y: 0, width: 42, height: 22 },
},
{
itemId: 62,
name: "Wizard Hat Mythical",
side: "left",
dimensions: { x: 15, y: 0, width: 34, height: 22 },
},
{
itemId: 62,
name: "Wizard Hat Mythical",
side: "right",
dimensions: { x: 15, y: 0, width: 34, height: 22 },
},
{
itemId: 63,
name: "Wizard Hat Godlike",
side: "back",
dimensions: { x: 11, y: 0, width: 42, height: 22 },
},
{
itemId: 63,
name: "Wizard Hat Godlike",
side: "left",
dimensions: { x: 15, y: 0, width: 34, height: 22 },
},
{
itemId: 63,
name: "Wizard Hat Godlike",
side: "right",
dimensions: { x: 15, y: 0, width: 34, height: 22 },
},
{
itemId: 64,
name: "Wizard Staff",
side: "back",
dimensions: { x: 7, y: 24, width: 7, height: 31 },
},
{
itemId: 64,
name: "Wizard Staff",
side: "left",
dimensions: { x: 25, y: 24, width: 3, height: 31 },
},
{
itemId: 64,
name: "Wizard Staff",
side: "right",
dimensions: { x: 36, y: 24, width: 3, height: 31 },
},
{
itemId: 65,
name: "Wizard Staff Legendary",
side: "left",
dimensions: { x: 23, y: 22, width: 7, height: 33 },
},
{
itemId: 65,
name: "Wizard Staff Legendary",
side: "back",
dimensions: { x: 6, y: 22, width: 9, height: 33 },
},
{
itemId: 65,
name: "Wizard Staff Legendary",
side: "right",
dimensions: { x: 34, y: 22, width: 7, height: 33 },
},
{
itemId: 66,
name: "Future Wizard Visor",
side: "back",
dimensions: { x: 15, y: 24, width: 34, height: 4 },
},
{
itemId: 66,
name: "Future Wizard Visor",
side: "left",
dimensions: { x: 19, y: 22, width: 25, height: 8 },
},
{
itemId: 66,
name: "Future Wizard Visor",
side: "right",
dimensions: { x: 20, y: 22, width: 25, height: 8 },
},
{
itemId: 67,
name: "Farmer Straw Hat",
side: "back",
dimensions: { x: 7, y: 2, width: 50, height: 20 },
},
{
itemId: 67,
name: "Farmer Straw Hat",
side: "left",
dimensions: { x: 13, y: 2, width: 38, height: 20 },
},
{
itemId: 67,
name: "Farmer Straw Hat",
side: "right",
dimensions: { x: 13, y: 2, width: 38, height: 20 },
},
{
itemId: 68,
name: "Farmer Jeans",
side: "back",
dimensions: { x: 15, y: 41, width: 34, height: 14 },
},
{
itemId: 68,
name: "Farmer Jeans",
side: "left",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 68,
name: "Farmer Jeans",
side: "right",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 69,
name: "Farmer Pitchfork",
side: "back",
dimensions: { x: 7, y: 24, width: 7, height: 31 },
},
{
itemId: 69,
name: "Farmer Pitchfork",
side: "left",
dimensions: { x: 26, y: 24, width: 1, height: 31 },
},
{
itemId: 69,
name: "Farmer Pitchfork",
side: "right",
dimensions: { x: 37, y: 24, width: 1, height: 31 },
},
{
itemId: 70,
name: "Farmer Handsaw",
side: "left back",
dimensions: { x: 7, y: 19, width: 5, height: 27 },
},
{
itemId: 70,
name: "Farmer Handsaw",
side: "left",
dimensions: { x: 23, y: 19, width: 5, height: 27 },
},
{
itemId: 70,
name: "Farmer Handsaw",
side: "back",
dimensions: { x: 7, y: 19, width: 5, height: 27 },
},
{
itemId: 70,
name: "Farmer Handsaw",
side: "right",
dimensions: { x: 36, y: 19, width: 5, height: 27 },
},
{
itemId: 71,
name: "Santagotchi Hat",
side: "back",
dimensions: { x: 8, y: 0, width: 45, height: 22 },
},
{
itemId: 71,
name: "Santagotchi Hat",
side: "left",
dimensions: { x: 15, y: 0, width: 37, height: 22 },
},
{
itemId: 71,
name: "Santagotchi Hat",
side: "right",
dimensions: { x: 12, y: 0, width: 37, height: 22 },
},
{
itemId: 72,
name: "Jaay Hairpiece",
side: "back",
dimensions: { x: 13, y: 6, width: 36, height: 25 },
},
{
itemId: 72,
name: "Jaay Hairpiece",
side: "left",
dimensions: { x: 18, y: 6, width: 26, height: 25 },
},
{
itemId: 72,
name: "Jaay Hairpiece",
side: "right",
dimensions: { x: 20, y: 6, width: 24, height: 25 },
},
{
itemId: 73,
name: "Jaay Glasses",
side: "back",
dimensions: { x: 15, y: 20, width: 34, height: 2 },
},
{
itemId: 73,
name: "Jaay Glasses",
side: "left",
dimensions: { x: 19, y: 21, width: 25, height: 10 },
},
{
itemId: 73,
name: "Jaay Glasses",
side: "right",
dimensions: { x: 20, y: 21, width: 25, height: 10 },
},
{
itemId: 74,
name: "Jaay Hao Suit",
side: "left",
dimensions: { x: 20, y: 32, width: 24, height: 22 },
},
{
itemId: 74,
name: "Jaay Hao Suit",
side: "right",
dimensions: { x: 20, y: 32, width: 24, height: 22 },
},
{
itemId: 74,
name: "Jaay Hao Suit",
side: "back",
dimensions: { x: 11, y: 31, width: 34, height: 23 },
},
{
itemId: 74,
name: "Jaay Hao Suit",
side: "left back up",
dimensions: { x: 11, y: 31, width: 4, height: 10 },
},
{
itemId: 74,
name: "Jaay Hao Suit",
side: "left back",
dimensions: { x: 11, y: 32, width: 4, height: 11 },
},
{
itemId: 74,
name: "Jaay Hao Suit",
side: "left up",
dimensions: { x: 25, y: 32, width: 10, height: 5 },
},
{
itemId: 74,
name: "Jaay Hao Suit",
side: "left",
dimensions: { x: 20, y: 32, width: 5, height: 10 },
},
{
itemId: 74,
name: "Jaay Hao Suit",
side: "right back up",
dimensions: { x: 49, y: 31, width: 4, height: 10 },
},
{
itemId: 74,
name: "Jaay Hao Suit",
side: "right back",
dimensions: { x: 49, y: 32, width: 4, height: 11 },
},
{
itemId: 74,
name: "Jaay Hao Suit",
side: "right up",
dimensions: { x: 29, y: 32, width: 10, height: 5 },
},
{
itemId: 74,
name: "Jaay Hao Suit",
side: "right",
dimensions: { x: 20, y: 32, width: 5, height: 10 },
},
{
itemId: 75,
name: "OKex Sign",
side: "back",
dimensions: { x: 1, y: 24, width: 13, height: 22 },
},
{
itemId: 75,
name: "OKex Sign",
side: "left",
dimensions: { x: 26, y: 24, width: 1, height: 22 },
},
{
itemId: 76,
name: "Big GHST Token",
side: "back",
dimensions: { x: 1, y: 33, width: 12, height: 12 },
},
{
itemId: 76,
name: "Big GHST Token",
side: "right",
dimensions: { x: 37, y: 33, width: 2, height: 12 },
},
{
itemId: 76,
name: "Big GHST Token",
side: "left",
dimensions: { x: 25, y: 33, width: 2, height: 12 },
},
{
itemId: 77,
name: "Bitcoin Beanie",
side: "back",
dimensions: { x: 13, y: 2, width: 38, height: 18 },
},
{
itemId: 77,
name: "Bitcoin Beanie",
side: "left",
dimensions: { x: 18, y: 2, width: 28, height: 18 },
},
{
itemId: 77,
name: "Bitcoin Beanie",
side: "right",
dimensions: { x: 18, y: 2, width: 28, height: 18 },
},
{
itemId: 78,
name: "Skater Jeans",
side: "back",
dimensions: { x: 15, y: 41, width: 34, height: 14 },
},
{
itemId: 78,
name: "Skater Jeans",
side: "left",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 78,
name: "Skater Jeans",
side: "right",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 79,
name: "Skateboard",
side: "back",
dimensions: { x: 5, y: 25, width: 8, height: 26 },
},
{
itemId: 79,
name: "Skateboard",
side: "left",
dimensions: { x: 25, y: 25, width: 2, height: 26 },
},
{
itemId: 79,
name: "Skateboard",
side: "right",
dimensions: { x: 37, y: 25, width: 2, height: 26 },
},
];
export const sideViewDimensions2 = [
{
itemId: 80,
name: "Sushi Headband",
side: "back",
dimensions: { x: 11, y: 14, width: 38, height: 10 },
},
{
itemId: 80,
name: "Sushi Headband",
side: "left",
dimensions: { x: 19, y: 14, width: 30, height: 10 },
},
{
itemId: 80,
name: "Sushi Headband",
side: "right",
dimensions: { x: 15, y: 14, width: 30, height: 10 },
},
{
itemId: 81,
name: "Sushi Robe",
side: "back",
dimensions: { x: 13, y: 41, width: 36, height: 14 },
},
{
itemId: 81,
name: "Sushi Robe",
side: "left",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 81,
name: "Sushi Robe",
side: "right",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 82,
name: "Sushi Roll",
side: "back",
dimensions: { x: 1, y: 29, width: 19, height: 15 },
},
{
itemId: 82,
name: "Sushi Roll",
side: "left",
dimensions: { x: 18, y: 29, width: 15, height: 14 },
},
{
itemId: 82,
name: "Sushi Roll",
side: "right back",
dimensions: { x: 44, y: 29, width: 19, height: 15 },
},
{
itemId: 82,
name: "Sushi Roll",
side: "right",
dimensions: { x: 31, y: 29, width: 15, height: 14 },
},
{
itemId: 83,
name: "Sushi Knife",
side: "back",
dimensions: { x: 7, y: 25, width: 6, height: 18 },
},
{
itemId: 83,
name: "Sushi Knife",
side: "left",
dimensions: { x: 24, y: 25, width: 4, height: 18 },
},
{
itemId: 83,
name: "Sushi Knife",
side: "right back",
dimensions: { x: 51, y: 25, width: 6, height: 18 },
},
{
itemId: 83,
name: "Sushi Knife",
side: "right",
dimensions: { x: 36, y: 25, width: 4, height: 18 },
},
{
itemId: 84,
name: "Gentleman Hat",
side: "back",
dimensions: { x: 9, y: 2, width: 46, height: 18 },
},
{
itemId: 84,
name: "Gentleman Hat",
side: "left",
dimensions: { x: 13, y: 2, width: 38, height: 18 },
},
{
itemId: 84,
name: "Gentleman Hat",
side: "right",
dimensions: { x: 13, y: 2, width: 38, height: 18 },
},
{
itemId: 85,
name: "Gentleman Suit",
side: "left",
dimensions: { x: 20, y: 32, width: 24, height: 23 },
},
{
itemId: 85,
name: "Gentleman Suit",
side: "right",
dimensions: { x: 20, y: 32, width: 24, height: 23 },
},
{
itemId: 85,
name: "Gentleman Suit",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 23 },
},
{
itemId: 85,
name: "Gentleman Suit",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 85,
name: "Gentleman Suit",
side: "left back",
dimensions: { x: 12, y: 32, width: 3, height: 10 },
},
{
itemId: 85,
name: "Gentleman Suit",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 85,
name: "Gentleman Suit",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 85,
name: "Gentleman Suit",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 85,
name: "Gentleman Suit",
side: "right back",
dimensions: { x: 49, y: 32, width: 3, height: 10 },
},
{
itemId: 85,
name: "Gentleman Suit",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 85,
name: "Gentleman Suit",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 86,
name: "Gentleman Monocle",
side: "left",
dimensions: { x: 19, y: 21, width: 8, height: 21 },
},
{
itemId: 87,
name: "Miner Helmet",
side: "back",
dimensions: { x: 13, y: 4, width: 38, height: 18 },
},
{
itemId: 87,
name: "Miner Helmet",
side: "left",
dimensions: { x: 17, y: 4, width: 30, height: 18 },
},
{
itemId: 87,
name: "Miner Helmet",
side: "right",
dimensions: { x: 17, y: 4, width: 30, height: 18 },
},
{
itemId: 88,
name: "Miner Jeans",
side: "back",
dimensions: { x: 15, y: 41, width: 34, height: 14 },
},
{
itemId: 88,
name: "Miner Jeans",
side: "left",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 88,
name: "Miner Jeans",
side: "right",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 89,
name: "Miner Pickaxe",
side: "left back",
dimensions: { x: 0, y: 30, width: 14, height: 14 },
},
{
itemId: 89,
name: "Miner Pickaxe",
side: "left",
dimensions: { x: 17, y: 30, width: 14, height: 14 },
},
{
itemId: 89,
name: "Miner Pickaxe",
side: "back",
dimensions: { x: 0, y: 30, width: 14, height: 14 },
},
{
itemId: 89,
name: "Miner Pickaxe",
side: "right",
dimensions: { x: 33, y: 30, width: 14, height: 14 },
},
{
itemId: 90,
name: "Pajama Hat",
side: "back",
dimensions: { x: 13, y: 0, width: 43, height: 22 },
},
{
itemId: 90,
name: "Pajama Hat",
side: "left",
dimensions: { x: 17, y: 0, width: 35, height: 22 },
},
{
itemId: 90,
name: "Pajama Hat",
side: "right",
dimensions: { x: 12, y: 0, width: 35, height: 22 },
},
{
itemId: 91,
name: "Pajama Pants",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 91,
name: "Pajama Pants",
side: "right",
dimensions: { x: 20, y: 32, width: 24, height: 22 },
},
{
itemId: 91,
name: "Pajama Pants",
side: "back",
dimensions: { x: 11, y: 31, width: 34, height: 22 },
},
{
itemId: 91,
name: "Pajama Pants",
side: "left back up",
dimensions: { x: 11, y: 31, width: 4, height: 10 },
},
{
itemId: 91,
name: "Pajama Pants",
side: "left back",
dimensions: { x: 11, y: 33, width: 4, height: 10 },
},
{
itemId: 91,
name: "Pajama Pants",
side: "left up",
dimensions: { x: 25, y: 32, width: 10, height: 5 },
},
{
itemId: 91,
name: "Pajama Pants",
side: "left",
dimensions: { x: 20, y: 32, width: 5, height: 10 },
},
{
itemId: 91,
name: "Pajama Pants",
side: "right back up",
dimensions: { x: 49, y: 31, width: 4, height: 10 },
},
{
itemId: 91,
name: "Pajama Pants",
side: "right back",
dimensions: { x: 49, y: 33, width: 4, height: 10 },
},
{
itemId: 91,
name: "Pajama Pants",
side: "right up",
dimensions: { x: 29, y: 32, width: 10, height: 5 },
},
{
itemId: 91,
name: "Pajama Pants",
side: "right",
dimensions: { x: 20, y: 32, width: 5, height: 10 },
},
{
itemId: 92,
name: "Bedtime Milk",
side: "back",
dimensions: { x: 4, y: 34, width: 6, height: 10 },
},
{
itemId: 92,
name: "Bedtime Milk",
side: "left",
dimensions: { x: 21, y: 34, width: 6, height: 10 },
},
{
itemId: 92,
name: "Bedtime Milk",
side: "right back",
dimensions: { x: 54, y: 34, width: 6, height: 10 },
},
{
itemId: 92,
name: "Bedtime Milk",
side: "right",
dimensions: { x: 37, y: 34, width: 6, height: 10 },
},
{
itemId: 93,
name: "Fluffy Blanket",
side: "back",
dimensions: { x: 3, y: 36, width: 11, height: 19 },
},
{
itemId: 93,
name: "Fluffy Blanket",
side: "left",
dimensions: { x: 19, y: 38, width: 11, height: 17 },
},
{
itemId: 93,
name: "Fluffy Blanket",
side: "right back",
dimensions: { x: 50, y: 36, width: 11, height: 19 },
},
{
itemId: 93,
name: "Fluffy Blanket",
side: "right",
dimensions: { x: 34, y: 38, width: 11, height: 17 },
},
{
itemId: 94,
name: "Runner Sweatband",
side: "back",
dimensions: { x: 15, y: 14, width: 34, height: 6 },
},
{
itemId: 94,
name: "Runner Sweatband",
side: "left",
dimensions: { x: 20, y: 14, width: 24, height: 6 },
},
{
itemId: 94,
name: "Runner Sweatband",
side: "right",
dimensions: { x: 20, y: 14, width: 24, height: 6 },
},
{
itemId: 95,
name: "Runner Shorts",
side: "back",
dimensions: { x: 15, y: 41, width: 34, height: 14 },
},
{
itemId: 95,
name: "Runner Shorts",
side: "left",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 95,
name: "Runner Shorts",
side: "right",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 96,
name: "Water Bottle",
side: "back",
dimensions: { x: 7, y: 31, width: 6, height: 13 },
},
{
itemId: 96,
name: "Water Bottle",
side: "left",
dimensions: { x: 24, y: 31, width: 6, height: 13 },
},
{
itemId: 96,
name: "Water Bottle",
side: "right back",
dimensions: { x: 51, y: 31, width: 6, height: 13 },
},
{
itemId: 96,
name: "Water Bottle",
side: "right",
dimensions: { x: 34, y: 31, width: 6, height: 13 },
},
{
itemId: 97,
name: "Pillbox Hat",
side: "back",
dimensions: { x: 0, y: 0, width: 42, height: 18 },
},
{
itemId: 97,
name: "Pillbox Hat",
side: "left",
dimensions: { x: 0, y: 0, width: 32, height: 18 },
},
{
itemId: 97,
name: "Pillbox Hat",
side: "right",
dimensions: { x: 0, y: 0, width: 32, height: 18 },
},
{
itemId: 98,
name: "Lady Skirt",
side: "back",
dimensions: { x: 0, y: 0, width: 34, height: 15 },
},
{
itemId: 98,
name: "Lady Skirt",
side: "left",
dimensions: { x: 0, y: 0, width: 24, height: 15 },
},
{
itemId: 98,
name: "Lady Skirt",
side: "right",
dimensions: { x: 0, y: 0, width: 24, height: 15 },
},
{
itemId: 99,
name: "Lady Parasol",
side: "back",
dimensions: { x: 0, y: 0, width: 17, height: 25 },
},
{
itemId: 99,
name: "Lady Parasol",
side: "left",
dimensions: { x: 0, y: 0, width: 17, height: 25 },
},
{
itemId: 99,
name: "Lady Parasol",
side: "right back",
dimensions: { x: 46, y: 21, width: 17, height: 25 },
},
{
itemId: 99,
name: "Lady Parasol",
side: "right",
dimensions: { x: 0, y: 0, width: 17, height: 25 },
},
{
itemId: 100,
name: "Lady Clutch",
side: "back",
dimensions: { x: 0, y: 0, width: 9, height: 14 },
},
{
itemId: 100,
name: "Lady Clutch",
side: "left",
dimensions: { x: 0, y: 0, width: 9, height: 14 },
},
{
itemId: 100,
name: "Lady Clutch",
side: "right back",
dimensions: { x: 51, y: 37, width: 9, height: 14 },
},
{
itemId: 100,
name: "Lady Clutch",
side: "right",
dimensions: { x: 0, y: 0, width: 9, height: 14 },
},
{
itemId: 101,
name: "Witch Hat",
side: "back",
dimensions: { x: 11, y: 0, width: 42, height: 22 },
},
{
itemId: 101,
name: "Witch Hat",
side: "left",
dimensions: { x: 15, y: 0, width: 34, height: 22 },
},
{
itemId: 101,
name: "Witch Hat",
side: "right",
dimensions: { x: 15, y: 0, width: 34, height: 22 },
},
{
itemId: 102,
name: "Witch Cape",
side: "left",
dimensions: { x: 20, y: 29, width: 30, height: 26 },
},
{
itemId: 102,
name: "Witch Cape",
side: "right",
dimensions: { x: 14, y: 29, width: 30, height: 26 },
},
{
itemId: 102,
name: "Witch Cape",
side: "back",
dimensions: { x: 9, y: 30, width: 46, height: 25 },
},
{
itemId: 102,
name: "Witch Cape",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 102,
name: "Witch Cape",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 102,
name: "Witch Cape",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 102,
name: "Witch Cape",
side: "left",
dimensions: { x: 20, y: 29, width: 4, height: 9 },
},
{
itemId: 102,
name: "Witch Cape",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 102,
name: "Witch Cape",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 102,
name: "Witch Cape",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 102,
name: "Witch Cape",
side: "right",
dimensions: { x: 14, y: 29, width: 4, height: 9 },
},
{
itemId: 103,
name: "Witch Wand",
side: "back",
dimensions: { x: 3, y: 33, width: 11, height: 11 },
},
{
itemId: 103,
name: "Witch Wand",
side: "left",
dimensions: { x: 18, y: 33, width: 11, height: 11 },
},
{
itemId: 103,
name: "Witch Wand",
side: "right back",
dimensions: { x: 50, y: 33, width: 11, height: 11 },
},
{
itemId: 103,
name: "Witch Wand",
side: "right",
dimensions: { x: 35, y: 33, width: 11, height: 11 },
},
{
itemId: 104,
name: "Portal Mage Helmet",
side: "back",
dimensions: { x: 8, y: 1, width: 48, height: 32 },
},
{
itemId: 104,
name: "Portal Mage Helmet",
side: "left",
dimensions: { x: 20, y: 1, width: 24, height: 38 },
},
{
itemId: 104,
name: "Portal Mage Helmet",
side: "right",
dimensions: { x: 20, y: 1, width: 24, height: 38 },
},
{
itemId: 105,
name: "Portal Mage Armor",
side: "left",
dimensions: { x: 20, y: 29, width: 24, height: 26 },
},
{
itemId: 105,
name: "Portal Mage Armor",
side: "right",
dimensions: { x: 20, y: 29, width: 24, height: 26 },
},
{
itemId: 105,
name: "Portal Mage Armor",
side: "back",
dimensions: { x: 7, y: 29, width: 34, height: 26 },
},
{
itemId: 105,
name: "Portal Mage Armor",
side: "left back up",
dimensions: { x: 7, y: 29, width: 8, height: 12 },
},
{
itemId: 105,
name: "Portal Mage Armor",
side: "left back",
dimensions: { x: 7, y: 29, width: 8, height: 14 },
},
{
itemId: 105,
name: "Portal Mage Armor",
side: "left up",
dimensions: { x: 25, y: 28, width: 14, height: 15 },
},
{
itemId: 105,
name: "Portal Mage Armor",
side: "left",
dimensions: { x: 20, y: 28, width: 15, height: 14 },
},
{
itemId: 105,
name: "Portal Mage Armor",
side: "right back up",
dimensions: { x: 49, y: 29, width: 8, height: 12 },
},
{
itemId: 105,
name: "Portal Mage Armor",
side: "right back",
dimensions: { x: 49, y: 29, width: 8, height: 14 },
},
{
itemId: 105,
name: "Portal Mage Armor",
side: "right up",
dimensions: { x: 25, y: 28, width: 14, height: 15 },
},
{
itemId: 105,
name: "Portal Mage Armor",
side: "right",
dimensions: { x: 20, y: 28, width: 15, height: 14 },
},
{
itemId: 106,
name: "Portal Mage Axe",
side: "back",
dimensions: { x: 0, y: 18, width: 14, height: 28 },
},
{
itemId: 106,
name: "Portal Mage Axe",
side: "left",
dimensions: { x: 17, y: 19, width: 14, height: 28 },
},
{
itemId: 106,
name: "Portal Mage Axe",
side: "right back",
dimensions: { x: 50, y: 18, width: 14, height: 28 },
},
{
itemId: 106,
name: "Portal Mage Axe",
side: "right",
dimensions: { x: 33, y: 19, width: 14, height: 28 },
},
{
itemId: 107,
name: "Portal Mage Black Axe",
side: "back",
dimensions: { x: 0, y: 18, width: 14, height: 28 },
},
{
itemId: 107,
name: "Portal Mage Black Axe",
side: "left",
dimensions: { x: 17, y: 19, width: 14, height: 28 },
},
{
itemId: 107,
name: "Portal Mage Black Axe",
side: "right back",
dimensions: { x: 50, y: 18, width: 14, height: 28 },
},
{
itemId: 107,
name: "Portal Mage Black Axe",
side: "right",
dimensions: { x: 33, y: 19, width: 14, height: 28 },
},
{
itemId: 108,
name: "Rasta Dreds",
side: "back",
dimensions: { x: 11, y: 3, width: 42, height: 27 },
},
{
itemId: 108,
name: "Rasta Dreds",
side: "left",
dimensions: { x: 16, y: 3, width: 32, height: 27 },
},
{
itemId: 108,
name: "Rasta Dreds",
side: "right",
dimensions: { x: 16, y: 3, width: 32, height: 27 },
},
{
itemId: 109,
name: "Rasta Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 109,
name: "Rasta Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 109,
name: "Rasta Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 20 },
},
{
itemId: 109,
name: "Rasta Shirt",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 109,
name: "Rasta Shirt",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 109,
name: "Rasta Shirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 109,
name: "Rasta Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 109,
name: "Rasta Shirt",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 109,
name: "Rasta Shirt",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 109,
name: "Rasta Shirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 109,
name: "Rasta Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 110,
name: "Jamaican Flag",
side: "back",
dimensions: { x: 2, y: 24, width: 10, height: 28 },
},
{
itemId: 110,
name: "Jamaican Flag",
side: "left",
dimensions: { x: 25, y: 24, width: 1, height: 28 },
},
{
itemId: 110,
name: "Jamaican Flag",
side: "right back",
dimensions: { x: 52, y: 24, width: 10, height: 28 },
},
{
itemId: 110,
name: "Jamaican Flag",
side: "right",
dimensions: { x: 38, y: 24, width: 1, height: 28 },
},
{
itemId: 111,
name: "Hazmat Hood",
side: "back",
dimensions: { x: 14, y: 6, width: 36, height: 30 },
},
{
itemId: 111,
name: "Hazmat Hood",
side: "left",
dimensions: { x: 20, y: 6, width: 24, height: 34 },
},
{
itemId: 111,
name: "Hazmat Hood",
side: "right",
dimensions: { x: 20, y: 6, width: 24, height: 34 },
},
{
itemId: 112,
name: "Hazmat Suit",
side: "left",
dimensions: { x: 20, y: 33, width: 31, height: 22 },
},
{
itemId: 112,
name: "Hazmat Suit",
side: "right",
dimensions: { x: 13, y: 33, width: 31, height: 22 },
},
{
itemId: 112,
name: "Hazmat Suit",
side: "back",
dimensions: { x: 7, y: 31, width: 34, height: 22 },
},
{
itemId: 112,
name: "Hazmat Suit",
side: "left back up",
dimensions: { x: 7, y: 31, width: 8, height: 10 },
},
{
itemId: 112,
name: "Hazmat Suit",
side: "left back",
dimensions: { x: 7, y: 33, width: 8, height: 10 },
},
{
itemId: 112,
name: "Hazmat Suit",
side: "left up",
dimensions: { x: 25, y: 28, width: 10, height: 10 },
},
{
itemId: 112,
name: "Hazmat Suit",
side: "left",
dimensions: { x: 20, y: 28, width: 10, height: 10 },
},
{
itemId: 112,
name: "Hazmat Suit",
side: "right back up",
dimensions: { x: 49, y: 31, width: 8, height: 10 },
},
{
itemId: 112,
name: "Hazmat Suit",
side: "right back",
dimensions: { x: 49, y: 33, width: 8, height: 10 },
},
{
itemId: 112,
name: "Hazmat Suit",
side: "right up",
dimensions: { x: 29, y: 28, width: 10, height: 10 },
},
{
itemId: 112,
name: "Hazmat Suit",
side: "right",
dimensions: { x: 13, y: 28, width: 10, height: 10 },
},
{
itemId: 113,
name: "Uranium Rod",
side: "back",
dimensions: { x: 9, y: 25, width: 3, height: 19 },
},
{
itemId: 113,
name: "Uranium Rod",
side: "left",
dimensions: { x: 22, y: 25, width: 3, height: 19 },
},
{
itemId: 113,
name: "Uranium Rod",
side: "right back",
dimensions: { x: 52, y: 25, width: 3, height: 19 },
},
{
itemId: 113,
name: "Uranium Rod",
side: "right",
dimensions: { x: 37, y: 25, width: 3, height: 19 },
},
{
itemId: 114,
name: "Red Hawaiian Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 18 },
},
{
itemId: 114,
name: "Red Hawaiian Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 18 },
},
{
itemId: 114,
name: "Red Hawaiian Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 18 },
},
{
itemId: 114,
name: "Red Hawaiian Shirt",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 114,
name: "Red Hawaiian Shirt",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 114,
name: "Red Hawaiian Shirt",
side: "left up",
dimensions: { x: 26, y: 32, width: 9, height: 5 },
},
{
itemId: 114,
name: "Red Hawaiian Shirt",
side: "left",
dimensions: { x: 20, y: 32, width: 5, height: 9 },
},
{
itemId: 114,
name: "Red Hawaiian Shirt",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 114,
name: "Red Hawaiian Shirt",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 114,
name: "Red Hawaiian Shirt",
side: "right up",
dimensions: { x: 29, y: 32, width: 9, height: 5 },
},
{
itemId: 114,
name: "Red Hawaiian Shirt",
side: "right",
dimensions: { x: 20, y: 32, width: 5, height: 9 },
},
{
itemId: 115,
name: "Blue Hawaiian Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 18 },
},
{
itemId: 115,
name: "Blue Hawaiian Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 18 },
},
{
itemId: 115,
name: "Blue Hawaiian Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 18 },
},
{
itemId: 115,
name: "Blue Hawaiian Shirt",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 115,
name: "Blue Hawaiian Shirt",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 115,
name: "Blue Hawaiian Shirt",
side: "left up",
dimensions: { x: 26, y: 32, width: 9, height: 5 },
},
{
itemId: 115,
name: "Blue Hawaiian Shirt",
side: "left",
dimensions: { x: 20, y: 32, width: 5, height: 9 },
},
{
itemId: 115,
name: "Blue Hawaiian Shirt",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 115,
name: "Blue Hawaiian Shirt",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 115,
name: "Blue Hawaiian Shirt",
side: "right up",
dimensions: { x: 29, y: 32, width: 9, height: 5 },
},
{
itemId: 115,
name: "Blue Hawaiian Shirt",
side: "right",
dimensions: { x: 20, y: 32, width: 5, height: 9 },
},
{
itemId: 116,
name: "Coconut",
side: "left back",
dimensions: { x: 1, y: 27, width: 12, height: 18 },
},
{
itemId: 116,
name: "Coconut",
side: "left",
dimensions: { x: 18, y: 27, width: 12, height: 18 },
},
{
itemId: 116,
name: "Coconut",
side: "back",
dimensions: { x: 1, y: 27, width: 12, height: 18 },
},
{
itemId: 116,
name: "Coconut",
side: "right",
dimensions: { x: 34, y: 27, width: 12, height: 18 },
},
{
itemId: 117,
name: "Deal With It Shades",
side: "back",
dimensions: { x: 15, y: 22, width: 34, height: 2 },
},
{
itemId: 117,
name: "Deal With It Shades",
side: "left",
dimensions: { x: 19, y: 22, width: 25, height: 8 },
},
{
itemId: 117,
name: "Deal With It Shades",
side: "right",
dimensions: { x: 20, y: 22, width: 25, height: 8 },
},
{
itemId: 118,
name: "Water Jug",
side: "left back",
dimensions: { x: 1, y: 21, width: 16, height: 26 },
},
{
itemId: 118,
name: "Water Jug",
side: "left",
dimensions: { x: 14, y: 21, width: 16, height: 26 },
},
{
itemId: 118,
name: "Water Jug",
side: "back",
dimensions: { x: 1, y: 21, width: 16, height: 26 },
},
{
itemId: 118,
name: "Water Jug",
side: "right",
dimensions: { x: 34, y: 21, width: 16, height: 26 },
},
];
export const sideViewDimensions3 = [
{
itemId: 119,
name: "Baby Bottle",
side: "left back",
dimensions: { x: 6, y: 27, width: 7, height: 17 },
},
{
itemId: 119,
name: "Baby Bottle",
side: "left",
dimensions: { x: 22, y: 27, width: 7, height: 17 },
},
{
itemId: 119,
name: "Baby Bottle",
side: "back",
dimensions: { x: 6, y: 27, width: 7, height: 17 },
},
{
itemId: 119,
name: "Baby Bottle",
side: "right",
dimensions: { x: 35, y: 27, width: 7, height: 17 },
},
{
itemId: 120,
name: "Martini",
side: "left back",
dimensions: { x: 1, y: 25, width: 14, height: 19 },
},
{
itemId: 120,
name: "Martini",
side: "left",
dimensions: { x: 21, y: 27, width: 14, height: 19 },
},
{
itemId: 120,
name: "Martini",
side: "back",
dimensions: { x: 1, y: 25, width: 14, height: 19 },
},
{
itemId: 120,
name: "Martini",
side: "right",
dimensions: { x: 29, y: 27, width: 14, height: 19 },
},
{
itemId: 121,
name: "Wine Bottle",
side: "left",
dimensions: { x: 23, y: 23, width: 7, height: 22 },
},
{
itemId: 121,
name: "Wine Bottle",
side: "right",
dimensions: { x: 34, y: 23, width: 7, height: 22 },
},
{
itemId: 121,
name: "Wine Bottle",
side: "left back",
dimensions: { x: 6, y: 23, width: 7, height: 22 },
},
{
itemId: 121,
name: "Wine Bottle",
side: "back",
dimensions: { x: 6, y: 23, width: 7, height: 22 },
},
{
itemId: 122,
name: "Milkshake",
side: "left back",
dimensions: { x: 2, y: 21, width: 12, height: 29 },
},
{
itemId: 122,
name: "Milkshake",
side: "left",
dimensions: { x: 19, y: 21, width: 12, height: 29 },
},
{
itemId: 122,
name: "Milkshake",
side: "back",
dimensions: { x: 2, y: 21, width: 12, height: 29 },
},
{
itemId: 122,
name: "Milkshake",
side: "right",
dimensions: { x: 33, y: 21, width: 12, height: 29 },
},
{
itemId: 123,
name: "Apple Juice",
side: "left back",
dimensions: { x: 3, y: 30, width: 8, height: 14 },
},
{
itemId: 123,
name: "Apple Juice",
side: "left",
dimensions: { x: 22, y: 30, width: 8, height: 14 },
},
{
itemId: 123,
name: "Apple Juice",
side: "back",
dimensions: { x: 3, y: 30, width: 8, height: 14 },
},
{
itemId: 123,
name: "Apple Juice",
side: "right",
dimensions: { x: 34, y: 30, width: 8, height: 14 },
},
{
itemId: 124,
name: "Beer Helmet",
side: "back",
dimensions: { x: 5, y: 2, width: 54, height: 32 },
},
{
itemId: 124,
name: "Beer Helmet",
side: "left",
dimensions: { x: 14, y: 3, width: 33, height: 27 },
},
{
itemId: 124,
name: "Beer Helmet",
side: "right",
dimensions: { x: 17, y: 3, width: 33, height: 27 },
},
{
itemId: 125,
name: "Track Suit",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 125,
name: "Track Suit",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 125,
name: "Track Suit",
side: "back",
dimensions: { x: 11, y: 31, width: 34, height: 22 },
},
{
itemId: 125,
name: "Track Suit",
side: "left back up",
dimensions: { x: 11, y: 31, width: 4, height: 10 },
},
{
itemId: 125,
name: "Track Suit",
side: "left back",
dimensions: { x: 11, y: 33, width: 4, height: 10 },
},
{
itemId: 125,
name: "Track Suit",
side: "left up",
dimensions: { x: 25, y: 32, width: 10, height: 5 },
},
{
itemId: 125,
name: "Track Suit",
side: "left",
dimensions: { x: 20, y: 32, width: 5, height: 10 },
},
{
itemId: 125,
name: "Track Suit",
side: "right back up",
dimensions: { x: 49, y: 31, width: 4, height: 10 },
},
{
itemId: 125,
name: "Track Suit",
side: "right back",
dimensions: { x: 49, y: 33, width: 4, height: 10 },
},
{
itemId: 125,
name: "Track Suit",
side: "right up",
dimensions: { x: 29, y: 32, width: 10, height: 5 },
},
{
itemId: 125,
name: "Track Suit",
side: "right",
dimensions: { x: 20, y: 32, width: 5, height: 10 },
},
{
itemId: 126,
name: "Kinship Potion",
side: "back",
dimensions: { x: 27, y: 37, width: 10, height: 14 },
},
{
itemId: 127,
name: "Greater Kinship Potion",
side: "back",
dimensions: { x: 27, y: 37, width: 10, height: 14 },
},
{
itemId: 128,
name: "XP Potion",
side: "back",
dimensions: { x: 3, y: 26, width: 10, height: 18 },
},
{
itemId: 129,
name: "Greater XP Potion",
side: "back",
dimensions: { x: 3, y: 26, width: 10, height: 18 },
},
{
itemId: 130,
name: "Fireball",
side: "left back",
dimensions: { x: 3, y: 32, width: 10, height: 12 },
},
{
itemId: 130,
name: "Fireball",
side: "left",
dimensions: { x: 23, y: 32, width: 7, height: 12 },
},
{
itemId: 130,
name: "Fireball",
side: "back",
dimensions: { x: 3, y: 32, width: 10, height: 12 },
},
{
itemId: 130,
name: "Fireball",
side: "right",
dimensions: { x: 34, y: 32, width: 7, height: 12 },
},
{
itemId: 131,
name: "Dragon Horns",
side: "back",
dimensions: { x: 19, y: 3, width: 26, height: 15 },
},
{
itemId: 131,
name: "Dragon Horns",
side: "left",
dimensions: { x: 27, y: 3, width: 8, height: 15 },
},
{
itemId: 131,
name: "Dragon Horns",
side: "right",
dimensions: { x: 29, y: 3, width: 8, height: 15 },
},
{
itemId: 132,
name: "Dragon Wings",
side: "back",
dimensions: { x: 7, y: 19, width: 50, height: 31 },
},
{
itemId: 132,
name: "Dragon Wings",
side: "left",
dimensions: { x: 37, y: 19, width: 20, height: 31 },
},
{
itemId: 132,
name: "Dragon Wings",
side: "right",
dimensions: { x: 7, y: 19, width: 20, height: 31 },
},
{
itemId: 133,
name: "Pointy Horns",
side: "back",
dimensions: { x: 19, y: 4, width: 26, height: 14 },
},
{
itemId: 133,
name: "Pointy Horns",
side: "left",
dimensions: { x: 27, y: 4, width: 7, height: 14 },
},
{
itemId: 133,
name: "Pointy Horns",
side: "right",
dimensions: { x: 30, y: 4, width: 7, height: 14 },
},
{
itemId: 134,
name: "L2 Sign",
side: "back",
dimensions: { x: 1, y: 24, width: 13, height: 23 },
},
{
itemId: 134,
name: "L2 Sign",
side: "left",
dimensions: { x: 25, y: 24, width: 1, height: 23 },
},
{
itemId: 134,
name: "L2 Sign",
side: "right",
dimensions: { x: 38, y: 24, width: 1, height: 23 },
},
{
itemId: 135,
name: "Polygon Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 135,
name: "Polygon Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 135,
name: "Polygon Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 20 },
},
{
itemId: 135,
name: "Polygon Shirt",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 135,
name: "Polygon Shirt",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 135,
name: "Polygon Shirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 135,
name: "Polygon Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 135,
name: "Polygon Shirt",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 135,
name: "Polygon Shirt",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 135,
name: "Polygon Shirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 135,
name: "Polygon Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 136,
name: "Polygon Cap",
side: "back",
dimensions: { x: 15, y: 4, width: 42, height: 17 },
},
{
itemId: 136,
name: "Polygon Cap",
side: "left",
dimensions: { x: 20, y: 4, width: 24, height: 17 },
},
{
itemId: 136,
name: "Polygon Cap",
side: "right",
dimensions: { x: 20, y: 4, width: 24, height: 19 },
},
{
itemId: 137,
name: "Vote Sign",
side: "back",
dimensions: { x: 0, y: 24, width: 17, height: 23 },
},
{
itemId: 137,
name: "Vote Sign",
side: "left",
dimensions: { x: 26, y: 24, width: 1, height: 23 },
},
{
itemId: 137,
name: "Vote Sign",
side: "right",
dimensions: { x: 38, y: 24, width: 1, height: 23 },
},
{
itemId: 138,
name: "Snapshot Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 138,
name: "Snapshot Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 138,
name: "Snapshot Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 20 },
},
{
itemId: 138,
name: "Snapshot Shirt",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 138,
name: "Snapshot Shirt",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 138,
name: "Snapshot Shirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 138,
name: "Snapshot Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 138,
name: "Snapshot Shirt",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 138,
name: "Snapshot Shirt",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 138,
name: "Snapshot Shirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 138,
name: "Snapshot Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 139,
name: "Snapshot Hat",
side: "back",
dimensions: { x: 15, y: 4, width: 42, height: 17 },
},
{
itemId: 139,
name: "Snapshot Hat",
side: "left",
dimensions: { x: 20, y: 4, width: 24, height: 17 },
},
{
itemId: 139,
name: "Snapshot Hat",
side: "right",
dimensions: { x: 20, y: 4, width: 24, height: 19 },
},
{
itemId: 140,
name: "Elf Ears",
side: "back",
dimensions: { x: 9, y: 18, width: 46, height: 12 },
},
{
itemId: 140,
name: "Elf Ears",
side: "left",
dimensions: { x: 31, y: 18, width: 6, height: 12 },
},
{
itemId: 140,
name: "Elf Ears",
side: "right",
dimensions: { x: 27, y: 18, width: 6, height: 12 },
},
];
export const sideViewDimensions4 = [
{
itemId: 141,
name: "Gemstone Ring",
side: "left back",
dimensions: { x: 5, y: 29, width: 8, height: 14 },
},
{
itemId: 141,
name: "Gemstone Ring",
side: "left",
dimensions: { x: 22, y: 29, width: 7, height: 14 },
},
{
itemId: 141,
name: "Gemstone Ring",
side: "back",
dimensions: { x: 5, y: 29, width: 8, height: 14 },
},
{
itemId: 141,
name: "Gemstone Ring",
side: "right",
dimensions: { x: 35, y: 29, width: 7, height: 14 },
},
{
itemId: 142,
name: "Princess Tiara",
side: "back",
dimensions: { x: 15, y: 14, width: 34, height: 4 },
},
{
itemId: 142,
name: "Princess Tiara",
side: "left",
dimensions: { x: 19, y: 8, width: 26, height: 10 },
},
{
itemId: 142,
name: "Princess Tiara",
side: "right",
dimensions: { x: 19, y: 8, width: 26, height: 10 },
},
{
itemId: 143,
name: "Gold Necklace",
side: "back",
dimensions: { x: 15, y: 33, width: 34, height: 1 },
},
{
itemId: 143,
name: "Gold Necklace",
side: "left",
dimensions: { x: 19, y: 33, width: 25, height: 13 },
},
{
itemId: 143,
name: "Gold Necklace",
side: "right",
dimensions: { x: 20, y: 33, width: 25, height: 13 },
},
{
itemId: 144,
name: "Princess Hair",
side: "back",
dimensions: { x: 15, y: 6, width: 34, height: 45 },
},
{
itemId: 144,
name: "Princess Hair",
side: "left",
dimensions: { x: 19, y: 6, width: 26, height: 45 },
},
{
itemId: 144,
name: "Princess Hair",
side: "right",
dimensions: { x: 19, y: 6, width: 26, height: 45 },
},
{
itemId: 145,
name: "Godli Locks",
side: "back",
dimensions: { x: 15, y: 6, width: 34, height: 45 },
},
{
itemId: 145,
name: "Godli Locks",
side: "left",
dimensions: { x: 19, y: 6, width: 26, height: 45 },
},
{
itemId: 145,
name: "Godli Locks",
side: "right",
dimensions: { x: 19, y: 6, width: 26, height: 45 },
},
{
itemId: 146,
name: "Imperial Moustache",
side: "left",
dimensions: { x: 18, y: 32, width: 8, height: 7 },
},
{
itemId: 146,
name: "Imperial Moustache",
side: "right",
dimensions: { x: 38, y: 32, width: 8, height: 7 },
},
{
itemId: 147,
name: "Tiny Crown",
side: "back",
dimensions: { x: 26, y: 4, width: 12, height: 6 },
},
{
itemId: 147,
name: "Tiny Crown",
side: "left",
dimensions: { x: 27, y: 4, width: 10, height: 6 },
},
{
itemId: 147,
name: "Tiny Crown",
side: "right",
dimensions: { x: 27, y: 4, width: 10, height: 6 },
},
{
itemId: 148,
name: "Royal Scepter",
side: "left back",
dimensions: { x: 7, y: 28, width: 6, height: 21 },
},
{
itemId: 148,
name: "Royal Scepter",
side: "left",
dimensions: { x: 26, y: 28, width: 1, height: 21 },
},
{
itemId: 148,
name: "Royal Scepter",
side: "back",
dimensions: { x: 7, y: 28, width: 6, height: 21 },
},
{
itemId: 148,
name: "Royal Scepter",
side: "right",
dimensions: { x: 37, y: 28, width: 1, height: 21 },
},
{
itemId: 149,
name: "Royal Crown",
side: "back",
dimensions: { x: 15, y: 6, width: 34, height: 12 },
},
{
itemId: 149,
name: "Royal Crown",
side: "left",
dimensions: { x: 20, y: 5, width: 24, height: 12 },
},
{
itemId: 149,
name: "Royal Crown",
side: "right",
dimensions: { x: 20, y: 5, width: 24, height: 12 },
},
{
itemId: 150,
name: "Royal Robes",
side: "left",
dimensions: { x: 20, y: 30, width: 30, height: 25 },
},
{
itemId: 150,
name: "Royal Robes",
side: "right",
dimensions: { x: 14, y: 30, width: 30, height: 25 },
},
{
itemId: 150,
name: "Royal Robes",
side: "back",
dimensions: { x: 9, y: 30, width: 46, height: 25 },
},
{
itemId: 150,
name: "Royal Robes",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 150,
name: "Royal Robes",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 150,
name: "Royal Robes",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 150,
name: "Royal Robes",
side: "left",
dimensions: { x: 20, y: 30, width: 4, height: 9 },
},
{
itemId: 150,
name: "Royal Robes",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 150,
name: "Royal Robes",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 150,
name: "Royal Robes",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 150,
name: "Royal Robes",
side: "right",
dimensions: { x: 14, y: 30, width: 4, height: 9 },
},
{
itemId: 151,
name: "Common Rofl",
side: "back",
dimensions: { x: 2, y: 43, width: 20, height: 17 },
},
{
itemId: 151,
name: "Common Rofl",
side: "left",
dimensions: { x: 14, y: 43, width: 19, height: 17 },
},
{
itemId: 151,
name: "Common Rofl",
side: "right",
dimensions: { x: 31, y: 43, width: 19, height: 17 },
},
{
itemId: 152,
name: "Uncommon Rofl",
side: "back",
dimensions: { x: 2, y: 43, width: 20, height: 17 },
},
{
itemId: 152,
name: "Uncommon Rofl",
side: "left",
dimensions: { x: 14, y: 43, width: 19, height: 17 },
},
{
itemId: 152,
name: "Uncommon Rofl",
side: "right",
dimensions: { x: 31, y: 43, width: 19, height: 17 },
},
{
itemId: 153,
name: "Rare Rofl",
side: "back",
dimensions: { x: 2, y: 43, width: 20, height: 17 },
},
{
itemId: 153,
name: "Rare Rofl",
side: "left",
dimensions: { x: 14, y: 43, width: 19, height: 17 },
},
{
itemId: 153,
name: "Rare Rofl",
side: "right",
dimensions: { x: 31, y: 43, width: 19, height: 17 },
},
{
itemId: 154,
name: "Legendary Rofl",
side: "back",
dimensions: { x: 2, y: 43, width: 20, height: 17 },
},
{
itemId: 154,
name: "Legendary Rofl",
side: "left",
dimensions: { x: 14, y: 43, width: 19, height: 17 },
},
{
itemId: 154,
name: "Legendary Rofl",
side: "right",
dimensions: { x: 31, y: 43, width: 19, height: 17 },
},
{
itemId: 155,
name: "Mythical Rofl",
side: "back",
dimensions: { x: 2, y: 38, width: 20, height: 22 },
},
{
itemId: 155,
name: "Mythical Rofl",
side: "left",
dimensions: { x: 14, y: 38, width: 19, height: 22 },
},
{
itemId: 155,
name: "Mythical Rofl",
side: "right",
dimensions: { x: 31, y: 38, width: 19, height: 22 },
},
{
itemId: 156,
name: "Godlike Rofl",
side: "back",
dimensions: { x: 1, y: 38, width: 26, height: 22 },
},
{
itemId: 156,
name: "Godlike Rofl",
side: "left",
dimensions: { x: 14, y: 38, width: 25, height: 22 },
},
{
itemId: 156,
name: "Godlike Rofl",
side: "right",
dimensions: { x: 25, y: 38, width: 25, height: 22 },
},
{
itemId: 158,
name: "Lil Pump Drink",
side: "left back",
dimensions: { x: 4, y: 31, width: 8, height: 13 },
},
{
itemId: 158,
name: "Lil Pump Drink",
side: "left",
dimensions: { x: 21, y: 31, width: 7, height: 13 },
},
{
itemId: 158,
name: "Lil Pump Drink",
side: "back",
dimensions: { x: 4, y: 31, width: 8, height: 13 },
},
{
itemId: 158,
name: "Lil Pump Drink",
side: "right",
dimensions: { x: 36, y: 31, width: 7, height: 13 },
},
{
itemId: 159,
name: "Lil Pump Shades",
side: "back",
dimensions: { x: 15, y: 24, width: 34, height: 2 },
},
{
itemId: 159,
name: "Lil Pump Shades",
side: "left",
dimensions: { x: 19, y: 19, width: 25, height: 12 },
},
{
itemId: 159,
name: "Lil Pump Shades",
side: "right",
dimensions: { x: 20, y: 19, width: 25, height: 12 },
},
{
itemId: 160,
name: "Lil Pump Threads",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 160,
name: "Lil Pump Threads",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 160,
name: "Lil Pump Threads",
side: "back",
dimensions: { x: 11, y: 31, width: 34, height: 22 },
},
{
itemId: 160,
name: "Lil Pump Threads",
side: "left back up",
dimensions: { x: 11, y: 31, width: 4, height: 10 },
},
{
itemId: 160,
name: "Lil Pump Threads",
side: "left back",
dimensions: { x: 11, y: 33, width: 4, height: 10 },
},
{
itemId: 160,
name: "Lil Pump Threads",
side: "left up",
dimensions: { x: 25, y: 32, width: 10, height: 5 },
},
{
itemId: 160,
name: "Lil Pump Threads",
side: "left",
dimensions: { x: 20, y: 32, width: 5, height: 10 },
},
{
itemId: 160,
name: "Lil Pump Threads",
side: "right back up",
dimensions: { x: 49, y: 31, width: 4, height: 10 },
},
{
itemId: 160,
name: "Lil Pump Threads",
side: "right back",
dimensions: { x: 49, y: 33, width: 4, height: 10 },
},
{
itemId: 160,
name: "Lil Pump Threads",
side: "right up",
dimensions: { x: 29, y: 32, width: 10, height: 5 },
},
{
itemId: 160,
name: "Lil Pump Threads",
side: "right",
dimensions: { x: 20, y: 32, width: 5, height: 10 },
},
{
itemId: 161,
name: "Lil Pump Dreads",
side: "back",
dimensions: { x: 13, y: 6, width: 38, height: 28 },
},
{
itemId: 161,
name: "Lil Pump Dreads",
side: "left",
dimensions: { x: 21, y: 6, width: 23, height: 28 },
},
{
itemId: 161,
name: "Lil Pump Dreads",
side: "right",
dimensions: { x: 20, y: 6, width: 23, height: 28 },
},
/*{
itemId: "n/a",
name: "Aagent Radio Front",
side: "front",
dimensions: {x:53, y:31, width:5, height:13},
},
{
itemId: "n/a",
name: "Aagent Radio",
side: "left back",
dimensions: {x:6, y:31, width:5, height:13},
},
{
itemId: "n/a",
name: "Aagent Radio",
side: "left",
dimensions: {x:25, y:31, width:2, height:13},
},
{
itemId: "n/a",
name: "Aagent Radio",
side: "right back",
dimensions: {x:53, y:31, width:5, height:13},
},
{
itemId: "n/a",
name: "Aagent Radio",
side: "right",
dimensions: {x:37, y:31, width:2, height:13},
},*/
{
itemId: 203,
name: "Gamer Jacket",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "front",
dimensions: { x: 15, y: 33, width: 34, height: 20 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 20 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "left back up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "left back",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "left front up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "left front",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "right back up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "right back",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "right front up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "right front",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 203,
name: "Gamer Jacket",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 202,
name: "Cyberpunk VR",
side: "back",
dimensions: { x: 14, y: 5, width: 36, height: 20 },
},
{
itemId: 202,
name: "Cyberpunk VR Front",
side: "front",
dimensions: { x: 14, y: 5, width: 36, height: 26 },
},
{
itemId: 202,
name: "Cyberpunk VR",
side: "left",
dimensions: { x: 19, y: 6, width: 26, height: 25 },
},
{
itemId: 202,
name: "Cyberpunk VR",
side: "right",
dimensions: { x: 19, y: 6, width: 26, height: 25 },
},
{
itemId: 204,
name: "Cyberpunk Control Front",
side: "front",
dimensions: { x: 0, y: 35, width: 16, height: 13 },
},
{
itemId: 204,
name: "Cyberpunk Control",
side: "left back",
dimensions: { x: 0, y: 35, width: 16, height: 13 },
},
{
itemId: 204,
name: "Cyberpunk Control",
side: "left",
dimensions: { x: 12, y: 35, width: 16, height: 13 },
},
{
itemId: 204,
name: "Cyberpunk Control",
side: "back",
dimensions: { x: 0, y: 35, width: 16, height: 13 },
},
{
itemId: 204,
name: "Cyberpunk Control",
side: "right",
dimensions: { x: 36, y: 35, width: 16, height: 13 },
},
{
itemId: 202,
name: "Cyberpunk Ear Plug Front",
side: "front",
dimensions: { x: 40, y: 26, width: 11, height: 9 },
},
{
itemId: 202,
name: "Cyberpunk Ear Plug",
side: "left back",
dimensions: { x: 13, y: 26, width: 3, height: 4 },
},
{
itemId: 202,
name: "Cyberpunk Ear Plug",
side: "left",
dimensions: { x: 19, y: 6, width: 11, height: 9 },
},
{
itemId: 200,
name: "Steampunk",
side: "back",
dimensions: { x: 15, y: 41, width: 34, height: 14 },
},
{
itemId: 200,
name: "Steampunk Front",
side: "front",
dimensions: { x: 15, y: 41, width: 34, height: 14 },
},
{
itemId: 200,
name: "Steampunk",
side: "left",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 200,
name: "Steampunk",
side: "right",
dimensions: { x: 20, y: 41, width: 24, height: 14 },
},
{
itemId: 201,
name: "Steampunk Glove Front",
side: "front",
dimensions: { x: 1, y: 33, width: 14, height: 11 },
},
{
itemId: 201,
name: "Steampunk Glove",
side: "back left up",
dimensions: { x: 1, y: 30, width: 14, height: 11 },
},
{
itemId: 201,
name: "Steampunk Glove",
side: "back",
dimensions: { x: 1, y: 33, width: 14, height: 11 },
},
{
itemId: 201,
name: "Steampunk Glove",
side: "back right up",
dimensions: { x: 49, y: 30, width: 14, height: 11 },
},
{
itemId: 201,
name: "Steampunk Glove",
side: "back right",
dimensions: { x: 1, y: 33, width: 14, height: 11 },
},
{
itemId: 201,
name: "Steampunk Glove",
side: "left up",
dimensions: { x: 24, y: 22, width: 11, height: 15 },
},
{
itemId: 201,
name: "Steampunk Glove",
side: "left",
dimensions: { x: 18, y: 35, width: 15, height: 11 },
},
{
itemId: 201,
name: "Steampunk Glove",
side: "right up",
dimensions: { x: 29, y: 22, width: 11, height: 15 },
},
{
itemId: 201,
name: "Steampunk Glove",
side: "right",
dimensions: { x: 31, y: 35, width: 15, height: 11 },
},
];
export const sideViewDimensions5 = [
{
itemId: 199,
name: "Steampunk Glasses",
side: "front",
dimensions: { x: 15, y: 20, width: 34, height: 19 },
},
{
itemId: 199,
name: "Steampunk Glasses",
side: "back",
dimensions: { x: 15, y: 24, width: 34, height: 4 },
},
{
itemId: 199,
name: "Steampunk Glasses",
side: "left",
dimensions: { x: 16, y: 20, width: 28, height: 19 },
},
{
itemId: 199,
name: "Steampunk Glasses",
side: "right",
dimensions: { x: 20, y: 20, width: 28, height: 19 },
},
{
itemId: 162,
name: "Miami Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 162,
name: "Miami Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 162,
name: "Miami Shirt",
side: "back left up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 162,
name: "Miami Shirt",
side: "back left",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 162,
name: "Miami Shirt",
side: "back right up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 162,
name: "Miami Shirt",
side: "back right",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 162,
name: "Miami Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 20 },
},
{
itemId: 162,
name: "Miami Shirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 162,
name: "Miami Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 162,
name: "Miami Shirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 162,
name: "Miami Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 4, height: 9 },
},
{
itemId: 205,
name: "Coffee Cup Front",
side: "front",
dimensions: { x: 1, y: 29, width: 13, height: 15 },
},
{
itemId: 205,
name: "Coffee Cup",
side: "back",
dimensions: { x: 1, y: 29, width: 13, height: 15 },
},
{
itemId: 205,
name: "Coffee Cup",
side: "back left",
dimensions: { x: 1, y: 29, width: 13, height: 15 },
},
{
itemId: 205,
name: "Coffee Cup",
side: "left",
dimensions: { x: 14, y: 33, width: 13, height: 15 },
},
{
itemId: 205,
name: "Coffee Cup",
side: "right",
dimensions: { x: 37, y: 33, width: 13, height: 15 },
},
{
itemId: 206,
name: "Biker Helmet",
side: "front",
dimensions: { x: 12, y: 2, width: 40, height: 30 },
},
{
itemId: 206,
name: "Biker Helmet",
side: "back",
dimensions: { x: 12, y: 2, width: 40, height: 30 },
},
{
itemId: 206,
name: "Biker Helmet",
side: "right",
dimensions: { x: 17, y: 2, width: 29, height: 30 },
},
{
itemId: 206,
name: "Biker Helmet",
side: "left",
dimensions: { x: 18, y: 2, width: 29, height: 30 },
},
{
itemId: 207,
name: "Biker Jacket",
side: "front",
dimensions: { x: 15, y: 33, width: 34, height: 20 },
},
{
itemId: 207,
name: "Biker Jacket",
side: "right",
dimensions: { x: 20, y: 33, width: 34, height: 20 },
},
{
itemId: 207,
name: "Biker Jacket",
side: "back",
dimensions: { x: 15, y: 33, width: 24, height: 20 },
},
{
itemId: 207,
name: "Biker Jacket",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 208,
name: "Aviators",
side: "front",
dimensions: { x: 15, y: 21, width: 34, height: 11 },
},
{
itemId: 208,
name: "Aviators",
side: "back",
dimensions: { x: 15, y: 24, width: 34, height: 1 },
},
{
itemId: 208,
name: "Aviators",
side: "right",
dimensions: { x: 20, y: 21, width: 25, height: 11 },
},
{
itemId: 208,
name: "Aviators",
side: "left",
dimensions: { x: 19, y: 21, width: 25, height: 11 },
},
{
itemId: 209,
name: "Horsehoe Mustache",
side: "front",
dimensions: { x: 23, y: 32, width: 18, height: 9 },
},
{
itemId: 209,
name: "Horsehoe Mustache",
side: "right",
dimensions: { x: 41, y: 33, width: 4, height: 8 },
},
{
itemId: 209,
name: "Horsehoe Mustache",
side: "left",
dimensions: { x: 19, y: 33, width: 4, height: 8 },
},
];
export const sideViewDimensions6 = [
{
itemId: 211,
name: "Guy Fauwkes Mask",
side: "back",
dimensions: { x: 15, y: 21, width: 34, height: 2 },
},
{
itemId: 211,
name: "Guy Fauwkes Mask",
side: "left",
dimensions: { x: 14, y: 8, width: 30, height: 35 },
},
{
itemId: 211,
name: "Guy Fauwkes Mask",
side: "right",
dimensions: { x: 20, y: 8, width: 30, height: 35 },
},
{
itemId: 212,
name: "1337 Laptop",
side: "back",
dimensions: { x: 0, y: 30, width: 16, height: 14 },
},
{
itemId: 212,
name: "1339 Laptop",
side: "right",
dimensions: { x: 35, y: 30, width: 14, height: 14 },
},
{
itemId: 212,
name: "1339 Laptop",
side: "left",
dimensions: { x: 35, y: 30, width: 14, height: 14 },
},
{
itemId: 213,
name: "H4xx0r Shirt",
side: "left",
dimensions: { x: 20, y: 31, width: 24, height: 20 },
},
{
itemId: 213,
name: "H4xx0r Shirt",
side: "right",
dimensions: { x: 20, y: 31, width: 24, height: 20 },
},
{
itemId: 213,
name: "H4xx0r Shirt",
side: "back left up",
dimensions: { x: 10, y: 31, width: 5, height: 10 },
},
{
itemId: 213,
name: "H4xx0r Shirt",
side: "back left",
dimensions: { x: 10, y: 33, width: 5, height: 10 },
},
{
itemId: 213,
name: "H4xx0r Shirt",
side: "back right up",
dimensions: { x: 49, y: 31, width: 5, height: 10 },
},
{
itemId: 213,
name: "H4xx0r Shirt",
side: "back right",
dimensions: { x: 49, y: 33, width: 5, height: 10 },
},
{
itemId: 213,
name: "H4xx0r Shirt",
side: "back",
dimensions: { x: 10, y: 31, width: 34, height: 20 },
},
{
itemId: 213,
name: "H4xx0r Shirt",
side: "left up",
dimensions: { x: 25, y: 31, width: 10, height: 6 },
},
{
itemId: 213,
name: "H4xx0r Shirt",
side: "left down",
dimensions: { x: 27, y: 35, width: 6, height: 10 },
},
{
itemId: 213,
name: "H4xx0r Shirt",
side: "right up",
dimensions: { x: 29, y: 31, width: 10, height: 6 },
},
{
itemId: 213,
name: "H4xx0r Shirt",
side: "right down",
dimensions: { x: 31, y: 35, width: 6, height: 10 },
},
{
itemId: 214,
name: "Matrix Eyes",
side: "right",
dimensions: { x: 39, y: 22, width: 5, height: 8 },
},
{
itemId: 214,
name: "Matrix Eyes",
side: "left",
dimensions: { x: 20, y: 22, width: 5, height: 8 },
},
{
itemId: 215,
name: "Cyborg Eye",
side: "back",
dimensions: { x: 13, y: 23, width: 2, height: 6 },
},
{
itemId: 215,
name: "Cyborg Eye",
side: "left",
dimensions: { x: 19, y: 15, width: 20, height: 19 },
},
{
itemId: 215,
name: "Cyborg Eye",
side: "right",
dimensions: { x: 44, y: 15, width: 1, height: 15 },
},
{
itemId: 216,
name: "Rainbow Vomit",
side: "back",
dimensions: { x: 22, y: 32, width: 20, height: 23 },
},
{
itemId: 216,
name: "Rainbow Vomit",
side: "left",
dimensions: { x: 14, y: 32, width: 13, height: 23 },
},
{
itemId: 216,
name: "Rainbow Vomit",
side: "right",
dimensions: { x: 37, y: 32, width: 13, height: 23 },
},
];
export const sideViewDimensions7 = [
{
itemId: 217,
name: "Energy Gun",
side: "back",
dimensions: { x: 2, y: 33, width: 13, height: 11 },
},
{
itemId: 217,
name: "Energy Gun",
side: "back left",
dimensions: { x: 2, y: 33, width: 13, height: 11 },
},
{
itemId: 217,
name: "Energy Gun",
side: "right up",
dimensions: { x: 28, y: 23, width: 11, height: 14 },
},
{
itemId: 217,
name: "Energy Gun",
side: "right",
dimensions: { x: 31, y: 34, width: 14, height: 11 },
},
{
itemId: 217,
name: "Energy Gun",
side: "left up",
dimensions: { x: 25, y: 23, width: 11, height: 14 },
},
{
itemId: 217,
name: "Energy Gun",
side: "left",
dimensions: { x: 19, y: 34, width: 14, height: 11 },
},
{
itemId: 218,
name: "Mohawk",
side: "back",
dimensions: { x: 27, y: 0, width: 10, height: 22 },
},
{
itemId: 218,
name: "Mohawk",
side: "left",
dimensions: { x: 20, y: 0, width: 24, height: 19 },
},
{
itemId: 218,
name: "Mohawk",
side: "right",
dimensions: { x: 20, y: 0, width: 24, height: 19 },
},
{
itemId: 219,
name: "Mutton Chops",
side: "left",
dimensions: { x: 19, y: 21, width: 11, height: 17 },
},
{
itemId: 219,
name: "Mutton Chops",
side: "right",
dimensions: { x: 34, y: 21, width: 11, height: 17 },
},
{
itemId: 220,
name: "Punk Shirt",
side: "left",
dimensions: { x: 20, y: 30, width: 24, height: 20 },
},
{
itemId: 220,
name: "Punk Shirt",
side: "right",
dimensions: { x: 20, y: 30, width: 24, height: 20 },
},
{
itemId: 220,
name: "Punk Shirt",
side: "back left up",
dimensions: { x: 9, y: 32, width: 6, height: 6 },
},
{
itemId: 220,
name: "Punk Shirt",
side: "back left",
dimensions: { x: 9, y: 36, width: 6, height: 6 },
},
{
itemId: 220,
name: "Punk Shirt",
side: "back right up",
dimensions: { x: 49, y: 32, width: 6, height: 6 },
},
{
itemId: 220,
name: "Punk Shirt",
side: "back right",
dimensions: { x: 49, y: 36, width: 6, height: 6 },
},
{
itemId: 220,
name: "Punk Shirt",
side: "back",
dimensions: { x: 9, y: 32, width: 34, height: 20 },
},
{
itemId: 220,
name: "Punk Shirt",
side: "left up",
dimensions: { x: 26, y: 30, width: 6, height: 6 },
},
{
itemId: 220,
name: "Punk Shirt",
side: "left down",
dimensions: { x: 26, y: 38, width: 6, height: 6 },
},
{
itemId: 220,
name: "Punk Shirt",
side: "right up",
dimensions: { x: 32, y: 30, width: 6, height: 6 },
},
{
itemId: 220,
name: "Punk Shirt",
side: "right down",
dimensions: { x: 32, y: 38, width: 6, height: 6 },
},
{
itemId: 221,
name: "Pirate Hat",
side: "back",
dimensions: { x: 7, y: 0, width: 50, height: 20 },
},
{
itemId: 221,
name: "Pirate Hat",
side: "left",
dimensions: { x: 12, y: 0, width: 40, height: 20 },
},
{
itemId: 221,
name: "Pirate Hat",
side: "right",
dimensions: { x: 12, y: 0, width: 40, height: 20 },
},
{
itemId: 222,
name: "Pirate Coat",
side: "left",
dimensions: { x: 20, y: 31, width: 25, height: 24 },
},
{
itemId: 222,
name: "Pirate Coat",
side: "right",
dimensions: { x: 19, y: 31, width: 25, height: 24 },
},
{
itemId: 222,
name: "Pirate Coat",
side: "back left up",
dimensions: { x: 10, y: 31, width: 5, height: 10 },
},
{
itemId: 222,
name: "Pirate Coat",
side: "back left",
dimensions: { x: 10, y: 33, width: 5, height: 10 },
},
{
itemId: 222,
name: "Pirate Coat",
side: "back right up",
dimensions: { x: 49, y: 31, width: 5, height: 10 },
},
{
itemId: 222,
name: "Pirate Coat",
side: "back right",
dimensions: { x: 49, y: 33, width: 5, height: 10 },
},
{
itemId: 222,
name: "Pirate Coat",
side: "back",
dimensions: { x: 10, y: 31, width: 36, height: 24 },
},
{
itemId: 222,
name: "Pirate Coat",
side: "left up",
dimensions: { x: 25, y: 31, width: 10, height: 6 },
},
{
itemId: 222,
name: "Pirate Coat",
side: "left down",
dimensions: { x: 27, y: 35, width: 6, height: 10 },
},
{
itemId: 222,
name: "Pirate Coat",
side: "right up",
dimensions: { x: 29, y: 31, width: 10, height: 6 },
},
{
itemId: 222,
name: "Pirate Coat",
side: "right down",
dimensions: { x: 31, y: 35, width: 6, height: 10 },
},
{
itemId: 223,
name: "Hook Hand",
side: "back",
dimensions: { x: 1, y: 35, width: 9, height: 9 },
},
{
itemId: 223,
name: "Hook Hand",
side: "left up",
dimensions: { x: 24, y: 22, width: 9, height: 9 },
},
{
itemId: 223,
name: "Hook Hand",
side: "left",
dimensions: { x: 18, y: 37, width: 9, height: 9 },
},
{
itemId: 223,
name: "Hook Hand",
side: "right up",
dimensions: { x: 31, y: 22, width: 9, height: 9 },
},
{
itemId: 223,
name: "Hook Hand",
side: "right",
dimensions: { x: 37, y: 37, width: 9, height: 9 },
},
{
itemId: 224,
name: "Pirate Patch",
side: "back",
dimensions: { x: 15, y: 21, width: 34, height: 2 },
},
{
itemId: 224,
name: "Pirate Patch",
side: "left",
dimensions: { x: 19, y: 21, width: 25, height: 10 },
},
{
itemId: 224,
name: "Pirate Patch",
side: "right",
dimensions: { x: 20, y: 21, width: 25, height: 10 },
},
{
itemId: 225,
name: "Basketball",
side: "back",
dimensions: { x: 1, y: 28, width: 13, height: 13 },
},
{
itemId: 225,
name: "Basketball",
side: "right",
dimensions: { x: 33, y: 28, width: 13, height: 13 },
},
{
itemId: 225,
name: "Basketball",
side: "left",
dimensions: { x: 17, y: 28, width: 13, height: 13 },
},
{
itemId: 226,
name: "Red Headband",
side: "back",
dimensions: { x: 15, y: 14, width: 34, height: 6 },
},
{
itemId: 226,
name: "Red Headband",
side: "left",
dimensions: { x: 20, y: 14, width: 24, height: 6 },
},
{
itemId: 226,
name: "Red Headband",
side: "right",
dimensions: { x: 20, y: 14, width: 24, height: 6 },
},
{
itemId: 227,
name: "23 Jersey",
side: "back",
dimensions: { x: 15, y: 33, width: 34, height: 22 },
},
{
itemId: 227,
name: "23 Jersey",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 227,
name: "23 Jersey",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
];
export const sideViewDimensions8 = [
{
itemId: 228,
name: "10 Gallon Hat",
side: "back",
dimensions: { x: 9, y: 3, width: 46, height: 18 },
},
{
itemId: 228,
name: "10 Gallon Hat",
side: "left",
dimensions: { x: 12, y: 2, width: 40, height: 19 },
},
{
itemId: 228,
name: "10 Gallon Hat",
side: "right",
dimensions: { x: 12, y: 2, width: 40, height: 19 },
},
{
itemId: 229,
name: "Lasso",
side: "back",
dimensions: { x: 2, y: 23, width: 12, height: 26 },
},
{
itemId: 229,
name: "Lasso",
side: "right",
dimensions: { x: 28, y: 23, width: 12, height: 26 },
},
{
itemId: 229,
name: "Lasso",
side: "left",
dimensions: { x: 24, y: 23, width: 12, height: 26 },
},
{
itemId: 230,
name: "Wraangler Jeans",
side: "back",
dimensions: { x: 15, y: 41, width: 34, height: 14 },
},
{
itemId: 230,
name: "Wraangler Jeans",
side: "left",
dimensions: { x: 18, y: 40, width: 26, height: 15 },
},
{
itemId: 230,
name: "Wraangler Jeans",
side: "right",
dimensions: { x: 20, y: 40, width: 26, height: 15 },
},
{
itemId: 231,
name: "Comfy Poncho",
side: "left",
dimensions: { x: 19, y: 31, width: 26, height: 24 },
},
{
itemId: 231,
name: "Comfy Poncho",
side: "right",
dimensions: { x: 19, y: 31, width: 26, height: 24 },
},
{
itemId: 231,
name: "Comfy Poncho",
side: "back left up",
dimensions: { x: 12, y: 31, width: 3, height: 18 },
},
{
itemId: 231,
name: "Comfy Poncho",
side: "back left",
dimensions: { x: 12, y: 32, width: 3, height: 18 },
},
{
itemId: 231,
name: "Comfy Poncho",
side: "back right up",
dimensions: { x: 48, y: 31, width: 3, height: 18 },
},
{
itemId: 231,
name: "Comfy Poncho",
side: "back right",
dimensions: { x: 48, y: 32, width: 3, height: 18 },
},
{
itemId: 231,
name: "Comfy Poncho",
side: "back",
dimensions: { x: 12, y: 31, width: 35, height: 24 },
},
{
itemId: 231,
name: "Comfy Poncho",
side: "left up",
dimensions: { x: 21, y: 33, width: 17, height: 4 },
},
{
itemId: 231,
name: "Comfy Poncho",
side: "left down",
dimensions: { x: 29, y: 32, width: 4, height: 18 },
},
{
itemId: 231,
name: "Comfy Poncho",
side: "right up",
dimensions: { x: 26, y: 33, width: 17, height: 4 },
},
{
itemId: 231,
name: "Comfy Poncho",
side: "right down",
dimensions: { x: 31, y: 32, width: 4, height: 18 },
},
{
itemId: 232,
name: "Poncho Hoodie",
side: "back",
dimensions: { x: 12, y: 1, width: 40, height: 30 },
},
{
itemId: 232,
name: "Poncho Hoodie",
side: "left",
dimensions: { x: 19, y: 1, width: 26, height: 30 },
},
{
itemId: 232,
name: "Poncho Hoodie",
side: "right",
dimensions: { x: 19, y: 1, width: 26, height: 30 },
},
{
itemId: 233,
name: "Uncommon Cacti",
side: "back",
dimensions: { x: 0, y: 45, width: 13, height: 17 },
},
{
itemId: 233,
name: "Uncommon Cacti",
side: "left",
dimensions: { x: 2, y: 43, width: 15, height: 19 },
},
{
itemId: 234,
name: "Shaaman Poncho",
side: "left",
dimensions: { x: 19, y: 31, width: 26, height: 24 },
},
{
itemId: 234,
name: "Shaaman Poncho",
side: "right",
dimensions: { x: 19, y: 31, width: 26, height: 24 },
},
{
itemId: 234,
name: "Shaaman Poncho",
side: "back left up",
dimensions: { x: 12, y: 31, width: 3, height: 18 },
},
{
itemId: 234,
name: "Shaaman Poncho",
side: "back left",
dimensions: { x: 12, y: 32, width: 3, height: 18 },
},
{
itemId: 234,
name: "Shaaman Poncho",
side: "back right up",
dimensions: { x: 48, y: 31, width: 3, height: 18 },
},
{
itemId: 234,
name: "Shaaman Poncho",
side: "back right",
dimensions: { x: 48, y: 32, width: 3, height: 18 },
},
{
itemId: 234,
name: "Shaaman Poncho",
side: "back",
dimensions: { x: 12, y: 31, width: 35, height: 24 },
},
{
itemId: 234,
name: "Shaaman Poncho",
side: "left up",
dimensions: { x: 21, y: 33, width: 17, height: 4 },
},
{
itemId: 234,
name: "Shaaman Poncho",
side: "left down",
dimensions: { x: 29, y: 32, width: 4, height: 18 },
},
{
itemId: 234,
name: "Shaaman Poncho",
side: "right up",
dimensions: { x: 26, y: 33, width: 17, height: 4 },
},
{
itemId: 234,
name: "Shaaman Poncho",
side: "right down",
dimensions: { x: 31, y: 32, width: 4, height: 18 },
},
{
itemId: 235,
name: "Shaaman Hoodie",
side: "back",
dimensions: { x: 12, y: 1, width: 40, height: 30 },
},
{
itemId: 235,
name: "Shaaman Hoodie",
side: "left",
dimensions: { x: 19, y: 1, width: 26, height: 30 },
},
{
itemId: 235,
name: "Shaaman Hoodie",
side: "right",
dimensions: { x: 19, y: 1, width: 26, height: 30 },
},
{
itemId: 236,
name: "Blue Cacti",
side: "back",
dimensions: { x: 0, y: 45, width: 13, height: 17 },
},
{
itemId: 236,
name: "Blue Cacti",
side: "left",
dimensions: { x: 2, y: 43, width: 15, height: 19 },
},
{
itemId: 237,
name: "Mythical Cacti",
side: "back",
dimensions: { x: 0, y: 45, width: 15, height: 15 },
},
{
itemId: 237,
name: "Mythical Cacti",
side: "left",
dimensions: { x: 2, y: 43, width: 15, height: 19 },
},
{
itemId: 238,
name: "Godlike Cacti",
side: "back",
dimensions: { x: 1, y: 44, width: 62, height: 10 },
},
{
itemId: 238,
name: "Godlike Cacti",
side: "left",
dimensions: { x: 2, y: 39, width: 16, height: 23 },
},
{
itemId: 238,
name: "Godlike Cacti",
side: "right",
dimensions: { x: 46, y: 39, width: 16, height: 23 },
},
{
itemId: 239,
name: "Wagie Cap",
side: "back",
dimensions: { x: 15, y: 4, width: 34, height: 18 },
},
{
itemId: 239,
name: "Wagie Cap",
side: "left",
dimensions: { x: 12, y: 4, width: 32, height: 18 },
},
{
itemId: 239,
name: "Wagie Cap",
side: "right",
dimensions: { x: 20, y: 4, width: 32, height: 18 },
},
{
itemId: 240,
name: "Headphones",
side: "back",
dimensions: { x: 11, y: 2, width: 42, height: 29 },
},
{
itemId: 240,
name: "Headphones",
side: "left",
dimensions: { x: 25, y: 2, width: 14, height: 29 },
},
{
itemId: 240,
name: "Headphones",
side: "right",
dimensions: { x: 25, y: 2, width: 14, height: 29 },
},
{
itemId: 241,
name: "WGMI Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 241,
name: "WGMI Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 241,
name: "WGMI Shirt",
side: "back left up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 241,
name: "WGMI Shirt",
side: "back left",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 241,
name: "WGMI Shirt",
side: "back right up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 241,
name: "WGMI Shirt",
side: "back right",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 241,
name: "WGMI Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 20 },
},
{
itemId: 241,
name: "WGMI Shirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 241,
name: "WGMI Shirt",
side: "left down",
dimensions: { x: 29, y: 35, width: 4, height: 9 },
},
{
itemId: 241,
name: "WGMI Shirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 241,
name: "WGMI Shirt",
side: "right down",
dimensions: { x: 31, y: 35, width: 4, height: 9 },
},
{
itemId: 242,
name: "Yellow Manbun",
side: "back",
dimensions: { x: 15, y: 0, width: 34, height: 24 },
},
{
itemId: 242,
name: "Yellow Manbun",
side: "left",
dimensions: { x: 20, y: 0, width: 24, height: 24 },
},
{
itemId: 242,
name: "Yellow Manbun",
side: "right",
dimensions: { x: 20, y: 0, width: 24, height: 24 },
},
{
itemId: 243,
name: "Tinted Shades",
side: "back",
dimensions: { x: 15, y: 24, width: 34, height: 3 },
},
{
itemId: 243,
name: "Tinted Shades",
side: "left",
dimensions: { x: 19, y: 22, width: 25, height: 9 },
},
{
itemId: 243,
name: "Tinted Shades",
side: "right",
dimensions: { x: 20, y: 22, width: 25, height: 9 },
},
{
itemId: 244,
name: "V-Neck Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 244,
name: "V-Neck Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 22 },
},
{
itemId: 244,
name: "V-Neck Shirt",
side: "back left up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 244,
name: "V-Neck Shirt",
side: "back left",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 244,
name: "V-Neck Shirt",
side: "back right up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 244,
name: "V-Neck Shirt",
side: "back right",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 244,
name: "V-Neck Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 35, height: 22 },
},
{
itemId: 244,
name: "V-Neck Shirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 244,
name: "V-Neck Shirt",
side: "left down",
dimensions: { x: 29, y: 35, width: 4, height: 9 },
},
{
itemId: 244,
name: "V-Neck Shirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 244,
name: "V-Neck Shirt",
side: "right down",
dimensions: { x: 31, y: 35, width: 4, height: 9 },
},
];
export const sideViewDimensions9 = [
{
itemId: 245,
name: "Gecko Hat",
side: "back",
dimensions: { x: 15, y: 3, width: 34, height: 36 },
},
{
itemId: 245,
name: "Gecko Hat",
side: "left",
dimensions: { x: 18, y: 3, width: 29, height: 38 },
},
{
itemId: 245,
name: "Gecko Hat",
side: "right",
dimensions: { x: 17, y: 3, width: 29, height: 38 },
},
{
itemId: 246,
name: "APY Shades",
side: "back",
dimensions: { x: 15, y: 24, width: 34, height: 4 },
},
{
itemId: 246,
name: "APY Shades",
side: "left",
dimensions: { x: 19, y: 20, width: 25, height: 12 },
},
{
itemId: 246,
name: "APY Shades",
side: "right",
dimensions: { x: 20, y: 20, width: 25, height: 12 },
},
{
itemId: 247,
name: "Up Arrow",
side: "back",
dimensions: { x: 0, y: 24, width: 16, height: 26 },
},
{
itemId: 247,
name: "Up Arrow",
side: "left",
dimensions: { x: 20, y: 25, width: 15, height: 25 },
},
{
itemId: 247,
name: "Up Arrow",
side: "right",
dimensions: { x: 29, y: 25, width: 15, height: 25 },
},
{
itemId: 248,
name: "Up Only Shirt",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 248,
name: "Up Only Shirt",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 248,
name: "Up Only Shirt",
side: "back left up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 248,
name: "Up Only Shirt",
side: "back left",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 248,
name: "Up Only Shirt",
side: "back right up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 248,
name: "Up Only Shirt",
side: "back right",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 248,
name: "Up Only Shirt",
side: "back",
dimensions: { x: 12, y: 32, width: 33, height: 20 },
},
{
itemId: 248,
name: "Up Only Shirt",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 248,
name: "Up Only Shirt",
side: "left down",
dimensions: { x: 29, y: 35, width: 4, height: 9 },
},
{
itemId: 248,
name: "Up Only Shirt",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 248,
name: "Up Only Shirt",
side: "right down",
dimensions: { x: 31, y: 35, width: 4, height: 9 },
},
{
itemId: 249,
name: "Gecko Eyes",
side: "left",
dimensions: { x: 20, y: 20, width: 6, height: 12 },
},
{
itemId: 249,
name: "Gecko Eyes",
side: "right",
dimensions: { x: 38, y: 20, width: 6, height: 12 },
},
{
itemId: 250,
name: "CoinGecko Tee",
side: "left",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 250,
name: "CoinGecko Tee",
side: "right",
dimensions: { x: 20, y: 33, width: 24, height: 20 },
},
{
itemId: 250,
name: "CoinGecko Tee",
side: "back left up",
dimensions: { x: 12, y: 32, width: 3, height: 9 },
},
{
itemId: 250,
name: "CoinGecko Tee",
side: "back left",
dimensions: { x: 12, y: 33, width: 3, height: 9 },
},
{
itemId: 250,
name: "CoinGecko Tee",
side: "back right up",
dimensions: { x: 49, y: 32, width: 3, height: 9 },
},
{
itemId: 250,
name: "CoinGecko Tee",
side: "back right",
dimensions: { x: 49, y: 33, width: 3, height: 9 },
},
{
itemId: 250,
name: "CoinGecko Tee",
side: "back",
dimensions: { x: 12, y: 32, width: 34, height: 20 },
},
{
itemId: 250,
name: "CoinGecko Tee",
side: "left up",
dimensions: { x: 26, y: 33, width: 9, height: 4 },
},
{
itemId: 250,
name: "CoinGecko Tee",
side: "left down",
dimensions: { x: 29, y: 35, width: 4, height: 9 },
},
{
itemId: 250,
name: "CoinGecko Tee",
side: "right up",
dimensions: { x: 29, y: 33, width: 9, height: 4 },
},
{
itemId: 250,
name: "CoinGecko Tee",
side: "right down",
dimensions: { x: 31, y: 35, width: 4, height: 9 },
},
{
itemId: 251,
name: "Candy Jaar",
side: "back",
dimensions: { x: 1, y: 25, width: 14, height: 20 },
},
{
itemId: 251,
name: "Candy Jaar",
side: "left",
dimensions: { x: 17, y: 25, width: 14, height: 20 },
},
{
itemId: 251,
name: "Candy Jaar",
side: "right",
dimensions: { x: 33, y: 25, width: 14, height: 20 },
},
{
itemId: 252,
name: "Aastronaut Helmet",
side: "back",
dimensions: { x: 12, y: 5, width: 40, height: 29 },
},
{
itemId: 252,
name: "Aastronaut Helmet",
side: "left",
dimensions: { x: 19, y: 5, width: 26, height: 35 },
},
{
itemId: 252,
name: "Aastronaut Helmet",
side: "right",
dimensions: { x: 19, y: 5, width: 26, height: 35 },
},
{
itemId: 253,
name: "Aastronaut Suit",
side: "left",
dimensions: { x: 20, y: 28, width: 24, height: 22 },
},
{
itemId: 253,
name: "Aastronaut Suit",
side: "right",
dimensions: { x: 20, y: 28, width: 24, height: 22 },
},
{
itemId: 253,
name: "Aastronaut Suit",
side: "back left up",
dimensions: { x: 7, y: 31, width: 8, height: 10 },
},
{
itemId: 253,
name: "Aastronaut Suit",
side: "back left",
dimensions: { x: 7, y: 33, width: 8, height: 10 },
},
{
itemId: 253,
name: "Aastronaut Suit",
side: "back right up",
dimensions: { x: 49, y: 31, width: 8, height: 10 },
},
{
itemId: 253,
name: "Aastronaut Suit",
side: "back right",
dimensions: { x: 49, y: 33, width: 8, height: 10 },
},
{
itemId: 253,
name: "Aastronaut Suit",
side: "back",
dimensions: { x: 7, y: 31, width: 34, height: 22 },
},
{
itemId: 253,
name: "Aastronaut Suit",
side: "left up",
dimensions: { x: 25, y: 28, width: 10, height: 9 },
},
{
itemId: 253,
name: "Aastronaut Suit",
side: "left down",
dimensions: { x: 24, y: 35, width: 9, height: 10 },
},
{
itemId: 253,
name: "Aastronaut Suit",
side: "right up",
dimensions: { x: 29, y: 28, width: 10, height: 9 },
},
{
itemId: 253,
name: "Aastronaut Suit",
side: "right down",
dimensions: { x: 31, y: 35, width: 9, height: 10 },
},
{
itemId: 254,
name: "uGOTCHI Token",
side: "back",
dimensions: { x: 0, y: 34, width: 12, height: 12 },
},
{
itemId: 254,
name: "uGOTCHI Token",
side: "left",
dimensions: { x: 25, y: 33, width: 2, height: 12 },
},
{
itemId: 254,
name: "uGOTCHI Token",
side: "right",
dimensions: { x: 37, y: 33, width: 2, height: 12 },
},
{
itemId: 255,
name: "Space Helmet",
side: "back",
dimensions: { x: 14, y: 5, width: 36, height: 29 },
},
{
itemId: 255,
name: "Space Helmet",
side: "left",
dimensions: { x: 19, y: 5, width: 26, height: 35 },
},
{
itemId: 255,
name: "Space Helmet",
side: "right",
dimensions: { x: 19, y: 5, width: 26, height: 35 },
},
{
itemId: 256,
name: "Lil Bubble Space Suit",
side: "left",
dimensions: { x: 20, y: 28, width: 24, height: 22 },
},
{
itemId: 256,
name: "Lil Bubble Space Suit",
side: "right",
dimensions: { x: 20, y: 28, width: 24, height: 22 },
},
{
itemId: 256,
name: "Lil Bubble Space Suit",
side: "back left up",
dimensions: { x: 7, y: 31, width: 8, height: 10 },
},
{
itemId: 256,
name: "Lil Bubble Space Suit",
side: "back left",
dimensions: { x: 7, y: 33, width: 8, height: 10 },
},
{
itemId: 256,
name: "Lil Bubble Space Suit",
side: "back right up",
dimensions: { x: 49, y: 31, width: 8, height: 10 },
},
{
itemId: 256,
name: "Lil Bubble Space Suit",
side: "back right",
dimensions: { x: 49, y: 33, width: 8, height: 10 },
},
{
itemId: 256,
name: "Lil Bubble Space Suit",
side: "back",
dimensions: { x: 7, y: 31, width: 34, height: 22 },
},
{
itemId: 256,
name: "Lil Bubble Space Suit",
side: "left up",
dimensions: { x: 25, y: 28, width: 10, height: 9 },
},
{
itemId: 256,
name: "Lil Bubble Space Suit",
side: "left down",
dimensions: { x: 24, y: 35, width: 9, height: 10 },
},
{
itemId: 256,
name: "Lil Bubble Space Suit",
side: "right up",
dimensions: { x: 29, y: 28, width: 10, height: 9 },
},
{
itemId: 256,
name: "Lil Bubble Space Suit",
side: "right down",
dimensions: { x: 31, y: 35, width: 9, height: 10 },
},
{
itemId: 257,
name: "Bitcoin Guitar",
side: "back",
dimensions: { x: 0, y: 17, width: 15, height: 38 },
},
{
itemId: 257,
name: "Bitcoin Guitar",
side: "left",
dimensions: { x: 16, y: 17, width: 15, height: 38 },
},
{
itemId: 257,
name: "Bitcoin Guitar",
side: "right",
dimensions: { x: 33, y: 17, width: 15, height: 38 },
},
{
itemId: 258,
name: "Taoist Robe",
side: "left",
dimensions: { x: 20, y: 31, width: 24, height: 23 },
},
{
itemId: 258,
name: "Taoist Robe",
side: "right",
dimensions: { x: 20, y: 31, width: 24, height: 23 },
},
{
itemId: 258,
name: "Taoist Robe",
side: "back left up",
dimensions: { x: 10, y: 31, width: 5, height: 13 },
},
{
itemId: 258,
name: "Taoist Robe",
side: "back left",
dimensions: { x: 10, y: 33, width: 5, height: 13 },
},
{
itemId: 258,
name: "Taoist Robe",
side: "back right up",
dimensions: { x: 49, y: 31, width: 5, height: 13 },
},
{
itemId: 258,
name: "Taoist Robe",
side: "back right",
dimensions: { x: 49, y: 33, width: 5, height: 13 },
},
{
itemId: 258,
name: "Taoist Robe",
side: "back",
dimensions: { x: 10, y: 31, width: 34, height: 23 },
},
{
itemId: 258,
name: "Taoist Robe",
side: "left up",
dimensions: { x: 22, y: 31, width: 13, height: 6 },
},
{
itemId: 258,
name: "Taoist Robe",
side: "left down",
dimensions: { x: 27, y: 35, width: 6, height: 13 },
},
{
itemId: 258,
name: "Taoist Robe",
side: "right up",
dimensions: { x: 29, y: 31, width: 13, height: 6 },
},
{
itemId: 258,
name: "Taoist Robe",
side: "right down",
dimensions: { x: 31, y: 35, width: 6, height: 13 },
},
{
itemId: 259,
name: "Bushy Eyebrows",
side: "left",
dimensions: { x: 19, y: 18, width: 10, height: 9 },
},
{
itemId: 259,
name: "Bushy Eyebrows",
side: "right",
dimensions: { x: 35, y: 18, width: 10, height: 9 },
},
{
itemId: 260,
name: "Beard of Wisdom",
side: "left",
dimensions: { x: 19, y: 32, width: 6, height: 14 },
},
{
itemId: 260,
name: "Beard of Wisdom",
side: "right",
dimensions: { x: 39, y: 32, width: 6, height: 14 },
},
{
itemId: 261,
name: "Aantenna Bot",
side: "back",
dimensions: { x: 3, y: 33, width: 17, height: 26 },
},
{
itemId: 261,
name: "Aantenna Bot",
side: "left",
dimensions: { x: 6, y: 33, width: 19, height: 26 },
},
{
itemId: 262,
name: "Radar Eyes",
side: "left",
dimensions: { x: 20, y: 20, width: 6, height: 12 },
},
{
itemId: 262,
name: "Radar Eyes",
side: "right",
dimensions: { x: 38, y: 20, width: 6, height: 12 },
},
{
itemId: 263,
name: "Signal Headset",
side: "back",
dimensions: { x: 11, y: 6, width: 42, height: 25 },
},
{
itemId: 263,
name: "Signal Headset",
side: "left",
dimensions: { x: 26, y: 6, width: 12, height: 25 },
},
{
itemId: 263,
name: "Signal Headset",
side: "right",
dimensions: { x: 26, y: 6, width: 12, height: 25 },
},
];
/*
sideViewDimensions1 = sideViewDimensions1.map((value) => {
delete value.name;
return value;
});
sideViewDimensions2 = sideViewDimensions2.map((value) => {
delete value.name;
return value;
});
sideViewDimensions3 = sideViewDimensions3.map((value) => {
delete value.name;
return value;
});
sideViewDimensions4 = sideViewDimensions4.map((value) => {
delete value.name;
return value;
});
sideViewDimensions5 = sideViewDimensions5.map((value) => {
delete value.name;
return value;
});
sideViewDimensions6 = sideViewDimensions6.map((value) => {
delete value.name;
return value;
});
sideViewDimensions7 = sideViewDimensions7.map((value) => {
delete value.name;
return value;
});
sideViewDimensions8 = sideViewDimensions8.map((value) => {
delete value.name;
return value;
});
sideViewDimensions9 = sideViewDimensions9.map((value) => {
delete value.name;
return value;
});
*/
// console.log(sideViewDimensions) | the_stack |
import {
AnyObject,
DataObject,
PropertyDefinition,
Type,
} from '@loopback/repository';
import {HttpErrors, Model} from '@loopback/rest';
import {QueryList} from '../query-list';
import {Errors, TWO} from '../../const';
import {SearchQuery, SearchResult} from '../../models';
import {
ColumnMap,
isSearchableModel,
PredicateComparison,
SearchableModel,
PredicateValueType,
Queries,
Query,
SearchWhereFilter,
ShortHandEqualType,
} from '../../types';
import {IGNORED_COLUMN, ModelProperties} from '../..';
export abstract class SearchQueryBuilder<T extends Model> {
protected baseQueryList: Query[];
protected limitQuery: string;
protected orderQuery: string;
protected query: DataObject<SearchQuery>;
protected schema?: string;
protected idType?: string = 'uuid';
protected _placeholderIndex = 0;
protected get placeholder(): string {
this._placeholderIndex += 1;
return this.paramString(this._placeholderIndex);
}
protected set placeholder(val: string | number) {
if (typeof val === 'number') {
this._placeholderIndex = val;
}
}
constructor(query: DataObject<SearchQuery>, schema?: string) {
this.query = query;
this.schema = schema;
}
abstract search(
model: typeof Model,
columns: Array<keyof T> | ColumnMap<T>,
ignoredColumns: (keyof T)[],
): void;
abstract unionString: string;
limit() {
if (this.query.limit) {
if (this.query.limitByType) {
if (this.query.offset) {
throw new HttpErrors.BadRequest(Errors.OFFSET_WITH_TYPE);
}
this.baseQueryList = this.baseQueryList.map(q => ({
sql: `${q.sql} LIMIT ${this.query.limit}`,
params: q.params,
}));
} else {
this.limitQuery = `LIMIT ${this.query.limit} OFFSET ${
this.query.offset ?? 0
}`;
}
} else {
if (this.query.limitByType) {
throw new HttpErrors.BadRequest(Errors.TYPE_WITHOUT_LIMIT);
}
if (this.query.offset) {
throw new HttpErrors.BadRequest(Errors.OFFSET_WITHOUT_LIMIT);
}
}
}
order(columns: Array<keyof T>) {
let orderQuery: string;
if (this.query.order) {
const [column, sortOrder] = this.query.order.split(' ') as [
keyof T,
'ASC' | 'DESC',
];
if (
!columns.includes(column) ||
!(sortOrder === 'DESC' || sortOrder === 'ASC')
) {
throw new HttpErrors.BadRequest(Errors.INVALID_ORDER);
}
orderQuery = `ORDER BY ${column} ${sortOrder}`;
} else {
orderQuery = 'ORDER BY rank DESC';
}
if (this.query.limitByType) {
this.baseQueryList = this.baseQueryList.map(q => ({
sql: `${q.sql} ${orderQuery}`,
params: q.params,
}));
}
if (this.baseQueryList.length === 1 && this.query.limitByType) {
this.orderQuery = '';
} else {
this.orderQuery = orderQuery;
}
}
getColumnListFromArrayOrMap(
model: typeof Model,
columns: Array<keyof T> | ColumnMap<T>,
filter: (keyof T)[],
) {
if (Array.isArray(columns)) {
return this._getColumnListFromArray(model, columns, filter);
} else {
return this._getColumnListFromMap(model, columns, filter);
}
}
_getColumnListFromMap(
model: typeof Model,
columns: ColumnMap<T>,
filter: (keyof T)[],
) {
const columnList = Object.keys(columns)
.filter(
column =>
column !== IGNORED_COLUMN && !filter.includes(column as keyof T),
)
.map(column => (columns as AnyObject)[column])
.join(', ');
const selectors = Object.keys(columns)
.map(column => {
const columnNameInMap = (columns as AnyObject)[column];
if (columnNameInMap === IGNORED_COLUMN) {
return `null as ${column}`;
} else {
const dbName = this._getColumnName(model, columnNameInMap);
return this._formatColumnSameInDb(column as keyof T, dbName);
}
})
.join(', ');
return {
columnList,
selectors,
};
}
_getColumnListFromArray(
model: typeof Model,
columns: Array<keyof T>,
filter: (keyof T)[],
) {
const columnList = columns
.filter(column => !filter.includes(column))
.map(column => this._getColumnName(model, column))
.join(', ');
const selectors = columns
.map(column => {
const nameInDb = this._getColumnName(model, column);
return this._formatColumnSameInDb(column, nameInDb);
})
.join(', ');
return {
columnList,
selectors,
};
}
build(
models: (SearchableModel<T> | typeof Model)[],
ignoredColumns?: ModelProperties<T>[],
type?: typeof Model,
idType?: string,
) {
this.idType = idType ?? 'uuid';
if (!this.query.match) {
throw new HttpErrors.BadRequest(Errors.MISSING_MATCH);
}
if (!(models && models.length > 0)) {
throw new HttpErrors.BadRequest(Errors.NO_COLUMNS_TO_MATCH);
}
return {
query: this.queryBuild(models, ignoredColumns, type),
params: this.paramsBuild(this.query.match),
};
}
paramsBuild(param: string): AnyObject | Array<AnyObject | string> {
const params = this.baseQueryList.reduce(
(t: ShortHandEqualType[], v) => [...t, ...v.params],
[],
);
return [param, ...params];
}
paramString(index: number) {
return `:${index}`;
}
queryBuild(
models: (SearchableModel<T> | typeof Model)[],
ignoredColumns?: (keyof T)[],
type?: typeof Model,
) {
this.baseQueryList = [];
this.limitQuery = '';
this.orderQuery = '';
if (!type) {
type = SearchResult;
}
const skipped = ignoredColumns ?? [];
const defaultColumns = Object.keys(
type.definition.properties,
) as ModelProperties<T>[];
models.forEach(model => {
if (isSearchableModel(model)) {
const mapWithDefaults = defaultColumns.reduce((combined, column) => {
if (!combined[column]) {
combined[column] = column as string;
}
return combined;
}, model.columns);
this.search(model.model, mapWithDefaults, skipped);
} else {
this.search(model, defaultColumns, skipped);
}
});
this.order(defaultColumns);
this.limit();
const mainQuery = this.baseQueryList
.filter(q => q.sql)
.map(q => `(${q.sql})`)
.join(this.unionString);
return [mainQuery, this.orderQuery, this.limitQuery]
.filter(q => q?.length > 0)
.join(' ');
}
whereBuild<S extends typeof Model>(model: S, where?: SearchWhereFilter) {
const queries = new QueryList();
if (!where) {
return {sql: '', params: []};
}
const keys = Object.keys(where) as (keyof SearchWhereFilter<T>)[];
for (const key of keys) {
const stmts = this.handleKeys(model, key, where);
queries.add(stmts);
}
return queries.merge();
}
handleKeys(
model: typeof Model,
key: keyof SearchWhereFilter<T>,
where: SearchWhereFilter,
): Query | Queries | undefined {
const props = model.definition.properties;
const stmts: Queries = [];
let columnValue;
if (key === 'and' || key === 'or') {
return this.handleAndOr(where, key, model);
}
const p = props[key as string];
if (p === null || p === undefined) {
throw new HttpErrors.BadRequest(`${Errors.UNKNOWN_PROPERTY}:${key}`);
}
const expression = where[key] as
| PredicateComparison<typeof key>
| (typeof key & ShortHandEqualType);
const columnName = this._getColumnName(model, key);
if (expression === null || expression === undefined) {
stmts.push({sql: `${columnName} IS NULL`, params: []});
} else if (typeof expression === 'object') {
const mergedStmt = this.handleObjectValue(expression, p, key, model);
if (mergedStmt) {
stmts.push(mergedStmt);
} else {
return;
}
} else {
columnValue = this._toColumnValue(p, expression);
if (columnValue === null) {
stmts.push({sql: `${columnName} IS NULL`, params: []});
} else {
stmts.push({
sql: `${columnName}=${this.parseIdPlaceholder(p)}`,
params: [columnValue],
});
}
}
return stmts;
}
handleAndOr<S extends typeof Model>(
where: SearchWhereFilter,
key: never,
model: S,
): Query | undefined {
const branches = [];
let branchParams: ShortHandEqualType[] = [];
const clauses = where[key] as Array<SearchWhereFilter<T>>;
if (Array.isArray(clauses)) {
for (let i = 0, n = clauses.length; i < n; i++) {
const stmtForClause = this.whereBuild(model, clauses[i]);
if (stmtForClause.sql) {
stmtForClause.sql = `(${stmtForClause.sql})`;
branchParams = branchParams.concat(stmtForClause.params);
branches.push(stmtForClause.sql);
}
}
const joinString = ` ${(key as string).toUpperCase()} `;
if (branches.length > 0) {
return {
sql: `(${branches.join(joinString)})`,
params: branchParams,
};
} else {
return undefined;
}
} else {
// do nothing
}
}
handleObjectValue<S extends typeof Model>(
expression: PredicateComparison<ShortHandEqualType>,
p: PropertyDefinition,
key: never,
model: S,
): Query | undefined {
const operator = Object.keys(
expression,
)[0] as keyof PredicateComparison<ShortHandEqualType>;
const expressionValue = expression[
operator
] as PredicateValueType<ShortHandEqualType>;
const columnValue = this._buildColumnValueForExpression(expressionValue, p);
if (['inq', 'nin', 'between'].includes(operator)) {
if (operator === 'between' && columnValue.length !== TWO) {
throw new HttpErrors.BadRequest(Errors.EXACTLY_TWO_VALUES_FOR_BETWEEN);
} else {
if (columnValue.length === 0) {
return;
}
}
}
return this._buildExpression(key, p, operator, columnValue, model);
}
_buildColumnValueForExpression(
expressionValue: PredicateValueType<ShortHandEqualType>,
p: PropertyDefinition,
) {
const columnValue = [];
if (Array.isArray(expressionValue)) {
for (let j = 0, m = expressionValue.length; j < m; j++) {
columnValue.push(this._toColumnValue(p, expressionValue[j]));
}
} else {
columnValue.push(this._toColumnValue(p, expressionValue));
}
return columnValue;
}
parseIdPlaceholder(prop: PropertyDefinition) {
if (prop.id && this.idType === 'uuid') {
return `(${this.placeholder})::uuid`;
} else {
return this.placeholder;
}
}
_getColumnName(model: typeof Model, name: keyof T) {
if (model.definition.properties[name as string]) {
return model.definition.properties[name as string].name || name;
}
return undefined;
}
_toColumnValue(
prop: PropertyDefinition,
val: PredicateValueType<ShortHandEqualType>,
) {
if (prop.type === String && typeof val === 'string') {
return String(val);
}
if (prop.type === Number && typeof val === 'number') {
if (isNaN(val)) {
// Map NaN to NULL
return val;
}
return val;
}
if (
(prop.type === Date ||
(prop.type as Type<string>).name === 'Timestamp') &&
(val instanceof Date || typeof val === 'string')
) {
return this._toDateType(val);
}
// PostgreSQL support char(1) Y/N
if (prop.type === Boolean && typeof val === 'boolean') {
return !!val;
}
if (Array.isArray(prop.type)) {
// There is two possible cases for the type of "val" as well as two cases for dataType
return this._toArrayPropTypes(prop, val);
}
return val;
}
_toDateType(val: Date | string) {
if (!(val instanceof Date) || !val.toISOString) {
val = new Date(val);
}
const iso = val.toISOString();
// Pass in date as UTC and make sure Postgresql stores using UTC timezone
return {
sql: `${this.placeholder}::TIMESTAMP WITH TIME ZONE`,
params: [iso],
};
}
_toArrayPropTypes<R>(prop: PropertyDefinition, val: R[] | R) {
const isArrayDataType =
prop.postgresql && prop.postgresql.dataType === 'varchar[]';
if (Array.isArray(val)) {
if (isArrayDataType) {
return val;
} else {
return JSON.stringify(val);
}
} else {
if (isArrayDataType && typeof val === 'string') {
return JSON.parse(val);
} else {
return val;
}
}
}
_escape(str: string) {
let escaped = '"';
for (const c of str) {
if (c === '"') {
escaped += c + c;
} else {
escaped += c;
}
}
escaped += '"';
return escaped;
}
_buildExpression(
columnName: keyof T,
prop: PropertyDefinition,
operator: string,
value: (Query | ShortHandEqualType)[] | ShortHandEqualType | Query,
model: typeof Model,
) {
const getPlaceholder = () => this.parseIdPlaceholder(prop);
let expression = this._getColumnName(model, columnName);
let clause: Query;
switch (operator) {
case 'gt':
expression += '>';
clause = this._buildClauseFromExpress(value, '', false, getPlaceholder);
break;
case 'gte':
expression += '>=';
clause = this._buildClauseFromExpress(value, '', false, getPlaceholder);
break;
case 'lt':
expression += '<';
clause = this._buildClauseFromExpress(value, '', false, getPlaceholder);
break;
case 'lte':
expression += '<=';
clause = this._buildClauseFromExpress(value, '', false, getPlaceholder);
break;
case 'neq':
if (value === null) {
expression += ' IS NOT NULL';
} else {
expression += '!=';
}
clause = this._buildClauseFromExpress(value, '', false, getPlaceholder);
break;
case 'between':
expression += ' BETWEEN ';
clause = this._buildClauseFromExpress(
value,
' AND ',
false,
getPlaceholder,
);
break;
case 'nin':
expression += ' NOT IN ';
clause = this._buildClauseFromExpress(
value,
', ',
true,
getPlaceholder,
);
break;
case 'inq':
expression += ' IN ';
clause = this._buildClauseFromExpress(
value,
', ',
true,
getPlaceholder,
);
break;
default:
throw new HttpErrors.BadRequest(
`${Errors.INVALID_WHERE_OPERATOR}:${operator}`,
);
}
return {
sql: `${expression}${clause.sql}`,
params: clause.params,
};
}
_buildClauseFromExpress(
values: (Query | ShortHandEqualType)[] | ShortHandEqualType | Query,
separator: string,
grouping: boolean,
getPlaceholder: () => string,
) {
if (Array.isArray(values)) {
const stmts: string[] = [];
let params: ShortHandEqualType[] = [];
for (const val of values) {
if (this._isQuery(val)) {
stmts.push(val.sql);
params = [...params, ...val.params];
} else {
stmts.push(getPlaceholder());
params.push(val);
}
}
let sql = stmts.join(separator);
if (grouping) {
sql = `(${sql})`;
}
return {
sql,
params,
};
} else {
if (this._isQuery(values)) {
return values;
} else {
return {
sql: getPlaceholder(),
params: [values],
};
}
}
}
private _isQuery(query: Query | ShortHandEqualType): query is Query {
return !!(query && (query as Query).sql && (query as Query).params);
}
private _formatColumnSameInDb(modelColumn: keyof T, dbColumn: string) {
if (modelColumn !== dbColumn) {
return `${dbColumn} as ${modelColumn}`;
} else {
return modelColumn;
}
}
} | the_stack |
import { attr, observable, Observable } from "@microsoft/fast-element";
import {
keyArrowDown,
keyArrowUp,
keyEnd,
keyEnter,
keyEscape,
keyHome,
keySpace,
keyTab,
uniqueId,
} from "@microsoft/fast-web-utilities";
import { FoundationElement } from "../foundation-element";
import { isListboxOption, ListboxOption } from "../listbox-option/listbox-option";
import { ARIAGlobalStatesAndProperties } from "../patterns/aria-global";
import { applyMixins } from "../utilities/apply-mixins";
import { ListboxRole } from "./listbox.options";
/**
* A Listbox Custom HTML Element.
* Implements the {@link https://www.w3.org/TR/wai-aria-1.1/#listbox | ARIA listbox }.
*
* @public
*/
export abstract class Listbox extends FoundationElement {
/**
* The internal unfiltered list of selectable options.
*
* @internal
*/
protected _options: ListboxOption[] = [];
/**
* The first selected option.
*
* @internal
*/
public get firstSelectedOption(): ListboxOption {
return this.selectedOptions[0] ?? null;
}
/**
* The number of options.
*
* @public
*/
public get length(): number {
if (this.options) {
return this.options.length;
}
return 0;
}
/**
* The list of options.
*
* @public
*/
public get options(): ListboxOption[] {
Observable.track(this, "options");
return this._options;
}
public set options(value: ListboxOption[]) {
this._options = value;
Observable.notify(this, "options");
}
/**
* Flag for the typeahead timeout expiration.
*
* @deprecated use `Listbox.typeaheadExpired`
* @internal
*/
protected get typeAheadExpired(): boolean {
return this.typeaheadExpired;
}
protected set typeAheadExpired(value: boolean) {
this.typeaheadExpired = value;
}
/**
* The disabled state of the listbox.
*
* @public
* @remarks
* HTML Attribute: `disabled`
*/
@attr({ mode: "boolean" })
public disabled: boolean;
/**
* The role of the element.
*
* @public
* @remarks
* HTML Attribute: `role`
*/
@attr
public role: string = ListboxRole.listbox;
/**
* The index of the selected option.
*
* @public
*/
@observable
public selectedIndex: number = -1;
/**
* A collection of the selected options.
*
* @public
*/
@observable
public selectedOptions: ListboxOption[] = [];
/**
* A standard `click` event creates a `focus` event before firing, so a
* `mousedown` event is used to skip that initial focus.
*
* @internal
*/
protected shouldSkipFocus: boolean = false;
/**
* A static filter to include only selectable options.
*
* @param n - element to filter
* @public
*/
public static slottedOptionFilter = (n: HTMLElement) =>
isListboxOption(n) && !n.disabled && !n.hidden;
/**
* The default slotted elements.
*
* @internal
*/
@observable
public slottedOptions: Element[];
/**
* Typeahead timeout in milliseconds.
*
* @internal
*/
protected static readonly TYPE_AHEAD_TIMEOUT_MS = 1000;
/**
* The current typeahead buffer string.
*
* @internal
*/
@observable
protected typeaheadBuffer: string = "";
/**
* Flag for the typeahead timeout expiration.
*
* @internal
*/
protected typeaheadExpired: boolean = true;
/**
* The timeout ID for the typeahead handler.
*
* @internal
*/
protected typeaheadTimeout: number = -1;
/**
* Handle click events for listbox options.
*
* @internal
*/
public clickHandler(e: MouseEvent): boolean | void {
const captured = (e.target as HTMLElement).closest(
`option,[role=option]`
) as ListboxOption;
if (captured && !captured.disabled) {
this.selectedIndex = this.options.indexOf(captured);
return true;
}
}
/**
* Focus the first selected option and scroll it into view.
*
* @internal
*/
protected focusAndScrollOptionIntoView(): void {
if (this.contains(document.activeElement) && this.firstSelectedOption) {
this.firstSelectedOption.focus();
requestAnimationFrame(() => {
this.firstSelectedOption.scrollIntoView({ block: "nearest" });
});
}
}
/**
* Handles `focusin` actions for the component. When the component receives focus,
* the list of selected options is refreshed and the first selected option is scrolled
* into view.
*
* @internal
*/
public focusinHandler(e: FocusEvent): void {
if (!this.shouldSkipFocus && e.target === e.currentTarget) {
this.setSelectedOptions();
this.focusAndScrollOptionIntoView();
}
this.shouldSkipFocus = false;
}
/**
* Moves focus to an option whose label matches characters typed by the user.
* Consecutive keystrokes are batched into a buffer of search text used
* to match against the set of options. If `TYPE_AHEAD_TIMEOUT_MS` passes
* between consecutive keystrokes, the search restarts.
*
* @param key - the key to be evaluated
*/
public handleTypeAhead(key: string): void {
if (this.typeaheadTimeout) {
window.clearTimeout(this.typeaheadTimeout);
}
this.typeaheadTimeout = window.setTimeout(
() => (this.typeaheadExpired = true),
Listbox.TYPE_AHEAD_TIMEOUT_MS
);
if (key.length > 1) {
return;
}
this.typeaheadBuffer = `${
this.typeaheadExpired ? "" : this.typeaheadBuffer
}${key}`;
}
/**
* Handles `keydown` actions for listbox navigation and typeahead.
*
* @internal
*/
public keydownHandler(e: KeyboardEvent): boolean | void {
if (this.disabled) {
return true;
}
this.shouldSkipFocus = false;
const key = e.key;
switch (key) {
// Select the first available option
case keyHome: {
if (!e.shiftKey) {
e.preventDefault();
this.selectFirstOption();
}
break;
}
// Select the next selectable option
case keyArrowDown: {
if (!e.shiftKey) {
e.preventDefault();
this.selectNextOption();
}
break;
}
// Select the previous selectable option
case keyArrowUp: {
if (!e.shiftKey) {
e.preventDefault();
this.selectPreviousOption();
}
break;
}
// Select the last available option
case keyEnd: {
e.preventDefault();
this.selectLastOption();
break;
}
case keyTab: {
this.focusAndScrollOptionIntoView();
return true;
}
case keyEnter:
case keyEscape: {
return true;
}
case keySpace: {
if (this.typeaheadExpired) {
return true;
}
}
// Send key to Typeahead handler
default: {
if (key.length === 1) {
this.handleTypeAhead(`${key}`);
}
return true;
}
}
}
/**
* Prevents `focusin` events from firing before `click` events when the
* element is unfocused.
*
* @internal
*/
public mousedownHandler(e: MouseEvent): boolean | void {
this.shouldSkipFocus = !this.contains(document.activeElement);
return true;
}
/**
* Updates the list of selected options when the `selectedIndex` changes.
*
* @param prev - the previous selected index value
* @param next - the current selected index value
*
* @internal
*/
public selectedIndexChanged(prev: number, next: number): void {
this.setSelectedOptions();
}
/**
* Updates the selectedness of each option when the list of selected options changes.
*
* @param prev - the previous list of selected options
* @param next - the current list of selected options
*
* @internal
*/
protected selectedOptionsChanged(
prev: ListboxOption[] | undefined,
next: ListboxOption[]
): void {
if (this.$fastController.isConnected) {
this.options.forEach(o => {
o.selected = next.includes(o);
});
}
}
/**
* Moves focus to the first selectable option.
*
* @public
*/
public selectFirstOption(): void {
if (!this.disabled) {
this.selectedIndex = 0;
}
}
/**
* Moves focus to the last selectable option.
*
* @internal
*/
public selectLastOption(): void {
if (!this.disabled) {
this.selectedIndex = this.options.length - 1;
}
}
/**
* Moves focus to the next selectable option.
*
* @internal
*/
public selectNextOption(): void {
if (
!this.disabled &&
this.options &&
this.selectedIndex < this.options.length - 1
) {
this.selectedIndex += 1;
}
}
/**
* Moves focus to the previous selectable option.
*
* @internal
*/
public selectPreviousOption(): void {
if (!this.disabled && this.selectedIndex > 0) {
this.selectedIndex = this.selectedIndex - 1;
}
}
/**
* Updates the selected index to match the first selected option.
*
* @internal
*/
protected setDefaultSelectedOption() {
if (this.options && this.$fastController.isConnected) {
const selectedIndex = this.options.findIndex(
el => el.getAttribute("selected") !== null
);
if (selectedIndex !== -1) {
this.selectedIndex = selectedIndex;
return;
}
this.selectedIndex = 0;
}
}
/**
* Sets the selected option and gives it focus.
*
* @public
*/
protected setSelectedOptions() {
if (this.$fastController.isConnected && this.options) {
const selectedOption = this.options[this.selectedIndex] ?? null;
this.selectedOptions = this.options.filter(el =>
el.isSameNode(selectedOption)
);
this.ariaActiveDescendant = this.firstSelectedOption?.id ?? "";
this.focusAndScrollOptionIntoView();
}
}
/**
* Updates the list of options and resets the selected option when the slotted option content changes.
*
* @param prev - the previous list of slotted options
* @param next - the current list of slotted options
*
* @internal
*/
public slottedOptionsChanged(prev: Element[] | unknown, next: Element[]) {
if (this.$fastController.isConnected) {
this.options = next.reduce((options, item) => {
if (isListboxOption(item)) {
options.push(item);
}
return options;
}, [] as ListboxOption[]);
this.options.forEach(o => {
o.id = o.id || uniqueId("option-");
});
this.setSelectedOptions();
this.setDefaultSelectedOption();
}
}
/**
* Updates the filtered list of options when the typeahead buffer changes.
*
* @param prev - the previous typeahead buffer value
* @param next - the current typeahead buffer value
*
* @internal
*/
public typeaheadBufferChanged(prev: string, next: string): void {
if (this.$fastController.isConnected) {
const pattern = this.typeaheadBuffer.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
const re = new RegExp(`^${pattern}`, "gi");
const filteredOptions = this.options.filter((o: ListboxOption) =>
o.text.trim().match(re)
);
if (filteredOptions.length) {
const selectedIndex = this.options.indexOf(filteredOptions[0]);
if (selectedIndex > -1) {
this.selectedIndex = selectedIndex;
}
}
this.typeaheadExpired = false;
}
}
}
/**
* Includes ARIA states and properties relating to the ARIA listbox role
*
* @public
*/
export class DelegatesARIAListbox {
/**
* See {@link https://www.w3.org/WAI/PF/aria/roles#listbox} for more information
* @public
* @remarks
* HTML Attribute: aria-activedescendant
*/
@observable
public ariaActiveDescendant: string = "";
/**
* See {@link https://www.w3.org/WAI/PF/aria/roles#listbox} for more information
* @public
* @remarks
* HTML Attribute: aria-disabled
*/
@observable
public ariaDisabled: "true" | "false";
/**
* See {@link https://www.w3.org/WAI/PF/aria/roles#listbox} for more information
* @public
* @remarks
* HTML Attribute: aria-expanded
*/
@observable
public ariaExpanded: "true" | "false" | undefined;
}
/**
* Mark internal because exporting class and interface of the same name
* confuses API documenter.
* TODO: https://github.com/microsoft/fast/issues/3317
* @internal
*/
/* eslint-disable-next-line */
export interface DelegatesARIAListbox extends ARIAGlobalStatesAndProperties {}
applyMixins(DelegatesARIAListbox, ARIAGlobalStatesAndProperties);
/**
* @internal
*/
export interface Listbox extends DelegatesARIAListbox {}
applyMixins(Listbox, DelegatesARIAListbox); | the_stack |
import {
Handler,
PreSignUpTriggerEvent, PreSignUpTriggerHandler,
PostConfirmationTriggerEvent, PostConfirmationTriggerHandler,
PreAuthenticationTriggerEvent, PreAuthenticationTriggerHandler,
PostAuthenticationTriggerEvent, PostAuthenticationTriggerHandler,
CreateAuthChallengeTriggerEvent, CreateAuthChallengeTriggerHandler,
DefineAuthChallengeTriggerEvent, DefineAuthChallengeTriggerHandler,
VerifyAuthChallengeResponseTriggerEvent, VerifyAuthChallengeResponseTriggerHandler,
PreTokenGenerationTriggerEvent, PreTokenGenerationTriggerHandler,
UserMigrationTriggerEvent, UserMigrationTriggerHandler,
CustomMessageTriggerEvent, CustomMessageTriggerHandler,
CustomEmailSenderTriggerEvent, CustomEmailSenderTriggerHandler,
} from 'aws-lambda';
type CognitoTriggerEvent =
| PreSignUpTriggerEvent
| PostConfirmationTriggerEvent
| PreAuthenticationTriggerEvent
| PostAuthenticationTriggerEvent
| DefineAuthChallengeTriggerEvent
| CreateAuthChallengeTriggerEvent
| VerifyAuthChallengeResponseTriggerEvent
| PreTokenGenerationTriggerEvent
| UserMigrationTriggerEvent
| CustomMessageTriggerEvent
| CustomEmailSenderTriggerEvent;
const baseTest: Handler<CognitoTriggerEvent> = async (event: CognitoTriggerEvent, _, callback) => {
str = event.version;
str = event.region;
str = event.userPoolId;
str = event.triggerSource;
str = event.userName;
str = event.callerContext.awsSdkVersion;
str = event.callerContext.clientId;
obj = event.request;
obj = event.response;
callback(new Error());
callback(null, event);
callback(null, { response: event.response });
return event;
};
const preSignUp: PreSignUpTriggerHandler = async (event, _, callback) => {
const { request, response, triggerSource } = event;
obj = request.userAttributes;
str = request.userAttributes.email;
str = request.validationData!['k1'];
str = request.clientMetadata!['action'];
bool = response.autoConfirmUser;
bool = response.autoVerifyEmail;
bool = response.autoVerifyPhone;
triggerSource === 'PreSignUp_SignUp';
triggerSource === 'PreSignUp_ExternalProvider';
triggerSource === 'PreSignUp_AdminCreateUser';
// $ExpectError
triggerSource === 'PostConfirmation_ConfirmSignUp';
// $ExpectError
request.session![0].challengeName === 'CUSTOM_CHALLENGE';
};
const postConfirmation: PostConfirmationTriggerHandler = async (event, _, callback) => {
const { request, response, triggerSource } = event;
obj = request.userAttributes;
str = request.userAttributes.email;
str = request.clientMetadata!['action'];
objectOrUndefined = response;
triggerSource === 'PostConfirmation_ConfirmSignUp';
triggerSource === 'PostConfirmation_ConfirmForgotPassword';
// $ExpectError
triggerSource === 'PreSignUp_ExternalProvider';
// $ExpectError
request.session![0].challengeName === 'CUSTOM_CHALLENGE';
// $ExpectError
str = request.validationData!['k1'];
// $ExpectError
bool = response.autoVerifyEmail;
// $ExpectError
bool = response.autoVerifyPhone;
};
const defineAuthChallenge: DefineAuthChallengeTriggerHandler = async (event, _, callback) => {
const { request, response, triggerSource } = event;
obj = request.userAttributes;
str = request.userAttributes.email;
array = request.session;
const session = request.session[0];
session.challengeName === 'CUSTOM_CHALLENGE';
session.challengeName === 'PASSWORD_VERIFIER';
session.challengeName === 'SMS_MFA';
session.challengeName === 'DEVICE_SRP_AUTH';
session.challengeName === 'DEVICE_PASSWORD_VERIFIER';
session.challengeName === 'ADMIN_NO_SRP_AUTH';
session.challengeName === 'SRP_A';
bool = session.challengeResult;
boolOrUndefined = request.userNotFound;
str = response.challengeName;
bool = response.failAuthentication;
bool = response.issueTokens;
triggerSource === 'DefineAuthChallenge_Authentication';
// $ExpectError
nullOrUndefined = request.userAttributes;
};
const createAuthChallenge: CreateAuthChallengeTriggerHandler = async (event, _, callback) => {
const { request, response, triggerSource } = event;
obj = request.userAttributes;
str = request.userAttributes.email;
str = request.challengeName;
array = request.session;
str = request.session[0].challengeName;
bool = request.session[0].challengeResult;
strOrUndefined = request.session[0].challengeMetadata;
boolOrUndefined = request.userNotFound;
obj = response.publicChallengeParameters;
str = response.publicChallengeParameters['foo'];
obj = response.privateChallengeParameters;
str = response.privateChallengeParameters['bar'];
str = response.challengeMetadata;
triggerSource === 'CreateAuthChallenge_Authentication';
// $ExpectError
nullOrUndefined = request.userAttributes;
};
const validateAuthChallengeResponse: VerifyAuthChallengeResponseTriggerHandler = async (event, _, callback) => {
const { request, response, triggerSource } = event;
obj = request.userAttributes;
str = request.userAttributes.email;
obj = request.privateChallengeParameters;
str = request.privateChallengeParameters['foo'];
str = request.challengeAnswer;
boolOrUndefined = request.userNotFound;
bool = response.answerCorrect;
triggerSource === 'VerifyAuthChallengeResponse_Authentication';
};
const preAuthentication: PreAuthenticationTriggerHandler = async (event, _, callback) => {
const { request, response, triggerSource } = event;
obj = request.userAttributes;
str = request.userAttributes.email;
boolOrUndefined = request.userNotFound;
objectOrUndefined = response;
triggerSource === 'PreAuthentication_Authentication';
};
const postAuthentication: PostAuthenticationTriggerHandler = async (event, _, callback) => {
const { request, response, triggerSource } = event;
obj = request.userAttributes;
str = request.userAttributes.email;
bool = request.newDeviceUsed;
objectOrUndefined = response;
triggerSource === 'PostAuthentication_Authentication';
};
const preTokenGeneration: PreTokenGenerationTriggerHandler = async (event, _, callback) => {
const { request, response, triggerSource } = event;
obj = request.userAttributes;
str = request.userAttributes.email;
obj = request.groupConfiguration;
strArrayOrUndefined = request.groupConfiguration.groupsToOverride;
strArrayOrUndefined = request.groupConfiguration.iamRolesToOverride;
strOrUndefined = request.groupConfiguration.preferredRole;
obj = response.claimsOverrideDetails;
objectOrUndefined = response.claimsOverrideDetails.claimsToAddOrOverride;
strArrayOrUndefined = response.claimsOverrideDetails.claimsToSuppress;
const groupOverrideDetails = response.claimsOverrideDetails.groupOverrideDetails!;
strArrayOrUndefined = groupOverrideDetails.groupsToOverride;
strArrayOrUndefined = groupOverrideDetails.iamRolesToOverride;
strOrUndefined = groupOverrideDetails.preferredRole;
triggerSource === 'TokenGeneration_AuthenticateDevice';
triggerSource === 'TokenGeneration_Authentication';
triggerSource === 'TokenGeneration_HostedAuth';
triggerSource === 'TokenGeneration_NewPasswordChallenge';
triggerSource === 'TokenGeneration_RefreshTokens';
};
const userMigration: UserMigrationTriggerHandler = async (event, _, callback) => {
const { request, response, triggerSource } = event;
str = request.password;
objectOrUndefined = request.validationData;
str = request.validationData!.foobar;
obj = response.userAttributes;
str = response.userAttributes.email;
strOrUndefined = response.finalUserStatus;
response.finalUserStatus === 'UNCONFIRMED';
response.finalUserStatus === 'CONFIRMED';
response.finalUserStatus === 'ARCHIVED';
response.finalUserStatus === 'COMPROMISED';
response.finalUserStatus === 'UNKNOWN';
response.finalUserStatus === 'RESET_REQUIRED';
response.finalUserStatus === 'FORCE_CHANGE_PASSWORD';
boolOrUndefined = response.forceAliasCreation;
response.messageAction === 'RESEND';
response.messageAction === 'SUPPRESS';
response.desiredDeliveryMediums === ['EMAIL'];
response.desiredDeliveryMediums === ['SMS'];
response.desiredDeliveryMediums === ['SMS', 'EMAIL'];
triggerSource === 'UserMigration_Authentication';
triggerSource === 'UserMigration_ForgotPassword';
};
const customMessage: CustomMessageTriggerHandler = async (event, _, callback) => {
const { request, response, triggerSource } = event;
obj = request.userAttributes;
str = request.userAttributes.email;
str = request.codeParameter;
str = request.usernameParameter;
str = response.smsMessage;
str = response.emailMessage;
str = response.emailSubject;
triggerSource === 'CustomMessage_AdminCreateUser';
triggerSource === 'CustomMessage_Authentication';
triggerSource === 'CustomMessage_ForgotPassword';
triggerSource === 'CustomMessage_ResendCode';
triggerSource === 'CustomMessage_SignUp';
triggerSource === 'CustomMessage_UpdateUserAttribute';
triggerSource === 'CustomMessage_VerifyUserAttribute';
};
const customEmailSender: CustomEmailSenderTriggerHandler = async (event, _, callback) => {
const { request, response, triggerSource } = event;
str = request.type;
strOrNull = request.code;
obj = request.userAttributes;
objectOrUndefined = request.clientMetadata;
triggerSource === 'CustomEmailSender_AdminCreateUser';
triggerSource === 'CustomEmailSender_VerifyUserAttribute';
triggerSource === 'CustomEmailSender_UpdateUserAttribute';
triggerSource === 'CustomEmailSender_ResendCode';
triggerSource === 'CustomEmailSender_SignUp';
triggerSource === 'CustomEmailSender_AccountTakeOverNotification';
}; | the_stack |
import {
configureStore,
createAction,
createSlice,
isAnyOf,
} from '@reduxjs/toolkit'
import type { AnyAction, PayloadAction, Action } from '@reduxjs/toolkit'
import { createListenerMiddleware, TaskAbortError } from '../index'
import type { TypedAddListener } from '../index'
describe('Saga-style Effects Scenarios', () => {
interface CounterState {
value: number
}
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterState,
reducers: {
increment(state) {
state.value += 1
},
decrement(state) {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})
const { increment, decrement, incrementByAmount } = counterSlice.actions
let { reducer } = counterSlice
let listenerMiddleware = createListenerMiddleware<CounterState>()
let { middleware, startListening, stopListening } = listenerMiddleware
let store = configureStore({
reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
const testAction1 = createAction<string>('testAction1')
type TestAction1 = ReturnType<typeof testAction1>
const testAction2 = createAction<string>('testAction2')
type TestAction2 = ReturnType<typeof testAction2>
const testAction3 = createAction<string>('testAction3')
type TestAction3 = ReturnType<typeof testAction3>
type RootState = ReturnType<typeof store.getState>
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
beforeAll(() => {
const noop = () => {}
jest.spyOn(console, 'error').mockImplementation(noop)
})
beforeEach(() => {
listenerMiddleware = createListenerMiddleware<CounterState>()
middleware = listenerMiddleware.middleware
startListening = listenerMiddleware.startListening
store = configureStore({
reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
})
test('throttle', async () => {
// Ignore incoming actions for a given period of time while processing a task.
// Ref: https://redux-saga.js.org/docs/api#throttlems-pattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: (action, listenerApi) => {
listenerCalls++
// Stop listening until further notice
listenerApi.unsubscribe()
// Queue to start listening again after a delay
setTimeout(listenerApi.subscribe, 15)
workPerformed++
},
})
// Dispatch 3 actions. First triggers listener, next two ignored.
store.dispatch(increment())
store.dispatch(increment())
store.dispatch(increment())
// Wait for resubscription
await delay(25)
// Dispatch 2 more actions, first triggers, second ignored
store.dispatch(increment())
store.dispatch(increment())
// Wait for work
await delay(5)
// Both listener calls completed
expect(listenerCalls).toBe(2)
expect(workPerformed).toBe(2)
})
test('debounce / takeLatest', async () => {
// Repeated calls cancel previous ones, no work performed
// until the specified delay elapses without another call
// NOTE: This is also basically identical to `takeLatest`.
// Ref: https://redux-saga.js.org/docs/api#debouncems-pattern-saga-args
// Ref: https://redux-saga.js.org/docs/api#takelatestpattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
listenerCalls++
// Cancel any in-progress instances of this listener
listenerApi.cancelActiveListeners()
// Delay before starting actual work
await listenerApi.delay(15)
workPerformed++
},
})
// First action, listener 1 starts, nothing to cancel
store.dispatch(increment())
// Second action, listener 2 starts, cancels 1
store.dispatch(increment())
// Third action, listener 3 starts, cancels 2
store.dispatch(increment())
// 3 listeners started, third is still paused
expect(listenerCalls).toBe(3)
expect(workPerformed).toBe(0)
await delay(25)
// All 3 started
expect(listenerCalls).toBe(3)
// First two canceled, `delay()` threw JobCanceled and skipped work.
// Third actually completed.
expect(workPerformed).toBe(1)
})
test('takeEvery', async () => {
// Runs the listener on every action match
// Ref: https://redux-saga.js.org/docs/api#takeeverypattern-saga-args
// NOTE: This is already the default behavior - nothing special here!
let listenerCalls = 0
startListening({
actionCreator: increment,
effect: (action, listenerApi) => {
listenerCalls++
},
})
store.dispatch(increment())
expect(listenerCalls).toBe(1)
store.dispatch(increment())
expect(listenerCalls).toBe(2)
})
test('takeLeading', async () => {
// Starts listener on first action, ignores others until task completes
// Ref: https://redux-saga.js.org/docs/api#takeleadingpattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
listenerCalls++
// Stop listening for this action
listenerApi.unsubscribe()
// Pretend we're doing expensive work
await listenerApi.delay(15)
workPerformed++
// Re-enable the listener
listenerApi.subscribe()
},
})
// First action starts the listener, which unsubscribes
store.dispatch(increment())
// Second action is ignored
store.dispatch(increment())
// One instance in progress, but not complete
expect(listenerCalls).toBe(1)
expect(workPerformed).toBe(0)
await delay(5)
// In-progress listener not done yet
store.dispatch(increment())
// No changes in status
expect(listenerCalls).toBe(1)
expect(workPerformed).toBe(0)
await delay(20)
// Work finished, should have resubscribed
expect(workPerformed).toBe(1)
// Listener is re-subscribed, will trigger again
store.dispatch(increment())
expect(listenerCalls).toBe(2)
expect(workPerformed).toBe(1)
await delay(20)
expect(workPerformed).toBe(2)
})
test('fork + join', async () => {
// fork starts a child job, join waits for the child to complete and return a value
// Ref: https://redux-saga.js.org/docs/api#forkfn-args
// Ref: https://redux-saga.js.org/docs/api#jointask
let childResult = 0
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
const childOutput = 42
// Spawn a child job and start it immediately
const result = await listenerApi.fork(async () => {
// Artificially wait a bit inside the child
await listenerApi.delay(5)
// Complete the child by returning an Outcome-wrapped value
return childOutput
}).result
// Unwrap the child result in the listener
if (result.status === 'ok') {
childResult = result.value
}
},
})
store.dispatch(increment())
await delay(10)
expect(childResult).toBe(42)
})
test('fork + cancel', async () => {
// fork starts a child job, cancel will raise an exception if the
// child is paused in the middle of an effect
// Ref: https://redux-saga.js.org/docs/api#forkfn-args
let childResult = 0
let listenerCompleted = false
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
// Spawn a child job and start it immediately
const forkedTask = listenerApi.fork(async () => {
// Artificially wait a bit inside the child
await listenerApi.delay(15)
// Complete the child by returning an Outcome-wrapped value
childResult = 42
return 0
})
await listenerApi.delay(5)
forkedTask.cancel()
listenerCompleted = true
},
})
// Starts listener, which starts child
store.dispatch(increment())
// Wait for child to have maybe completed
await delay(20)
// Listener finished, but the child was canceled and threw an exception, so it never finished
expect(listenerCompleted).toBe(true)
expect(childResult).toBe(0)
})
test('canceled', async () => {
// canceled allows checking if the current task was canceled
// Ref: https://redux-saga.js.org/docs/api#cancelled
let canceledAndCaught = false
let canceledCheck = false
startListening({
matcher: isAnyOf(increment, decrement, incrementByAmount),
effect: async (action, listenerApi) => {
if (increment.match(action)) {
// Have this branch wait around to be canceled by the other
try {
await listenerApi.delay(10)
} catch (err) {
// Can check cancelation based on the exception and its reason
if (err instanceof TaskAbortError) {
canceledAndCaught = true
}
}
} else if (incrementByAmount.match(action)) {
// do a non-cancelation-aware wait
await delay(15)
if (listenerApi.signal.aborted) {
canceledCheck = true
}
} else if (decrement.match(action)) {
listenerApi.cancelActiveListeners()
}
},
})
// Start first branch
store.dispatch(increment())
// Cancel first listener
store.dispatch(decrement())
// Have to wait for the delay to resolve
// TODO Can we make ``Job.delay()` be a race?
await delay(15)
expect(canceledAndCaught).toBe(true)
// Start second branch
store.dispatch(incrementByAmount(42))
// Cancel second listener, although it won't know about that until later
store.dispatch(decrement())
expect(canceledCheck).toBe(false)
await delay(20)
expect(canceledCheck).toBe(true)
})
}) | the_stack |
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { MainData, Torrent, UserPreferences } from '../../utils/Interfaces';
// UI Components
import { MatSpinner } from '@angular/material/progress-spinner';
// Helpers
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { DeleteTorrentDialogComponent } from '../modals/delete-torrent-dialog/delete-torrent-dialog.component';
import { TorrentSearchServiceService } from '../services/torrent-search-service.service';
import { TorrentDataStoreService } from '../services/torrent-management/torrent-data-store.service';
import { PrettyPrintTorrentDataService } from '../services/pretty-print-torrent-data.service';
import { BulkUpdateTorrentsComponent } from './bulk-update-torrents/bulk-update-torrents.component';
import { SelectionModel } from '@angular/cdk/collections';
import { RowSelectionService } from '../services/torrent-management/row-selection.service';
import { TorrentInfoDialogComponent } from '../modals/torrent-info-dialog/torrent-info-dialog.component';
import { ThemeService } from '../services/theme.service';
import { Observable } from 'rxjs';
import { GetTorrentSearchName, IsMobileUser } from 'src/utils/Helpers';
import { MoveTorrentsDialogComponent } from '../modals/move-torrents-dialog/move-torrents-dialog.component';
import { ApplicationConfigService } from '../services/app/application-config.service';
import { TorrentHelperService } from '../services/torrent-management/torrent-helper.service';
import { SnackbarService } from '../services/notifications/snackbar.service';
import { MenuItem } from 'primeng/api';
import { getClassForStatus } from '../../utils/Helpers'
import { Constants } from 'src/constants';
import { TorrentFilter, TorrentFilterService } from '../services/torrent-filter-service.service';
@Component({
selector: 'app-torrents-table',
templateUrl: './torrents-table.component.html',
styleUrls: ['./torrents-table.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class TorrentsTableComponent implements OnInit {
public allTorrentInformation: MainData;
public allTorrentData : Torrent[];
public filteredTorrentData: Torrent[];
public isDarkTheme: Observable<boolean>;
public userPref: UserPreferences = { } as UserPreferences;
selection = new SelectionModel<Torrent>(true, []);
// For drag & drop of columns
public displayedColumns: any[];
// A reverse mapping from column name to torrent property
public displayedColumnsMapping = ApplicationConfigService.TORRENT_TABLE_COLUMNS_MAPPING
public colWidths = Constants.TORRENT_TABLE_COLUMNS_WIDTHS as any;
// Context menu items
public contextMenuItems: MenuItem[];
public contextMenuSelectedTorrent: Torrent;
public isMobileUser = IsMobileUser();
// Other
private deleteTorDialogRef: MatDialogRef<DeleteTorrentDialogComponent, any>;
private infoTorDialogRef: MatDialogRef<TorrentInfoDialogComponent, any>;
private currentMatSort = {active: "Completed On", direction: "desc"};
private torrentSearchValue = ""; // Keep track of which torrents are currently selected
private torrentFilterBy: TorrentFilter = { type: '', value: '' };
constructor(private appConfig: ApplicationConfigService, private data_store: TorrentDataStoreService,
private pp: PrettyPrintTorrentDataService, public deleteTorrentDialog: MatDialog, private infoTorDialog: MatDialog, private moveTorrentDialog: MatDialog,
private torrentSearchService: TorrentSearchServiceService, private filterService: TorrentFilterService, private torrentsSelectedService: RowSelectionService,
private snackbar: SnackbarService, private theme: ThemeService) { }
ngOnInit(): void {
// Theming
this.isDarkTheme = this.theme.getThemeSubscription();
// Subscribe to torrent searching service
this.torrentSearchService.getSearchValue().subscribe((res: string) => {
this.updateTorrentSearchValue(res);
});
// Filtering torrents
this.filterService.getFilterValue().subscribe((res: TorrentFilter) => {
// TODO: Account for different filter types
this.updateFilterValue(res);
})
// Get user preferences
this.appConfig.getUserPreferencesSubscription().subscribe(res => { this.setUserPreferences(res) });
// Retrieve all torrent data first, then update torrent data on interval
this.allTorrentData = null;
this.filteredTorrentData = null;
this.data_store.GetTorrentDataSubscription().subscribe(data => { if(data) { this.updateTorrentData(data) }})
// Which torrents are selected
this.torrentsSelectedService.getTorrentsSelected().subscribe(res => {
// If empty, clear selection
if(res.length === 0) {
this.selection.clear();
}
});
this.contextMenuItems = [
{ label: 'Pause', icon: 'pi pi-fw pi-pause', command: () => this.pauseTorrentsBulk(this.selection.selected) },
{ label: 'Resume', icon: 'pi pi-fw pi-play', command: () => this.resumeTorrentsBulk(this.selection.selected) },
{ label: 'Force Resume', icon: 'pi pi-fw pi-forward', command: () => this.forceStartTorrentsBulk(this.selection.selected) },
{ /* Divider */ },
{ label: 'Delete', icon: 'pi pi-fw pi-trash', command: () => this.openDeleteTorrentDialog(null, this.selection.selected) },
{ /* Divider */ },
{ label: 'Set location...', icon: 'pi pi-fw pi-folder', command: () => this.openMoveTorrentDialog() },
{ label: 'Force recheck', icon: 'pi pi-fw pi-refresh', command: () => this.recheckTorrents(this.selection.selected) },
{ /* Divider */ },
{ label: 'Increase Priority', icon: 'pi pi-fw pi-chevron-up', command: () => this.increasePriorityBulk(this.selection.selected) },
{ label: 'Decrease Priority', icon: 'pi pi-fw pi-chevron-down', command: () => this.decreasePriorityBulk(this.selection.selected) },
{ label: 'Max Priority', icon: 'pi pi-fw pi-angle-double-up', command: () => this.maximumPriorityBulk(this.selection.selected) },
{ label: 'Min Priority', icon: 'pi pi-fw pi-angle-double-down', command: () => this.minimumPriorityBulk(this.selection.selected) },
];
}
ngOnDestroy(): void { }
/** Whether the number of selected elements matches the total number of rows. */
isAllSelected() {
const numSelected = this.selection.selected.length;
return numSelected === this.filteredTorrentData.length;
}
/** Selects all rows if they are not all selected; otherwise clear selection. */
masterToggle() {
this.isAllSelected() ? this.selection.clear() : this.filteredTorrentData.forEach(row => this.selection.select(row));
this._updateSelectionService();
}
isTorrentPaused(tor: Torrent): boolean {
return tor.state === "pausedDL" || tor.state === "pausedUP";
}
getFileSizeString(size: number): string { return this.pp.pretty_print_file_size(size); }
getStatusString(status: string): string { return this.pp.pretty_print_status(status); }
getTorrentETAString(tor: Torrent): string { return this.pp.pretty_print_eta(tor); }
getTorrentUploadedString(tor: Torrent): string { return this.pp.pretty_print_uploaded(tor); }
getTorrentRatioString(tor: Torrent): number { return this.pp.pretty_print_ratio(tor); }
getCompletedOnString(timestamp: number): string { return this.pp.pretty_print_completed_on(timestamp); }
getTrackerString(tracker: string): string { return this.pp.pretty_print_tracker(tracker); }
getClassNameForColumns(column: string): string {
return 'table-col table-col-' + column.replace(/ /g, '-')
}
getIdForColumns(column: string): string {
return column.replace(/ /g, '-');
}
trackBy(index: number, item: Torrent) { return item.hash; }
/** Get all torrent data and update the table */
private async updateTorrentData(data): Promise<void>{
// Update state with fresh torrent data
this.allTorrentInformation = data;
this.allTorrentData = data.torrents;
this.filteredTorrentData = data.torrents;
// Re-sort data
this.handleSortChange(this.currentMatSort);
// Filter by any search criteria
this.updateTorrentsBasedOnSearchValue();
this.updateTorrentsBasedOnFilterValue();
}
private updateTorrentSearchValue(val: string): void {
val = val ?? ""; // In case null is given
this.torrentSearchValue = GetTorrentSearchName(val);
// User is searching for something
this.updateTorrentsBasedOnSearchValue()
}
private updateFilterValue(val: TorrentFilter) {
this.torrentFilterBy = val;
this.updateTorrentsBasedOnFilterValue();
}
/** Callback for when user is searching for a torrent. Filter all torrents displayed that match torrent criteria
*
* NOTE: If search value in state is empty, no filtering is done
*/
updateTorrentsBasedOnSearchValue(): void {
// If a search value is given, then do the work
if(this.allTorrentData && this.torrentSearchValue) {
this.filteredTorrentData = this.allTorrentData
.filter((tor: Torrent) => {
return GetTorrentSearchName(tor.name).includes(this.torrentSearchValue);
});
}
else if(this.torrentSearchValue === "") { // If searching for value is empty, restore filteredTorrentData
this.filteredTorrentData = this.allTorrentData
}
}
updateTorrentsBasedOnFilterValue() {
// If a filter value is given, then do the work
if(this.allTorrentData && this.torrentFilterBy) {
// Sometimes filtered data is empty while not searching, likely a timing issue
// Super hacky...
this.filteredTorrentData = (this.filteredTorrentData.length === 0 && this.torrentSearchValue === '' ? this.allTorrentData : this.filteredTorrentData)
.filter((tor: Torrent) => {
// Special case for when we consider all torrents
if(this.torrentFilterBy.value === 'All') return true;
if(this.torrentFilterBy.type === 'filter_status')
return Constants.TORRENT_STATE_MAPPING[this.torrentFilterBy.value]?.includes(tor.state);
if(this.torrentFilterBy.type === 'filter_tracker')
return this.allTorrentInformation.trackers[this.torrentFilterBy.value].includes(tor.hash)
});
}
}
handleSortChange(event: any) {
if(!this.filteredTorrentData) { return; }
this.currentMatSort = event;
TorrentHelperService.sortByField(event.active, event.direction, this.filteredTorrentData);
}
/** Pause given array of torrents
* @param tor The torrents in question.
*/
pauseTorrentsBulk(tor: Torrent[]) {
this.data_store.PauseTorrents(tor).subscribe(res => {
this.snackbar.enqueueSnackBar(tor.length === 1 ? `Paused "${tor[0].name}".` : `Paused ${tor.length} torrent(s)`)
});
}
/** Resume given array of torrents
* @param tor The torrents in question
*/
resumeTorrentsBulk(tor: Torrent[]) {
this.data_store.ResumeTorrents(tor).subscribe(res => {
this.snackbar.enqueueSnackBar(tor.length === 1 ? `Resumed "${tor[0].name}".` : `Resumed ${tor.length} torrent(s)`)
});
}
forceStartTorrentsBulk(tor: Torrent[]) {
this.data_store.ForceStartTorrents(tor).subscribe(res => {
this.snackbar.enqueueSnackBar(tor.length === 1 ? `Force started "${tor[0].name}".` : `Force started ${tor.length} torrent(s)`)
});
}
increasePriorityBulk(tor: Torrent[]) {
this.data_store.IncreaseTorrentPriority(tor).subscribe(res => {
this.snackbar.enqueueSnackBar(tor.length === 1 ? `Increased priority for "${tor[0].name}".` : `Increased priority for ${tor.length} torrent(s)`)
});
}
decreasePriorityBulk(tor: Torrent[]) {
this.data_store.DecreaseTorrentPriority(tor).subscribe(res => {
this.snackbar.enqueueSnackBar(tor.length === 1 ? `Decreased priority for "${tor[0].name}".` : `Decreased priority for ${tor.length} torrent(s)`)
})
}
maximumPriorityBulk(tor: Torrent[]) {
this.data_store.AssignTopPriority(tor).subscribe(res => {
this.snackbar.enqueueSnackBar(tor.length === 1 ? `Maximum priority for "${tor[0].name}".` : `Maximum priority for ${tor.length} torrent(s)`)
});
}
minimumPriorityBulk(tor: Torrent[]) {
this.data_store.AssignLowestPriority(tor).subscribe(res => {
this.snackbar.enqueueSnackBar(tor.length === 1 ? `Minimum priority for "${tor[0].name}".` : `Minimum priority for ${tor.length} torrent(s)`)
});
}
recheckTorrents(tor: Torrent[]) {
this.data_store.RecheckTorrents(tor).subscribe(res => {
this.snackbar.enqueueSnackBar(tor.length === 1 ? `Rechecked ${tor[0].name}.` : `Rechecked ${tor.length} torrent(s).`)
});
}
/** Callback for when a torrent is selected in the table. Update row selection service with new data
* @param event The event thrown.
*/
handleTorrentSelected(tor: Torrent): void {
this.selection.toggle(tor);
this._updateSelectionService();
}
/** Callback for when columns are re-ordered in the torrent table. */
handleColumnReorder(event: any) {
this.appConfig.setTorrentTableColumns(event.columns, true);
}
/** Callback for when table changes col width */
handleColumnResize(event: any) {
let colName = event.element.id.replace(/-/g, ' ');
this.appConfig.setColumnWidth(colName, event.delta);
// Immediately update preferences in-memory
this.colWidths = this.appConfig.getWebUISettings().torrent_table.column_widths;
this.updateTorrentData(this.allTorrentInformation);
}
/** Determine whether a torrent is selected or not */
isSelected(tor: Torrent): boolean {
return this.selection.isSelected(tor);
}
_updateSelectionService() {
this.torrentsSelectedService.updateTorrentsSelected(this.selection.selected.map(elem => elem.hash));
}
/** Open the modal for deleting a new torrent */
openDeleteTorrentDialog(event: any, tors: Torrent[]): void {
if(event) { event.stopPropagation() };
let opts: any = { disableClose: true, data: {torrent: tors}, panelClass: "generic-dialog" };
if(this.isMobileUser) {
opts = {
...opts,
maxWidth: '100vw',
maxHeight: '100vh',
height: '100%',
width: '100%'
}
}
this.deleteTorDialogRef = this.deleteTorrentDialog.open(DeleteTorrentDialogComponent, opts);
this.deleteTorDialogRef.afterClosed().subscribe((result: any) => {
if (result.attemptedDelete) { this.torrentDeleteFinishCallback() }
});
}
/** Open modal for viewing details torrent information */
openInfoTorrentDialog(event: any, tor: Torrent): void {
if(event) { event.stopPropagation(); }
let opts: any = {data: {torrent: tor}, autoFocus: false, panelClass: "generic-dialog"};
if(this.isMobileUser) {
opts = {
...opts,
maxWidth: '100vw',
maxHeight: '100vh',
height: '100%',
width: '100%'
}
}
this.infoTorDialogRef = this.infoTorDialog.open(TorrentInfoDialogComponent, opts)
this.infoTorDialogRef.afterClosed().subscribe((result: any) => { })
}
/** Open the modal for adding a new torrent */
openMoveTorrentDialog(): void {
const addTorDialogRef = this.moveTorrentDialog.open(MoveTorrentsDialogComponent, {disableClose: true, panelClass: "generic-dialog"});
addTorDialogRef.afterClosed().subscribe((result: any) => { });
}
public handleBulkEditChange(result?: string): void {
const _close = () => {
this._updateSelectionService();
}
const actions = {
'cancel': () => _close(),
'delete': () => this.openDeleteTorrentDialog(null, this.selection.selected),
'pause': () => this.pauseTorrentsBulk(this.selection.selected),
'play': () => this.resumeTorrentsBulk(this.selection.selected),
'forceStart': () => this.forceStartTorrentsBulk(this.selection.selected),
'increasePrio': () => this.increasePriorityBulk(this.selection.selected),
'decreasePrio': () => this.decreasePriorityBulk(this.selection.selected),
'maxPrio': () => this.maximumPriorityBulk(this.selection.selected),
'minPrio': () => this.minimumPriorityBulk(this.selection.selected),
'moveTorrent': () => this.openMoveTorrentDialog()
}
if(result && actions[result]) {
actions[result]();
}
else {
this.snackbar.enqueueSnackBar(`Unable to perform the bulk action ${result}!`, { type: 'error' });
}
_close();
}
/** After torrent delete action is completed */
torrentDeleteFinishCallback(): void {
this.selection.clear();
this._updateSelectionService();
}
private setUserPreferences(pref: UserPreferences) {
this.userPref = pref;
let torrent_table_pref = pref.web_ui_options?.torrent_table
let table_sort_opt = torrent_table_pref?.default_sort_order;
this.currentMatSort = table_sort_opt ? {
active: table_sort_opt.column_name.replace(/\s/, '_'),
direction: table_sort_opt.order
} : this.currentMatSort
// Column order
this.displayedColumns = pref.web_ui_options?.torrent_table?.columns_to_show;
// Want to override defaults
let oldColWidths = this.colWidths;
let newColWidths = pref.web_ui_options?.torrent_table?.column_widths
this.colWidths = { ...oldColWidths, ...newColWidths };
// Re-sort data
this.handleSortChange(this.currentMatSort);
}
colNameForMapping(col) {
return this.displayedColumnsMapping[col].name
}
public getClassForStatus(t: Torrent): string { return getClassForStatus(t); }
public isTorrentsEmpty() {
return this.filteredTorrentData?.length === 0;
}
/** Determine if table is loading data or not */
isLoading(): boolean {
return this.allTorrentData == null;
}
} | the_stack |
import { Gantt } from '../base/gantt';
import { KeyboardEventArgs, isNullOrUndefined, getValue } from '@syncfusion/ej2-base';
import { IKeyPressedEventArgs, IGanttData, ColumnModel, ITaskData } from '..';
import { TextBox } from '@syncfusion/ej2-inputs';
import { ISelectedCell, IIndex } from '@syncfusion/ej2-grids';
import { ContextMenu } from '@syncfusion/ej2-navigations/src/context-menu';
interface EJ2Instance extends HTMLElement {
// eslint-disable-next-line
ej2_instances: Object[];
}
/**
* Focus module is used to handle certain action on focus elements in keyboard navigations.
*/
export class FocusModule {
private parent: Gantt;
private activeElement: HTMLElement;
private previousActiveElement: HTMLElement;
constructor(parent: Gantt) {
this.parent = parent;
this.activeElement = null;
this.previousActiveElement = null;
}
public getActiveElement(isPreviousActiveElement?: boolean): HTMLElement {
return isPreviousActiveElement ? this.previousActiveElement : this.activeElement;
}
public setActiveElement(element: HTMLElement): void {
this.previousActiveElement = this.activeElement;
this.activeElement = element;
}
/**
* To perform key interaction in Gantt
*
* @param {KeyboardEventArgs} e .
* @returns {void} .
* @private
*/
public onKeyPress(e: KeyboardEventArgs): void | boolean {
const ganttObj: Gantt = this.parent;
const expandedRecords: IGanttData[] = ganttObj.getExpandedRecords(ganttObj.currentViewData);
const targetElement: Element = this.parent.focusModule.getActiveElement();
if (e.action === 'home' || e.action === 'end' || e.action === 'downArrow' || e.action === 'upArrow' || e.action === 'delete' ||
e.action === 'rightArrow' || e.action === 'leftArrow' || e.action === 'focusTask' || e.action === 'focusSearch' ||
e.action === 'expandAll' || e.action === 'collapseAll') {
if (!isNullOrUndefined(ganttObj.editModule) && !isNullOrUndefined(ganttObj.editModule.cellEditModule) &&
ganttObj.editModule.cellEditModule.isCellEdit === true) {
return;
}
}
if (ganttObj.isAdaptive) {
if (e.action === 'addRowDialog' || e.action === 'editRowDialog' || e.action === 'delete'
|| e.action === 'addRow') {
if (ganttObj.selectionModule && ganttObj.selectionSettings.type === 'Multiple') {
ganttObj.selectionModule.hidePopUp();
(<HTMLElement>document.getElementsByClassName('e-gridpopup')[0]).style.display = 'none';
}
}
}
switch (e.action) {
case 'home':
if (ganttObj.selectionModule && ganttObj.selectionSettings.mode !== 'Cell') {
if (ganttObj.selectedRowIndex === 0) {
return;
}
ganttObj.selectionModule.selectRow(0, false, true);
}
break;
case 'end':
if (ganttObj.selectionModule && ganttObj.selectionSettings.mode !== 'Cell') {
const currentSelectingRecord: IGanttData = expandedRecords[expandedRecords.length - 1];
if (ganttObj.selectedRowIndex === ganttObj.flatData.indexOf(currentSelectingRecord)) {
return;
}
ganttObj.selectionModule.selectRow(ganttObj.flatData.indexOf(currentSelectingRecord), false, true);
}
break;
case 'downArrow':
case 'upArrow':
{
const searchElement: HTMLInputElement = ganttObj.element.querySelector('#' + ganttObj.element.id + '_searchbar');
if (searchElement && searchElement.parentElement.classList.contains('e-input-focus')) {
ganttObj.selectionModule.clearSelection();
}
if (!ganttObj.element.classList.contains('e-scroll-disabled')) {
this.upDownKeyNavigate(e);
if (!isNullOrUndefined(targetElement) && !isNullOrUndefined(targetElement.closest('.e-chart-row'))) {
ganttObj.ganttChartModule.manageFocus(this.getActiveElement(), 'remove', true);
}
}
break;
}
case 'expandAll':
ganttObj.ganttChartModule.expandCollapseAll('expand');
break;
case 'collapseAll':
ganttObj.ganttChartModule.expandCollapseAll('collapse');
break;
case 'expandRow':
case 'collapseRow':
this.expandCollapseKey(e);
break;
case 'saveRequest':
if (!isNullOrUndefined(ganttObj.editModule) && !isNullOrUndefined(ganttObj.editModule.cellEditModule) &&
ganttObj.editModule.cellEditModule.isCellEdit) {
const col: ColumnModel = ganttObj.editModule.cellEditModule.editedColumn;
if (col.field === ganttObj.columnMapping.duration && !isNullOrUndefined(col.edit) &&
!isNullOrUndefined(col.edit.read)) {
const textBox: TextBox = <TextBox>(<EJ2Instance>e.target).ej2_instances[0];
const textValue: string = (e.target as HTMLInputElement).value;
const ganttProp: ITaskData = ganttObj.currentViewData[ganttObj.selectedRowIndex].ganttProperties;
let tempValue: string | Date | number;
if (col.field === ganttObj.columnMapping.duration) {
tempValue = !isNullOrUndefined(col.edit) && !isNullOrUndefined(col.edit.read) ? (col.edit.read as Function)() :
// eslint-disable-next-line
!isNullOrUndefined(col.valueAccessor) ? (col.valueAccessor as Function)(ganttObj.columnMapping.duration, ganttObj.editedRecords, col) :
ganttObj.dataOperation.getDurationString(ganttProp.duration, ganttProp.durationUnit);
if (textValue !== tempValue.toString()) {
textBox.value = textValue;
textBox.dataBind();
}
}
}
if (ganttObj.editModule.dialogModule.dialogObj && getValue('dialogOpen', ganttObj.editModule.dialogModule.dialogObj)) {
return;
}
ganttObj.editModule.cellEditModule.isCellEdit = false;
ganttObj.treeGrid.grid.saveCell();
const focussedElement: HTMLElement = <HTMLElement>ganttObj.element.querySelector('.e-treegrid');
focussedElement.focus();
}
if (!isNullOrUndefined(this.parent.onTaskbarClick) && !isNullOrUndefined(targetElement)
&& !isNullOrUndefined(targetElement.closest('.e-chart-row'))) {
const target: EventTarget = e.target;
const taskbarElement: Element = targetElement.querySelector('.e-gantt-parent-taskbar,' +
'.e-gantt-child-taskbar,.e-gantt-milestone');
if (taskbarElement) {
this.parent.ganttChartModule.onTaskbarClick(e, target, taskbarElement);
}
}
break;
case 'cancelRequest':
if (!isNullOrUndefined(ganttObj.editModule) && !isNullOrUndefined(ganttObj.editModule.cellEditModule)) {
ganttObj.editModule.cellEditModule.isCellEdit = false;
if (!isNullOrUndefined(ganttObj.toolbarModule)) {
ganttObj.toolbarModule.refreshToolbarItems();
}
}
break;
case 'addRow':
{
if (isNullOrUndefined(document.getElementById(this.parent.element.id + '_dialog'))) {
e.preventDefault();
const focussedElement: HTMLElement = <HTMLElement>ganttObj.element.querySelector('.e-gantt-chart');
focussedElement.focus();
ganttObj.addRecord();
}
break;
}
case 'addRowDialog':
e.preventDefault();
if (ganttObj.editModule && ganttObj.editModule.dialogModule && ganttObj.editSettings.allowAdding) {
if (ganttObj.editModule.dialogModule.dialogObj && getValue('dialogOpen', ganttObj.editModule.dialogModule.dialogObj)) {
return;
}
ganttObj.editModule.dialogModule.openAddDialog();
}
break;
case 'editRowDialog':
{
e.preventDefault();
const focussedTreeElement: HTMLElement = <HTMLElement>ganttObj.element.querySelector('.e-treegrid');
focussedTreeElement.focus();
if (ganttObj.editModule && ganttObj.editModule.dialogModule && ganttObj.editSettings.allowEditing) {
if (ganttObj.editModule.dialogModule.dialogObj && getValue('dialogOpen', ganttObj.editModule.dialogModule.dialogObj)) {
return;
}
ganttObj.editModule.dialogModule.openToolbarEditDialog();
}
break;
}
case 'delete':
if (ganttObj.selectionModule && ganttObj.editModule && (!ganttObj.editModule.dialogModule.dialogObj ||
(ganttObj.editModule.dialogModule.dialogObj &&
!ganttObj.editModule.dialogModule.dialogObj.visible)) && (!ganttObj.editSettings.allowTaskbarEditing
|| (ganttObj.editSettings.allowTaskbarEditing && !ganttObj.editModule.taskbarEditModule.touchEdit))) {
if ((ganttObj.selectionSettings.mode !== 'Cell' && ganttObj.selectionModule.selectedRowIndexes.length)
|| (ganttObj.selectionSettings.mode === 'Cell' && ganttObj.selectionModule.getSelectedRowCellIndexes().length)) {
ganttObj.editModule.startDeleteAction();
}
}
break;
case 'focusTask':
{
e.preventDefault();
let selectedId: string;
if (ganttObj.selectionModule) {
const currentViewData: IGanttData[] = ganttObj.currentViewData;
if (ganttObj.selectionSettings.mode !== 'Cell' &&
!isNullOrUndefined(currentViewData[ganttObj.selectedRowIndex])) {
selectedId = ganttObj.currentViewData[ganttObj.selectedRowIndex].ganttProperties.rowUniqueID;
} else if (ganttObj.selectionSettings.mode === 'Cell' &&
ganttObj.selectionModule.getSelectedRowCellIndexes().length > 0) {
const selectCellIndex: ISelectedCell[] = ganttObj.selectionModule.getSelectedRowCellIndexes();
selectedId = currentViewData[selectCellIndex[selectCellIndex.length - 1].rowIndex].ganttProperties.rowUniqueID;
}
}
if (selectedId) {
ganttObj.scrollToTask(selectedId.toString());
}
break;
}
case 'focusSearch':
{
if (<HTMLInputElement>ganttObj.element.querySelector('#' + ganttObj.element.id + '_searchbar')) {
const searchElement: HTMLInputElement =
<HTMLInputElement>ganttObj.element.querySelector('#' + ganttObj.element.id + '_searchbar');
searchElement.setAttribute('tabIndex', '-1');
searchElement.focus();
}
break;
}
case 'tab':
case 'shiftTab':
if (!ganttObj.element.classList.contains('e-scroll-disabled')) {
ganttObj.ganttChartModule.onTabAction(e);
}
break;
case 'contextMenu':
{
const contextMenu: ContextMenu = <ContextMenu>(<EJ2Instance>document.getElementById(this.parent.element.id +
'_contextmenu')).ej2_instances[0];
const containerPosition: { top: number, left: number, width?: number, height?: number } =
this.parent.getOffsetRect(e.target as HTMLElement);
const top: number = containerPosition.top + (containerPosition.height / 2);
const left: number = containerPosition.left + (containerPosition.width / 2);
this.setActiveElement(e.target as HTMLElement);
contextMenu.open(top, left);
e.preventDefault();
break;
}
default:
{
const eventArgs: IKeyPressedEventArgs = {
requestType: 'keyPressed',
action: e.action,
keyEvent: e
};
ganttObj.trigger('actionComplete', eventArgs);
break;
}
}
}
private upDownKeyNavigate(e: KeyboardEventArgs): void {
e.preventDefault();
const ganttObj: Gantt = this.parent;
const expandedRecords: IGanttData[] = ganttObj.getExpandedRecords(ganttObj.currentViewData);
if (ganttObj.selectionModule) {
if (ganttObj.selectionSettings.mode !== 'Cell' && ganttObj.selectedRowIndex !== -1) {
const selectedItem: IGanttData = ganttObj.currentViewData[ganttObj.selectedRowIndex];
const focusedRowIndex: number = this.parent.ganttChartModule.focusedRowIndex;
const selectingRowIndex: number = focusedRowIndex > -1 ? focusedRowIndex : expandedRecords.indexOf(selectedItem);
const currentSelectingRecord: IGanttData = e.action === 'downArrow' ? expandedRecords[selectingRowIndex + 1] :
expandedRecords[selectingRowIndex - 1];
ganttObj.selectionModule.selectRow(ganttObj.currentViewData.indexOf(currentSelectingRecord), false, true);
} else if (ganttObj.selectionSettings.mode === 'Cell' && ganttObj.selectionModule.getSelectedRowCellIndexes().length > 0) {
const selectCellIndex: ISelectedCell[] = ganttObj.selectionModule.getSelectedRowCellIndexes();
const selectedCellItem: ISelectedCell = selectCellIndex[selectCellIndex.length - 1];
const currentCellIndex: number = selectedCellItem.cellIndexes[selectedCellItem.cellIndexes.length - 1];
const selectedItem: IGanttData = ganttObj.currentViewData[selectedCellItem.rowIndex];
const selectingRowIndex: number = expandedRecords.indexOf(selectedItem);
const currentSelectingRecord: IGanttData = e.action === 'downArrow' ? expandedRecords[selectingRowIndex + 1] :
expandedRecords[selectingRowIndex - 1];
const cellInfo: IIndex = {
rowIndex: ganttObj.currentViewData.indexOf(currentSelectingRecord),
cellIndex: currentCellIndex
};
ganttObj.selectionModule.selectCell(cellInfo);
}
this.parent.ganttChartModule.focusedRowIndex = this.parent.selectedRowIndex;
}
}
private expandCollapseKey(e: KeyboardEventArgs): void {
const ganttObj: Gantt = this.parent;
if (ganttObj.selectionModule && ganttObj.selectedRowIndex !== -1) {
let selectedRowIndex: number;
if (ganttObj.selectionSettings.mode !== 'Cell') {
selectedRowIndex = ganttObj.selectedRowIndex;
} else if (ganttObj.selectionSettings.mode === 'Cell' && ganttObj.selectionModule.getSelectedRowCellIndexes().length > 0) {
const selectCellIndex: ISelectedCell[] = ganttObj.selectionModule.getSelectedRowCellIndexes();
selectedRowIndex = selectCellIndex[selectCellIndex.length - 1].rowIndex;
}
if (e.action === 'expandRow') {
ganttObj.expandByIndex(selectedRowIndex);
} else {
ganttObj.collapseByIndex(selectedRowIndex);
}
}
}
} | the_stack |
'use strict';
import * as nls from 'vscode-nls';
import * as vscode from 'vscode';
import { join, isAbsolute, dirname, relative } from 'path';
import * as fs from 'fs';
import { writeToConsole, mkdirP, Logger } from './utilities';
import { detectDebugType } from './protocolDetection';
import { resolveProcessId } from './processPicker';
import { Cluster } from './cluster';
const DEBUG_SETTINGS = 'debug.node';
const SHOW_USE_WSL_IS_DEPRECATED_WARNING_SETTING = 'showUseWslIsDeprecatedWarning';
const DEFAULT_JS_PATTERNS: ReadonlyArray<string> = ['*.js', '*.es6', '*.jsx', '*.mjs'];
const localize = nls.loadMessageBundle();
//---- NodeConfigurationProvider
export class NodeConfigurationProvider implements vscode.DebugConfigurationProvider {
private _logger: Logger;
constructor(private _extensionContext: vscode.ExtensionContext) {
this._logger = new Logger();
}
/**
* Try to add all missing attributes to the debug configuration being launched.
*/
resolveDebugConfiguration(folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration, token?: vscode.CancellationToken): vscode.ProviderResult<vscode.DebugConfiguration> {
return this.resolveConfigAsync(folder, config).catch(err => {
return vscode.window.showErrorMessage(err.message, { modal: true }).then(_ => undefined); // abort launch
});
}
/**
* Try to add all missing attributes to the debug configuration being launched.
*/
private async resolveConfigAsync(folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration, token?: vscode.CancellationToken): Promise<vscode.DebugConfiguration | undefined> {
// if launch.json is missing or empty
if (!config.type && !config.request && !config.name) {
config = createLaunchConfigFromContext(folder, true, config);
if (!config.program) {
throw new Error(localize('program.not.found.message', "Cannot find a program to debug"));
}
}
// make sure that config has a 'cwd' attribute set
if (!config.cwd) {
if (folder) {
config.cwd = folder.uri.fsPath;
}
// no folder -> config is a user or workspace launch config
if (!config.cwd && vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) {
config.cwd = vscode.workspace.workspaceFolders[0].uri.fsPath;
}
// no folder case
if (!config.cwd && config.program === '${file}') {
config.cwd = '${fileDirname}';
}
// program is some absolute path
if (!config.cwd && config.program && isAbsolute(config.program)) {
// derive 'cwd' from 'program'
config.cwd = dirname(config.program);
}
// last resort
if (!config.cwd && folder) {
config.cwd = '${workspaceFolder}';
}
}
// if a 'remoteRoot' is specified without a corresponding 'localRoot', set 'localRoot' to the workspace folder.
// see https://github.com/Microsoft/vscode/issues/63118
if (config.remoteRoot && !config.localRoot) {
config.localRoot = '${workspaceFolder}';
}
// warn about deprecated 'useWSL' attribute.
if (typeof config.useWSL !== 'undefined') {
this.warnAboutUseWSL();
}
// remove 'useWSL' on all platforms but Windows
if (process.platform !== 'win32' && config.useWSL) {
this._logger.debug('useWSL attribute ignored on non-Windows OS.');
delete config.useWSL;
}
// "nvm" support
if (config.request === 'launch' && typeof config.runtimeVersion === 'string' && config.runtimeVersion !== 'default') {
await this.nvmSupport(config);
}
// "auto attach child process" (aka Cluster) support
if (config.autoAttachChildProcesses) {
Cluster.prepareAutoAttachChildProcesses(folder, config);
// if no console is set, use the integrated terminal so that output of all child processes goes to one terminal. See https://github.com/Microsoft/vscode/issues/62420
if (!config.console) {
config.console = 'integratedTerminal';
}
}
// when using "integratedTerminal" ensure that debug console doesn't get activated; see https://github.com/Microsoft/vscode/issues/43164
if (config.console === 'integratedTerminal' && !config.internalConsoleOptions) {
config.internalConsoleOptions = 'neverOpen';
}
// fixup log parameters
if (config.trace && !config.logFilePath) {
const fileName = config.type === 'legacy-node' ? 'debugadapter-legacy.txt' : 'debugadapter.txt';
if (this._extensionContext.logPath) {
try {
await mkdirP(this._extensionContext.logPath);
} catch (e) {
// Already exists
}
config.logFilePath = join(this._extensionContext.logPath, fileName);
}
}
// tell the extension what file patterns can be debugged
config.__debuggablePatterns = this.getJavaScriptPatterns();
// everything ok: let VS Code start the debug session
return config;
}
/**
* Try to add all missing attributes to the debug configuration being launched.
*/
resolveDebugConfigurationWithSubstitutedVariables(folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration, token?: vscode.CancellationToken): vscode.ProviderResult<vscode.DebugConfiguration> {
return this.resolveConfigWithSubstitutedVariablesAsync(folder, config).catch(err => {
return vscode.window.showErrorMessage(err.message, { modal: true }).then(_ => undefined); // abort launch
});
}
/**
* Try to add all missing attributes to the debug configuration being launched.
*/
private async resolveConfigWithSubstitutedVariablesAsync(folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration): Promise<vscode.DebugConfiguration | undefined> {
// attach to process by processId
if (config.request === 'attach' && typeof config.processId === 'string') {
await resolveProcessId(config);
}
// determine which protocol to use after all variables have been substituted (including command variables for process picker)
const debugType = await determineDebugType(config, this._logger);
if (debugType) {
config.type = debugType;
}
// everything ok: let VS Code start the debug session
return config;
}
private getJavaScriptPatterns() {
const associations = vscode.workspace.getConfiguration('files.associations');
const extension = vscode.extensions.getExtension<{}>('ms-vscode.node-debug');
if (!extension) {
throw new Error('Expected to be able to load extension data');
}
const handledLanguages = extension.packageJSON.contributes.breakpoints.map(b => b.language);
return Object.keys(associations)
.filter(pattern => handledLanguages.indexOf(associations[pattern]) !== -1)
.concat(DEFAULT_JS_PATTERNS);
}
private warnAboutUseWSL() {
interface MyMessageItem extends vscode.MessageItem {
id: number;
}
if (vscode.workspace.getConfiguration(DEBUG_SETTINGS).get<boolean>(SHOW_USE_WSL_IS_DEPRECATED_WARNING_SETTING, true)) {
vscode.window.showWarningMessage<MyMessageItem>(
localize(
'useWslDeprecationWarning.title',
"Attribute 'useWSL' is deprecated. Please use the 'Remote WSL' extension instead. Click [here]({0}) to learn more.",
'https://go.microsoft.com/fwlink/?linkid=2097212'
), {
title: localize('useWslDeprecationWarning.doNotShowAgain', "Don't Show Again"),
id: 1
}
).then(selected => {
if (!selected) {
return;
}
switch (selected.id) {
case 1:
vscode.workspace.getConfiguration(DEBUG_SETTINGS).update(SHOW_USE_WSL_IS_DEPRECATED_WARNING_SETTING, false, vscode.ConfigurationTarget.Global);
break;
}
});
}
}
/**
* if a runtime version is specified we prepend env.PATH with the folder that corresponds to the version.
* Returns false on error
*/
private async nvmSupport(config: vscode.DebugConfiguration): Promise<void> {
let bin: string | undefined = undefined;
let versionManagerName: string | undefined = undefined;
// first try the Node Version Switcher 'nvs'
let nvsHome = process.env['NVS_HOME'];
if (!nvsHome) {
// NVS_HOME is not always set. Probe for 'nvs' directory instead
const nvsDir = process.platform === 'win32' ? join(process.env['LOCALAPPDATA'] || '', 'nvs') : join(process.env['HOME'] || '', '.nvs');
if (fs.existsSync(nvsDir)) {
nvsHome = nvsDir;
}
}
const { nvsFormat, remoteName, semanticVersion, arch } = parseVersionString(config.runtimeVersion);
if (nvsFormat || nvsHome) {
if (nvsHome) {
bin = join(nvsHome, remoteName, semanticVersion, arch);
if (process.platform !== 'win32') {
bin = join(bin, 'bin');
}
versionManagerName = 'nvs';
} else {
throw new Error(localize('NVS_HOME.not.found.message', "Attribute 'runtimeVersion' requires Node.js version manager 'nvs'."));
}
}
if (!bin) {
// now try the Node Version Manager 'nvm'
if (process.platform === 'win32') {
const nvmHome = process.env['NVM_HOME'];
if (!nvmHome) {
throw new Error(localize('NVM_HOME.not.found.message', "Attribute 'runtimeVersion' requires Node.js version manager 'nvm-windows' or 'nvs'."));
}
bin = join(nvmHome, `v${config.runtimeVersion}`);
versionManagerName = 'nvm-windows';
} else { // macOS and linux
let nvmHome = process.env['NVM_DIR'];
if (!nvmHome) {
// if NVM_DIR is not set. Probe for '.nvm' directory instead
const nvmDir = join(process.env['HOME'] || '', '.nvm');
if (fs.existsSync(nvmDir)) {
nvmHome = nvmDir;
}
}
if (!nvmHome) {
throw new Error(localize('NVM_DIR.not.found.message', "Attribute 'runtimeVersion' requires Node.js version manager 'nvm' or 'nvs'."));
}
bin = join(nvmHome, 'versions', 'node', `v${config.runtimeVersion}`, 'bin');
versionManagerName = 'nvm';
}
}
if (fs.existsSync(bin)) {
if (!config.env) {
config.env = {};
}
if (process.platform === 'win32') {
config.env['Path'] = `${bin};${process.env['Path']}`;
} else {
config.env['PATH'] = `${bin}:${process.env['PATH']}`;
}
} else {
throw new Error(localize('runtime.version.not.found.message', "Node.js version '{0}' not installed for '{1}'.", config.runtimeVersion, versionManagerName));
}
}
}
//---- helpers ----------------------------------------------------------------------------------------------------------------
function createLaunchConfigFromContext(folder: vscode.WorkspaceFolder | undefined, resolve: boolean, existingConfig?: vscode.DebugConfiguration): vscode.DebugConfiguration {
const config = {
type: 'legacy-node',
request: 'launch',
name: localize('node.launch.config.name', "Launch Program"),
skipFiles: ['<node_internals>/**'],
};
if (existingConfig && existingConfig.noDebug) {
config['noDebug'] = true;
}
const pkg = loadJSON(folder, 'package.json');
if (pkg && pkg.name === 'mern-starter') {
if (resolve) {
writeToConsole(localize({ key: 'mern.starter.explanation', comment: ['argument contains product name without translation'] }, "Launch configuration for '{0}' project created.", 'Mern Starter'));
}
configureMern(config);
} else {
let program: string | undefined;
let useSourceMaps = false;
if (pkg) {
// try to find a value for 'program' by analysing package.json
program = guessProgramFromPackage(folder, pkg, resolve);
if (program && resolve) {
writeToConsole(localize('program.guessed.from.package.json.explanation', "Launch configuration created based on 'package.json'."));
}
}
if (!program) {
// try to use file open in editor
const editor = vscode.window.activeTextEditor;
if (editor) {
const languageId = editor.document.languageId;
if (languageId === 'javascript' || isTranspiledLanguage(languageId)) {
const wf = vscode.workspace.getWorkspaceFolder(editor.document.uri);
if (wf && wf === folder) {
program = relative(wf.uri.fsPath || '/', editor.document.uri.fsPath || '/');
if (program && !isAbsolute(program)) {
program = join('${workspaceFolder}', program);
}
}
}
useSourceMaps = isTranspiledLanguage(languageId);
}
}
// if we couldn't find a value for 'program', we just let the launch config use the file open in the editor
if (!program) {
program = '${file}';
}
if (program) {
config['program'] = program;
}
// prepare for source maps by adding 'outFiles' if typescript or coffeescript is detected
if (useSourceMaps || vscode.workspace.textDocuments.some(document => isTranspiledLanguage(document.languageId))) {
if (resolve) {
writeToConsole(localize('outFiles.explanation', "Adjust glob pattern(s) in the 'outFiles' attribute so that they cover the generated JavaScript."));
}
let dir = '';
const tsConfig = loadJSON(folder, 'tsconfig.json');
if (tsConfig && tsConfig.compilerOptions && tsConfig.compilerOptions.outDir) {
const outDir = <string>tsConfig.compilerOptions.outDir;
if (!isAbsolute(outDir)) {
dir = outDir;
if (dir.indexOf('./') === 0) {
dir = dir.substr(2);
}
if (dir[dir.length - 1] !== '/') {
dir += '/';
}
}
config['preLaunchTask'] = 'tsc: build - tsconfig.json';
}
config['outFiles'] = ['${workspaceFolder}/' + dir + '**/*.js'];
}
}
return config;
}
function loadJSON(folder: vscode.WorkspaceFolder | undefined, file: string): any {
if (folder) {
try {
const path = join(folder.uri.fsPath, file);
const content = fs.readFileSync(path, 'utf8');
return JSON.parse(content);
} catch (error) {
// silently ignore
}
}
return undefined;
}
function configureMern(config: any) {
config.protocol = 'inspector';
config.runtimeExecutable = 'nodemon';
config.program = '${workspaceFolder}/index.js';
config.restart = true;
config.env = {
BABEL_DISABLE_CACHE: '1',
NODE_ENV: 'development'
};
config.console = 'integratedTerminal';
config.internalConsoleOptions = 'neverOpen';
}
function isTranspiledLanguage(languagId: string): boolean {
return languagId === 'typescript' || languagId === 'coffeescript';
}
/*
* try to find the entry point ('main') from the package.json
*/
function guessProgramFromPackage(folder: vscode.WorkspaceFolder | undefined, packageJson: any, resolve: boolean): string | undefined {
let program: string | undefined;
try {
if (packageJson.main) {
program = packageJson.main;
} else if (packageJson.scripts && typeof packageJson.scripts.start === 'string') {
// assume a start script of the form 'node server.js'
program = (<string>packageJson.scripts.start).split(' ').pop();
}
if (program) {
let path: string | undefined;
if (isAbsolute(program)) {
path = program;
} else {
path = folder ? join(folder.uri.fsPath, program) : undefined;
program = join('${workspaceFolder}', program);
}
if (resolve && path && !fs.existsSync(path) && !fs.existsSync(path + '.js')) {
return undefined;
}
}
} catch (error) {
// silently ignore
}
return program;
}
//---- debug type -------------------------------------------------------------------------------------------------------------
async function determineDebugType(config: any, logger: Logger): Promise<string | null> {
if (config.protocol === 'legacy') {
return 'legacy-node';
} else if (config.protocol === 'inspector') {
return 'legacy-node2';
} else {
// 'auto', or unspecified
return detectDebugType(config, logger);
}
}
function nvsStandardArchName(arch) {
switch (arch) {
case '32':
case 'x86':
case 'ia32':
return 'x86';
case '64':
case 'x64':
case 'amd64':
return 'x64';
case 'arm':
const arm_version = (process.config.variables as any).arm_version;
return arm_version ? 'armv' + arm_version + 'l' : 'arm';
default:
return arch;
}
}
/**
* Parses a node version string into remote name, semantic version, and architecture
* components. Infers some unspecified components based on configuration.
*/
function parseVersionString(versionString) {
const versionRegex = /^(([\w-]+)\/)?(v?(\d+(\.\d+(\.\d+)?)?))(\/((x86)|(32)|((x)?64)|(arm\w*)|(ppc\w*)))?$/i;
const match = versionRegex.exec(versionString);
if (!match) {
throw new Error('Invalid version string: ' + versionString);
}
const nvsFormat = !!(match[2] || match[8]);
const remoteName = match[2] || 'node';
const semanticVersion = match[4] || '';
const arch = nvsStandardArchName(match[8] || process.arch);
return { nvsFormat, remoteName, semanticVersion, arch };
} | the_stack |
import {PRNG, PRNGSeed} from '../../../sim/prng';
import {MoveCounter, RandomTeams} from '../../random-teams';
export class RandomBDSPTeams extends RandomTeams {
constructor(format: Format | string, prng: PRNG | PRNGSeed | null) {
super(format, prng);
this.noStab = [...this.noStab, 'gigaimpact'];
}
getHighPriorityItem(
ability: string,
types: Set<string>,
moves: Set<string>,
counter: MoveCounter,
teamDetails: RandomTeamsTypes.TeamDetails,
species: Species,
isLead: boolean,
isDoubles: boolean
) {
// not undefined — we want "no item" not "go find a different item"
if (moves.has('acrobatics')) return '';
if (moves.has('solarbeam') && !(moves.has('sunnyday') || ability === 'Drought' || teamDetails.sun)) return 'Power Herb';
if (moves.has('shellsmash')) return 'White Herb';
// Species-specific item assigning
if (species.name === 'Farfetch\u2019d') return 'Leek';
if (species.name === 'Latios' || species.name === 'Latias') return 'Soul Dew';
if (species.name === 'Lopunny') return 'Toxic Orb';
if (species.baseSpecies === 'Marowak') return 'Thick Club';
if (species.baseSpecies === 'Pikachu') return 'Light Ball';
if (species.name === 'Shedinja' || species.name === 'Smeargle') return 'Focus Sash';
if (species.name === 'Shuckle' && moves.has('stickyweb')) return 'Mental Herb';
if (ability !== 'Sniper' && (ability === 'Super Luck' || moves.has('focusenergy'))) return 'Scope Lens';
if (species.name === 'Wobbuffet' && moves.has('destinybond')) return 'Custap Berry';
if (species.name === 'Scyther' && counter.damagingMoves.size > 3) return 'Choice Band';
if ((moves.has('bellydrum') || moves.has('tailglow')) && moves.has('substitute')) return 'Salac Berry';
// Ability based logic and miscellaneous logic
if (species.name === 'Wobbuffet' || ability === 'Ripen' || ability === 'Harvest') return 'Sitrus Berry';
if (ability === 'Gluttony') return this.sample(['Aguav', 'Figy', 'Iapapa', 'Mago', 'Wiki']) + ' Berry';
if (ability === 'Imposter') return 'Choice Scarf';
if (ability === 'Guts' && counter.get('Physical') > 2) {
return types.has('Fire') ? 'Toxic Orb' : 'Flame Orb';
}
if (ability === 'Toxic Boost' || ability === 'Poison Heal') return 'Toxic Orb';
if (ability === 'Magic Guard' && counter.damagingMoves.size > 1) {
return moves.has('counter') ? 'Focus Sash' : 'Life Orb';
}
if (ability === 'Sheer Force' && counter.get('sheerforce')) return 'Life Orb';
if (ability === 'Unburden') return (moves.has('closecombat') || moves.has('curse')) ? 'White Herb' : 'Sitrus Berry';
if (!moves.has('fakeout') && (moves.has('trick') || moves.has('switcheroo'))) {
if (species.baseStats.spe >= 60 && species.baseStats.spe <= 108 && !counter.get('priority')) {
return 'Choice Scarf';
} else {
return (counter.get('Physical') > counter.get('Special')) ? 'Choice Band' : 'Choice Specs';
}
}
if (moves.has('auroraveil') || moves.has('lightscreen') && moves.has('reflect')) return 'Light Clay';
const statusCuringAbility = (
ability === 'Shed Skin' ||
ability === 'Natural Cure' ||
(ability === 'Hydration' && moves.has('raindance'))
);
const restWithoutSleepTalk = (moves.has('rest') && !moves.has('sleeptalk'));
if (restWithoutSleepTalk && !statusCuringAbility) return 'Chesto Berry';
if (moves.has('bellydrum')) return 'Sitrus Berry';
}
getMediumPriorityItem(
ability: string,
moves: Set<string>,
counter: MoveCounter,
species: Species,
isLead: boolean,
isDoubles: boolean,
): string | undefined {
// Choice items
if (moves.size === 1) {
switch (this.dex.moves.get([...moves][0]).category) {
case 'Status':
return 'Choice Scarf';
case 'Physical':
return 'Choice Band';
case 'Special':
return 'Choice Specs';
}
}
const choiceOK = ['fakeout', 'flamecharge', 'rapidspin'].every(m => !moves.has(m));
if (counter.get('Physical') >= 4 && ability !== 'Serene Grace' && choiceOK) {
const scarfReqs = (
(species.baseStats.atk >= 100 || ability === 'Huge Power') &&
species.baseStats.spe >= 60 && species.baseStats.spe <= 108 &&
ability !== 'Speed Boost' && !counter.get('priority') &&
['bounce', 'aerialace'].every(m => !moves.has(m))
);
return (scarfReqs && this.randomChance(2, 3)) ? 'Choice Scarf' : 'Choice Band';
}
if (moves.has('sunnyday')) return 'Heat Rock';
if (counter.get('Special') >= 4 && !moves.has('uturn')) {
const scarfReqs = (
species.baseStats.spa >= 100 &&
species.baseStats.spe >= 60 && species.baseStats.spe <= 108 &&
ability !== 'Tinted Lens' && !counter.get('Physical')
);
return (scarfReqs && this.randomChance(2, 3)) ? 'Choice Scarf' : 'Choice Specs';
}
if (counter.get('Physical') >= 4 && choiceOK) return 'Choice Band';
if (
((counter.get('Physical') >= 3 && moves.has('defog')) || (counter.get('Special') >= 3 && moves.has('healingwish'))) &&
!counter.get('priority') && !moves.has('uturn')
) return 'Choice Scarf';
// Other items
if (
moves.has('raindance') || moves.has('sunnyday') ||
(ability === 'Speed Boost' && !counter.get('hazards'))
) return 'Life Orb';
if (
['clearsmog', 'curse', 'haze', 'healbell', 'protect', 'sleeptalk'].some(m => moves.has(m)) &&
ability === 'Moody'
) return 'Leftovers';
}
getLowPriorityItem(
ability: string,
types: Set<string>,
moves: Set<string>,
abilities: Set<string>,
counter: MoveCounter,
teamDetails: RandomTeamsTypes.TeamDetails,
species: Species,
isLead: boolean,
isDoubles: boolean
): string | undefined {
const defensiveStatTotal = species.baseStats.hp + species.baseStats.def + species.baseStats.spd;
if (
isLead &&
ability !== 'Sturdy' && !moves.has('substitute') &&
!counter.get('drain') && !counter.get('recoil') && !counter.get('recovery') &&
((defensiveStatTotal <= 250 && counter.get('hazards')) || defensiveStatTotal <= 210)
) return 'Focus Sash';
if (
counter.damagingMoves.size >= 3 &&
!counter.get('damage') &&
ability !== 'Sturdy' &&
(species.baseStats.spe >= 90 || !moves.has('voltswitch')) &&
['foulplay', 'rapidspin', 'substitute', 'uturn'].every(m => !moves.has(m)) && (
counter.get('speedsetup') ||
// No Dynamax Buzzwole doesn't want Life Orb with Bulk Up + 3 attacks
(counter.get('drain') && moves.has('roost')) ||
moves.has('trickroom') || moves.has('psystrike') ||
(species.baseStats.spe > 40 && defensiveStatTotal < 275)
)
) return 'Life Orb';
if (
counter.damagingMoves.size >= 4 &&
!counter.get('Dragon') && !counter.get('Normal')
) {
return 'Expert Belt';
}
if (
!moves.has('substitute') &&
(moves.has('dragondance') || moves.has('swordsdance')) &&
(moves.has('outrage') || (
['Bug', 'Fire', 'Ground', 'Normal', 'Poison'].every(type => !types.has(type)) &&
ability !== 'Storm Drain'
))
) return 'Lum Berry';
}
shouldCullMove(
move: Move,
types: Set<string>,
moves: Set<string>,
abilities: Set<string>,
counter: MoveCounter,
movePool: string[],
teamDetails: RandomTeamsTypes.TeamDetails,
species: Species,
isLead: boolean,
isDoubles: boolean,
): {cull: boolean, isSetup?: boolean} {
if (isDoubles && species.baseStats.def >= 140 && movePool.includes('bodypress')) {
// In Doubles, Pokémon with Defense stats >= 140 should always have body press
return {cull: true};
}
if (species.id === 'entei' && movePool.includes('extremespeed')) {
return {cull: true};
}
// Spore is really, really good and should be forced onto all sets.
// zzzzzz
// Substitute is a hardcode for Breloom.
if (movePool.includes('spore') && move.id !== 'substitute') {
return {cull: true};
}
const hasRestTalk = moves.has('rest') && moves.has('sleeptalk');
// Reject moves that need support
switch (move.id) {
case 'fly':
return {cull: !types.has(move.type) && !counter.setupType && !!counter.get('Status')};
case 'healbell':
return {cull: movePool.includes('protect') || movePool.includes('wish')};
case 'fireblast':
// Special case for Togekiss, which always wants Aura Sphere
return {cull: abilities.has('Serene Grace') && (!moves.has('trick') || counter.get('Status') > 1)};
case 'firepunch':
// Special case for Darmanitan-Zen-Galar, which doesn't always want Fire Punch
return {cull: moves.has('earthquake') && movePool.includes('substitute')};
case 'flamecharge':
return {cull: movePool.includes('swordsdance')};
case 'focuspunch':
return {cull: !moves.has('substitute')};
case 'rest':
const bulkySetup = !moves.has('sleeptalk') && ['bulkup', 'calmmind', 'coil', 'curse'].some(m => movePool.includes(m));
// Registeel would otherwise get Curse sets without Rest, which are very bad generally
return {cull: species.id !== 'registeel' && (movePool.includes('sleeptalk') || bulkySetup)};
case 'sleeptalk':
if (moves.has('stealthrock') || !moves.has('rest')) return {cull: true};
if (movePool.length > 1 && !abilities.has('Contrary')) {
const rest = movePool.indexOf('rest');
if (rest >= 0) this.fastPop(movePool, rest);
}
break;
case 'storedpower':
return {cull: !counter.setupType};
case 'switcheroo': case 'trick':
// We cull Switcheroo + Fake Out because Switcheroo is often used with a Choice item
return {cull: counter.get('Physical') + counter.get('Special') < 3 || moves.has('rapidspin') || moves.has('fakeout')};
case 'trickroom':
const webs = !!teamDetails.stickyWeb;
return {cull:
isLead || webs || !!counter.get('speedsetup') ||
counter.damagingMoves.size < 2 || movePool.includes('nastyplot'),
};
// Set up once and only if we have the moves for it
case 'bellydrum': case 'bulkup': case 'coil': case 'curse': case 'dragondance': case 'honeclaws': case 'swordsdance':
if (counter.setupType !== 'Physical') return {cull: true}; // if we're not setting up physically this is pointless
if (counter.get('Physical') + counter.get('physicalpool') < 2 && !hasRestTalk) return {cull: true};
if (move.id === 'swordsdance' && moves.has('dragondance')) return {cull: true}; // Dragon Dance is judged as better
return {cull: false, isSetup: true};
case 'calmmind': case 'nastyplot':
if (counter.setupType !== 'Special') return {cull: true};
if (
(counter.get('Special') + counter.get('specialpool')) < 2 &&
!hasRestTalk &&
!(moves.has('wish') && moves.has('protect'))
) return {cull: true};
if (moves.has('healpulse') || move.id === 'calmmind' && moves.has('trickroom')) return {cull: true};
return {cull: false, isSetup: true};
case 'quiverdance':
return {cull: false, isSetup: true};
case 'shellsmash': case 'workup':
if (counter.setupType !== 'Mixed') return {cull: true};
if (counter.damagingMoves.size + counter.get('physicalpool') + counter.get('specialpool') < 2) return {cull: true};
return {cull: false, isSetup: true};
case 'agility': case 'autotomize': case 'rockpolish':
if (counter.damagingMoves.size < 2 || moves.has('rest')) return {cull: true};
if (movePool.includes('calmmind') || movePool.includes('nastyplot')) return {cull: true};
return {cull: false, isSetup: !counter.setupType};
// Bad after setup
case 'counter': case 'reversal':
// Counter: special case for Alakazam, which doesn't want Counter + Nasty Plot
return {cull: !!counter.setupType};
case 'bulletpunch': case 'extremespeed': case 'rockblast':
return {cull: (
!!counter.get('speedsetup') ||
(!isDoubles && moves.has('dragondance')) ||
counter.damagingMoves.size < 2
)};
case 'closecombat': case 'flashcannon':
const substituteCullCondition = (
(moves.has('substitute') && !types.has('Fighting')) ||
(moves.has('toxic') && movePool.includes('substitute'))
);
const preferHJKOverCCCullCondition = (
move.id === 'closecombat' &&
!counter.setupType &&
(moves.has('highjumpkick') || movePool.includes('highjumpkick'))
);
return {cull: substituteCullCondition || preferHJKOverCCCullCondition};
case 'defog':
return {cull: (
!!counter.setupType ||
['healbell', 'toxicspikes', 'stealthrock', 'spikes'].some(m => moves.has(m)) ||
!!teamDetails.defog
)};
case 'fakeout':
return {cull: !!counter.setupType || ['protect', 'rapidspin', 'substitute', 'uturn'].some(m => moves.has(m))};
case 'glare': case 'icywind': case 'tailwind': case 'waterspout':
return {cull: !!counter.setupType || !!counter.get('speedsetup') || moves.has('rest')};
case 'healingwish': case 'memento':
return {cull: !!counter.setupType || !!counter.get('recovery') || moves.has('substitute') || moves.has('uturn')};
case 'partingshot':
return {cull: !!counter.get('speedsetup') || moves.has('bulkup') || moves.has('uturn')};
case 'protect':
if (!isDoubles && ((counter.setupType && !moves.has('wish')) || moves.has('rest'))) return {cull: true};
if (
!isDoubles &&
counter.get('Status') < 2 &&
['Speed Boost', 'Moody'].every(m => !abilities.has(m))
) return {cull: true};
if (movePool.includes('leechseed') || (movePool.includes('toxic') && !moves.has('wish'))) return {cull: true};
if (isDoubles && (
['bellydrum', 'fakeout', 'shellsmash', 'spore'].some(m => movePool.includes(m)) ||
moves.has('tailwind') || moves.has('waterspout')
)) return {cull: true};
return {cull: false};
case 'rapidspin':
const setup = ['curse', 'nastyplot', 'shellsmash'].some(m => moves.has(m));
return {cull: !!teamDetails.rapidSpin || setup || (!!counter.setupType && counter.get('Fighting') >= 2)};
case 'roar':
// for Blastoise
return {cull: moves.has('shellsmash')};
case 'shadowsneak':
const sneakIncompatible = ['substitute', 'trickroom', 'toxic'].some(m => moves.has(m));
return {cull: hasRestTalk || sneakIncompatible || counter.setupType === 'Special'};
case 'spikes':
return {cull: !!counter.setupType || (!!teamDetails.spikes && teamDetails.spikes > 1)};
case 'stealthrock':
return {cull:
!!counter.setupType ||
!!counter.get('speedsetup') ||
!!teamDetails.stealthRock ||
['rest', 'substitute', 'trickroom', 'teleport'].some(m => moves.has(m)),
};
case 'stickyweb':
return {cull: counter.setupType === 'Special' || !!teamDetails.stickyWeb};
case 'taunt':
return {cull: moves.has('encore') || moves.has('nastyplot') || moves.has('swordsdance')};
case 'thunderwave': case 'voltswitch':
const cullInDoubles = isDoubles && (moves.has('electroweb') || moves.has('nuzzle'));
return {cull: (
!!counter.setupType ||
!!counter.get('speedsetup') ||
moves.has('shiftgear') ||
moves.has('raindance') ||
cullInDoubles
)};
case 'toxic':
return {cull: !!counter.setupType || ['sludgewave', 'thunderwave', 'willowisp'].some(m => moves.has(m))};
case 'toxicspikes':
return {cull: !!counter.setupType || !!teamDetails.toxicSpikes};
case 'uturn':
const bugSwordsDanceCase = types.has('Bug') && counter.get('recovery') && moves.has('swordsdance');
return {cull: (
!!counter.get('speedsetup') ||
(counter.setupType && !bugSwordsDanceCase) ||
(isDoubles && moves.has('leechlife'))
)};
/**
* Ineffective to have both moves together
*
* These are sorted in order of:
* Normal>Fire>Water>Electric>Grass>Ice>Fighting>Poison>Ground>Flying>Psychic>Bug>Rock>Ghost>Dragon>Dark>Fairy
* and then subsorted alphabetically.
* This type order is arbitrary and referenced from https://pokemondb.net/type.
*/
case 'explosion':
const otherMoves = ['curse', 'stompingtantrum', 'painsplit', 'wish'].some(m => moves.has(m));
return {cull: !!counter.get('speedsetup') || !!counter.get('recovery') || otherMoves};
case 'quickattack':
return {cull: !!counter.get('speedsetup') || (types.has('Rock') && !!counter.get('Status'))};
case 'flamethrower': case 'lavaplume':
const otherFireMoves = ['heatwave', 'overheat'].some(m => moves.has(m));
return {cull: (moves.has('fireblast') && counter.setupType !== 'Physical') || otherFireMoves};
case 'overheat':
return {cull: moves.has('flareblitz') || (isDoubles && moves.has('calmmind'))};
case 'aquatail':
return {cull: moves.has('aquajet') || !!counter.get('Status')};
case 'hydropump':
return {cull: moves.has('scald') && (
(counter.get('Special') < 4 && !moves.has('uturn')) ||
(species.types.length > 1 && counter.get('stab') < 3)
)};
case 'gigadrain':
return {cull: types.has('Poison') && !counter.get('Poison')};
case 'leafstorm':
const leafBladePossible = movePool.includes('leafblade') || moves.has('leafblade');
return {cull:
(counter.setupType === 'Physical' && leafBladePossible) ||
(moves.has('gigadrain') && !!counter.get('Status')) ||
(isDoubles && moves.has('energyball')),
};
case 'freezedry':
const betterIceMove = (
(moves.has('blizzard') && !!counter.setupType) ||
(moves.has('icebeam') && counter.get('Special') < 4)
);
const preferThunderWave = movePool.includes('thunderwave') && types.has('Electric');
return {cull: betterIceMove || preferThunderWave || movePool.includes('bodyslam')};
case 'bodypress':
const pressIncompatible = ['shellsmash', 'mirrorcoat', 'whirlwind'].some(m => moves.has(m));
return {cull: pressIncompatible || counter.setupType === 'Special'};
case 'drainpunch':
return {cull: moves.has('closecombat') || (!types.has('Fighting') && movePool.includes('swordsdance'))};
case 'facade':
// Prefer Dynamic Punch when it can be a guaranteed-hit STAB move (mostly for Machamp)
return {cull: moves.has('dynamicpunch') && species.types.includes('Fighting') && abilities.has('No Guard')};
case 'focusblast':
// Special cases for Blastoise and Regice; Blastoise wants Shell Smash, and Regice wants Thunderbolt
return {cull: movePool.includes('shellsmash') || hasRestTalk};
case 'superpower':
return {
cull: moves.has('hydropump') ||
(counter.get('Physical') >= 4 && movePool.includes('uturn')) ||
(moves.has('substitute') && !abilities.has('Contrary')),
isSetup: abilities.has('Contrary'),
};
case 'poisonjab':
return {cull: !types.has('Poison') && counter.get('Status') >= 2};
case 'earthquake':
const doublesCull = moves.has('earthpower') || moves.has('highhorsepower');
const subToxicPossible = moves.has('substitute') && movePool.includes('toxic');
return {cull: (isDoubles && doublesCull) || subToxicPossible || moves.has('bonemerang')};
case 'airslash':
return {cull: hasRestTalk || counter.setupType === 'Physical'};
case 'hurricane':
return {cull: counter.setupType === 'Physical'};
case 'futuresight':
return {cull: moves.has('psyshock') || moves.has('trick') || movePool.includes('teleport')};
case 'psychic':
return {cull: moves.has('psyshock') && (!!counter.setupType || isDoubles)};
case 'psyshock':
return {cull: moves.has('psychic')};
case 'bugbuzz':
return {cull: moves.has('uturn') && !counter.setupType};
case 'leechlife':
return {cull:
(isDoubles && moves.has('lunge')) ||
(moves.has('uturn') && !counter.setupType) ||
movePool.includes('spikes'),
};
case 'stoneedge':
const gutsCullCondition = abilities.has('Guts') && (!moves.has('dynamicpunch') || moves.has('spikes'));
const rockSlidePlusStatusPossible = counter.get('Status') && movePool.includes('rockslide');
const otherRockMove = moves.has('rockblast') || moves.has('rockslide');
const lucarioCull = species.id === 'lucario' && !!counter.setupType;
return {cull: gutsCullCondition || (!isDoubles && rockSlidePlusStatusPossible) || otherRockMove || lucarioCull};
case 'shadowball':
return {cull:
(isDoubles && moves.has('phantomforce')) ||
(!types.has('Ghost') && movePool.includes('focusblast')),
};
case 'shadowclaw':
return {cull: types.has('Steel') && moves.has('shadowsneak') && counter.get('Physical') < 4};
case 'dragonpulse': case 'spacialrend':
return {cull: moves.has('dracometeor') && counter.get('Special') < 4};
case 'darkpulse':
const pulseIncompatible = ['foulplay', 'knockoff'].some(m => moves.has(m)) || (
species.id === 'shiftry' && (moves.has('defog') || moves.has('suckerpunch'))
);
// Special clause to prevent bugged Shiftry sets with Sucker Punch + Nasty Plot
const shiftryCase = movePool.includes('nastyplot') && !moves.has('defog');
return {cull: pulseIncompatible && !shiftryCase && counter.setupType !== 'Special'};
case 'suckerpunch':
return {cull:
moves.has('rest') ||
counter.damagingMoves.size < 2 ||
(counter.setupType === 'Special') ||
(counter.get('Dark') > 1 && !types.has('Dark')),
};
case 'dazzlinggleam':
return {cull: ['moonblast', 'petaldance'].some(m => moves.has(m))};
// Status:
case 'bodyslam': case 'clearsmog':
const toxicCullCondition = moves.has('toxic') && !types.has('Normal');
return {cull: moves.has('sludgebomb') || moves.has('trick') || movePool.includes('recover') || toxicCullCondition};
case 'willowisp': case 'yawn':
// Swords Dance is a special case for Rapidash
return {cull: moves.has('thunderwave') || moves.has('toxic') || moves.has('swordsdance')};
case 'painsplit': case 'recover': case 'synthesis':
return {cull: moves.has('rest') || moves.has('wish') || (move.id === 'synthesis' && moves.has('gigadrain'))};
case 'roost':
return {cull:
moves.has('throatchop') ||
// Special cases for Salamence, Dynaless Dragonite, and Scizor to help prevent sets with poor coverage or no setup.
(moves.has('dualwingbeat') && (moves.has('outrage') || species.id === 'scizor')),
};
case 'reflect': case 'lightscreen':
return {cull: !!teamDetails.screens};
case 'slackoff':
// Special case to prevent Scaldless Slowking
return {cull: species.id === 'slowking' && !moves.has('scald')};
case 'substitute':
const moveBasedCull = (
// Breloom is OK with Substitute + Swords Dance (for subpunch sets)
species.id !== 'breloom' &&
['bulkup', 'nastyplot', 'painsplit', 'roost', 'swordsdance'].some(m => movePool.includes(m))
);
const shayminCase = abilities.has('Serene Grace') && movePool.includes('airslash') && !moves.has('airslash');
return {cull: moves.has('rest') || moveBasedCull || shayminCase};
case 'helpinghand':
// Special case for Shuckle in Doubles, which doesn't want sets with no method to harm foes
return {cull: moves.has('acupressure')};
case 'wideguard':
return {cull: moves.has('protect')};
case 'grassknot':
// Special case for Raichu
return {cull: moves.has('surf')};
}
return {cull: false};
}
shouldCullAbility(
ability: string,
types: Set<string>,
moves: Set<string>,
abilities: Set<string>,
counter: MoveCounter,
movePool: string[],
teamDetails: RandomTeamsTypes.TeamDetails,
species: Species,
isDoubles: boolean,
): boolean {
if ([
'Flare Boost', 'Hydration', 'Ice Body', 'Immunity', 'Insomnia', 'Quick Feet', 'Rain Dish',
'Snow Cloak', 'Steadfast',
].includes(ability)) return true;
switch (ability) {
// Abilities which are primarily useful for certain moves
case 'Contrary': case 'Serene Grace': case 'Skill Link':
return !counter.get(ability.toLowerCase().replace(/\s/g, ''));
case 'Analytic':
return (moves.has('rapidspin') || species.nfe || isDoubles);
case 'Blaze':
return (isDoubles && abilities.has('Solar Power')) || (!isDoubles && species.id === 'charizard');
case 'Chlorophyll':
return (species.baseStats.spe > 100 || !counter.get('Fire') && !moves.has('sunnyday') && !teamDetails.sun);
case 'Cloud Nine':
return species.id !== 'golduck';
case 'Competitive':
return (counter.get('Special') < 2 || (moves.has('rest') && moves.has('sleeptalk')));
case 'Compound Eyes': case 'No Guard':
return !counter.get('inaccurate');
case 'Cursed Body':
return abilities.has('Infiltrator');
case 'Defiant':
return !counter.get('Physical');
case 'Download':
return (counter.damagingMoves.size < 3 || moves.has('trick'));
case 'Early Bird':
return (types.has('Grass') && isDoubles);
case 'Flash Fire':
return (this.dex.getEffectiveness('Fire', species) < -1 || abilities.has('Drought'));
case 'Gluttony':
return !moves.has('bellydrum');
case 'Guts':
return (!moves.has('facade') && !moves.has('sleeptalk') && !species.nfe);
case 'Harvest':
return (abilities.has('Frisk') && !isDoubles);
case 'Hustle': case 'Inner Focus':
return (counter.get('Physical') < 2 || abilities.has('Iron Fist'));
case 'Infiltrator':
return (moves.has('rest') && moves.has('sleeptalk')) || (isDoubles && abilities.has('Clear Body'));
case 'Intimidate':
if (species.id === 'salamence' && moves.has('dragondance')) return true;
return ['bodyslam', 'bounce', 'tripleaxel'].some(m => moves.has(m));
case 'Iron Fist':
return (counter.get('ironfist') < 2 || moves.has('dynamicpunch'));
case 'Justified':
return (isDoubles && abilities.has('Inner Focus'));
case 'Lightning Rod':
return (species.types.includes('Ground') || counter.setupType === 'Physical');
case 'Limber':
return species.types.includes('Electric') || moves.has('facade');
case 'Mold Breaker':
return (
abilities.has('Adaptability') || abilities.has('Scrappy') || (abilities.has('Unburden') && !!counter.setupType) ||
(abilities.has('Sheer Force') && !!counter.get('sheerforce'))
);
case 'Moody':
return !!counter.setupType && abilities.has('Simple');
case 'Moxie':
return (counter.get('Physical') < 2 || moves.has('stealthrock') || moves.has('defog'));
case 'Overgrow':
return !counter.get('Grass');
case 'Own Tempo':
return !moves.has('petaldance');
case 'Prankster':
return !counter.get('Status');
case 'Pressure':
return (!!counter.setupType || counter.get('Status') < 2 || isDoubles);
case 'Reckless':
return !counter.get('recoil') || moves.has('curse');
case 'Rock Head':
return !counter.get('recoil');
case 'Sand Force': case 'Sand Veil':
return !teamDetails.sand;
case 'Sand Rush':
return (!teamDetails.sand && (!counter.setupType || !counter.get('Rock') || moves.has('rapidspin')));
case 'Scrappy':
return (moves.has('earthquake') && species.id === 'miltank');
case 'Sheer Force':
return (!counter.get('sheerforce') || abilities.has('Guts'));
case 'Shell Armor':
return (species.id === 'omastar' && (moves.has('spikes') || moves.has('stealthrock')));
case 'Sniper':
return counter.get('Water') > 1 && !moves.has('focusenergy');
case 'Sturdy':
return (moves.has('bulkup') || !!counter.get('recoil') || abilities.has('Solid Rock'));
case 'Swarm':
return (!counter.get('Bug') || !!counter.get('recovery'));
case 'Swift Swim':
const neverWantsSwim = !moves.has('raindance') && [
'Intimidate', 'Rock Head', 'Water Absorb',
].some(m => abilities.has(m));
const noSwimIfNoRain = !moves.has('raindance') && [
'Cloud Nine', 'Lightning Rod', 'Intimidate', 'Rock Head', 'Sturdy', 'Water Absorb', 'Weak Armor',
].some(m => abilities.has(m));
return teamDetails.rain ? neverWantsSwim : noSwimIfNoRain;
case 'Synchronize':
return counter.get('Status') < 3;
case 'Technician':
return (
!counter.get('technician') ||
moves.has('tailslap') ||
abilities.has('Punk Rock')
);
case 'Tinted Lens':
return (
// For Butterfree
(moves.has('hurricane') && abilities.has('Compound Eyes')) ||
(counter.get('Status') > 2 && !counter.setupType) ||
// For Yanmega
moves.has('protect')
);
case 'Unaware':
return species.id === 'bibarel';
case 'Unburden':
return (
abilities.has('Prankster') ||
// intended for Hitmonlee
abilities.has('Reckless') ||
!counter.setupType && !isDoubles
);
case 'Volt Absorb':
return (this.dex.getEffectiveness('Electric', species) < -1);
case 'Water Absorb':
return (
moves.has('raindance') ||
['Drizzle', 'Strong Jaw', 'Unaware', 'Volt Absorb'].some(abil => abilities.has(abil))
);
case 'Weak Armor':
return (
species.id === 'skarmory' ||
moves.has('shellsmash') || moves.has('rapidspin')
);
}
return false;
}
}
export default RandomBDSPTeams; | the_stack |
import {} from "mocha";
import sinon from "sinon";
import express from "express";
import nock from "nock";
import _ from "lodash";
import supertest from "supertest";
import Authenticator from "../Authenticator";
import setupTenantMode from "../setupTenantMode";
import createGenericProxyRouter from "../createGenericProxyRouter";
import { expect } from "chai";
describe("createGenericProxyRouter", () => {
const defaultTenantMode = setupTenantMode({
enableMultiTenants: false
});
afterEach(() => {
nock.cleanAll();
});
it("should accept url string as target proxy definition item", async () => {
let isApplyToRouteCalled = false;
const dummyAuthenticator = sinon.createStubInstance(Authenticator);
dummyAuthenticator.applyToRoute = () => {
isApplyToRouteCalled = true;
};
const router = createGenericProxyRouter({
authenticator: dummyAuthenticator,
jwtSecret: "xxx",
routes: {
"test-route": "http://test-route.com"
},
tenantMode: defaultTenantMode
});
const app = express();
app.use(router);
const scope = nock("http://test-route.com").get("/").reply(200);
await supertest(app).get("/test-route").expect(200);
expect(scope.isDone()).to.be.true;
// by default no auth
expect(isApplyToRouteCalled).to.be.false;
// only `get` route is setup by default
scope.post("/", {}).reply(200);
await supertest(app).post("/test-route").expect(404);
});
it("should process complete target proxy definition item well", async () => {
let isApplyToRouteCalled = false;
const dummyAuthenticator = sinon.createStubInstance(Authenticator);
dummyAuthenticator.applyToRoute = () => {
isApplyToRouteCalled = true;
};
const router = createGenericProxyRouter({
authenticator: dummyAuthenticator,
jwtSecret: "xxx",
routes: {
"test-route": {
to: "http://test-route.com",
auth: true,
methods: ["get", "post"]
}
},
tenantMode: defaultTenantMode
});
const app = express();
app.use(router);
const scope = nock("http://test-route.com").get("/").reply(200);
await supertest(app).get("/test-route").expect(200);
expect(scope.isDone()).to.be.true;
// Auth is on now
expect(isApplyToRouteCalled).to.be.true;
// only `post` route is also setup now
scope.post("/").reply(200);
await supertest(app).post("/test-route").expect(200);
expect(scope.isDone()).to.be.true;
});
it("should support `all` method", async () => {
let isApplyToRouteCalled = false;
const dummyAuthenticator = sinon.createStubInstance(Authenticator);
dummyAuthenticator.applyToRoute = () => {
isApplyToRouteCalled = true;
};
const router = createGenericProxyRouter({
authenticator: dummyAuthenticator,
jwtSecret: "xxx",
routes: {
"test-route": {
to: "http://test-route.com",
auth: false,
methods: ["all"]
}
},
tenantMode: defaultTenantMode
});
const app = express();
app.use(router);
const scope = nock("http://test-route.com").get("/").reply(200);
await supertest(app).get("/test-route").expect(200);
expect(scope.isDone()).to.be.true;
// `post` route is also setup now (as it's `all`)
scope.post("/").reply(200);
await supertest(app).post("/test-route").expect(200);
expect(scope.isDone()).to.be.true;
// `put` route is also setup now (as it's `all`)
scope.put("/").reply(200);
await supertest(app).put("/test-route").expect(200);
expect(scope.isDone()).to.be.true;
// `delete` route is also setup now (as it's `all`)
scope.delete("/").reply(200);
await supertest(app).delete("/test-route").expect(200);
expect(scope.isDone()).to.be.true;
// Auth is off now
expect(isApplyToRouteCalled).to.be.false;
});
it("should support specifying different target for different methods", async () => {
const dummyAuthenticator = sinon.createStubInstance(Authenticator);
const router = createGenericProxyRouter({
authenticator: dummyAuthenticator,
jwtSecret: "xxx",
routes: {
"test-route": {
to: "http://test-default-route.com",
auth: false,
methods: [
{
method: "get",
target: "http://test-get-route.com"
},
{
method: "post",
target: "http://test-post-route.com"
},
// --- srting method will use `to` field as default target
"delete",
{
// if target field not exist, `to` field will be used as default target
method: "patch"
}
]
}
},
tenantMode: defaultTenantMode
});
const app = express();
app.use(router);
const defaultScope = nock("http://test-default-route.com");
defaultScope.get("/").reply(200, { route: "default" });
defaultScope.post("/").reply(200, { route: "default" });
defaultScope.delete("/").reply(200, { route: "default" });
defaultScope.patch("/").reply(200, { route: "default" });
nock("http://test-get-route.com").get("/").reply(200, { route: "get" });
nock("http://test-post-route.com")
.post("/")
.reply(200, { route: "post" });
// GET request should reach GET route
let res = await supertest(app).get("/test-route").expect(200);
expect(res.body.route).to.equal("get");
// POST request should reach POST route
res = await supertest(app).post("/test-route").expect(200);
expect(res.body.route).to.equal("post");
// DELETE request should reach default route
res = await supertest(app).delete("/test-route").expect(200);
expect(res.body.route).to.equal("default");
// PATCH request should reach default route
res = await supertest(app).patch("/test-route").expect(200);
expect(res.body.route).to.equal("default");
});
it("should accept url string as target proxy definition item", async () => {
let isApplyToRouteCalled = false;
const dummyAuthenticator = sinon.createStubInstance(Authenticator);
dummyAuthenticator.applyToRoute = () => {
isApplyToRouteCalled = true;
};
const router = createGenericProxyRouter({
authenticator: dummyAuthenticator,
jwtSecret: "xxx",
routes: {
"test-route": "http://test-route.com"
},
tenantMode: defaultTenantMode
});
const app = express();
app.use(router);
const scope = nock("http://test-route.com").get("/").reply(200);
await supertest(app).get("/test-route").expect(200);
expect(scope.isDone()).to.be.true;
// by default no auth
expect(isApplyToRouteCalled).to.be.false;
// only `get` route is setup by default
scope.post("/", {}).reply(200);
await supertest(app).post("/test-route").expect(404);
});
it("should forward incoming request path correctly", async () => {
const dummyAuthenticator = sinon.createStubInstance(Authenticator);
const router = createGenericProxyRouter({
authenticator: dummyAuthenticator,
jwtSecret: "xxx",
routes: {
"test-route": {
to: "http://test-route.com/routes",
auth: true,
methods: ["get", "post"]
}
},
tenantMode: defaultTenantMode
});
const app = express();
app.use(router);
const scope = nock("http://test-route.com");
let res;
// check GET routes
scope.get("/routes").reply(200, { route: "GET:root" });
res = await supertest(app).get("/test-route").expect(200);
expect(res.body.route).to.equal("GET:root");
scope
.get((uri) => {
// nock won't match request for tailing path with a query string somehow
// use function instead
return uri === "/routes/?sds=232";
})
.reply(200, { route: "GET:root", query: "?sds=232" });
res = await supertest(app).get("/test-route/?sds=232").expect(200);
expect(res.body.route).to.equal("GET:root");
expect(res.body.query).to.equal("?sds=232");
scope.get("/routes/route1").reply(200, { route: "GET:route1" });
res = await supertest(app).get("/test-route/route1").expect(200);
expect(res.body.route).to.equal("GET:route1");
scope
.get("/routes/route1?sds=232")
.reply(200, { route: "GET:route1", query: "?sds=232" });
res = await supertest(app)
.get("/test-route/route1?sds=232")
.expect(200);
expect(res.body.route).to.equal("GET:route1");
expect(res.body.query).to.equal("?sds=232");
scope.get("/routes/route2/").reply(200, { route: "GET:route2/" });
res = await supertest(app).get("/test-route/route2/").expect(200);
expect(res.body.route).to.equal("GET:route2/");
scope
.get((uri) => {
// nock won't match request for tailing path with a query string somehow
// use function instead
return uri === "/routes/route2/?sds=232";
})
.reply(200, { route: "GET:route2/", query: "?sds=232" });
res = await supertest(app)
.get("/test-route/route2/?sds=232")
.expect(200);
expect(res.body.route).to.equal("GET:route2/");
expect(res.body.query).to.equal("?sds=232");
scope.get("/routes/route3/12").reply(200, { route: "GET:route3/12" });
res = await supertest(app).get("/test-route/route3/12").expect(200);
expect(res.body.route).to.equal("GET:route3/12");
scope
.get("/routes/route3/12?sds=232")
.reply(200, { route: "GET:route3/12", query: "?sds=232" });
res = await supertest(app)
.get("/test-route/route3/12?sds=232")
.expect(200);
expect(res.body.route).to.equal("GET:route3/12");
expect(res.body.query).to.equal("?sds=232");
// check POST routes
scope.post("/routes/route1").reply(200, { route: "POST:route1" });
res = await supertest(app).post("/test-route/route1").expect(200);
expect(res.body.route).to.equal("POST:route1");
scope.post("/routes/route2/").reply(200, { route: "POST:route2/" });
res = await supertest(app).post("/test-route/route2/").expect(200);
expect(res.body.route).to.equal("POST:route2/");
scope.post("/routes/route3/12").reply(200, { route: "POST:route3/12" });
res = await supertest(app).post("/test-route/route3/12").expect(200);
expect(res.body.route).to.equal("POST:route3/12");
});
it("should forward incoming request path correctly when route key contains segment (e.g. test-route/abcd)", async () => {
const dummyAuthenticator = sinon.createStubInstance(Authenticator);
const router = createGenericProxyRouter({
authenticator: dummyAuthenticator,
jwtSecret: "xxx",
routes: {
"test-route/abcd": {
to: "http://test-route.com/abcd/routes",
auth: true,
methods: ["get", "post"]
}
},
tenantMode: defaultTenantMode
});
const app = express();
app.use(router);
const scope = nock("http://test-route.com/abcd");
let res;
// check GET routes
scope.get("/routes").reply(200, { route: "GET:root" });
res = await supertest(app).get("/test-route/abcd").expect(200);
expect(res.body.route).to.equal("GET:root");
scope
.get((uri) => {
// nock won't match request for tailing path with a query string somehow
// use function instead
return uri === "/abcd/routes/?sds=232";
})
.reply(200, { route: "GET:root", query: "?sds=232" });
res = await supertest(app).get("/test-route/abcd/?sds=232").expect(200);
expect(res.body.route).to.equal("GET:root");
expect(res.body.query).to.equal("?sds=232");
scope.get("/routes/route1").reply(200, { route: "GET:route1" });
res = await supertest(app).get("/test-route/abcd/route1").expect(200);
expect(res.body.route).to.equal("GET:route1");
scope
.get("/routes/route1?sds=232")
.reply(200, { route: "GET:route1", query: "?sds=232" });
res = await supertest(app)
.get("/test-route/abcd/route1?sds=232")
.expect(200);
expect(res.body.route).to.equal("GET:route1");
expect(res.body.query).to.equal("?sds=232");
scope.get("/routes/route2/").reply(200, { route: "GET:route2/" });
res = await supertest(app).get("/test-route/abcd/route2/").expect(200);
expect(res.body.route).to.equal("GET:route2/");
scope
.get((uri) => {
// nock won't match request for tailing path with a query string somehow
// use function instead
return uri === "/abcd/routes/route2/?sds=232";
})
.reply(200, { route: "GET:route2/", query: "?sds=232" });
res = await supertest(app)
.get("/test-route/abcd/route2/?sds=232")
.expect(200);
expect(res.body.route).to.equal("GET:route2/");
expect(res.body.query).to.equal("?sds=232");
scope.get("/routes/route3/12").reply(200, { route: "GET:route3/12" });
res = await supertest(app)
.get("/test-route/abcd/route3/12")
.expect(200);
expect(res.body.route).to.equal("GET:route3/12");
scope
.get("/routes/route3/12?sds=232")
.reply(200, { route: "GET:route3/12", query: "?sds=232" });
res = await supertest(app)
.get("/test-route/abcd/route3/12?sds=232")
.expect(200);
expect(res.body.route).to.equal("GET:route3/12");
expect(res.body.query).to.equal("?sds=232");
// check POST routes
scope.post("/routes/route1").reply(200, { route: "POST:route1" });
res = await supertest(app).post("/test-route/abcd/route1").expect(200);
expect(res.body.route).to.equal("POST:route1");
scope.post("/routes/route2/").reply(200, { route: "POST:route2/" });
res = await supertest(app).post("/test-route/abcd/route2/").expect(200);
expect(res.body.route).to.equal("POST:route2/");
scope.post("/routes/route3/12").reply(200, { route: "POST:route3/12" });
res = await supertest(app)
.post("/test-route/abcd/route3/12")
.expect(200);
expect(res.body.route).to.equal("POST:route3/12");
});
}); | the_stack |
import Head from "next/head";
export default function Home(props: ReturnType<typeof getStaticProps>["props"]) {
return (
<>
<Head>
<title>Shiki Twoslash: Static Code Samples for JS Projects</title>
<meta name="description" content="You take some Shiki, add a hint of the TypeScript compiler, and 🎉! Incredible static code samples" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png" />
<link rel="icon" type="image/png" sizes="192x192" href="/android-icon-192x192.png" />
<meta property="og:title" content="Shiki Twoslash: Static Code Samples for JS Projects" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://shikijs.github.io/twoslash/" />
<meta property="og:image" content="https://shikijs.github.io/twoslash/img/ograph.png" />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@orta" />
<meta name="twitter:creator" content="@orta" />
<meta name="theme-color" content="#fcf3d9" />
<meta name="msapplication-TileColor" content="#fcf3d9" />
</Head>
<body>
<header className="nav home">
<a href="/">
<svg width="23" height="32" viewBox="0 0 23 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0.0673828 22.0295V19.2L11.2505 25.7347V28.3621L0.0673828 22.0295Z" fill="#183F66" fillOpacity="0.8" />
<path d="M11.251 2.62737V0L22.232 6.06316L22.2994 8.82526L11.251 2.62737Z" fill="#E23D1E" fillOpacity="0.8" />
<path d="M0.0673828 8.96001V6.19791L22.3663 19.0653V22.0295L0.0673828 8.96001Z" fill="#E5A604" fillOpacity="0.8" />
<path d="M0.0673828 25.6674V22.8379L11.2505 29.3726V32L0.0673828 25.6674Z" fill="#183F66" fillOpacity="0.8" />
<path d="M11.251 6.06316V3.43579L22.232 9.90316V12.5305L11.251 6.06316Z" fill="#E23D1E" fillOpacity="0.8" />
<path d="M0 12.5979L0.0673684 9.76843L22.5011 22.9053V25.5326L0 12.5979Z" fill="#E5A604" fillOpacity="0.8" />
<path d="M22.4336 22.0295V19.2L11.2504 25.7347V28.3621L22.4336 22.0295Z" fill="#183F66" fillOpacity="0.8" />
<path d="M11.251 2.62737V0L0.0678196 6.33263V8.96L11.251 2.62737Z" fill="#E23D1E" fillOpacity="0.8" />
<path d="M22.4336 25.6674V22.8379L11.2504 29.3726V32L22.4336 25.6674Z" fill="#183F66" fillOpacity="0.8" />
<path d="M11.1152 6.13053V3.43579L0.0668125 9.97053V12.5979L11.1152 6.13053Z" fill="#E23D1E" fillOpacity="0.8" />
</svg>
</a>
<p className="subtitle"><a href="/twoslash/playground">Playground</a></p>
</header>
<main className="main">
<article className="container border-red">
<div className="intro">
<p>
The documentation concerning
<br />
the npm modules of
</p>
<h1 className="title">Shiki-Twoslash</h1>
<p>
In which markdown code samples are powered by
<br />
the syntax engine of Visual Studio Code
<br />
mixed with the TypeScript compiler’s information
</p>
</div>
<div style={{ textAlign: "center", marginTop: "3rem", marginBottom: "3rem" }}>
<img src={"./svgs/squiggle.svg"} alt="Decoration" width={70} height={25.5} />
</div>
<div className="intro">
<p className="by">By <a href='https://orta.io'>orta therox</a></p>
<p>
Purveyor of renowned open source code
<br />
and TypeScript compiler team member
</p>
</div>
<div style={{ textAlign: "center", marginTop: "3rem" }}>
<img src="./svgs/logo.svg" alt="Shiki Logo" width={167} height={238} />
</div>
</article>
<Split num={0} />
<article className="container border-yellow" id="shiki">
<div style={{ textAlign: "center" }}>
<img className="old" src="./svgs/shiki.svg" alt="The word 'shiki'" width={309} height={95} />
</div>
<div className="split-50-50">
<div className="left-margin-1">
<p>
<span className="eu">V</span>isual Studio Code’s syntax highlighter packaged for running in a web browser and statically via Node.js.
</p>
<p>
Supports all possible languages available on the VS Code extension marketplace. That’s over 200 languages. All you need is a
<code> .tmlanguage</code> file for anything not shipped with{" "}
<a href="https://github.com/shikijs/shiki" target="_blank">
Shiki
</a>
.
</p>
<p>Shiki colours your code with any VS Code theme. That’s {Math.round(props.stats.themeCount / 100) * 100}+ last time we checked.</p>
</div>
<div className="left-margin-1">
<p>Fig 1.</p>
<p className="center-small">
<img src="./svgs/fig-1-code.svg" alt="A diagram showing syntax tokens" width="246" height="284" />
</p>
</div>
</div>
</article>
<article className="container border-blue" id="twoslash">
<div style={{ textAlign: "center" }}>
<img className="old" src="./svgs/twoslash.svg" alt="The word 'twoslash'" width={501} height={92} />
</div>
<div className="split-50-50">
<div className="left-margin-1 ">
<p>
<span className="eu">T</span>hink of twoslash as a pre-processor for your code-samples.
</p>
<p>Twoslash is a JavaScript and TypeScript markup language. You can write a single code sample which describes an entire JavaScript project</p>
<p>Twoslash uses the same compiler APIs as your text editors to provide type-driven hover information, accurate errors and type callouts</p>
<p>
Each code sample is compiled in isolation, so you can be certain all your examples still compile and work right a few major versions down the
line.
</p>
</div>
<div className="left-margin-1">
<p>Fig 2.</p>
<p className="center-small">
<img src="./svgs/fig-2-code.svg" alt="A diagram showing a twoslash code sample being converted to HTML" width="331" height="270" />
</p>
</div>
</div>
</article>
<article className="container border-red" id="twoslash">
<div style={{ textAlign: "center" }}>
<img className="old" src="./svgs/shiki.svg" alt="The word 'shiki'" width={309} height={95} />
<br />
<img className="old" src="./svgs/twoslash.svg" alt="The word 'twoslash'" width={501} height={92} />
</div>
<div className="split-50-50">
<div className="left-margin-1 ">
<p>
<span className="eu">M</span>ixing these two ideas is Shiki Twoslash. The goal being that you can write ergonomic code samples which are backed
by the TypeScript compiler.
</p>
<p>All code samples use Shiki, then you can opt-in to have Twoslash markup inside specific TypeScript / JavaScript code blocks.</p>
<p>
Shiki Twoslash is built to generate completely server-side syntax highlighted code samples with no reliance that the user can run JavaScript.
</p>
</div>
<div className="left-margin-1">
<p>Fig 3.</p>
<p className="center-small">
<img src="./svgs/fig-3-code.svg" alt="A diagram of markdown -> HTML with Shiki Twoslash" width="331" height="421" />
</p>
</div>
</div>
</article>
<Split num={1} />
<article className="container border-yellow" id="markup">
<h2>
<a href="#markup">#</a>Chapter 1:
<br className="small-only" /> Twoslash Markup
</h2>
<Point msg="By default all codeblocks in Shiki Twoslash act like traditional static code samples, making Shiki Twoslash backwards compatible with existing codebases." />
<Code code={props.html.basic.replace("shiki-twoslash twoslash", "").replace("twoslash", "").replace("lsp", "")} />
<Point msg="However, on JavaScript-y code samples, you can opt-in a code sample to use Twoslash. Try move your cursor into this code sample:" />
<Code code={props.html.basic} />
<Point msg="The name Twoslash refers to specially formatted comments which can be used to set up your environment, like compiler flags or separate input files. For example, here is a code sample showing export/importing a function:" />
<TwoCode source={props.html.multiFileSrc} output={props.html.multiFileHTML} />
<MicroPoint>
Compiler flag comments are removed from the output, but we keep the filename around to help people understand that you've made a multi-file code
sample.
</MicroPoint>
<Point msg="You can write comment queries to have the twoslash powered code-samples highlight types without user interaction." />
<TwoCode source={props.html.multiFileHighSrc} output={props.html.multiFileHighHTML} />
<Point msg="And if a code sample becomes un-focused, you can snip it down to just the bit that matters. The compiler still verifies everything ahead of time." />
<TwoCode source={props.html.multiFileSnipSrc} output={props.html.multiFileSnipHTML} />
<Point msg="To some extent, anything your editor can show you about code, Twoslash can show. For example, here is the real auto-complete for an express app in JS:" />
<TwoCode source={props.html.expressSrc} output={props.html.expressHTML} />
<Point msg="Are you wondering where the types come from? Express is a JavaScript library, it does not ship types. During the build process Shiki-Twoslash can use types from your app’s node_modules folder. I just had to run: <code>yarn add @types/express</code>.<br/><br/>You probably don't want to only show golden-path code too, showing <em>how</em> code goes wrong is also a critical way to understand code. Shiki Twoslash has native support for TypeScript compiler errors." />
<TwoCode source={props.html.errorSrc} output={props.html.errorHTML} />
<Point msg="You see how we declared which errors were expected in the source? That means if this code sample errors with something else, Shiki Twoslash will fail to render.<br /><br />Failing rocks because your CI will tell you that your code samples are out of date." />
</article>
<article className="container border-blue" id="shiki">
<h2>
<a href="#shiki">#</a>Chapter 2:
<br className="small-only" /> Shiki Twoslash
</h2>
<Point msg="Twoslash Shiki is a polite but hard fork of the Shiki code rendering engine. Let's look at a few of the Shiki Twoslash features.<br/><br/><strong>Multi-theme rendering</strong> gives you the chance to set up your own custom color themes ahead of time. Shiki Twoslash will render each codeblock multiple times. For example, rendering with these settings uses the site theme and every shipped Shiki theme." />
<Code code={shikiWrap(`{ "themes": ${themes()}}`)} />
<MicroPoint>Turns into:</MicroPoint>
<div className="show-lots-of-code mid-10" dangerouslySetInnerHTML={{ __html: props.html.theme }} />
<MicroPoint>Each code sample has the theme name as a class:</MicroPoint>
<Code code={shikiWrap(`<pre class="shiki dark-plus" style="..."`)} />
<MicroPoint>Giving you the chance to use CSS to hide the ones which should not be seen.</MicroPoint>
<Code code={props.html.cssSrc} />
<Point msg="Highlighting code in your sample can be done via codefence comments:" />
<TwoCode source={fakeCodeFence(props.html.highlightSrc, "{1, 3-4}")} output={props.html.highlightHTML.replace("// codefence: {1, 3-4}", "")} />
<MicroPoint>Shiki Twoslash uses CSS classes to set up the highlighting, so style-wise, it's all up to you.</MicroPoint>
<Point msg="Code blocks which are atomic is great, but can get repetitive in your markdown file. To avoid constantly repeating yourself, Shiki Twoslash has a simple includes system where you can create a hidden codeblock which is imported in parts into your code samples." />
<TwoCode source={props.html.includeHtml} output={props.html.includeHtmlRender} />
</article>
<article className="container border-red" id="integrations">
<h2>
<a href="#integrations">#</a>Chapter 3:
<br className="small-only" /> Integrations
</h2>
<Point msg="I built plugins for most of the big static site generators in the JavaScript ecosystem. These are production ready, but aside from Gatsby, haven't had a true stress test yet." />
<MicroPoint>The goal of these plugins is to get the markdown parsing set up, then you add the CSS and decide how you want to style it.</MicroPoint>
<Library
top="Gatsby plugin"
body="Add the package, edit your <code>gatsby-config.js</code>, add CSS."
npm="gatsby-remark-shiki-twoslash"
imgName="gatsby"
/>
<Library
right
top="Docusaurus preset"
body="Add the package, edit your <code>docusaurus.config</code>, add CSS."
npm="docusaurus-preset-shiki-twoslash"
imgName="docusaurus"
/>
<Library
top="VuePress plugin"
body="Add the package, edit your <code>./vuepress/config.ts</code>, add CSS ."
npm="vuepress-plugin-shiki-twoslash"
imgName="vue"
/>
<Library right top="Hexo plugin" body="Add the package, edit your <code>./config.yml</code> add CSS," npm="hexo-shiki-twoslash" imgName="h" />
<Library
top="11ty plugin"
body="Add the package, edit your <code>.eleventy.js</code>, add CSS."
npm="eleventy-plugin-shiki-twoslash"
imgName="11ty"
/>
<Point msg="These generator plugins are powered by two markdown engine plugins. Of those, <code>remark-shiki-twoslash</code> does most of the work." />
<a className="mid-6 lib" href="https://www.npmjs.com/package/remark-shiki-twoslash">
remark-shiki-twoslash
</a>
<a className="mid-6 lib" href="https://www.npmjs.com/package/markdown-it-shiki-twoslash">
markdown-it-shiki-twoslash
</a>
<MicroPoint>
You can use these libraries to set up in almost any JavaScript tool. There are examples in the{" "}
<a href="https://github.com/shikijs/twoslash/tree/main/examples">Shiki Twoslash monorepo</a> of working with Next.js, Elder.js and MDX.
<br />
<br />
I'm open to adding more examples.
</MicroPoint>
</article>
<article className="container border-yellow" id="tooling">
<h2>
<a href="#tooling">#</a>Chapter 4:
<br className="small-only" /> Tooling
</h2>
<Point msg="No markdown document is an island. To build out a corpus of markdown documents which rely on Twoslash there are some additional tools which might come in handy." />
<Tool
top="Twoslash CLI"
body="Render documents via the terminal and verify the code samples all pass. <a href='https://github.com/shikijs/twoslash/tree/main/site/examples'>This site</a> uses the CLI for all of the above code samples."
npm="twoslash-cli"
imgName="cli"
/>
<Tool
top="Twoslash VS Code"
body="Adds twoslash markup auto-complete to code samples, and offers a one-click link to a Twoslash repl with a reference on the TypeScript website."
npm="vscode-twoslash"
url="https://marketplace.visualstudio.com/items?itemName=Orta.vscode-twoslash"
imgName="vscode"
/>
<Tool
top="Twoslash Playground"
body="Share and create repros of Twoslash code samples. Contains a full API reference for Twoslash commands."
npm="Playground"
url="/twoslash/playground"
imgName="playground"
/>
</article>
<Split num={2} />
<article className="container border-blue" id="vision">
<h2>
<a href="#vision">#</a>Vision
</h2>
<Point msg="I intend for Shiki Twoslash to be a <a href='https://github.com/shikijs/twoslash/blob/main/VISION.md'>very long term project</a>. Initially created to power the TypeScript website and handbook, Shiki Twoslash has the potential for being a solid foundation for almost any website which describes JavaScript-y code." />
<MicroPoint>
Extracting Shiki Twoslash, documenting, improving and abstracting into generator plugins is work I do on my own time and if that is the sort of work
you want to see more of, consider sponsoring me on GitHub Sponsors
</MicroPoint>
<a className="mid-6 lib" href="https://github.com/sponsors/orta/">
github.com/sponsors/orta/
</a>
<MicroPoint>Have a good one!</MicroPoint>
<MicroPoint>
<img src="./img/us.jpg" width="480" height="361" />
</MicroPoint>
<MicroPoint>
Big thanks to <a href="https://www.instagram.com/gemmamcshane/">Danger</a>, <a href="https://www.instagram.com/outlook_hayesy/">Hayes</a>,{" "}
<a href="https://matsu.io">Pine</a> for Shiki, <a href="https://github.com/RyanCavanaugh">Ryan Cavanaugh</a> for the idea, starting code and
optimism, <a href="https://www.c82.net">Nicholas Rougeux</a> whose design work helped me{" "}
<a href="https://www.figma.com/file/OVzyeDLLDSvqCwgoaXsr0T/Twoslash?node-id=0%3A1">really nail</a> the aesthetic I wanted,{" "}
<a href="https://www.facebook.com/thehappychappo">The Happy Chappo</a> for art and finally all the folks who helped out build the TypeScript website
in Discord.
</MicroPoint>
<MicroPoint>
<a href="https://github.com/shikijs/twoslash">https://github.com/shikijs/twoslash</a>
</MicroPoint>
</article>
</main>
</body>
</>
);
}
function shikiWrap(code: string) {
return `<pre class="shiki " style="background-color: #FCF3D9; color: #111111; "><div class="language-id">ts</div><div class='code-container'><code style='white-space: pre-wrap'>${code}</code></div></pre>`;
}
function themes() {
const themes = [
"../shiki-twoslash",
"dark-plus",
"github-dark",
"github-light",
"light-plus",
"material-theme-darker",
"material-theme-default",
"material-theme-lighter",
"min-light",
"min-dark",
"monokai",
"slack-theme-ochin",
"solarized-light",
"nord",
"slack-theme-dark-mode",
"material-theme-ocean",
"solarized-dark",
"material-theme-palenight",
];
return themes.map((t) => '"' + t + '"').join(", ");
}
function fakeCodeFence(str: string, fence: string) {
return str
.replace('class="shiki', `class="not-shiki`)
.replace("<div class='code-container'><code>", `<div class='code-container'><code>\`\`\`ts twoslash ${fence}`)
.replace("<div class='line'></div></code", '<div class="line" style="color: #BB8700">```</div></code');
}
function cssForHiding() {
return `@media (prefers-color-scheme: light) {
.shiki.dark-plus {
display: none;
}
}
@media (prefers-color-scheme: dark) {
.shiki.light-plus {
display: none;
}
}
`;
}
const Point = (props: { msg: string }) => {
const msg = `<span class="eu">${props.msg[0]}</span>${props.msg.substring(1)}`;
return <p className="mid-6 has-funny-opening-letter" dangerouslySetInnerHTML={{ __html: msg }} />;
};
const MicroPoint = (props: { children: any }) => {
return <p className="mid-6">{props.children}</p>;
};
const Library = (props: { top: string; body: string; npm: string; right?: true; imgName: string }) => {
return (
<div className="mid-6 lib">
<div className={"lib-content " + (props.right ? "right" : "")}>
<img src={`./prints/${props.imgName}.png`} width="150" height="150" />
<div>
<h4>{props.top}</h4>
<p dangerouslySetInnerHTML={{ __html: props.body }} />
</div>
</div>
<a href={`https://www.npmjs.com/package/${props.npm}`}>{props.npm}</a>
</div>
);
};
const Tool = (props: { top: string; body: string; npm: string; url?: string; imgName: string }) => {
return (
<div className="mid-6 lib">
<h4>{props.top}</h4>
<p dangerouslySetInnerHTML={{ __html: props.body }} />
<img src={`./svgs/${props.imgName}.svg`} width="480" height="201" />
<a href={props.url || `https://www.npmjs.com/package/${props.npm}`}>{props.npm}</a>
</div>
);
};
const Code = (props: { code: string }) => <div className="mid-8" dangerouslySetInnerHTML={{ __html: props.code }} />;
const TwoCode = (props: { source: string; output: string }) => (
<div className="mid-10 code-split">
<div style={{ paddingRight: "5px" }}>
<span className="source">Source</span>
<div dangerouslySetInnerHTML={{ __html: props.source }} />
</div>
<div style={{ marginLeft: "5px" }}>
<span className="output">Output</span>
<div dangerouslySetInnerHTML={{ __html: props.output }} />
</div>
</div>
);
const Split = (props: { num: number }) => (
<div className="split">
<img src={`./svgs/split-${props.num}.svg`} width="630" height="81" />
</div>
);
// Grabs the code samples
export function getStaticProps() {
const fs = require("fs");
const get = (path: string) => fs.readFileSync(`examples/render/${path}.html`, "utf8");
return {
props: {
stats: JSON.parse(fs.readFileSync("script/stats.json", "utf8")),
html: {
basic: get("basic.ts"),
multiFileSrc: get("multi-file.ts_src"),
multiFileHTML: get("multi-file.ts"),
multiFileHighSrc: get("multi-file-highlight.ts_src"),
multiFileHighHTML: get("multi-file-highlight.ts"),
multiFileSnipSrc: get("multi-file-snip.ts_src"),
multiFileSnipHTML: get("multi-file-snip.ts"),
expressSrc: get("express.js_src"),
expressHTML: get("express.js"),
errorSrc: get("errors.ts_src"),
errorHTML: get("errors.ts"),
highlightSrc: get("highlight-1.ts_src"),
highlightHTML: get("highlight-1.ts"),
includeSrc: get("includes"),
includeHtmlRender: get("includes-render"),
includeHtml: get("includes"),
cssSrc: get("css"),
theme: get("theme.ts"),
},
},
};
} | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
lastWasStarboard?: boolean;
}
// O11N - Alphascape 3.0
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.AlphascapeV30,
timelineFile: 'o11n.txt',
timelineTriggers: [
{
id: 'O11N Blaster',
regex: /Blaster/,
beforeSeconds: 3,
condition: (data) => data.role === 'tank',
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Tank Tether',
de: 'Tank Verbindung',
fr: 'Lien tank',
ja: 'タンク 線を取る',
cn: '坦克接线远离人群',
ko: '탱 블래스터 징',
},
},
},
],
triggers: [
{
id: 'O11N Atomic Ray',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3286', source: 'Omega', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3286', source: 'Omega', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3286', source: 'Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3286', source: 'オメガ', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3286', source: '欧米茄', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3286', source: '오메가', capture: false }),
response: Responses.aoe(),
},
{
id: 'O11N Mustard Bomb',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3287', source: 'Omega' }),
netRegexDe: NetRegexes.startsUsing({ id: '3287', source: 'Omega' }),
netRegexFr: NetRegexes.startsUsing({ id: '3287', source: 'Oméga' }),
netRegexJa: NetRegexes.startsUsing({ id: '3287', source: 'オメガ' }),
netRegexCn: NetRegexes.startsUsing({ id: '3287', source: '欧米茄' }),
netRegexKo: NetRegexes.startsUsing({ id: '3287', source: '오메가' }),
response: Responses.tankBuster('alarm'),
},
{
// Ability IDs:
// Starboard 1: 3281
// Starboard 2: 3282
// Larboard 1: 3283
// Larboard 2: 3284
// For the cannons, match #1 and #2 for the first one. This is so
// that if a log entry for the first is dropped for some reason, it
// will at least say left/right for the second.
id: 'O11N Cannon Cleanup',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '328[13]', source: 'Omega', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '328[13]', source: 'Omega', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '328[13]', source: 'Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '328[13]', source: 'オメガ', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '328[13]', source: '欧米茄', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '328[13]', source: '오메가', capture: false }),
delaySeconds: 15,
run: (data) => delete data.lastWasStarboard,
},
{
id: 'O11N Starboard Cannon 1',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '328[12]', source: 'Omega', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '328[12]', source: 'Omega', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '328[12]', source: 'Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '328[12]', source: 'オメガ', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '328[12]', source: '欧米茄', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '328[12]', source: '오메가', capture: false }),
condition: (data) => data.lastWasStarboard === undefined,
response: Responses.goLeft(),
run: (data) => data.lastWasStarboard = true,
},
{
id: 'O11N Larboard Cannon 1',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '328[34]', source: 'Omega', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '328[34]', source: 'Omega', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '328[34]', source: 'Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '328[34]', source: 'オメガ', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '328[34]', source: '欧米茄', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '328[34]', source: '오메가', capture: false }),
condition: (data) => data.lastWasStarboard === undefined,
response: Responses.goRight(),
run: (data) => data.lastWasStarboard = false,
},
{
id: 'O11N Starboard Cannon 2',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3282', source: 'Omega', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3282', source: 'Omega', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3282', source: 'Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3282', source: 'オメガ', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3282', source: '欧米茄', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3282', source: '오메가', capture: false }),
condition: (data) => data.lastWasStarboard !== undefined,
alertText: (data, _matches, output) => {
if (data.lastWasStarboard)
return output.moveLeft!();
return output.stayLeft!();
},
outputStrings: {
moveLeft: {
en: 'Move (Left)',
de: 'Bewegen (Links)',
fr: 'Bougez (Gauche)',
ja: '動け (左へ)',
cn: '去左边',
ko: '이동 (왼쪽)',
},
stayLeft: {
en: 'Stay (Left)',
de: 'Stehenbleiben (Links)',
fr: 'Restez ici (Gauche)',
ja: 'そのまま (左に)',
cn: '呆在左边',
ko: '멈추기 (왼쪽)',
},
},
},
{
id: 'O11N Larboard Cannon 2',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3284', source: 'Omega', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3284', source: 'Omega', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3284', source: 'Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3284', source: 'オメガ', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3284', source: '欧米茄', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3284', source: '오메가', capture: false }),
condition: (data) => data.lastWasStarboard !== undefined,
alertText: (data, _matches, output) => {
if (data.lastWasStarboard)
return output.stayRight!();
return output.moveRight!();
},
outputStrings: {
stayRight: {
en: 'Stay (Right)',
de: 'Stehenbleiben (Rechts)',
fr: 'Restez ici (Droite)',
ja: 'そのまま (右に)',
cn: '呆在右边',
ko: '멈추기 (오른쪽)',
},
moveRight: {
en: 'Move (Right)',
de: 'Bewegen (Rechts)',
fr: 'Bougez (droite)',
ja: '動け (右へ)',
cn: '去右边',
ko: '이동 (오른쪽)',
},
},
},
{
id: 'O11N Ballistic Missile',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0065' }),
condition: Conditions.targetIsYou(),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Drop Fire Outside',
de: 'Feuer draußen ablegen',
fr: 'Déposez le feu à l\'extérieur',
cn: '把火放在外面',
ko: '불 장판 바깥으로 유도',
},
},
},
{
id: 'O11N Electric Slide',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '003E' }),
response: Responses.stackMarkerOn(),
},
{
id: 'O11N Delta Attack',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '327B', source: 'Omega', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '327B', source: 'Omega', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '327B', source: 'Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '327B', source: 'オメガ', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '327B', source: '欧米茄', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '327B', source: '오메가', capture: false }),
delaySeconds: 3,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Use duty action on Conductive Focus',
de: 'Benutze Spezialkommando auf "Ziel des Blitzstrahls"',
fr: 'Utilisez l\'action spéciale sur le Point de convergence électrique',
cn: '在雷力投射点上使用任务指令',
ko: '뇌력 투사 지점에 교란기 사용',
},
},
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Engaging Delta Attack protocol': 'Reinitialisiere Deltaprotokoll',
'Level Checker': 'Monitor',
'Omega': 'Omega',
'Rocket Punch': 'Raketenschlag',
},
'replaceText': {
'Atomic Ray': 'Atomstrahlung',
'Ballistic Impact': 'Ballistischer Einschlag',
'Ballistic Missile': 'Ballistische Rakete',
'Blaster': 'Blaster',
'Delta Attack': 'Delta-Attacke',
'Electric Slide': 'Elektrosturz',
'Executable': 'Programmstart',
'Flamethrower': 'Flammenwerfer',
'Force Quit': 'Erzwungenes Herunterfahren',
'Mustard Bomb': 'Senfbombe',
'Peripheral Synthesis': 'Ausdrucken',
'Program Loop': 'Programmschleife',
'Reformat': 'Optimierung',
'Reset': 'Zurücksetzen',
'Rush': 'Stürmen',
'Starboard/Larboard Cannon': 'Steuerbord/Backbord Kanone',
},
},
{
'locale': 'fr',
'replaceSync': {
'Engaging Delta Attack protocol': 'Nécessité d\'utiliser l\'attaque Delta',
'Level Checker': 'vérifiniveau',
'Omega': 'Oméga',
'Rocket Punch': 'Astéropoing',
},
'replaceText': {
'Atomic Ray': 'Rayon atomique',
'Ballistic Impact': 'Impact de missile',
'Ballistic Missile': 'Tir de missile',
'Blaster': 'Électrochoc',
'Delta Attack': 'Attaque Delta',
'Electric Slide': 'Glissement Oméga',
'Executable': 'Exécution de programme',
'Flamethrower': 'Lance-flammes',
'Force Quit': 'Interruption forcée',
'Mustard Bomb': 'Obus d\'ypérite',
'Peripheral Synthesis': 'Impression',
'Program Loop': 'Boucle de programme',
'Reformat': 'Optimisation',
'Reset': 'Réinitialisation',
'Rush': 'Ruée',
'Starboard/Larboard Cannon': 'Tribord/Bâbord',
},
},
{
'locale': 'ja',
'replaceSync': {
'Engaging Delta Attack protocol': 'デルタアタックの必要性を認定します',
'Level Checker': 'レベルチェッカー',
'Omega': 'オメガ',
'Rocket Punch': 'ロケットパンチ',
},
'replaceText': {
'Atomic Ray': 'アトミックレイ',
'Ballistic Impact': 'ミサイル着弾',
'Ballistic Missile': 'ミサイル発射',
'Blaster': 'ブラスター',
'Delta Attack': 'デルタアタック',
'Electric Slide': 'オメガスライド',
'Executable': 'プログラム実行',
'Flamethrower': '火炎放射',
'Force Quit': '強制終了',
'Mustard Bomb': 'マスタードボム',
'Peripheral Synthesis': 'プリントアウト',
'Program Loop': 'サークルプログラム',
'Reformat': '最適化',
'Reset': '初期化',
'Rush': '突進',
'Starboard/Larboard Cannon': '右舷/左舷・波動砲',
},
},
{
'locale': 'cn',
'replaceSync': {
'Engaging Delta Attack protocol': '认定有必要使用三角攻击。',
'Level Checker': '等级检测仪',
'Omega': '欧米茄',
'Rocket Punch': '火箭飞拳',
},
'replaceText': {
'Atomic Ray': '原子射线',
'Ballistic Impact': '导弹命中',
'Ballistic Missile': '导弹发射',
'Blaster': '冲击波',
'Delta Attack': '三角攻击',
'Electric Slide': '欧米茄滑跃',
'Executable': '运行程序',
'Flamethrower': '火焰喷射器',
'Force Quit': '强制结束',
'Mustard Bomb': '芥末爆弹',
'Peripheral Synthesis': '生成外设',
'Program Loop': '循环程序',
'Reformat': '最优化',
'Reset': '初始化',
'Rush': '突进',
'Starboard/Larboard Cannon': '右/左舷齐射·波动炮',
},
},
{
'locale': 'ko',
'replaceSync': {
'Engaging Delta Attack protocol': '델타 공격의 필요성을 인정합니다',
'Level Checker': '레벨 측정기',
'Omega': '오메가',
'Rocket Punch': '로켓 주먹',
},
'replaceText': {
'Atomic Ray': '원자 파동',
'Ballistic Impact': '미사일 착탄',
'Ballistic Missile': '미사일 발사',
'Blaster': '블래스터',
'Delta Attack': '델타 공격',
'Electric Slide': '오메가 슬라이드',
'Executable': '프로그램 실행',
'Flamethrower': '화염 방사',
'Force Quit': '강제 종료',
'Mustard Bomb': '겨자 폭탄',
'Peripheral Synthesis': '출력',
'Program Loop': '순환 프로그램',
'Reformat': '최적화',
'Reset': '초기화',
'Rush': '돌진',
'Starboard/Larboard Cannon': '좌/우현 사격 파동포',
},
},
],
};
export default triggerSet; | the_stack |
import { Context, Recogniser } from '.';
import match, { Match } from '../match';
/**
* Binary search implementation (recursive)
*/
function binarySearch(arr: number[], searchValue: number) {
const find = (
arr: number[],
searchValue: number,
left: number,
right: number
): number => {
if (right < left) return -1;
/*
int mid = mid = (left + right) / 2;
There is a bug in the above line;
Joshua Bloch suggests the following replacement:
*/
const mid = Math.floor((left + right) >>> 1);
if (searchValue > arr[mid]) return find(arr, searchValue, mid + 1, right);
if (searchValue < arr[mid]) return find(arr, searchValue, left, mid - 1);
return mid;
};
return find(arr, searchValue, 0, arr.length - 1);
}
// 'Character' iterated character class.
// Recognizers for specific mbcs encodings make their 'characters' available
// by providing a nextChar() function that fills in an instance of iteratedChar
// with the next char from the input.
// The returned characters are not converted to Unicode, but remain as the raw
// bytes (concatenated into an int) from the codepage data.
//
// For Asian charsets, use the raw input rather than the input that has been
// stripped of markup. Detection only considers multi-byte chars, effectively
// stripping markup anyway, and double byte chars do occur in markup too.
//
class IteratedChar {
charValue: number; // 1-4 bytes from the raw input data
index: number;
nextIndex: number;
error: boolean;
done: boolean;
constructor() {
this.charValue = 0; // 1-4 bytes from the raw input data
this.index = 0;
this.nextIndex = 0;
this.error = false;
this.done = false;
}
reset() {
this.charValue = 0;
this.index = -1;
this.nextIndex = 0;
this.error = false;
this.done = false;
}
nextByte(det: Context) {
if (this.nextIndex >= det.rawLen) {
this.done = true;
return -1;
}
const byteValue = det.rawInput[this.nextIndex++] & 0x00ff;
return byteValue;
}
}
/**
* Asian double or multi-byte - charsets.
* Match is determined mostly by the input data adhering to the
* encoding scheme for the charset, and, optionally,
* frequency-of-occurrence of characters.
*/
class mbcs implements Recogniser {
commonChars: number[] = [];
name() {
return 'mbcs';
}
/**
* Test the match of this charset with the input text data
* which is obtained via the CharsetDetector object.
*
* @param det The CharsetDetector, which contains the input text
* to be checked for being in this charset.
* @return Two values packed into one int (Damn java, anyhow)
* bits 0-7: the match confidence, ranging from 0-100
* bits 8-15: The match reason, an enum-like value.
*/
match(det: Context): Match | null {
let singleByteCharCount = 0, //TODO Do we really need this?
doubleByteCharCount = 0,
commonCharCount = 0,
badCharCount = 0,
totalCharCount = 0,
confidence = 0;
const iter = new IteratedChar();
detectBlock: {
for (iter.reset(); this.nextChar(iter, det); ) {
totalCharCount++;
if (iter.error) {
badCharCount++;
} else {
const cv = iter.charValue & 0xffffffff;
if (cv <= 0xff) {
singleByteCharCount++;
} else {
doubleByteCharCount++;
if (this.commonChars != null) {
// NOTE: This assumes that there are no 4-byte common chars.
if (binarySearch(this.commonChars, cv) >= 0) {
commonCharCount++;
}
}
}
}
if (badCharCount >= 2 && badCharCount * 5 >= doubleByteCharCount) {
// console.log('its here!')
// Bail out early if the byte data is not matching the encoding scheme.
break detectBlock;
}
}
if (doubleByteCharCount <= 10 && badCharCount == 0) {
// Not many multi-byte chars.
if (doubleByteCharCount == 0 && totalCharCount < 10) {
// There weren't any multibyte sequences, and there was a low density of non-ASCII single bytes.
// We don't have enough data to have any confidence.
// Statistical analysis of single byte non-ASCII characters would probably help here.
confidence = 0;
} else {
// ASCII or ISO file? It's probably not our encoding,
// but is not incompatible with our encoding, so don't give it a zero.
confidence = 10;
}
break detectBlock;
}
//
// No match if there are too many characters that don't fit the encoding scheme.
// (should we have zero tolerance for these?)
//
if (doubleByteCharCount < 20 * badCharCount) {
confidence = 0;
break detectBlock;
}
if (this.commonChars == null) {
// We have no statistics on frequently occurring characters.
// Assess confidence purely on having a reasonable number of
// multi-byte characters (the more the better
confidence = 30 + doubleByteCharCount - 20 * badCharCount;
if (confidence > 100) {
confidence = 100;
}
} else {
// Frequency of occurrence statistics exist.
const maxVal = Math.log(doubleByteCharCount / 4);
const scaleFactor = 90.0 / maxVal;
confidence = Math.floor(
Math.log(commonCharCount + 1) * scaleFactor + 10
);
confidence = Math.min(confidence, 100);
}
} // end of detectBlock:
return confidence == 0 ? null : match(det, this, confidence);
}
/**
* Get the next character (however many bytes it is) from the input data
* Subclasses for specific charset encodings must implement this function
* to get characters according to the rules of their encoding scheme.
*
* This function is not a method of class iteratedChar only because
* that would require a lot of extra derived classes, which is awkward.
* @param it The iteratedChar 'struct' into which the returned char is placed.
* @param det The charset detector, which is needed to get at the input byte data
* being iterated over.
* @return True if a character was returned, false at end of input.
*/
nextChar(iter: IteratedChar, det: Context): boolean {
return true;
}
}
/**
* Shift_JIS charset recognizer.
*/
export class sjis extends mbcs {
name() {
return 'Shift_JIS';
}
language() {
return 'ja';
}
// TODO: This set of data comes from the character frequency-
// of-occurrence analysis tool. The data needs to be moved
// into a resource and loaded from there.
commonChars = [
0x8140,
0x8141,
0x8142,
0x8145,
0x815b,
0x8169,
0x816a,
0x8175,
0x8176,
0x82a0,
0x82a2,
0x82a4,
0x82a9,
0x82aa,
0x82ab,
0x82ad,
0x82af,
0x82b1,
0x82b3,
0x82b5,
0x82b7,
0x82bd,
0x82be,
0x82c1,
0x82c4,
0x82c5,
0x82c6,
0x82c8,
0x82c9,
0x82cc,
0x82cd,
0x82dc,
0x82e0,
0x82e7,
0x82e8,
0x82e9,
0x82ea,
0x82f0,
0x82f1,
0x8341,
0x8343,
0x834e,
0x834f,
0x8358,
0x835e,
0x8362,
0x8367,
0x8375,
0x8376,
0x8389,
0x838a,
0x838b,
0x838d,
0x8393,
0x8e96,
0x93fa,
0x95aa,
];
nextChar(iter: IteratedChar, det: Context) {
iter.index = iter.nextIndex;
iter.error = false;
const firstByte = (iter.charValue = iter.nextByte(det));
if (firstByte < 0) return false;
if (firstByte <= 0x7f || (firstByte > 0xa0 && firstByte <= 0xdf))
return true;
const secondByte = iter.nextByte(det);
if (secondByte < 0) return false;
iter.charValue = (firstByte << 8) | secondByte;
if (
!(
(secondByte >= 0x40 && secondByte <= 0x7f) ||
(secondByte >= 0x80 && secondByte <= 0xff)
)
) {
// Illegal second byte value.
iter.error = true;
}
return true;
}
}
/**
* Big5 charset recognizer.
*/
export class big5 extends mbcs {
name() {
return 'Big5';
}
language() {
return 'zh';
}
// TODO: This set of data comes from the character frequency-
// of-occurrence analysis tool. The data needs to be moved
// into a resource and loaded from there.
commonChars = [
0xa140,
0xa141,
0xa142,
0xa143,
0xa147,
0xa149,
0xa175,
0xa176,
0xa440,
0xa446,
0xa447,
0xa448,
0xa451,
0xa454,
0xa457,
0xa464,
0xa46a,
0xa46c,
0xa477,
0xa4a3,
0xa4a4,
0xa4a7,
0xa4c1,
0xa4ce,
0xa4d1,
0xa4df,
0xa4e8,
0xa4fd,
0xa540,
0xa548,
0xa558,
0xa569,
0xa5cd,
0xa5e7,
0xa657,
0xa661,
0xa662,
0xa668,
0xa670,
0xa6a8,
0xa6b3,
0xa6b9,
0xa6d3,
0xa6db,
0xa6e6,
0xa6f2,
0xa740,
0xa751,
0xa759,
0xa7da,
0xa8a3,
0xa8a5,
0xa8ad,
0xa8d1,
0xa8d3,
0xa8e4,
0xa8fc,
0xa9c0,
0xa9d2,
0xa9f3,
0xaa6b,
0xaaba,
0xaabe,
0xaacc,
0xaafc,
0xac47,
0xac4f,
0xacb0,
0xacd2,
0xad59,
0xaec9,
0xafe0,
0xb0ea,
0xb16f,
0xb2b3,
0xb2c4,
0xb36f,
0xb44c,
0xb44e,
0xb54c,
0xb5a5,
0xb5bd,
0xb5d0,
0xb5d8,
0xb671,
0xb7ed,
0xb867,
0xb944,
0xbad8,
0xbb44,
0xbba1,
0xbdd1,
0xc2c4,
0xc3b9,
0xc440,
0xc45f,
];
nextChar(iter: IteratedChar, det: Context) {
iter.index = iter.nextIndex;
iter.error = false;
const firstByte = (iter.charValue = iter.nextByte(det));
if (firstByte < 0) return false;
// single byte character.
if (firstByte <= 0x7f || firstByte == 0xff) return true;
const secondByte = iter.nextByte(det);
if (secondByte < 0) return false;
iter.charValue = (iter.charValue << 8) | secondByte;
if (secondByte < 0x40 || secondByte == 0x7f || secondByte == 0xff)
iter.error = true;
return true;
}
}
/**
* EUC charset recognizers. One abstract class that provides the common function
* for getting the next character according to the EUC encoding scheme,
* and nested derived classes for EUC_KR, EUC_JP, EUC_CN.
*
* Get the next character value for EUC based encodings.
* Character 'value' is simply the raw bytes that make up the character
* packed into an int.
*/
function eucNextChar(iter: IteratedChar, det: Context) {
iter.index = iter.nextIndex;
iter.error = false;
let firstByte = 0;
let secondByte = 0;
let thirdByte = 0;
//int fourthByte = 0;
buildChar: {
firstByte = iter.charValue = iter.nextByte(det);
if (firstByte < 0) {
// Ran off the end of the input data
iter.done = true;
break buildChar;
}
if (firstByte <= 0x8d) {
// single byte char
break buildChar;
}
secondByte = iter.nextByte(det);
iter.charValue = (iter.charValue << 8) | secondByte;
if (firstByte >= 0xa1 && firstByte <= 0xfe) {
// Two byte Char
if (secondByte < 0xa1) {
iter.error = true;
}
break buildChar;
}
if (firstByte == 0x8e) {
// Code Set 2.
// In EUC-JP, total char size is 2 bytes, only one byte of actual char value.
// In EUC-TW, total char size is 4 bytes, three bytes contribute to char value.
// We don't know which we've got.
// Treat it like EUC-JP. If the data really was EUC-TW, the following two
// bytes will look like a well formed 2 byte char.
if (secondByte < 0xa1) {
iter.error = true;
}
break buildChar;
}
if (firstByte == 0x8f) {
// Code set 3.
// Three byte total char size, two bytes of actual char value.
thirdByte = iter.nextByte(det);
iter.charValue = (iter.charValue << 8) | thirdByte;
if (thirdByte < 0xa1) {
iter.error = true;
}
}
}
return iter.done == false;
}
/**
* The charset recognize for EUC-JP. A singleton instance of this class
* is created and kept by the public CharsetDetector class
*/
export class euc_jp extends mbcs {
name() {
return 'EUC-JP';
}
language() {
return 'ja';
}
// TODO: This set of data comes from the character frequency-
// of-occurrence analysis tool. The data needs to be moved
// into a resource and loaded from there.
commonChars = [
0xa1a1,
0xa1a2,
0xa1a3,
0xa1a6,
0xa1bc,
0xa1ca,
0xa1cb,
0xa1d6,
0xa1d7,
0xa4a2,
0xa4a4,
0xa4a6,
0xa4a8,
0xa4aa,
0xa4ab,
0xa4ac,
0xa4ad,
0xa4af,
0xa4b1,
0xa4b3,
0xa4b5,
0xa4b7,
0xa4b9,
0xa4bb,
0xa4bd,
0xa4bf,
0xa4c0,
0xa4c1,
0xa4c3,
0xa4c4,
0xa4c6,
0xa4c7,
0xa4c8,
0xa4c9,
0xa4ca,
0xa4cb,
0xa4ce,
0xa4cf,
0xa4d0,
0xa4de,
0xa4df,
0xa4e1,
0xa4e2,
0xa4e4,
0xa4e8,
0xa4e9,
0xa4ea,
0xa4eb,
0xa4ec,
0xa4ef,
0xa4f2,
0xa4f3,
0xa5a2,
0xa5a3,
0xa5a4,
0xa5a6,
0xa5a7,
0xa5aa,
0xa5ad,
0xa5af,
0xa5b0,
0xa5b3,
0xa5b5,
0xa5b7,
0xa5b8,
0xa5b9,
0xa5bf,
0xa5c3,
0xa5c6,
0xa5c7,
0xa5c8,
0xa5c9,
0xa5cb,
0xa5d0,
0xa5d5,
0xa5d6,
0xa5d7,
0xa5de,
0xa5e0,
0xa5e1,
0xa5e5,
0xa5e9,
0xa5ea,
0xa5eb,
0xa5ec,
0xa5ed,
0xa5f3,
0xb8a9,
0xb9d4,
0xbaee,
0xbbc8,
0xbef0,
0xbfb7,
0xc4ea,
0xc6fc,
0xc7bd,
0xcab8,
0xcaf3,
0xcbdc,
0xcdd1,
];
nextChar = eucNextChar;
}
/**
* The charset recognize for EUC-KR. A singleton instance of this class
* is created and kept by the public CharsetDetector class
*/
export class euc_kr extends mbcs {
name() {
return 'EUC-KR';
}
language() {
return 'ko';
}
// TODO: This set of data comes from the character frequency-
// of-occurrence analysis tool. The data needs to be moved
// into a resource and loaded from there.
commonChars = [
0xb0a1,
0xb0b3,
0xb0c5,
0xb0cd,
0xb0d4,
0xb0e6,
0xb0ed,
0xb0f8,
0xb0fa,
0xb0fc,
0xb1b8,
0xb1b9,
0xb1c7,
0xb1d7,
0xb1e2,
0xb3aa,
0xb3bb,
0xb4c2,
0xb4cf,
0xb4d9,
0xb4eb,
0xb5a5,
0xb5b5,
0xb5bf,
0xb5c7,
0xb5e9,
0xb6f3,
0xb7af,
0xb7c2,
0xb7ce,
0xb8a6,
0xb8ae,
0xb8b6,
0xb8b8,
0xb8bb,
0xb8e9,
0xb9ab,
0xb9ae,
0xb9cc,
0xb9ce,
0xb9fd,
0xbab8,
0xbace,
0xbad0,
0xbaf1,
0xbbe7,
0xbbf3,
0xbbfd,
0xbcad,
0xbcba,
0xbcd2,
0xbcf6,
0xbdba,
0xbdc0,
0xbdc3,
0xbdc5,
0xbec6,
0xbec8,
0xbedf,
0xbeee,
0xbef8,
0xbefa,
0xbfa1,
0xbfa9,
0xbfc0,
0xbfe4,
0xbfeb,
0xbfec,
0xbff8,
0xc0a7,
0xc0af,
0xc0b8,
0xc0ba,
0xc0bb,
0xc0bd,
0xc0c7,
0xc0cc,
0xc0ce,
0xc0cf,
0xc0d6,
0xc0da,
0xc0e5,
0xc0fb,
0xc0fc,
0xc1a4,
0xc1a6,
0xc1b6,
0xc1d6,
0xc1df,
0xc1f6,
0xc1f8,
0xc4a1,
0xc5cd,
0xc6ae,
0xc7cf,
0xc7d1,
0xc7d2,
0xc7d8,
0xc7e5,
0xc8ad,
];
nextChar = eucNextChar;
}
/**
* GB-18030 recognizer. Uses simplified Chinese statistics.
*/
export class gb_18030 extends mbcs {
name() {
return 'GB18030';
}
language() {
return 'zh';
}
/*
* Get the next character value for EUC based encodings.
* Character 'value' is simply the raw bytes that make up the character
* packed into an int.
*/
nextChar(iter: IteratedChar, det: Context) {
iter.index = iter.nextIndex;
iter.error = false;
let firstByte = 0;
let secondByte = 0;
let thirdByte = 0;
let fourthByte = 0;
buildChar: {
firstByte = iter.charValue = iter.nextByte(det);
if (firstByte < 0) {
// Ran off the end of the input data
iter.done = true;
break buildChar;
}
if (firstByte <= 0x80) {
// single byte char
break buildChar;
}
secondByte = iter.nextByte(det);
iter.charValue = (iter.charValue << 8) | secondByte;
if (firstByte >= 0x81 && firstByte <= 0xfe) {
// Two byte Char
if (
(secondByte >= 0x40 && secondByte <= 0x7e) ||
(secondByte >= 80 && secondByte <= 0xfe)
) {
break buildChar;
}
// Four byte char
if (secondByte >= 0x30 && secondByte <= 0x39) {
thirdByte = iter.nextByte(det);
if (thirdByte >= 0x81 && thirdByte <= 0xfe) {
fourthByte = iter.nextByte(det);
if (fourthByte >= 0x30 && fourthByte <= 0x39) {
iter.charValue =
(iter.charValue << 16) | (thirdByte << 8) | fourthByte;
break buildChar;
}
}
}
iter.error = true;
break buildChar;
}
}
return iter.done == false;
}
// TODO: This set of data comes from the character frequency-
// of-occurrence analysis tool. The data needs to be moved
// into a resource and loaded from there.
commonChars = [
0xa1a1,
0xa1a2,
0xa1a3,
0xa1a4,
0xa1b0,
0xa1b1,
0xa1f1,
0xa1f3,
0xa3a1,
0xa3ac,
0xa3ba,
0xb1a8,
0xb1b8,
0xb1be,
0xb2bb,
0xb3c9,
0xb3f6,
0xb4f3,
0xb5bd,
0xb5c4,
0xb5e3,
0xb6af,
0xb6d4,
0xb6e0,
0xb7a2,
0xb7a8,
0xb7bd,
0xb7d6,
0xb7dd,
0xb8b4,
0xb8df,
0xb8f6,
0xb9ab,
0xb9c9,
0xb9d8,
0xb9fa,
0xb9fd,
0xbacd,
0xbba7,
0xbbd6,
0xbbe1,
0xbbfa,
0xbcbc,
0xbcdb,
0xbcfe,
0xbdcc,
0xbecd,
0xbedd,
0xbfb4,
0xbfc6,
0xbfc9,
0xc0b4,
0xc0ed,
0xc1cb,
0xc2db,
0xc3c7,
0xc4dc,
0xc4ea,
0xc5cc,
0xc6f7,
0xc7f8,
0xc8ab,
0xc8cb,
0xc8d5,
0xc8e7,
0xc9cf,
0xc9fa,
0xcab1,
0xcab5,
0xcac7,
0xcad0,
0xcad6,
0xcaf5,
0xcafd,
0xccec,
0xcdf8,
0xceaa,
0xcec4,
0xced2,
0xcee5,
0xcfb5,
0xcfc2,
0xcfd6,
0xd0c2,
0xd0c5,
0xd0d0,
0xd0d4,
0xd1a7,
0xd2aa,
0xd2b2,
0xd2b5,
0xd2bb,
0xd2d4,
0xd3c3,
0xd3d0,
0xd3fd,
0xd4c2,
0xd4da,
0xd5e2,
0xd6d0,
];
} | the_stack |
export function log() {
console.log('log');
}
type MapKey = string|number;
type MapableArray = MapKey[];
export type TruthTable = { [string: string]: boolean;[number: number]: boolean };
/**
* Create a quick lookup map from list
*/
export function createMap(arr: MapableArray): TruthTable {
return arr.reduce((result: { [string: string]: boolean }, key: string) => {
result[key] = true;
return result;
}, <{ [string: string]: boolean }>{});
}
/**
* Create a quick lookup map from list
*/
export function createMapByKey<K extends MapKey,V>(arr: V[], getKey:(item:V)=>K): { [key:string]: V[]; [key:number]: V[]} {
var result: any = {};
arr.forEach(item => {
let key: any = getKey(item);
result[key] = result[key] ? result[key].concat(item) : [item];
})
return result;
}
/**
* Turns keys into values and values into keys
*/
export function reverseKeysAndValues(obj: { [key: string]: string | number, [key: number]: string | number }): { [key: string]: string } {
var toret = {};
Object.keys(obj).forEach(function(key) {
toret[obj[key]] = key;
});
return toret;
}
/** Sloppy but effective code to find distinct */
export function distinct(arr: string[]): string[] {
var map = createMap(arr);
return Object.keys(map);
}
export const uniq = distinct;
/**
* Values for dictionary
*/
export function values<V>(dict: { [key: string]: V;[key: number]: V }): V[] {
return Object.keys(dict).map(key => dict[key]);
}
/**
* Debounce
*/
var now = () => new Date().getTime();
export function debounce<T extends Function>(func: T, milliseconds: number, immediate = false): T {
var timeout, args, context, timestamp, result;
var wait = milliseconds;
var later = function() {
var last = now() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return <any>function() {
context = this;
args = arguments;
timestamp = now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
/**
* Like debounce but will also call if a state change is significant enough to not ignore silently
* Note:
* - Significant changes : the function is called *immediately* without debouncing (but still marked for future debouncing).
*/
export function triggeredDebounce<Arg>(config:{
func: (arg:Arg)=>void,
/** Only called after there is at least one `oldArg` */
mustcall: (newArg:Arg,oldArg:Arg)=>boolean,
milliseconds: number}): (arg:Arg) => void {
let lastArg, lastCallTimeStamp;
let hasALastArg = false; // true if we are `holding back` any previous arg
let pendingTimeout = null;
const later = function() {
const timeSinceLast = now() - lastCallTimeStamp;
if (timeSinceLast < config.milliseconds) {
if (pendingTimeout) {
clearTimeout(pendingTimeout);
pendingTimeout = null;
}
pendingTimeout = setTimeout(later, config.milliseconds - timeSinceLast);
} else {
config.func(lastArg);
hasALastArg = false;
}
};
return function(arg:Arg) {
const stateChangeSignificant = hasALastArg && config.mustcall(arg,lastArg);
if (stateChangeSignificant) {
config.func(lastArg);
}
lastArg = arg;
hasALastArg = true;
lastCallTimeStamp = now();
later();
};
};
export function throttle<T extends Function>(func: T, milliseconds: number, options?: { leading?: boolean; trailing?: boolean }): T {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
let gnow = now;
var later = function() {
previous = options.leading === false ? 0 : gnow();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = gnow();
if (!previous && options.leading === false) previous = now;
var remaining = milliseconds - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > milliseconds) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
} as any;
};
export function once<T extends Function>(func: T): T {
let ran = false;
let memo = undefined;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
} as any;
}
export function rangeLimited(args: { num: number, min: number, max: number, loopAround?: boolean }) {
let {num, min, max, loopAround} = args;
var limited = Math.max(Math.min(num, max), min);
if (loopAround && limited > num){
return max;
}
if (loopAround && limited < num){
return min;
}
return limited;
}
/**
* Is TypeSript or is JavaScript file checks
*/
export const isTs = (filePath: string, ext = getExt(filePath)) => {
return ext == 'ts' || ext == 'tsx';
}
export const isTsx = (filePath: string, ext = getExt(filePath)) => {
return ext == 'tsx';
}
export const isJs = (filePath: string, ext = getExt(filePath)) => {
return ext == 'js' || ext == 'jsx';
}
export const isJsOrTs = (filePath: string) => {
const ext = getExt(filePath);
return isJs(filePath, ext) || isTs(filePath, ext);
}
/** `/asdf/bar/j.ts` => `ts` */
export function getExt(filePath: string) {
let parts = filePath.split('.');
return parts[parts.length - 1].toLowerCase();
}
/**
* `/asdf/bar/j.ts` => `/asdf/bar/j`
* `/asdf/bar/j.d.ts` => `/asdf/bar/j.d`
*/
export function removeExt(filePath: string) {
const dot = filePath.lastIndexOf('.');
if (dot === -1) {
return filePath;
}
return filePath.substring(0, dot);
}
/**
* asdf/asdf:123 => asdf/asdf + 122
* Note: returned line is 0 based
*/
export function getFilePathLine(query: string) {
let [filePath,lineNum] = query.split(':');
let line = lineNum ? parseInt(lineNum) - 1 : 0;
line = line > 0 ? line : 0;
return { filePath, line };
}
/** `/asdf/bar/j.ts` => `j.ts` */
export function getFileName(fullFilePath:string){
let parts = fullFilePath.split('/');
return parts[parts.length - 1];
}
/** `/asdf/bar/j.ts` => `/asdf/bar` */
export function getDirectory(filePath: string): string {
let directory = filePath.substring(0, filePath.lastIndexOf("/"));
return directory;
}
/** Folder + filename only e.g. `/asdf/something/tsconfig.json` => `something/tsconfig.json` */
export function getDirectoryAndFileName(filePath:string): string {
let directoryPath = getDirectory(filePath);
let directoryName = getFileName(directoryPath);
let fileName = getFileName(filePath);
return `${directoryName}/${fileName}`;
}
/**
* shallow equality of sorted arrays
*/
export function arraysEqual<T>(a: T[], b: T[]): boolean {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length !== b.length) return false;
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
/** Creates a Guid (UUID v4) */
export function createId(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
/** Creates a Guid (UUID v4) */
export var createGuid = createId;
// Not optimized
export function selectMany<T>(arr: T[][]): T[] {
var result = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
result.push(arr[i][j]);
}
}
return result;
}
/** From `file://filePath` to `filePath` */
export function getFilePathFromUrl(url: string) {
let {filePath} = getFilePathAndProtocolFromUrl(url);
return filePath;
}
/** We consistently have tabs with protocol + filePath */
export function getFilePathAndProtocolFromUrl(url: string): {protocol: string; filePath:string}{
// TODO: error handling
let protocol = url.substr(0,url.indexOf('://'));
let filePath = url.substr((protocol + '://').length);
return {protocol, filePath};
}
export function getUrlFromFilePathAndProtocol(config:{protocol:string,filePath:string}){
return config.protocol + '://' + config.filePath;
}
/**
* Promise.resolve is something I call the time (allows you to take x|promise and return promise ... aka make sync prog async if needed)
*/
export var resolve: typeof Promise.resolve = Promise.resolve.bind(Promise);
/** Useful for various editor related stuff e.g. completions */
var punctuations = createMap([';', '{', '}', '(', ')', '.', ':', '<', '>', "'", '"']);
/** Does the prefix end in punctuation */
export var prefixEndsInPunctuation = (prefix: string) => prefix.length && prefix.trim().length && punctuations[prefix.trim()[prefix.trim().length - 1]];
/** String based enum pattern */
export function stringEnum(x){
// make values same as keys
Object.keys(x).map((key) => x[key] = key);
}
/**
* Just adds your intercept function to be called whenever the original function is called
* Calls your function *before* the original is called
*/
export function intercepted<T extends Function>(config: { context: any; orig: T; intercept: T }): T {
return function() {
config.intercept.apply(null, arguments);
return config.orig.apply(config.context, arguments);
} as any;
}
/**
* path.relative for browser
* from : https://github.com/substack/path-browserify/blob/master/index.js
* but modified to not depened on `path.resolve` as from and to are already resolved in our case
*/
export const relative = function(from:string, to:string) {
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
export const imageUrl = '/images';
const supportedImages = {
'svg': 'image/svg+xml',
'gif': 'image/gif',
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'bmp': 'image/bmp'
}
const imageExtensions = Object.keys(supportedImages);
/**
* Provides info on the image files we support
*/
export function isImage(url: string) {
return imageExtensions.some(ext => url.endsWith("." + ext));
}
export function getImageMimeType(filePath: string){
const ext = getExt(filePath);
return supportedImages[ext];
}
/**
* Great for find and replace
*/
export function findOptionsToQueryRegex(options: { query: string, isRegex: boolean, isFullWord: boolean, isCaseSensitive: boolean }): RegExp {
// Note that Code mirror only takes `query` string *tries* to detect case senstivity, regex on its own
// So simpler if we just convert options into regex, and then code mirror will happy use the regex as is
let str = options.query;
var query: RegExp;
/** This came from search.js in code mirror */
let defaultQuery = /x^/;
if (!options.isRegex){
// from CMs search.js
str = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
if (options.isFullWord){
str = `\\b${str}\\b`;
}
try {
query = new RegExp(str, options.isCaseSensitive ? "g" : "gi");
}
catch (e) {
query = defaultQuery;
}
if (query.test("")){
query = defaultQuery;
}
return query;
}
/**
* Quick and dirty pad left
*/
export function padLeft(str: string, paddingValue: number) {
let pad = ' ';
return pad.substring(0, paddingValue - str.length) + str;
}
/**
* Quick and dirty shallow extend
*/
export function extend<A>(a: A): A;
export function extend<A, B>(a: A, b: B): A & B;
export function extend<A, B, C>(a: A, b: B, c: C): A & B & C;
export function extend<A, B, C, D>(a: A, b: B, c: C, d: D): A & B & C & D;
export function extend(...args: any[]): any {
const newObj = {};
for (const obj of args) {
for (const key in obj) {
//copy all the fields
newObj[key] = obj[key];
}
}
return newObj;
};
/**
* Simple timer
*/
export function timer() {
let timeStart = new Date().getTime();
return {
/** <integer>s e.g 2s etc. */
get seconds() {
const seconds = Math.ceil((new Date().getTime() - timeStart) / 1000) + 's';
return seconds;
},
/** Milliseconds e.g. 2000ms etc. */
get ms() {
const ms = (new Date().getTime() - timeStart) + 'ms';
return ms;
}
}
}
/**
* Returns a nice conversion of milliseconds into seconds / mintues as needed
*/
export function formatMilliseconds(ms: number): string {
if (ms < 1000) return `${ms}ms`;
const s = ms / 1000;
if (s < 60) {
return `${s.toFixed(2)}s`;
}
const m = s / 60;
return `${m.toFixed(2)}min`
}
/**
* If you add a new schema make sure you download its schema as well
*/
export const supportedAutocompleteConfigFileNames: { [fileName: string]: boolean } = {
'tsconfig.json': true,
'package.json': true,
'tslint.json': true,
'alm.json': true,
}
/**
* Files for which we have autocomplete intelligence
*/
export function isSupportedConfigFileForAutocomplete(filePath: string): boolean {
const fileName = getFileName(filePath);
return !!supportedAutocompleteConfigFileNames[fileName];
}
export const supportedHoverConfigFileNames: { [fileName: string]: boolean } = {
'package.json': true,
}
/**
* Files for which we have hover intelligence
*/
export function isSupportedConfigFileForHover(filePath: string): boolean {
const fileName = getFileName(filePath);
return !!supportedHoverConfigFileNames[fileName];
}
/**
* Cancellation token
*/
export type CancellationToken = { cancel(): void, isCancelled: boolean };
export const cancellationToken = (): CancellationToken => {
let cancelled = false;
return {
get isCancelled(): boolean {
return cancelled;
},
cancel: () => cancelled = true
}
}
export const cancelled = "cancelled";
/**
* Cancellable For Each
*/
export function cancellableForEach<T>(config: {
items: T[],
cb: (item: T) => void,
cancellationToken: CancellationToken,
}): Promise<any> {
return new Promise((resolve,reject) => {
let index = 0;
const lookAtNext = () => {
// Completed?
if (index === config.items.length) {
resolve({});
}
// Aborted?
else if (config.cancellationToken.isCancelled) {
reject(cancelled);
}
// Next and schedule
else {
const nextItem = config.items[index++];
config.cb(nextItem);
// Yield the thread for a bit
setTimeout(lookAtNext);
}
}
lookAtNext();
});
}
/**
* https://github.com/facebook/react/issues/5465#issuecomment-157888325
*/
const makeCancelable = <T>(promise:Promise<T>) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve: any, reject) => {
promise.then((val) =>
hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
);
promise.catch((error) =>
hasCanceled_ ? reject({ isCanceled: true }) : reject(error)
);
});
return {
promise: wrappedPromise as Promise<T>,
cancel() {
hasCanceled_ = true;
},
};
};
/**
* For promise chains that might become invalid fast
*/
export function onlyLastCall<T>(call: () => Promise<T>) {
/**
* Kept the delay to 0 as I am using this in select list view
* and that really benifits from immediate feedback.
*/
const delay = 0;
let timeout: any;
let _resolve: any;
let _reject: any;
let _cancel: () => void = () => null;
const later = () => {
timeout = null;
let {promise, cancel} = makeCancelable(call());
_cancel = cancel;
promise
.then((res) => {
_resolve(res);
})
.catch((rej) => {
_reject(rej);
})
}
let trueCall = () => new Promise((resolve, reject) => {
if (timeout) {
clearTimeout(timeout);
}
// Cancel any pending
_cancel();
_resolve = resolve;
_reject = reject;
timeout = setTimeout(later, delay);
})
return trueCall;
}
/**
* Delay given ms
*/
export function delay(ms: number) {
return new Promise(res => setTimeout(res, ms));
} | the_stack |
import {mockBoutCaneloGGG1} from "boxrec-mocks";
import {WinLossDraw} from "../../boxrec.constants";
import {WeightDivision} from "../../champions/boxrec.champions.constants";
import {BoxingBoutOutcome, BoxrecPromoter} from "../boxrec.event.constants";
import {BoutPageLast6, BoxrecEventBoutOutput} from "./boxrec.event.bout.constants";
import {BoxrecPageEventBout} from "./boxrec.page.event.bout";
const testLast6: (last6Obj: BoutPageLast6, expectations: BoutPageLast6) => void =
(last6Obj: BoutPageLast6, expectations: BoutPageLast6): void => {
const {date, id, name, outcome, outcomeByWayOf} = last6Obj;
expect(name).toBe(expectations.name);
expect(id).toBe(expectations.id);
expect(date).toBe(expectations.date);
expect(outcome).toBe(expectations.outcome);
expect(outcomeByWayOf).toBe(expectations.outcomeByWayOf);
};
describe("class BoxrecPageEventBout", () => {
let caneloGGG1: BoxrecEventBoutOutput;
let caneloGGG1Fake: BoxrecPageEventBout;
beforeAll(() => {
caneloGGG1 = new BoxrecPageEventBout(mockBoutCaneloGGG1).output;
// create additional HTML mock so we can modify it for testing
let modifiedCaneloGGG1: string = mockBoutCaneloGGG1;
// change the ranking for the first boxer to be empty
modifiedCaneloGGG1 = modifiedCaneloGGG1.replace(/\>\d\</, "><");
caneloGGG1Fake = new BoxrecPageEventBout(modifiedCaneloGGG1);
});
describe("getter date", () => {
it("should give the date", () => {
expect(caneloGGG1.date).toBe("2017-09-16");
});
});
describe("getter rating", () => {
it("should return the rating of the bout", () => {
expect(caneloGGG1.rating).toBe(100);
});
});
describe("getter location", () => {
it("should return the venue", () => {
expect(caneloGGG1.location.venue).toEqual({id: 246559, name: "T-Mobile Arena"});
});
});
describe("getter division", () => {
it("should return the division of this bout", () => {
expect(caneloGGG1.division).toEqual(WeightDivision.middleweight);
});
});
describe("getter numberOfRounds", () => {
it("should return the total number of rounds", () => {
expect(caneloGGG1.numberOfRounds).toBe(12);
});
});
describe("getter titles", () => {
it("should give an array of titles on the line for this fight", () => {
expect(caneloGGG1.titles).toEqual([
{
id: "6/Middleweight",
name: "World Boxing Council World Middleweight Title",
},
{
id: "43/Middleweight",
name: "World Boxing Association Super World Middleweight Title",
},
{
id: "75/Middleweight",
name: "International Boxing Federation World Middleweight Title",
},
{
id: "189/Middleweight",
name: "International Boxing Organization World Middleweight Title",
supervisor: {
id: 403048,
name: "Ed Levine",
},
},
]);
});
});
describe("getter referee", () => {
// bug on BoxRec - https://github.com/boxing/boxrec/issues/171
xit("should return the id of the ref", () => {
expect(caneloGGG1.referee.id).toBe(400853);
});
it("should return the name of the ref", () => {
expect(caneloGGG1.referee.name).toBe("Kenny Bayless");
});
});
describe("getter judges", () => {
// because BoxRec is playing dangerously with `style` and no proper selectors, we'll test all judges
describe("first judge", () => {
// breaking down this because of this BoxRec bug - https://github.com/boxing/boxrec/issues/170
xit("should return the id", () => {
expect(caneloGGG1.judges[0].id).toBe(401967);
});
xit("should return the name", () => {
expect(caneloGGG1.judges[0].name).toBe("Adalaide Byrd");
});
xit("should return the scorecard", () => {
expect(caneloGGG1.judges[0].scorecard).toEqual([110, 118]);
});
});
// re-enable tests once resolved - https://github.com/boxing/boxrec/issues/170
xit("should return the id, name and scorecard of judges", () => {
expect(caneloGGG1.judges[1].id).toBe(401002);
expect(caneloGGG1.judges[1].name).toBe("Dave Moretti");
expect(caneloGGG1.judges[1].scorecard).toEqual([115, 113]);
});
// re-enable tests once resolved - https://github.com/boxing/boxrec/issues/170
xit("should return the id, name and scorecard of judges", () => {
expect(caneloGGG1.judges[2].id).toBe(402265);
expect(caneloGGG1.judges[2].name).toBe("Don Trella");
expect(caneloGGG1.judges[2].scorecard).toEqual([114, 114]);
});
});
describe("getter firstBoxerRanking", () => {
it("should be the first boxer's rating", () => {
expect(caneloGGG1.firstBoxerRanking).toBe(2);
});
it("should return null if cannot find the boxer's ranking", () => {
expect(caneloGGG1Fake.firstBoxerRanking).toBe(null);
});
});
describe("getter secondBoxerRanking", () => {
it("should be the second boxer's rating", () => {
expect(caneloGGG1.secondBoxerRanking).toBe(1);
});
});
describe("getter firstBoxerAge", () => {
it("should be the first boxer's age", () => {
expect(caneloGGG1.firstBoxerAge).toBe(35);
});
});
describe("getter secondBoxerAge", () => {
it("should be the second boxer's age", () => {
expect(caneloGGG1.secondBoxerAge).toBe(27);
});
});
describe("getter promoter", () => {
it("should return the first promoter", () => {
// todo should sort by id or name to keep consistency
const {company, id, name} = caneloGGG1.promoters.find(item => item.id === 8253) as BoxrecPromoter;
expect(id).toBe(8253);
expect(name).toBe("Oscar De La Hoya");
expect(company).toBe("Golden Boy Promotions");
});
it("should return the second promoter if they exist", () => {
// if this starts breaking, let's sort these values
const {company, id, name} = caneloGGG1.promoters[1];
expect(id).toBeGreaterThan(8252);
expect(name).not.toBeNull();
expect(company).not.toBeNull();
});
});
describe("getter firstBoxerStance", () => {
it("should return the stance", () => {
expect(caneloGGG1.firstBoxerStance).toBe("orthodox");
});
});
describe("getter secondBoxerStance", () => {
it("should return the stance", () => {
expect(caneloGGG1.secondBoxerStance).toBe("orthodox");
});
});
describe("getter firstBoxerHeight", () => {
it("should return the height of the boxer", () => {
expect(caneloGGG1.firstBoxerHeight).toEqual([5, 10.5, 179]);
});
});
describe("getter secondBoxerHeight", () => {
it("should return height of the boxer", () => {
expect(caneloGGG1.secondBoxerHeight).toEqual([5, 8, 173]);
});
});
describe("getter firstBoxerReach", () => {
it("should return reach of the boxer", () => {
expect(caneloGGG1.firstBoxerReach).toEqual([70, 178]);
});
});
describe("getter firstBoxerRecord", () => {
it("should return the win/loss/draw record of the first boxer at this time", () => {
const {win, loss, draw} = caneloGGG1.firstBoxerRecord;
expect(win).toBe(37);
expect(loss).toBe(0);
expect(draw).toBe(0);
});
});
describe("getter secondBoxerRecord", () => {
it("should return the win/loss/draw record of the second boxer at this time", () => {
const {win, loss, draw} = caneloGGG1.secondBoxerRecord;
expect(win).toBe(49);
expect(loss).toBe(1);
expect(draw).toBe(1);
});
});
describe("getter firstBoxerKOs", () => {
it("should return the number of KOs for this boxer at the time", () => {
expect(caneloGGG1.firstBoxerKOs).toBe(33);
});
});
describe("getter secondBoxerKOs", () => {
it("should return the number of KOs for this boxer at the time", () => {
expect(caneloGGG1.secondBoxerKOs).toBe(34);
});
});
describe("getter location", () => {
describe("location", () => {
it("should return the country", () => {
expect(caneloGGG1.location.location.country).toEqual({
id: "US",
name: "USA",
});
});
it("should return the region", () => {
expect(caneloGGG1.location.location.region).toEqual({
id: "NV",
name: "Nevada",
});
});
it("should return the town", () => {
expect(caneloGGG1.location.location.town).toEqual({
id: 20388,
name: "Las Vegas",
});
});
});
it("should return the venue", () => {
expect(caneloGGG1.location.venue).toEqual({
id: 246559,
name: "T-Mobile Arena",
});
});
});
describe("getter firstBoxerLast6", () => {
describe("array of last 6 boxers", () => {
it("should give the first boxer information", () => {
testLast6(caneloGGG1.firstBoxerLast6[0], {
date: "2017-03-18",
id: 432984,
name: "Daniel Jacobs",
outcome: WinLossDraw.win,
outcomeByWayOf: BoxingBoutOutcome.UD,
});
});
it("should give the second boxer information", () => {
testLast6(caneloGGG1.firstBoxerLast6[1], {
date: "2016-09-10",
id: 272717,
name: "Kell Brook",
outcome: WinLossDraw.win,
outcomeByWayOf: BoxingBoutOutcome.TKO,
});
});
});
});
describe("getter secondBoxerLast6", () => {
describe("array of last 6 boxers", () => {
it("should give the first boxer information", () => {
testLast6(caneloGGG1.secondBoxerLast6[0], {
date: "2017-05-06",
id: 214371,
name: "Julio Cesar Chavez Jr",
outcome: WinLossDraw.win,
outcomeByWayOf: BoxingBoutOutcome.UD,
});
});
it("should give the second boxer information", () => {
testLast6(caneloGGG1.secondBoxerLast6[1], {
date: "2016-09-17",
id: 466535,
name: "Liam Smith",
outcome: WinLossDraw.win,
outcomeByWayOf: BoxingBoutOutcome.KO,
});
});
});
});
describe("getter secondBoxerReach", () => {
it("should return reach of the boxer", () => {
expect(caneloGGG1.secondBoxerReach).toEqual([70.5, 179]);
});
});
describe("getter firstBoxerPointsBefore", () => {
it("should return the points before", () => {
expect(caneloGGG1.firstBoxerPointsBefore).toEqual(jasmine.any(Number));
});
});
describe("getter secondBoxerPointsBefore", () => {
it("should return the points before", () => {
expect(caneloGGG1.secondBoxerPointsBefore).toEqual(jasmine.any(Number));
});
});
describe("getter firstBoxerPointsAfter", () => {
it("should return the points after", () => {
expect(caneloGGG1.firstBoxerPointsAfter).toEqual(jasmine.any(Number));
});
});
describe("getter secondBoxerPointsAfter", () => {
it("should return the points after", () => {
expect(caneloGGG1.secondBoxerPointsAfter).toEqual(jasmine.any(Number));
});
});
describe("getter matchmakers", () => {
it("should return an array of matchmakers", () => {
expect(caneloGGG1.matchmakers[0].id).toBeGreaterThan(400000);
expect(caneloGGG1.matchmakers[0].name).not.toBeNull();
});
});
describe("getter firstBoxer", () => {
it("should return the name and id of the boxer", () => {
expect(caneloGGG1.firstBoxer.id).toBe(356831);
expect(caneloGGG1.firstBoxer.name).toBe("Gennady Golovkin");
});
});
describe("getter secondBoxer", () => {
it("should return the name and id of the boxer", () => {
expect(caneloGGG1.secondBoxer.id).toBe(348759);
expect(caneloGGG1.secondBoxer.name).toBe("Saul Alvarez");
});
});
describe("getter outcome", () => {
describe("when a bout is a draw", () => {
it("should return the outcome of the bout", () => {
expect(caneloGGG1.outcome.outcome).toBe(WinLossDraw.draw);
});
it("should have `boxer` values as `null`", () => {
expect(caneloGGG1.outcome.boxer.id).toBeNull();
expect(caneloGGG1.outcome.boxer.name).toBeNull();
});
it("should return `null` for `outcomeByWayOf`", () => {
expect(caneloGGG1.outcome.outcomeByWayOf).toBe(BoxingBoutOutcome.SD);
});
});
});
describe("getter doctors", () => {
it("should return an array of doctors", () => {
expect(caneloGGG1.doctors[0].id).toBeGreaterThan(41130);
expect(caneloGGG1.doctors[0].name).not.toBeNull();
});
});
}); | the_stack |
import * as am5 from "@amcharts/amcharts5";
import * as am5xy from "@amcharts/amcharts5/xy";
import * as am5radar from "@amcharts/amcharts5/radar";
import am5themes_Animated from "@amcharts/amcharts5/themes/Animated";
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
const root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/radar-chart/
const chart = root.container.children.push( am5radar.RadarChart.new(root, {
innerRadius: am5.percent(50),
panX: false,
panY: false,
wheelX: "panX",
wheelY: "zoomX",
maxTooltipDistance: 0,
layout: root.verticalLayout
}));
// Create axes and their renderers
// https://www.amcharts.com/docs/v5/charts/radar-chart/#Adding_axes
const yRenderer = am5radar.AxisRendererRadial.new(root, {
visible: false,
axisAngle: 90,
minGridDistance: 10,
inversed: true
});
yRenderer.labels.template.setAll({
textType: "circular",
textAlign: "center",
radius: -8
});
yRenderer.grid.template.set("visible", false);
const yAxis = chart.yAxes.push( am5xy.CategoryAxis.new(root, {
maxDeviation: 0,
renderer: yRenderer,
categoryField: "weekday"
}));
const xRenderer = am5radar.AxisRendererCircular.new(root, {
visible: false,
minGridDistance: 30
});
xRenderer.labels.template.setAll({
textType: "circular",
radius: 10
});
xRenderer.grid.template.set("visible", false);
const xAxis = chart.xAxes.push( am5xy.CategoryAxis.new(root, {
renderer: xRenderer,
categoryField: "hour"
}));
// Create series
// https://www.amcharts.com/docs/v5/charts/radar-chart/#Adding_series
const series = chart.series.push( am5radar.RadarColumnSeries.new(root, {
calculateAggregates: true,
stroke: am5.color(0xffffff),
clustered: false,
xAxis: xAxis,
yAxis: yAxis,
categoryXField: "hour",
categoryYField: "weekday",
valueField: "value"
}));
series.columns.template.setAll({
tooltipText: "{value}",
strokeOpacity: 1,
strokeWidth: 2,
width: am5.percent(100),
height: am5.percent(100)
});
series.columns.template.events.on("pointerover", (event) => {
let di = event.target.dataItem as any;
if (di) {
heatLegend.showValue(di.get("value", 0) as number);
}
});
series.events.on("datavalidated", () => {
heatLegend.set("startValue", series.getPrivate("valueHigh"));
heatLegend.set("endValue", series.getPrivate("valueLow"));
});
// Set up heat rules
// https://www.amcharts.com/docs/v5/concepts/settings/heat-rules/
series.set("heatRules", [{
target: series.columns.template,
min: am5.color(0xfffb77),
max: am5.color(0xfe131a),
dataField: "value",
key: "fill"
}]);
// Add heat legend
// https://www.amcharts.com/docs/v5/concepts/legend/heat-legend/
const heatLegend = chart.children.push( am5.HeatLegend.new(root, {
orientation: "horizontal",
endColor: am5.color(0xfffb77),
startColor: am5.color(0xfe131a)
}));
// Set data
// https://www.amcharts.com/docs/v5/charts/radar-chart/#Setting_data
const data = [{
hour: "12pm",
weekday: "Sunday",
value: 2990
}, {
hour: "1am",
weekday: "Sunday",
value: 2520
}, {
hour: "2am",
weekday: "Sunday",
value: 2334
}, {
hour: "3am",
weekday: "Sunday",
value: 2230
}, {
hour: "4am",
weekday: "Sunday",
value: 2325
}, {
hour: "5am",
weekday: "Sunday",
value: 2019
}, {
hour: "6am",
weekday: "Sunday",
value: 2128
}, {
hour: "7am",
weekday: "Sunday",
value: 2246
}, {
hour: "8am",
weekday: "Sunday",
value: 2421
}, {
hour: "9am",
weekday: "Sunday",
value: 2788
}, {
hour: "10am",
weekday: "Sunday",
value: 2959
}, {
hour: "11am",
weekday: "Sunday",
value: 3018
}, {
hour: "12am",
weekday: "Sunday",
value: 3154
}, {
hour: "1pm",
weekday: "Sunday",
value: 3172
}, {
hour: "2pm",
weekday: "Sunday",
value: 3368
}, {
hour: "3pm",
weekday: "Sunday",
value: 3464
}, {
hour: "4pm",
weekday: "Sunday",
value: 3746
}, {
hour: "5pm",
weekday: "Sunday",
value: 3656
}, {
hour: "6pm",
weekday: "Sunday",
value: 3336
}, {
hour: "7pm",
weekday: "Sunday",
value: 3292
}, {
hour: "8pm",
weekday: "Sunday",
value: 3269
}, {
hour: "9pm",
weekday: "Sunday",
value: 3300
}, {
hour: "10pm",
weekday: "Sunday",
value: 3403
}, {
hour: "11pm",
weekday: "Sunday",
value: 3323
}, {
hour: "12pm",
weekday: "Monday",
value: 3346
}, {
hour: "1am",
weekday: "Monday",
value: 2725
}, {
hour: "2am",
weekday: "Monday",
value: 3052
}, {
hour: "3am",
weekday: "Monday",
value: 3876
}, {
hour: "4am",
weekday: "Monday",
value: 4453
}, {
hour: "5am",
weekday: "Monday",
value: 3972
}, {
hour: "6am",
weekday: "Monday",
value: 4644
}, {
hour: "7am",
weekday: "Monday",
value: 5715
}, {
hour: "8am",
weekday: "Monday",
value: 7080
}, {
hour: "9am",
weekday: "Monday",
value: 8022
}, {
hour: "10am",
weekday: "Monday",
value: 8446
}, {
hour: "11am",
weekday: "Monday",
value: 9313
}, {
hour: "12am",
weekday: "Monday",
value: 9011
}, {
hour: "1pm",
weekday: "Monday",
value: 8508
}, {
hour: "2pm",
weekday: "Monday",
value: 8515
}, {
hour: "3pm",
weekday: "Monday",
value: 8399
}, {
hour: "4pm",
weekday: "Monday",
value: 8649
}, {
hour: "5pm",
weekday: "Monday",
value: 7869
}, {
hour: "6pm",
weekday: "Monday",
value: 6933
}, {
hour: "7pm",
weekday: "Monday",
value: 5969
}, {
hour: "8pm",
weekday: "Monday",
value: 5552
}, {
hour: "9pm",
weekday: "Monday",
value: 5434
}, {
hour: "10pm",
weekday: "Monday",
value: 5070
}, {
hour: "11pm",
weekday: "Monday",
value: 4851
}, {
hour: "12pm",
weekday: "Tuesday",
value: 4468
}, {
hour: "1am",
weekday: "Tuesday",
value: 3306
}, {
hour: "2am",
weekday: "Tuesday",
value: 3906
}, {
hour: "3am",
weekday: "Tuesday",
value: 4413
}, {
hour: "4am",
weekday: "Tuesday",
value: 4726
}, {
hour: "5am",
weekday: "Tuesday",
value: 4584
}, {
hour: "6am",
weekday: "Tuesday",
value: 5717
}, {
hour: "7am",
weekday: "Tuesday",
value: 6504
}, {
hour: "8am",
weekday: "Tuesday",
value: 8104
}, {
hour: "9am",
weekday: "Tuesday",
value: 8813
}, {
hour: "10am",
weekday: "Tuesday",
value: 9278
}, {
hour: "11am",
weekday: "Tuesday",
value: 10425
}, {
hour: "12am",
weekday: "Tuesday",
value: 10137
}, {
hour: "1pm",
weekday: "Tuesday",
value: 9290
}, {
hour: "2pm",
weekday: "Tuesday",
value: 9255
}, {
hour: "3pm",
weekday: "Tuesday",
value: 9614
}, {
hour: "4pm",
weekday: "Tuesday",
value: 9713
}, {
hour: "5pm",
weekday: "Tuesday",
value: 9667
}, {
hour: "6pm",
weekday: "Tuesday",
value: 8774
}, {
hour: "7pm",
weekday: "Tuesday",
value: 8649
}, {
hour: "8pm",
weekday: "Tuesday",
value: 9937
}, {
hour: "9pm",
weekday: "Tuesday",
value: 10286
}, {
hour: "10pm",
weekday: "Tuesday",
value: 9175
}, {
hour: "11pm",
weekday: "Tuesday",
value: 8581
}, {
hour: "12pm",
weekday: "Wednesday",
value: 8145
}, {
hour: "1am",
weekday: "Wednesday",
value: 7177
}, {
hour: "2am",
weekday: "Wednesday",
value: 5657
}, {
hour: "3am",
weekday: "Wednesday",
value: 6802
}, {
hour: "4am",
weekday: "Wednesday",
value: 8159
}, {
hour: "5am",
weekday: "Wednesday",
value: 8449
}, {
hour: "6am",
weekday: "Wednesday",
value: 9453
}, {
hour: "7am",
weekday: "Wednesday",
value: 9947
}, {
hour: "8am",
weekday: "Wednesday",
value: 11471
}, {
hour: "9am",
weekday: "Wednesday",
value: 12492
}, {
hour: "10am",
weekday: "Wednesday",
value: 9388
}, {
hour: "11am",
weekday: "Wednesday",
value: 9928
}, {
hour: "12am",
weekday: "Wednesday",
value: 9644
}, {
hour: "1pm",
weekday: "Wednesday",
value: 9034
}, {
hour: "2pm",
weekday: "Wednesday",
value: 8964
}, {
hour: "3pm",
weekday: "Wednesday",
value: 9069
}, {
hour: "4pm",
weekday: "Wednesday",
value: 8898
}, {
hour: "5pm",
weekday: "Wednesday",
value: 8322
}, {
hour: "6pm",
weekday: "Wednesday",
value: 6909
}, {
hour: "7pm",
weekday: "Wednesday",
value: 5810
}, {
hour: "8pm",
weekday: "Wednesday",
value: 5151
}, {
hour: "9pm",
weekday: "Wednesday",
value: 4911
}, {
hour: "10pm",
weekday: "Wednesday",
value: 4487
}, {
hour: "11pm",
weekday: "Wednesday",
value: 4118
}, {
hour: "12pm",
weekday: "Thursday",
value: 3689
}, {
hour: "1am",
weekday: "Thursday",
value: 3081
}, {
hour: "2am",
weekday: "Thursday",
value: 6525
}, {
hour: "3am",
weekday: "Thursday",
value: 6228
}, {
hour: "4am",
weekday: "Thursday",
value: 6917
}, {
hour: "5am",
weekday: "Thursday",
value: 6568
}, {
hour: "6am",
weekday: "Thursday",
value: 6405
}, {
hour: "7am",
weekday: "Thursday",
value: 8106
}, {
hour: "8am",
weekday: "Thursday",
value: 8542
}, {
hour: "9am",
weekday: "Thursday",
value: 8501
}, {
hour: "10am",
weekday: "Thursday",
value: 8802
}, {
hour: "11am",
weekday: "Thursday",
value: 9420
}, {
hour: "12am",
weekday: "Thursday",
value: 8966
}, {
hour: "1pm",
weekday: "Thursday",
value: 8135
}, {
hour: "2pm",
weekday: "Thursday",
value: 8224
}, {
hour: "3pm",
weekday: "Thursday",
value: 8387
}, {
hour: "4pm",
weekday: "Thursday",
value: 8218
}, {
hour: "5pm",
weekday: "Thursday",
value: 7641
}, {
hour: "6pm",
weekday: "Thursday",
value: 6469
}, {
hour: "7pm",
weekday: "Thursday",
value: 5441
}, {
hour: "8pm",
weekday: "Thursday",
value: 4952
}, {
hour: "9pm",
weekday: "Thursday",
value: 4643
}, {
hour: "10pm",
weekday: "Thursday",
value: 4393
}, {
hour: "11pm",
weekday: "Thursday",
value: 4017
}, {
hour: "12pm",
weekday: "Friday",
value: 4022
}, {
hour: "1am",
weekday: "Friday",
value: 3063
}, {
hour: "2am",
weekday: "Friday",
value: 3638
}, {
hour: "3am",
weekday: "Friday",
value: 3968
}, {
hour: "4am",
weekday: "Friday",
value: 4070
}, {
hour: "5am",
weekday: "Friday",
value: 4019
}, {
hour: "6am",
weekday: "Friday",
value: 4548
}, {
hour: "7am",
weekday: "Friday",
value: 5465
}, {
hour: "8am",
weekday: "Friday",
value: 6909
}, {
hour: "9am",
weekday: "Friday",
value: 7706
}, {
hour: "10am",
weekday: "Friday",
value: 7867
}, {
hour: "11am",
weekday: "Friday",
value: 8615
}, {
hour: "12am",
weekday: "Friday",
value: 8218
}, {
hour: "1pm",
weekday: "Friday",
value: 7604
}, {
hour: "2pm",
weekday: "Friday",
value: 7429
}, {
hour: "3pm",
weekday: "Friday",
value: 7488
}, {
hour: "4pm",
weekday: "Friday",
value: 7493
}, {
hour: "5pm",
weekday: "Friday",
value: 6998
}, {
hour: "6pm",
weekday: "Friday",
value: 5941
}, {
hour: "7pm",
weekday: "Friday",
value: 5068
}, {
hour: "8pm",
weekday: "Friday",
value: 4636
}, {
hour: "9pm",
weekday: "Friday",
value: 4241
}, {
hour: "10pm",
weekday: "Friday",
value: 3858
}, {
hour: "11pm",
weekday: "Friday",
value: 3833
}, {
hour: "12pm",
weekday: "Saturday",
value: 3503
}, {
hour: "1am",
weekday: "Saturday",
value: 2842
}, {
hour: "2am",
weekday: "Saturday",
value: 2808
}, {
hour: "3am",
weekday: "Saturday",
value: 2399
}, {
hour: "4am",
weekday: "Saturday",
value: 2280
}, {
hour: "5am",
weekday: "Saturday",
value: 2139
}, {
hour: "6am",
weekday: "Saturday",
value: 2527
}, {
hour: "7am",
weekday: "Saturday",
value: 2940
}, {
hour: "8am",
weekday: "Saturday",
value: 3066
}, {
hour: "9am",
weekday: "Saturday",
value: 3494
}, {
hour: "10am",
weekday: "Saturday",
value: 3287
}, {
hour: "11am",
weekday: "Saturday",
value: 3416
}, {
hour: "12am",
weekday: "Saturday",
value: 3432
}, {
hour: "1pm",
weekday: "Saturday",
value: 3523
}, {
hour: "2pm",
weekday: "Saturday",
value: 3542
}, {
hour: "3pm",
weekday: "Saturday",
value: 3347
}, {
hour: "4pm",
weekday: "Saturday",
value: 3292
}, {
hour: "5pm",
weekday: "Saturday",
value: 3416
}, {
hour: "6pm",
weekday: "Saturday",
value: 3131
}, {
hour: "7pm",
weekday: "Saturday",
value: 3057
}, {
hour: "8pm",
weekday: "Saturday",
value: 3227
}, {
hour: "9pm",
weekday: "Saturday",
value: 3060
}, {
hour: "10pm",
weekday: "Saturday",
value: 2855
}, {
hour: "11pm",
weekday: "Saturday",
value: 2625
}
]
series.data.setAll(data);
yAxis.data.setAll([
{ weekday: "Sunday" },
{ weekday: "Monday" },
{ weekday: "Tuesday" },
{ weekday: "Wednesday" },
{ weekday: "Thursday" },
{ weekday: "Friday" },
{ weekday: "Saturday" }
]);
xAxis.data.setAll([
{ hour: "12pm" },
{ hour: "1am" },
{ hour: "2am" },
{ hour: "3am" },
{ hour: "4am" },
{ hour: "5am" },
{ hour: "6am" },
{ hour: "7am" },
{ hour: "8am" },
{ hour: "9am" },
{ hour: "10am" },
{ hour: "11am" },
{ hour: "12am" },
{ hour: "1pm" },
{ hour: "2pm" },
{ hour: "3pm" },
{ hour: "4pm" },
{ hour: "5pm" },
{ hour: "6pm" },
{ hour: "7pm" },
{ hour: "8pm" },
{ hour: "9pm" },
{ hour: "10pm" },
{ hour: "11pm" }
]);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/#Forcing_appearance_animation#Forcing_appearance_animation
chart.appear(1000, 100); | the_stack |
module Kiwi.Components {
/**
* The Box Component is used to handle the various 'bounds' that each GameObject has.
* There are two main different types of bounds (Bounds and Hitbox) with each one having three variants (each one is a rectangle) depending on what you are wanting:
*
* RawBounds: The bounding box of the GameObject before rotation/scale.
*
* RawHitbox: The hitbox of the GameObject before rotation/scale. This can be modified to be different than the normal bounds but if not specified it will be the same as the raw bounds.
*
* Bounds: The bounding box of the GameObject after rotation/scale.
*
* Hitbox: The hitbox of the GameObject after rotation/scale. If you modified the raw hitbox then this one will be modified as well, otherwise it will be the same as the normal bounds.
*
* WorldBounds: The bounding box of the Entity using its world coordinates and after rotation/scale.
*
* WorldHitbox: The hitbox of the Entity using its world coordinates and after rotation/scale.
*
* @class Box
* @extends Kiwi.Component
* @namespace Kiwi.Components
* @constructor
* @param parent {Kiwi.Entity} The entity that this box belongs to.
* @param [x=0] {Number} Its position on the x axis
* @param [y=0] {Number} Its position on the y axis
* @param [width=0] {Number} The width of the box.
* @param [height=0] {Number} The height of the box.
* @return {Kiwi.Components.Box}
*/
export class Box extends Component {
constructor(parent: Entity, x: number = 0, y: number = 0, width: number = 0, height: number = 0) {
super(parent, 'Box');
this.entity = parent;
this._rawBounds = new Kiwi.Geom.Rectangle(x,y,width,height);
this._rawCenter = new Kiwi.Geom.Point(x + width / 2, y + height / 2);
this._rawHitbox = new Kiwi.Geom.Rectangle();
this._hitboxOffset = new Kiwi.Geom.Point();
this.hitbox = new Kiwi.Geom.Rectangle(0, 0, width, height);
this.autoUpdate = true;
this._scratchMatrix = new Kiwi.Geom.Matrix();
}
/**
* The entity that this box belongs to.
* @property entity
* @type Kiwi.Entity
* @public
*/
public entity: Kiwi.Entity;
/**
* The type of object that this is.
* @method objType
* @return {string} "Box"
* @public
*/
public objType() {
return "Box";
}
/**
* Controls whether the hitbox should update automatically to match the hitbox of the current cell on the entity this Box component is attached to (default behaviour).
* Or if the hitbox shouldn't auto update. Which will mean it will stay the same as the last value it had.
* This property is automatically set to 'false' when you override the hitboxes width/height, but you can set this to true afterwards.
*
* @property autoUpdate
* @type boolean
* @default true
* @private
*/
public autoUpdate: boolean = true;
/**
* Indicates whether or not this component needs re-rendering/updating or not.
* @property dirty
* @type boolean
* @public
* @deprecated in version 1.1.0 because the box always needed updating
*/
public dirty: boolean;
/**
* Contains offset point for the hitbox
* @property _hitboxOffset
* @type Kiwi.Geom.Point
* @private
*/
private _hitboxOffset: Kiwi.Geom.Point;
/**
* Returns the offset value of the hitbox as a point for the X/Y axis for the developer to use.
* This is without rotation or scaling.
* This is a READ ONLY property.
* @property hitboxOffset
* @type Kiwi.Geom.Point
* @public
*/
public get hitboxOffset(): Kiwi.Geom.Point {
if ( this.autoUpdate == true && this.entity.atlas !== null && this.entity.atlas.cells && this.entity.atlas.cells[ 0 ].hitboxes ) {
this._hitboxOffset.x =
this.entity.atlas.cells[this.entity.cellIndex].hitboxes[0].x || 0;
this._hitboxOffset.y =
this.entity.atlas.cells[this.entity.cellIndex].hitboxes[0].y || 0;
}
return this._hitboxOffset;
}
/**
* Contains the offset rectangle for the raw hitbox.
* @property _rawHitbox
* @type Kiwi.Geom.Rectangle
* @private
*/
private _rawHitbox: Kiwi.Geom.Rectangle;
/**
* Returns the raw hitbox rectangle for the developer to use.
* 'Raw' means where it would be without rotation or scaling.
* This is READ ONLY.
* @property rawHitbox
* @type Kiwi.Geom.Rectangle
* @public
*/
public get rawHitbox(): Kiwi.Geom.Rectangle {
this._rawHitbox.x = this.rawBounds.x + this.hitboxOffset.x;
this._rawHitbox.y = this.rawBounds.y + this.hitboxOffset.y;
//If the hitbox has not already been set, then update the width/height based upon the current cell that the entity has.
if (this.autoUpdate == true) {
var atlas = this.entity.atlas;
if ( atlas !== null && atlas.cells && atlas.cells[ 0 ].hitboxes ) {
this._rawHitbox.width = atlas.cells[ this.entity.cellIndex ].hitboxes[ 0 ].w;
this._rawHitbox.height = atlas.cells[ this.entity.cellIndex ].hitboxes[ 0 ].h;
} else {
this._rawHitbox.width = this.entity.width;
this._rawHitbox.height = this.entity.height;
}
}
return this._rawHitbox;
}
/**
* The transformed or 'normal' hitbox for the entity. This is its box after rotation/scale.
* @property _transformedHitbox
* @type Kiwi.Geom.Rectangle
* @private
*/
private _transformedHitbox: Kiwi.Geom.Rectangle;
/**
* The transformed 'world' hitbox for the entity. This is its box after rotation/scale.
* @property _worldHitbox
* @type Kiwi.Geom.Rectangle
* @private
*/
private _worldHitbox: Kiwi.Geom.Rectangle;
/**
* The 'normal' or transformed hitbox for the entity. This is its box after rotation/Kiwi.Geom.Rectangle.
* @property hitbox
* @type Kiwi.Geom.Rectangle
* @public
*/
public get hitbox(): Kiwi.Geom.Rectangle {
this._transformedHitbox = this._rotateHitbox(this.rawHitbox.clone());
return this._transformedHitbox;
}
public set hitbox(value: Kiwi.Geom.Rectangle) {
//Use custom hitbox defined by user.
this._hitboxOffset.x = value.x;
this._hitboxOffset.y = value.y;
this._rawHitbox = value;
this._rawHitbox.x += this._rawBounds.x;
this._rawHitbox.y += this._rawBounds.y;
this.autoUpdate = false;
}
/**
* Returns the transformed hitbox for the entity using its 'world' coordinates.
* This is READ ONLY.
* @property worldHitbox
* @type Kiwi.Geom.Rectangle
* @public
*/
public get worldHitbox(): Kiwi.Geom.Rectangle {
this._worldHitbox = this._rotateHitbox(this.rawHitbox.clone(), true);
return this._worldHitbox;
}
/**
* The 'raw' bounds of entity. This is its bounds before rotation/scale.
* This for property is only for storage of the values and should be accessed via the getter 'rawBounds' so that it can update.
*
* @property _rawBounds
* @type Kiwi.Geom.Rectangle
* @private
*/
private _rawBounds: Kiwi.Geom.Rectangle;
/**
* Returns the 'raw' bounds for this entity.
* This is READ ONLY.
* @property rawBounds
* @type Kiwi.Geom.Rectangle
* @public
*/
public get rawBounds(): Kiwi.Geom.Rectangle {
this._rawBounds.x = this.entity.x;
this._rawBounds.y = this.entity.y;
this._rawBounds.width = this.entity.width;
this._rawBounds.height = this.entity.height;
return this._rawBounds;
}
/**
* Contains the 'raw' center point for the bounds.
* @property Kiwi.Geom.Point
* @type Kiwi.Geom.Point
* @private
*/
private _rawCenter: Kiwi.Geom.Point;
/**
* Returns the raw center point of the box.
* This is READ ONLY.
* @property rawCenter
* @type Kiwi.Geom.Point
* @public
*/
public get rawCenter(): Kiwi.Geom.Point {
this._rawCenter.x = this.rawBounds.x + this.rawBounds.width / 2;
this._rawCenter.y = this.rawBounds.y + this.rawBounds.height / 2;
return this._rawCenter;
}
/**
* Scratch matrix used in geometry calculations
*
* @property _scratchMatrix
* @type Kiwi.Geom.Matrix
* @private
* @since 1.3.1
*/
private _scratchMatrix: Kiwi.Geom.Matrix;
/**
* Contains the center point after the box has been transformed.
* @property _transformedCenter
* @type Kiwi.Geom.Point
* @private
*/
private _transformedCenter: Kiwi.Geom.Point;
/**
* Returns the center point for the box after it has been transformed.
* World coordinates.
* This is READ ONLY.
* @property center
* @type Kiwi.Geom.Point
* @public
*/
public get center(): Kiwi.Geom.Point {
var m: Kiwi.Geom.Matrix = this.entity.transform.getConcatenatedMatrix();
this._transformedCenter = m.transformPoint(
new Kiwi.Geom.Point(
this.entity.width / 2 - this.entity.anchorPointX,
this.entity.height / 2 - this.entity.anchorPointY ) );
return this._transformedCenter;
}
/**
* Contains the transformed or 'normal' bounds for this entity.
* @property _transformedBounds
* @type Kiwi.Geom.Rectangle
* @private
*/
private _transformedBounds: Kiwi.Geom.Rectangle;
/**
* The 'world' transformed bounds for this entity.
* @property _worldBounds
* @type Kiwi.Geom.Rectangle
* @private
*/
private _worldBounds: Kiwi.Geom.Rectangle;
/**
* Returns the 'transformed' or 'normal' bounds for this box.
* This is READ ONLY.
* @property bounds
* @type Kiwi.Geom.Rectangle
* @public
*/
public get bounds(): Kiwi.Geom.Rectangle {
this._transformedBounds = this._rotateRect(this.rawBounds.clone());
return this._transformedBounds;
}
/**
* Returns the 'transformed' bounds for this entity using the world coodinates.
* This is READ ONLY.
* @property worldBounds
* @type Kiwi.Geom.Rectangle
* @public
*/
public get worldBounds(): Kiwi.Geom.Rectangle {
this._worldBounds = this._rotateRect(this.rawBounds.clone(), true);
return this._worldBounds;
}
/**
* Private internal method only. Used to calculate the transformed bounds after rotation/scale.
* @method _rotateRect
* @param rect {Kiwi.Geom.Rectangle}
* @param [useWorldCoords=false] {Boolean}
* @return {Kiwi.Geom.Rectangle}
* @private
*/
private _rotateRect(rect: Kiwi.Geom.Rectangle, useWorldCoords: boolean=false): Kiwi.Geom.Rectangle {
var out: Kiwi.Geom.Rectangle = new Kiwi.Geom.Rectangle();
var t: Kiwi.Geom.Transform = this.entity.transform;
var m: Kiwi.Geom.Matrix = this._scratchMatrix.copyFrom(
t.getConcatenatedMatrix() );
// Use world coordinates?
if( !useWorldCoords )
{
m.setTo(m.a, m.b, m.c, m.d, t.x + t.rotPointX, t.y + t.rotPointY);
}
out = this.extents(
m.transformPoint({ x: - t.rotPointX, y: - t.rotPointY }),
m.transformPoint({ x: - t.rotPointX + rect.width, y: - t.rotPointY }),
m.transformPoint({ x: - t.rotPointX + rect.width, y: - t.rotPointY + rect.height }),
m.transformPoint({ x: - t.rotPointX, y: - t.rotPointY + rect.height })
);
return out;
}
/**
* A private method that is used to calculate the transformed hitbox's coordinates after rotation.
* @method _rotateHitbox
* @param rect {Kiwi.Geom.Rectangle}
* @param [useWorldCoords=false] {Boolean}
* @return {Kiwi.Geom.Rectangle}
* @private
*/
private _rotateHitbox(rect: Kiwi.Geom.Rectangle, useWorldCoords: boolean=false): Kiwi.Geom.Rectangle {
var out: Kiwi.Geom.Rectangle = new Kiwi.Geom.Rectangle();
var t: Kiwi.Geom.Transform = this.entity.transform;
var m: Kiwi.Geom.Matrix = this._scratchMatrix.copyFrom(
t.getConcatenatedMatrix() );
//Use world coordinates?
if( !useWorldCoords )
{
m.setTo(m.a, m.b, m.c, m.d, t.x + t.rotPointX, t.y + t.rotPointY);
}
out = this.extents(
m.transformPoint({ x: - t.rotPointX + this._hitboxOffset.x, y: - t.rotPointY + this._hitboxOffset.y }),
m.transformPoint({ x: - t.rotPointX + rect.width + this._hitboxOffset.x, y: - t.rotPointY + this._hitboxOffset.y }),
m.transformPoint({ x: - t.rotPointX + rect.width + this._hitboxOffset.x, y: - t.rotPointY + rect.height + this._hitboxOffset.y}),
m.transformPoint({ x: - t.rotPointX + this._hitboxOffset.x, y: - t.rotPointY + rect.height + this._hitboxOffset.y })
);
return out;
}
/**
* Draws the various bounds on a context that is passed. Useful for debugging and using in combination with the debug canvas.
* @method draw
* @param ctx {CanvasRenderingContext2D} Context of the canvas that this box component is to be rendered on top of.
* @param [camera] {Kiwi.Camera} A camera that should be taken into account before rendered. This is the default camera by default.
* @public
*/
public draw(ctx: CanvasRenderingContext2D, camera: Kiwi.Camera = this.game.cameras.defaultCamera) {
var t: Kiwi.Geom.Transform = this.entity.transform;
var ct: Kiwi.Geom.Transform = camera.transform;
// Draw raw bounds and raw center
ctx.strokeStyle = "red";
ctx.fillRect(this.rawCenter.x + ct.x - 1, this.rawCenter.y + ct.y - 1, 3, 3);
ctx.strokeRect(t.x + ct.x + t.rotPointX - 3, t.y + ct.y + t.rotPointY - 3, 7, 7);
// Draw bounds
ctx.strokeStyle = "blue";
ctx.strokeRect(this.bounds.x + ct.x, this.bounds.y + ct.y, this.bounds.width, this.bounds.height);
// Draw hitbox
ctx.strokeStyle = "green";
ctx.strokeRect(this.hitbox.x + ct.x, this.hitbox.y + ct.y, this.hitbox.width, this.hitbox.height);
// Draw raw hitbox
ctx.strokeStyle = "white";
ctx.strokeRect(this.rawHitbox.x + ct.x, this.rawHitbox.y + ct.y, this.rawHitbox.width, this.rawHitbox.height);
// Draw world bounds
ctx.strokeStyle = "purple";
ctx.strokeRect(this.worldBounds.x, this.worldBounds.y, this.worldBounds.width, this.worldBounds.height);
// Draw world hitbox
ctx.strokeStyle = "cyan";
ctx.strokeRect(this.worldHitbox.x, this.worldHitbox.y, this.worldHitbox.width, this.worldHitbox.height);
}
/**
* Method which takes four Points and then converts it into a Rectangle, which represents the area those points covered.
* The points passed can be maybe in any order, as the are checked for validity first.
*
* @method extents
* @param topLeftPoint {Kiwi.Geom.Point} The top left Point that the Rectangle should have.
* @param topRightPoint {Kiwi.Geom.Point} The top right Point that the Rectangle should have.
* @param bottomRightPoint {Kiwi.Geom.Point} The bottom right Point that the Rectangle should have.
* @param bottomLeftPoint {Kiwi.Geom.Point} The bottom left Point that the Rectangle should have.
* @return {Kiwi.Geom.Rectangle} The new Rectangle that represents the area the points covered.
* @return Rectangle
*/
public extents(topLeftPoint:Kiwi.Geom.Point, topRightPoint:Kiwi.Geom.Point, bottomRightPoint:Kiwi.Geom.Point, bottomLeftPoint:Kiwi.Geom.Point):Kiwi.Geom.Rectangle {
var left: number = Math.min(topLeftPoint.x, topRightPoint.x, bottomRightPoint.x, bottomLeftPoint.x);
var right: number = Math.max(topLeftPoint.x, topRightPoint.x, bottomRightPoint.x, bottomLeftPoint.x);
var top: number = Math.min(topLeftPoint.y, topRightPoint.y, bottomRightPoint.y, bottomLeftPoint.y);
var bottom: number = Math.max(topLeftPoint.y, topRightPoint.y, bottomRightPoint.y, bottomLeftPoint.y);
return new Kiwi.Geom.Rectangle(left, top, right - left, bottom - top);
}
/**
* Destroys this component and all of the links it may have to other objects.
* @method destroy
* @public
*/
public destroy() {
super.destroy();
delete this.entity;
}
}
} | the_stack |
import { component, ComponentBlock, fields } from './DocumentEditor/component-blocks/api';
import { Relationships } from './DocumentEditor/relationship';
import { defaultDocumentFeatures, makeEditor, jsx } from './DocumentEditor/tests/utils';
import { PropValidationError, validateAndNormalizeDocument } from './validation';
// note this is just about ensuring things fail validation
// we already test that the correct input succeeds on validation in all of the other tests
// because the test utils run validation
const relationships: Relationships = {
one: { kind: 'prop', listKey: 'Post', many: false, selection: 'somethine' },
inline: {
kind: 'inline',
label: 'Inline',
listKey: 'Post',
selection: `something`,
},
many: { kind: 'prop', listKey: 'Post', many: true, selection: 'somethine' },
};
const componentBlocks: Record<string, ComponentBlock> = {
basic: component({
component: () => null,
label: '',
props: { prop: fields.text({ label: '' }) },
}),
relationship: component({
component: () => null,
label: '',
props: {
one: fields.relationship({ label: '', relationship: 'one' }),
many: fields.relationship({ label: '', relationship: 'many' }),
},
}),
relationshipSpecifiedInPropThatDoesNotExist: component({
component: () => null,
label: '',
props: {
prop: fields.relationship({ label: '', relationship: 'doesNotExist' }),
},
}),
relationshipSpecifiedInPropIsWrongKind: component({
component: () => null,
label: '',
props: {
prop: fields.relationship({ label: '', relationship: 'inline' }),
},
}),
object: component({
component: () => null,
label: '',
props: {
prop: fields.object({
prop: fields.text({ label: '' }),
}),
},
}),
conditional: component({
component: () => null,
label: '',
props: {
prop: fields.conditional(fields.checkbox({ label: '' }), {
true: fields.text({ label: '' }),
false: fields.child({ kind: 'inline', placeholder: '' }),
}),
},
}),
};
const validate = (val: unknown) => {
try {
const node = validateAndNormalizeDocument(
val,
defaultDocumentFeatures,
componentBlocks,
relationships
);
return makeEditor(<editor>{node}</editor>, {
componentBlocks,
relationships,
skipRenderingDOM: true,
});
} catch (err) {
return err;
}
};
expect.addSnapshotSerializer({
test(val) {
return val instanceof PropValidationError;
},
serialize(val) {
return `PropValidationError ${JSON.stringify(val.message)} ${JSON.stringify(val.path)}`;
},
});
test('invalid structure', () => {
expect(validate({})).toMatchInlineSnapshot(`[Error: Invalid document structure]`);
});
test('bad link', () => {
expect(
validate([
{
type: 'paragraph',
children: [
{ type: 'link', href: 'javascript:doBadThings()', children: [{ text: 'some text' }] },
],
},
])
).toMatchInlineSnapshot(`[Error: Invalid document structure]`);
});
test('excess properties', () => {
expect(
validate([
{
type: 'paragraph',
children: [
{
type: 'link',
somethingElse: true,
href: 'https://keystonejs.com',
children: [{ text: 'something' }],
},
],
},
])
).toMatchInlineSnapshot(`[Error: Invalid document structure]`);
});
test('relationships that do not exist in the allowed relationships are normalized away', () => {
expect(
validate([
{
type: 'paragraph',
children: [
{ text: 'something' },
{
type: 'relationship',
relationship: 'doesNotExist',
data: { id: 'an-id' },
children: [{ text: '' }],
},
{ text: 'something' },
],
},
])
).toMatchInlineSnapshot(`
<editor>
<paragraph>
<text>
somethingan-id (doesNotExist:an-id)something
</text>
</paragraph>
</editor>
`);
});
test('inline relationships not of kind inline are normalized away', () => {
expect(
validate([
{
type: 'paragraph',
children: [
{ text: 'something' },
{
type: 'relationship',
relationship: 'many',
data: { id: 'an-id' },
children: [{ text: '' }],
},
{ text: 'something' },
],
},
])
).toMatchInlineSnapshot(`
<editor>
<paragraph>
<text>
somethingan-id (many:an-id)something
</text>
</paragraph>
</editor>
`);
});
test('label and data in inline relationships are stripped', () => {
expect(
validate([
{
type: 'paragraph',
children: [
{ text: 'something' },
{
type: 'relationship',
relationship: 'inline',
data: { id: 'an-id', label: 'something', data: { wow: true } },
children: [{ text: '' }],
},
{ text: 'something' },
],
},
])
).toMatchInlineSnapshot(`
<editor>
<paragraph>
<text>
something
</text>
<relationship
@@isInline={true}
@@isVoid={true}
data={
Object {
"data": undefined,
"id": "an-id",
"label": undefined,
}
}
relationship="inline"
>
<text>
</text>
</relationship>
<text>
something
</text>
</paragraph>
</editor>
`);
});
test('label and data in relationship props are stripped', () => {
expect(
validate([
{
type: 'component-block',
props: {
one: { id: 'some-id', label: 'some label', data: { something: true } },
many: [
{ id: 'some-id', label: 'some label', data: { something: true } },
{ id: 'another-id', label: 'another label', data: { something: false } },
],
},
component: 'relationship',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(`
<editor>
<component-block
component="relationship"
props={
Object {
"many": Array [
Object {
"id": "some-id",
},
Object {
"id": "another-id",
},
],
"one": Object {
"id": "some-id",
},
}
}
>
<component-inline-prop>
<text>
</text>
</component-inline-prop>
</component-block>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('array in to-one relationship', () => {
expect(
validate([
{
type: 'component-block',
props: {
one: [],
many: [
{ id: 'some-id', label: 'some label', data: { something: true } },
{ id: 'another-id', label: 'another label', data: { something: false } },
],
},
component: 'relationship',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(`PropValidationError "Invalid relationship value" ["one"]`);
});
test('single item in many relationship', () => {
expect(
validate([
{
type: 'component-block',
props: {
one: null,
many: { id: 'some-id', label: 'some label', data: { something: true } },
},
component: 'relationship',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(`PropValidationError "Invalid relationship value" ["many"]`);
});
test('missing relationships', () => {
expect(
validate([
{
type: 'component-block',
props: {},
component: 'relationship',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(`PropValidationError "Invalid relationship value" ["one"]`);
});
test('relationship specified in prop does not exist', () => {
expect(
validate([
{
type: 'component-block',
props: {
prop: null,
},
component: 'relationshipSpecifiedInPropThatDoesNotExist',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(
`PropValidationError "Relationship prop specifies the relationship \\"doesNotExist\\" but it is not an allowed relationship" ["prop"]`
);
});
test("relationship specified in prop is not kind: 'prop'", () => {
expect(
validate([
{
type: 'component-block',
props: {
prop: null,
},
component: 'relationshipSpecifiedInPropIsWrongKind',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(
`PropValidationError "Unexpected relationship \\"inline\\" of kind \\"inline\\" where the kind should be \\"prop\\"" ["prop"]`
);
});
test('excess prop', () => {
expect(
validate([
{
type: 'component-block',
props: { something: true, prop: '' },
component: 'basic',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(
`PropValidationError "Key on object value \\"something\\" is not allowed" []`
);
});
test('form prop validation', () => {
expect(
validate([
{
type: 'component-block',
props: { prop: {} },
component: 'basic',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(`PropValidationError "Invalid form prop value" ["prop"]`);
});
test('object prop of wrong type', () => {
expect(
validate([
{
type: 'component-block',
props: { prop: false },
component: 'object',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(`PropValidationError "Object value must be an object" ["prop"]`);
});
test('form prop failure inside of object', () => {
expect(
validate([
{
type: 'component-block',
props: { prop: { prop: false } },
component: 'object',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(`PropValidationError "Invalid form prop value" ["prop","prop"]`);
});
test('non-object value in conditional prop', () => {
expect(
validate([
{
type: 'component-block',
props: { prop: '' },
component: 'conditional',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(`PropValidationError "Conditional value must be an object" ["prop"]`);
});
test('excess prop in conditional object', () => {
expect(
validate([
{
type: 'component-block',
props: { prop: { discriminant: false, excess: true } },
component: 'conditional',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(
`PropValidationError "Conditional value only allows keys named \\"discriminant\\" and \\"value\\", not \\"excess\\"" ["prop"]`
);
});
test('validation failure on discriminant', () => {
expect(
validate([
{
type: 'component-block',
props: { prop: { discriminant: '' } },
component: 'conditional',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(`PropValidationError "Invalid form prop value" ["prop","discriminant"]`);
});
test('validation failure on value', () => {
expect(
validate([
{
type: 'component-block',
props: { prop: { discriminant: true, value: false } },
component: 'conditional',
children: [],
},
{
type: 'paragraph',
children: [{ text: '' }],
},
])
).toMatchInlineSnapshot(`PropValidationError "Invalid form prop value" ["prop","value"]`);
}); | the_stack |
import React from 'react'
import { store } from '../../../store'
import { StoreContext } from 'storeon/react'
import { object, withKnobs, select, boolean, text, files } from '@storybook/addon-knobs'
import uiManagmentApi from '../../../api/uiManagment/uiManagmentApi'
import stylesApi from '../../../api/styles/stylesApi'
// import { darkTheme, lightTheme } from '../../../configs/styles'
// import { ru, en } from '../../../configs/languages'
import languagesApi from '../../../api/languages/languagesApi'
// import { settings } from '../../../configs/settings'
import settingsApi from '../../../api/settings/settingsApi'
import Header from '../Header'
import { withInfo } from '@storybook/addon-info'
import info from './HeaderInfo.md'
import { iconsList } from '../../../configs/icons'
import '../../../styles/storyBookContainer.css'
// import Logo from '../../../assets/Logo.png'
export default {
title: 'Header',
decorators: [withKnobs, withInfo],
parameters: {
info: {
text: info,
source: false,
propTables: false,
},
},
}
const groupUIManagment = 'UIManagment'
const groupStyles = 'Styles'
const groupLanguages = 'Languages'
const groupSettings = 'Settings'
// const storyDarkStyles = {
// mainContainer: {
// display: 'flex',
// width: '100%',
// alignItems: 'center',
// color: 'white',
// justifyContent: 'space-between',
// fontSize: '30px',
// backgroundColor: '#373737',
// padding: '8px',
// borderRadius: '15px',
// },
// avatarContainer: {},
// titleContainer: {},
// buttonsContainer: {
// display: 'flex',
// flexDirection: 'row-reverse',
// alignItems: 'center',
// width: '30%',
// marginRight: '8%',
// marginLeft: '16%',
// },
// resetButton: {
// backgroundColor: '#373737',
// border: 'none',
// display: 'flex',
// justifyContent: 'space-around',
// width: '50%',
// outline: 'none',
// color: 'white',
// fontSize: '12px',
// },
// settingsButton: {
// backgroundColor: '#373737',
// border: 'none',
// display: 'flex',
// justifyContent: 'space-around',
// outline: 'none',
// width: '50%',
// color: 'white',
// fontSize: '12px',
// },
// image: {
// width: '50px',
// height: '50px',
// },
// }
// const storyLightStyles = {
// mainContainer: {
// display: 'flex',
// width: '100%',
// alignItems: 'center',
// color: 'white',
// justifyContent: 'space-between',
// fontSize: '30px',
// backgroundColor: '#4a76a8',
// padding: '8px',
// borderRadius: '15px',
// },
// avatarContainer: {},
// titleContainer: {},
// buttonsContainer: {
// display: 'flex',
// flexDirection: 'row-reverse',
// alignItems: 'center',
// width: '30%',
// marginRight: '8%',
// marginLeft: '16%',
// },
// resetButton: {
// backgroundColor: '#4a76a8',
// border: 'none',
// display: 'flex',
// justifyContent: 'space-around',
// width: '50%',
// outline: 'none',
// color: 'white',
// fontSize: '12px',
// },
// settingsButton: {
// backgroundColor: '#4a76a8',
// border: 'none',
// display: 'flex',
// justifyContent: 'space-around',
// outline: 'none',
// width: '50%',
// color: 'white',
// fontSize: '12px',
// },
// image: {
// width: '50px',
// height: '50px',
// },
// }
// stylesApi.styles('changeHeader', { themeName: 'darkTheme', data: storyDarkStyles })
// stylesApi.styles('changeHeader', { themeName: 'lightTheme', data: storyLightStyles })
// export const HeaderComponent = () => {
// const r = optionsKnob(
// label,
// valuesObj,
// defaultValue,
// {
// display: 'select',
// },
// groupId
// )
// console.log(r)
// const resetIcon = object('resetIcon', settings.media.icons.resetIcon, groupSettings)
// settingsApi.settings('changeIcon', { iconName: 'resetIcon', iconData: resetIcon })
// const settingsIcon = object('settingsIcon', settings.media.icons.settingsIcon, groupSettings)
// settingsApi.settings('changeIcon', { iconName: 'settingsIcon', iconData: settingsIcon })
// const resetButton = object('resetButton',uiManagmentHeader.reset, groupUIManagment)
// const settingsButton = object('settingsButton',uiManagmentHeader.settings, groupUIManagment)
// const showAvatar = boolean('showAvatar',uiManagmentHeader.showAvatar, groupUIManagment)
// const showTitle = boolean('showTitle',uiManagmentHeader.showTitle, groupUIManagment)
// uiManagmentApi.uiManagment('setUpHeader', {
// reset: resetButton,
// settings: settingsButton,
// showTitle: showTitle,
// showAvatar: showAvatar,
// })
// const activeLanguage = select('active', { en: 'en', ru: 'ru' }, 'en', groupLanguages)
// languagesApi.languages('changeLanguage', activeLanguage)
// const russian = object('Russian', ru.packet.Header, groupLanguages)
// languagesApi.languages('changeHeader', { language: 'ru', data: russian })
// const english = object('English', en.packet.Header, groupLanguages)
// languagesApi.languages('changeHeader', { language: 'en', data: english })
// const activeTheme = select('active', { darkTheme: 'darkTheme', lightTheme: 'lightTheme' }, 'darkTheme', groupStyles)
// stylesApi.styles('switchTheme', activeTheme)
// const stylesDarkTheme = object('darkTheme', darkTheme.data.Header, groupStyles)
// stylesApi.styles('changeHeader', { themeName: 'darkTheme', data: stylesDarkTheme })
// const stylesLightTheme = object('lightTheme', lightTheme.data.Header, groupStyles)
// stylesApi.styles('changeHeader', { themeName: 'lightTheme', data: stylesLightTheme })
// return (
// <StoreContext.Provider value={store}>
// <Header />
// </StoreContext.Provider>
// )
// }
const languagePacket = {
title: (language: string, title: string) => text(`${language}/title`, title, groupLanguages),
settingsButtonTitle: (language: string, title: string) =>
text(`${language}/settingsButtonTitle`, title, groupLanguages),
resetButtonTitle: (language: string, title: string) => text(`${language}/resetButtonTitle`, title, groupLanguages),
}
const stylesPacket = {
mainContainer: (themeName: string, data: any) => object(`${themeName}/mainContainer`, data, groupStyles),
avatarContainer: (themeName: string, data: any) => object(`${themeName}/avatarContainer`, data, groupStyles),
image: (themeName: string, data: any) => object(`${themeName}/image`, data, groupStyles),
titleContainer: (themeName: string, data: any) => object(`${themeName}/titleContainer`, data, groupStyles),
buttonsContainer: (themeName: string, data: any) => object(`${themeName}/buttonsContainer`, data, groupStyles),
resetButton: (themeName: string, data: any) => object(`${themeName}/resetButton`, data, groupStyles),
settingsButton: (themeName: string, data: any) => object(`${themeName}/settingsButton`, data, groupStyles),
}
export const HeaderComponent = () => {
//settings start
const avatar = files('avatar', '.png', [], groupSettings)
settingsApi.settings('changeAvatar', avatar[0])
const resetIcon = select('resetIcon', iconsList, 'fas redo-alt', groupSettings)
settingsApi.settings('changeIcon', { iconName: 'resetIcon', iconData: { icon: resetIcon.split(' ') } })
const settingsIcon = select('settingsIcon', iconsList, 'fas ellipsis-v', groupSettings)
settingsApi.settings('changeIcon', { iconName: 'settingsIcon', iconData: { icon: settingsIcon.split(' ') } })
const closeSettingsIcon = select('closeSettingsIcon', iconsList, 'fas arrow-down', groupSettings)
settingsApi.settings('changeIcon', {
iconName: 'closeSettingsIcon',
iconData: { icon: closeSettingsIcon.split(' ') },
})
// settings end
//ui managment start
const uiManagmentHeader = store.get().managment.getIn(['components', 'Header'])
const resetButton = boolean('resetButton enabled', uiManagmentHeader.reset.enabled, groupUIManagment)
const titleResetButton = boolean('show resetTitle', uiManagmentHeader.reset.withTitle, groupUIManagment)
const iconResetButton = boolean('show resetIcon', uiManagmentHeader.reset.withIcon, groupUIManagment)
const settingsButton = boolean('settingsButton enabled', uiManagmentHeader.settings.enabled, groupUIManagment)
const titleSettings = boolean('show settingsTitle', uiManagmentHeader.settings.withTitle, groupUIManagment)
const iconSettings = boolean('show settingsIcon', uiManagmentHeader.settings.withIcon, groupUIManagment)
const showAvatar = boolean('showAvatar', uiManagmentHeader.showAvatar, groupUIManagment)
const showTitle = boolean('showTitle', uiManagmentHeader.showTitle, groupUIManagment)
uiManagmentApi.uiManagment('setUpHeader', {
settings: { enabled: settingsButton, withTitle: titleSettings, withIcon: iconSettings },
reset: { enabled: resetButton, withTitle: titleResetButton, withIcon: iconResetButton },
showAvatar,
showTitle,
})
// ui managment end
// languages start
const language = select('language', { en: 'en', ru: 'ru' }, 'en', groupLanguages)
languagesApi.languages('changeLanguage', language)
const activeLanguagePacket = store.get().languages.getIn(['stack', language, 'Header'])
const title = languagePacket.title(language, activeLanguagePacket.title)
const settingsButtonTitle = languagePacket.settingsButtonTitle(language, activeLanguagePacket.settingsButtonTitle)
const resetButtonTitle = languagePacket.resetButtonTitle(language, activeLanguagePacket.resetButtonTitle)
languagesApi.languages('changeHeader', { language: language, data: { title, settingsButtonTitle, resetButtonTitle } })
// languages end
//styles start
const themeName = select(
'theme',
{ sovaDark: 'sovaDark', sovaLight: 'sovaLight', sovaGray: 'sovaGray' },
'sovaLight',
groupStyles
)
stylesApi.styles('switchTheme', themeName)
const activeThemePacket = store.get().styles.getIn(['stack', themeName, 'Header'])
const mainContainer = stylesPacket.mainContainer(themeName, activeThemePacket.mainContainer)
const avatarContainer = stylesPacket.avatarContainer(themeName, activeThemePacket.avatarContainer)
const titleContainer = stylesPacket.titleContainer(themeName, activeThemePacket.titleContainer)
const buttonsContainer = stylesPacket.buttonsContainer(themeName, activeThemePacket.buttonsContainer)
const reset = stylesPacket.resetButton(themeName, activeThemePacket.resetButton)
const settings = stylesPacket.settingsButton(themeName, activeThemePacket.settingsButton)
const image = stylesPacket.image(themeName, activeThemePacket.image)
stylesApi.styles('changeHeader', {
themeName: themeName,
data: {
mainContainer,
avatarContainer,
resetButton: reset,
settingsButton: settings,
titleContainer,
buttonsContainer,
image,
},
})
//styles end
return (
<StoreContext.Provider value={store}>
<div className="sova-ck-main">
<div className="sova-ck-chat">
<Header />
</div>
</div>
</StoreContext.Provider>
)
} | the_stack |
export type Mask = MaskObj | MaskObj[] | boolean;
/**
* Plain object data for an ObjectMask instance.
*/
export interface MaskObj {
[key: string]: Mask;
}
/**
* Interface for "masked out" hook functions.
*/
export interface MaskedOutHook {
/**
* Call signature
* @param path - Path on the object that was masked out
*/
(path: string): void;
}
/**
* Interface for `onField` and `onChange` hooks for the `syncObject` function.
*/
export interface OnFieldHook {
/**
* Call signature.
* @param field - The field name (dot-separated notation)
* @param toVal - What the field is being changed to
* @param fromVal - What the field used to be
* @param parentObj - The immediate parent object containing the field
* @returns Usually void, if boolean `false` is returned will stop traversal
* in the case of an `onField` hook.
*/
(
field: string,
toVal: any,
fromVal: any,
parentObj: Record<string, any>,
): any;
}
export interface SyncObjectOptions {
/**
* An optional callback to call whenever a field is traversed during this
* function. If it returns a boolean `false`, any modification is prevented
* and further subfields will not be traversed.
*/
onField: OnFieldHook;
/**
* Optional function to be called when a value changes.
*/
onChange: OnFieldHook;
}
/**
* Represents a mask, or whitelist, of fields on an object.
*
* @remarks
* This class represents a mask, or whitelist, of fields on an object. Such
* a mask is stored in a format that looks like this:
*
* { foo: true, bar: { baz: true } }
*
* This mask applies to the properties "foo" and "bar.baz" on an object.
* Wilcards can also be used:
*
* { foo: false, bar: false, _: true }
*
* This will allow all fields but foo and bar. The use of arrays with
* a single element is equivalent to the use of wildcards, as arrays in
* the masked object are treated as objects with numeric keys. These
* two masks are equivalent:
*
* { foo: [ { bar: true, baz: true } ] }
*
* { foo: { _: { bar: true, baz: true } } }
*
* Note: array-type wildcards are converted to underscores on instantiation
*/
export class ObjectMask {
/**
* Creates an ObjectMask.
* @param mask The data for the mask
*/
constructor(mask: Mask);
/**
* Creates a structured mask given a list of fields that should be included
* in the mask.
* @param fields - Array of fields to include
* @returns The created mask
*/
static createMaskFromFieldList(fields: string[]): ObjectMask;
/**
* Combines two or more masks such that the result mask matches fields
* matched by any of the combined masks.
* @param masks - Mask data or ObjectMask instances ot add.
* @returns The result of adding together the component masks. Will be
* `true` if either of the masks is `true` or an ObjectMask wrapping
* `true`.
*/
static addMasks(...masks: Array<ObjectMask|Mask>): ObjectMask|true;
/**
* Combines two or more masks such that the result mask matches fields
* matched by the first mask but not the second
* @param min - the minuend
* @param sub - the subtrahend
* @returns The result of subtracting the second mask from the first
*/
static subtractMasks(
min: ObjectMask|Mask,
sub: ObjectMask|Mask,
): ObjectMask;
/**
* Inverts a mask. The resulting mask disallows all fields previously
* allowed, and allows all fields previously disallowed.
* @param - the mask to invert
* @returns the inverted mask
*/
static invertMask(mask: ObjectMask|Mask): ObjectMask;
/**
* Check if an object is an ObjectMask
* @param obj - the object to determine if is an ObjectMask
* @returns true if obj is an ObjectMask, false otherwise
*/
static isObjectMask(mask: ObjectMask|Mask): boolean;
/**
* Adds a set of masks together, but using a logical AND instead of a
* logical OR (as in addMasks). IE, a field must be allowed in all given
* masks to be in the result mask.
* @param masks - Mask data or ObjectMask instances.
* @returns The result of ANDing together the component masks. Will be
* `false` if the result would be an empty mask.
*/
static andMasks(...masks: Array<ObjectMask|Mask>): ObjectMask|false;
/**
* Subtracts a mask.
* @param mask - the mask to subtract
* @returns the new mask
*/
subtractMask(mask: ObjectMask|Mask): ObjectMask;
/**
* Adds a field to a filter. If the filter already matches, the method is a
* no-op.
* @param path - the dotted path to the field to add
* @returns returns self
*/
addField(path: string): this;
/**
* Removes a field from a filter. If the mask already does not match, the
* method is a no-op.
* @param path - the dotted path to the field to remove
* @returns returns self
*/
removeField(path: string): this;
/**
* Returns a copy of the given object, but only including the fields allowed
* by the mask.
*
* @remarks
* If the maskedOutHook function is provided, it is called for each field
* disallowed by the mask (at the highest level it is disallowed).
*
* @param obj - Object to filter
* @param maskedOutHook - Function to call for fields disallowed
* by the mask
*/
filterObject(
obj: Record<string, any>,
maskedOutHook?: MaskedOutHook,
): Record<string, any>;
/**
* Returns a subsection of a mask given a dot-separated path to the
* subsection.
* @param path - Dot-separated path to submask to fetch
* @returns Mask component corresponding to the path
*/
getSubMask(path: string): ObjectMask;
/**
* Returns true if the given path is allowed by the mask. false otherwise.
* @param path - Dot-separated path
* @returns Whether or not the given path is allowed
*/
checkPath(path: string): boolean;
/**
* Make a deep copy of the mask.
* @returns Created copy.
*/
clone(): ObjectMask;
/**
* Returns the internal object that represents this mask.
* @returns Object representation of this mask
*/
toObject(): Mask;
/**
* Check if a mask is valid in strict form (ie, it only contains objects and
* booleans)
* @return Whether or not the mask is strictly valid
*/
validate(): boolean;
/**
* Returns an array of fields in the given object which are restricted by
* the given mask
* @param obj - The object to check against
* @returns Paths to fields that are restricted by the mask
*/
getMaskedOutFields(obj: Record<string, any>): string[];
/**
* Given a dot-notation mapping from fields to values, remove all fields
* that are not allowed by the mask.
* @param dottedObj - Map from dotted paths to values, such as
* { "foo.bar": "baz" }
* @param maskedOutHook - Function to call for removed fields
* @returns The result
*/
filterDottedObject(
dottedObj: Record<string, any>,
maskedOutHook?: MaskedOutHook,
): Record<string, any>;
/**
* Returns an array of fields in the given object which are restricted by
* the given mask. The object is in dotted notation as in
* filterDottedObject()
* @param obj - The object to check against
* @returns Paths to fields that are restricted by the mask
*/
getDottedMaskedOutFields(obj: Record<string, any>): string[];
/**
* Given a structured document, ensures that all fields are allowed by the
* given mask. Returns true or false.
* @param obj - Object to check.
* @returns The check result
*/
checkFields(obj: Record<string, any>): boolean;
/**
* Given a dot-notation mapping from fields to values (only 1 level deep is
* checked), ensure that all fields are in the (structured) mask.
* @param dottedObj - Mapping from dot-separated paths to values
* @returns The check result.
*/
checkDottedFields(dottedObj: Record<string, any>): boolean;
/**
* Returns a function that filters object fields based on a structured
* mask/whitelist.
* @returns A function(obj) that is the equivalent of callingfilterObject()
* on obj.
*/
createFilterFunc(): (obj: Record<string, any>) => Record<string, any>;
}
/**
* Determines whether a value is considered a scalar or an object.
*
* @remarks
* Currently, primitives plus Date types plus undefined and null plus functions
* are considered scalar.
*
* @param value - Value to check
* @returns The check result
*/
export function isScalar(val: any): boolean;
/**
* Returns true if the given value is considered a terminal value for traversal
* operations.
*
* @remarks
* Terminal values are as follows:
* - Any scalars (anything isScalar() returns true for)
* - Any non-plain objects, other than arrays
*
* @param value- Value to check
* @returns The check result
*/
export function isTerminal(val: any): boolean;
/**
* Checks for deep equality between two object or values.
* @param a - First value to check.
* @param b - Second value to check.
* @returns The check result.
*/
export function deepEquals(a: any, b: any): boolean;
/**
* Checks whether two scalar values (as determined by isScalar()) are equal.
* @param a - First value
* @param b - Second value
* @returns The check result.
*/
export function scalarEquals(a: any, b: any): boolean;
/**
* Returns a deep copy of the given value such that entities are not passed
* by reference.
* @param obj - The object or value to copy
* @returns The copied object or value
*/
export function deepCopy(obj: any): any;
/**
* Given an object, converts it into a one-level-deep object where the keys are
* dot-separated paths and the values are the values at those paths.
* @param obj - The object to convert
* @param includeRedundantLevels - If set to true, the returned object also
* includes keys for internal objects. By default, an object such as
* { foo: { bar: "baz"} } will be converted into { "foo.bar": "baz" }. If
* includeRedundantLevels is set, it will instead be converted into
* { "foo": { bar: "baz" }, "foo.bar": "baz" } .
* @param stopAtArrays - If set to true, the collapsing function will not
* descend into arrays.
* @returns The result
*/
export function collapseToDotted(
obj: Record<string, any>,
includeRedundantLevels?: boolean,
stopAtArrays?: boolean,
): Record<string, any>;
/**
* Returns whether or not the given query fields (in dotted notation) match the
* document (also in dotted notation). The "queries" here are simple equality
* matches.
* @param doc - The document to test
* @param query - A one-layer-deep set of key/values to check doc for
* @returns Whether or not the doc matches
*/
export function matchDottedObject(
doc: Record<string, any>,
query: Record<string, any>,
): boolean;
/**
* Same as matchDottedObject, but for non-dotted objects and queries.
* Deprecated, as it is equivalent to lodash.isMatch(), which we delegate to.
* @deprecated
* @param doc - Object to match against, in structured (not dotted) form
* @param query - Set of fields (in structed form) to match
* @returns Whether or not the object matches
*/
export function matchObject(
doc: Record<string, any>,
query: Record<string, any>,
): boolean;
/**
* Synchronizes one object to another object, in-place. Updates to the existing
* object are done in-place as much as possible. Full objects are only replaced
* if necessary.
* @param toObj - The object to modify
* @param fromObj - The object to copy from
* @param options - Options object.
* @returns The resulting object (usually the same object as toObj)
*/
export function syncObject(
toObj: Record<string, any>,
fromObj: Record<string, any>,
options?: SyncObjectOptions,
): Record<string, any>;
/**
* Sets the value at a given path in an object.
* @param obj - The object
* @param path - The path, dot-separated
* @param value - Value to set
* @returns The same object
*/
export function setPath(
obj: Record<string, any>,
path: string,
value: any,
): Record<string, any>;
/**
* Deletes the value at a given path in an object.
* @param obj - The object
* @param path - The path, dot-separated
* @returns The object that was passed in
*/
export function deletePath(
obj: Record<string, any>,
path: string,
): Record<string, any>;
/**
* Gets the value at a given path in an object.
* @param obj - The object
* @param path - The path, dot-separated
* @param allowSkipArrays - If true: If a field in an object is an array and the
* path key is non-numeric, and the array has exactly 1 element, then the first
* element of the array is used.
* @return The value at the path
*/
export function getPath(
obj: Record<string, any>,
path: string,
allowSkipArrays?: boolean,
): any;
/**
* This is the "light", more performant version of `merge()`. It does not
* support a customizer function or being used as a lodash iterator.
* @param object - the destination object
* @param sources - the source object
* @returns the merged object
*/
export function mergeLight<TTarget, TSource>(
target: TTarget,
source: TSource,
): TTarget & TSource;
/**
* @see objtools.mergeLight
*/
export function mergeLight<TTarget, TSource1, TSource2>(
target: TTarget,
source1: TSource1,
source2: TSource2,
): TTarget & TSource1 & TSource2;
/**
* @see objtools.mergeLight
*/
export function mergeLight<TTarget, TSource1, TSource2, TSource3>(
target: TTarget,
source1: TSource1,
source2: TSource2,
source3: TSource3,
): TTarget & TSource1 & TSource2 & TSource3;
/**
* @see objtools.mergeLight
*/
export function mergeLight<TTarget, TSource1, TSource2, TSource3, TSource4>(
target: TTarget,
source1: TSource1,
source2: TSource2,
source3: TSource3,
source4: TSource4,
): TTarget & TSource1 & TSource2 & TSource3 & TSource4;
/**
* @see objtools.mergeLight
*/
export function mergeLight(...args: any[]): any;
/**
* Type for merge customizer functions.
* @param objectValue - the value at `key` in the base object
* @param sourceValue - the value at `key` in the source object
* @param key - the key currently being merged
* @param object - the base object
* @param source - the source object
* @returns The merged value. If `undefined`, merging will be handled by the
* invoked method instead.
*/
export type MergeCustomizer = { bivariantHack(
objectValue: any,
sourceValue: any,
key: string,
object: any,
): any }['bivariantHack'];
/**
* Merges n objects together.
* @param object - the destination object
* @param sources - the source object
* @param customizer - the function to customize merging properties. If
* provided, customizer is invoked to produce the merged values of the
* destination and source properties. If customizer returns undefined, merging
* is handled by the method instead.
* @returns the merged object
*/
export function merge<TTarget, TSource>(
target: TTarget,
source: TSource,
customizer?: MergeCustomizer,
): TTarget & TSource;
/**
* @see objtools.merge
*/
export function merge<TTarget, TSource1, TSource2>(
target: TTarget,
source1: TSource1,
source2: TSource2,
customizer?: MergeCustomizer,
): TTarget & TSource1 & TSource2;
/**
* @see objtools.merge
*/
export function merge<TTarget, TSource1, TSource2, TSource3>(
target: TTarget,
source1: TSource1,
source2: TSource2,
source3: TSource3,
customizer?: MergeCustomizer,
): TTarget & TSource1 & TSource2 & TSource3;
/**
* @see objtools.merge
*/
export function merge<TTarget, TSource1, TSource2, TSource3, TSource4>(
target: TTarget,
source1: TSource1,
source2: TSource2,
source3: TSource3,
source4: TSource4,
customizer?: MergeCustomizer,
): TTarget & TSource1 & TSource2 & TSource3 & TSource4;
/**
* @see objtools.merge
*/
export function merge(...args: any[]): any;
/**
* This is the "heavy" version of `merge()`, which is significantly less
* performant than the light version, but supports customizers and being used as
* a lodash iterator.
* @param object - the destination object
* @param sources - the source object
* @param customizer - the function to customize merging properties. If
* provided, customizer is invoked to produce the merged values of the
* destination and source properties. If customizer returns undefined, merging
* is handled by the method instead.
* @return the merged object
*/
export function mergeHeavy<TTarget, TSource>(
target: TTarget,
source: TSource,
customizer?: MergeCustomizer,
): TTarget & TSource;
/**
* @see objtools.mergeHeavy
*/
export function mergeHeavy<TTarget, TSource1, TSource2>(
target: TTarget,
source1: TSource1,
source2: TSource2,
customizer?: MergeCustomizer,
): TTarget & TSource1 & TSource2;
/**
* @see objtools.mergeHeavy
*/
export function mergeHeavy<TTarget, TSource1, TSource2, TSource3>(
target: TTarget,
source1: TSource1,
source2: TSource2,
source3: TSource3,
customizer?: MergeCustomizer,
): TTarget & TSource1 & TSource2 & TSource3;
/**
* @see objtools.mergeHeavy
*/
export function mergeHeavy<TTarget, TSource1, TSource2, TSource3, TSource4>(
target: TTarget,
source1: TSource1,
source2: TSource2,
source3: TSource3,
source4: TSource4,
customizer?: MergeCustomizer,
): TTarget & TSource1 & TSource2 & TSource3 & TSource4;
/**
* @see objtools.mergeHeavy
*/
export function mergeHeavy(...args: any[]): any;
/**
* Gets the duplicates in an array
* @param arr - the array to find duplicates in
* @returns array of the duplicates in arr
*/
export function getDuplicates(arr: any[]): any[];
/**
* Diffs n objects
* @param objects - the objects to diff
* @returns If no scalars are passed, returns an object with arrays of values at
* every path from which all source objects are different. If scalars are
* passed, the return value is an array with non-numeric fields. Terminal
* arrays will contain objects only if they contain no overlapping keys. See
* README.md for usage examples.
*/
export function diffObjects(
...objects: Array<Record<string, any>>,
): Record<string, any>;
/**
* @see objtools.diffObjects
*/
export function diffObjects(...args: any[]): any;
/**
* Diffs two objects
* @param val1 - the first value to diff
* @param val2 - the second value to diff
* @returns an array of dot-separated paths to the shallowest branches present
* in both objects from which there are no identical scalar values.
*/
export function dottedDiff(val1: any, val2: any): string[];
/**
* Construct a consistent hash of an object, array, or other Javascript entity.
* @param obj - The object to hash.
* @return The hash string. Long enough so collisions are extremely unlikely.
*/
export function objectHash(obj: any): string;
/**
* Converts a date string, number of miliseconds or object with a date field
* into an instance of Date. It will return the same instance if a Date instance
* is passed in.
* @param value - the value to convert
* @returns the converted Date instance
*/
export function sanitizeDate(value: any): Date|null;
/**
* Checks if value is a plain object, that is, an object created by the Object
* constructor or one with a [[Prototype]] of null.
* @param val - Value to check
* @returns Check result
*/
export function isPlainObject(val: any): boolean;
/**
* Checks if value is an object or array
* @param val - Value to check
* @returns Check result
*/
export function isEmptyObject(val: any): boolean;
/**
* Checks if value is an empty array
* @param val - Value to check
* @returns Check result
*/
export function isEmptyArray(val: any): boolean;
/**
* Checks if value is an empty object or array
* @param val - Value to check
* @returns Check result
*/
export function isEmpty(val: any): boolean; | the_stack |
import '../test/common-test-setup-karma';
import {
extractAssociatedLabels,
getApprovalInfo,
getLabelStatus,
getMaxAccounts,
getRepresentativeValue,
getVotingRange,
getVotingRangeOrDefault,
getRequirements,
getTriggerVotes,
hasNeutralStatus,
labelCompare,
LabelStatus,
} from './label-util';
import {
AccountId,
AccountInfo,
ApprovalInfo,
DetailedLabelInfo,
LabelInfo,
QuickLabelInfo,
} from '../types/common';
import {
createAccountWithEmail,
createChange,
createSubmitRequirementExpressionInfo,
createSubmitRequirementResultInfo,
createDetailedLabelInfo,
} from '../test/test-data-generators';
import {
SubmitRequirementResultInfo,
SubmitRequirementStatus,
} from '../api/rest-api';
const VALUES_0 = {
'0': 'neutral',
};
const VALUES_1 = {
'-1': 'bad',
'0': 'neutral',
'+1': 'good',
};
const VALUES_2 = {
'-2': 'blocking',
'-1': 'bad',
'0': 'neutral',
'+1': 'good',
'+2': 'perfect',
};
suite('label-util', () => {
test('getVotingRange -1 to +1', () => {
const label = {values: VALUES_1};
const expectedRange = {min: -1, max: 1};
assert.deepEqual(getVotingRange(label), expectedRange);
assert.deepEqual(getVotingRangeOrDefault(label), expectedRange);
});
test('getVotingRange -2 to +2', () => {
const label = {values: VALUES_2};
const expectedRange = {min: -2, max: 2};
assert.deepEqual(getVotingRange(label), expectedRange);
assert.deepEqual(getVotingRangeOrDefault(label), expectedRange);
});
test('getVotingRange empty values', () => {
const label = {
values: {},
};
const expectedRange = {min: 0, max: 0};
assert.isUndefined(getVotingRange(label));
assert.deepEqual(getVotingRangeOrDefault(label), expectedRange);
});
test('getVotingRange no values', () => {
const label = {};
const expectedRange = {min: 0, max: 0};
assert.isUndefined(getVotingRange(label));
assert.deepEqual(getVotingRangeOrDefault(label), expectedRange);
});
test('getMaxAccounts', () => {
const label: DetailedLabelInfo = {
values: VALUES_2,
all: [
{value: 2, _account_id: 314 as AccountId},
{value: 1, _account_id: 777 as AccountId},
],
};
const maxAccounts = getMaxAccounts(label);
assert.equal(maxAccounts.length, 1);
assert.equal(maxAccounts[0]._account_id, 314 as AccountId);
});
test('getMaxAccounts unset parameters', () => {
assert.isEmpty(getMaxAccounts());
assert.isEmpty(getMaxAccounts({}));
assert.isEmpty(getMaxAccounts({values: VALUES_2}));
});
test('getApprovalInfo', () => {
const myAccountInfo: AccountInfo = {_account_id: 314 as AccountId};
const myApprovalInfo: ApprovalInfo = {
value: 2,
_account_id: 314 as AccountId,
};
const label: DetailedLabelInfo = {
values: VALUES_2,
all: [myApprovalInfo, {value: 1, _account_id: 777 as AccountId}],
};
assert.equal(getApprovalInfo(label, myAccountInfo), myApprovalInfo);
});
test('getApprovalInfo no approval for user', () => {
const myAccountInfo: AccountInfo = {_account_id: 123 as AccountId};
const label: DetailedLabelInfo = {
values: VALUES_2,
all: [
{value: 2, _account_id: 314 as AccountId},
{value: 1, _account_id: 777 as AccountId},
],
};
assert.isUndefined(getApprovalInfo(label, myAccountInfo));
});
test('labelCompare', () => {
let sorted = ['c', 'b', 'a'].sort(labelCompare);
assert.sameOrderedMembers(sorted, ['a', 'b', 'c']);
sorted = ['b', 'a', 'Code-Review'].sort(labelCompare);
assert.sameOrderedMembers(sorted, ['Code-Review', 'a', 'b']);
});
test('getLabelStatus', () => {
let labelInfo: DetailedLabelInfo = {all: [], values: VALUES_2};
assert.equal(getLabelStatus(labelInfo), LabelStatus.NEUTRAL);
labelInfo = {all: [{value: 0}], values: VALUES_0};
assert.equal(getLabelStatus(labelInfo), LabelStatus.NEUTRAL);
labelInfo = {all: [{value: 0}], values: VALUES_1};
assert.equal(getLabelStatus(labelInfo), LabelStatus.NEUTRAL);
labelInfo = {all: [{value: 0}], values: VALUES_2};
assert.equal(getLabelStatus(labelInfo), LabelStatus.NEUTRAL);
labelInfo = {all: [{value: 1}], values: VALUES_2};
assert.equal(getLabelStatus(labelInfo), LabelStatus.RECOMMENDED);
labelInfo = {all: [{value: -1}], values: VALUES_2};
assert.equal(getLabelStatus(labelInfo), LabelStatus.DISLIKED);
labelInfo = {all: [{value: 1}], values: VALUES_1};
assert.equal(getLabelStatus(labelInfo), LabelStatus.APPROVED);
labelInfo = {all: [{value: -1}], values: VALUES_1};
assert.equal(getLabelStatus(labelInfo), LabelStatus.REJECTED);
labelInfo = {all: [{value: 2}, {value: 1}], values: VALUES_2};
assert.equal(getLabelStatus(labelInfo), LabelStatus.APPROVED);
labelInfo = {all: [{value: -2}, {value: -1}], values: VALUES_2};
assert.equal(getLabelStatus(labelInfo), LabelStatus.REJECTED);
labelInfo = {all: [{value: -2}, {value: 2}], values: VALUES_2};
assert.equal(getLabelStatus(labelInfo), LabelStatus.REJECTED);
labelInfo = {all: [{value: -1}, {value: 2}], values: VALUES_2};
assert.equal(getLabelStatus(labelInfo), LabelStatus.APPROVED);
labelInfo = {all: [{value: 0}, {value: 2}], values: VALUES_2};
assert.equal(getLabelStatus(labelInfo), LabelStatus.APPROVED);
labelInfo = {all: [{value: 0}, {value: -2}], values: VALUES_2};
assert.equal(getLabelStatus(labelInfo), LabelStatus.REJECTED);
});
test('getLabelStatus - quicklabelinfo', () => {
let labelInfo: QuickLabelInfo = {};
assert.equal(getLabelStatus(labelInfo), LabelStatus.NEUTRAL);
labelInfo = {approved: createAccountWithEmail()};
assert.equal(getLabelStatus(labelInfo), LabelStatus.APPROVED);
labelInfo = {rejected: createAccountWithEmail()};
assert.equal(getLabelStatus(labelInfo), LabelStatus.REJECTED);
labelInfo = {recommended: createAccountWithEmail()};
assert.equal(getLabelStatus(labelInfo), LabelStatus.RECOMMENDED);
labelInfo = {disliked: createAccountWithEmail()};
assert.equal(getLabelStatus(labelInfo), LabelStatus.DISLIKED);
});
test('getLabelStatus - detailed and quick info', () => {
let labelInfo: LabelInfo = {all: [], values: VALUES_2};
labelInfo = {
all: [{value: 0}],
values: VALUES_0,
rejected: createAccountWithEmail(),
};
assert.equal(getLabelStatus(labelInfo), LabelStatus.NEUTRAL);
});
test('hasNeutralStatus', () => {
const labelInfo: DetailedLabelInfo = {all: [], values: VALUES_2};
assert.isTrue(hasNeutralStatus(labelInfo));
assert.isTrue(hasNeutralStatus(labelInfo, {}));
assert.isTrue(hasNeutralStatus(labelInfo, {value: 0}));
assert.isFalse(hasNeutralStatus(labelInfo, {value: -1}));
assert.isFalse(hasNeutralStatus(labelInfo, {value: 1}));
});
test('getRepresentativeValue', () => {
let labelInfo: DetailedLabelInfo = {all: []};
assert.equal(getRepresentativeValue(labelInfo), 0);
labelInfo = {all: [{value: 0}]};
assert.equal(getRepresentativeValue(labelInfo), 0);
labelInfo = {all: [{value: 1}]};
assert.equal(getRepresentativeValue(labelInfo), 1);
labelInfo = {all: [{value: 2}, {value: 1}]};
assert.equal(getRepresentativeValue(labelInfo), 2);
labelInfo = {all: [{value: -2}, {value: -1}]};
assert.equal(getRepresentativeValue(labelInfo), -2);
labelInfo = {all: [{value: -2}, {value: 2}]};
assert.equal(getRepresentativeValue(labelInfo), -2);
labelInfo = {all: [{value: -1}, {value: 2}]};
assert.equal(getRepresentativeValue(labelInfo), 2);
labelInfo = {all: [{value: 0}, {value: 2}]};
assert.equal(getRepresentativeValue(labelInfo), 2);
labelInfo = {all: [{value: 0}, {value: -2}]};
assert.equal(getRepresentativeValue(labelInfo), -2);
});
suite('extractAssociatedLabels()', () => {
function createSubmitRequirementExpressionInfoWith(expression: string) {
return {
...createSubmitRequirementResultInfo(),
submittability_expression_result: {
...createSubmitRequirementExpressionInfo(),
expression,
},
};
}
test('1 label', () => {
const submitRequirement = createSubmitRequirementExpressionInfoWith(
'label:Verified=MAX -label:Verified=MIN'
);
const labels = extractAssociatedLabels(submitRequirement);
assert.deepEqual(labels, ['Verified']);
});
test('label with number', () => {
const submitRequirement = createSubmitRequirementExpressionInfoWith(
'label2:verified=MAX'
);
const labels = extractAssociatedLabels(submitRequirement);
assert.deepEqual(labels, ['verified']);
});
test('2 labels', () => {
const submitRequirement = createSubmitRequirementExpressionInfoWith(
'label:Verified=MAX -label:Code-Review=MIN'
);
const labels = extractAssociatedLabels(submitRequirement);
assert.deepEqual(labels, ['Verified', 'Code-Review']);
});
test('overridden label', () => {
const submitRequirement = {
...createSubmitRequirementExpressionInfoWith(
'label:Verified=MAX -label:Verified=MIN'
),
override_expression_result: {
...createSubmitRequirementExpressionInfo(),
expression: 'label:Build-cop-override',
},
};
const labels = extractAssociatedLabels(submitRequirement);
assert.deepEqual(labels, ['Verified', 'Build-cop-override']);
});
});
suite('getRequirements()', () => {
function createChangeInfoWith(
submit_requirements: SubmitRequirementResultInfo[]
) {
return {
...createChange(),
submit_requirements,
};
}
test('only legacy', () => {
const requirement = {
...createSubmitRequirementResultInfo(),
is_legacy: true,
};
const change = createChangeInfoWith([requirement]);
assert.deepEqual(getRequirements(change), [requirement]);
});
test('legacy and non-legacy - show all', () => {
const requirement = {
...createSubmitRequirementResultInfo(),
is_legacy: true,
};
const requirement2 = {
...createSubmitRequirementResultInfo(),
is_legacy: false,
};
const change = createChangeInfoWith([requirement, requirement2]);
assert.deepEqual(getRequirements(change), [requirement, requirement2]);
});
test('filter not applicable', () => {
const requirement = createSubmitRequirementResultInfo();
const requirement2 = {
...createSubmitRequirementResultInfo(),
status: SubmitRequirementStatus.NOT_APPLICABLE,
};
const change = createChangeInfoWith([requirement, requirement2]);
assert.deepEqual(getRequirements(change), [requirement]);
});
});
suite('getTriggerVotes()', () => {
test('no requirements', () => {
const triggerVote = 'Trigger-Vote';
const change = {
...createChange(),
labels: {
[triggerVote]: createDetailedLabelInfo(),
},
};
assert.deepEqual(getTriggerVotes(change), [triggerVote]);
});
test('no trigger votes, all labels associated with sub requirement', () => {
const triggerVote = 'Trigger-Vote';
const change = {
...createChange(),
submit_requirements: [
{
...createSubmitRequirementResultInfo(),
submittability_expression_result: {
...createSubmitRequirementExpressionInfo(),
expression: `label:${triggerVote}=MAX`,
},
is_legacy: false,
},
],
labels: {
[triggerVote]: createDetailedLabelInfo(),
},
};
assert.deepEqual(getTriggerVotes(change), []);
});
});
}); | the_stack |
import { Id64, Id64String, OpenMode } from "@itwin/core-bentley";
import { Angle, Arc3d, GeometryQuery, LineString3d, Loop, Range3d, StandardViewIndex } from "@itwin/core-geometry";
import {
CategorySelector, DefinitionModel, DisplayStyle3d, IModelDb, ModelSelector, OrthographicViewDefinition, PhysicalModel, SnapshotDb, SpatialCategory,
SpatialModel, StandaloneDb, ViewDefinition,
} from "@itwin/core-backend";
import {
AxisAlignedBox3d, BackgroundMapType, Cartographic, Code, ColorByName, ColorDef, EcefLocation, GeometricElement3dProps,
GeometryParams, GeometryStreamBuilder, GeometryStreamProps, IModel, PersistentBackgroundMapProps, RenderMode, ViewFlags,
} from "@itwin/core-common";
import { insertClassifiedRealityModel } from "./ClassifyRealityModel";
import { GeoJson } from "./GeoJson";
/** */
export class GeoJsonImporter {
public iModelDb: IModelDb;
public definitionModelId: Id64String = Id64.invalid;
public physicalModelId: Id64String = Id64.invalid;
public featureCategoryId: Id64String = Id64.invalid;
public featureClassFullName = "Generic:SpatialLocation";
private readonly _geoJson: GeoJson;
private readonly _appendToExisting: boolean;
private readonly _modelName?: string;
private readonly _forceZeroHeight = true;
private readonly _labelProperty?: string;
private readonly _pointRadius: number;
private _colorIndex?: number;
private readonly _viewFlags: ViewFlags;
private readonly _backgroundMap: PersistentBackgroundMapProps | undefined;
/** Construct a new GeoJsonImporter
* @param iModelFileName the output iModel file name
* @param geoJson the input GeoJson data
*/
public constructor(iModelFileName: string, geoJson: GeoJson, appendToExisting: boolean, modelName?: string, labelProperty?: string, pointRadius?: number, pseudoColor?: boolean, mapTypeString?: string, mapGroundBias?: number,
private _classifiedURL?: string, private _classifiedName?: string, private _classifiedOutside?: string, private _classifiedInside?: string) {
this.iModelDb = appendToExisting ? StandaloneDb.openFile(iModelFileName, OpenMode.ReadWrite) : SnapshotDb.createEmpty(iModelFileName, { rootSubject: { name: geoJson.title } });
this._geoJson = geoJson;
this._appendToExisting = appendToExisting;
this._modelName = modelName;
this._labelProperty = labelProperty;
this._pointRadius = pointRadius === undefined ? .25 : pointRadius;
this._colorIndex = pseudoColor ? 0 : undefined;
let mapType;
switch (mapTypeString) {
case "streets": mapType = BackgroundMapType.Street; break;
case "aerial": mapType = BackgroundMapType.Aerial; break;
case "hybrid": mapType = BackgroundMapType.Hybrid; break;
}
this._viewFlags = new ViewFlags({ renderMode: RenderMode.SmoothShade, backgroundMap: undefined !== mapType });
if (undefined !== mapType)
this._backgroundMap = { providerName: "BingProvider", groundBias: mapGroundBias, providerData: { mapType } };
}
/** Perform the import */
public async import(): Promise<void> {
const categoryName = this._modelName ? this._modelName : "GeoJson Category";
const modelName = this._modelName ? this._modelName : "GeoJson Model";
let featureModelExtents: AxisAlignedBox3d;
if (this._appendToExisting) {
this.physicalModelId = PhysicalModel.insert(this.iModelDb, IModelDb.rootSubjectId, modelName);
const foundCategoryId = SpatialCategory.queryCategoryIdByName(this.iModelDb, IModel.dictionaryId, categoryName);
this.featureCategoryId = (foundCategoryId !== undefined) ? foundCategoryId : this.addCategoryToExistingDb(categoryName);
this.convertFeatureCollection();
const featureModel: SpatialModel = this.iModelDb.models.getModel<SpatialModel>(this.physicalModelId);
featureModelExtents = featureModel.queryExtents();
const projectExtents = Range3d.createFrom(this.iModelDb.projectExtents);
projectExtents.extendRange(featureModelExtents);
this.iModelDb.updateProjectExtents(projectExtents);
} else {
this.definitionModelId = DefinitionModel.insert(this.iModelDb, IModelDb.rootSubjectId, "GeoJSON Definitions");
this.physicalModelId = PhysicalModel.insert(this.iModelDb, IModelDb.rootSubjectId, modelName);
this.featureCategoryId = SpatialCategory.insert(this.iModelDb, this.definitionModelId, categoryName, { color: ColorDef.white.tbgr });
/** To geo-locate the project, we need to first scan the GeoJSon and extract range. This would not be required
* if the bounding box was directly available.
*/
const featureMin = Cartographic.createZero(), featureMax = Cartographic.createZero();
if (!this.getFeatureRange(featureMin, featureMax))
return;
const featureCenter = Cartographic.fromRadians({ longitude: (featureMin.longitude + featureMax.longitude) / 2, latitude: (featureMin.latitude + featureMax.latitude) / 2 });
this.iModelDb.setEcefLocation(EcefLocation.createFromCartographicOrigin(featureCenter));
this.convertFeatureCollection();
const featureModel: SpatialModel = this.iModelDb.models.getModel<SpatialModel>(this.physicalModelId);
featureModelExtents = featureModel.queryExtents();
if (!this._classifiedURL)
this.insertSpatialView("Spatial View", featureModelExtents);
this.iModelDb.updateProjectExtents(featureModelExtents);
}
if (this._classifiedURL) {
const isPlanar = (featureModelExtents.high.z - featureModelExtents.low.z) < 1.0E-2;
await insertClassifiedRealityModel(this._classifiedURL, this.physicalModelId, this.featureCategoryId, this.iModelDb, this._viewFlags, isPlanar, this._backgroundMap, this._classifiedName ? this._classifiedName : this._modelName, this._classifiedInside, this._classifiedOutside);
}
this.iModelDb.saveChanges();
}
private addCategoryToExistingDb(categoryName: string) {
const categoryId = SpatialCategory.insert(this.iModelDb, IModel.dictionaryId, categoryName, { color: ColorDef.white.tbgr });
this.iModelDb.views.iterateViews({ from: "BisCore.SpatialViewDefinition" }, ((view: ViewDefinition) => {
const categorySelector = this.iModelDb.elements.getElement<CategorySelector>(view.categorySelectorId);
categorySelector.categories.push(categoryId);
this.iModelDb.elements.updateElement(categorySelector);
return true;
}));
return categoryId;
}
/** Iterate through and accumulate the GeoJSON FeatureCollection range. */
protected getFeatureRange(featureMin: Cartographic, featureMax: Cartographic) {
featureMin.longitude = featureMin.latitude = Angle.pi2Radians;
featureMax.longitude = featureMax.latitude = -Angle.pi2Radians;
for (const feature of this._geoJson.data.features) {
if (feature.geometry) {
switch (feature.geometry.type) {
case GeoJson.GeometryType.polygon:
for (const loop of feature.geometry.coordinates)
this.extendRangeForCoordinates(featureMin, featureMax, loop);
break;
case GeoJson.GeometryType.linestring:
this.extendRangeForCoordinates(featureMin, featureMax, feature.geometry.coordinates);
break;
case GeoJson.GeometryType.point:
this.extendRangeForCoordinate(featureMin, featureMax, feature.geometry.coordinates);
break;
case GeoJson.GeometryType.multiPolygon:
for (const polygon of feature.geometry.coordinates)
for (const loop of polygon)
this.extendRangeForCoordinates(featureMin, featureMax, loop);
break;
}
}
}
return featureMin.longitude < featureMax.longitude && featureMin.latitude < featureMax.latitude;
}
private extendRangeForCoordinate(featureMin: Cartographic, featureMax: Cartographic, point: GeoJson.Point) {
const longitude = Angle.degreesToRadians(point[0]);
const latitude = Angle.degreesToRadians(point[1]);
featureMin.longitude = Math.min(longitude, featureMin.longitude);
featureMin.latitude = Math.min(latitude, featureMin.latitude);
featureMax.longitude = Math.max(longitude, featureMax.longitude);
featureMax.latitude = Math.max(latitude, featureMax.latitude);
}
private extendRangeForCoordinates(featureMin: Cartographic, featureMax: Cartographic, lineString: GeoJson.LineString) {
for (const point of lineString) {
this.extendRangeForCoordinate(featureMin, featureMax, point);
}
}
/** Iterate through the GeoJSON FeatureCollection converting each Feature in the collection. */
protected convertFeatureCollection(): void {
const featureProps: GeometricElement3dProps = {
model: this.physicalModelId,
code: Code.createEmpty(),
classFullName: this.featureClassFullName,
category: this.featureCategoryId,
};
for (const featureJson of this._geoJson.data.features) {
featureProps.geom = this.convertFeatureGeometry(featureJson.geometry);
if (featureJson.properties) {
if (this._labelProperty !== undefined && featureJson.properties[this._labelProperty] !== undefined)
featureProps.userLabel = featureJson.properties[this._labelProperty];
else
featureProps.userLabel = featureJson.properties.mapname;
}
this.iModelDb.elements.insertElement(featureProps);
}
}
/** Convert GeoJSON feature geometry into an iModel GeometryStream. */
private convertFeatureGeometry(inGeometry: GeoJson.Geometry): GeometryStreamProps | undefined {
if (!inGeometry)
return undefined;
const builder = new GeometryStreamBuilder();
if (this._colorIndex !== undefined) {
const colorValues = [ColorByName.blue, ColorByName.red, ColorByName.green, ColorByName.yellow, ColorByName.cyan, ColorByName.magenta, ColorByName.cornSilk, ColorByName.blueViolet, ColorByName.deepSkyBlue, ColorByName.indigo, ColorByName.fuchsia];
const geomParams = new GeometryParams(this.featureCategoryId);
geomParams.lineColor = ColorDef.create(colorValues[this._colorIndex++ % colorValues.length]);
builder.appendGeometryParamsChange(geomParams);
}
switch (inGeometry.type) {
case GeoJson.GeometryType.point:
const pointGeometry = this.convertPoint(inGeometry.coordinates);
if (pointGeometry)
builder.appendGeometry(pointGeometry);
break;
case GeoJson.GeometryType.linestring:
const linestringGeometry = this.convertLinestring(inGeometry.coordinates);
if (linestringGeometry)
builder.appendGeometry(linestringGeometry);
break;
case GeoJson.GeometryType.polygon:
const polyGeometry = this.convertPolygon(inGeometry.coordinates);
if (polyGeometry)
builder.appendGeometry(polyGeometry);
break;
case GeoJson.GeometryType.multiPolygon:
for (const polygon of inGeometry.coordinates) {
const outGeometry = this.convertPolygon(polygon);
if (outGeometry)
builder.appendGeometry(outGeometry);
}
break;
}
return builder.geometryStream;
}
private pointFromCoordinate(coordinates: number[]) {
GeoJsonImporter._scratchCartographic.longitude = Angle.degreesToRadians(coordinates[0]);
GeoJsonImporter._scratchCartographic.latitude = Angle.degreesToRadians(coordinates[1]);
const point = this.iModelDb.cartographicToSpatialFromEcef(GeoJsonImporter._scratchCartographic);
/** the ecef Transform (particularly if it appending) may introduce some deviation from 0 x-y plane. */
if (this._forceZeroHeight)
point.z = 0.0;
return point;
}
private convertPoint(inPoint: GeoJson.Point): Loop {
return Loop.create(Arc3d.createXY(this.pointFromCoordinate(inPoint), this._pointRadius));
}
/** Convert a GeoJSON LineString into an @itwin/core-geometry lineString */
private convertLinestring(inLinestring: GeoJson.LineString): LineString3d | undefined {
if (!Array.isArray(inLinestring))
return undefined;
const outPoints = [];
for (const inPoint of inLinestring) {
outPoints.push(this.pointFromCoordinate(inPoint));
}
return LineString3d.createPoints(outPoints);
}
/** Convert a GeoJSON polygon into geometry that can be appended to an iModel GeometryStream. */
private convertPolygon(inPolygon: GeoJson.Polygon): GeometryQuery | undefined {
if (!Array.isArray(inPolygon))
return undefined;
const outLoops = [];
for (const inLoop of inPolygon) {
const outLoop = this.convertLoop(inLoop);
if (outLoop)
outLoops.push(outLoop);
}
switch (outLoops.length) {
case 0:
return undefined;
case 1:
return outLoops[0];
default:
return undefined; // TBD... Multi-loop Regions,
}
}
private static _scratchCartographic = Cartographic.createZero();
/** Convert a GeoJSON LineString into an @itwin/core-geometry Loop */
private convertLoop(inLoop: GeoJson.LineString): Loop | undefined {
const lineString = this.convertLinestring(inLoop);
return lineString ? Loop.create(lineString) : undefined;
}
/** Insert a SpatialView configured to display the GeoJSON data that was converted/imported. */
protected insertSpatialView(viewName: string, range: AxisAlignedBox3d): Id64String {
const modelSelectorId: Id64String = ModelSelector.insert(this.iModelDb, this.definitionModelId, viewName, [this.physicalModelId]);
const categorySelectorId: Id64String = CategorySelector.insert(this.iModelDb, this.definitionModelId, viewName, [this.featureCategoryId]);
const displayStyleId: Id64String = DisplayStyle3d.insert(this.iModelDb, this.definitionModelId, viewName, { viewFlags: this._viewFlags, backgroundMap: this._backgroundMap });
return OrthographicViewDefinition.insert(this.iModelDb, this.definitionModelId, viewName, modelSelectorId, categorySelectorId, displayStyleId, range, StandardViewIndex.Top);
}
} | the_stack |
export class Token {
type: TokenType;
value?: string | number;
meta?: string;
constructor(type: TokenType, value?: string | number, meta?: string) {
this.type = type;
this.value = value;
this.meta = meta;
}
}
/*
name operators associativity precedence level
factor int | str | template | bool | dict | list | tuple | (expr) | variable
x[...] x.attr func() L
** R
+x -x !x R
* / % L
+ - L
== != > >= <= < <= L
in not in L
not R
and L
or L
... ? ... : ... R
exp1, exp2 L
*/
/*
*/
export enum TokenType {
NUMBER = 'NUMBER',
PIXEL = 'PIXEL',
REM = 'REM',
EM = 'EM',
SECOND = 'SECOND',
DEGREE = 'DEGREE',
PERCENTAGE = 'PERCENTAGE',
STRING = 'STRING',
TEMPLATE = 'TEMPLATE',
COLOR = 'COLOR',
// Arithmetic Operators
PLUS = '+',
MINUS = '-',
MUL = '*',
DIV = '/',
MOD = '%',
EXP = '**',
// Assignment Operators
ADDEQUAL = '+=',
MINUSEQUAL = '-=',
MULEQUAL = '*=',
DIVEQUAL = '/=',
MODEQUAL = '%=',
EXPEQUAL = '**=',
INCREASE = '++',
DECREASE = '--',
ARROW = '=>',
// Comparison Operators
EQUAL = '==',
NOTEQUAL = '!=',
GERATER = '>',
LESS = '<',
GERATEREQUAL = '>=',
LESSEQUAL = '<=',
TERNARY = '?',
// Logical Operators
NO = '!',
AND = 'and',
OR = 'or',
NOT = 'not',
FROM = 'from',
IN = 'in',
NOTIN = 'not in',
AS = 'as',
NONE = 'None',
TRUE = 'True',
FALSE = 'False',
DOLLAR = '$',
DOT = '.',
COMMA = ',',
LPAREN = '(',
RPAREN = ')',
LCURLY = '{',
RCURLY = '}',
LSQUARE = '[',
RSQUARE = ']',
UNKNOWN = 'UNKNOWN',
ASSIGN = '=',
SPACE = 'SPACE',
SEMI = ';',
COLON = ':',
EOF = 'EOF',
ID = 'ID',
VAR = '@var',
APPLY = '@apply',
ATTR = '@attr',
MIXIN = '@mixin',
INCLUDE = '@include',
FUNC = '@func',
ASYNC = '@async',
AWAIT = '@await',
RETURN = '@return',
YIELD = '@yield',
IMPORT = '@import',
EXPORT = '@export',
LOAD = '@load',
IF = '@if',
ELSE = '@else',
ELIF = '@elif',
WHILE = '@while',
FOR = '@for',
JS = '@js',
LOG = '@log',
WARN = '@warn',
ERROR = '@error',
ASSERT = '@assert',
BREAK = '@break',
CONTINUE = '@continue',
TRY = '@try',
EXCEPT = '@except',
FINALLY = '@finally',
WITH = '@with',
RAISE = '@raise',
DEL = '@del',
NEW = 'new',
}
export const REVERSED_KEYWORDS: {[key:string]:Token} = {
'apply': new Token(TokenType.APPLY, '@apply'),
'attr': new Token(TokenType.ATTR, '@attr'),
'mixin': new Token(TokenType.MIXIN, '@mixin'),
'include': new Token(TokenType.INCLUDE, '@include'),
'func': new Token(TokenType.FUNC, '@func'),
'async': new Token(TokenType.ASYNC, '@async'),
'return': new Token(TokenType.RETURN, '@return'),
'yield': new Token(TokenType.YIELD, '@yield'),
'break': new Token(TokenType.BREAK, '@break'),
'continue': new Token(TokenType.CONTINUE, '@continue'),
'try': new Token(TokenType.TRY, '@try'),
'except': new Token(TokenType.EXCEPT, '@except'),
'finally': new Token(TokenType.FINALLY, '@finally'),
'raise': new Token(TokenType.RAISE, '@raise'),
'with': new Token(TokenType.WITH, '@with'),
'var': new Token(TokenType.VAR, '@var'),
'load': new Token(TokenType.LOAD, '@load'),
'import': new Token(TokenType.IMPORT, '@import'),
'export': new Token(TokenType.EXPORT, '@export'),
'if': new Token(TokenType.IF, '@if'),
'else': new Token(TokenType.ELSE, '@else'),
'elif': new Token(TokenType.ELIF, '@elif'),
'while': new Token(TokenType.WHILE, '@while'),
'for': new Token(TokenType.FOR, '@for'),
'js': new Token(TokenType.JS, '@js'),
'log': new Token(TokenType.LOG, '@log'),
'warn': new Token(TokenType.WARN, '@warn'),
'error': new Token(TokenType.ERROR, '@error'),
'assert': new Token(TokenType.ASSERT, '@assert'),
'del': new Token(TokenType.DEL, '@del'),
};
export class Num {
token: Token;
value: number;
constructor(token: Token) {
this.token = token;
this.value = token.value as number;
}
}
export class Bool {
value: boolean;
constructor(value: boolean) {
this.value = value;
}
}
export class None {
}
export class PIXEL extends Num {
}
export class REM extends Num {
}
export class Str {
token: Token;
value: string;
constructor(token: Token) {
this.token = token;
this.value = token.value as string;
}
}
export type DataType = Operand | Str | Template | Tuple | List | Dict | Bool | None | Func;
export class Tuple {
values: (DataType)[];
constructor(values: (DataType)[]) {
this.values = values;
}
}
export class List {
values: (DataType)[];
constructor(values: (DataType)[]) {
this.values = values;
}
}
export class Params {
values: (DataType)[];
constructor(values: (DataType)[]) {
this.values = values;
}
}
export class Dict {
pairs: [string|number, (DataType)][]
constructor(pairs: [string|number, (DataType)][]) {
this.pairs = pairs;
}
}
export class Template {
token: Token;
value: string;
constructor(token: Token) {
this.token = token;
this.value = token.value as string;
}
}
export class Apply {
value: Str | Template;
constructor(value: string) {
const token = new Token(TokenType.STRING, value);
this.value = /\${.*}/.test(value) ? new Template(token): new Str(token);
}
}
export class Attr {
attr: string;
value: Str | Template;
constructor(attr: string, value: string) {
const token = new Token(TokenType.STRING, value);
this.attr = attr;
this.value = /\${.*}/.test(value) ? new Template(token): new Str(token);
}
}
export class Var {
token: Token;
value: string;
constructor(token: Token) {
this.token = token;
this.value = token.value as string;
}
}
export class Assign {
left: Var;
op: Token;
right: DataType;
constructor(left: Var, op: Token, right: DataType) {
this.left = left;
this.op = op;
this.right = right;
}
}
export class Update {
left: Var;
op: Token;
right: DataType;
constructor(left: Var, op: Token, right: DataType) {
this.left = left;
this.op = op;
this.right = right;
}
}
export class Console {
type: TokenType.LOG | TokenType.WARN | TokenType.ERROR | TokenType.ASSERT;
expr: DataType;
constructor(type: TokenType.LOG | TokenType.WARN | TokenType.ERROR | TokenType.ASSERT, expr: DataType) {
this.type = type;
this.expr = expr;
}
}
export class JS {
code: string
constructor(code: string) {
this.code = code;
}
}
export class PropDecl {
name: string;
value: Str | Template;
constructor(name: string, value: Str | Template) {
this.name = name;
this.value = value;
}
}
export class StyleDecl {
selector: string;
children: Block;
constructor(selector: string, children: Block) {
this.selector = selector;
this.children = children;
}
}
export class Block {
statement_list: (Assign | Update | Console | NoOp)[]
style_list: (StyleDecl | PropDecl | NoOp)[]
constructor(statement_list: (Assign | Update | Console | NoOp)[], style_list: (StyleDecl | PropDecl | NoOp)[]) {
this.statement_list = statement_list;
this.style_list = style_list;
}
}
export class Func {
name?: string;
params: string[];
block: Block;
async: boolean;
constructor(params: string[], block: Block, name?: string, async = false) {
this.name = name;
this.params = params;
this.block = block;
this.async = async;
}
}
export class Instance {
name: string;
params?: DataType[];
constructor(name: string, params?: DataType[]) {
this.name = name;
this.params = params;
}
}
export class Lambda {
params: string[];
expr: DataType;
name?: string;
async: boolean;
constructor(params: string[], expr: DataType, name?:string, async = false) {
this.params = params;
this.expr = expr;
this.name = name;
this.async = async;
}
}
export class Return {
value: DataType;
constructor(value: DataType) {
this.value = value;
}
}
export class Await {
value: DataType;
constructor(value: DataType) {
this.value = value;
}
}
export class Yield {
value: DataType;
constructor(value: DataType) {
this.value = value;
}
}
export class Del {
value: DataType;
constructor(value: DataType) {
this.value = value;
}
}
export class Raise {
value: DataType;
constructor(value: DataType) {
this.value = value;
}
}
export class Continue {
}
export class Break {
}
export class If {
if_block: [DataType, Block];
elif_blocks?: [DataType, Block][];
else_block?: Block;
constructor(expr: DataType, block: Block, elif_blocks?: [DataType, Block][], else_block?: Block) {
this.if_block = [expr, block];
this.elif_blocks = elif_blocks;
this.else_block = else_block;
}
add_elif(expr: DataType, block: Block): void {
this.elif_blocks = [...(this.elif_blocks ?? []), [expr, block]];
}
add_else(block: Block): void {
this.else_block = block;
}
}
export class Try {
try_block: Block;
except_blocks?: [string, Block, string|undefined][];
finally_except_block?: Block;
else_block?: Block;
finally_block?: Block;
constructor(block: Block) {
this.try_block = block;
}
add_except(error: string, block: Block, alias?: string): void {
this.except_blocks = [...(this.except_blocks ?? []), [error, block, alias]];
}
add_else(block: Block): void {
this.else_block = block;
}
add_finally(block: Block): void {
this.finally_block = block;
}
add_finally_except(block: Block): void {
this.finally_except_block = block;
}
}
export class While {
if_block: [DataType, Block];
else_block?: Block;
constructor(expr: DataType, block: Block, else_block?: Block) {
this.if_block = [expr, block];
this.else_block = else_block;
}
add_else(block: Block): void {
this.else_block = block;
}
}
export class For {
variables: string[];
iterable: DataType;
for_block: Block;
else_block?: Block;
constructor(variables: string[], iterable: DataType, for_block: Block, else_block?: Block) {
this.variables = variables;
this.iterable = iterable;
this.for_block = for_block;
this.else_block = else_block;
}
add_else(block: Block): void {
this.else_block = block;
}
}
export class With {
expr: DataType;
name: string;
block: Block;
constructor(expr: DataType, name: string, block: Block) {
this.expr = expr;
this.name = name;
this.block = block;
}
}
export class Program {
block: Block;
constructor(block: Block) {
this.block = block;
}
}
export class UnaryOp {
op: Token;
expr: Operand;
constructor(op: Token, expr: Operand) {
this.op = op;
this.expr = expr;
}
}
export class BinOp {
left: Operand;
op: Token;
right: Operand;
constructor(left: Operand, op: Token, right: Operand) {
this.left = left;
this.op = op;
this.right = right;
}
}
export class Import {
urls: string[];
constructor(urls: string[]) {
this.urls = urls;
}
}
export type Module = {
url: string,
default?: string,
exports?: { [ key : string ] : string }
}
export class Load {
modules: Module[]
constructor(modules: Module[]) {
this.modules = modules;
}
}
export class NoOp {
// NoOp node is used to represent an empty statement. such as {}
}
export type Operand = Num | BinOp | UnaryOp | NoOp; | the_stack |
const rowRegex = /^.*[\.#].*$/;
enum LabelMode {
None,
Number,
Letter
}
namespace pxtblockly {
export class FieldMatrix extends Blockly.Field implements Blockly.FieldCustom {
private static CELL_WIDTH = 25;
private static CELL_HORIZONTAL_MARGIN = 7;
private static CELL_VERTICAL_MARGIN = 5;
private static CELL_CORNER_RADIUS = 5;
private static BOTTOM_MARGIN = 9;
private static Y_AXIS_WIDTH = 9;
private static X_AXIS_HEIGHT = 10;
private static TAB = " ";
public isFieldCustom_ = true;
public SERIALIZABLE = true;
private params: any;
private onColor = "#FFFFFF";
private offColor: string;
private static DEFAULT_OFF_COLOR = "#000000";
private scale = 1;
// The number of columns
private matrixWidth: number = 5;
// The number of rows
private matrixHeight: number = 5;
private yAxisLabel: LabelMode = LabelMode.None;
private xAxisLabel: LabelMode = LabelMode.None;
private cellState: boolean[][] = [];
private cells: SVGRectElement[][] = [];
private elt: SVGSVGElement;
private currentDragState_: boolean;
constructor(text: string, params: any, validator?: Function) {
super(text, validator);
this.params = params;
if (this.params.rows !== undefined) {
let val = parseInt(this.params.rows);
if (!isNaN(val)) {
this.matrixHeight = val;
}
}
if (this.params.columns !== undefined) {
let val = parseInt(this.params.columns);
if (!isNaN(val)) {
this.matrixWidth = val;
}
}
if (this.params.onColor !== undefined) {
this.onColor = this.params.onColor;
}
if (this.params.offColor !== undefined) {
this.offColor = this.params.offColor;
}
if (this.params.scale !== undefined)
this.scale = Math.max(0.6, Math.min(2, Number(this.params.scale)));
else if (Math.max(this.matrixWidth, this.matrixHeight) > 15)
this.scale = 0.85;
else if (Math.max(this.matrixWidth, this.matrixHeight) > 10)
this.scale = 0.9;
}
/**
* Show the inline free-text editor on top of the text.
* @private
*/
showEditor_() {
// Intentionally left empty
}
private initMatrix() {
if (!this.sourceBlock_.isInsertionMarker()) {
this.elt = pxsim.svg.parseString(`<svg xmlns="http://www.w3.org/2000/svg" id="field-matrix" />`);
// Initialize the matrix that holds the state
for (let i = 0; i < this.matrixWidth; i++) {
this.cellState.push([])
this.cells.push([]);
for (let j = 0; j < this.matrixHeight; j++) {
this.cellState[i].push(false);
}
}
this.restoreStateFromString();
// Create the cells of the matrix that is displayed
for (let i = 0; i < this.matrixWidth; i++) {
for (let j = 0; j < this.matrixHeight; j++) {
this.createCell(i, j);
}
}
this.updateValue();
if (this.xAxisLabel !== LabelMode.None) {
const y = this.scale * this.matrixHeight * (FieldMatrix.CELL_WIDTH + FieldMatrix.CELL_VERTICAL_MARGIN) + FieldMatrix.CELL_VERTICAL_MARGIN * 2 + FieldMatrix.BOTTOM_MARGIN
const xAxis = pxsim.svg.child(this.elt, "g", { transform: `translate(${0} ${y})` });
for (let i = 0; i < this.matrixWidth; i++) {
const x = this.getYAxisWidth() + this.scale * i * (FieldMatrix.CELL_WIDTH + FieldMatrix.CELL_HORIZONTAL_MARGIN) + FieldMatrix.CELL_WIDTH / 2 + FieldMatrix.CELL_HORIZONTAL_MARGIN / 2;
const lbl = pxsim.svg.child(xAxis, "text", { x, class: "blocklyText" })
lbl.textContent = this.getLabel(i, this.xAxisLabel);
}
}
if (this.yAxisLabel !== LabelMode.None) {
const yAxis = pxsim.svg.child(this.elt, "g", {});
for (let i = 0; i < this.matrixHeight; i++) {
const y = this.scale * i * (FieldMatrix.CELL_WIDTH + FieldMatrix.CELL_VERTICAL_MARGIN) + FieldMatrix.CELL_WIDTH / 2 + FieldMatrix.CELL_VERTICAL_MARGIN * 2;
const lbl = pxsim.svg.child(yAxis, "text", { x: 0, y, class: "blocklyText" })
lbl.textContent = this.getLabel(i, this.yAxisLabel);
}
}
this.fieldGroup_.replaceChild(this.elt, this.fieldGroup_.firstChild);
}
}
private getLabel(index: number, mode: LabelMode) {
switch (mode) {
case LabelMode.Letter:
return String.fromCharCode(index + /*char code for A*/ 65);
default:
return (index + 1).toString();
}
}
private dontHandleMouseEvent_ = (ev: MouseEvent) => {
ev.stopPropagation();
ev.preventDefault();
}
private clearLedDragHandler = (ev: MouseEvent) => {
const svgRoot = (this.sourceBlock_ as Blockly.BlockSvg).getSvgRoot();
pxsim.pointerEvents.down.forEach(evid => svgRoot.removeEventListener(evid, this.dontHandleMouseEvent_));
svgRoot.removeEventListener(pxsim.pointerEvents.move, this.dontHandleMouseEvent_);
document.removeEventListener(pxsim.pointerEvents.up, this.clearLedDragHandler);
document.removeEventListener(pxsim.pointerEvents.leave, this.clearLedDragHandler);
(Blockly as any).Touch.clearTouchIdentifier();
this.elt.removeEventListener(pxsim.pointerEvents.move, this.handleRootMouseMoveListener);
ev.stopPropagation();
ev.preventDefault();
}
private createCell(x: number, y: number) {
const tx = this.scale * x * (FieldMatrix.CELL_WIDTH + FieldMatrix.CELL_HORIZONTAL_MARGIN) + FieldMatrix.CELL_HORIZONTAL_MARGIN + this.getYAxisWidth();
const ty = this.scale * y * (FieldMatrix.CELL_WIDTH + FieldMatrix.CELL_VERTICAL_MARGIN) + FieldMatrix.CELL_VERTICAL_MARGIN;
const cellG = pxsim.svg.child(this.elt, "g", { transform: `translate(${tx} ${ty})` }) as SVGGElement;
const cellRect = pxsim.svg.child(cellG, "rect", {
'class': `blocklyLed${this.cellState[x][y] ? 'On' : 'Off'}`,
'cursor': 'pointer',
width: this.scale * FieldMatrix.CELL_WIDTH, height: this.scale * FieldMatrix.CELL_WIDTH,
fill: this.getColor(x, y),
'data-x': x,
'data-y': y,
rx: Math.max(2, this.scale * FieldMatrix.CELL_CORNER_RADIUS) }) as SVGRectElement;
this.cells[x][y] = cellRect;
if ((this.sourceBlock_.workspace as any).isFlyout) return;
pxsim.pointerEvents.down.forEach(evid => cellRect.addEventListener(evid, (ev: MouseEvent) => {
const svgRoot = (this.sourceBlock_ as Blockly.BlockSvg).getSvgRoot();
this.currentDragState_ = !this.cellState[x][y];
// select and hide chaff
Blockly.hideChaff();
(this.sourceBlock_ as Blockly.BlockSvg).select();
this.toggleRect(x, y);
pxsim.pointerEvents.down.forEach(evid => svgRoot.addEventListener(evid, this.dontHandleMouseEvent_));
svgRoot.addEventListener(pxsim.pointerEvents.move, this.dontHandleMouseEvent_);
document.addEventListener(pxsim.pointerEvents.up, this.clearLedDragHandler);
document.addEventListener(pxsim.pointerEvents.leave, this.clearLedDragHandler);
// Begin listening on the canvas and toggle any matches
this.elt.addEventListener(pxsim.pointerEvents.move, this.handleRootMouseMoveListener);
ev.stopPropagation();
ev.preventDefault();
}, false));
}
private toggleRect = (x: number, y: number) => {
this.cellState[x][y] = this.currentDragState_;
this.updateValue();
}
private handleRootMouseMoveListener = (ev: MouseEvent) => {
let clientX;
let clientY;
if ((ev as any).changedTouches && (ev as any).changedTouches.length == 1) {
// Handle touch events
clientX = (ev as any).changedTouches[0].clientX;
clientY = (ev as any).changedTouches[0].clientY;
} else {
// All other events (pointer + mouse)
clientX = ev.clientX;
clientY = ev.clientY;
}
const target = document.elementFromPoint(clientX, clientY);
if (!target) return;
const x = target.getAttribute('data-x');
const y = target.getAttribute('data-y');
if (x != null && y != null) {
this.toggleRect(parseInt(x), parseInt(y));
}
}
private getColor(x: number, y: number) {
return this.cellState[x][y] ? this.onColor : (this.offColor || FieldMatrix.DEFAULT_OFF_COLOR);
}
private getOpacity(x: number, y: number) {
return this.cellState[x][y] ? '1.0' : '0.2';
}
private updateCell(x: number, y: number) {
const cellRect = this.cells[x][y];
cellRect.setAttribute("fill", this.getColor(x, y));
cellRect.setAttribute("fill-opacity", this.getOpacity(x, y));
cellRect.setAttribute('class', `blocklyLed${this.cellState[x][y] ? 'On' : 'Off'}`);
}
setValue(newValue: string | number, restoreState = true) {
super.setValue(String(newValue));
if (this.elt) {
if (restoreState) this.restoreStateFromString();
for (let x = 0; x < this.matrixWidth; x++) {
for (let y = 0; y < this.matrixHeight; y++) {
this.updateCell(x, y);
}
}
}
}
render_() {
if (!this.visible_) {
this.markDirty();
return;
}
if (!this.elt) {
this.initMatrix();
}
// The height and width must be set by the render function
this.size_.height = this.scale * Number(this.matrixHeight) * (FieldMatrix.CELL_WIDTH + FieldMatrix.CELL_VERTICAL_MARGIN) + FieldMatrix.CELL_VERTICAL_MARGIN * 2 + FieldMatrix.BOTTOM_MARGIN + this.getXAxisHeight()
this.size_.width = this.scale * Number(this.matrixWidth) * (FieldMatrix.CELL_WIDTH + FieldMatrix.CELL_HORIZONTAL_MARGIN) + this.getYAxisWidth();
}
// The return value of this function is inserted in the code
getValue() {
// getText() returns the value that is set by calls to setValue()
let text = removeQuotes(this.value_);
return `\`\n${FieldMatrix.TAB}${text}\n${FieldMatrix.TAB}\``;
}
// Restores the block state from the text value of the field
private restoreStateFromString() {
let r = this.value_ as string;
if (r) {
const rows = r.split("\n").filter(r => rowRegex.test(r));
for (let y = 0; y < rows.length && y < this.matrixHeight; y++) {
let x = 0;
const row = rows[y];
for (let j = 0; j < row.length && x < this.matrixWidth; j++) {
if (isNegativeCharacter(row[j])) {
this.cellState[x][y] = false;
x++;
}
else if (isPositiveCharacter(row[j])) {
this.cellState[x][y] = true;
x++;
}
}
}
}
}
// Composes the state into a string an updates the field's state
private updateValue() {
let res = "";
for (let y = 0; y < this.matrixHeight; y++) {
for (let x = 0; x < this.matrixWidth; x++) {
res += (this.cellState[x][y] ? "#" : ".") + " "
}
res += "\n" + FieldMatrix.TAB
}
// Blockly stores the state of the field as a string
this.setValue(res, false);
}
private getYAxisWidth() {
return this.yAxisLabel === LabelMode.None ? 0 : FieldMatrix.Y_AXIS_WIDTH;
}
private getXAxisHeight() {
return this.xAxisLabel === LabelMode.None ? 0 : FieldMatrix.X_AXIS_HEIGHT;
}
}
function isPositiveCharacter(c: string) {
return c === "#" || c === "*" || c === "1";
}
function isNegativeCharacter(c: string) {
return c === "." || c === "_" || c === "0";
}
const allQuotes = ["'", '"', "`"];
function removeQuotes(str: string) {
str = (str || "").trim();
const start = str.charAt(0);
if (start === str.charAt(str.length - 1) && allQuotes.indexOf(start) !== -1) {
return str.substr(1, str.length - 2).trim();
}
return str;
}
} | the_stack |
"use strict";
import * as vscode from "vscode";
import LanguageIdentifier from "../contract/LanguageIdentifier";
import type IDisposable from "../IDisposable";
import { configManager } from "../configuration/manager";
import { DecorationClass, decorationClassConfigMap, decorationStyles } from "./constant";
import decorationWorkerRegistry from "./decorationWorkerRegistry";
/**
* Represents a set of decoration ranges.
*/
export interface IDecorationRecord {
readonly target: DecorationClass;
/**
* The ranges that the decoration applies to.
*/
readonly ranges: readonly vscode.Range[];
}
/**
* Represents a decoration analysis worker.
*
* A worker is a function, which analyzes a document, and returns a thenable that resolves to a `IDecorationRecord`.
* A worker **may** accept a `CancellationToken`, and then must **reject** the promise when the task is cancelled.
*/
export interface IFuncAnalysisWorker {
(document: vscode.TextDocument, token: vscode.CancellationToken): Thenable<IDecorationRecord>;
}
export type IWorkerRegistry = { readonly [target in DecorationClass]: IFuncAnalysisWorker; };
/**
* Represents the state of an asynchronous or long running operation.
*/
const enum TaskState {
Pending,
Fulfilled,
Cancelled,
}
/**
* Represents a decoration analysis task.
*
* Such a task should be asynchronous.
*/
interface IDecorationAnalysisTask {
/**
* The document that the task works on.
*/
readonly document: vscode.TextDocument;
/**
* The thenable that represents the task.
*
* This is just a handle for caller to await.
* It must be guaranteed to be still **fulfilled** on cancellation.
*/
readonly executor: Thenable<unknown>;
/**
* The result.
*
* Only available when the task is `Fulfilled`. Otherwise, `undefined`.
*/
readonly result?: readonly IDecorationRecord[];
/**
* The state of the task.
*/
readonly state: TaskState;
/**
* Cancels the task.
*/
cancel(): void;
}
class DecorationAnalysisTask implements IDecorationAnalysisTask {
private readonly _cts: vscode.CancellationTokenSource;
private _result: readonly IDecorationRecord[] | undefined = undefined;
public readonly document: vscode.TextDocument;
public readonly executor: Thenable<readonly IDecorationRecord[] | void>;
public get result(): readonly IDecorationRecord[] | undefined {
return this._result;
}
public get state(): TaskState {
if (this._cts.token.isCancellationRequested) {
return TaskState.Cancelled;
} else if (this._result) {
return TaskState.Fulfilled;
} else {
return TaskState.Pending;
}
}
constructor(document: vscode.TextDocument, workers: IWorkerRegistry, targets: readonly DecorationClass[]) {
this.document = document;
const token =
(this._cts = new vscode.CancellationTokenSource()).token;
// The weird nesting is to defer the task creation to reduce runtime cost.
// The outermost is a so-called "cancellable promise".
// If you create a task and cancel it immediately, this design guarantees that most workers are not called.
// Otherwise, you will observe thousands of discarded microtasks quickly.
this.executor = new Promise<IDecorationRecord[]>((resolve, reject): void => {
token.onCancellationRequested(reject);
if (token.isCancellationRequested) {
reject();
}
resolve(Promise.all(targets.map<Thenable<IDecorationRecord>>(target => workers[target](document, token))));
})
.then(result => this._result = result) // Copy the result and pass it down.
.catch(reason => {
// We'll adopt `vscode.CancellationError` when it matures.
// For now, falsy indicates cancellation, and we won't throw an exception for that.
if (reason) {
throw reason;
}
});
}
public cancel(): void {
this._cts.cancel();
this._cts.dispose();
}
}
interface IDecorationManager extends IDisposable { }
/**
* Represents a text editor decoration manager.
*
* For reliability reasons, do not leak any mutable content out of the manager.
*
* VS Code does not define a corresponding `*Provider` interface, so we implement it ourselves.
* The following scenarios are considered:
*
* * Activation.
* * Opening a document with/without corresponding editors.
* * Changing a document.
* * Closing a document.
* * Closing a Markdown editor, and immediately switching to an arbitrary editor.
* * Switching between arbitrary editors, including Markdown to Markdown.
* * Changing configuration after a decoration analysis task started.
* * Deactivation.
*/
class DecorationManager implements IDecorationManager {
/**
* Decoration type instances **currently in use**.
*/
private readonly _decorationHandles = new Map<DecorationClass, vscode.TextEditorDecorationType>();
/**
* Decoration analysis workers.
*/
private readonly _decorationWorkers: IWorkerRegistry;
/**
* The keys of `_decorationWorkers`.
* This is for improving performance.
*/
private readonly _supportedClasses: readonly DecorationClass[];
/**
* Disposables which unregister contributions to VS Code.
*/
private readonly _disposables: vscode.Disposable[];
/**
* Decoration analysis tasks **currently in use**.
* This serves as both a task pool, and a result cache.
*/
private readonly _tasks = new Map<vscode.TextDocument, IDecorationAnalysisTask>();
/**
* This is exclusive to `applyDecoration()`.
*/
private _displayDebounceHandle: vscode.CancellationTokenSource | undefined;
constructor(workers: IWorkerRegistry) {
this._decorationWorkers = Object.assign<IWorkerRegistry, IWorkerRegistry>(Object.create(null), workers);
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#property_names
this._supportedClasses = Object.keys(workers).map(Number);
// Here are many different kinds of calls. Bind `this` context carefully.
// Load all.
vscode.workspace.textDocuments.forEach(this.updateCache, this);
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor) {
this.applyDecoration(activeEditor);
}
// Register event listeners.
this._disposables = [
vscode.workspace.onDidOpenTextDocument(this.updateCache, this),
vscode.workspace.onDidChangeTextDocument(event => {
this.updateCache(event.document);
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor && activeEditor.document === event.document) {
this.applyDecoration(activeEditor);
}
}),
vscode.workspace.onDidCloseTextDocument(this.collectGarbage, this),
vscode.window.onDidChangeActiveTextEditor(editor => { if (editor) { this.applyDecoration(editor); } }),
];
}
public dispose(): void {
// Unsubscribe event listeners.
for (const disposable of this._disposables) {
disposable.dispose();
}
this._disposables.length = 0;
// Stop rendering.
if (this._displayDebounceHandle) {
this._displayDebounceHandle.cancel();
this._displayDebounceHandle.dispose();
}
this._displayDebounceHandle = undefined;
// Terminate tasks.
for (const task of this._tasks.values()) {
task.cancel();
}
this._tasks.clear();
// Remove decorations.
for (const handle of this._decorationHandles.values()) {
handle.dispose();
}
this._decorationHandles.clear();
}
/**
* Applies a set of decorations to the text editor asynchronously.
*
* This method is expected to be started frequently on volatile state.
* It begins with a short sync part, to make immediate response to event possible.
* Then, it internally creates an async job, to keep data access correct.
* It stops silently, if any condition is not met.
*
* For performance reasons, it only works on the **active** editor (not visible editors),
* although VS Code renders decorations as long as the editor is visible.
* Besides, we have a threshold to stop analyzing large documents.
* When it is reached, related task will be unavailable, thus by design, this method will quit.
*/
private applyDecoration(editor: vscode.TextEditor): void {
const document = editor.document;
if (document.languageId !== LanguageIdentifier.Markdown) {
return;
}
// The task can be in any state (typically pending, fulfilled, obsolete) during this call.
// The editor can be suspended or even disposed at any time.
// Thus, we have to check at each stage.
const task = this._tasks.get(document);
if (!task || task.state === TaskState.Cancelled) {
return;
}
// Discard the previous operation, in case the user is switching between editors fast.
// Although I don't think a debounce can make much value.
if (this._displayDebounceHandle) {
this._displayDebounceHandle.cancel();
this._displayDebounceHandle.dispose();
}
const debounceToken =
(this._displayDebounceHandle = new vscode.CancellationTokenSource()).token;
// Queue the display refresh job.
(async (): Promise<void> => {
if (task.state === TaskState.Pending) {
await task.executor;
}
if (task.state !== TaskState.Fulfilled || debounceToken.isCancellationRequested) {
return;
}
const results = task.result!;
for (const { ranges, target } of results) {
let handle = this._decorationHandles.get(target);
// Recheck applicability, since the user may happen to change settings.
if (configManager.get<boolean>(decorationClassConfigMap[target])) {
// Create a new decoration type instance if needed.
if (!handle) {
handle = vscode.window.createTextEditorDecorationType(decorationStyles[target]);
this._decorationHandles.set(target, handle);
}
} else {
// Remove decorations if the type is disabled.
if (handle) {
handle.dispose();
this._decorationHandles.delete(target);
}
continue;
}
if (
debounceToken.isCancellationRequested
|| task.state !== TaskState.Fulfilled // Confirm the cache is still up-to-date.
|| vscode.window.activeTextEditor !== editor // Confirm the editor is still active.
) {
return;
}
// Create a shallow copy for VS Code to use. This operation shouldn't cost much.
editor.setDecorations(handle, Array.from(ranges));
}
})();
}
/**
* Terminates tasks that are linked to the document, and frees corresponding resources.
*/
private collectGarbage(document: vscode.TextDocument): void {
const task = this._tasks.get(document);
if (task) {
task.cancel();
this._tasks.delete(document);
}
}
/**
* Initiates and **queues** a decoration cache update task that is linked to the document.
*/
private updateCache(document: vscode.TextDocument): void {
if (document.languageId !== LanguageIdentifier.Markdown) {
return;
}
// Discard previous tasks. Effectively mark existing cache as obsolete.
this.collectGarbage(document);
// Stop if the document exceeds max length.
// The factor is for compatibility. There should be new logic someday.
if (document.getText().length * 1.5 > configManager.get<number>("syntax.decorationFileSizeLimit")) {
return;
}
// Create the new task.
this._tasks.set(document, new DecorationAnalysisTask(
document,
this._decorationWorkers,
// No worry. `applyDecoration()` should recheck applicability.
this._supportedClasses.filter(target => configManager.get<boolean>(decorationClassConfigMap[target]))
));
}
}
export const decorationManager: IDecorationManager = new DecorationManager(decorationWorkerRegistry); | the_stack |
import * as hex from "@stablelib/hex";
import { concat } from "@stablelib/bytes";
import {
encode, decode, Simple, Tagged, TaggedEncoder, TaggedDecoder,
DEFAULT_TAGGED_ENCODERS, DEFAULT_TAGGED_DECODERS
} from "./cbor";
// Test vectors from RFC 7049: Appendix A. Examples.
const encoderTestVectors = [
0, "00",
1, "01",
10, "0a",
23, "17",
24, "1818",
25, "1819",
100, "1864",
1000, "1903e8",
1000000, "1a000f4240",
1000000000000, "1b000000e8d4a51000",
// 18446744073709551615, "1bffffffffffffffff", // 64-bit integer, cannot be represented in JS
// 18446744073709551616, "c249010000000000000000", // big integer, not supported yet
// -18446744073709551616, "3bffffffffffffffff", // 64-bit integer, cannot be represented in JS
// -18446744073709551617, "c349010000000000000000", // big integer, not supported yet
-1, "20",
-10, "29",
-100, "3863",
-1000, "3903e7",
// 0.0, "f90000", // 0.0 encoded as integer 0
-0.0, "f98000",
// 1.0, "f93c00", // integer
1.1, "fb3ff199999999999a",
// 1.5, "f93e00", // not supporting float16 for encoding
// 65504.0, "f97bff",
// 100000.0, "fa47c35000", // integer
3.4028234663852886e+38, "fa7f7fffff",
1.0e+300, "fb7e37e43c8800759c",
// 5.960464477539063e-8, "f90001", // not supporting float16 for encoding
// 0.00006103515625, "f90400", // not supporting float16 for encoding
// -4.0, "f9c400", // not supporting float16 for encoding
-4.1, "fbc010666666666666",
Infinity, "f97c00",
NaN, "f97e00",
-Infinity, "f9fc00",
false, "f4",
true, "f5",
null, "f6",
undefined, "f7",
new Simple(16), "f0",
new Simple(24), "f818",
new Simple(255), "f8ff",
new Date("2013-03-21T20:04:00Z"), "c074323031332d30332d32315432303a30343a30305a",
new Tagged(1, 1363896240), "c11a514b67b0", // epoch date
new Tagged(1, 1363896240.5), "c1fb41d452d9ec200000", // epoch date
new Tagged(23, new Uint8Array([1, 2, 3, 4])), "d74401020304",
new Tagged(24, new Uint8Array([0x64, 0x49, 0x45, 0x54, 0x46])), "d818456449455446",
new Tagged(32, "http://www.example.com"), "d82076687474703a2f2f7777772e6578616d706c652e636f6d",
new Uint8Array(0), "40",
new Uint8Array([1, 2, 3, 4]), "4401020304",
"", "60",
"a", "6161",
"IETF", "6449455446",
"\"\\", "62225c",
"\u00fc", "62c3bc",
"\u6c34", "63e6b0b4",
"\ud800\udd51", "64f0908591",
[], "80",
[1, 2, 3], "83010203",
[1, [2, 3], [4, 5]], "8301820203820405",
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25], "98190102030405060708090a0b0c0d0e0f101112131415161718181819",
{}, "a0",
// { 1: 2, 3: 4 }, "a201020304", // in JS keys are always strings
{ "a": 1, "b": [2, 3] }, "a26161016162820203",
["a", { "b": "c" }], "826161a161626163",
{ "a": "A", "b": "B", "c": "C", "d": "D", "e": "E" }, "a56161614161626142616361436164614461656145",
/^a[bc]+$/gi, "d8236c2f5e615b62635d2b242f6769"
];
const decoderTestVectors = [
0, "00",
1, "01",
10, "0a",
23, "17",
24, "1818",
25, "1819",
100, "1864",
1000, "1903e8",
1000000, "1a000f4240",
1000000000000, "1b000000e8d4a51000",
-1, "20",
-10, "29",
-100, "3863",
-1000, "3903e7",
0.0, "f90000",
-0.0, "f98000",
-0.0, "fb8000000000000000",
1.0, "f93c00",
1.1, "fb3ff199999999999a",
1.5, "f93e00",
65504.0, "f97bff",
100000.0, "fa47c35000",
3.4028234663852886e+38, "fa7f7fffff",
1.0e+300, "fb7e37e43c8800759c",
5.960464477539063e-8, "f90001",
0.00006103515625, "f90400",
-4.0, "f9c400",
-4.1, "fbc010666666666666",
Infinity, "f97c00",
NaN, "f97e00",
-Infinity, "f9fc00",
Infinity, "fa7f800000",
NaN, "fa7fc00000",
-Infinity, "faff800000",
Infinity, "fb7ff0000000000000",
NaN, "fb7ff8000000000000",
-Infinity, "fbfff0000000000000",
false, "f4",
true, "f5",
null, "f6",
undefined, "f7",
new Simple(16), "f0",
new Simple(24), "f818",
new Simple(255), "f8ff",
new Date("2013-03-21T20:04:00Z"), "c074323031332d30332d32315432303a30343a30305a",
new Date(1363896240 * 1000), "c11a514b67b0",
new Date(1363896240.5 * 1000), "c1fb41d452d9ec200000",
new Tagged(23, new Uint8Array([1, 2, 3, 4])), "d74401020304",
new Tagged(24, new Uint8Array([0x64, 0x49, 0x45, 0x54, 0x46])), "d818456449455446",
new Tagged(32, "http://www.example.com"), "d82076687474703a2f2f7777772e6578616d706c652e636f6d",
new Uint8Array(0), "40",
new Uint8Array([1, 2, 3, 4]), "4401020304",
"", "60",
"a", "6161",
"IETF", "6449455446",
"\"\\", "62225c",
"\u00fc", "62c3bc",
"\u6c34", "63e6b0b4",
"\ud800\udd51", "64f0908591",
[], "80",
[1, 2, 3], "83010203",
[1, [2, 3], [4, 5]], "8301820203820405",
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25], "98190102030405060708090a0b0c0d0e0f101112131415161718181819",
{}, "a0",
{ 1: 2, 3: 4 }, "a201020304", // in JS keys are always strings
{ "a": 1, "b": [2, 3] }, "a26161016162820203",
["a", { "b": "c" }], "826161a161626163",
{ "a": "A", "b": "B", "c": "C", "d": "D", "e": "E" }, "a56161614161626142616361436164614461656145",
// Indefinite
new Uint8Array([1, 2, 3, 4, 5]), "5f42010243030405ff",
"streaming", "7f657374726561646d696e67ff",
[], "9fff",
[1, [2, 3], [4, 5]], "9f018202039f0405ffff",
[1, [2, 3], [4, 5]], "9f01820203820405ff",
[1, [2, 3], [4, 5]], "83018202039f0405ff",
[1, [2, 3], [4, 5]], "83019f0203ff820405",
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25],
"9f0102030405060708090a0b0c0d0e0f101112131415161718181819ff",
{ "a": 1, "b": [2, 3] }, "bf61610161629f0203ffff",
// Additional tests
0.333251953125, "f93555",
/^a[bc]+$/gi, "d8236c2f5e615b62635d2b242f6769"
];
describe("cbor", () => {
it("should encode and decode", () => {
const v = {
"one": 1,
"example array": [
new Uint8Array([1, 2, 3]),
"hello",
42,
-123456789,
123.456,
144115188075855870
],
"created": new Date("2016-05-14T16:44:15.000Z")
};
const encoded = encode(v);
const decoded = decode(encoded);
expect(decoded).toEqual(v);
});
it("should correctly encode test vectors", () => {
for (let i = 0; i < encoderTestVectors.length; i += 2) {
const value = encoderTestVectors[i];
const expected = encoderTestVectors[i + 1] as string;
const got = encode(value);
expect(hex.encode(got, true)).toBe(expected);
}
});
it("should correctly decode test vectors", () => {
for (let i = 0; i < decoderTestVectors.length; i += 2) {
const expected = decoderTestVectors[i];
const value = hex.decode(decoderTestVectors[i + 1] as string);
const got = decode(value);
expect(got).toEqual(expected);
}
});
it("should encode and decode -0.0", () => {
const encoded = encode(-0.0);
const decoded = decode(encoded);
expect(1 / decoded).toBe(-Infinity);
});
it("should throw if 64-bit integer is too large", () => {
const vectors = [
"1bffffffffffffffff", // 18446744073709551615
"3bffffffffffffffff", // -18446744073709551616
];
vectors.forEach(v => {
expect(() => decode(hex.decode(v))).toThrowError(/too large/);
});
});
it("should throw if there's extra data and the end", () => {
const encoded = concat(encode("Hello world"), new Uint8Array(1));
expect(() => decode(encoded)).toThrowError(/extra/);
});
it("should throw for objects cycles", () => {
const a: { [key: string]: any } = { "one": 1 };
const b: { [key: string]: any } = { "two": 2 };
// create cycle
b["a"] = a;
a["b"] = b;
// We expect JS runtime to throw "Maximum call stack size exceeded" error.
expect(() => encode(a)).toThrowError(/call stack/);
expect(() => encode(["insideArray", a])).toThrowError(/call stack/);
expect(() => encode({ "insideObject": a })).toThrowError(/call stack/);
});
it("should encode maps with integer keys differently from string keys", () => {
const a: { [key: string]: any } = { 1: "one", 2: "two", "3str": "three" };
const eai = encode(a, { intKeys: true });
// make sure it decodes
const dec = decode(eai);
expect(dec).toEqual(a);
// make sure it differs from string encoding
expect(encode(a)).not.toEqual(eai);
});
it("should encode and decode custom tagged object", () => {
class Hello {
greeting: string;
constructor(g: string) {
this.greeting = g;
}
get() {
return this.greeting;
}
}
const HelloEncoder: TaggedEncoder<Hello> =
h => {
if (!(h instanceof Hello)) {
return undefined;
}
return new Tagged(7777, h.get());
};
const HelloDecoder: TaggedDecoder<Hello> =
({ tag, value }) => {
if (tag !== 7777) {
return undefined;
}
if (typeof value !== "string") {
throw new Error(`cbor: unexpected type for Hello string: "${typeof value}"`);
}
return new Hello(value);
};
const testData = {
one: new Hello("world"),
two: new Date(123)
};
const encodedData = encode(testData, {
taggedEncoders: DEFAULT_TAGGED_ENCODERS.concat(HelloEncoder)
});
const decodedData = decode(encodedData, {
taggedDecoders: DEFAULT_TAGGED_DECODERS.concat(HelloDecoder)
});
expect(decodedData.one instanceof Hello).toBeTruthy();
expect(decodedData.one.greeting).toEqual(testData.one.greeting);
expect(decodedData.two instanceof Date).toBeTruthy();
});
}); | the_stack |
import { addComponent, Component, defineComponent, defineQuery, removeComponent } from "bitecs";
import { vec3, mat4 } from "gl-matrix";
import { GameState } from "../GameTypes";
import { shallowArraysEqual } from "../utils/shallowArraysEqual";
import {
AddComponentMessage,
//ExportGLTFMessage,
RemoveComponentMessage,
SelectionChangedMessage,
SetComponentPropertyMessage,
WorkerMessages,
WorkerMessageType,
} from "../WorkerMessage";
import {
ComponentPropertyGetter,
ComponentPropertyGetters,
ComponentPropertySetter,
ComponentPropertySetters,
} from "../component/serialization";
import {
ComponentInfo,
ComponentPropertyInfo,
ComponentPropertyValue,
ComponentPropertyType,
ComponentPropertyStore,
} from "../component/types";
import { getDirection, hierarchyObjectBuffer, registerTransformComponent, Transform } from "../component/transform";
import {
ActionMap,
ActionType,
BindingType,
ButtonActionState,
disableActionMap,
enableActionMap,
} from "../input/ActionMappingSystem";
import { getRaycastResults, raycast, createRay } from "../raycaster/raycaster.game";
import { TripleBuffer } from "../allocator/TripleBuffer";
import { defineModule, getModule, registerMessageHandler, Thread } from "../module/module.common";
import { InputModule } from "../input/input.game";
import {
EditorMessageType,
editorModuleName,
InitializeEditorStateMessage,
SharedHierarchyState,
} from "./editor.common";
import { hierarchyObjectBufferSchema } from "../component/transform.common";
import { commitToTripleBufferView, createTripleBufferBackedObjectBufferView } from "../allocator/ObjectBufferView";
// TODO: Importing this module changes the order of Renderable / Transform imports
// Which in turn changes the cursor buffer view order and breaks transforms.
//import { exportGLTF } from "../gltf/exportGLTF";
/*********
* Types *
********/
export interface EditorModuleState {
rayId: number;
editorLoaded: boolean;
messages: WorkerMessages[];
selectedEntities: number[];
activeEntity?: number;
activeEntityChanged: boolean;
componentIdMap: Map<Component, number>;
componentInfoMap: Map<number, ComponentInfo>;
propertyIdMap: Map<ComponentPropertyStore, number>;
propertyGetterMap: Map<number, ComponentPropertyGetter>;
propertySetterMap: Map<number, ComponentPropertySetter>;
componentAdderMap: Map<number, ComponentAdder>;
componentRemoverMap: Map<number, ComponentRemover>;
nextComponentId: number;
nextPropertyId: number;
sharedHierarchyState: SharedHierarchyState;
}
/******************
* Initialization *
*****************/
export const EditorModule = defineModule<GameState, EditorModuleState>({
name: editorModuleName,
async create(ctx, { sendMessage }) {
const sharedHierarchyState = createTripleBufferBackedObjectBufferView(
hierarchyObjectBufferSchema,
hierarchyObjectBuffer,
ctx.mainToGameTripleBufferFlags
);
sendMessage<InitializeEditorStateMessage>(Thread.Main, EditorMessageType.InitializeEditorState, {
sharedHierarchyState,
});
return {
rayId: createRay(),
editorLoaded: false,
messages: [],
selectedEntities: [],
activeEntity: undefined,
activeEntityChanged: false,
nextComponentId: 1,
componentIdMap: new Map(),
componentInfoMap: new Map(),
componentAdderMap: new Map(),
componentRemoverMap: new Map(),
nextPropertyId: 1,
propertyIdMap: new Map(),
propertyGetterMap: new Map(),
propertySetterMap: new Map(),
sharedHierarchyState,
};
},
init(ctx) {
const disposables = [
registerMessageHandler(ctx, WorkerMessageType.LoadEditor, onLoadEditor),
registerMessageHandler(ctx, WorkerMessageType.DisposeEditor, onDisposeEditor),
registerMessageHandler(ctx, WorkerMessageType.AddComponent, onEditorMessage),
registerMessageHandler(ctx, WorkerMessageType.RemoveComponent, onEditorMessage),
registerMessageHandler(ctx, WorkerMessageType.SetComponentProperty, onEditorMessage),
//registerMessageHandler(ctx, WorkerMessageType.ExportGLTF, onExportGLTF),
];
registerTransformComponent(ctx);
return () => {
for (const dispose of disposables) {
dispose();
}
};
},
});
export function onLoadEditor(state: GameState) {
const editor = getModule(state, EditorModule);
editor.editorLoaded = true;
enableActionMap(state, editorActionMap);
postMessage({
type: WorkerMessageType.EditorLoaded,
componentInfos: editor.componentInfoMap,
});
addComponent(state.world, Selected, state.camera);
}
export function onDisposeEditor(state: GameState) {
const editor = getModule(state, EditorModule);
editor.editorLoaded = false;
editor.messages.length = 0;
disableActionMap(state, editorActionMap);
}
export function onEditorMessage(state: GameState, message: any) {
const editor = getModule(state, EditorModule);
if (editor.editorLoaded) {
editor.messages.push(message);
}
}
function onAddComponent(state: GameState, message: AddComponentMessage) {
const editor = getModule(state, EditorModule);
const { entities, componentId, props } = message;
const adder = editor.componentAdderMap.get(componentId);
if (!adder) {
return;
}
// Should we make setters that take the full entity array to batch operations?
for (let i = 0; i < entities.length; i++) {
adder(state, entities[i], props);
}
}
function onRemoveComponent(state: GameState, message: RemoveComponentMessage) {
const editor = getModule(state, EditorModule);
const remover = editor.componentRemoverMap.get(message.componentId);
if (!remover) {
return;
}
// Should we make setters that take the full entity array to batch operations?
for (let i = 0; i < message.entities.length; i++) {
remover(state, message.entities[i]);
}
}
function onSetComponentProperty(state: GameState, message: SetComponentPropertyMessage) {
const editor = getModule(state, EditorModule);
const setter = editor.propertySetterMap.get(message.propertyId);
if (!setter) {
return;
}
// Should we make setters that take the full entity array to batch operations?
for (let i = 0; i < message.entities.length; i++) {
setter(state, message.entities[i], message.value);
}
}
// function onExportGLTF(state: GameState, message: ExportGLTFMessage) {
// exportGLTF(state, state.scene);
// }
/***********
* Systems *
**********/
export enum EditorActions {
select = "Editor/select",
}
const editorActionMap: ActionMap = {
id: "Editor",
actions: [
{
id: "select",
path: EditorActions.select,
type: ActionType.Button,
bindings: [
{
type: BindingType.Button,
path: "Keyboard/KeyG",
},
],
},
],
};
export const Selected = defineComponent({});
const selectedQuery = defineQuery([Selected]);
export function EditorStateSystem(state: GameState) {
const editor = getModule(state, EditorModule);
if (!editor.editorLoaded) {
return;
}
while (editor.messages.length) {
const msg = editor.messages.pop();
if (msg) processEditorMessage(state, msg);
}
const selectedEntities = selectedQuery(state.world);
if (!shallowArraysEqual(selectedEntities, editor.selectedEntities) || editor.activeEntityChanged) {
updateSelectedEntities(state, selectedEntities.slice());
}
commitToTripleBufferView(editor.sharedHierarchyState);
}
function processEditorMessage(state: GameState, message: WorkerMessages) {
switch (message.type) {
case WorkerMessageType.AddComponent:
onAddComponent(state, message);
break;
case WorkerMessageType.RemoveComponent:
onRemoveComponent(state, message);
break;
case WorkerMessageType.SetComponentProperty:
onSetComponentProperty(state, message);
break;
}
}
function updateSelectedEntities(state: GameState, selectedEntities: number[]) {
const editor = getModule(state, EditorModule);
editor.selectedEntities = selectedEntities;
const activeEntity = editor.activeEntity;
let activeEntityComponents: number[] | undefined;
let activeEntityTripleBuffer: TripleBuffer | undefined;
if (editor.activeEntityChanged) {
// TODO: collect active entity components and construct activeEntityTripleBuffer
}
postMessage({
type: WorkerMessageType.SelectionChanged,
selectedEntities,
activeEntity,
activeEntityComponents,
activeEntityTripleBuffer,
} as SelectionChangedMessage);
}
const editorRayId = 0;
export function EditorSelectionSystem(state: GameState) {
const editor = getModule(state, EditorModule);
if (!editor.editorLoaded) {
return;
}
const raycastResults = getRaycastResults(state, editorRayId);
if (raycastResults && raycastResults.length > 0) {
const intersection = raycastResults[raycastResults.length - 1];
const selectedEntities = editor.selectedEntities;
for (let i = 0; i < selectedEntities.length; i++) {
removeComponent(state.world, Selected, selectedEntities[i]);
}
addComponent(state.world, Selected, intersection.entity);
if (intersection.entity !== editor.activeEntity) {
editor.activeEntity = intersection.entity;
editor.activeEntityChanged = true;
}
}
const input = getModule(state, InputModule);
const select = input.actions.get(EditorActions.select) as ButtonActionState;
if (select.pressed) {
const direction = getDirection(vec3.create(), Transform.worldMatrix[state.camera]);
vec3.negate(direction, direction);
raycast(state, editorRayId, mat4.getTranslation(vec3.create(), Transform.worldMatrix[state.camera]), direction);
}
}
/**
* Component definitions (for editor, serialization/deserialization, and networking)
*/
export interface ComponentPropertyDefinition<PropType extends ComponentPropertyType> {
type: PropType;
store: ComponentPropertyStore<PropType>;
// In the future add properties like min/max for component property editors
}
export interface ComponentPropertyMap {
[name: string]: ComponentPropertyDefinition<ComponentPropertyType>;
}
export type ComponentPropertyValues<Props extends ComponentPropertyMap = {}> = Partial<{
[PropName in keyof Props]: ComponentPropertyValue<Props[PropName]["type"]>;
}>;
export type ComponentAdder<Props extends ComponentPropertyMap = {}> = (
state: GameState,
eid: number,
props?: ComponentPropertyValues<Props>
) => void;
export type ComponentRemover = (state: GameState, eid: number) => void;
export interface ComponentDefinition<Props extends ComponentPropertyMap = {}> {
name: string;
props: Props;
add: ComponentAdder<Props>;
remove: ComponentRemover;
}
export function registerEditorComponent<Props extends ComponentPropertyMap>(
state: GameState,
component: Component,
definition: ComponentDefinition<Props>
) {
const editor = getModule(state, EditorModule);
const props: ComponentPropertyInfo[] = [];
for (const [name, { type, store }] of Object.entries(definition.props)) {
const propertyId = editor.nextPropertyId++;
const propInfo: ComponentPropertyInfo = {
id: propertyId,
name,
type,
};
props.push(propInfo);
editor.propertyIdMap.set(store, propertyId);
editor.propertyGetterMap.set(propertyId, ComponentPropertyGetters[type](store));
editor.propertySetterMap.set(propertyId, ComponentPropertySetters[type](store));
}
const componentId = editor.nextComponentId++;
editor.componentIdMap.set(component, componentId);
editor.componentInfoMap.set(componentId, {
name: definition.name,
props,
});
editor.componentAdderMap.set(componentId, definition.add);
editor.componentRemoverMap.set(componentId, definition.remove);
} | the_stack |
import {
Address,
Algorithm,
Amount,
ChainId,
isSendTransaction,
isSwapAbortTransaction,
isSwapClaimTransaction,
isSwapOfferTransaction,
PubkeyBundle,
SendTransaction,
SwapAbortTransaction,
SwapClaimTransaction,
SwapOfferTransaction,
TimestampTimeout,
UnsignedTransaction,
} from "@iov/bcp";
import { As } from "type-tagger";
import * as codecImpl from "./generated/codecimpl";
// Internal (those are not used outside of @iov/bns)
export interface CashConfiguration {
readonly owner: Address;
readonly collectorAddress: Address;
readonly minimalFee: Amount | null;
}
export interface TxFeeConfiguration {
readonly owner: Address;
readonly freeBytes: number | null;
readonly baseFee: Amount | null;
}
export interface MsgFeeConfiguration {
readonly owner: Address;
readonly feeAdmin: Address | null;
}
export interface PreRegistrationConfiguration {
readonly owner: Address;
}
export interface QualityScoreConfiguration {
readonly owner: Address;
readonly c: Fraction;
readonly k: Fraction;
readonly kp: Fraction;
readonly q0: Fraction;
readonly x: Fraction;
readonly xInf: Fraction;
readonly xSup: Fraction;
readonly delta: Fraction;
}
// TermDepositStandardRate represents the horribly named IDepositBonus
export interface TermDepositStandardRate {
readonly lockinPeriod: number;
readonly rate: Fraction;
}
export interface TermDepositCustomRate {
readonly address: Address;
readonly rate: Fraction;
}
export interface TermDepositConfiguration {
readonly owner: Address;
readonly admin: Address | null;
readonly standardRates: readonly TermDepositStandardRate[]; // represents the horribly named "bonuses"
readonly customRates: readonly TermDepositCustomRate[]; // represents the horribly named "baseRates"
}
/**
* The message part of a bnsd.Tx
*
* @see https://htmlpreview.github.io/?https://github.com/iov-one/weave/blob/v0.24.0/docs/proto/index.html#bnsd.Tx
*/
export type BnsdTxMsg = Omit<codecImpl.bnsd.ITx, "fees" | "signatures" | "multisig">;
// Accounts NFT
export interface ChainAddressPair {
readonly chainId: ChainId;
readonly address: Address;
}
export interface BnsAccountByNameQuery {
readonly name: string;
}
export interface BnsAccountsByOwnerQuery {
readonly owner: Address;
}
export interface BnsAccountsByDomainQuery {
readonly domain: string;
}
export type BnsAccountsQuery = BnsAccountByNameQuery | BnsAccountsByOwnerQuery | BnsAccountsByDomainQuery;
export function isBnsAccountByNameQuery(query: BnsAccountsQuery): query is BnsAccountByNameQuery {
return typeof (query as BnsAccountByNameQuery).name !== "undefined";
}
export function isBnsAccountsByOwnerQuery(query: BnsAccountsQuery): query is BnsAccountsByOwnerQuery {
return typeof (query as BnsAccountsByOwnerQuery).owner !== "undefined";
}
export function isBnsAccountsByDomainQuery(query: BnsAccountsQuery): query is BnsAccountsByDomainQuery {
return typeof (query as BnsAccountsByDomainQuery).domain !== "undefined";
}
export interface BnsDomainByNameQuery {
readonly name: string;
}
export interface BnsDomainsByAdminQuery {
readonly admin: Address;
}
export type BnsDomainsQuery = BnsDomainByNameQuery | BnsDomainsByAdminQuery;
export function isBnsDomainByNameQuery(query: BnsDomainsQuery): query is BnsDomainByNameQuery {
return typeof (query as BnsDomainByNameQuery).name !== "undefined";
}
export function isBnsDomainsByAdminQuery(query: BnsDomainsQuery): query is BnsDomainsByAdminQuery {
return typeof (query as BnsDomainsByAdminQuery).admin !== "undefined";
}
export interface AccountConfiguration {
readonly owner: Address;
readonly validDomain: string;
readonly validName: string;
readonly validBlockchainId: string;
readonly validBlockchainAddress: string;
readonly domainRenew: number;
readonly domainGracePeriod: number;
}
export interface AccountMsgFee {
readonly msgPath: string;
readonly fee: Amount;
}
export interface AccountNft {
readonly domain: string;
readonly name?: string;
readonly owner: Address;
readonly validUntil: number;
readonly targets: readonly ChainAddressPair[];
readonly certificates: readonly Uint8Array[];
}
export interface Domain {
readonly domain: string;
readonly admin: Address;
readonly broker: Address;
readonly validUntil: number;
readonly hasSuperuser: boolean;
readonly msgFees: readonly AccountMsgFee[];
readonly accountRenew: number;
}
// Governance
export interface ValidatorProperties {
readonly power: number;
}
export interface Validator extends ValidatorProperties {
readonly pubkey: PubkeyBundle;
}
/**
* An unordered map from validator pubkey address to remaining properies
*
* The string key is in the form `ed25519_<pubkey_hex>`
*/
export interface Validators {
readonly [index: string]: ValidatorProperties;
}
/** Like Elector from the backend but without the address field */
export interface ElectorProperties {
/** The voting weight of this elector. Max value is 65535 (2^16-1). */
readonly weight: number;
}
export interface Elector extends ElectorProperties {
readonly address: Address;
}
/** An unordered map from elector address to remaining properies */
export interface Electors {
readonly [index: string]: ElectorProperties;
}
export interface Electorate {
readonly id: number;
readonly version: number;
readonly admin: Address;
readonly title: string;
readonly electors: Electors;
/** Sum of all electors' weights */
readonly totalWeight: number;
}
export interface Fraction {
readonly numerator: number;
readonly denominator: number;
}
export interface ElectionRule {
readonly id: number;
readonly version: number;
readonly admin: Address;
/**
* The eligible voters in this rule.
*
* This is an unversioned ID (see `id` field in weave's VersionedIDRef), meaning the
* electorate can change over time without changing this ID. When a proposal with this
* rule is created, the latest version of the electorate will be used.
*/
readonly electorateId: number;
readonly title: string;
/** Voting period in seconds */
readonly votingPeriod: number;
readonly threshold: Fraction;
readonly quorum: Fraction | null;
}
export interface VersionedId {
readonly id: number;
readonly version: number;
}
export enum ProposalExecutorResult {
NotRun,
Succeeded,
Failed,
}
export enum ProposalResult {
Undefined,
Accepted,
Rejected,
}
export enum ProposalStatus {
Submitted,
Closed,
Withdrawn,
}
/**
* Raw values are used for the JSON representation (e.g. in the wallet to browser extension communication)
* and must remain unchanged across different semver compatible versions of IOV Core.
*/
export enum VoteOption {
Yes = "yes",
No = "no",
Abstain = "abstain",
}
export enum ActionKind {
CreateTextResolution = "gov_create_text_resolution",
ExecuteProposalBatch = "execute_proposal_batch",
ReleaseEscrow = "escrow_release",
Send = "cash_send",
SetMsgFee = "msgfee_set_msg_fee",
SetValidators = "validators_apply_diff",
UpdateElectionRule = "gov_update_election_rule",
UpdateElectorate = "gov_update_electorate",
ExecuteMigration = "datamigration_execute_migration",
UpgradeSchema = "migration_upgrade_schema",
SetMsgFeeConfiguration = "msgfee_update_configuration_msg",
SetPreRegistrationConfiguration = "preregistration_update_configuration_msg",
SetQualityScoreConfiguration = "qualityscore_update_configuration_msg",
SetTermDepositConfiguration = "termdeposit_update_configuration_msg",
SetTxFeeConfiguration = "txfee_update_configuration_msg",
SetCashConfiguration = "cash_update_configuration_msg",
SetAccountConfiguration = "account_update_configuration_msg",
RegisterDomain = "account_register_domain_msg",
RenewDomain = "account_renew_domain_msg",
SetAccountMsgFees = "account_replace_account_msg_fees_msg",
SetAccountTargets = "account_replace_account_targets_msg",
AddAccountCertificate = "account_add_account_certificate_msg",
DeleteAccountCertificate = "account_delete_account_certificate_msg",
}
export interface TallyResult {
readonly totalYes: number;
readonly totalNo: number;
readonly totalAbstain: number;
readonly totalElectorateWeight: number;
}
export interface CreateTextResolutionAction {
readonly kind: ActionKind.CreateTextResolution;
readonly resolution: string;
}
export function isCreateTextResolutionAction(action: ProposalAction): action is CreateTextResolutionAction {
return action.kind === ActionKind.CreateTextResolution;
}
export interface ExecuteProposalBatchAction {
readonly kind: ActionKind.ExecuteProposalBatch;
readonly messages: readonly ProposalAction[];
}
export function isExecuteProposalBatchAction(action: ProposalAction): action is ExecuteProposalBatchAction {
return action.kind === ActionKind.ExecuteProposalBatch;
}
export interface ReleaseEscrowAction {
readonly kind: ActionKind.ReleaseEscrow;
readonly escrowId: number;
readonly amount: Amount;
}
export function isReleaseEscrowAction(action: ProposalAction): action is ReleaseEscrowAction {
return action.kind === ActionKind.ReleaseEscrow;
}
export interface SendAction {
readonly kind: ActionKind.Send;
readonly sender: Address;
readonly recipient: Address;
readonly amount: Amount;
readonly memo?: string;
}
export function isSendAction(action: ProposalAction): action is SendAction {
return action.kind === ActionKind.Send;
}
export interface SetMsgFeeAction {
readonly kind: ActionKind.SetMsgFee;
readonly msgPath: string;
readonly fee: Amount;
}
export function isSetMsgFeeAction(action: ProposalAction): action is SetMsgFeeAction {
return action.kind === ActionKind.SetMsgFee;
}
export interface SetValidatorsAction {
readonly kind: ActionKind.SetValidators;
readonly validatorUpdates: Validators;
}
export function isSetValidatorsAction(action: ProposalAction): action is SetValidatorsAction {
return action.kind === ActionKind.SetValidators;
}
export interface UpdateElectionRuleAction {
readonly kind: ActionKind.UpdateElectionRule;
readonly electionRuleId: number;
readonly threshold?: Fraction;
readonly quorum?: Fraction | null;
readonly votingPeriod: number;
}
export function isUpdateElectionRuleAction(action: ProposalAction): action is UpdateElectionRuleAction {
return action.kind === ActionKind.UpdateElectionRule;
}
export interface UpdateElectorateAction {
readonly kind: ActionKind.UpdateElectorate;
readonly electorateId: number;
readonly diffElectors: Electors;
}
export function isUpdateElectorateAction(action: ProposalAction): action is UpdateElectorateAction {
return action.kind === ActionKind.UpdateElectorate;
}
export interface ExecuteMigrationAction {
readonly kind: ActionKind.ExecuteMigration;
readonly id: string;
}
export function isExecuteMigrationAction(action: ProposalAction): action is ExecuteMigrationAction {
return action.kind === ActionKind.ExecuteMigration;
}
export interface UpgradeSchemaAction {
readonly kind: ActionKind.UpgradeSchema;
readonly pkg: string;
readonly toVersion: number;
}
export function isUpgradeSchemaAction(action: ProposalAction): action is UpgradeSchemaAction {
return action.kind === ActionKind.UpgradeSchema;
}
export interface SetMsgFeeConfigurationAction {
readonly kind: ActionKind.SetMsgFeeConfiguration;
readonly patch: MsgFeeConfiguration;
}
export function isSetMsgFeeConfigurationAction(
action: ProposalAction,
): action is SetMsgFeeConfigurationAction {
return action.kind === ActionKind.SetMsgFeeConfiguration;
}
export interface SetPreRegistrationConfigurationAction {
readonly kind: ActionKind.SetPreRegistrationConfiguration;
readonly patch: PreRegistrationConfiguration;
}
export function isSetPreRegistrationConfigurationAction(
action: ProposalAction,
): action is SetPreRegistrationConfigurationAction {
return action.kind === ActionKind.SetPreRegistrationConfiguration;
}
export interface SetQualityScoreConfigurationAction {
readonly kind: ActionKind.SetQualityScoreConfiguration;
readonly patch: QualityScoreConfiguration;
}
export function isSetQualityScoreConfigurationAction(
action: ProposalAction,
): action is SetQualityScoreConfigurationAction {
return action.kind === ActionKind.SetQualityScoreConfiguration;
}
export interface SetTermDepositConfigurationAction {
readonly kind: ActionKind.SetTermDepositConfiguration;
readonly patch: TermDepositConfiguration;
}
export function isSetTermDepositConfigurationAction(
action: ProposalAction,
): action is SetTermDepositConfigurationAction {
return action.kind === ActionKind.SetTermDepositConfiguration;
}
export interface SetTxFeeConfigurationAction {
readonly kind: ActionKind.SetTxFeeConfiguration;
readonly patch: TxFeeConfiguration;
}
export function isSetTxFeeConfigurationAction(action: ProposalAction): action is SetTxFeeConfigurationAction {
return action.kind === ActionKind.SetTxFeeConfiguration;
}
export interface SetCashConfigurationAction {
readonly kind: ActionKind.SetCashConfiguration;
readonly patch: CashConfiguration;
}
export function isSetCashConfigurationAction(action: ProposalAction): action is SetCashConfigurationAction {
return action.kind === ActionKind.SetCashConfiguration;
}
export interface SetAccountConfigurationAction {
readonly kind: ActionKind.SetAccountConfiguration;
readonly patch: AccountConfiguration;
}
export function isSetAccountConfigurationAction(
action: ProposalAction,
): action is SetAccountConfigurationAction {
return action.kind === ActionKind.SetAccountConfiguration;
}
export interface RegisterDomainAction {
readonly kind: ActionKind.RegisterDomain;
readonly domain: string;
readonly admin: Address;
readonly broker?: Address;
readonly hasSuperuser: boolean;
readonly msgFees: readonly AccountMsgFee[];
readonly accountRenew: number;
}
export function isRegisterDomainAction(action: ProposalAction): action is RegisterDomainAction {
return action.kind === ActionKind.RegisterDomain;
}
export interface RenewDomainAction {
readonly kind: ActionKind.RenewDomain;
readonly domain: string;
}
export function isRenewDomainAction(action: ProposalAction): action is RenewDomainAction {
return action.kind === ActionKind.RenewDomain;
}
export interface SetAccountMsgFeesAction {
readonly kind: ActionKind.SetAccountMsgFees;
readonly domain: string;
readonly newMsgFees: readonly AccountMsgFee[];
}
export function isSetAccountMsgFeesAction(action: ProposalAction): action is SetAccountMsgFeesAction {
return action.kind === ActionKind.SetAccountMsgFees;
}
export interface SetAccountTargetsAction {
readonly kind: ActionKind.SetAccountTargets;
readonly domain: string;
readonly name: string;
readonly newTargets: readonly ChainAddressPair[];
}
export function isSetAccountTargetsAction(action: ProposalAction): action is SetAccountTargetsAction {
return action.kind === ActionKind.SetAccountTargets;
}
export interface AddAccountCertificateAction {
readonly kind: ActionKind.AddAccountCertificate;
readonly domain: string;
readonly name: string;
readonly certificate: Uint8Array;
}
export function isAddAccountCertificateAction(action: ProposalAction): action is AddAccountCertificateAction {
return action.kind === ActionKind.AddAccountCertificate;
}
export interface DeleteAccountCertificateAction {
readonly kind: ActionKind.DeleteAccountCertificate;
readonly domain: string;
readonly name: string;
readonly certificateHash: Uint8Array;
}
export function isDeleteAccountCertificateAction(
action: ProposalAction,
): action is DeleteAccountCertificateAction {
return action.kind === ActionKind.DeleteAccountCertificate;
}
/** The action to be executed when the proposal is accepted */
export type ProposalAction =
| CreateTextResolutionAction
| ExecuteProposalBatchAction
| ReleaseEscrowAction
| SendAction
| SetMsgFeeAction
| SetValidatorsAction
| UpdateElectorateAction
| UpdateElectionRuleAction
| ExecuteMigrationAction
| UpgradeSchemaAction
| SetMsgFeeConfigurationAction
| SetPreRegistrationConfigurationAction
| SetQualityScoreConfigurationAction
| SetTermDepositConfigurationAction
| SetTxFeeConfigurationAction
| SetCashConfigurationAction
| SetAccountConfigurationAction
| RegisterDomainAction
| RenewDomainAction
| SetAccountMsgFeesAction
| SetAccountTargetsAction
| AddAccountCertificateAction
| DeleteAccountCertificateAction;
export interface Proposal {
readonly id: number;
readonly title: string;
/**
* The transaction to be executed when the proposal is accepted
*
* This is one of the actions from
* https://htmlpreview.github.io/?https://github.com/iov-one/weave/blob/v0.16.0/docs/proto/index.html#app.ProposalOptions
*/
readonly action: ProposalAction;
readonly description: string;
readonly electionRule: VersionedId;
readonly electorate: VersionedId;
/** Time when the voting on this proposal starts (Unix timestamp) */
readonly votingStartTime: number;
/** Time when the voting on this proposal starts (Unix timestamp) */
readonly votingEndTime: number;
/** Time of the block where the proposal was added to the chain (Unix timestamp) */
readonly submissionTime: number;
/** The author of the proposal must be included in the list of transaction signers. */
readonly author: Address;
readonly state: TallyResult;
readonly status: ProposalStatus;
readonly result: ProposalResult;
readonly executorResult: ProposalExecutorResult;
}
export interface Vote {
readonly proposalId: number;
readonly elector: Elector;
readonly selection: VoteOption;
}
// username NFT
export interface BnsUsernameNft {
readonly id: string;
readonly owner: Address;
readonly targets: readonly ChainAddressPair[];
}
export interface BnsUsernamesByUsernameQuery {
readonly username: string;
}
export interface BnsUsernamesByOwnerQuery {
readonly owner: Address;
}
export type BnsUsernamesQuery = BnsUsernamesByUsernameQuery | BnsUsernamesByOwnerQuery;
export function isBnsUsernamesByUsernameQuery(
query: BnsUsernamesQuery,
): query is BnsUsernamesByUsernameQuery {
return typeof (query as BnsUsernamesByUsernameQuery).username !== "undefined";
}
export function isBnsUsernamesByOwnerQuery(query: BnsUsernamesQuery): query is BnsUsernamesByOwnerQuery {
return typeof (query as BnsUsernamesByOwnerQuery).owner !== "undefined";
}
// Rest
export type PrivkeyBytes = Uint8Array & As<"privkey-bytes">;
export interface PrivkeyBundle {
readonly algo: Algorithm;
readonly data: PrivkeyBytes;
}
export interface Result {
readonly key: Uint8Array;
readonly value: Uint8Array;
}
export interface Keyed {
readonly _id: Uint8Array;
}
export interface Decoder<T extends {}> {
readonly decode: (data: Uint8Array) => T;
}
// Transactions: Usernames
export interface RegisterUsernameTx extends UnsignedTransaction {
readonly kind: "bns/register_username";
readonly username: string;
readonly targets: readonly ChainAddressPair[];
}
export function isRegisterUsernameTx(tx: UnsignedTransaction): tx is RegisterUsernameTx {
return tx.kind === "bns/register_username";
}
export interface UpdateTargetsOfUsernameTx extends UnsignedTransaction {
readonly kind: "bns/update_targets_of_username";
/** the username to be updated, must exist on chain */
readonly username: string;
readonly targets: readonly ChainAddressPair[];
}
export function isUpdateTargetsOfUsernameTx(tx: UnsignedTransaction): tx is UpdateTargetsOfUsernameTx {
return tx.kind === "bns/update_targets_of_username";
}
export interface TransferUsernameTx extends UnsignedTransaction {
readonly kind: "bns/transfer_username";
/** the username to be transferred, must exist on chain */
readonly username: string;
readonly newOwner: Address;
}
export function isTransferUsernameTx(tx: UnsignedTransaction): tx is TransferUsernameTx {
return tx.kind === "bns/transfer_username";
}
// Transactions: Accounts
export interface UpdateAccountConfigurationTx extends UnsignedTransaction {
readonly kind: "bns/update_account_configuration";
readonly configuration: AccountConfiguration;
}
export function isUpdateAccountConfigurationTx(tx: UnsignedTransaction): tx is UpdateAccountConfigurationTx {
return tx.kind === "bns/update_account_configuration";
}
export interface RegisterDomainTx extends UnsignedTransaction {
readonly kind: "bns/register_domain";
readonly domain: string;
readonly admin: Address;
readonly hasSuperuser: boolean;
readonly broker?: Address;
readonly msgFees: readonly AccountMsgFee[];
readonly accountRenew: number;
}
export function isRegisterDomainTx(tx: UnsignedTransaction): tx is RegisterDomainTx {
return tx.kind === "bns/register_domain";
}
export interface TransferDomainTx extends UnsignedTransaction {
readonly kind: "bns/transfer_domain";
readonly domain: string;
readonly newAdmin: Address;
}
export function isTransferDomainTx(tx: UnsignedTransaction): tx is TransferDomainTx {
return tx.kind === "bns/transfer_domain";
}
export interface RenewDomainTx extends UnsignedTransaction {
readonly kind: "bns/renew_domain";
readonly domain: string;
}
export function isRenewDomainTx(tx: UnsignedTransaction): tx is RenewDomainTx {
return tx.kind === "bns/renew_domain";
}
export interface DeleteDomainTx extends UnsignedTransaction {
readonly kind: "bns/delete_domain";
readonly domain: string;
}
export function isDeleteDomainTx(tx: UnsignedTransaction): tx is DeleteDomainTx {
return tx.kind === "bns/delete_domain";
}
export interface RegisterAccountTx extends UnsignedTransaction {
readonly kind: "bns/register_account";
readonly domain: string;
readonly name: string;
readonly owner: Address;
readonly targets: readonly ChainAddressPair[];
readonly broker?: Address;
}
export function isRegisterAccountTx(tx: UnsignedTransaction): tx is RegisterAccountTx {
return tx.kind === "bns/register_account";
}
export interface TransferAccountTx extends UnsignedTransaction {
readonly kind: "bns/transfer_account";
readonly domain: string;
readonly name: string;
readonly newOwner: Address;
}
export function isTransferAccountTx(tx: UnsignedTransaction): tx is TransferAccountTx {
return tx.kind === "bns/transfer_account";
}
export interface ReplaceAccountTargetsTx extends UnsignedTransaction {
readonly kind: "bns/replace_account_targets";
readonly domain: string;
readonly name: string | undefined;
readonly newTargets: readonly ChainAddressPair[];
}
export function isReplaceAccountTargetsTx(tx: UnsignedTransaction): tx is ReplaceAccountTargetsTx {
return tx.kind === "bns/replace_account_targets";
}
export interface DeleteAccountTx extends UnsignedTransaction {
readonly kind: "bns/delete_account";
readonly domain: string;
readonly name: string;
}
export function isDeleteAccountTx(tx: UnsignedTransaction): tx is DeleteAccountTx {
return tx.kind === "bns/delete_account";
}
export interface DeleteAllAccountsTx extends UnsignedTransaction {
readonly kind: "bns/delete_all_accounts";
readonly domain: string;
}
export function isDeleteAllAccountsTx(tx: UnsignedTransaction): tx is DeleteAllAccountsTx {
return tx.kind === "bns/delete_all_accounts";
}
export interface RenewAccountTx extends UnsignedTransaction {
readonly kind: "bns/renew_account";
readonly domain: string;
readonly name: string;
}
export function isRenewAccountTx(tx: UnsignedTransaction): tx is RenewAccountTx {
return tx.kind === "bns/renew_account";
}
export interface AddAccountCertificateTx extends UnsignedTransaction {
readonly kind: "bns/add_account_certificate";
readonly domain: string;
readonly name: string;
readonly certificate: Uint8Array;
}
export function isAddAccountCertificateTx(tx: UnsignedTransaction): tx is AddAccountCertificateTx {
return tx.kind === "bns/add_account_certificate";
}
export interface ReplaceAccountMsgFeesTx extends UnsignedTransaction {
readonly kind: "bns/replace_account_msg_fees";
readonly domain: string;
readonly newMsgFees: readonly AccountMsgFee[];
}
export function isReplaceAccountMsgFeesTx(tx: UnsignedTransaction): tx is ReplaceAccountMsgFeesTx {
return tx.kind === "bns/replace_account_msg_fees";
}
export interface DeleteAccountCertificateTx extends UnsignedTransaction {
readonly kind: "bns/delete_account_certificate";
readonly domain: string;
readonly name: string;
readonly certificateHash: Uint8Array;
}
export function isDeleteAccountCertificateTx(tx: UnsignedTransaction): tx is DeleteAccountCertificateTx {
return tx.kind === "bns/delete_account_certificate";
}
// Transactions: Multisignature contracts
export interface Participant {
readonly address: Address;
readonly weight: number;
}
export interface CreateMultisignatureTx extends UnsignedTransaction {
readonly kind: "bns/create_multisignature_contract";
readonly participants: readonly Participant[];
readonly activationThreshold: number;
readonly adminThreshold: number;
}
export function isCreateMultisignatureTx(tx: UnsignedTransaction): tx is CreateMultisignatureTx {
return tx.kind === "bns/create_multisignature_contract";
}
export interface UpdateMultisignatureTx extends UnsignedTransaction {
readonly kind: "bns/update_multisignature_contract";
readonly contractId: number;
readonly participants: readonly Participant[];
readonly activationThreshold: number;
readonly adminThreshold: number;
}
export function isUpdateMultisignatureTx(tx: UnsignedTransaction): tx is UpdateMultisignatureTx {
return tx.kind === "bns/update_multisignature_contract";
}
// Transactions: Escrows
export interface CreateEscrowTx extends UnsignedTransaction {
readonly kind: "bns/create_escrow";
readonly sender: Address;
readonly arbiter: Address;
readonly recipient: Address;
readonly amounts: readonly Amount[];
readonly timeout: TimestampTimeout;
readonly memo?: string;
}
export function isCreateEscrowTx(tx: UnsignedTransaction): tx is CreateEscrowTx {
return tx.kind === "bns/create_escrow";
}
export interface ReleaseEscrowTx extends UnsignedTransaction {
readonly kind: "bns/release_escrow";
readonly escrowId: number;
readonly amounts: readonly Amount[];
}
export function isReleaseEscrowTx(tx: UnsignedTransaction): tx is ReleaseEscrowTx {
return tx.kind === "bns/release_escrow";
}
export interface ReturnEscrowTx extends UnsignedTransaction {
readonly kind: "bns/return_escrow";
readonly escrowId: number;
}
export function isReturnEscrowTx(tx: UnsignedTransaction): tx is ReturnEscrowTx {
return tx.kind === "bns/return_escrow";
}
export interface UpdateEscrowPartiesTx extends UnsignedTransaction {
readonly kind: "bns/update_escrow_parties";
readonly escrowId: number;
readonly sender?: Address;
readonly arbiter?: Address;
readonly recipient?: Address;
}
export function isUpdateEscrowPartiesTx(tx: UnsignedTransaction): tx is UpdateEscrowPartiesTx {
return tx.kind === "bns/update_escrow_parties";
}
// Transactions: Governance
export interface CreateProposalTx extends UnsignedTransaction {
readonly kind: "bns/create_proposal";
readonly title: string;
/**
* The transaction to be executed when the proposal is accepted
*
* This is one of the actions from
* https://htmlpreview.github.io/?https://github.com/iov-one/weave/blob/v0.16.0/docs/proto/index.html#app.ProposalOptions
*/
readonly action: ProposalAction;
readonly description: string;
readonly electionRuleId: number;
/** Unix timestamp when the proposal starts */
readonly startTime: number;
/** The author of the proposal must be included in the list of transaction signers. */
readonly author: Address;
}
export function isCreateProposalTx(transaction: UnsignedTransaction): transaction is CreateProposalTx {
return transaction.kind === "bns/create_proposal";
}
export interface VoteTx extends UnsignedTransaction {
readonly kind: "bns/vote";
readonly proposalId: number;
readonly selection: VoteOption;
/**
* Voter should be set explicitly to avoid falling back to the first signer,
* which is potentially insecure. When encoding a new transaction, this field
* is required. Not all transaction from blockchain history have a voter set.
*/
readonly voter: Address | null;
}
export function isVoteTx(transaction: UnsignedTransaction): transaction is VoteTx {
return transaction.kind === "bns/vote";
}
// Transactions: BNS
export type BnsTx =
// BCP: Token sends
| SendTransaction
// BCP: Atomic swaps
| SwapOfferTransaction
| SwapClaimTransaction
| SwapAbortTransaction
// BNS: Usernames
| RegisterUsernameTx
| UpdateTargetsOfUsernameTx
| TransferUsernameTx
// BNS: Accounts
| UpdateAccountConfigurationTx
| RegisterDomainTx
| TransferDomainTx
| RenewDomainTx
| DeleteDomainTx
| RegisterAccountTx
| TransferAccountTx
| ReplaceAccountTargetsTx
| DeleteAccountTx
| DeleteAllAccountsTx
| RenewAccountTx
| AddAccountCertificateTx
| ReplaceAccountMsgFeesTx
| DeleteAccountCertificateTx
// BNS: Multisignature contracts
| CreateMultisignatureTx
| UpdateMultisignatureTx
// BNS: Escrows
| CreateEscrowTx
| ReleaseEscrowTx
| ReturnEscrowTx
| UpdateEscrowPartiesTx
// BNS: Governance
| CreateProposalTx
| VoteTx;
export function isBnsTx(transaction: UnsignedTransaction): transaction is BnsTx {
if (
isSendTransaction(transaction) ||
isSwapOfferTransaction(transaction) ||
isSwapClaimTransaction(transaction) ||
isSwapAbortTransaction(transaction)
) {
return true;
}
return transaction.kind.startsWith("bns/");
}
export interface MultisignatureTx extends UnsignedTransaction {
readonly multisig: readonly number[];
}
export function isMultisignatureTx(transaction: UnsignedTransaction): transaction is MultisignatureTx {
return (
Array.isArray((transaction as any).multisig) &&
(transaction as any).multisig.every((id: any) => typeof id === "number")
);
} | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* AuthorizationOperations
* __NOTE__: An instance of this class is automatically created for an
* instance of the ManagementLockClient.
*/
export interface AuthorizationOperations {
/**
* Lists all of the available Microsoft.Authorization REST API operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>;
/**
* Lists all of the available Microsoft.Authorization REST API operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>;
list(callback: ServiceCallback<models.OperationListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void;
/**
* Lists all of the available Microsoft.Authorization REST API operations.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>;
/**
* Lists all of the available Microsoft.Authorization REST API operations.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void;
}
/**
* @class
* ManagementLocks
* __NOTE__: An instance of this class is automatically created for an
* instance of the ManagementLockClient.
*/
export interface ManagementLocks {
/**
* @summary Creates or updates a management lock at the resource group level.
*
* When you apply a lock at a parent scope, all child resources inherit the
* same lock. To create management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} resourceGroupName The name of the resource group to lock.
*
* @param {string} lockName The lock name. The lock name can be a maximum of
* 260 characters. It cannot contain <, > %, &, :, \, ?, /, or any control
* characters.
*
* @param {object} parameters The management lock parameters.
*
* @param {string} parameters.level The level of the lock. Possible values are:
* NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users
* are able to read and modify the resources, but not delete. ReadOnly means
* authorized users can only read from a resource, but they can't modify or
* delete it. Possible values include: 'NotSpecified', 'CanNotDelete',
* 'ReadOnly'
*
* @param {string} [parameters.notes] Notes about the lock. Maximum of 512
* characters.
*
* @param {array} [parameters.owners] The owners of the lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockObject>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateAtResourceGroupLevelWithHttpOperationResponse(resourceGroupName: string, lockName: string, parameters: models.ManagementLockObject, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockObject>>;
/**
* @summary Creates or updates a management lock at the resource group level.
*
* When you apply a lock at a parent scope, all child resources inherit the
* same lock. To create management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} resourceGroupName The name of the resource group to lock.
*
* @param {string} lockName The lock name. The lock name can be a maximum of
* 260 characters. It cannot contain <, > %, &, :, \, ?, /, or any control
* characters.
*
* @param {object} parameters The management lock parameters.
*
* @param {string} parameters.level The level of the lock. Possible values are:
* NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users
* are able to read and modify the resources, but not delete. ReadOnly means
* authorized users can only read from a resource, but they can't modify or
* delete it. Possible values include: 'NotSpecified', 'CanNotDelete',
* 'ReadOnly'
*
* @param {string} [parameters.notes] Notes about the lock. Maximum of 512
* characters.
*
* @param {array} [parameters.owners] The owners of the lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockObject} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockObject} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockObject} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdateAtResourceGroupLevel(resourceGroupName: string, lockName: string, parameters: models.ManagementLockObject, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockObject>;
createOrUpdateAtResourceGroupLevel(resourceGroupName: string, lockName: string, parameters: models.ManagementLockObject, callback: ServiceCallback<models.ManagementLockObject>): void;
createOrUpdateAtResourceGroupLevel(resourceGroupName: string, lockName: string, parameters: models.ManagementLockObject, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockObject>): void;
/**
* @summary Deletes a management lock at the resource group level.
*
* To delete management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} resourceGroupName The name of the resource group containing
* the lock.
*
* @param {string} lockName The name of lock to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteAtResourceGroupLevelWithHttpOperationResponse(resourceGroupName: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* @summary Deletes a management lock at the resource group level.
*
* To delete management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} resourceGroupName The name of the resource group containing
* the lock.
*
* @param {string} lockName The name of lock to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteAtResourceGroupLevel(resourceGroupName: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteAtResourceGroupLevel(resourceGroupName: string, lockName: string, callback: ServiceCallback<void>): void;
deleteAtResourceGroupLevel(resourceGroupName: string, lockName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Gets a management lock at the resource group level.
*
* @param {string} resourceGroupName The name of the locked resource group.
*
* @param {string} lockName The name of the lock to get.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockObject>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getAtResourceGroupLevelWithHttpOperationResponse(resourceGroupName: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockObject>>;
/**
* Gets a management lock at the resource group level.
*
* @param {string} resourceGroupName The name of the locked resource group.
*
* @param {string} lockName The name of the lock to get.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockObject} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockObject} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockObject} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
getAtResourceGroupLevel(resourceGroupName: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockObject>;
getAtResourceGroupLevel(resourceGroupName: string, lockName: string, callback: ServiceCallback<models.ManagementLockObject>): void;
getAtResourceGroupLevel(resourceGroupName: string, lockName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockObject>): void;
/**
* Create or update a management lock by scope.
*
* @param {string} scope The scope for the lock. When providing a scope for the
* assignment, use '/subscriptions/{subscriptionId}' for subscriptions,
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for
* resource groups, and
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}'
* for resources.
*
* @param {string} lockName The name of lock.
*
* @param {object} parameters Create or update management lock parameters.
*
* @param {string} parameters.level The level of the lock. Possible values are:
* NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users
* are able to read and modify the resources, but not delete. ReadOnly means
* authorized users can only read from a resource, but they can't modify or
* delete it. Possible values include: 'NotSpecified', 'CanNotDelete',
* 'ReadOnly'
*
* @param {string} [parameters.notes] Notes about the lock. Maximum of 512
* characters.
*
* @param {array} [parameters.owners] The owners of the lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockObject>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateByScopeWithHttpOperationResponse(scope: string, lockName: string, parameters: models.ManagementLockObject, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockObject>>;
/**
* Create or update a management lock by scope.
*
* @param {string} scope The scope for the lock. When providing a scope for the
* assignment, use '/subscriptions/{subscriptionId}' for subscriptions,
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}' for
* resource groups, and
* '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePathIfPresent}/{resourceType}/{resourceName}'
* for resources.
*
* @param {string} lockName The name of lock.
*
* @param {object} parameters Create or update management lock parameters.
*
* @param {string} parameters.level The level of the lock. Possible values are:
* NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users
* are able to read and modify the resources, but not delete. ReadOnly means
* authorized users can only read from a resource, but they can't modify or
* delete it. Possible values include: 'NotSpecified', 'CanNotDelete',
* 'ReadOnly'
*
* @param {string} [parameters.notes] Notes about the lock. Maximum of 512
* characters.
*
* @param {array} [parameters.owners] The owners of the lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockObject} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockObject} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockObject} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdateByScope(scope: string, lockName: string, parameters: models.ManagementLockObject, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockObject>;
createOrUpdateByScope(scope: string, lockName: string, parameters: models.ManagementLockObject, callback: ServiceCallback<models.ManagementLockObject>): void;
createOrUpdateByScope(scope: string, lockName: string, parameters: models.ManagementLockObject, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockObject>): void;
/**
* Delete a management lock by scope.
*
* @param {string} scope The scope for the lock.
*
* @param {string} lockName The name of lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteByScopeWithHttpOperationResponse(scope: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Delete a management lock by scope.
*
* @param {string} scope The scope for the lock.
*
* @param {string} lockName The name of lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteByScope(scope: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteByScope(scope: string, lockName: string, callback: ServiceCallback<void>): void;
deleteByScope(scope: string, lockName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Get a management lock by scope.
*
* @param {string} scope The scope for the lock.
*
* @param {string} lockName The name of lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockObject>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getByScopeWithHttpOperationResponse(scope: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockObject>>;
/**
* Get a management lock by scope.
*
* @param {string} scope The scope for the lock.
*
* @param {string} lockName The name of lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockObject} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockObject} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockObject} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
getByScope(scope: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockObject>;
getByScope(scope: string, lockName: string, callback: ServiceCallback<models.ManagementLockObject>): void;
getByScope(scope: string, lockName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockObject>): void;
/**
* @summary Creates or updates a management lock at the resource level or any
* level below the resource.
*
* When you apply a lock at a parent scope, all child resources inherit the
* same lock. To create management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} resourceGroupName The name of the resource group containing
* the resource to lock.
*
* @param {string} resourceProviderNamespace The resource provider namespace of
* the resource to lock.
*
* @param {string} parentResourcePath The parent resource identity.
*
* @param {string} resourceType The resource type of the resource to lock.
*
* @param {string} resourceName The name of the resource to lock.
*
* @param {string} lockName The name of lock. The lock name can be a maximum of
* 260 characters. It cannot contain <, > %, &, :, \, ?, /, or any control
* characters.
*
* @param {object} parameters Parameters for creating or updating a management
* lock.
*
* @param {string} parameters.level The level of the lock. Possible values are:
* NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users
* are able to read and modify the resources, but not delete. ReadOnly means
* authorized users can only read from a resource, but they can't modify or
* delete it. Possible values include: 'NotSpecified', 'CanNotDelete',
* 'ReadOnly'
*
* @param {string} [parameters.notes] Notes about the lock. Maximum of 512
* characters.
*
* @param {array} [parameters.owners] The owners of the lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockObject>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateAtResourceLevelWithHttpOperationResponse(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, parameters: models.ManagementLockObject, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockObject>>;
/**
* @summary Creates or updates a management lock at the resource level or any
* level below the resource.
*
* When you apply a lock at a parent scope, all child resources inherit the
* same lock. To create management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} resourceGroupName The name of the resource group containing
* the resource to lock.
*
* @param {string} resourceProviderNamespace The resource provider namespace of
* the resource to lock.
*
* @param {string} parentResourcePath The parent resource identity.
*
* @param {string} resourceType The resource type of the resource to lock.
*
* @param {string} resourceName The name of the resource to lock.
*
* @param {string} lockName The name of lock. The lock name can be a maximum of
* 260 characters. It cannot contain <, > %, &, :, \, ?, /, or any control
* characters.
*
* @param {object} parameters Parameters for creating or updating a management
* lock.
*
* @param {string} parameters.level The level of the lock. Possible values are:
* NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users
* are able to read and modify the resources, but not delete. ReadOnly means
* authorized users can only read from a resource, but they can't modify or
* delete it. Possible values include: 'NotSpecified', 'CanNotDelete',
* 'ReadOnly'
*
* @param {string} [parameters.notes] Notes about the lock. Maximum of 512
* characters.
*
* @param {array} [parameters.owners] The owners of the lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockObject} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockObject} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockObject} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdateAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, parameters: models.ManagementLockObject, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockObject>;
createOrUpdateAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, parameters: models.ManagementLockObject, callback: ServiceCallback<models.ManagementLockObject>): void;
createOrUpdateAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, parameters: models.ManagementLockObject, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockObject>): void;
/**
* @summary Deletes the management lock of a resource or any level below the
* resource.
*
* To delete management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} resourceGroupName The name of the resource group containing
* the resource with the lock to delete.
*
* @param {string} resourceProviderNamespace The resource provider namespace of
* the resource with the lock to delete.
*
* @param {string} parentResourcePath The parent resource identity.
*
* @param {string} resourceType The resource type of the resource with the lock
* to delete.
*
* @param {string} resourceName The name of the resource with the lock to
* delete.
*
* @param {string} lockName The name of the lock to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteAtResourceLevelWithHttpOperationResponse(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* @summary Deletes the management lock of a resource or any level below the
* resource.
*
* To delete management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} resourceGroupName The name of the resource group containing
* the resource with the lock to delete.
*
* @param {string} resourceProviderNamespace The resource provider namespace of
* the resource with the lock to delete.
*
* @param {string} parentResourcePath The parent resource identity.
*
* @param {string} resourceType The resource type of the resource with the lock
* to delete.
*
* @param {string} resourceName The name of the resource with the lock to
* delete.
*
* @param {string} lockName The name of the lock to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, callback: ServiceCallback<void>): void;
deleteAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Get the management lock of a resource or any level below resource.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceProviderNamespace The namespace of the resource
* provider.
*
* @param {string} parentResourcePath An extra path parameter needed in some
* services, like SQL Databases.
*
* @param {string} resourceType The type of the resource.
*
* @param {string} resourceName The name of the resource.
*
* @param {string} lockName The name of lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockObject>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getAtResourceLevelWithHttpOperationResponse(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockObject>>;
/**
* Get the management lock of a resource or any level below resource.
*
* @param {string} resourceGroupName The name of the resource group.
*
* @param {string} resourceProviderNamespace The namespace of the resource
* provider.
*
* @param {string} parentResourcePath An extra path parameter needed in some
* services, like SQL Databases.
*
* @param {string} resourceType The type of the resource.
*
* @param {string} resourceName The name of the resource.
*
* @param {string} lockName The name of lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockObject} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockObject} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockObject} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
getAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockObject>;
getAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, callback: ServiceCallback<models.ManagementLockObject>): void;
getAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, lockName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockObject>): void;
/**
* @summary Creates or updates a management lock at the subscription level.
*
* When you apply a lock at a parent scope, all child resources inherit the
* same lock. To create management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} lockName The name of lock. The lock name can be a maximum of
* 260 characters. It cannot contain <, > %, &, :, \, ?, /, or any control
* characters.
*
* @param {object} parameters The management lock parameters.
*
* @param {string} parameters.level The level of the lock. Possible values are:
* NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users
* are able to read and modify the resources, but not delete. ReadOnly means
* authorized users can only read from a resource, but they can't modify or
* delete it. Possible values include: 'NotSpecified', 'CanNotDelete',
* 'ReadOnly'
*
* @param {string} [parameters.notes] Notes about the lock. Maximum of 512
* characters.
*
* @param {array} [parameters.owners] The owners of the lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockObject>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateAtSubscriptionLevelWithHttpOperationResponse(lockName: string, parameters: models.ManagementLockObject, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockObject>>;
/**
* @summary Creates or updates a management lock at the subscription level.
*
* When you apply a lock at a parent scope, all child resources inherit the
* same lock. To create management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} lockName The name of lock. The lock name can be a maximum of
* 260 characters. It cannot contain <, > %, &, :, \, ?, /, or any control
* characters.
*
* @param {object} parameters The management lock parameters.
*
* @param {string} parameters.level The level of the lock. Possible values are:
* NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users
* are able to read and modify the resources, but not delete. ReadOnly means
* authorized users can only read from a resource, but they can't modify or
* delete it. Possible values include: 'NotSpecified', 'CanNotDelete',
* 'ReadOnly'
*
* @param {string} [parameters.notes] Notes about the lock. Maximum of 512
* characters.
*
* @param {array} [parameters.owners] The owners of the lock.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockObject} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockObject} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockObject} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdateAtSubscriptionLevel(lockName: string, parameters: models.ManagementLockObject, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockObject>;
createOrUpdateAtSubscriptionLevel(lockName: string, parameters: models.ManagementLockObject, callback: ServiceCallback<models.ManagementLockObject>): void;
createOrUpdateAtSubscriptionLevel(lockName: string, parameters: models.ManagementLockObject, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockObject>): void;
/**
* @summary Deletes the management lock at the subscription level.
*
* To delete management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} lockName The name of lock to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteAtSubscriptionLevelWithHttpOperationResponse(lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* @summary Deletes the management lock at the subscription level.
*
* To delete management locks, you must have access to
* Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions. Of the
* built-in roles, only Owner and User Access Administrator are granted those
* actions.
*
* @param {string} lockName The name of lock to delete.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteAtSubscriptionLevel(lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteAtSubscriptionLevel(lockName: string, callback: ServiceCallback<void>): void;
deleteAtSubscriptionLevel(lockName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Gets a management lock at the subscription level.
*
* @param {string} lockName The name of the lock to get.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockObject>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getAtSubscriptionLevelWithHttpOperationResponse(lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockObject>>;
/**
* Gets a management lock at the subscription level.
*
* @param {string} lockName The name of the lock to get.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockObject} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockObject} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockObject} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
getAtSubscriptionLevel(lockName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockObject>;
getAtSubscriptionLevel(lockName: string, callback: ServiceCallback<models.ManagementLockObject>): void;
getAtSubscriptionLevel(lockName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockObject>): void;
/**
* Gets all the management locks for a resource group.
*
* @param {string} resourceGroupName The name of the resource group containing
* the locks to get.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] The filter to apply on the operation.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listAtResourceGroupLevelWithHttpOperationResponse(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockListResult>>;
/**
* Gets all the management locks for a resource group.
*
* @param {string} resourceGroupName The name of the resource group containing
* the locks to get.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] The filter to apply on the operation.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listAtResourceGroupLevel(resourceGroupName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockListResult>;
listAtResourceGroupLevel(resourceGroupName: string, callback: ServiceCallback<models.ManagementLockListResult>): void;
listAtResourceGroupLevel(resourceGroupName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockListResult>): void;
/**
* Gets all the management locks for a resource or any level below resource.
*
* @param {string} resourceGroupName The name of the resource group containing
* the locked resource. The name is case insensitive.
*
* @param {string} resourceProviderNamespace The namespace of the resource
* provider.
*
* @param {string} parentResourcePath The parent resource identity.
*
* @param {string} resourceType The resource type of the locked resource.
*
* @param {string} resourceName The name of the locked resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] The filter to apply on the operation.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listAtResourceLevelWithHttpOperationResponse(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockListResult>>;
/**
* Gets all the management locks for a resource or any level below resource.
*
* @param {string} resourceGroupName The name of the resource group containing
* the locked resource. The name is case insensitive.
*
* @param {string} resourceProviderNamespace The namespace of the resource
* provider.
*
* @param {string} parentResourcePath The parent resource identity.
*
* @param {string} resourceType The resource type of the locked resource.
*
* @param {string} resourceName The name of the locked resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] The filter to apply on the operation.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockListResult>;
listAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, callback: ServiceCallback<models.ManagementLockListResult>): void;
listAtResourceLevel(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockListResult>): void;
/**
* Gets all the management locks for a subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] The filter to apply on the operation.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listAtSubscriptionLevelWithHttpOperationResponse(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockListResult>>;
/**
* Gets all the management locks for a subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] The filter to apply on the operation.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listAtSubscriptionLevel(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockListResult>;
listAtSubscriptionLevel(callback: ServiceCallback<models.ManagementLockListResult>): void;
listAtSubscriptionLevel(options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockListResult>): void;
/**
* Gets all the management locks for a resource group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listAtResourceGroupLevelNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockListResult>>;
/**
* Gets all the management locks for a resource group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listAtResourceGroupLevelNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockListResult>;
listAtResourceGroupLevelNext(nextPageLink: string, callback: ServiceCallback<models.ManagementLockListResult>): void;
listAtResourceGroupLevelNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockListResult>): void;
/**
* Gets all the management locks for a resource or any level below resource.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listAtResourceLevelNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockListResult>>;
/**
* Gets all the management locks for a resource or any level below resource.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listAtResourceLevelNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockListResult>;
listAtResourceLevelNext(nextPageLink: string, callback: ServiceCallback<models.ManagementLockListResult>): void;
listAtResourceLevelNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockListResult>): void;
/**
* Gets all the management locks for a subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ManagementLockListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listAtSubscriptionLevelNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementLockListResult>>;
/**
* Gets all the management locks for a subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ManagementLockListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ManagementLockListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ManagementLockListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listAtSubscriptionLevelNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementLockListResult>;
listAtSubscriptionLevelNext(nextPageLink: string, callback: ServiceCallback<models.ManagementLockListResult>): void;
listAtSubscriptionLevelNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementLockListResult>): void;
} | the_stack |
import * as assert from 'assert'
import * as B from '../src/boolean'
import { Endomorphism } from '../src/Endomorphism'
import * as Eq from '../src/Eq'
import { identity, pipe } from '../src/function'
import * as N from '../src/number'
import * as O from '../src/Option'
import * as Ord from '../src/Ord'
import * as _ from '../src/ReadonlyNonEmptyArray'
import * as Se from '../src/Semigroup'
import * as S from '../src/string'
import * as U from './util'
describe('ReadonlyNonEmptyArray', () => {
describe('pipeables', () => {
it('traverse', () => {
assert.deepStrictEqual(
pipe(
[1, 2, 3],
_.traverse(O.Applicative)((n) => (n >= 0 ? O.some(n) : O.none))
),
O.some([1, 2, 3])
)
U.deepStrictEqual(
pipe(
[1, 2, 3],
_.traverse(O.Applicative)((n) => (n >= 2 ? O.some(n) : O.none))
),
O.none
)
})
it('sequence', () => {
const sequence = _.sequence(O.Applicative)
assert.deepStrictEqual(sequence([O.some(1), O.some(2), O.some(3)]), O.some([1, 2, 3]))
U.deepStrictEqual(sequence([O.none, O.some(2), O.some(3)]), O.none)
})
it('traverseWithIndex', () => {
assert.deepStrictEqual(
pipe(
['a', 'bb'],
_.traverseWithIndex(O.Applicative)((i, s) => (s.length >= 1 ? O.some(s + i) : O.none))
),
O.some(['a0', 'bb1'])
)
U.deepStrictEqual(
pipe(
['a', 'bb'],
_.traverseWithIndex(O.Applicative)((i, s) => (s.length > 1 ? O.some(s + i) : O.none))
),
O.none
)
})
})
it('head', () => {
U.deepStrictEqual(_.head([1, 2]), 1)
})
it('tail', () => {
U.deepStrictEqual(_.tail([1, 2]), [2])
})
it('map', () => {
U.deepStrictEqual(
pipe(
[1, 2],
_.map((n) => n * 2)
),
[2, 4]
)
})
it('mapWithIndex', () => {
const add = (i: number, n: number) => n + i
U.deepStrictEqual(pipe([1, 2], _.mapWithIndex(add)), [1, 3])
})
it('of', () => {
U.deepStrictEqual(_.of(1), [1])
})
it('ap', () => {
const fab: _.ReadonlyNonEmptyArray<(n: number) => number> = [U.double, U.double]
U.deepStrictEqual(pipe(fab, _.ap([1, 2])), [2, 4, 2, 4])
})
it('chain', () => {
const f = (a: number): _.ReadonlyNonEmptyArray<number> => [a, 4]
U.deepStrictEqual(pipe([1, 2], _.chain(f)), [1, 4, 2, 4])
})
it('extend', () => {
const sum = (as: _.ReadonlyNonEmptyArray<number>): number => {
const head = _.head(as)
assert.ok(typeof (head as any) === 'number')
return Se.concatAll(N.MonoidSum)(head)(_.tail(as))
}
U.deepStrictEqual(pipe([1, 2, 3, 4], _.extend(sum)), [10, 9, 7, 4])
U.deepStrictEqual(pipe([1], _.extend(sum)), [1])
})
it('extract', () => {
U.deepStrictEqual(_.extract([1, 2, 3]), 1)
})
it('min', () => {
U.deepStrictEqual(_.min(N.Ord)([2, 1, 3]), 1)
U.deepStrictEqual(_.min(N.Ord)([3]), 3)
})
it('max', () => {
U.deepStrictEqual(_.max(N.Ord)([1, 2, 3]), 3)
U.deepStrictEqual(_.max(N.Ord)([1]), 1)
})
it('reduce', () => {
U.deepStrictEqual(
pipe(
['a', 'b'],
_.reduce('', (b, a) => b + a)
),
'ab'
)
})
it('foldMap', () => {
U.deepStrictEqual(pipe(['a', 'b', 'c'], _.foldMap(S.Monoid)(identity)), 'abc')
})
it('reduceRight', () => {
const f = (a: string, acc: string) => acc + a
U.deepStrictEqual(pipe(['a', 'b', 'c'], _.reduceRight('', f)), 'cba')
})
it('fromReadonlyArray', () => {
U.deepStrictEqual(_.fromReadonlyArray([]), O.none)
assert.deepStrictEqual(_.fromReadonlyArray([1]), O.some([1]))
assert.deepStrictEqual(_.fromReadonlyArray([1, 2]), O.some([1, 2]))
})
it('getSemigroup', () => {
const S = _.getSemigroup<number>()
U.deepStrictEqual(S.concat([1], [2]), [1, 2])
U.deepStrictEqual(S.concat([1, 2], [3, 4]), [1, 2, 3, 4])
})
it('getEq', () => {
const S = _.getEq(N.Eq)
U.deepStrictEqual(S.equals([1], [1]), true)
U.deepStrictEqual(S.equals([1], [1, 2]), false)
})
it('group', () => {
U.deepStrictEqual(_.group(N.Eq)([]), [])
U.deepStrictEqual(_.group(N.Eq)([1, 2, 1, 1]), [[1], [2], [1, 1]])
U.deepStrictEqual(_.group(N.Eq)([1, 2, 1, 1, 3]), [[1], [2], [1, 1], [3]])
})
it('groupSort', () => {
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.groupSort(N.Ord)([]), [])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.groupSort(N.Ord)([1, 2, 1, 1]), [[1, 1, 1], [2]])
})
it('last', () => {
U.deepStrictEqual(_.last([1, 2, 3]), 3)
U.deepStrictEqual(_.last([1]), 1)
})
it('init', () => {
U.deepStrictEqual(_.init([1, 2, 3]), [1, 2])
U.deepStrictEqual(_.init([1]), [])
})
it('sort', () => {
const sort = _.sort(N.Ord)
U.deepStrictEqual(sort([3, 2, 1]), [1, 2, 3])
// should optimize `1`-length `ReadonlyNonEmptyArray`s
const singleton: _.ReadonlyNonEmptyArray<number> = [1]
U.strictEqual(sort(singleton), singleton)
})
it('prependAll', () => {
U.deepStrictEqual(_.prependAll(0)([1, 2, 3]), [0, 1, 0, 2, 0, 3])
U.deepStrictEqual(_.prependAll(0)([1]), [0, 1])
U.deepStrictEqual(_.prependAll(0)([1, 2, 3, 4]), [0, 1, 0, 2, 0, 3, 0, 4])
})
it('intersperse', () => {
U.deepStrictEqual(_.intersperse(0)([1, 2, 3]), [1, 0, 2, 0, 3])
U.deepStrictEqual(_.intersperse(0)([1]), [1])
U.deepStrictEqual(_.intersperse(0)([1, 2]), [1, 0, 2])
U.deepStrictEqual(_.intersperse(0)([1, 2, 3, 4]), [1, 0, 2, 0, 3, 0, 4])
})
it('reverse', () => {
const singleton: _.ReadonlyNonEmptyArray<number> = [1]
U.strictEqual(_.reverse(singleton), singleton)
U.deepStrictEqual(_.reverse([1, 2, 3]), [3, 2, 1])
})
it('groupBy', () => {
U.deepStrictEqual(_.groupBy((_) => '')([]), {})
U.deepStrictEqual(_.groupBy(String)([1]), { '1': [1] })
U.deepStrictEqual(_.groupBy((s: string) => String(s.length))(['foo', 'bar', 'foobar']), {
'3': ['foo', 'bar'],
'6': ['foobar']
})
})
it('insertAt', () => {
const make = (x: number) => ({ x })
const a1 = make(1)
const a2 = make(1)
const a3 = make(2)
const a4 = make(3)
// tslint:disable-next-line: deprecation
U.deepStrictEqual(pipe([], _.insertAt(1, 1)), O.none)
// tslint:disable-next-line: deprecation
assert.deepStrictEqual(_.insertAt(0, a4)([a1, a2, a3]), O.some([a4, a1, a2, a3]))
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.insertAt(-1, a4)([a1, a2, a3]), O.none)
// tslint:disable-next-line: deprecation
assert.deepStrictEqual(_.insertAt(3, a4)([a1, a2, a3]), O.some([a1, a2, a3, a4]))
// tslint:disable-next-line: deprecation
assert.deepStrictEqual(_.insertAt(1, a4)([a1, a2, a3]), O.some([a1, a4, a2, a3]))
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.insertAt(4, a4)([a1, a2, a3]), O.none)
})
it('updateAt', () => {
const make2 = (x: number) => ({ x })
const a1 = make2(1)
const a2 = make2(1)
const a3 = make2(2)
const a4 = make2(3)
const arr: _.ReadonlyNonEmptyArray<{ readonly x: number }> = [a1, a2, a3]
assert.deepStrictEqual(_.updateAt(0, a4)(arr), O.some([a4, a2, a3]))
U.deepStrictEqual(_.updateAt(-1, a4)(arr), O.none)
U.deepStrictEqual(_.updateAt(3, a4)(arr), O.none)
assert.deepStrictEqual(_.updateAt(1, a4)(arr), O.some([a1, a4, a3]))
// should return the same reference if nothing changed
const r1 = _.updateAt(0, a1)(arr)
if (O.isSome(r1)) {
U.deepStrictEqual(r1.value, arr)
} else {
assert.fail('is not a Some')
}
const r2 = _.updateAt(2, a3)(arr)
if (O.isSome(r2)) {
U.deepStrictEqual(r2.value, arr)
} else {
assert.fail('is not a Some')
}
})
it('modifyAt', () => {
U.deepStrictEqual(_.modifyAt(1, U.double)([1]), O.none)
U.deepStrictEqual(_.modifyAt(1, U.double)([1, 2]), O.some([1, 4] as const))
// should return the same reference if nothing changed
const input: _.ReadonlyNonEmptyArray<number> = [1, 2, 3]
U.deepStrictEqual(
pipe(
input,
_.modifyAt(1, identity),
O.map((out) => out === input)
),
O.some(true)
)
})
it('filter', () => {
const make = (x: number) => ({ x })
const a1 = make(1)
const a2 = make(1)
const a3 = make(2)
assert.deepStrictEqual(_.filter(({ x }) => x !== 1)([a1, a2, a3]), O.some([a3]))
assert.deepStrictEqual(_.filter(({ x }) => x !== 2)([a1, a2, a3]), O.some([a1, a2]))
U.deepStrictEqual(
_.filter(({ x }) => {
return !(x === 1 || x === 2)
})([a1, a2, a3]),
O.none
)
assert.deepStrictEqual(_.filter(({ x }) => x !== 10)([a1, a2, a3]), O.some([a1, a2, a3]))
// refinements
// tslint:disable-next-line: deprecation
const actual1 = _.filter(O.isSome)([O.some(3), O.some(2), O.some(1)])
assert.deepStrictEqual(actual1, O.some([O.some(3), O.some(2), O.some(1)]))
// tslint:disable-next-line: deprecation
const actual2 = _.filter(O.isSome)([O.some(3), O.none, O.some(1)])
assert.deepStrictEqual(actual2, O.some([O.some(3), O.some(1)]))
})
it('filterWithIndex', () => {
// tslint:disable-next-line: deprecation
assert.deepStrictEqual(_.filterWithIndex((i) => i % 2 === 0)([1, 2, 3]), O.some([1, 3]))
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.filterWithIndex((i, a: number) => i % 2 === 1 && a > 2)([1, 2, 3]), O.none)
})
it('reduceWithIndex', () => {
U.deepStrictEqual(
pipe(
['a', 'b'],
_.reduceWithIndex('', (i, b, a) => b + i + a)
),
'0a1b'
)
})
it('foldMapWithIndex', () => {
U.deepStrictEqual(
pipe(
['a', 'b'],
_.foldMapWithIndex(S.Monoid)((i, a) => i + a)
),
'0a1b'
)
})
it('reduceRightWithIndex', () => {
U.deepStrictEqual(
pipe(
['a', 'b'],
_.reduceRightWithIndex('', (i, a, b) => b + i + a)
),
'1b0a'
)
})
it('cons', () => {
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.cons(1, [2, 3, 4]), [1, 2, 3, 4])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(pipe([2, 3, 4], _.cons(1)), [1, 2, 3, 4])
})
it('snoc', () => {
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.snoc([], 0), [0])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.snoc([1, 2, 3], 4), [1, 2, 3, 4])
})
it('unprepend', () => {
U.deepStrictEqual(_.unprepend([0]), [0, []])
U.deepStrictEqual(_.unprepend([1, 2, 3, 4]), [1, [2, 3, 4]])
})
it('unappend', () => {
U.deepStrictEqual(_.unappend([0]), [[], 0])
U.deepStrictEqual(_.unappend([1, 2, 3, 4]), [[1, 2, 3], 4])
U.deepStrictEqual(_.unappend([0]), [[], 0])
U.deepStrictEqual(_.unappend([1, 2, 3, 4]), [[1, 2, 3], 4])
})
it('getShow', () => {
const Sh = _.getShow(S.Show)
U.deepStrictEqual(Sh.show(['a']), `["a"]`)
U.deepStrictEqual(Sh.show(['a', 'b', 'c']), `["a", "b", "c"]`)
})
it('alt', () => {
U.deepStrictEqual(
pipe(
['a'],
_.alt(() => ['b'])
),
['a', 'b']
)
})
it('foldMap', () => {
const f = _.foldMap(N.SemigroupSum)((s: string) => s.length)
U.deepStrictEqual(f(['a']), 1)
U.deepStrictEqual(f(['a', 'bb']), 3)
})
it('foldMapWithIndex', () => {
const f = _.foldMapWithIndex(N.SemigroupSum)((i: number, s: string) => s.length + i)
U.deepStrictEqual(f(['a']), 1)
U.deepStrictEqual(f(['a', 'bb']), 4)
})
it('fromArray', () => {
U.strictEqual(_.fromArray([]), O.none)
// tslint:disable-next-line: readonly-array
const as = [1, 2, 3]
const bs = _.fromArray(as)
assert.deepStrictEqual(bs, O.some(as))
assert.notStrictEqual((bs as any).value, as)
})
it('fromReadonlyArray', () => {
const as: ReadonlyArray<number> = [1, 2, 3]
const bs = _.fromReadonlyArray(as)
U.deepStrictEqual(bs, O.some(as))
U.strictEqual((bs as any).value, as)
})
it('concatAll', () => {
const f = _.concatAll(S.Semigroup)
U.deepStrictEqual(f(['a']), 'a')
U.deepStrictEqual(f(['a', 'bb']), 'abb')
})
it('do notation', () => {
U.deepStrictEqual(
pipe(
_.of(1),
_.bindTo('a'),
_.bind('b', () => _.of('b'))
),
[{ a: 1, b: 'b' }]
)
})
it('apS', () => {
U.deepStrictEqual(pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b'))), [{ a: 1, b: 'b' }])
})
it('zipWith', () => {
U.deepStrictEqual(
_.zipWith([1, 2, 3], ['a', 'b', 'c', 'd'], (n, s) => s + n),
['a1', 'b2', 'c3']
)
})
it('zip', () => {
U.deepStrictEqual(_.zip([1, 2, 3], ['a', 'b', 'c', 'd']), [
[1, 'a'],
[2, 'b'],
[3, 'c']
])
U.deepStrictEqual(pipe([1, 2, 3] as const, _.zip(['a', 'b', 'c', 'd'])), [
[1, 'a'],
[2, 'b'],
[3, 'c']
])
})
it('unzip', () => {
U.deepStrictEqual(
_.unzip([
[1, 'a'],
[2, 'b'],
[3, 'c']
]),
[
[1, 2, 3],
['a', 'b', 'c']
]
)
})
it('splitAt', () => {
const assertSplitAt = (
input: _.ReadonlyNonEmptyArray<number>,
index: number,
expectedInit: ReadonlyArray<number>,
expectedRest: ReadonlyArray<number>
) => {
const [init, rest] = _.splitAt(index)(input)
U.strictEqual(init, expectedInit)
U.strictEqual(rest, expectedRest)
}
const two: _.ReadonlyNonEmptyArray<number> = [1, 2]
U.deepStrictEqual(_.splitAt(1)(two), [[1], [2]])
assertSplitAt(two, 2, two, _.empty)
const singleton: _.ReadonlyNonEmptyArray<number> = [1]
assertSplitAt(singleton, 1, singleton, _.empty)
// out of bounds
assertSplitAt(singleton, 0, singleton, _.empty)
assertSplitAt(singleton, 2, singleton, _.empty)
U.deepStrictEqual(_.splitAt(0)(two), [[1], [2]])
assertSplitAt(two, 3, two, _.empty)
})
it('chunksOf', () => {
U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]])
U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5, 6]), [
[1, 2],
[3, 4],
[5, 6]
])
U.deepStrictEqual(_.chunksOf(1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])
U.deepStrictEqual(_.chunksOf(5)([1, 2, 3, 4, 5]), [[1, 2, 3, 4, 5]])
// out of bounds
U.deepStrictEqual(_.chunksOf(0)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])
U.deepStrictEqual(_.chunksOf(-1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])
const assertSingleChunk = (input: _.ReadonlyNonEmptyArray<number>, n: number) => {
const chunks = _.chunksOf(n)(input)
U.strictEqual(chunks.length, 1)
U.strictEqual(_.head(chunks), input)
}
// n = length
assertSingleChunk([1, 2], 2)
// n out of bounds
assertSingleChunk([1, 2], 3)
})
it('rotate', () => {
const singleton: _.ReadonlyNonEmptyArray<number> = [1]
U.strictEqual(_.rotate(1)(singleton), singleton)
U.strictEqual(_.rotate(2)(singleton), singleton)
U.strictEqual(_.rotate(-1)(singleton), singleton)
U.strictEqual(_.rotate(-2)(singleton), singleton)
const two: _.ReadonlyNonEmptyArray<number> = [1, 2]
U.strictEqual(_.rotate(2)(two), two)
U.strictEqual(_.rotate(0)(two), two)
U.strictEqual(_.rotate(-2)(two), two)
U.deepStrictEqual(_.rotate(1)([1, 2]), [2, 1])
U.deepStrictEqual(_.rotate(1)([1, 2, 3, 4, 5]), [5, 1, 2, 3, 4])
U.deepStrictEqual(_.rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3])
U.deepStrictEqual(_.rotate(-1)([1, 2, 3, 4, 5]), [2, 3, 4, 5, 1])
U.deepStrictEqual(_.rotate(-2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2])
U.deepStrictEqual(_.rotate(7)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3])
U.deepStrictEqual(_.rotate(-7)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2])
U.deepStrictEqual(_.rotate(2.2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3])
U.deepStrictEqual(_.rotate(-2.2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2])
})
it('uniq', () => {
interface A {
readonly a: string
readonly b: number
}
const eqA = pipe(
N.Eq,
Eq.contramap((f: A) => f.b)
)
const arrA: A = { a: 'a', b: 1 }
const arrB: A = { a: 'b', b: 1 }
const arrC: A = { a: 'c', b: 2 }
const arrD: A = { a: 'd', b: 2 }
const arrUniq: _.ReadonlyNonEmptyArray<A> = [arrA, arrC]
U.deepStrictEqual(_.uniq(eqA)(arrUniq), arrUniq)
U.deepStrictEqual(_.uniq(eqA)([arrA, arrB, arrC, arrD]), [arrA, arrC])
U.deepStrictEqual(_.uniq(eqA)([arrB, arrA, arrC, arrD]), [arrB, arrC])
U.deepStrictEqual(_.uniq(eqA)([arrA, arrA, arrC, arrD, arrA]), [arrA, arrC])
U.deepStrictEqual(_.uniq(eqA)([arrA, arrC]), [arrA, arrC])
U.deepStrictEqual(_.uniq(eqA)([arrC, arrA]), [arrC, arrA])
U.deepStrictEqual(_.uniq(B.Eq)([true, false, true, false]), [true, false])
U.deepStrictEqual(_.uniq(N.Eq)([-0, -0]), [-0])
U.deepStrictEqual(_.uniq(N.Eq)([0, -0]), [0])
U.deepStrictEqual(_.uniq(N.Eq)([1]), [1])
U.deepStrictEqual(_.uniq(N.Eq)([2, 1, 2]), [2, 1])
U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 1]), [1, 2])
U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])
U.deepStrictEqual(_.uniq(N.Eq)([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]), [1, 2, 3, 4, 5])
U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 3, 4, 5, 1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])
U.deepStrictEqual(_.uniq(S.Eq)(['a', 'b', 'a']), ['a', 'b'])
U.deepStrictEqual(_.uniq(S.Eq)(['a', 'b', 'A']), ['a', 'b', 'A'])
const as: _.ReadonlyNonEmptyArray<number> = [1]
U.strictEqual(_.uniq(N.Eq)(as), as)
})
it('sortBy', () => {
interface X {
readonly a: string
readonly b: number
readonly c: boolean
}
const byName = pipe(
S.Ord,
Ord.contramap((p: { readonly a: string; readonly b: number }) => p.a)
)
const byAge = pipe(
N.Ord,
Ord.contramap((p: { readonly a: string; readonly b: number }) => p.b)
)
const f = _.sortBy([byName, byAge])
const xs: _.ReadonlyNonEmptyArray<X> = [
{ a: 'a', b: 1, c: true },
{ a: 'b', b: 3, c: true },
{ a: 'c', b: 2, c: true },
{ a: 'b', b: 2, c: true }
]
U.deepStrictEqual(f(xs), [
{ a: 'a', b: 1, c: true },
{ a: 'b', b: 2, c: true },
{ a: 'b', b: 3, c: true },
{ a: 'c', b: 2, c: true }
])
const sortByAgeByName = _.sortBy([byAge, byName])
U.deepStrictEqual(sortByAgeByName(xs), [
{ a: 'a', b: 1, c: true },
{ a: 'b', b: 2, c: true },
{ a: 'c', b: 2, c: true },
{ a: 'b', b: 3, c: true }
])
U.deepStrictEqual(_.sortBy([])(xs), xs)
})
it('union', () => {
const concat = _.getUnionSemigroup(N.Eq).concat
U.deepStrictEqual(concat([1, 2], [3, 4]), [1, 2, 3, 4])
U.deepStrictEqual(concat([1, 2], [2, 3]), [1, 2, 3])
U.deepStrictEqual(concat([1, 2], [1, 2]), [1, 2])
})
it('matchLeft', () => {
U.deepStrictEqual(
pipe(
[1, 2, 3],
_.matchLeft((head, tail) => [head, tail])
),
[1, [2, 3]]
)
})
it('matchRight', () => {
U.deepStrictEqual(
pipe(
[1, 2, 3],
_.matchRight((init, last) => [init, last])
),
[[1, 2], 3]
)
})
it('modifyHead', () => {
const f: Endomorphism<string> = (s) => s + '!'
U.deepStrictEqual(pipe(['a'], _.modifyHead(f)), ['a!'])
U.deepStrictEqual(pipe(['a', 'b'], _.modifyHead(f)), ['a!', 'b'])
U.deepStrictEqual(pipe(['a', 'b', 'c'], _.modifyHead(f)), ['a!', 'b', 'c'])
})
it('modifyLast', () => {
const f: Endomorphism<string> = (s) => s + '!'
U.deepStrictEqual(pipe(['a'], _.modifyLast(f)), ['a!'])
U.deepStrictEqual(pipe(['a', 'b'], _.modifyLast(f)), ['a', 'b!'])
U.deepStrictEqual(pipe(['a', 'b', 'c'], _.modifyLast(f)), ['a', 'b', 'c!'])
})
it('makeBy', () => {
const f = _.makeBy(U.double)
U.deepStrictEqual(f(5), [0, 2, 4, 6, 8])
// If `n` (must be a natural number) is non positive return `[f(0)]`.
U.deepStrictEqual(f(0), [0])
U.deepStrictEqual(f(-1), [0])
})
it('range', () => {
U.deepStrictEqual(_.range(0, 0), [0])
U.deepStrictEqual(_.range(0, 1), [0, 1])
U.deepStrictEqual(_.range(1, 5), [1, 2, 3, 4, 5])
U.deepStrictEqual(_.range(10, 15), [10, 11, 12, 13, 14, 15])
U.deepStrictEqual(_.range(-1, 0), [-1, 0])
U.deepStrictEqual(_.range(-5, -1), [-5, -4, -3, -2, -1])
// out of bound
U.deepStrictEqual(_.range(2, 1), [2])
U.deepStrictEqual(_.range(-1, -2), [-1])
})
it('replicate', () => {
const f = _.replicate('a')
U.deepStrictEqual(pipe(0, f), ['a'])
U.deepStrictEqual(pipe(1, f), ['a'])
U.deepStrictEqual(pipe(2, f), ['a', 'a'])
})
it('updateHead', () => {
U.deepStrictEqual(pipe(['a'], _.updateHead('d')), ['d'])
U.deepStrictEqual(pipe(['a', 'b'], _.updateHead('d')), ['d', 'b'])
U.deepStrictEqual(pipe(['a', 'b', 'c'], _.updateHead('d')), ['d', 'b', 'c'])
})
it('updateLast', () => {
U.deepStrictEqual(pipe(['a'], _.updateLast('d')), ['d'])
U.deepStrictEqual(pipe(['a', 'b'], _.updateLast('d')), ['a', 'd'])
U.deepStrictEqual(pipe(['a', 'b', 'c'], _.updateLast('d')), ['a', 'b', 'd'])
})
it('concatW', () => {
U.deepStrictEqual(pipe(['a'], _.concatW(['b'])), ['a', 'b'])
})
it('concat', () => {
U.deepStrictEqual(pipe(['a'], _.concat(['b'])), ['a', 'b'])
U.deepStrictEqual(pipe(_.empty, _.concat(['b'])), ['b'])
U.deepStrictEqual(pipe(['a'], _.concat<string>(_.empty)), ['a'])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.concat(['a'], ['b']), ['a', 'b'])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.concat(['a'], _.empty), ['a'])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.concat(_.empty, ['b']), ['b'])
})
}) | the_stack |
import * as cdk from '@aws-cdk/core';
import * as s3 from '@aws-cdk/aws-s3';
import * as sns from '@aws-cdk/aws-sns';
import * as lambda from '@aws-cdk/aws-lambda';
import { StringParameter, CfnParameter } from '@aws-cdk/aws-ssm';
import * as kms from '@aws-cdk/aws-kms';
import * as fs from 'fs';
import {
Role,
CfnRole,
Policy,
CfnPolicy,
PolicyStatement,
PolicyDocument,
ServicePrincipal,
AccountRootPrincipal
} from '@aws-cdk/aws-iam';
import { OrchestratorConstruct } from '../../Orchestrator/lib/common-orchestrator-construct';
import { CfnStateMachine, StateMachine } from '@aws-cdk/aws-stepfunctions';
import { OneTrigger } from '../../lib/ssmplaybook';
export interface SHARRStackProps extends cdk.StackProps {
solutionId: string;
solutionVersion: string;
solutionDistBucket: string;
solutionTMN: string;
solutionName: string;
runtimePython: lambda.Runtime;
orchLogGroup: string;
}
export class SolutionDeployStack extends cdk.Stack {
SEND_ANONYMOUS_DATA = 'Yes'
constructor(scope: cdk.App, id: string, props: SHARRStackProps) {
super(scope, id, props);
const stack = cdk.Stack.of(this);
const RESOURCE_PREFIX = props.solutionId.replace(/^DEV-/,''); // prefix on every resource name
//-------------------------------------------------------------------------
// Solutions Bucket - Source Code
//
const SolutionsBucket = s3.Bucket.fromBucketAttributes(this, 'SolutionsBucket', {
bucketName: props.solutionDistBucket + '-' + this.region
});
//=========================================================================
// MAPPINGS
//=========================================================================
new cdk.CfnMapping(this, 'SourceCode', {
mapping: { "General": {
"S3Bucket": props.solutionDistBucket,
"KeyPrefix": props.solutionTMN + '/' + props.solutionVersion
} }
})
//-------------------------------------------------------------------------
// KMS Key for solution encryption
//
// Key Policy
const kmsKeyPolicy:PolicyDocument = new PolicyDocument()
const kmsServicePolicy = new PolicyStatement({
principals: [
new ServicePrincipal('sns.amazonaws.com'),
new ServicePrincipal(`logs.${this.urlSuffix}`)
],
actions: [
"kms:Encrypt*",
"kms:Decrypt*",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:Describe*"
],
resources: [
'*'
],
conditions: {
ArnEquals: {
"kms:EncryptionContext:aws:logs:arn": this.formatArn({
service: 'logs',
resource: 'log-group:SO0111-SHARR-*'
})
}
}
})
kmsKeyPolicy.addStatements(kmsServicePolicy)
const kmsRootPolicy = new PolicyStatement({
principals: [
new AccountRootPrincipal()
],
actions: [
'kms:*'
],
resources: [
'*'
]
})
kmsKeyPolicy.addStatements(kmsRootPolicy)
const kmsKey = new kms.Key(this, 'SHARR-key', {
enableKeyRotation: true,
alias: `${RESOURCE_PREFIX}-SHARR-Key`,
trustAccountIdentities: true,
policy: kmsKeyPolicy
});
const kmsKeyParm = new StringParameter(this, 'SHARR_Key', {
description: 'KMS Customer Managed Key that SHARR will use to encrypt data',
parameterName: `/Solutions/${RESOURCE_PREFIX}/CMK_ARN`,
stringValue: kmsKey.keyArn
});
//-------------------------------------------------------------------------
// SNS Topic for notification fanout on Playbook completion
//
const snsTopic = new sns.Topic(this, 'SHARR-Topic', {
displayName: 'SHARR Playbook Topic (' + RESOURCE_PREFIX + ')',
topicName: RESOURCE_PREFIX + '-SHARR_Topic',
masterKey: kmsKey
});
new StringParameter(this, 'SHARR_SNS_Topic', {
description: 'SNS Topic ARN where SHARR will send status messages. This\
topic can be useful for driving additional actions, such as email notifications,\
trouble ticket updates.',
parameterName: '/Solutions/' + RESOURCE_PREFIX + '/SNS_Topic_ARN',
stringValue: snsTopic.topicArn
});
const mapping = new cdk.CfnMapping(this, 'mappings');
mapping.setValue("sendAnonymousMetrics", "data", this.SEND_ANONYMOUS_DATA)
new StringParameter(this, 'SHARR_SendAnonymousMetrics', {
description: 'Flag to enable or disable sending anonymous metrics.',
parameterName: '/Solutions/' + RESOURCE_PREFIX + '/sendAnonymousMetrics',
stringValue: mapping.findInMap("sendAnonymousMetrics", "data")
});
new StringParameter(this, 'SHARR_version', {
description: 'Solution version for metrics.',
parameterName: '/Solutions/' + RESOURCE_PREFIX + '/version',
stringValue: props.solutionVersion
});
/**
* @description Lambda Layer for common solution functions
* @type {lambda.LayerVersion}
*/
const sharrLambdaLayer = new lambda.LayerVersion(this, 'SharrLambdaLayer', {
compatibleRuntimes: [
lambda.Runtime.PYTHON_3_6,
lambda.Runtime.PYTHON_3_7,
lambda.Runtime.PYTHON_3_8
],
description: 'SO0111 SHARR Common functions used by the solution',
license: "https://www.apache.org/licenses/LICENSE-2.0",
code: lambda.Code.fromBucket(
SolutionsBucket,
props.solutionTMN + '/' + props.solutionVersion + '/lambda/layer.zip'
),
});
/**
* @description Policy for role used by common Orchestrator Lambdas
* @type {Policy}
*/
const orchestratorPolicy = new Policy(this, 'orchestratorPolicy', {
policyName: RESOURCE_PREFIX + '-SHARR_Orchestrator',
statements: [
new PolicyStatement({
actions: [
'logs:CreateLogGroup',
'logs:CreateLogStream',
'logs:PutLogEvents'
],
resources: ['*']
}),
new PolicyStatement({
actions: [
'ssm:GetParameter',
'ssm:GetParameters',
'ssm:PutParameter'
],
resources: [`arn:${this.partition}:ssm:*:${this.account}:parameter/Solutions/SO0111/*`]
}),
new PolicyStatement({
actions: [
'sts:AssumeRole'
],
resources: [
`arn:${this.partition}:iam::*:role/${RESOURCE_PREFIX}-SHARR-Orchestrator-Member`,
'arn:' + this.partition + ':iam::*:role/' + RESOURCE_PREFIX +
'-Remediate-*',
]
})
]
})
{
let childToMod = orchestratorPolicy.node.findChild('Resource') as CfnPolicy;
childToMod.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [{
id: 'W12',
reason: 'Resource * is required for read-only policies used by orchestrator Lambda functions.'
}]
}
}
}
/**
* @description Role used by common Orchestrator Lambdas
* @type {Role}
*/
const orchestratorRole = new Role(this, 'orchestratorRole', {
assumedBy: new ServicePrincipal('lambda.amazonaws.com'),
description: 'Lambda role to allow cross account read-only SHARR orchestrator functions',
roleName: `${RESOURCE_PREFIX}-SHARR-Orchestrator-Admin`
});
orchestratorRole.attachInlinePolicy(orchestratorPolicy);
{
let childToMod = orchestratorRole.node.findChild('Resource') as CfnRole;
childToMod.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [{
id: 'W28',
reason: 'Static names chosen intentionally to provide easy integration with playbook orchestrator step functions.'
}]
}
}
}
/**
* @description checkSSMDocState - get the status of an ssm document
* @type {lambda.Function}
*/
const checkSSMDocState = new lambda.Function(this, 'checkSSMDocState', {
functionName: RESOURCE_PREFIX + '-SHARR-checkSSMDocState',
handler: 'check_ssm_doc_state.lambda_handler',
runtime: props.runtimePython,
description: 'Checks the status of an SSM Automation Document in the target account',
code: lambda.Code.fromBucket(
SolutionsBucket,
props.solutionTMN + '/' + props.solutionVersion + '/lambda/check_ssm_doc_state.py.zip'
),
environment: {
log_level: 'info',
AWS_PARTITION: this.partition,
SOLUTION_ID: props.solutionId,
SOLUTION_VERSION: props.solutionVersion
},
memorySize: 256,
timeout: cdk.Duration.seconds(600),
role: orchestratorRole,
layers: [sharrLambdaLayer]
});
{
const childToMod = checkSSMDocState.node.findChild('Resource') as lambda.CfnFunction;
childToMod.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [
{
id: 'W58',
reason: 'False positive. Access is provided via a policy'
},
{
id: 'W89',
reason: 'There is no need to run this lambda in a VPC'
},
{
id: 'W92',
reason: 'There is no need for Reserved Concurrency'
}
]
}
};
}
/**
* @description getApprovalRequirement - determine whether manual approval is required
* @type {lambda.Function}
*/
const getApprovalRequirement = new lambda.Function(this, 'getApprovalRequirement', {
functionName: RESOURCE_PREFIX + '-SHARR-getApprovalRequirement',
handler: 'get_approval_requirement.lambda_handler',
runtime: props.runtimePython,
description: 'Determines if a manual approval is required for remediation',
code: lambda.Code.fromBucket(
SolutionsBucket,
props.solutionTMN + '/' + props.solutionVersion + '/lambda/get_approval_requirement.py.zip'
),
environment: {
log_level: 'info',
AWS_PARTITION: this.partition,
SOLUTION_ID: props.solutionId,
SOLUTION_VERSION: props.solutionVersion,
WORKFLOW_RUNBOOK: ''
},
memorySize: 256,
timeout: cdk.Duration.seconds(600),
role: orchestratorRole,
layers: [sharrLambdaLayer]
});
{
const childToMod = getApprovalRequirement.node.findChild('Resource') as lambda.CfnFunction;
childToMod.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [{
id: 'W58',
reason: 'False positive. Access is provided via a policy'
},{
id: 'W89',
reason: 'There is no need to run this lambda in a VPC'
},
{
id: 'W92',
reason: 'There is no need for Reserved Concurrency'
}]
}
};
}
/**
* @description execAutomation - initiate an SSM automation document in a target account
* @type {lambda.Function}
*/
const execAutomation = new lambda.Function(this, 'execAutomation', {
functionName: RESOURCE_PREFIX + '-SHARR-execAutomation',
handler: 'exec_ssm_doc.lambda_handler',
runtime: props.runtimePython,
description: 'Executes an SSM Automation Document in a target account',
code: lambda.Code.fromBucket(
SolutionsBucket,
props.solutionTMN + '/' + props.solutionVersion + '/lambda/exec_ssm_doc.py.zip'
),
environment: {
log_level: 'info',
AWS_PARTITION: this.partition,
SOLUTION_ID: props.solutionId,
SOLUTION_VERSION: props.solutionVersion
},
memorySize: 256,
timeout: cdk.Duration.seconds(600),
role: orchestratorRole,
layers: [sharrLambdaLayer]
});
{
const childToMod = execAutomation.node.findChild('Resource') as lambda.CfnFunction;
childToMod.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [{
id: 'W58',
reason: 'False positive. Access is provided via a policy'
},{
id: 'W89',
reason: 'There is no need to run this lambda in a VPC'
},
{
id: 'W92',
reason: 'There is no need for Reserved Concurrency'
}]
}
};
}
/**
* @description monitorSSMExecState - get the status of an ssm execution
* @type {lambda.Function}
*/
const monitorSSMExecState = new lambda.Function(this, 'monitorSSMExecState', {
functionName: RESOURCE_PREFIX + '-SHARR-monitorSSMExecState',
handler: 'check_ssm_execution.lambda_handler',
runtime: props.runtimePython,
description: 'Checks the status of an SSM automation document execution',
code: lambda.Code.fromBucket(
SolutionsBucket,
props.solutionTMN + '/' + props.solutionVersion + '/lambda/check_ssm_execution.py.zip'
),
environment: {
log_level: 'info',
AWS_PARTITION: this.partition,
SOLUTION_ID: props.solutionId,
SOLUTION_VERSION: props.solutionVersion
},
memorySize: 256,
timeout: cdk.Duration.seconds(600),
role: orchestratorRole,
layers: [sharrLambdaLayer]
});
{
const childToMod = monitorSSMExecState.node.findChild('Resource') as lambda.CfnFunction;
childToMod.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [{
id: 'W58',
reason: 'False positive. Access is provided via a policy'
},{
id: 'W89',
reason: 'There is no need to run this lambda in a VPC'
},
{
id: 'W92',
reason: 'There is no need for Reserved Concurrency'
}]
}
};
}
/**
* @description Policy for role used by common Orchestrator notification lambda
* @type {Policy}
*/
const notifyPolicy = new Policy(this, 'notifyPolicy', {
policyName: RESOURCE_PREFIX + '-SHARR_Orchestrator_Notifier',
statements: [
new PolicyStatement({
actions: [
'logs:CreateLogGroup',
'logs:CreateLogStream',
'logs:PutLogEvents'
],
resources: ['*']
}),
new PolicyStatement({
actions: [
'securityhub:BatchUpdateFindings'
],
resources: ['*']
}),
new PolicyStatement({
actions: [
'ssm:GetParameter'
],
resources: [`arn:${this.partition}:ssm:${this.region}:${this.account}:parameter/Solutions/SO0111/*`]
}),
new PolicyStatement({
actions: [
'kms:Encrypt',
'kms:Decrypt',
'kms:GenerateDataKey',
],
resources: [kmsKey.keyArn]
}),
new PolicyStatement({
actions: [
'sns:Publish'
],
resources: [
`arn:${this.partition}:sns:${this.region}:${this.account}:${RESOURCE_PREFIX}-SHARR_Topic`
]
})
]
})
{
let childToMod = notifyPolicy.node.findChild('Resource') as CfnPolicy;
childToMod.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [{
id: 'W12',
reason: 'Resource * is required for CloudWatch Logs and Security Hub policies used by core solution Lambda function for notifications.'
},{
id: 'W58',
reason: 'False positive. Access is provided via a policy'
}]
}
}
}
notifyPolicy.attachToRole(orchestratorRole) // Any Orchestrator Lambda can send to sns
/**
* @description Role used by common Orchestrator Lambdas
* @type {Role}
*/
const notifyRole = new Role(this, 'notifyRole', {
assumedBy: new ServicePrincipal('lambda.amazonaws.com'),
description: 'Lambda role to perform notification and logging from orchestrator step function'
});
notifyRole.attachInlinePolicy(notifyPolicy);
{
let childToMod = notifyRole.node.findChild('Resource') as CfnRole;
childToMod.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [{
id: 'W28',
reason: 'Static names chosen intentionally to provide easy integration with playbook orchestrator step functions.'
}]
}
}
}
/**
* @description sendNotifications - send notifications and log messages from Orchestrator step function
* @type {lambda.Function}
*/
const sendNotifications = new lambda.Function(this, 'sendNotifications', {
functionName: RESOURCE_PREFIX + '-SHARR-sendNotifications',
handler: 'send_notifications.lambda_handler',
runtime: props.runtimePython,
description: 'Sends notifications and log messages',
code: lambda.Code.fromBucket(
SolutionsBucket,
props.solutionTMN + '/' + props.solutionVersion + '/lambda/send_notifications.py.zip'
),
environment: {
log_level: 'info',
AWS_PARTITION: this.partition,
SOLUTION_ID: props.solutionId,
SOLUTION_VERSION: props.solutionVersion
},
memorySize: 256,
timeout: cdk.Duration.seconds(600),
role: notifyRole,
layers: [sharrLambdaLayer]
});
{
const childToMod = sendNotifications.node.findChild('Resource') as lambda.CfnFunction;
childToMod.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [{
id: 'W58',
reason: 'False positive. Access is provided via a policy'
},{
id: 'W89',
reason: 'There is no need to run this lambda in a VPC'
},
{
id: 'W92',
reason: 'There is no need for Reserved Concurrency due to low request rate'
}]
}
};
}
//-------------------------------------------------------------------------
// Custom Lambda Policy
//
const createCustomActionPolicy = new Policy(this, 'createCustomActionPolicy', {
policyName: RESOURCE_PREFIX + '-SHARR_Custom_Action',
statements: [
new PolicyStatement({
actions: [
'cloudwatch:PutMetricData'
],
resources: ['*']
}),
new PolicyStatement({
actions: [
'logs:CreateLogGroup',
'logs:CreateLogStream',
'logs:PutLogEvents'
],
resources: ['*']
}),
new PolicyStatement({
actions: [
'securityhub:CreateActionTarget',
'securityhub:DeleteActionTarget'
],
resources: ['*']
}),
new PolicyStatement({
actions: [
'ssm:GetParameter',
'ssm:GetParameters',
'ssm:PutParameter'
],
resources: [`arn:${this.partition}:ssm:*:${this.account}:parameter/Solutions/SO0111/*`]
}),
]
})
const createCAPolicyResource = createCustomActionPolicy.node.findChild('Resource') as CfnPolicy;
createCAPolicyResource.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [{
id: 'W12',
reason: 'Resource * is required for CloudWatch Logs policies used on Lambda functions.'
}]
}
};
//-------------------------------------------------------------------------
// Custom Lambda Role
//
const createCustomActionRole = new Role(this, 'createCustomActionRole', {
assumedBy: new ServicePrincipal('lambda.amazonaws.com'),
description: 'Lambda role to allow creation of Security Hub Custom Actions'
});
createCustomActionRole.attachInlinePolicy(createCustomActionPolicy);
const createCARoleResource = createCustomActionRole.node.findChild('Resource') as CfnRole;
createCARoleResource.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [{
id: 'W28',
reason: 'Static names chosen intentionally to provide easy integration with playbook templates'
}]
}
};
//-------------------------------------------------------------------------
// Custom Lambda - Create Custom Action
//
const createCustomAction = new lambda.Function(this, 'CreateCustomAction', {
functionName: RESOURCE_PREFIX + '-SHARR-CustomAction',
handler: 'createCustomAction.lambda_handler',
runtime: props.runtimePython,
description: 'Custom resource to create an action target in Security Hub',
code: lambda.Code.fromBucket(
SolutionsBucket,
props.solutionTMN + '/' + props.solutionVersion + '/lambda/createCustomAction.py.zip'
),
environment: {
log_level: 'info',
AWS_PARTITION: this.partition,
sendAnonymousMetrics: mapping.findInMap("sendAnonymousMetrics", "data"),
SOLUTION_ID: props.solutionId,
SOLUTION_VERSION: props.solutionVersion
},
memorySize: 256,
timeout: cdk.Duration.seconds(600),
role: createCustomActionRole,
layers: [sharrLambdaLayer]
});
const createCAFuncResource = createCustomAction.node.findChild('Resource') as lambda.CfnFunction;
createCAFuncResource.cfnOptions.metadata = {
cfn_nag: {
rules_to_suppress: [
{
id: 'W58',
reason: 'False positive. the lambda role allows write to CW Logs'
},
{
id: 'W89',
reason: 'There is no need to run this lambda in a VPC'
},
{
id: 'W92',
reason: 'There is no need for Reserved Concurrency due to low request rate'
}]
}
};
const orchestrator = new OrchestratorConstruct(this, "orchestrator", {
roleArn: orchestratorRole.roleArn,
ssmDocStateLambda: checkSSMDocState.functionArn,
ssmExecDocLambda: execAutomation.functionArn,
ssmExecMonitorLambda: monitorSSMExecState.functionArn,
notifyLambda: sendNotifications.functionArn,
getApprovalRequirementLambda: getApprovalRequirement.functionArn,
solutionId: RESOURCE_PREFIX,
solutionName: props.solutionName,
solutionVersion: props.solutionVersion,
orchLogGroup: props.orchLogGroup,
kmsKeyParm: kmsKeyParm
})
let orchStateMachine = orchestrator.node.findChild('StateMachine') as StateMachine
let stateMachineConstruct = orchStateMachine.node.defaultChild as CfnStateMachine
let orchArnParm = orchestrator.node.findChild('SHARR_Orchestrator_Arn') as StringParameter
let orchestratorArn = orchArnParm.node.defaultChild as CfnParameter
//---------------------------------------------------------------------
// OneTrigger - Remediate with SHARR custom action
//
new OneTrigger(this, 'RemediateWithSharr', {
targetArn: orchStateMachine.stateMachineArn,
serviceToken: createCustomAction.functionArn,
prereq: [
createCAFuncResource,
createCAPolicyResource
]
})
//-------------------------------------------------------------------------
// Loop through all of the Playbooks and create an option to load each
//
const PB_DIR = `${__dirname}/../../playbooks`
var ignore = ['.DS_Store', 'core', 'python_lib', 'python_tests', '.pytest_cache', 'NEWPLAYBOOK', '.coverage'];
let illegalChars = /[\._]/g;
var standardLogicalNames: string[] = []
fs.readdir(PB_DIR, (err, items) => {
items.forEach(file => {
if (!ignore.includes(file)) {
var template_file = `${file}Stack.template`
//---------------------------------------------------------------------
// Playbook Admin Template Nested Stack
//
let parmname = file.replace(illegalChars, '')
let adminStackOption = new cdk.CfnParameter(this, `LoadAdminStack${parmname}`, {
type: "String",
description: `Load CloudWatch Event Rules for ${file}?`,
default: "yes",
allowedValues: ["yes", "no"],
})
adminStackOption.overrideLogicalId(`Load${parmname}AdminStack`)
standardLogicalNames.push(`Load${parmname}AdminStack`)
let adminStack = new cdk.CfnStack(this, `PlaybookAdminStack${file}`, {
templateUrl: "https://" + cdk.Fn.findInMap("SourceCode", "General", "S3Bucket") +
"-reference.s3.amazonaws.com/" + cdk.Fn.findInMap("SourceCode", "General", "KeyPrefix") +
"/playbooks/" + template_file
})
adminStack.addDependsOn(stateMachineConstruct)
adminStack.addDependsOn(orchestratorArn)
adminStack.cfnOptions.condition = new cdk.CfnCondition(this, `load${file}Cond`, {
expression:
cdk.Fn.conditionEquals(adminStackOption, "yes")
});
}
});
})
stack.templateOptions.metadata = {
"AWS::CloudFormation::Interface": {
ParameterGroups: [
{
Label: {default: "Security Standard Playbooks"},
Parameters: standardLogicalNames
}
]
},
};
}
} | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import {
AddApplicationCloudWatchLoggingOptionCommand,
AddApplicationCloudWatchLoggingOptionCommandInput,
AddApplicationCloudWatchLoggingOptionCommandOutput,
} from "./commands/AddApplicationCloudWatchLoggingOptionCommand";
import {
AddApplicationInputCommand,
AddApplicationInputCommandInput,
AddApplicationInputCommandOutput,
} from "./commands/AddApplicationInputCommand";
import {
AddApplicationInputProcessingConfigurationCommand,
AddApplicationInputProcessingConfigurationCommandInput,
AddApplicationInputProcessingConfigurationCommandOutput,
} from "./commands/AddApplicationInputProcessingConfigurationCommand";
import {
AddApplicationOutputCommand,
AddApplicationOutputCommandInput,
AddApplicationOutputCommandOutput,
} from "./commands/AddApplicationOutputCommand";
import {
AddApplicationReferenceDataSourceCommand,
AddApplicationReferenceDataSourceCommandInput,
AddApplicationReferenceDataSourceCommandOutput,
} from "./commands/AddApplicationReferenceDataSourceCommand";
import {
CreateApplicationCommand,
CreateApplicationCommandInput,
CreateApplicationCommandOutput,
} from "./commands/CreateApplicationCommand";
import {
DeleteApplicationCloudWatchLoggingOptionCommand,
DeleteApplicationCloudWatchLoggingOptionCommandInput,
DeleteApplicationCloudWatchLoggingOptionCommandOutput,
} from "./commands/DeleteApplicationCloudWatchLoggingOptionCommand";
import {
DeleteApplicationCommand,
DeleteApplicationCommandInput,
DeleteApplicationCommandOutput,
} from "./commands/DeleteApplicationCommand";
import {
DeleteApplicationInputProcessingConfigurationCommand,
DeleteApplicationInputProcessingConfigurationCommandInput,
DeleteApplicationInputProcessingConfigurationCommandOutput,
} from "./commands/DeleteApplicationInputProcessingConfigurationCommand";
import {
DeleteApplicationOutputCommand,
DeleteApplicationOutputCommandInput,
DeleteApplicationOutputCommandOutput,
} from "./commands/DeleteApplicationOutputCommand";
import {
DeleteApplicationReferenceDataSourceCommand,
DeleteApplicationReferenceDataSourceCommandInput,
DeleteApplicationReferenceDataSourceCommandOutput,
} from "./commands/DeleteApplicationReferenceDataSourceCommand";
import {
DescribeApplicationCommand,
DescribeApplicationCommandInput,
DescribeApplicationCommandOutput,
} from "./commands/DescribeApplicationCommand";
import {
DiscoverInputSchemaCommand,
DiscoverInputSchemaCommandInput,
DiscoverInputSchemaCommandOutput,
} from "./commands/DiscoverInputSchemaCommand";
import {
ListApplicationsCommand,
ListApplicationsCommandInput,
ListApplicationsCommandOutput,
} from "./commands/ListApplicationsCommand";
import {
ListTagsForResourceCommand,
ListTagsForResourceCommandInput,
ListTagsForResourceCommandOutput,
} from "./commands/ListTagsForResourceCommand";
import {
StartApplicationCommand,
StartApplicationCommandInput,
StartApplicationCommandOutput,
} from "./commands/StartApplicationCommand";
import {
StopApplicationCommand,
StopApplicationCommandInput,
StopApplicationCommandOutput,
} from "./commands/StopApplicationCommand";
import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import {
UntagResourceCommand,
UntagResourceCommandInput,
UntagResourceCommandOutput,
} from "./commands/UntagResourceCommand";
import {
UpdateApplicationCommand,
UpdateApplicationCommandInput,
UpdateApplicationCommandOutput,
} from "./commands/UpdateApplicationCommand";
import { KinesisAnalyticsClient } from "./KinesisAnalyticsClient";
/**
* <fullname>Amazon Kinesis Analytics</fullname>
* <p>
* <b>Overview</b>
* </p>
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>This is the <i>Amazon Kinesis Analytics v1 API Reference</i>.
* The Amazon Kinesis Analytics Developer Guide provides additional information.
* </p>
*/
export class KinesisAnalytics extends KinesisAnalyticsClient {
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Adds a CloudWatch log stream to monitor application configuration errors. For more
* information about using CloudWatch log streams with Amazon Kinesis Analytics
* applications, see <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/cloudwatch-logs.html">Working with Amazon
* CloudWatch Logs</a>.</p>
*/
public addApplicationCloudWatchLoggingOption(
args: AddApplicationCloudWatchLoggingOptionCommandInput,
options?: __HttpHandlerOptions
): Promise<AddApplicationCloudWatchLoggingOptionCommandOutput>;
public addApplicationCloudWatchLoggingOption(
args: AddApplicationCloudWatchLoggingOptionCommandInput,
cb: (err: any, data?: AddApplicationCloudWatchLoggingOptionCommandOutput) => void
): void;
public addApplicationCloudWatchLoggingOption(
args: AddApplicationCloudWatchLoggingOptionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AddApplicationCloudWatchLoggingOptionCommandOutput) => void
): void;
public addApplicationCloudWatchLoggingOption(
args: AddApplicationCloudWatchLoggingOptionCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: AddApplicationCloudWatchLoggingOptionCommandOutput) => void),
cb?: (err: any, data?: AddApplicationCloudWatchLoggingOptionCommandOutput) => void
): Promise<AddApplicationCloudWatchLoggingOptionCommandOutput> | void {
const command = new AddApplicationCloudWatchLoggingOptionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>
* Adds a streaming source to your Amazon Kinesis application.
* For conceptual information,
* see <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-input.html">Configuring Application Input</a>.
* </p>
* <p>You can add a streaming source either when you create an application or you can use
* this operation to add a streaming source after you create an application. For more information, see
* <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_CreateApplication.html">CreateApplication</a>.</p>
* <p>Any configuration update, including adding a streaming source using this operation,
* results in a new version of the application. You can use the <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_DescribeApplication.html">DescribeApplication</a> operation
* to find the current application version.
* </p>
* <p>This operation requires permissions to perform the
* <code>kinesisanalytics:AddApplicationInput</code> action.</p>
*/
public addApplicationInput(
args: AddApplicationInputCommandInput,
options?: __HttpHandlerOptions
): Promise<AddApplicationInputCommandOutput>;
public addApplicationInput(
args: AddApplicationInputCommandInput,
cb: (err: any, data?: AddApplicationInputCommandOutput) => void
): void;
public addApplicationInput(
args: AddApplicationInputCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AddApplicationInputCommandOutput) => void
): void;
public addApplicationInput(
args: AddApplicationInputCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AddApplicationInputCommandOutput) => void),
cb?: (err: any, data?: AddApplicationInputCommandOutput) => void
): Promise<AddApplicationInputCommandOutput> | void {
const command = new AddApplicationInputCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Adds an <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_InputProcessingConfiguration.html">InputProcessingConfiguration</a> to an application. An input processor preprocesses records on the input stream
* before the application's SQL code executes. Currently, the only input processor available is
* <a href="https://docs.aws.amazon.com/lambda/">AWS Lambda</a>.</p>
*/
public addApplicationInputProcessingConfiguration(
args: AddApplicationInputProcessingConfigurationCommandInput,
options?: __HttpHandlerOptions
): Promise<AddApplicationInputProcessingConfigurationCommandOutput>;
public addApplicationInputProcessingConfiguration(
args: AddApplicationInputProcessingConfigurationCommandInput,
cb: (err: any, data?: AddApplicationInputProcessingConfigurationCommandOutput) => void
): void;
public addApplicationInputProcessingConfiguration(
args: AddApplicationInputProcessingConfigurationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AddApplicationInputProcessingConfigurationCommandOutput) => void
): void;
public addApplicationInputProcessingConfiguration(
args: AddApplicationInputProcessingConfigurationCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: AddApplicationInputProcessingConfigurationCommandOutput) => void),
cb?: (err: any, data?: AddApplicationInputProcessingConfigurationCommandOutput) => void
): Promise<AddApplicationInputProcessingConfigurationCommandOutput> | void {
const command = new AddApplicationInputProcessingConfigurationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Adds an external destination to your Amazon Kinesis Analytics application.</p>
* <p>If you want Amazon Kinesis Analytics to deliver data from an in-application stream
* within your application to an external destination (such as an Amazon Kinesis stream, an
* Amazon Kinesis Firehose delivery stream, or an AWS Lambda function), you add the
* relevant configuration to your application using this operation. You can configure one
* or more outputs for your application. Each output configuration maps an in-application
* stream and an external destination.</p>
* <p> You can use one of the output configurations to deliver data from your
* in-application error stream to an external destination so that you can analyze the
* errors. For more information, see <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-output.html">Understanding Application
* Output (Destination)</a>. </p>
* <p> Any configuration update, including adding a streaming source using this
* operation, results in a new version of the application. You can use the <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_DescribeApplication.html">DescribeApplication</a> operation to find the current application
* version.</p>
* <p>For the limits on the number of application inputs and outputs
* you can configure, see <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/limits.html">Limits</a>.</p>
* <p>This operation requires permissions to perform the <code>kinesisanalytics:AddApplicationOutput</code> action.</p>
*/
public addApplicationOutput(
args: AddApplicationOutputCommandInput,
options?: __HttpHandlerOptions
): Promise<AddApplicationOutputCommandOutput>;
public addApplicationOutput(
args: AddApplicationOutputCommandInput,
cb: (err: any, data?: AddApplicationOutputCommandOutput) => void
): void;
public addApplicationOutput(
args: AddApplicationOutputCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AddApplicationOutputCommandOutput) => void
): void;
public addApplicationOutput(
args: AddApplicationOutputCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AddApplicationOutputCommandOutput) => void),
cb?: (err: any, data?: AddApplicationOutputCommandOutput) => void
): Promise<AddApplicationOutputCommandOutput> | void {
const command = new AddApplicationOutputCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Adds a reference data source to an existing application.</p>
* <p>Amazon Kinesis Analytics reads reference data (that is, an Amazon S3 object) and creates an in-application table within your application. In the request, you provide the source (S3 bucket name and object key name), name of the in-application table to create, and the necessary mapping information that describes how data in Amazon S3 object maps to columns in the resulting in-application table.</p>
* <p>
* For conceptual information,
* see <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-input.html">Configuring Application Input</a>.
* For the limits on data sources you can add to your application, see
* <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/limits.html">Limits</a>.
* </p>
* <p>
* This operation requires permissions to perform the <code>kinesisanalytics:AddApplicationOutput</code> action.
* </p>
*/
public addApplicationReferenceDataSource(
args: AddApplicationReferenceDataSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<AddApplicationReferenceDataSourceCommandOutput>;
public addApplicationReferenceDataSource(
args: AddApplicationReferenceDataSourceCommandInput,
cb: (err: any, data?: AddApplicationReferenceDataSourceCommandOutput) => void
): void;
public addApplicationReferenceDataSource(
args: AddApplicationReferenceDataSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AddApplicationReferenceDataSourceCommandOutput) => void
): void;
public addApplicationReferenceDataSource(
args: AddApplicationReferenceDataSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AddApplicationReferenceDataSourceCommandOutput) => void),
cb?: (err: any, data?: AddApplicationReferenceDataSourceCommandOutput) => void
): Promise<AddApplicationReferenceDataSourceCommandOutput> | void {
const command = new AddApplicationReferenceDataSourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
*
* <p>
* Creates an Amazon Kinesis Analytics application.
* You can configure each application with one streaming source as input,
* application code to process the input, and up to
* three destinations where
* you want Amazon Kinesis Analytics to write the output data from your application.
* For an overview, see
* <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works.html">How it Works</a>.
* </p>
* <p>In the input configuration, you map the streaming source to an in-application stream, which you can think of as a constantly updating table. In the mapping, you must provide a schema for the in-application stream and map each data column in the in-application stream to a
* data element in the streaming source.</p>
*
* <p>Your application code is one or more SQL statements that read input data, transform it, and generate output. Your application code can create one or more SQL artifacts like SQL streams or pumps.</p>
* <p>In the output configuration, you can configure the application to write data from in-application streams created in your applications to up to three destinations.</p>
* <p>
* To read data from your source stream or write data to destination streams, Amazon Kinesis Analytics
* needs your permissions. You grant these permissions by creating IAM roles. This operation requires permissions to perform the
* <code>kinesisanalytics:CreateApplication</code> action.
* </p>
* <p>
* For introductory exercises to create an Amazon Kinesis Analytics application, see
* <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/getting-started.html">Getting Started</a>.
* </p>
*/
public createApplication(
args: CreateApplicationCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateApplicationCommandOutput>;
public createApplication(
args: CreateApplicationCommandInput,
cb: (err: any, data?: CreateApplicationCommandOutput) => void
): void;
public createApplication(
args: CreateApplicationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateApplicationCommandOutput) => void
): void;
public createApplication(
args: CreateApplicationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateApplicationCommandOutput) => void),
cb?: (err: any, data?: CreateApplicationCommandOutput) => void
): Promise<CreateApplicationCommandOutput> | void {
const command = new CreateApplicationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Deletes the specified application. Amazon Kinesis Analytics halts application execution and deletes the application, including any application artifacts (such as in-application streams, reference table, and application code).</p>
*
* <p>This operation requires permissions to perform the <code>kinesisanalytics:DeleteApplication</code> action.</p>
*/
public deleteApplication(
args: DeleteApplicationCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteApplicationCommandOutput>;
public deleteApplication(
args: DeleteApplicationCommandInput,
cb: (err: any, data?: DeleteApplicationCommandOutput) => void
): void;
public deleteApplication(
args: DeleteApplicationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteApplicationCommandOutput) => void
): void;
public deleteApplication(
args: DeleteApplicationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteApplicationCommandOutput) => void),
cb?: (err: any, data?: DeleteApplicationCommandOutput) => void
): Promise<DeleteApplicationCommandOutput> | void {
const command = new DeleteApplicationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Deletes a CloudWatch log stream from an application. For more information about
* using CloudWatch log streams with Amazon Kinesis Analytics applications, see
* <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/cloudwatch-logs.html">Working with Amazon CloudWatch Logs</a>.</p>
*/
public deleteApplicationCloudWatchLoggingOption(
args: DeleteApplicationCloudWatchLoggingOptionCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteApplicationCloudWatchLoggingOptionCommandOutput>;
public deleteApplicationCloudWatchLoggingOption(
args: DeleteApplicationCloudWatchLoggingOptionCommandInput,
cb: (err: any, data?: DeleteApplicationCloudWatchLoggingOptionCommandOutput) => void
): void;
public deleteApplicationCloudWatchLoggingOption(
args: DeleteApplicationCloudWatchLoggingOptionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteApplicationCloudWatchLoggingOptionCommandOutput) => void
): void;
public deleteApplicationCloudWatchLoggingOption(
args: DeleteApplicationCloudWatchLoggingOptionCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: DeleteApplicationCloudWatchLoggingOptionCommandOutput) => void),
cb?: (err: any, data?: DeleteApplicationCloudWatchLoggingOptionCommandOutput) => void
): Promise<DeleteApplicationCloudWatchLoggingOptionCommandOutput> | void {
const command = new DeleteApplicationCloudWatchLoggingOptionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Deletes an <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_InputProcessingConfiguration.html">InputProcessingConfiguration</a> from an input.</p>
*/
public deleteApplicationInputProcessingConfiguration(
args: DeleteApplicationInputProcessingConfigurationCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteApplicationInputProcessingConfigurationCommandOutput>;
public deleteApplicationInputProcessingConfiguration(
args: DeleteApplicationInputProcessingConfigurationCommandInput,
cb: (err: any, data?: DeleteApplicationInputProcessingConfigurationCommandOutput) => void
): void;
public deleteApplicationInputProcessingConfiguration(
args: DeleteApplicationInputProcessingConfigurationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteApplicationInputProcessingConfigurationCommandOutput) => void
): void;
public deleteApplicationInputProcessingConfiguration(
args: DeleteApplicationInputProcessingConfigurationCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: DeleteApplicationInputProcessingConfigurationCommandOutput) => void),
cb?: (err: any, data?: DeleteApplicationInputProcessingConfigurationCommandOutput) => void
): Promise<DeleteApplicationInputProcessingConfigurationCommandOutput> | void {
const command = new DeleteApplicationInputProcessingConfigurationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Deletes output destination configuration from your application configuration. Amazon Kinesis Analytics will no longer write data from the corresponding in-application stream to the external output destination.</p>
* <p>This operation requires permissions to perform the
* <code>kinesisanalytics:DeleteApplicationOutput</code> action.</p>
*/
public deleteApplicationOutput(
args: DeleteApplicationOutputCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteApplicationOutputCommandOutput>;
public deleteApplicationOutput(
args: DeleteApplicationOutputCommandInput,
cb: (err: any, data?: DeleteApplicationOutputCommandOutput) => void
): void;
public deleteApplicationOutput(
args: DeleteApplicationOutputCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteApplicationOutputCommandOutput) => void
): void;
public deleteApplicationOutput(
args: DeleteApplicationOutputCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteApplicationOutputCommandOutput) => void),
cb?: (err: any, data?: DeleteApplicationOutputCommandOutput) => void
): Promise<DeleteApplicationOutputCommandOutput> | void {
const command = new DeleteApplicationOutputCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Deletes a reference data source configuration from the specified application configuration.</p>
* <p>If the application is running, Amazon Kinesis Analytics immediately removes the in-application table
* that you created using the <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_AddApplicationReferenceDataSource.html">AddApplicationReferenceDataSource</a> operation. </p>
*
* <p>This operation requires permissions to perform the <code>kinesisanalytics.DeleteApplicationReferenceDataSource</code>
* action.</p>
*/
public deleteApplicationReferenceDataSource(
args: DeleteApplicationReferenceDataSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteApplicationReferenceDataSourceCommandOutput>;
public deleteApplicationReferenceDataSource(
args: DeleteApplicationReferenceDataSourceCommandInput,
cb: (err: any, data?: DeleteApplicationReferenceDataSourceCommandOutput) => void
): void;
public deleteApplicationReferenceDataSource(
args: DeleteApplicationReferenceDataSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteApplicationReferenceDataSourceCommandOutput) => void
): void;
public deleteApplicationReferenceDataSource(
args: DeleteApplicationReferenceDataSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteApplicationReferenceDataSourceCommandOutput) => void),
cb?: (err: any, data?: DeleteApplicationReferenceDataSourceCommandOutput) => void
): Promise<DeleteApplicationReferenceDataSourceCommandOutput> | void {
const command = new DeleteApplicationReferenceDataSourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Returns information about a specific Amazon Kinesis Analytics application.</p>
* <p>If you want to retrieve a list of all applications in your account,
* use the <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_ListApplications.html">ListApplications</a> operation.</p>
* <p>This operation requires permissions to perform the <code>kinesisanalytics:DescribeApplication</code>
* action. You can use <code>DescribeApplication</code> to get the current application versionId, which you need to call other
* operations such as <code>Update</code>.
* </p>
*/
public describeApplication(
args: DescribeApplicationCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeApplicationCommandOutput>;
public describeApplication(
args: DescribeApplicationCommandInput,
cb: (err: any, data?: DescribeApplicationCommandOutput) => void
): void;
public describeApplication(
args: DescribeApplicationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeApplicationCommandOutput) => void
): void;
public describeApplication(
args: DescribeApplicationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeApplicationCommandOutput) => void),
cb?: (err: any, data?: DescribeApplicationCommandOutput) => void
): Promise<DescribeApplicationCommandOutput> | void {
const command = new DescribeApplicationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Infers a schema by evaluating sample records on the specified streaming source (Amazon Kinesis stream or Amazon Kinesis Firehose delivery stream) or S3 object. In the response, the operation returns the inferred schema and also the sample records that the operation used to infer the schema.</p>
* <p>
* You can use the inferred schema when configuring a streaming source
* for your application. For conceptual information,
* see <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-it-works-input.html">Configuring Application Input</a>.
* Note that when you create an application using the Amazon Kinesis Analytics console,
* the console uses this operation to infer a schema and show it in the console user interface.
* </p>
* <p>
* This operation requires permissions to perform the
* <code>kinesisanalytics:DiscoverInputSchema</code> action.
* </p>
*/
public discoverInputSchema(
args: DiscoverInputSchemaCommandInput,
options?: __HttpHandlerOptions
): Promise<DiscoverInputSchemaCommandOutput>;
public discoverInputSchema(
args: DiscoverInputSchemaCommandInput,
cb: (err: any, data?: DiscoverInputSchemaCommandOutput) => void
): void;
public discoverInputSchema(
args: DiscoverInputSchemaCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DiscoverInputSchemaCommandOutput) => void
): void;
public discoverInputSchema(
args: DiscoverInputSchemaCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DiscoverInputSchemaCommandOutput) => void),
cb?: (err: any, data?: DiscoverInputSchemaCommandOutput) => void
): Promise<DiscoverInputSchemaCommandOutput> | void {
const command = new DiscoverInputSchemaCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Returns a list of Amazon Kinesis Analytics applications in your account.
* For each application, the response includes the application name,
* Amazon Resource Name (ARN), and status.
*
* If the response returns the <code>HasMoreApplications</code> value as true,
* you can send another request by adding the
* <code>ExclusiveStartApplicationName</code> in the request body, and
* set the value of this to the last application name from
* the previous response.
* </p>
* <p>If you want detailed information about a specific application, use
* <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_DescribeApplication.html">DescribeApplication</a>.</p>
* <p>This operation requires permissions to perform the
* <code>kinesisanalytics:ListApplications</code> action.</p>
*/
public listApplications(
args: ListApplicationsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListApplicationsCommandOutput>;
public listApplications(
args: ListApplicationsCommandInput,
cb: (err: any, data?: ListApplicationsCommandOutput) => void
): void;
public listApplications(
args: ListApplicationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListApplicationsCommandOutput) => void
): void;
public listApplications(
args: ListApplicationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListApplicationsCommandOutput) => void),
cb?: (err: any, data?: ListApplicationsCommandOutput) => void
): Promise<ListApplicationsCommandOutput> | void {
const command = new ListApplicationsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the list of key-value tags assigned to the application. For more information, see <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-tagging.html">Using Tagging</a>.</p>
*/
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTagsForResourceCommandOutput>;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void),
cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void
): Promise<ListTagsForResourceCommandOutput> | void {
const command = new ListTagsForResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Starts the specified Amazon Kinesis Analytics application. After creating an application, you must exclusively call this operation to start your application.</p>
* <p>After the application starts, it begins consuming the input data, processes it, and writes the output to the configured destination.</p>
* <p>
* The application status must be <code>READY</code> for you to start an application. You can
* get the application status in the console or using the <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_DescribeApplication.html">DescribeApplication</a> operation.</p>
* <p>After you start the application, you can stop the application from processing
* the input by calling the <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_StopApplication.html">StopApplication</a> operation.</p>
* <p>This operation requires permissions to perform the
* <code>kinesisanalytics:StartApplication</code> action.</p>
*/
public startApplication(
args: StartApplicationCommandInput,
options?: __HttpHandlerOptions
): Promise<StartApplicationCommandOutput>;
public startApplication(
args: StartApplicationCommandInput,
cb: (err: any, data?: StartApplicationCommandOutput) => void
): void;
public startApplication(
args: StartApplicationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: StartApplicationCommandOutput) => void
): void;
public startApplication(
args: StartApplicationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartApplicationCommandOutput) => void),
cb?: (err: any, data?: StartApplicationCommandOutput) => void
): Promise<StartApplicationCommandOutput> | void {
const command = new StartApplicationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Stops the application from processing input data. You can stop
* an application only if it is in the running state.
* You can use the <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/API_DescribeApplication.html">DescribeApplication</a> operation to find the application state.
* After the application is stopped,
* Amazon Kinesis Analytics stops reading data from the input, the
* application stops processing data, and there is no output written to the destination. </p>
* <p>This operation requires permissions to perform the
* <code>kinesisanalytics:StopApplication</code> action.</p>
*/
public stopApplication(
args: StopApplicationCommandInput,
options?: __HttpHandlerOptions
): Promise<StopApplicationCommandOutput>;
public stopApplication(
args: StopApplicationCommandInput,
cb: (err: any, data?: StopApplicationCommandOutput) => void
): void;
public stopApplication(
args: StopApplicationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: StopApplicationCommandOutput) => void
): void;
public stopApplication(
args: StopApplicationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StopApplicationCommandOutput) => void),
cb?: (err: any, data?: StopApplicationCommandOutput) => void
): Promise<StopApplicationCommandOutput> | void {
const command = new StopApplicationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Adds one or more key-value tags to a Kinesis Analytics application. Note that the maximum number of application tags includes system tags. The maximum number of user-defined application tags is 50.
* For more information, see <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-tagging.html">Using Tagging</a>.</p>
*/
public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>;
public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void;
public tagResource(
args: TagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TagResourceCommandOutput) => void
): void;
public tagResource(
args: TagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void),
cb?: (err: any, data?: TagResourceCommandOutput) => void
): Promise<TagResourceCommandOutput> | void {
const command = new TagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes one or more tags from a Kinesis Analytics application. For more information, see <a href="https://docs.aws.amazon.com/kinesisanalytics/latest/dev/how-tagging.html">Using Tagging</a>.</p>
*/
public untagResource(
args: UntagResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<UntagResourceCommandOutput>;
public untagResource(
args: UntagResourceCommandInput,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void),
cb?: (err: any, data?: UntagResourceCommandOutput) => void
): Promise<UntagResourceCommandOutput> | void {
const command = new UntagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <note>
* <p>This documentation is for version 1 of the Amazon Kinesis Data Analytics API, which only supports SQL applications. Version 2 of the API supports SQL and Java applications. For more information about version 2, see <a href="/kinesisanalytics/latest/apiv2/Welcome.html">Amazon Kinesis Data Analytics API V2 Documentation</a>.</p>
* </note>
* <p>Updates an existing Amazon Kinesis Analytics application. Using this API,
* you can update application code, input configuration, and
* output configuration. </p>
* <p>Note that Amazon Kinesis Analytics updates the <code>CurrentApplicationVersionId</code>
* each time you update your application. </p>
* <p>This operation requires permission for the
* <code>kinesisanalytics:UpdateApplication</code> action.</p>
*/
public updateApplication(
args: UpdateApplicationCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateApplicationCommandOutput>;
public updateApplication(
args: UpdateApplicationCommandInput,
cb: (err: any, data?: UpdateApplicationCommandOutput) => void
): void;
public updateApplication(
args: UpdateApplicationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateApplicationCommandOutput) => void
): void;
public updateApplication(
args: UpdateApplicationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateApplicationCommandOutput) => void),
cb?: (err: any, data?: UpdateApplicationCommandOutput) => void
): Promise<UpdateApplicationCommandOutput> | void {
const command = new UpdateApplicationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
} | the_stack |
import * as svgson from 'svgson';
import { SVGPathData } from 'svg-pathdata';
import Frame from '../models/Base/Frame';
import ShapePath from '../models/Layer/ShapePath';
import ShapeGroup from '../models/Layer/ShapeGroup';
import Ellipse from '../models/Layer/Ellipse';
import Rectangle from '../models/Layer/Rectangle';
import Group from '../models/Layer/Group';
import Text from '../models/Layer/Text';
import Style from '../models/Style/Style';
import TextStyle from '../models/Style/TextStyle';
import Gradient from '../models/Style/Gradient';
import Fill from '../models/Style/Fill';
import Color from '../models/Style/Color';
import { transformStrToMatrix } from '../utils/matrix';
import {
SketchFormat,
AnyLayer,
FrameType,
ShapeGroupType,
SvgDefsStyle,
SvgLayerType,
} from '../types';
/**
* 计算 Frame 的缩放比例
*/
export const calcFrameScale = (
originFrame: FrameType,
targetFrame: FrameType,
) => {
const targetAspectRatio = targetFrame.width / targetFrame.height;
const originAspectRatio = originFrame.width / originFrame.height;
// 确定缩放比例
// 如果目标长宽比大于自身的
// scale 是高度比
let scale = targetFrame.height / originFrame.height;
// 否则是 scale 是长度比
if (targetAspectRatio < originAspectRatio) {
scale = targetFrame.width / originFrame.width;
}
return scale;
};
/**
* 一致化缠绕规则参数
* @param ruleStr
*/
export const normalizeWindingRule = (ruleStr?: string) => {
const rule = ruleStr?.toLowerCase();
if (rule && ['nonzero', 'nozero', 'non-zero', 'no-zero'].includes(rule)) {
return SketchFormat.WindingRule.NonZero;
}
return SketchFormat.WindingRule.EvenOdd;
};
/**
* 获取 svgPath 的内部定界框
* @param svgPath svg 的path路径
*/
export const getSvgPathGroupFrame = (svgPath: string) => {
const shapeGroup = new SVGPathData(svgPath);
const bounds = shapeGroup.getBounds();
return {
width: bounds.maxX - bounds.minX,
height: bounds.maxY - bounds.minY,
x: bounds.minX,
y: bounds.minY,
};
};
/**
* 将 Path 转为贝赛尔曲线
* @param svgPath 路径
*/
export const pathToShapeGroup = (svgPath: string): ShapeGroupType => {
// ------ 第一步: 获取有效的 Path 数组 ---------- //
// 将 多个 svg 通过 M 符号进行分割
const pathStr = svgPath.split(/([Mm])/).filter((s) => s);
if (pathStr.length % 2 !== 0) {
throw Error(
`Error Path!\nData:${svgPath}\nPlease check whether the path is correct.`,
);
}
const paths = [];
for (let i = 0; i < pathStr.length; i += 2) {
const p = pathStr[i] + pathStr[i + 1];
paths.push(p.trim());
}
// ------ 第二步: 获取这组Path的 frame ---------- //
// 获取 shapeGroup 的 frame
const groupFrame = getSvgPathGroupFrame(svgPath);
// 解析每个路径中的shape
const shapes = paths.map(ShapePath.svgPathToShapePath).filter((shape) => {
// 需要对 shape 进行清理,如果只有两个点,起点和终点,直接过滤
for (let i = 0; i < shape.points.length; i += 1) {
const point = shape.points[i];
if (isNaN(point.x) || isNaN(point.y)) {
return false;
}
}
return true;
});
return {
shapes,
frame: groupFrame,
};
};
/**
* SVG 对象
*/
export class Svgson {
constructor(
svgString: string,
{ width, height }: Partial<Pick<FrameType, 'width' | 'height'>>,
) {
if (!svgString) return;
// --------- 处理 Svg String 变成 Svg Shape ---------- //
let result = svgson.parseSync(svgString, { camelcase: true });
// 排除一下 svg 的循环嵌套的问题
while (result.children.length === 1 && result.children[0].name === 'svg') {
[result] = result.children;
}
const { children, attributes } = result;
if (!children) return;
const { viewBox } = attributes;
// 如果有 viewBox 则使用 viewBox 的视野
// 否则用默认长宽高
if (viewBox) {
// 解析获得 viewBox 值
const [viewX, viewY, viewWidth, viewHeight] = viewBox
.split(' ')
.map(parseFloat);
this.viewBox = new Frame({
x: viewX || 0,
height: viewHeight || height,
width: viewWidth || width,
y: viewY || 0,
});
this.aspectRatio = calcFrameScale(this.viewBox.toJSON(), {
height: height || viewHeight,
width: width || viewWidth,
x: 0,
y: 0,
});
} else {
this.viewBox = new Frame({
x: 0,
y: 0,
height,
width,
});
}
// 添加 mask
const background = new Rectangle(this.viewBox.toJSON());
background.name = '容器';
background.hasClippingMask = true;
// ------ 将 svgson 的子节点转换成子图层 ------ //
this.layers = children
// .map((child) => {
// return this.extendsParentAttr(child, attributes);
// })
.map(this.parseSvgson)
.filter((c) => c) as [];
this.layers.unshift(background);
// 根据 viewBox 进行相应的偏移
this.layers.forEach((layer) => {
layer.frame.offset(-this.viewBox.x, -this.viewBox.y);
});
// 对内部每个图层都进行坐标变换 //
this.layers.forEach(this.scaleLayersToFrame);
}
/**
* 缩放比例
*/
aspectRatio: number = 1;
/**
* svg 的 ViewBox
*/
viewBox = new Frame();
/**
* Svg 包含的图层对象
* 每一个对象都是 SvgLayer 类型
*/
layers: AnyLayer[] = [];
/**
* 全局描述
* @private
*/
defs: (Gradient | SvgDefsStyle)[] = [];
static init(): Svgson {
return new Svgson('', {});
}
/**
* 将图层
*/
scaleLayersToFrame = (layer: AnyLayer) => {
layer.frame.scale(this.aspectRatio);
if (layer.class === 'text') {
(layer as Text).textStyle.fontSize *= this.aspectRatio;
}
if (layer.layers.length > 0) {
layer.layers.forEach(this.scaleLayersToFrame);
}
};
// ---------- Svgson 解析方法群 ---------- //
// ------------------------------------- //
/**
* 解析 Svgson 变成 layer
* @param node
*/
parseSvgson = (node: svgson.INode): SvgLayerType => {
switch (node.name) {
// 全局定义
case 'defs':
this.defs = node.children.map(Svgson.parseSvgDefs) as [];
break;
// 编组
case 'g':
return this.parseNodeToGroup(node);
// 蒙版 编组
// case 'mask':
// return this.parseNodeToGroup(node, true);
// 路径
case 'path':
return this.parseSvgsonPathToShape(node);
// 椭圆
case 'ellipse':
return this.parseNodeToEllipse(node);
// 圆形
case 'circle':
return this.parseNodeToCircle(node);
// 矩形
case 'rect':
return this.parseNodeToRectangle(node);
// 多边形
case 'polygon':
// return Svg.parseNodeToPolygon(node);
break;
// 文本
case 'text':
return this.parseNodeToText(node);
case 'svg':
return node.children.map(this.parseSvgson);
default:
console.log(node);
}
};
/**
* 将节点解析为 pathShape
* @param node
*/
parseSvgsonPathToShape(node: svgson.INode) {
const { attributes, name } = node;
// 如果没有对象的话 就直接结束
if (name !== 'path') return;
// ------ 进行统一的坐标和尺寸变换 -------- //
const path = new SVGPathData(attributes.d).toAbs().encode();
const shapeGroupType = pathToShapeGroup(path);
const shapePaths = this.shapeGroupDataToLayers(shapeGroupType);
if (shapePaths.length === 1) {
const shapePath = shapePaths[0];
shapePath.style = this.parseNodeAttrToStyle(node.attributes);
}
const shapeGroup = new ShapeGroup(shapeGroupType.frame);
shapeGroup.addLayers(shapePaths);
shapeGroup.style = this.parseNodeAttrToStyle(node.attributes);
return shapeGroup;
}
/**
* 将 svg 的 Defs 解析成相应的对象
* @param defsNode
*/
static parseSvgDefs(defsNode: svgson.INode) {
const { attributes, name, children } = defsNode;
switch (name) {
case 'linearGradient':
return new Gradient({
name: attributes.id,
from: {
// 解析得到的是 109% 这样的值
x: parseFloat(attributes.x1) / 100,
y: parseFloat(attributes.y1) / 100,
},
to: {
x: parseFloat(attributes.x2) / 100,
y: parseFloat(attributes.y2) / 100,
},
stops: defsNode.children.map((item) => {
const { offset, stopColor, stopOpacity } = item.attributes;
const color = new Color(stopColor);
return {
color: [
color.red,
color.green,
color.blue,
Number(stopOpacity) || 1,
],
offset: parseFloat(offset) / 100,
};
}),
});
case 'radialGradient':
return new Gradient({
type: SketchFormat.GradientType.Radial,
name: attributes.id,
from: {
// 解析得到的是 109% 这样的值
x: parseFloat(attributes.fx) / 100,
y: parseFloat(attributes.fy) / 100,
},
to: {
x: (parseFloat(attributes.cx) + parseFloat(attributes.r)) / 100,
y: parseFloat(attributes.cy) / 100,
},
// radius: parseFloat(attributes.r) / 100,
stops: defsNode.children.map((item) => {
const { offset, stopColor, stopOpacity } = item.attributes;
const color = new Color(stopColor);
const opacity = Number(stopOpacity);
return {
color: [
color.red,
color.green,
color.blue,
isNaN(opacity) ? 1 : opacity,
],
offset: parseFloat(offset) / 100,
};
}),
});
case 'style':
// eslint-disable-next-line no-case-declarations
const style = children?.[0]?.value;
if (!style) return;
// eslint-disable-next-line no-case-declarations
const rules = Style.parseClassStyle(style);
return { class: 'classStyle', rules };
default:
}
}
/**
* 解析 Node 的 Attribute 变成 style
* @param attributes node 的属性
*/
parseNodeAttrToStyle = (attributes: svgson.INode['attributes']) => {
const {
stroke,
strokeWidth,
strokeDasharray,
fill: fillStr,
style: styleString,
class: className,
opacity,
} = attributes;
const style = new Style();
const styleObj = Style.parseStyleString(styleString);
// 获得具体的 class 规则
const rule = this.getCssRuleByClassName(className);
if (rule) {
const { styles } = rule;
// 处理 fill
if (styles.fill) {
const fill = this.getFillByString(styles.fill);
if (fill) style.fills.push(fill);
}
}
const baseFill = this.getFillByString(fillStr);
if (baseFill) style.fills.push(baseFill);
// 如果存在currentColor 则采用 inline Style 的 fill
if (fillStr === 'currentColor' && styleObj?.fill) {
style.addColorFill(styleObj.fill);
}
if (stroke && stroke !== 'none') {
style.addBorder({
thickness: parseFloat(strokeWidth || '1'),
color: stroke,
position: SketchFormat.BorderPosition.Center,
});
// 如果存在 dash array
if (strokeDasharray) {
const dashArr = strokeDasharray.split(',').map(parseFloat);
if (dashArr.length > 0) {
style.sketchBorderOptions.dashPattern = dashArr;
}
}
}
// 设置不透明度
style.opacity = Number(opacity) || 1;
return style;
};
/**
* 解析 Node 的 Attribute 变成 textStyle
* @param attributes node 的属性
*/
parseNodeAttrToTextStyle = (attributes: svgson.INode['attributes']) => {
const {
fontSize,
lineHeight,
class: className,
style: styleString,
} = attributes;
const style = new TextStyle({
fontSize: parseFloat(fontSize) || 14,
lineHeight: parseFloat(lineHeight) || 22,
});
const styleObj = Style.parseStyleString(styleString);
if (styleObj) {
// console.log(styleObj);
}
const rule = this.getCssRuleByClassName(className);
// 获得具体的规则
if (rule) {
const { styles } = rule;
if (styles.fill) {
style.color = new Color(styles.fill);
}
if (styles.fontSize) {
style.fontSize = parseFloat(styles.fontSize);
}
if (styles.lineHeight) {
style.lineHeight = parseFloat(styles.lineHeight);
}
}
return style;
};
/**
* 将 g 节点解析为 Group
* @param node
* @param isMask 是否使用剪切蒙版
*/
parseNodeToGroup = (node: svgson.INode, isMask: boolean = false): Group => {
const group = new Group();
const { transform, fill } = node.attributes;
const layers = node.children
.map((child) => {
this.extendsParentAttr(child, { fill });
return this.parseSvgson(child);
})
.filter((c) => c);
if (layers && layers.length > 0) {
group.addLayers(layers as []);
}
const { height, width } = group.getSize();
group.height = height;
group.width = width;
group.name = isMask ? '蒙版' : '编组';
group.hasClippingMask = isMask;
this.applyTransformString(group.frame, transform);
// TODO 确认缠绕规则
// const { fillRule } = node.attributes;
// group.windingRule = normalizeWindingRule(fillRule);
return group;
};
/**
* 将 ellipse 的节点解析为椭圆
* @param node
*/
parseNodeToEllipse(node: svgson.INode): Ellipse | undefined {
if (!node || (node && node.name !== 'ellipse')) return;
const { rx, ry, cx, cy, transform } = node.attributes;
const style = this.parseNodeAttrToStyle(node.attributes);
const ellipse = new Ellipse({
cx: parseFloat(cx),
cy: parseFloat(cy),
rx: parseFloat(rx),
ry: parseFloat(ry),
});
ellipse.name = '椭圆';
ellipse.style = style;
this.applyTransformString(ellipse.frame, transform);
return ellipse;
}
/**
* 将 ellipse 的节点解析为圆
* @param node
*/
parseNodeToCircle(node: svgson.INode): Ellipse | undefined {
if (!node || (node && node.name !== 'circle')) return;
const { r, cx, cy, transform } = node.attributes;
const style = this.parseNodeAttrToStyle(node.attributes);
const ellipse = new Ellipse({
cx: parseFloat(cx),
cy: parseFloat(cy),
rx: parseFloat(r),
ry: parseFloat(r),
});
ellipse.style = style;
this.applyTransformString(ellipse.frame, transform);
return ellipse;
}
/**
* 将 ellipse 的节点解析为矩形
* @param node
*/
parseNodeToRectangle(node: svgson.INode) {
const { name, attributes } = node;
if (name !== 'rect') return;
const { x, y, width, height, rx, transform } = attributes;
const style = this.parseNodeAttrToStyle(attributes);
const rect = new Rectangle({
cornerRadius: parseFloat(rx),
width: parseFloat(width),
height: parseFloat(height),
x: parseFloat(x),
y: parseFloat(y),
});
rect.style = style;
this.applyTransformString(rect.frame, transform);
return rect;
}
/**
* 将 text 的节点解析为文本
* @param node
*/
parseNodeToText(node: svgson.INode): Text | undefined {
const { name, attributes, children } = node;
if (name !== 'text') return;
const { transform } = attributes;
const style = this.parseNodeAttrToTextStyle(attributes);
const text = new Text({
width: 0,
height: 0,
x: 0,
y: 0,
text: children?.[0]?.value,
});
text.textStyle = style;
this.applyTransformString(text.frame, transform);
return text;
}
/**
* ShapeGroup 转子图层方法
* @param shapeGroup
*/
shapeGroupDataToLayers = (shapeGroup: ShapeGroupType) => {
const { shapes } = shapeGroup;
return shapes.map((shape) => {
const { points, isClose, frame } = shape;
return new ShapePath({
points,
isClose,
width: frame.width,
height: frame.height,
// 需要计算与 innerFrame 的相对坐标
// https://www.yuque.com/design-engineering/sketch-dev/hsbz8m#OPWbw
x: frame.x,
y: frame.y,
});
});
};
/**
* 从 Defs 中获取样式表
* @param className
*/
private getCssRuleByClassName = (className: string | undefined) => {
if (!className) return;
// 拿到样式表
const classStyle = this.defs.find(
(d) => d.class === 'classStyle',
) as SvgDefsStyle;
// 获得具体的规则
return classStyle?.rules.find((r) => r.className === `.${className}`);
};
/**
* 根据 fill 字符填充 Fill 对象
* @param fill 填充文本
*/
private getFillByString = (fill: string) => {
if (fill === 'none') return;
// TODO 针对 path 类型的对象 如果没有 fill 不能默认填充黑色
if (!fill) {
return new Fill({ type: SketchFormat.FillType.Color, color: '#000' });
}
if (fill.startsWith('url')) {
// 说明来自 defs
const id = /url\(#(.*)\)/.exec(fill)?.[1];
// 从 defs 中拿到相应的配置项
const defsFill = this.defs.find(
(def) => def?.class === 'gradient' && def.name === id,
);
switch (defsFill?.class) {
case 'gradient':
// eslint-disable-next-line no-case-declarations
const newFill = new Fill({});
newFill.type = SketchFormat.FillType.Gradient;
newFill.gradient = defsFill;
return newFill;
default:
}
} else {
return new Fill({
type: SketchFormat.FillType.Color,
color: fill,
});
}
};
/**
* 应用变换字符串
* @param frame
* @param transform
*/
applyTransformString = (frame: Frame, transform?: string) => {
if (transform) {
try {
const matrix = transformStrToMatrix(transform);
frame.applyMatrix(matrix);
} catch (e) {
console.error(e);
}
}
};
/**
* 继承父级的参数
* @param node 需要继承的节点
* @param parentAttr
*/
extendsParentAttr = (
node: svgson.INode,
parentAttr?: svgson.INode['attributes'],
) => {
if (!parentAttr) return node;
// if (node.children.length > 0) {
// node.children.forEach((child) => {
// this.extendsParentAttr(child, node.attributes);
// });
// }
node.attributes = { ...parentAttr, ...node.attributes };
return node;
};
} | the_stack |
import earcut from 'earcut';
// For Web Mercator projection
const PI_4 = Math.PI / 4;
const DEGREES_TO_RADIANS_HALF = Math.PI / 360;
// 4 data formats are supported:
// Simple Polygon: an array of points
// Complex Polygon: an array of array of points (array of rings)
// with the first ring representing the outer hull and other rings representing holes
// Simple Flat: an array of numbers (flattened "simple polygon")
// Complex Flat: {position: array<number>, holeIndices: array<number>}
// (flattened "complex polygon")
/**
* Counts the number of vertices in any polygon representation.
* @param {Array|Object} polygon
* @param positionSize - size of a position, 2 (xy) or 3 (xyz)
* @returns vertex count
*/
export function getVertexCount(
polygon: any,
positionSize: number,
normalization: boolean = true
): number {
if (!normalization) {
polygon = polygon.positions || polygon;
return polygon.length / positionSize;
}
validate(polygon);
if (polygon.positions) {
// complex flat
const {positions, holeIndices} = polygon;
if (holeIndices) {
let vertexCount = 0;
// split the positions array into `holeIndices.length + 1` rings
// holeIndices[-1] falls back to 0
// holeIndices[holeIndices.length] falls back to positions.length
for (let i = 0; i <= holeIndices.length; i++) {
vertexCount += getFlatVertexCount(
polygon.positions,
positionSize,
holeIndices[i - 1],
holeIndices[i]
);
}
return vertexCount;
}
polygon = positions;
}
if (Number.isFinite(polygon[0])) {
// simple flat
return getFlatVertexCount(polygon, positionSize);
}
if (!isSimple(polygon)) {
// complex polygon
let vertexCount = 0;
for (const simplePolygon of polygon) {
vertexCount += getNestedVertexCount(simplePolygon);
}
return vertexCount;
}
// simple polygon
return getNestedVertexCount(polygon);
}
/**
* Normalize any polygon representation into the "complex flat" format
* @param {Array|Object} polygon
* @param positionSize - size of a position, 2 (xy) or 3 (xyz)
* @param [vertexCount] - pre-computed vertex count in the polygon.
* If provided, will skip counting.
* @return {Object} - {positions: <Float64Array>, holeIndices: <Array|null>}
*/
/* eslint-disable max-statements */
export function normalize(polygon, positionSize: number, vertexCount?: number): {
positions: Float64Array,
holeIndices
} {
validate(polygon);
vertexCount = vertexCount || getVertexCount(polygon, positionSize);
const positions = new Float64Array(vertexCount * positionSize);
const holeIndices = [];
if (polygon.positions) {
// complex flat
const {positions: srcPositions, holeIndices: srcHoleIndices} = polygon;
if (srcHoleIndices) {
let targetIndex = 0;
// split the positions array into `holeIndices.length + 1` rings
// holeIndices[-1] falls back to 0
// holeIndices[holeIndices.length] falls back to positions.length
for (let i = 0; i <= srcHoleIndices.length; i++) {
targetIndex = copyFlatRing(
positions,
targetIndex,
srcPositions,
positionSize,
srcHoleIndices[i - 1],
srcHoleIndices[i]
);
holeIndices.push(targetIndex);
}
// The last one is not a starting index of a hole, remove
holeIndices.pop();
return {positions, holeIndices};
}
polygon = srcPositions;
}
if (Number.isFinite(polygon[0])) {
// simple flat
copyFlatRing(positions, 0, polygon, positionSize);
return positions;
}
if (!isSimple(polygon)) {
// complex polygon
let targetIndex = 0;
for (const simplePolygon of polygon) {
targetIndex = copyNestedRing(positions, targetIndex, simplePolygon, positionSize);
holeIndices.push(targetIndex);
}
// The last one is not a starting index of a hole, remove
holeIndices.pop();
// last index points to the end of the array, remove it
return {positions, holeIndices};
}
// simple polygon
copyNestedRing(positions, 0, polygon, positionSize);
return positions;
}
/*
* Get vertex indices for drawing polygon mesh
* @param {Object} normalizedPolygon - {positions, holeIndices}
* @param positionSize - size of a position, 2 (xy) or 3 (xyz)
* @returns {Array} array of indices
*/
export function getSurfaceIndices(normalizedPolygon, positionSize: number, preproject: boolean) {
let holeIndices = null;
if (normalizedPolygon.holeIndices) {
holeIndices = normalizedPolygon.holeIndices.map(
(positionIndex) => positionIndex / positionSize
);
}
let positions = normalizedPolygon.positions || normalizedPolygon;
// TODO - handle other coordinate systems and projection modes
if (preproject) {
// When tesselating lnglat coordinates, project them to the Web Mercator plane for accuracy
const n = positions.length;
// Clone the array
positions = positions.slice();
for (let i = 0; i < n; i += positionSize) {
// project points to a scaled version of the web-mercator plane
// It doesn't matter if x and y are scaled/translated, but the relationship must be linear
const y = positions[i + 1];
positions[i + 1] = Math.log(Math.tan(PI_4 + y * DEGREES_TO_RADIANS_HALF));
}
}
// Let earcut triangulate the polygon
return earcut(positions, holeIndices, positionSize);
}
/**
* Ensure a polygon is valid format
* @param {Array|Object} polygon
*/
function validate(polygon): void {
polygon = (polygon && polygon.positions) || polygon;
if (!Array.isArray(polygon) && !ArrayBuffer.isView(polygon)) {
throw new Error('invalid polygon');
}
}
/**
* Check if a polygon is simple or complex
* @param {Array} polygon - either a complex or simple polygon
* @return - true if the polygon is a simple polygon (i.e. not an array of polygons)
*/
function isSimple(polygon): boolean {
return polygon.length >= 1 && polygon[0].length >= 2 && Number.isFinite(polygon[0][0]);
}
/**
* Check if a simple polygon is a closed ring
* @param {Array} simplePolygon - array of points
* @return - true if the simple polygon is a closed ring
*/
function isNestedRingClosed(simplePolygon): boolean {
// check if first and last vertex are the same
const p0 = simplePolygon[0];
const p1 = simplePolygon[simplePolygon.length - 1];
return p0[0] === p1[0] && p0[1] === p1[1] && p0[2] === p1[2];
}
/**
* Check if a simple flat array is a closed ring
* @param {Array} positions - array of numbers
* @param size - size of a position, 2 (xy) or 3 (xyz)
* @param startIndex - start index of the path in the positions array
* @param endIndex - end index of the path in the positions array
* @return - true if the simple flat array is a closed ring
*/
function isFlatRingClosed(positions, size: number, startIndex: number, endIndex: number): boolean {
for (let i = 0; i < size; i++) {
if (positions[startIndex + i] !== positions[endIndex - size + i]) {
return false;
}
}
return true;
}
/**
* Copy a simple polygon coordinates into a flat array, closes the ring if needed.
* @param starget - destination
* @param targetStartIndex - index in the destination to start copying into
* @param {Array} simplePolygon - array of points
* @param size - size of a position, 2 (xy) or 3 (xyz)
* @returns - the index of the write head in the destination
*/
function copyNestedRing(target: Float64Array, targetStartIndex: number, simplePolygon, size: number): number {
let targetIndex = targetStartIndex;
const len = simplePolygon.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < size; j++) {
target[targetIndex++] = simplePolygon[i][j] || 0;
}
}
if (!isNestedRingClosed(simplePolygon)) {
for (let j = 0; j < size; j++) {
target[targetIndex++] = simplePolygon[0][j] || 0;
}
}
return targetIndex;
}
/**
* Copy a simple flat array into another flat array, closes the ring if needed.
* @param target - destination
* @param targetStartIndex - index in the destination to start copying into
* @param {Array} positions - array of numbers
* @param size - size of a position, 2 (xy) or 3 (xyz)
* @param [srcStartIndex] - start index of the path in the positions array
* @param [srcEndIndex] - end index of the path in the positions array
* @returns - the index of the write head in the destination
*/
function copyFlatRing(
target: Float64Array,
targetStartIndex: number,
positions,
size: number,
srcStartIndex: number = 0,
srcEndIndex?: number
): number {
srcEndIndex = srcEndIndex || positions.length;
const srcLength = srcEndIndex - srcStartIndex;
if (srcLength <= 0) {
return targetStartIndex;
}
let targetIndex = targetStartIndex;
for (let i = 0; i < srcLength; i++) {
target[targetIndex++] = positions[srcStartIndex + i];
}
if (!isFlatRingClosed(positions, size, srcStartIndex, srcEndIndex)) {
for (let i = 0; i < size; i++) {
target[targetIndex++] = positions[srcStartIndex + i];
}
}
return targetIndex;
}
/**
* Counts the number of vertices in a simple polygon, closes the polygon if needed.
* @param {Array} simplePolygon - array of points
* @returns vertex count
*/
function getNestedVertexCount(simplePolygon): number {
return (isNestedRingClosed(simplePolygon) ? 0 : 1) + simplePolygon.length;
}
/**
* Counts the number of vertices in a simple flat array, closes the polygon if needed.
* @param {Array} positions - array of numbers
* @param size - size of a position, 2 (xy) or 3 (xyz)
* @param [startIndex] - start index of the path in the positions array
* @param [endIndex] - end index of the path in the positions array
* @returns vertex count
*/
function getFlatVertexCount(
positions,
size: number,
startIndex: number = 0,
endIndex?: number
): number {
endIndex = endIndex || positions.length;
if (startIndex >= endIndex) {
return 0;
}
return (
(isFlatRingClosed(positions, size, startIndex, endIndex) ? 0 : 1) +
(endIndex - startIndex) / size
);
} | the_stack |
import {MDCFoundation} from '@material/base/foundation';
import {MDCRippleAdapter} from './adapter';
import {cssClasses, numbers, strings} from './constants';
import {MDCRipplePoint} from './types';
import {getNormalizedEventCoords} from './util';
interface ActivationStateType {
isActivated?: boolean;
hasDeactivationUXRun?: boolean;
wasActivatedByPointer?: boolean;
wasElementMadeActive?: boolean;
activationEvent?: Event;
isProgrammatic?: boolean;
}
interface FgTranslationCoordinates {
startPoint: MDCRipplePoint;
endPoint: MDCRipplePoint;
}
interface Coordinates {
left: number;
top: number;
}
interface EventHandlerNonNull {
(event: Event): any;
}
type ActivationEventType = 'touchstart' | 'pointerdown' | 'mousedown' | 'keydown';
type DeactivationEventType = 'touchend' | 'pointerup' | 'mouseup' | 'contextmenu';
// Activation events registered on the root element of each instance for activation
const ACTIVATION_EVENT_TYPES: ActivationEventType[] = [
'touchstart', 'pointerdown', 'mousedown', 'keydown',
];
// Deactivation events registered on documentElement when a pointer-related down event occurs
const POINTER_DEACTIVATION_EVENT_TYPES: DeactivationEventType[] = [
'touchend', 'pointerup', 'mouseup', 'contextmenu',
];
// simultaneous nested activations
let activatedTargets: Array<EventTarget | null> = [];
export class MDCRippleFoundation extends MDCFoundation<MDCRippleAdapter> {
static override get cssClasses() {
return cssClasses;
}
static override get strings() {
return strings;
}
static override get numbers() {
return numbers;
}
static override get defaultAdapter(): MDCRippleAdapter {
return {
addClass: () => undefined,
browserSupportsCssVars: () => true,
computeBoundingRect: () =>
({top: 0, right: 0, bottom: 0, left: 0, width: 0, height: 0} as any),
containsEventTarget: () => true,
deregisterDocumentInteractionHandler: () => undefined,
deregisterInteractionHandler: () => undefined,
deregisterResizeHandler: () => undefined,
getWindowPageOffset: () => ({x: 0, y: 0}),
isSurfaceActive: () => true,
isSurfaceDisabled: () => true,
isUnbounded: () => true,
registerDocumentInteractionHandler: () => undefined,
registerInteractionHandler: () => undefined,
registerResizeHandler: () => undefined,
removeClass: () => undefined,
updateCssVariable: () => undefined,
};
}
private activationAnimationHasEnded = false;
private activationState: ActivationStateType;
private activationTimer = 0;
private fgDeactivationRemovalTimer = 0;
private fgScale = '0';
private frame = {width: 0, height: 0};
private initialSize = 0;
private layoutFrame = 0;
private maxRadius = 0;
private unboundedCoords: Coordinates = {left: 0, top: 0};
private readonly activationTimerCallback: () => void;
private readonly activateHandler: EventHandlerNonNull;
private readonly deactivateHandler: EventHandlerNonNull;
private readonly focusHandler: EventHandlerNonNull;
private readonly blurHandler: EventHandlerNonNull;
private readonly resizeHandler: EventHandlerNonNull;
private previousActivationEvent?: Event;
constructor(adapter?: Partial<MDCRippleAdapter>) {
super({...MDCRippleFoundation.defaultAdapter, ...adapter});
this.activationState = this.defaultActivationState();
this.activationTimerCallback = () => {
this.activationAnimationHasEnded = true;
this.runDeactivationUXLogicIfReady();
};
this.activateHandler = (e) => {
this.activateImpl(e);
};
this.deactivateHandler = () => {
this.deactivateImpl();
};
this.focusHandler = () => {
this.handleFocus();
};
this.blurHandler = () => {
this.handleBlur();
};
this.resizeHandler = () => {
this.layout();
};
}
override init() {
const supportsPressRipple = this.supportsPressRipple();
this.registerRootHandlers(supportsPressRipple);
if (supportsPressRipple) {
const {ROOT, UNBOUNDED} = MDCRippleFoundation.cssClasses;
requestAnimationFrame(() => {
this.adapter.addClass(ROOT);
if (this.adapter.isUnbounded()) {
this.adapter.addClass(UNBOUNDED);
// Unbounded ripples need layout logic applied immediately to set coordinates for both shade and ripple
this.layoutInternal();
}
});
}
}
override destroy() {
if (this.supportsPressRipple()) {
if (this.activationTimer) {
clearTimeout(this.activationTimer);
this.activationTimer = 0;
this.adapter.removeClass(MDCRippleFoundation.cssClasses.FG_ACTIVATION);
}
if (this.fgDeactivationRemovalTimer) {
clearTimeout(this.fgDeactivationRemovalTimer);
this.fgDeactivationRemovalTimer = 0;
this.adapter.removeClass(
MDCRippleFoundation.cssClasses.FG_DEACTIVATION);
}
const {ROOT, UNBOUNDED} = MDCRippleFoundation.cssClasses;
requestAnimationFrame(() => {
this.adapter.removeClass(ROOT);
this.adapter.removeClass(UNBOUNDED);
this.removeCssVars();
});
}
this.deregisterRootHandlers();
this.deregisterDeactivationHandlers();
}
/**
* @param evt Optional event containing position information.
*/
activate(evt?: Event): void {
this.activateImpl(evt);
}
deactivate(): void {
this.deactivateImpl();
}
layout(): void {
if (this.layoutFrame) {
cancelAnimationFrame(this.layoutFrame);
}
this.layoutFrame = requestAnimationFrame(() => {
this.layoutInternal();
this.layoutFrame = 0;
});
}
setUnbounded(unbounded: boolean): void {
const {UNBOUNDED} = MDCRippleFoundation.cssClasses;
if (unbounded) {
this.adapter.addClass(UNBOUNDED);
} else {
this.adapter.removeClass(UNBOUNDED);
}
}
handleFocus(): void {
requestAnimationFrame(
() => this.adapter.addClass(MDCRippleFoundation.cssClasses.BG_FOCUSED));
}
handleBlur(): void {
requestAnimationFrame(
() => this.adapter.removeClass(
MDCRippleFoundation.cssClasses.BG_FOCUSED));
}
/**
* We compute this property so that we are not querying information about the client
* until the point in time where the foundation requests it. This prevents scenarios where
* client-side feature-detection may happen too early, such as when components are rendered on the server
* and then initialized at mount time on the client.
*/
private supportsPressRipple(): boolean {
return this.adapter.browserSupportsCssVars();
}
private defaultActivationState(): ActivationStateType {
return {
activationEvent: undefined,
hasDeactivationUXRun: false,
isActivated: false,
isProgrammatic: false,
wasActivatedByPointer: false,
wasElementMadeActive: false,
};
}
/**
* supportsPressRipple Passed from init to save a redundant function call
*/
private registerRootHandlers(supportsPressRipple: boolean) {
if (supportsPressRipple) {
for (const evtType of ACTIVATION_EVENT_TYPES) {
this.adapter.registerInteractionHandler(evtType, this.activateHandler);
}
if (this.adapter.isUnbounded()) {
this.adapter.registerResizeHandler(this.resizeHandler);
}
}
this.adapter.registerInteractionHandler('focus', this.focusHandler);
this.adapter.registerInteractionHandler('blur', this.blurHandler);
}
private registerDeactivationHandlers(evt: Event) {
if (evt.type === 'keydown') {
this.adapter.registerInteractionHandler('keyup', this.deactivateHandler);
} else {
for (const evtType of POINTER_DEACTIVATION_EVENT_TYPES) {
this.adapter.registerDocumentInteractionHandler(
evtType, this.deactivateHandler);
}
}
}
private deregisterRootHandlers() {
for (const evtType of ACTIVATION_EVENT_TYPES) {
this.adapter.deregisterInteractionHandler(evtType, this.activateHandler);
}
this.adapter.deregisterInteractionHandler('focus', this.focusHandler);
this.adapter.deregisterInteractionHandler('blur', this.blurHandler);
if (this.adapter.isUnbounded()) {
this.adapter.deregisterResizeHandler(this.resizeHandler);
}
}
private deregisterDeactivationHandlers() {
this.adapter.deregisterInteractionHandler('keyup', this.deactivateHandler);
for (const evtType of POINTER_DEACTIVATION_EVENT_TYPES) {
this.adapter.deregisterDocumentInteractionHandler(
evtType, this.deactivateHandler);
}
}
private removeCssVars() {
const rippleStrings = MDCRippleFoundation.strings;
const keys = Object.keys(rippleStrings) as Array<keyof typeof rippleStrings>;
keys.forEach((key) => {
if (key.indexOf('VAR_') === 0) {
this.adapter.updateCssVariable(rippleStrings[key], null);
}
});
}
private activateImpl(evt?: Event) {
if (this.adapter.isSurfaceDisabled()) {
return;
}
const activationState = this.activationState;
if (activationState.isActivated) {
return;
}
// Avoid reacting to follow-on events fired by touch device after an already-processed user interaction
const previousActivationEvent = this.previousActivationEvent;
const isSameInteraction = previousActivationEvent && evt !== undefined && previousActivationEvent.type !== evt.type;
if (isSameInteraction) {
return;
}
activationState.isActivated = true;
activationState.isProgrammatic = evt === undefined;
activationState.activationEvent = evt;
activationState.wasActivatedByPointer = activationState.isProgrammatic ? false : evt !== undefined && (
evt.type === 'mousedown' || evt.type === 'touchstart' || evt.type === 'pointerdown'
);
const hasActivatedChild = evt !== undefined &&
activatedTargets.length > 0 &&
activatedTargets.some(
(target) => this.adapter.containsEventTarget(target));
if (hasActivatedChild) {
// Immediately reset activation state, while preserving logic that prevents touch follow-on events
this.resetActivationState();
return;
}
if (evt !== undefined) {
activatedTargets.push(evt.target);
this.registerDeactivationHandlers(evt);
}
activationState.wasElementMadeActive = this.checkElementMadeActive(evt);
if (activationState.wasElementMadeActive) {
this.animateActivation();
}
requestAnimationFrame(() => {
// Reset array on next frame after the current event has had a chance to bubble to prevent ancestor ripples
activatedTargets = [];
if (!activationState.wasElementMadeActive
&& evt !== undefined
&& ((evt as KeyboardEvent).key === ' ' || (evt as KeyboardEvent).keyCode === 32)) {
// If space was pressed, try again within an rAF call to detect :active, because different UAs report
// active states inconsistently when they're called within event handling code:
// - https://bugs.chromium.org/p/chromium/issues/detail?id=635971
// - https://bugzilla.mozilla.org/show_bug.cgi?id=1293741
// We try first outside rAF to support Edge, which does not exhibit this problem, but will crash if a CSS
// variable is set within a rAF callback for a submit button interaction (#2241).
activationState.wasElementMadeActive = this.checkElementMadeActive(evt);
if (activationState.wasElementMadeActive) {
this.animateActivation();
}
}
if (!activationState.wasElementMadeActive) {
// Reset activation state immediately if element was not made active.
this.activationState = this.defaultActivationState();
}
});
}
private checkElementMadeActive(evt?: Event) {
return (evt !== undefined && evt.type === 'keydown') ?
this.adapter.isSurfaceActive() :
true;
}
private animateActivation() {
const {VAR_FG_TRANSLATE_START, VAR_FG_TRANSLATE_END} = MDCRippleFoundation.strings;
const {FG_DEACTIVATION, FG_ACTIVATION} = MDCRippleFoundation.cssClasses;
const {DEACTIVATION_TIMEOUT_MS} = MDCRippleFoundation.numbers;
this.layoutInternal();
let translateStart = '';
let translateEnd = '';
if (!this.adapter.isUnbounded()) {
const {startPoint, endPoint} = this.getFgTranslationCoordinates();
translateStart = `${startPoint.x}px, ${startPoint.y}px`;
translateEnd = `${endPoint.x}px, ${endPoint.y}px`;
}
this.adapter.updateCssVariable(VAR_FG_TRANSLATE_START, translateStart);
this.adapter.updateCssVariable(VAR_FG_TRANSLATE_END, translateEnd);
// Cancel any ongoing activation/deactivation animations
clearTimeout(this.activationTimer);
clearTimeout(this.fgDeactivationRemovalTimer);
this.rmBoundedActivationClasses();
this.adapter.removeClass(FG_DEACTIVATION);
// Force layout in order to re-trigger the animation.
this.adapter.computeBoundingRect();
this.adapter.addClass(FG_ACTIVATION);
this.activationTimer = setTimeout(() => {
this.activationTimerCallback();
}, DEACTIVATION_TIMEOUT_MS);
}
private getFgTranslationCoordinates(): FgTranslationCoordinates {
const {activationEvent, wasActivatedByPointer} = this.activationState;
let startPoint;
if (wasActivatedByPointer) {
startPoint = getNormalizedEventCoords(
activationEvent,
this.adapter.getWindowPageOffset(),
this.adapter.computeBoundingRect(),
);
} else {
startPoint = {
x: this.frame.width / 2,
y: this.frame.height / 2,
};
}
// Center the element around the start point.
startPoint = {
x: startPoint.x - (this.initialSize / 2),
y: startPoint.y - (this.initialSize / 2),
};
const endPoint = {
x: (this.frame.width / 2) - (this.initialSize / 2),
y: (this.frame.height / 2) - (this.initialSize / 2),
};
return {startPoint, endPoint};
}
private runDeactivationUXLogicIfReady() {
// This method is called both when a pointing device is released, and when the activation animation ends.
// The deactivation animation should only run after both of those occur.
const {FG_DEACTIVATION} = MDCRippleFoundation.cssClasses;
const {hasDeactivationUXRun, isActivated} = this.activationState;
const activationHasEnded = hasDeactivationUXRun || !isActivated;
if (activationHasEnded && this.activationAnimationHasEnded) {
this.rmBoundedActivationClasses();
this.adapter.addClass(FG_DEACTIVATION);
this.fgDeactivationRemovalTimer = setTimeout(() => {
this.adapter.removeClass(FG_DEACTIVATION);
}, numbers.FG_DEACTIVATION_MS);
}
}
private rmBoundedActivationClasses() {
const {FG_ACTIVATION} = MDCRippleFoundation.cssClasses;
this.adapter.removeClass(FG_ACTIVATION);
this.activationAnimationHasEnded = false;
this.adapter.computeBoundingRect();
}
private resetActivationState() {
this.previousActivationEvent = this.activationState.activationEvent;
this.activationState = this.defaultActivationState();
// Touch devices may fire additional events for the same interaction within a short time.
// Store the previous event until it's safe to assume that subsequent events are for new interactions.
setTimeout(
() => this.previousActivationEvent = undefined,
MDCRippleFoundation.numbers.TAP_DELAY_MS);
}
private deactivateImpl(): void {
const activationState = this.activationState;
// This can happen in scenarios such as when you have a keyup event that blurs the element.
if (!activationState.isActivated) {
return;
}
const state: ActivationStateType = {...activationState};
if (activationState.isProgrammatic) {
requestAnimationFrame(() => {
this.animateDeactivation(state);
});
this.resetActivationState();
} else {
this.deregisterDeactivationHandlers();
requestAnimationFrame(() => {
this.activationState.hasDeactivationUXRun = true;
this.animateDeactivation(state);
this.resetActivationState();
});
}
}
private animateDeactivation({wasActivatedByPointer, wasElementMadeActive}:
ActivationStateType) {
if (wasActivatedByPointer || wasElementMadeActive) {
this.runDeactivationUXLogicIfReady();
}
}
private layoutInternal() {
this.frame = this.adapter.computeBoundingRect();
const maxDim = Math.max(this.frame.height, this.frame.width);
// Surface diameter is treated differently for unbounded vs. bounded ripples.
// Unbounded ripple diameter is calculated smaller since the surface is expected to already be padded appropriately
// to extend the hitbox, and the ripple is expected to meet the edges of the padded hitbox (which is typically
// square). Bounded ripples, on the other hand, are fully expected to expand beyond the surface's longest diameter
// (calculated based on the diagonal plus a constant padding), and are clipped at the surface's border via
// `overflow: hidden`.
const getBoundedRadius = () => {
const hypotenuse = Math.sqrt(
Math.pow(this.frame.width, 2) + Math.pow(this.frame.height, 2));
return hypotenuse + MDCRippleFoundation.numbers.PADDING;
};
this.maxRadius = this.adapter.isUnbounded() ? maxDim : getBoundedRadius();
// Ripple is sized as a fraction of the largest dimension of the surface, then scales up using a CSS scale transform
const initialSize = Math.floor(maxDim * MDCRippleFoundation.numbers.INITIAL_ORIGIN_SCALE);
// Unbounded ripple size should always be even number to equally center align.
if (this.adapter.isUnbounded() && initialSize % 2 !== 0) {
this.initialSize = initialSize - 1;
} else {
this.initialSize = initialSize;
}
this.fgScale = `${this.maxRadius / this.initialSize}`;
this.updateLayoutCssVars();
}
private updateLayoutCssVars() {
const {
VAR_FG_SIZE, VAR_LEFT, VAR_TOP, VAR_FG_SCALE,
} = MDCRippleFoundation.strings;
this.adapter.updateCssVariable(VAR_FG_SIZE, `${this.initialSize}px`);
this.adapter.updateCssVariable(VAR_FG_SCALE, this.fgScale);
if (this.adapter.isUnbounded()) {
this.unboundedCoords = {
left: Math.round((this.frame.width / 2) - (this.initialSize / 2)),
top: Math.round((this.frame.height / 2) - (this.initialSize / 2)),
};
this.adapter.updateCssVariable(
VAR_LEFT, `${this.unboundedCoords.left}px`);
this.adapter.updateCssVariable(VAR_TOP, `${this.unboundedCoords.top}px`);
}
}
}
// tslint:disable-next-line:no-default-export Needed for backward compatibility with MDC Web v0.44.0 and earlier.
export default MDCRippleFoundation; | the_stack |
import * as React from 'react';
import { BaseWebComponent, IDataFilterValueInfo, ExtensibilityConstants, IDataFilterInfo } from '@pnp/modern-search-extensibility';
import * as ReactDOM from 'react-dom';
import { IComboBoxOption, Label, Icon, SelectableOptionMenuItemType, ComboBox, IComboBox, mergeStyles, Fabric } from 'office-ui-fabric-react';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import update from 'immutability-helper';
import styles from './FilterComboBoxComponent.module.scss';
import { FilterMulti } from './FilterMultiComponent';
import * as strings from 'CommonStrings';
import { cloneDeep, isEqual, sortBy } from '@microsoft/sp-lodash-subset';
import 'core-js/features/dom-collections';
type FilterMultiEventCallback = () => void;
const FILTER_MULTI_KEY = 'FILTER_MULTI';
export interface IFilterComboBoxProps {
/**
* If the values should show the associated count
*/
showCount?: boolean;
/**
* If the combo box should be multi select
*/
isMulti?: boolean;
/**
* The options to display in the combo box
*/
options: IComboBoxOption[];
/**
* The current theme settings
*/
themeVariant?: IReadonlyTheme;
/**
* Handler when a filter value is selected
*/
onChange: (filterValues: IDataFilterValueInfo[], forceUpdate?: boolean) => void;
/**
* Callback handlers for filter multi events
*/
onClear: FilterMultiEventCallback;
}
export interface IFilterComboBoxState {
/**
* The current values updated by the user (selected or unselected)
*/
selectedValues: IDataFilterValueInfo[];
/**
* Flag indicating values have been updated compared to default
*/
isDirty: boolean;
/**
* The input search value
*/
searchValue: string;
}
export class FilterComboBox extends React.Component<IFilterComboBoxProps, IFilterComboBoxState> {
private comboRef = React.createRef<IComboBox>();
/**
* The initial options passed to the combo box
*/
private _initialOptions: IComboBoxOption[] = [];
/**
* The initial selected values derived from initial options. We use this property to see if the control has been changed by the user.
*/
private _initialSelectedValues: IDataFilterValueInfo[] = [];
public constructor(props: IFilterComboBoxProps) {
super(props);
this.state = {
selectedValues: [],
isDirty: false,
searchValue: undefined
};
this._applyFilters = this._applyFilters.bind(this);
this._clearFilters = this._clearFilters.bind(this);
this._onRenderOption = this._onRenderOption.bind(this);
this._onChange = this._onChange.bind(this);
}
public render() {
const wrapperClassName = mergeStyles({
selectors: {
'& .ms-ComboBox': { maxWidth: '200px' }
}
});
let options = this.props.options;
if (this.state.searchValue) {
const matchExpr = new RegExp(this.state.searchValue,"i");
options = options.filter(option => {
if (option.text && matchExpr.test(option.text)) {
return true;
}
if (option.key && matchExpr.test(option.key as string)) {
return true;
}
});
}
let renderIcon: JSX.Element = null;
let renderCombo: JSX.Element = <Fabric className={wrapperClassName}>
<ComboBox
allowFreeform={true}
text={this.state.searchValue ? this.state.searchValue : this.props.options.filter(option => option.selected).map(option => option.text).join(',')}
componentRef={this.comboRef}
disabled={this.props.options.length === 0}
options={options} // This will be mutated by the combo box when values are selected/unselected
placeholder={this.props.options.length === 0 ? strings.Filters.FilterNoValuesMessage : strings.Filters.ComboBoxPlaceHolder}
onRenderOption={this._onRenderOption}
useComboBoxAsMenuWidth={true}
onPendingValueChanged={(option?: IComboBoxOption, index?: number, value?: string) => {
// A new value has been entered
if (value !== undefined) {
if (this.state.searchValue === undefined) {
// Open the combo box
this.comboRef.current.focus(true);
}
this.setState({
searchValue: value
});
}
}}
autoComplete='off'
styles={{
optionsContainerWrapper: {
overflow: 'hidden'
},
input: {
backgroundColor: 'inherit'
},
header: {
height: '100%'
}
}}
multiSelect={this.props.isMulti}
onChange={this._onChange}
/>
</Fabric>;
if ((!this.props.isMulti && this.state.selectedValues.filter(selectedValue => selectedValue.selected).length > 0) ||
this.props.isMulti && this._initialOptions.filter(option => option.selected).length > 0) {
renderIcon = <Label>
<Icon
iconName='ClearFilter'
onClick={() => {
if (!this.props.isMulti) {
const selectedValueIdx = this.state.selectedValues.map(value => { return value.value; }).indexOf(this.comboRef.current.selectedOptions[0].key as string);
if (selectedValueIdx !== -1) {
const updatedSelectedValues = update(this.state.selectedValues, { [selectedValueIdx]: { selected: { $set: false } } });
this.setState({
selectedValues: updatedSelectedValues
});
this.props.onChange(updatedSelectedValues);
}
} else {
this._clearFilters();
}
}}>
</Icon>
</Label>;
}
return <div className={styles.filterComboBox}>
{renderCombo}
{renderIcon}
</div>;
}
public componentDidMount() {
// Build the initial array of selected values
const selectedValues: IDataFilterValueInfo[] = this.props.options.map(option => {
// Convert the option to a IDataFilterValue
if (option.itemType === SelectableOptionMenuItemType.Normal && option.selected) {
return {
name: option.data.textWithoutCount,
value: option.key as string,
selected: option.selected
};
}
});
const updatedValues = update(this.state.selectedValues, { $set: selectedValues.filter(v => v) });
this.setState({
selectedValues: updatedValues
});
this._initialOptions = cloneDeep(this.props.options);
// Save the initial state wo we could compare afterwards
this._initialSelectedValues = cloneDeep(updatedValues);
}
private _onChange(event: React.FormEvent<IComboBox>, option?: IComboBoxOption, index?: number, value?: string) {
if (option) {
let updatedSelectedValues: IDataFilterValueInfo[] = [];
// Get the corresponding value in selected values and change the selected flag
const selectedValueIdx = this.state.selectedValues.map(selectedValue => { return selectedValue.value; }).indexOf(option.key as string);
// The 'selected' flag is not updated when not multi so we use the opposite as the previous value
const isSelected = this.props.isMulti ? option.selected : !option.selected;
if (selectedValueIdx !== -1) {
if (!option.selected && this.props.isMulti) {
// Don't remove the value from the selected filter values but set it as unselected
updatedSelectedValues = update(this.state.selectedValues, { [selectedValueIdx]: { selected: { $set: false } } });
} else {
updatedSelectedValues = update(this.state.selectedValues, { [selectedValueIdx]: { selected: { $set: isSelected }, name: { $set: option.data.textWithoutCount } } });
}
} else {
const dataFilterValues: IDataFilterValueInfo = {
name: option.data.textWithoutCount,
value: option.key as string,
selected: isSelected
};
updatedSelectedValues = update(this.state.selectedValues, { $push: [dataFilterValues] });
}
this.setState({
selectedValues: updatedSelectedValues,
isDirty: true,
searchValue: undefined
});
if (!this.props.isMulti) {
this.props.onChange(updatedSelectedValues);
}
}
}
/**
* Applies all selected filter values for the current filter
*/
private _applyFilters() {
this.props.onChange(this.state.selectedValues, true);
}
/**
* Clears all selected filters for the current refiner
*/
private _clearFilters() {
this.props.onClear();
}
private _onRenderOption(option: IComboBoxOption, defaultRender?: (renderProps?: IComboBoxOption) => JSX.Element) {
if (option.key === FILTER_MULTI_KEY) {
return (
<div style={{
fontWeight: 'normal',
height: '100%',
color: this.props.themeVariant.semanticColors.bodyText,
fontSize: 12
}}>
<FilterMulti
onApply={this._applyFilters}
onClear={this._clearFilters}
themeVariant={this.props.themeVariant}
applyDisabled={isEqual(sortBy(this.state.selectedValues, 'value'), sortBy(this._initialSelectedValues, 'value'))}
clearDisabled={this._initialOptions.filter(initialOption => initialOption.selected).length === 0}
/>
</div>
);
} else {
return defaultRender(option);
}
}
}
export class FilterComboBoxWebComponent extends BaseWebComponent {
public constructor() {
super();
}
public async connectedCallback() {
let props = this.resolveAttributes();
let options: IComboBoxOption[] = [];
let filterComboBox: JSX.Element = null;
// Resolve all <option> nodes in the web component inner HTML
const htmlOptions = this.querySelectorAll("option");
if (htmlOptions.length > 0) {
htmlOptions.forEach((htmlOption, key) => {
options.push({
index: key,
key: htmlOption.value,
text: props.showCount ? `${htmlOption.text} (${Number(htmlOption.getAttribute('data-count'))})` : htmlOption.text,
itemType: SelectableOptionMenuItemType.Normal,
disabled: this.toBoolean(htmlOption.getAttribute('data-disabled')),
selected: this.toBoolean(htmlOption.getAttribute('data-selected')),
data: {
textWithoutCount: htmlOption.text
},
styles: {
root: {
paddingTop: 8,
paddingBottom: 8
}
}
} as IComboBoxOption);
});
if (props.isMulti) {
options.push(
{
key: undefined,
text: undefined,
itemType: SelectableOptionMenuItemType.Divider,
},
{
key: FILTER_MULTI_KEY,
text: '',
disabled: true,
itemType: SelectableOptionMenuItemType.Header
}
);
}
}
filterComboBox = <FilterComboBox
{...props}
options={options}
onChange={((filterValues: IDataFilterValueInfo[], forceUpdate?: boolean) => {
// Bubble event through the DOM
this.dispatchEvent(new CustomEvent(ExtensibilityConstants.EVENT_FILTER_UPDATED, {
detail: {
filterName: props.filterName,
filterValues: filterValues,
instanceId: props.instanceId,
forceUpdate: forceUpdate
} as IDataFilterInfo,
bubbles: true,
cancelable: true
}));
}).bind(this)}
onClear={(() => {
// Bubble event through the DOM
this.dispatchEvent(new CustomEvent(ExtensibilityConstants.EVENT_FILTER_CLEAR_ALL, {
detail: {
filterName: props.filterName,
instanceId: props.instanceId
},
bubbles: true,
cancelable: true
}));
}).bind(this)}
/>;
ReactDOM.render(filterComboBox, this);
}
private toBoolean(value: string): boolean {
if (/^(true|false)$/.test(value)) {
return (value === 'true');
} else {
return false;
}
}
} | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class HealthLake extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: HealthLake.Types.ClientConfiguration)
config: Config & HealthLake.Types.ClientConfiguration;
/**
* Creates a Data Store that can ingest and export FHIR formatted data.
*/
createFHIRDatastore(params: HealthLake.Types.CreateFHIRDatastoreRequest, callback?: (err: AWSError, data: HealthLake.Types.CreateFHIRDatastoreResponse) => void): Request<HealthLake.Types.CreateFHIRDatastoreResponse, AWSError>;
/**
* Creates a Data Store that can ingest and export FHIR formatted data.
*/
createFHIRDatastore(callback?: (err: AWSError, data: HealthLake.Types.CreateFHIRDatastoreResponse) => void): Request<HealthLake.Types.CreateFHIRDatastoreResponse, AWSError>;
/**
* Deletes a Data Store.
*/
deleteFHIRDatastore(params: HealthLake.Types.DeleteFHIRDatastoreRequest, callback?: (err: AWSError, data: HealthLake.Types.DeleteFHIRDatastoreResponse) => void): Request<HealthLake.Types.DeleteFHIRDatastoreResponse, AWSError>;
/**
* Deletes a Data Store.
*/
deleteFHIRDatastore(callback?: (err: AWSError, data: HealthLake.Types.DeleteFHIRDatastoreResponse) => void): Request<HealthLake.Types.DeleteFHIRDatastoreResponse, AWSError>;
/**
* Gets the properties associated with the FHIR Data Store, including the Data Store ID, Data Store ARN, Data Store name, Data Store status, created at, Data Store type version, and Data Store endpoint.
*/
describeFHIRDatastore(params: HealthLake.Types.DescribeFHIRDatastoreRequest, callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRDatastoreResponse) => void): Request<HealthLake.Types.DescribeFHIRDatastoreResponse, AWSError>;
/**
* Gets the properties associated with the FHIR Data Store, including the Data Store ID, Data Store ARN, Data Store name, Data Store status, created at, Data Store type version, and Data Store endpoint.
*/
describeFHIRDatastore(callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRDatastoreResponse) => void): Request<HealthLake.Types.DescribeFHIRDatastoreResponse, AWSError>;
/**
* Displays the properties of a FHIR export job, including the ID, ARN, name, and the status of the job.
*/
describeFHIRExportJob(params: HealthLake.Types.DescribeFHIRExportJobRequest, callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRExportJobResponse) => void): Request<HealthLake.Types.DescribeFHIRExportJobResponse, AWSError>;
/**
* Displays the properties of a FHIR export job, including the ID, ARN, name, and the status of the job.
*/
describeFHIRExportJob(callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRExportJobResponse) => void): Request<HealthLake.Types.DescribeFHIRExportJobResponse, AWSError>;
/**
* Displays the properties of a FHIR import job, including the ID, ARN, name, and the status of the job.
*/
describeFHIRImportJob(params: HealthLake.Types.DescribeFHIRImportJobRequest, callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRImportJobResponse) => void): Request<HealthLake.Types.DescribeFHIRImportJobResponse, AWSError>;
/**
* Displays the properties of a FHIR import job, including the ID, ARN, name, and the status of the job.
*/
describeFHIRImportJob(callback?: (err: AWSError, data: HealthLake.Types.DescribeFHIRImportJobResponse) => void): Request<HealthLake.Types.DescribeFHIRImportJobResponse, AWSError>;
/**
* Lists all FHIR Data Stores that are in the user’s account, regardless of Data Store status.
*/
listFHIRDatastores(params: HealthLake.Types.ListFHIRDatastoresRequest, callback?: (err: AWSError, data: HealthLake.Types.ListFHIRDatastoresResponse) => void): Request<HealthLake.Types.ListFHIRDatastoresResponse, AWSError>;
/**
* Lists all FHIR Data Stores that are in the user’s account, regardless of Data Store status.
*/
listFHIRDatastores(callback?: (err: AWSError, data: HealthLake.Types.ListFHIRDatastoresResponse) => void): Request<HealthLake.Types.ListFHIRDatastoresResponse, AWSError>;
/**
* Begins a FHIR export job.
*/
startFHIRExportJob(params: HealthLake.Types.StartFHIRExportJobRequest, callback?: (err: AWSError, data: HealthLake.Types.StartFHIRExportJobResponse) => void): Request<HealthLake.Types.StartFHIRExportJobResponse, AWSError>;
/**
* Begins a FHIR export job.
*/
startFHIRExportJob(callback?: (err: AWSError, data: HealthLake.Types.StartFHIRExportJobResponse) => void): Request<HealthLake.Types.StartFHIRExportJobResponse, AWSError>;
/**
* Begins a FHIR Import job.
*/
startFHIRImportJob(params: HealthLake.Types.StartFHIRImportJobRequest, callback?: (err: AWSError, data: HealthLake.Types.StartFHIRImportJobResponse) => void): Request<HealthLake.Types.StartFHIRImportJobResponse, AWSError>;
/**
* Begins a FHIR Import job.
*/
startFHIRImportJob(callback?: (err: AWSError, data: HealthLake.Types.StartFHIRImportJobResponse) => void): Request<HealthLake.Types.StartFHIRImportJobResponse, AWSError>;
}
declare namespace HealthLake {
export type BoundedLengthString = string;
export type ClientTokenString = string;
export interface CreateFHIRDatastoreRequest {
/**
* The user generated name for the Data Store.
*/
DatastoreName?: DatastoreName;
/**
* The FHIR version of the Data Store. The only supported version is R4.
*/
DatastoreTypeVersion: FHIRVersion;
/**
* Optional parameter to preload data upon creation of the Data Store. Currently, the only supported preloaded data is synthetic data generated from Synthea.
*/
PreloadDataConfig?: PreloadDataConfig;
/**
* Optional user provided token used for ensuring idempotency.
*/
ClientToken?: ClientTokenString;
}
export interface CreateFHIRDatastoreResponse {
/**
* The AWS-generated Data Store id. This id is in the output from the initial Data Store creation call.
*/
DatastoreId: DatastoreId;
/**
* The datastore ARN is generated during the creation of the Data Store and can be found in the output from the initial Data Store creation call.
*/
DatastoreArn: DatastoreArn;
/**
* The status of the FHIR Data Store. Possible statuses are ‘CREATING’, ‘ACTIVE’, ‘DELETING’, ‘DELETED’.
*/
DatastoreStatus: DatastoreStatus;
/**
* The AWS endpoint for the created Data Store. For preview, only US-east-1 endpoints are supported.
*/
DatastoreEndpoint: BoundedLengthString;
}
export type DatastoreArn = string;
export interface DatastoreFilter {
/**
* Allows the user to filter Data Store results by name.
*/
DatastoreName?: DatastoreName;
/**
* Allows the user to filter Data Store results by status.
*/
DatastoreStatus?: DatastoreStatus;
/**
* A filter that allows the user to set cutoff dates for records. All Data Stores created before the specified date will be included in the results.
*/
CreatedBefore?: Timestamp;
/**
* A filter that allows the user to set cutoff dates for records. All Data Stores created after the specified date will be included in the results.
*/
CreatedAfter?: Timestamp;
}
export type DatastoreId = string;
export type DatastoreName = string;
export interface DatastoreProperties {
/**
* The AWS-generated ID number for the Data Store.
*/
DatastoreId: DatastoreId;
/**
* The Amazon Resource Name used in the creation of the Data Store.
*/
DatastoreArn: DatastoreArn;
/**
* The user-generated name for the Data Store.
*/
DatastoreName?: DatastoreName;
/**
* The status of the Data Store. Possible statuses are 'CREATING', 'ACTIVE', 'DELETING', or 'DELETED'.
*/
DatastoreStatus: DatastoreStatus;
/**
* The time that a Data Store was created.
*/
CreatedAt?: Timestamp;
/**
* The FHIR version. Only R4 version data is supported.
*/
DatastoreTypeVersion: FHIRVersion;
/**
* The AWS endpoint for the Data Store. Each Data Store will have it's own endpoint with Data Store ID in the endpoint URL.
*/
DatastoreEndpoint: String;
/**
* The preloaded data configuration for the Data Store. Only data preloaded from Synthea is supported.
*/
PreloadDataConfig?: PreloadDataConfig;
}
export type DatastorePropertiesList = DatastoreProperties[];
export type DatastoreStatus = "CREATING"|"ACTIVE"|"DELETING"|"DELETED"|string;
export interface DeleteFHIRDatastoreRequest {
/**
* The AWS-generated ID for the Data Store to be deleted.
*/
DatastoreId?: DatastoreId;
}
export interface DeleteFHIRDatastoreResponse {
/**
* The AWS-generated ID for the Data Store to be deleted.
*/
DatastoreId: DatastoreId;
/**
* The Amazon Resource Name (ARN) that gives Amazon HealthLake access permission.
*/
DatastoreArn: DatastoreArn;
/**
* The status of the Data Store that the user has requested to be deleted.
*/
DatastoreStatus: DatastoreStatus;
/**
* The AWS endpoint for the Data Store the user has requested to be deleted.
*/
DatastoreEndpoint: BoundedLengthString;
}
export interface DescribeFHIRDatastoreRequest {
/**
* The AWS-generated Data Store id. This is part of the ‘CreateFHIRDatastore’ output.
*/
DatastoreId?: DatastoreId;
}
export interface DescribeFHIRDatastoreResponse {
/**
* All properties associated with a Data Store, including the Data Store ID, Data Store ARN, Data Store name, Data Store status, created at, Data Store type version, and Data Store endpoint.
*/
DatastoreProperties: DatastoreProperties;
}
export interface DescribeFHIRExportJobRequest {
/**
* The AWS generated ID for the Data Store from which files are being exported from for an export job.
*/
DatastoreId: DatastoreId;
/**
* The AWS generated ID for an export job.
*/
JobId: JobId;
}
export interface DescribeFHIRExportJobResponse {
/**
* Displays the properties of the export job, including the ID, Arn, Name, and the status of the job.
*/
ExportJobProperties: ExportJobProperties;
}
export interface DescribeFHIRImportJobRequest {
/**
* The AWS-generated ID of the Data Store.
*/
DatastoreId: DatastoreId;
/**
* The AWS-generated job ID.
*/
JobId: JobId;
}
export interface DescribeFHIRImportJobResponse {
/**
* The properties of the Import job request, including the ID, ARN, name, and the status of the job.
*/
ImportJobProperties: ImportJobProperties;
}
export interface ExportJobProperties {
/**
* The AWS generated ID for an export job.
*/
JobId: JobId;
/**
* The user generated name for an export job.
*/
JobName?: JobName;
/**
* The status of a FHIR export job. Possible statuses are SUBMITTED, IN_PROGRESS, COMPLETED, or FAILED.
*/
JobStatus: JobStatus;
/**
* The time an export job was initiated.
*/
SubmitTime: Timestamp;
/**
* The time an export job completed.
*/
EndTime?: Timestamp;
/**
* The AWS generated ID for the Data Store from which files are being exported for an export job.
*/
DatastoreId: DatastoreId;
/**
* The output data configuration that was supplied when the export job was created.
*/
OutputDataConfig: OutputDataConfig;
/**
* The Amazon Resource Name used during the initiation of the job.
*/
DataAccessRoleArn?: IamRoleArn;
/**
* An explanation of any errors that may have occurred during the export job.
*/
Message?: Message;
}
export type FHIRVersion = "R4"|string;
export type IamRoleArn = string;
export interface ImportJobProperties {
/**
* The AWS-generated id number for the Import job.
*/
JobId: JobId;
/**
* The user-generated name for an Import job.
*/
JobName?: JobName;
/**
* The job status for an Import job. Possible statuses are SUBMITTED, IN_PROGRESS, COMPLETED, FAILED.
*/
JobStatus: JobStatus;
/**
* The time that the Import job was submitted for processing.
*/
SubmitTime: Timestamp;
/**
* The time that the Import job was completed.
*/
EndTime?: Timestamp;
/**
* The datastore id used when the Import job was created.
*/
DatastoreId: DatastoreId;
/**
* The input data configuration that was supplied when the Import job was created.
*/
InputDataConfig: InputDataConfig;
/**
* The Amazon Resource Name (ARN) that gives Amazon HealthLake access to your input data.
*/
DataAccessRoleArn?: IamRoleArn;
/**
* An explanation of any errors that may have occurred during the FHIR import job.
*/
Message?: Message;
}
export interface InputDataConfig {
/**
* The S3Uri is the user specified S3 location of the FHIR data to be imported into Amazon HealthLake.
*/
S3Uri?: S3Uri;
}
export type JobId = string;
export type JobName = string;
export type JobStatus = "SUBMITTED"|"IN_PROGRESS"|"COMPLETED"|"FAILED"|string;
export interface ListFHIRDatastoresRequest {
/**
* Lists all filters associated with a FHIR Data Store request.
*/
Filter?: DatastoreFilter;
/**
* Fetches the next page of Data Stores when results are paginated.
*/
NextToken?: NextToken;
/**
* The maximum number of Data Stores returned in a single page of a ListFHIRDatastoresRequest call.
*/
MaxResults?: MaxResultsInteger;
}
export interface ListFHIRDatastoresResponse {
/**
* All properties associated with the listed Data Stores.
*/
DatastorePropertiesList: DatastorePropertiesList;
/**
* Pagination token that can be used to retrieve the next page of results.
*/
NextToken?: NextToken;
}
export type MaxResultsInteger = number;
export type Message = string;
export type NextToken = string;
export interface OutputDataConfig {
/**
* The S3Uri is the user specified S3 location to which data will be exported from a FHIR Data Store.
*/
S3Uri?: S3Uri;
}
export interface PreloadDataConfig {
/**
* The type of preloaded data. Only Synthea preloaded data is supported.
*/
PreloadDataType: PreloadDataType;
}
export type PreloadDataType = "SYNTHEA"|string;
export type S3Uri = string;
export interface StartFHIRExportJobRequest {
/**
* The user generated name for an export job.
*/
JobName?: JobName;
/**
* The output data configuration that was supplied when the export job was created.
*/
OutputDataConfig: OutputDataConfig;
/**
* The AWS generated ID for the Data Store from which files are being exported for an export job.
*/
DatastoreId: DatastoreId;
/**
* The Amazon Resource Name used during the initiation of the job.
*/
DataAccessRoleArn: IamRoleArn;
/**
* An optional user provided token used for ensuring idempotency.
*/
ClientToken: ClientTokenString;
}
export interface StartFHIRExportJobResponse {
/**
* The AWS generated ID for an export job.
*/
JobId: JobId;
/**
* The status of a FHIR export job. Possible statuses are SUBMITTED, IN_PROGRESS, COMPLETED, or FAILED.
*/
JobStatus: JobStatus;
/**
* The AWS generated ID for the Data Store from which files are being exported for an export job.
*/
DatastoreId?: DatastoreId;
}
export interface StartFHIRImportJobRequest {
/**
* The name of the FHIR Import job in the StartFHIRImport job request.
*/
JobName?: JobName;
/**
* The input properties of the FHIR Import job in the StartFHIRImport job request.
*/
InputDataConfig: InputDataConfig;
/**
* The AWS-generated Data Store ID.
*/
DatastoreId: DatastoreId;
/**
* The Amazon Resource Name (ARN) that gives Amazon HealthLake access permission.
*/
DataAccessRoleArn: IamRoleArn;
/**
* Optional user provided token used for ensuring idempotency.
*/
ClientToken: ClientTokenString;
}
export interface StartFHIRImportJobResponse {
/**
* The AWS-generated job ID.
*/
JobId: JobId;
/**
* The status of an import job.
*/
JobStatus: JobStatus;
/**
* The AWS-generated Data Store ID.
*/
DatastoreId?: DatastoreId;
}
export type String = string;
export type Timestamp = Date;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2017-07-01"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the HealthLake client.
*/
export import Types = HealthLake;
}
export = HealthLake; | the_stack |
import { call, put, all, takeLatest, takeEvery } from 'redux-saga/effects'
import {
LOAD_ORGANIZATIONS,
ADD_ORGANIZATION,
EDIT_ORGANIZATION,
DELETE_ORGANIZATION,
LOAD_ORGANIZATION_DETAIL,
LOAD_ORGANIZATIONS_ROLE,
LOAD_ORGANIZATIONS_PROJECTS,
LOAD_ORGANIZATIONS_MEMBERS,
ADD_ROLE,
DELETE_ROLE,
REL_ROLE_MEMBER,
EDIT_ROLE,
SEARCH_MEMBER,
INVITE_MEMBER,
DELETE_ORGANIZATION_MEMBER,
CHANGE_MEMBER_ROLE_ORGANIZATION,
GET_REL_ROLE_MEMBER,
LOAD_PROJECT_ADMINS,
GET_VIZ_VISBILITY,
POST_VIZ_VISBILITY
} from './constants'
import {
organizationsLoaded,
loadOrganizationsFail,
organizationAdded,
addOrganizationFail,
organizationEdited,
editOrganizationFail,
organizationDeleted,
deleteOrganizationFail,
organizationDetailLoaded,
organizationsMembersLoaded,
organizationsProjectsLoaded,
organizationsRoleLoaded,
loadOrganizationsProjectsFail,
loadOrganizationsMembersFail,
loadOrganizationsRoleFail,
addRoleFail,
roleAdded,
roleDeleted,
deleteRoleFail,
roleEdited,
editRoleFail,
relRoleMemberSuccess,
relRoleMemberFail,
inviteMemberSuccess,
inviteMemberFail,
memberSearched,
searchMemberFail,
organizationMemberDeleted,
deleteOrganizationMemberFail,
organizationMemberRoleChanged,
changeOrganizationMemberRoleFail,
getRelRoleMemberSuccess,
getRelRoleMemberFail,
projectAdminLoaded,
loadProjectAdminFail
} from './actions'
import { message } from 'antd'
import request from 'utils/request'
import api from 'utils/api'
import { errorHandler } from 'utils/util'
export function* getOrganizations () {
try {
const asyncData = yield call(request, api.organizations)
const organizations = asyncData.payload
yield put(organizationsLoaded(organizations))
} catch (err) {
yield put(loadOrganizationsFail())
errorHandler(err)
}
}
export function* addOrganization (action) {
const { organization, resolve } = action.payload
try {
const asyncData = yield call(request, {
method: 'post',
url: api.organizations,
data: organization
})
const result = asyncData.payload
yield put(organizationAdded(result))
resolve()
} catch (err) {
yield put(addOrganizationFail())
errorHandler(err)
}
}
export function* editOrganization (action) {
const { organization } = action.payload
try {
yield call(request, {
method: 'put',
url: `${api.organizations}/${organization.id}`,
data: organization
})
yield put(organizationEdited(organization))
message.success('success')
} catch (err) {
yield put(editOrganizationFail())
errorHandler(err)
}
}
export function* deleteOrganization (action) {
const { id, resolve } = action.payload
try {
yield call(request, {
method: 'delete',
url: `${api.organizations}/${id}`
})
yield put(organizationDeleted(id))
resolve()
} catch (err) {
yield put(deleteOrganizationFail())
errorHandler(err)
}
}
export function* getOrganizationDetail ({ payload }) {
try {
const asyncData = yield call(request, `${api.organizations}/${payload.id}`)
const organization = asyncData.payload
yield put(organizationDetailLoaded(organization))
} catch (err) {
errorHandler(err)
}
}
export function* getOrganizationsProjects ({payload}) {
const {param: {id, keyword, pageNum, pageSize}} = payload
const requestUrl = keyword
? `${api.organizations}/${id}/projects?keyword=${keyword}&pageNum=1&pageSize=${pageSize || 10}`
: `${api.organizations}/${id}/projects/?pageNum=${pageNum || 1}&pageSize=${pageSize || 10}`
try {
const asyncData = yield call(request, {
method: 'get',
url: requestUrl
})
const organizations = asyncData.payload
yield put(organizationsProjectsLoaded(organizations))
} catch (err) {
yield put(loadOrganizationsProjectsFail())
errorHandler(err)
}
}
export function* getOrganizationsMembers ({payload}) {
const {id} = payload
try {
const asyncData = yield call(request, `${api.organizations}/${id}/members`)
yield put(organizationsMembersLoaded(asyncData.payload))
} catch (err) {
yield put(loadOrganizationsMembersFail())
errorHandler(err)
}
}
export function* getOrganizationsRole ({payload}) {
const {id} = payload
try {
const asyncData = yield call(request, `${api.organizations}/${id}/roles`)
const organizations = asyncData.payload
yield put(organizationsRoleLoaded(organizations))
} catch (err) {
yield put(loadOrganizationsRoleFail())
errorHandler(err)
}
}
export function* addRole (action) {
const { name, description, id, resolve } = action.payload
try {
const role = {name, description, orgId: id}
const asyncData = yield call(request, {
method: 'post',
url: api.roles,
data: role
})
const result = asyncData.payload
yield put(roleAdded(result))
resolve()
} catch (err) {
yield put(addRoleFail())
errorHandler(err)
}
}
export function* deleteRole (action) {
const { id, resolve } = action.payload
try {
const asyncData = yield call(request, {
method: 'delete',
url: `${api.roles}/${id}`
})
const result = asyncData.payload
yield put(roleDeleted(result))
resolve()
} catch (err) {
yield put(deleteRoleFail())
errorHandler(err)
}
}
export function* editRole (action) {
const { name, description, id, resolve } = action.payload
try {
const role = {name, description}
const asyncData = yield call(request, {
method: 'put',
url: `${api.roles}/${id}`,
data: role
})
const result = asyncData.payload
yield put(roleEdited(result))
resolve()
} catch (err) {
yield put(editRoleFail())
errorHandler(err)
}
}
export function* relRoleMember (action) {
const { id, memberIds, resolve } = action.payload
try {
const asyncData = yield call(request, {
method: 'post',
url: `${api.roles}/${id}/members`,
data: memberIds
})
const result = asyncData.payload
yield put(relRoleMemberSuccess())
resolve()
} catch (err) {
yield put(relRoleMemberFail())
errorHandler(err)
}
}
export function* getRelRoleMember (action) {
const { id, resolve } = action.payload
try {
const asyncData = yield call(request, {
method: 'get',
url: `${api.roles}/${id}/members`
})
const result = asyncData.payload
yield put(getRelRoleMemberSuccess())
resolve(result)
} catch (err) {
yield put(getRelRoleMemberFail())
errorHandler(err)
}
}
export function* searchMember ({payload}) {
const {keyword} = payload
try {
const asyncData = yield call(request, {
method: 'get',
url: `${api.user}?keyword=${keyword}`
})
const msg = asyncData && asyncData.header && asyncData.header.msg ? asyncData.header.msg : ''
const code = asyncData && asyncData.header && asyncData.header.code ? asyncData.header.code : ''
const result = asyncData.payload
yield put(memberSearched(result))
} catch (err) {
yield put(searchMemberFail())
errorHandler(err)
}
}
export function* inviteMember ({payload}) {
const {orgId, memId} = payload
try {
const asyncData = yield call(request, {
method: 'post',
url: `${api.organizations}/${orgId}/member/${memId}`,
data: {
orgId,
memId
}
})
const result = asyncData.payload
yield put(inviteMemberSuccess(result))
} catch (err) {
yield put(inviteMemberFail())
errorHandler(err)
}
}
export function* deleteOrganizationMember ({payload}) {
const {relationId, resolve} = payload
try {
const asyncData = yield call(request, {
url: `${api.organizations}/member/${relationId}`,
method: 'delete'
})
yield put(organizationMemberDeleted(relationId))
resolve()
} catch (err) {
yield put(deleteOrganizationMemberFail())
errorHandler(err)
}
}
export function* changeOrganizationMemberRole ({payload}) {
const {relationId, newRole, resolve} = payload
try {
const asyncData = yield call(request, {
url: `${api.organizations}/member/${relationId}`,
method: 'put',
data: {role: newRole}
})
const member = asyncData.payload
yield put(organizationMemberRoleChanged(relationId, member))
yield resolve()
} catch (err) {
yield put(changeOrganizationMemberRoleFail())
errorHandler(err)
}
}
export function* getProjectAdmins ({payload}) {
const { projectId } = payload
try {
const asyncData = yield call(request, `${api.projects}/${projectId}/admins`)
const results = asyncData.payload
yield put(projectAdminLoaded(results))
} catch (err) {
yield put(loadProjectAdminFail())
errorHandler(err)
}
}
export function* getVizVisbility ({payload}) {
const {roleId, projectId, resolve} = payload
try {
const asyncData = yield call(request, {
method: 'get',
url: `${api.roles}/${roleId}/project/${projectId}/viz/visibility`
})
const results = asyncData.payload
resolve(results)
} catch (err) {
errorHandler(err)
}
}
export function* postVizVisbility ({payload}) {
const {id, permission, resolve} = payload
try {
const asyncData = yield call(request, {
url: `${api.roles}/${id}/viz/visibility`,
method: 'post',
data: permission
})
const result = asyncData.payload
yield resolve(result)
} catch (err) {
errorHandler(err)
}
}
export default function* rootOrganizationSaga (): IterableIterator<any> {
yield all([
takeLatest(LOAD_ORGANIZATIONS, getOrganizations),
takeEvery(ADD_ORGANIZATION, addOrganization),
takeEvery(EDIT_ORGANIZATION, editOrganization),
takeEvery(DELETE_ORGANIZATION, deleteOrganization),
takeLatest(LOAD_ORGANIZATION_DETAIL, getOrganizationDetail as any),
takeLatest(LOAD_ORGANIZATIONS_MEMBERS, getOrganizationsMembers as any),
takeLatest(LOAD_ORGANIZATIONS_PROJECTS, getOrganizationsProjects as any),
takeLatest(LOAD_ORGANIZATIONS_ROLE, getOrganizationsRole as any),
takeEvery(ADD_ROLE, addRole),
takeEvery(DELETE_ROLE, deleteRole),
takeEvery(EDIT_ROLE, editRole),
takeEvery(REL_ROLE_MEMBER, relRoleMember),
takeEvery(GET_REL_ROLE_MEMBER, getRelRoleMember),
// takeEvery(LOAD_PROJECT_ROLES, getProjectRoles as any),
takeLatest(LOAD_PROJECT_ADMINS, getProjectAdmins as any),
takeLatest(INVITE_MEMBER, inviteMember as any),
takeLatest(SEARCH_MEMBER, searchMember as any),
takeLatest(DELETE_ORGANIZATION_MEMBER, deleteOrganizationMember as any),
takeLatest(CHANGE_MEMBER_ROLE_ORGANIZATION, changeOrganizationMemberRole as any),
takeLatest(GET_VIZ_VISBILITY, getVizVisbility as any),
takeLatest(POST_VIZ_VISBILITY, postVizVisbility as any)
])
} | the_stack |
import 'jsdom-global/register';
import React from 'react';
import { useTimer } from './useTimer';
import { act } from 'react-dom/test-utils';
import { render, fireEvent } from '@testing-library/react';
jest.useFakeTimers();
describe('Start', () => {
it('should start timer', () => {
// Given
const Component = () => {
const { time, start } = useTimer();
return (
<div>
<button onClick={start}>Start</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByRole, getByTestId } = render(<Component />);
// When
fireEvent.click(getByRole('button'));
act(() => {
jest.advanceTimersByTime(5000);
});
// Then
expect(getByTestId('time').textContent).toBe('5');
});
it('should start timer with an initial time of 10', () => {
// Given
const Component = () => {
const { time, start } = useTimer({
initialTime: 10,
});
return (
<div>
<button onClick={start}>Start</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByRole, getByTestId } = render(<Component />);
// When
fireEvent.click(getByRole('button'));
act(() => {
jest.advanceTimersByTime(5000);
});
// Then
expect(getByTestId('time').textContent).toBe('15');
});
it('should start decremental timer with an initial time of 100', () => {
// Given
const Component = () => {
const { time, start } = useTimer({
initialTime: 100,
timerType: 'DECREMENTAL',
});
return (
<div>
<button onClick={start}>Start</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByRole, getByTestId } = render(<Component />);
// When
fireEvent.click(getByRole('button'));
act(() => {
jest.advanceTimersByTime(20000);
});
// Then
expect(getByTestId('time').textContent).toBe('80');
});
it('should update time with an interval of 2000 milliseconds', () => {
// Given
const Component = () => {
const { time, start } = useTimer({
interval: 2000,
});
return (
<div>
<button onClick={start}>Start</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByRole, getByTestId } = render(<Component />);
// When
fireEvent.click(getByRole('button'));
act(() => {
jest.advanceTimersByTime(10000);
});
// Then
expect(getByTestId('time').textContent).toBe('5');
});
it('should autostart', () => {
// Given
const Component = () => {
const { time } = useTimer({
autostart: true,
});
return <p data-testid="time">{time}</p>;
};
const { getByTestId } = render(<Component />);
act(() => {
jest.advanceTimersByTime(20000);
});
// Then
expect(getByTestId('time').textContent).toBe('20');
});
});
describe('Stop', () => {
it('should stop incremental timer when time is over', () => {
// Given
const Component = () => {
const { time, start } = useTimer({
endTime: 25,
initialTime: 5,
});
return (
<div>
<button onClick={start}>Start</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByRole, getByTestId } = render(<Component />);
// When
fireEvent.click(getByRole('button'));
act(() => {
jest.advanceTimersByTime(40000);
});
// Then
expect(getByTestId('time').textContent).toBe('25');
});
it('should stop decremental timer when time is over', () => {
// Given
const Component = () => {
const { time, start } = useTimer({
endTime: 10,
initialTime: 30,
timerType: 'DECREMENTAL',
});
return (
<div>
<button onClick={start}>Start</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByRole, getByTestId } = render(<Component />);
// When
fireEvent.click(getByRole('button'));
act(() => {
jest.advanceTimersByTime(30000);
});
// Then
expect(getByTestId('time').textContent).toBe('10');
});
});
describe('Pause', () => {
it('should pause timer', () => {
// Given
const Component = () => {
const { time, start, pause } = useTimer();
return (
<div>
<button data-testid="start" onClick={start}>
Start
</button>
<button data-testid="pause" onClick={pause}>
Start
</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByTestId } = render(<Component />);
// When
fireEvent.click(getByTestId('start'));
act(() => {
jest.advanceTimersByTime(5000);
});
fireEvent.click(getByTestId('pause'));
act(() => {
jest.advanceTimersByTime(5000);
});
// Then
expect(getByTestId('time').textContent).toBe('5');
});
it('should pause timer with an end time', () => {
// Given
const Component = () => {
const { time, start, pause } = useTimer({
endTime: 5,
});
return (
<div>
<button data-testid="start" onClick={start}>
Start
</button>
<button data-testid="pause" onClick={pause}>
Start
</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByTestId } = render(<Component />);
const startButton = getByTestId('start');
const pauseButton = getByTestId('pause');
const time = getByTestId('time');
// When
fireEvent.click(startButton);
act(() => {
jest.advanceTimersByTime(3000);
});
fireEvent.click(pauseButton);
act(() => {
jest.advanceTimersByTime(5000);
});
fireEvent.click(startButton);
// Then
expect(time.textContent).toBe('3');
act(() => {
jest.advanceTimersByTime(3000);
});
expect(time.textContent).toBe('5');
});
});
describe('Reset', () => {
it('should reset timer to default initial time', () => {
// Given
const Component = () => {
const { time, start, reset } = useTimer();
return (
<div>
<button data-testid="start" onClick={start}>
Start
</button>
<button data-testid="reset" onClick={reset}>
Reset
</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByTestId } = render(<Component />);
const startButton = getByTestId('start');
const resetButton = getByTestId('reset');
const time = getByTestId('time');
// When
fireEvent.click(startButton);
act(() => {
jest.advanceTimersByTime(5000);
});
fireEvent.click(resetButton);
// Then
expect(time.textContent).toBe('0');
});
it('should reset timer to default initial time after restart', () => {
// Given
const Component = () => {
const { time, start } = useTimer({
endTime: 10,
});
return (
<div>
<button onClick={start}>Start</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByRole, getByTestId } = render(<Component />);
// When
fireEvent.click(getByRole('button'));
act(() => {
jest.advanceTimersByTime(10000);
});
fireEvent.click(getByRole('button'));
act(() => {
jest.advanceTimersByTime(5000);
});
// Then
expect(getByTestId('time').textContent).toBe('5');
});
it('should reset timer to initial time of 20', () => {
// Given
const Component = () => {
const { time, start, reset } = useTimer({
initialTime: 20,
});
return (
<div>
<button data-testid="start" onClick={start}>
Start
</button>
<button data-testid="reset" onClick={reset}>
Reset
</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByTestId } = render(<Component />);
// When
fireEvent.click(getByTestId('start'));
act(() => {
jest.advanceTimersByTime(5000);
});
fireEvent.click(getByTestId('reset'));
// Then
expect(getByTestId('time').textContent).toBe('20');
});
});
describe('Advance time', () => {
it('should advance time and add 10 to time value', () => {
// Given
const Component = () => {
const { advanceTime, time, start } = useTimer({
initialTime: 0,
});
return (
<div>
<button data-testid="start" onClick={start}>
Start
</button>
<button data-testid="advanceTime" onClick={() => advanceTime(10)}>
Advance time
</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByTestId } = render(<Component />);
// When
fireEvent.click(getByTestId('start'));
act(() => {
jest.advanceTimersByTime(5000);
});
// When
fireEvent.click(getByTestId('advanceTime'));
// Then
expect(getByTestId('time').textContent).toBe('15');
});
it('should advance time and remove 5 to time value when timer type is decremental', () => {
// Given
const Component = () => {
const { advanceTime, time, start } = useTimer({
initialTime: 30,
timerType: 'DECREMENTAL',
});
return (
<div>
<button data-testid="start" onClick={start}>
Start
</button>
<button data-testid="advanceTime" onClick={() => advanceTime(5)}>
Advance time
</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByTestId } = render(<Component />);
// When
fireEvent.click(getByTestId('start'));
act(() => {
jest.advanceTimersByTime(10000);
});
// When
fireEvent.click(getByTestId('advanceTime'));
// Then
expect(getByTestId('time').textContent).toBe('15');
});
it('should continue to update time after it has been advanced', () => {
// Given
const Component = () => {
const { advanceTime, time, start } = useTimer({
initialTime: 0,
});
return (
<div>
<button data-testid="start" onClick={start}>
Start
</button>
<button data-testid="advanceTime" onClick={() => advanceTime(50)}>
Advance time
</button>
<p data-testid="time">{time}</p>
</div>
);
};
const { getByTestId } = render(<Component />);
// When
fireEvent.click(getByTestId('start'));
act(() => {
jest.advanceTimersByTime(10000);
});
// When
fireEvent.click(getByTestId('advanceTime'));
act(() => {
jest.advanceTimersByTime(20000);
});
// Then
expect(getByTestId('time').textContent).toBe('80');
});
});
describe('State and callbacks', () => {
it('should display "RUNNING" text when timer is running', () => {
// Given
const Component = () => {
const { status, start, pause, reset } = useTimer({
initialTime: 20,
});
return (
<div>
<button data-testid="start" onClick={start}>
Start
</button>
<button data-testid="pause" onClick={pause}>
Pause
</button>
<button data-testid="reset" onClick={reset}>
Reset
</button>
<p data-testid="status">{status}</p>
</div>
);
};
const { getByTestId } = render(<Component />);
const startButton = getByTestId('start');
const pauseButton = getByTestId('pause');
const resetButton = getByTestId('reset');
const statusBlock = getByTestId('status');
// When
fireEvent.click(startButton);
// Then
expect(statusBlock.textContent).toBe('RUNNING');
// When
fireEvent.click(pauseButton);
// Then
expect(statusBlock.textContent).toBe('PAUSED');
// When
fireEvent.click(startButton);
// Then
expect(statusBlock.textContent).toBe('RUNNING');
// When
fireEvent.click(resetButton);
// Then
expect(statusBlock.textContent).toBe('STOPPED');
});
it('should call callback function when time is over', () => {
// Given
const onTimeOver = jest.fn();
const Component = () => {
const { start } = useTimer({
endTime: 30,
initialTime: 0,
onTimeOver,
});
return (
<div>
<button onClick={start}>Start</button>
</div>
);
};
const { getByRole } = render(<Component />);
// When
fireEvent.click(getByRole('button'));
act(() => {
jest.advanceTimersByTime(30000);
});
// Then
expect(onTimeOver).toHaveBeenCalled();
});
it('should call callback function when time is updated', () => {
// Given
const onTimeUpdate = jest.fn();
const Component = () => {
const { start } = useTimer({
endTime: 10,
initialTime: 0,
onTimeUpdate,
});
return (
<div>
<button onClick={start}>Start</button>
</div>
);
};
const { getByRole } = render(<Component />);
// When
fireEvent.click(getByRole('button'));
act(() => {
jest.advanceTimersByTime(10000);
});
// Then
expect(onTimeUpdate).toHaveBeenCalledTimes(11);
expect(onTimeUpdate).toHaveBeenNthCalledWith(5, 4);
expect(onTimeUpdate).toHaveBeenLastCalledWith(10);
});
}); | the_stack |
import React, { useState } from 'react';
import { Story, Meta } from '@storybook/react';
import { Button } from '@zendeskgarden/react-buttons';
import { Paragraph } from '@zendeskgarden/react-typography';
import { Modal, Header, Body, Footer, FooterItem, Close } from '@zendeskgarden/react-modals';
import { Col, Grid, Row } from '@zendeskgarden/react-grid';
export default {
title: 'Components/Modals/Modal',
component: Modal
} as Meta;
export const Default: Story = ({
isLarge,
isDanger,
isAnimated,
isCentered,
focusOnMount,
restoreFocus,
id
}) => {
const [visible, setVisible] = useState(false);
return (
<Grid>
<Row>
<Col textAlign="center">
<Button isDanger={isDanger} onClick={() => setVisible(true)}>
Open modal
</Button>
{visible && (
<Modal
id={id}
isLarge={isLarge}
isAnimated={isAnimated}
isCentered={isCentered}
focusOnMount={focusOnMount}
restoreFocus={restoreFocus}
onClose={() => setVisible(false)}
>
<Header isDanger={isDanger}>Brussels Sprout</Header>
<Body>
{isLarge ? (
<>
<Paragraph>
Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi
amaranth water spinach avocado daikon napa cabbage asparagus winter purslane
kale. Celery potato scallion desert raisin horseradish spinach carrot soko.
Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss
chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander
water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress.
Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper
artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato
quandong celery. Bunya nuts black-eyed pea prairie turnip leek lentil turnip
greens parsnip. Sea lettuce lettuce water chestnut eggplant winter purslane
fennel azuki bean earthnut pea sierra leone bologi leek soko chicory celtuce
parsley jícama. Celery quandong swiss chard chicory earthnut pea potato.
Salsify taro catsear garlic gram celery bitterleaf wattle seed collard greens
nori. Grape wattle seed kombu beetroot horseradish carrot squash brussels
sprout chard. Pea horseradish azuki bean lettuce avocado asparagus okra.
Kohlrabi radish okra azuki bean corn fava bean mustard tigernut jícama green
bean celtuce collard greens avocado quandong fennel gumbo black-eyed pea. Soko
radicchio bunya nuts gram dulse silver beet parsnip napa cabbage lotus root
sea lettuce brussels sprout cabbage. Catsear cauliflower garbanzo yarrow
salsify chicory garlic bell pepper napa cabbage lettuce tomato kale arugula
melon sierra leone bologi rutabaga tigernut.
</Paragraph>
<Paragraph>
Sea lettuce gumbo grape kale kombu cauliflower salsify kohlrabi okra sea
lettuce broccoli celery lotus root carrot winter purslane turnip greens
garlic. Jícama garlic courgette coriander radicchio plantain scallion
cauliflower fava bean desert raisin spring onion chicory bunya nuts. Sea
lettuce water spinach gram fava bean leek dandelion silver beet eggplant bush.
Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi
beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean
chickweed potato bell pepper artichoke. Nori grape silver beet broccoli kombu
beet greens fava bean potato quandong celery. Bunya nuts black-eyed pea
prairie turnip leek lentil turnip greens parsnip. Sea lettuce lettuce water
chestnut eggplant winter purslane fennel azuki bean earthnut pea sierra leone
bologi leek soko chicory celtuce parsley jícama. Celery quandong swiss chard
chicory earthnut pea potato. Salsify taro catsear garlic gram celery
bitterleaf wattle seed collard greens nori. Grape wattle seed kombu beetroot
horseradish carrot squash brussels sprout chard. Pea horseradish azuki bean
lettuce avocado asparagus okra. Kohlrabi radish okra azuki bean corn fava bean
mustard tigernut jícama green bean celtuce collard greens avocado quandong
fennel gumbo black-eyed pea. Soko radicchio bunya nuts gram dulse silver beet
parsnip napa cabbage lotus root sea lettuce brussels sprout cabbage. Catsear
cauliflower garbanzo yarrow salsify chicory garlic bell pepper napa cabbage
lettuce tomato kale arugula melon sierra leone bologi rutabaga tigernut. Sea
lettuce gumbo grape kale kombu cauliflower salsify kohlrabi okra sea lettuce
broccoli celery lotus root carrot winter purslane turnip greens garlic. Jícama
garlic courgette coriander radicchio plantain scallion cauliflower fava bean
desert raisin spring onion chicory bunya nuts. Sea lettuce water spinach gram
fava bean leek dandelion silver beet eggplant bush.
</Paragraph>
<Paragraph>
Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi
amaranth water spinach avocado daikon napa cabbage asparagus winter purslane
kale. Celery potato scallion desert raisin horseradish spinach carrot soko.
Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss
chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander
water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress.
Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper
artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato
quandong celery. Bunya nuts black-eyed pea prairie turnip leek lentil turnip
greens parsnip. Sea lettuce lettuce water chestnut eggplant winter purslane
fennel azuki bean earthnut pea sierra leone bologi leek soko chicory celtuce
parsley jícama. Celery quandong swiss chard chicory earthnut pea potato.
Salsify taro catsear garlic gram celery bitterleaf wattle seed collard greens
nori. Grape wattle seed kombu beetroot horseradish carrot squash brussels
sprout chard. Pea horseradish azuki bean lettuce avocado asparagus okra.
Kohlrabi radish okra azuki bean corn fava bean mustard tigernut jícama green
bean celtuce collard greens avocado quandong fennel gumbo black-eyed pea. Soko
radicchio bunya nuts gram dulse silver beet parsnip napa cabbage lotus root
sea lettuce brussels sprout cabbage. Catsear cauliflower garbanzo yarrow
salsify chicory garlic bell pepper napa cabbage lettuce tomato kale arugula
melon sierra leone bologi rutabaga tigernut. Sea lettuce gumbo grape kale
kombu cauliflower salsify kohlrabi okra sea lettuce broccoli celery lotus root
carrot winter purslane turnip greens garlic. Jícama garlic courgette coriander
radicchio plantain scallion cauliflower fava bean desert raisin spring onion
chicory bunya nuts. Sea lettuce water spinach gram fava bean leek dandelion
silver beet eggplant bush.
</Paragraph>
<Paragraph>
Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi
amaranth water spinach avocado daikon napa cabbage asparagus winter purslane
kale. Celery potato scallion desert raisin horseradish spinach carrot soko.
Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss
chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander
water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress.
Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper
artichoke. Nori grape silver beet broccoli kombu beet greens fava bean potato
quandong celery. Bunya nuts black-eyed pea prairie turnip leek lentil turnip
greens parsnip. Sea lettuce lettuce water chestnut eggplant winter purslane
fennel azuki bean earthnut pea sierra leone bologi leek soko chicory celtuce
parsley jícama. Celery quandong swiss chard chicory earthnut pea potato.
Salsify taro catsear garlic gram celery bitterleaf wattle seed collard greens
nori. Grape wattle seed kombu beetroot horseradish carrot squash brussels
sprout chard. Pea horseradish azuki bean lettuce avocado asparagus okra.
Kohlrabi radish okra azuki bean corn fava bean mustard tigernut jícama green
bean celtuce collard greens avocado quandong fennel gumbo black-eyed pea. Soko
radicchio bunya nuts gram dulse silver beet parsnip napa cabbage lotus root
sea lettuce brussels sprout cabbage. Catsear cauliflower garbanzo yarrow
salsify chicory garlic bell pepper napa cabbage lettuce tomato kale arugula
melon sierra leone bologi rutabaga tigernut. Sea lettuce gumbo grape kale
kombu cauliflower salsify kohlrabi okra sea lettuce broccoli celery lotus root
carrot winter purslane turnip greens garlic. Jícama garlic courgette coriander
radicchio plantain scallion cauliflower fava bean desert raisin spring onion
chicory bunya nuts. Sea lettuce water spinach gram fava bean leek dandelion
silver beet eggplant bush.
</Paragraph>
</>
) : (
<>
Soko radicchio bunya nuts gram dulse silver beet parsnip napa cabbage lotus root
sea lettuce brussels sprout cabbage.
</>
)}
</Body>
<Footer>
<FooterItem>
<Button onClick={() => setVisible(false)} isBasic>
Cancel
</Button>
</FooterItem>
<FooterItem>
<Button isPrimary isDanger={isDanger} onClick={() => setVisible(false)}>
Save
</Button>
</FooterItem>
</Footer>
<Close aria-label="Close modal" />
</Modal>
)}
</Col>
</Row>
</Grid>
);
};
Default.argTypes = {
backdropProps: { control: { disable: true } },
isLarge: {
control: 'boolean'
},
isDanger: {
control: 'boolean'
},
isAnimated: {
control: 'boolean'
},
isCentered: {
control: 'boolean'
},
focusOnMount: {
control: 'boolean'
},
restoreFocus: {
control: 'boolean'
},
id: {
control: 'text'
},
appendToNode: { control: { disable: true } }
}; | the_stack |
import { Directionality } from '@angular/cdk/bidi';
import { Component, NgZone } from '@angular/core';
import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DateAdapter } from '@ptsecurity/cdk/datetime';
import { ENTER } from '@ptsecurity/cdk/keycodes';
import {
dispatchFakeEvent,
dispatchKeyboardEvent,
dispatchMouseEvent,
MockNgZone
} from '@ptsecurity/cdk/testing';
import { McMomentDateModule } from '@ptsecurity/mosaic-moment-adapter/adapter';
import { McCalendar, McCalendarView } from './calendar.component';
import { McDatepickerIntl } from './datepicker-intl';
import { McDatepickerModule } from './datepicker-module';
// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
// tslint:disable-next-line:ordered-imports
import * as _moment from 'moment';
// @ts-ignore
// tslint:disable-next-line:no-duplicate-imports
import { default as _rollupMoment, Moment } from 'moment';
// tslint:disable-next-line
const moment = _rollupMoment || _moment;
describe('McCalendar', () => {
let zone: MockNgZone;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
McMomentDateModule,
McDatepickerModule
],
declarations: [
// Test components.
StandardCalendar,
CalendarWithMinMax,
CalendarWithDateFilter,
CalendarWithSelectableMinDate
],
providers: [
McDatepickerIntl,
{ provide: NgZone, useFactory: () => zone = new MockNgZone() },
{ provide: Directionality, useFactory: () => ({ value: 'ltr' }) }
]
});
TestBed.compileComponents();
}));
describe('standard calendar', () => {
let fixture: ComponentFixture<StandardCalendar>;
let testComponent: StandardCalendar;
let calendarElement: HTMLElement;
let periodButton: HTMLElement;
let calendarInstance: McCalendar<Moment>;
beforeEach(() => {
fixture = TestBed.createComponent(StandardCalendar);
fixture.detectChanges();
const calendarDebugElement = fixture.debugElement.query(By.directive(McCalendar));
calendarElement = calendarDebugElement.nativeElement;
periodButton = calendarElement.querySelector('.mc-calendar__period-button') as HTMLElement;
calendarInstance = calendarDebugElement.componentInstance;
testComponent = fixture.componentInstance;
});
it(`should update today's date`, inject([DateAdapter], (adapter: DateAdapter<Moment>) => {
let fakeToday = moment([2018, 0, 1]);
spyOn(adapter, 'today').and.callFake(() => fakeToday);
calendarInstance.activeDate = fakeToday;
calendarInstance.updateTodaysDate();
fixture.detectChanges();
let todayCell = calendarElement.querySelector('.mc-calendar__body-today')!;
expect(todayCell).not.toBeNull();
expect(todayCell.innerHTML.trim()).toBe('1');
fakeToday = moment([2018, 0, 10]);
calendarInstance.updateTodaysDate();
fixture.detectChanges();
todayCell = calendarElement.querySelector('.mc-calendar__body-today')!;
expect(todayCell).not.toBeNull();
expect(todayCell.innerHTML.trim()).toBe('10');
}));
it('should be in month view with specified month active', () => {
expect(calendarInstance.currentView).toBe(McCalendarView.Month);
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2017, 0, 31));
});
it('should select date in month view', () => {
const monthCells = calendarElement.querySelectorAll('.mc-calendar__body-cell');
(monthCells[monthCells.length - 1] as HTMLElement).click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe(McCalendarView.Month);
expect(testComponent.selected.toDate()).toEqual(new Date(2017, 0, 31));
});
it('should emit the selected month on cell clicked in year view', () => {
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe(McCalendarView.Year);
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2017, 0, 31));
(calendarElement.querySelector('.mc-calendar__body_active') as HTMLElement).click();
fixture.detectChanges();
const normalizedMonth: Moment = fixture.componentInstance.selectedMonth;
expect(normalizedMonth.month()).toEqual(0);
});
it('should emit the selected year on cell clicked in multiyear view', () => {
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe(McCalendarView.Year);
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2017, 0, 31));
(calendarElement.querySelector('.mc-calendar__body_active') as HTMLElement).click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe(McCalendarView.MultiYear);
(calendarElement.querySelector('.mc-calendar__body_active') as HTMLElement).click();
fixture.detectChanges();
const normalizedYear: Moment = fixture.componentInstance.selectedYear;
expect(normalizedYear.year()).toEqual(2017);
});
it('should complete the stateChanges stream', () => {
const spy = jasmine.createSpy('complete spy');
const subscription = calendarInstance.stateChanges.subscribe({complete: spy});
fixture.destroy();
expect(spy).toHaveBeenCalled();
subscription.unsubscribe();
});
describe('a11y', () => {
describe('calendar body', () => {
let calendarBodyEl: HTMLElement;
beforeEach(() => {
calendarBodyEl = calendarElement.querySelector('.mc-calendar__content') as HTMLElement;
expect(calendarBodyEl).not.toBeNull();
dispatchFakeEvent(calendarBodyEl, 'focus');
fixture.detectChanges();
});
it('should initially set start date active', () => {
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2017, 0, 31));
});
it('should not move focus to the active cell on init', () => {
const activeCell =
calendarBodyEl.querySelector('.mc-calendar__body_active')! as HTMLElement;
spyOn(activeCell, 'focus').and.callThrough();
fixture.detectChanges();
zone.simulateZoneExit();
expect(activeCell.focus).not.toHaveBeenCalled();
});
it('should move focus to the active cell when the view changes', () => {
const activeCell =
calendarBodyEl.querySelector('.mc-calendar__body_active')! as HTMLElement;
spyOn(activeCell, 'focus').and.callThrough();
fixture.detectChanges();
zone.simulateZoneExit();
expect(activeCell.focus).not.toHaveBeenCalled();
calendarInstance.currentView = McCalendarView.MultiYear;
fixture.detectChanges();
zone.simulateZoneExit();
expect(activeCell.focus).toHaveBeenCalled();
});
});
});
});
describe('calendar with min and max date', () => {
let fixture: ComponentFixture<CalendarWithMinMax>;
let testComponent: CalendarWithMinMax;
let calendarElement: HTMLElement;
let calendarInstance: McCalendar<Moment>;
beforeEach(() => {
fixture = TestBed.createComponent(CalendarWithMinMax);
const calendarDebugElement = fixture.debugElement.query(By.directive(McCalendar));
calendarElement = calendarDebugElement.nativeElement;
calendarInstance = calendarDebugElement.componentInstance;
testComponent = fixture.componentInstance;
});
it('should clamp startAt value below min date', () => {
testComponent.startAt = moment([2000, 0, 1]);
fixture.detectChanges();
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2016, 0, 1));
});
it('should clamp startAt value above max date', () => {
testComponent.startAt = moment([2020, 0, 1]);
fixture.detectChanges();
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2018, 0, 1));
});
it('should not go back past min date', () => {
testComponent.startAt = moment([2016, 1, 1]);
fixture.detectChanges();
const prevButton =
calendarElement.querySelector('.mc-calendar__previous-button') as HTMLButtonElement;
expect(prevButton.disabled).toBe(false, 'previous button should not be disabled');
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2016, 1, 1));
prevButton.click();
fixture.detectChanges();
expect(prevButton.disabled).toBe(true, 'previous button should be disabled');
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2016, 0, 1));
prevButton.click();
fixture.detectChanges();
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2016, 0, 1));
});
it('should not go forward past max date', () => {
testComponent.startAt = moment([2017, 11, 1]);
fixture.detectChanges();
const nextButton =
calendarElement.querySelector('.mc-calendar__next-button') as HTMLButtonElement;
expect(nextButton.disabled).toBe(false, 'next button should not be disabled');
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2017, 11, 1));
nextButton.click();
fixture.detectChanges();
expect(nextButton.disabled).toBe(true, 'next button should be disabled');
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2018, 0, 1));
nextButton.click();
fixture.detectChanges();
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2018, 0, 1));
});
it('should re-render the month view when the minDate changes', () => {
fixture.detectChanges();
spyOn(calendarInstance.monthView, 'init').and.callThrough();
testComponent.minDate = moment([2017, 10, 1]);
fixture.detectChanges();
expect(calendarInstance.monthView.init).toHaveBeenCalled();
});
it('should re-render the month view when the maxDate changes', () => {
fixture.detectChanges();
spyOn(calendarInstance.monthView, 'init').and.callThrough();
testComponent.maxDate = moment([2017, 11, 1]);
fixture.detectChanges();
expect(calendarInstance.monthView.init).toHaveBeenCalled();
});
it('should re-render the year view when the minDate changes', () => {
fixture.detectChanges();
const periodButton = calendarElement.querySelector('.mc-calendar__period-button') as HTMLElement;
periodButton.click();
fixture.detectChanges();
spyOn(calendarInstance.yearView, 'init').and.callThrough();
testComponent.minDate = moment([2017, 10, 1]);
fixture.detectChanges();
expect(calendarInstance.yearView.init).toHaveBeenCalled();
});
it('should re-render the year view when the maxDate changes', () => {
fixture.detectChanges();
const periodButton = calendarElement.querySelector('.mc-calendar__period-button') as HTMLElement;
periodButton.click();
fixture.detectChanges();
spyOn(calendarInstance.yearView, 'init').and.callThrough();
testComponent.maxDate = moment([2017, 11, 1]);
fixture.detectChanges();
expect(calendarInstance.yearView.init).toHaveBeenCalled();
});
it('should re-render the multi-year view when the minDate changes', () => {
fixture.detectChanges();
const periodButton = calendarElement.querySelector('.mc-calendar__period-button') as HTMLElement;
periodButton.click();
fixture.detectChanges();
(calendarElement.querySelector('.mc-calendar__body_active') as HTMLElement).click();
fixture.detectChanges();
spyOn(calendarInstance.multiYearView, 'init').and.callThrough();
testComponent.minDate = moment([2017, 10, 1]);
fixture.detectChanges();
expect(calendarInstance.multiYearView.init).toHaveBeenCalled();
});
it('should re-render the multi-year view when the maxDate changes', () => {
fixture.detectChanges();
const periodButton = calendarElement.querySelector('.mc-calendar__period-button') as HTMLElement;
periodButton.click();
fixture.detectChanges();
(calendarElement.querySelector('.mc-calendar__body_active') as HTMLElement).click();
fixture.detectChanges();
spyOn(calendarInstance.multiYearView, 'init').and.callThrough();
testComponent.maxDate = moment([2017, 11, 1]);
fixture.detectChanges();
expect(calendarInstance.multiYearView.init).toHaveBeenCalled();
});
it('should update the minDate in the child view if it changed after an interaction', () => {
fixture.destroy();
const dynamicFixture = TestBed.createComponent(CalendarWithSelectableMinDate);
dynamicFixture.detectChanges();
const calendarDebugElement = dynamicFixture.debugElement.query(By.directive(McCalendar));
const disabledClass = 'mc-calendar__body_disabled';
calendarElement = calendarDebugElement.nativeElement;
calendarInstance = calendarDebugElement.componentInstance;
let cells = Array.from(calendarElement.querySelectorAll('.mc-calendar__body-cell'));
expect(cells.slice(0, 9).every((c) => c.classList.contains(disabledClass)))
.toBe(true, 'Expected dates up to the 10th to be disabled.');
expect(cells.slice(9).every((c) => c.classList.contains(disabledClass)))
.toBe(false, 'Expected dates after the 10th to be enabled.');
(cells[14] as HTMLElement).click();
dynamicFixture.detectChanges();
cells = Array.from(calendarElement.querySelectorAll('.mc-calendar__body-cell'));
expect(cells.slice(0, 14).every((c) => c.classList.contains(disabledClass)))
.toBe(true, 'Expected dates up to the 14th to be disabled.');
expect(cells.slice(14).every((c) => c.classList.contains(disabledClass)))
.toBe(false, 'Expected dates after the 14th to be enabled.');
});
});
describe('calendar with date filter', () => {
let fixture: ComponentFixture<CalendarWithDateFilter>;
let testComponent: CalendarWithDateFilter;
let calendarElement: HTMLElement;
let calendarInstance: McCalendar<Moment>;
beforeEach(() => {
fixture = TestBed.createComponent(CalendarWithDateFilter);
fixture.detectChanges();
const calendarDebugElement = fixture.debugElement.query(By.directive(McCalendar));
calendarElement = calendarDebugElement.nativeElement;
calendarInstance = calendarDebugElement.componentInstance;
testComponent = fixture.componentInstance;
});
it('should disable and prevent selection of filtered dates', () => {
const cells = calendarElement.querySelectorAll('.mc-calendar__body-cell');
(cells[0] as HTMLElement).click();
fixture.detectChanges();
expect(testComponent.selected).toBeFalsy();
(cells[1] as HTMLElement).click();
fixture.detectChanges();
expect(testComponent.selected.toDate()).toEqual(new Date(2017, 0, 2));
});
describe('a11y', () => {
let tableBodyEl: HTMLElement;
beforeEach(() => {
tableBodyEl = calendarElement.querySelector('.mc-calendar__body') as HTMLElement;
expect(tableBodyEl).not.toBeNull();
dispatchFakeEvent(tableBodyEl, 'focus');
fixture.detectChanges();
});
it('should not allow selection of disabled date in month view', () => {
expect(calendarInstance.currentView).toBe(McCalendarView.Month);
expect(calendarInstance.activeDate.toDate()).toEqual(new Date(2017, 0, 1));
dispatchKeyboardEvent(tableBodyEl, 'keydown', ENTER);
fixture.detectChanges();
expect(testComponent.selected).toBeUndefined();
});
it('should allow entering month view at disabled month', () => {
const periodButton = calendarElement.querySelector('.mc-calendar__period-button') as HTMLElement;
dispatchMouseEvent(periodButton, 'click');
fixture.detectChanges();
(calendarElement.querySelector('.mc-calendar__body_active') as HTMLElement).click();
fixture.detectChanges();
calendarInstance.activeDate = moment([2017, 10, 1]);
fixture.detectChanges();
expect(calendarInstance.currentView).toBe(McCalendarView.MultiYear);
tableBodyEl = calendarElement.querySelector('.mc-calendar__body') as HTMLElement;
dispatchKeyboardEvent(tableBodyEl, 'keydown', ENTER);
fixture.detectChanges();
expect(calendarInstance.currentView).toBe(McCalendarView.Month);
expect(testComponent.selected).toBeUndefined();
});
});
});
});
@Component({
template: `
<mc-calendar
[startAt]="startDate"
[(selected)]="selected"
(yearSelected)="selectedYear=$event"
(monthSelected)="selectedMonth=$event">
</mc-calendar>`
})
class StandardCalendar {
selected: Moment;
selectedYear: Moment;
selectedMonth: Moment;
startDate = moment([2017, 0, 31]);
}
@Component({
template: `
<mc-calendar [startAt]="startAt" [minDate]="minDate" [maxDate]="maxDate"></mc-calendar>
`
})
class CalendarWithMinMax {
startAt: Moment;
minDate = moment([2016, 0, 1]);
maxDate = moment([2018, 0, 1]);
}
@Component({
template: `
<mc-calendar [startAt]="startDate" [(selected)]="selected" [dateFilter]="dateFilter">
</mc-calendar>
`
})
class CalendarWithDateFilter {
selected: Moment;
startDate = moment([2017, 0, 1]);
dateFilter(date: Moment) {
return !(date.date() % 2) && date.month() !== 10;
}
}
@Component({
template: `
<mc-calendar
[startAt]="startAt"
(selectedChange)="select($event)"
[selected]="selected"
[minDate]="selected">
</mc-calendar>
`
})
class CalendarWithSelectableMinDate {
startAt = new Date(2018, 6, 0);
selected: Date;
minDate: Date;
constructor() {
this.select(new Date(2018, 6, 10));
}
select(value: Date) {
this.minDate = this.selected = value;
}
} | the_stack |
declare namespace tableau {
enum DashboardObjectType {
BLANK = 'blank',
WORKSHEET = 'worksheet',
QUICK_FILTER = 'quickFilter',
PARAMETER_CONTROL = 'parameterControl',
PAGE_FILTER = 'pageFilter',
LEGEND = 'legend',
TITLE = 'title',
TEXT = 'text',
IMAGE = 'image',
WEB_PAGE = 'webPage',
ADDIN = 'addIn'
}
enum FieldAggregationType {
SUM,
AVG,
MIN,
MAX,
STDEV,
STDEVP,
VAR,
VARP,
COUNT,
COUNTD,
MEDIAN,
ATTR,
NONE,
YEAR,
QTR,
MONTH,
DAY,
HOUR,
MINUTE,
SECOND,
WEEK,
WEEKDAY,
MONTHYEAR,
MDY,
END,
TRUNC_YEAR,
TRUNC_QTR,
TRUNC_MONTH,
TRUNC_WEEK,
TRUNC_DAY,
TRUNC_HOUR,
TRUNC_MINUTE,
TRUNC_SECOND,
QUART1,
QUART3,
SKEWNESS,
KURTOSIS,
INOUT,
USER
}
enum FieldRoleType {
DIMENSION, MEASURE, UKNOWN
}
enum SheetType {
WORKSHEET = 'worksheet',
DASHBOARD = 'dashboard',
STORY = 'story',
}
enum ParameterAllowableValuesType {
ALL = 'all',
LIST = 'list',
RANGE = 'range',
}
enum ParameterDataType {
FLOAT = 'float',
INTEGER = 'integer',
STRING = 'string',
BOOLEAN = 'boolean',
DATE = 'date',
DATETIME = 'datetime'
}
//#region Error Classes
class TableauException extends Error {
tableauSoftwareErrorCode: ErrorCode;
}
enum ErrorCode {
/** The browser is not capable of supporting the Tableau JavaScript API. */
BROWSER_NOT_CAPABLE = 'browserNotCapable',
/** The permissions on a workbook or a view do not allow downloading the workbook. */
DOWNLOAD_WORKBOOK_NOT_ALLOWED = 'downloadWorkbookNotAllowed',
/** An error occurred while attempting to perform a filter operation. */
FILTER_CANNOT_BE_PERFORMED = 'filterCannotBePerformed',
/** Attempted to switch to a sheet by index that does not exist in the workbook. */
INDEX_OUT_OF_RANGE = 'indexOutOfRange',
/** An error occurred within the Tableau JavaScript API. Contact Tableau Support. */
INTERNAL_ERROR = 'internalError',
/** An invalid aggregation was specified for the filter, such as setting a range filter to "SUM(Sales)" instead of "Sales". */
INVALID_AGGREGATION_FIELD_NAME = 'invalidAggregationFieldName',
/** An operation was attempted on a custom view that does not exist. */
INVALID_CUSTOM_VIEW_NAME = 'invalidCustomViewName',
/** An invalid date was specified in a method that required a date parameter. */
INVALID_DATE_PARAMETER = 'invalidDateParameter',
/** A filter operation was attempted on a field that does not exist in the data source. */
INVALID_FILTER_FIELDNAME = 'invalidFilterFieldName',
/**
* Either a filter operation was attempted on a field that does not exist in the data source,
* or the value supplied in the filter operation is the wrong data type or format.
*/
INVALID_FILTER_FIELDNAME_OR_VALUE = 'invalidFilterFieldNameOrValue',
/** A filter operation was attempted using a value that is the wrong data type or format. */
INVALID_FILTER_FIELDVALUE = 'invalidFilterFieldValue',
/** A parameter is not the correct data type or format. The name of the parameter is specified in the Error.message field. */
INVALID_PARAMETER = 'invalidParameter',
/** An invalid date value was specified in a Sheet.selectMarksAsync() call for a date field. */
INVALID_SELECTION_DATE = 'invalidSelectionDate',
/** A field was specified in a Sheet.selectMarksAsync() call that does not exist in the data source. */
INVALID_SELECTION_FIELDNAME = 'invalidSelectionFieldName',
/** An invalid value was specified in a Sheet.selectMarksAsync() call. */
INVALID_SELECTION_VALUE = 'invalidSelectionValue',
/** A negative size was specified or the maxSize value is less than minSize in Sheet.changeSizeAsync(). */
INVALID_SIZE = 'invalidSize',
/**
* A behavior other than SheetSizeBehavior.AUTOMATIC was specified in
* Sheet.changeSizeAsync() when the sheet is a Worksheet instance.
*/
INVALID_SIZE_BEHAVIOR_ON_WORKSHEET = 'invalidSizeBehaviorOnWorksheet',
/** The URL specified in the Viz class constructor is not valid. */
INVALID_URL = 'invalidUrl',
/** The maxSize field is missing in Sheet.changeSizeAsync() when specifying SheetSizeBehavior.ATMOST. */
MISSING_MAX_SIZE = 'missingMaxSize',
/** The minSize field is missing in Sheet.changeSizeAsync() when specifying SheetSizeBehavior.ATLEAST. */
MISSING_MIN_SIZE = 'missingMinSize',
/**
* Either or both of the minSize or maxSize fields is missing in
* Sheet.changeSizeAsync() when specifying SheetSizeBehavior.RANGE.
*/
MISSING_MINMAX_SIZE = 'missingMinMaxSize',
/** The rangeN field is missing for a relative date filter of type LASTN or NEXTN. */
MISSING_RANGEN_FOR_RELATIVE_DATE_FILTERS = 'missingRangeNForRelativeDateFilters',
/** An attempt was made to access Sheet.getUrl() on a hidden sheet. Hidden sheets do not have URLs. */
NO_URL_FOR_HIDDEN_WORKSHEET = 'noUrlForHiddenWorksheet',
/** One or both of the parentElement or the URL parameters is not specified in the Viz constructor. */
NO_URL_OR_PARENT_ELEMENT_NOT_FOUND = 'noUrlOrParentElementNotFound',
/** An operation was attempted on a sheet that is not active or embedded within the active dashboard. */
NOT_ACTIVE_SHEET = 'notActiveSheet',
/** A required parameter was not specified, null, or an empty string/array. */
NULL_OR_EMPTY_PARAMETER = 'nullOrEmptyParameter',
/** A general-purpose server error occurred. Details are contained in the Error object. */
SERVER_ERROR = 'serverError',
/** An operation was attempted on a sheet that does not exist in the workbook. */
SHEET_NOT_IN_WORKBOOK = 'sheetNotInWorkbook',
/** An operation is performed on a CustomView object that is no longer valid (it has been removed). */
STALE_DATA_REFERENCE = 'staleDataReference',
/** An unknown event name was specified in the call to Viz.addEventListener or Viz.removeEventListener. */
UNSUPPORTED_EVENT_NAME = 'unsupportedEventName',
/** A Viz object has already been created as a child of the parentElement specified in the Viz constructor. */
VIZ_ALREADY_IN_MANAGER = 'vizAlreadyInManager',
INVALID_TOOLBAR_BUTTON_NAME = 'invalidToolbarButtonName',
MAX_VIZ_RESIZE_ATTEMPTS = 'maxVizResizeAttempts',
}
//#endregion
//#region Viz Classes
class VizManager {
getVizs(): Viz[];
}
type ListenerFunction<T extends TableauEvent> = (event: T) => void;
class Viz {
/**
* Creates a new Tableau Viz inside of the given HTML container, which is typically a <div> element.
* Each option as well as the options parameter is optional.
* If there is already a Viz associated with the parentElement, an exception is thrown.
* Before reusing the parentElement you must first call dispose().
*/
constructor(node: HTMLElement, url: string, options?: VizCreateOptions);
/** Indicates whether the tabs are displayed in the UI. It does not actually hide individual tabs. */
getAreTabsHidden(): boolean;
/** Indicates whether the toolbar is displayed. */
getToolbarHidden(): boolean;
/** Indicates whether the visualization is displayed on the hosting page. */
getIsHidden(): boolean;
/** Returns the node that was specified in the constructor. */
getParentElement(): HTMLElement;
/** The URL of the visualization, as specified in the constructor */
getUrl(): string;
/** One Workbook is supported per visualization. */
getWorkbook(): Workbook;
/** Indicates whether automatic updates are currently paused. */
getAreAutomaticUpdatesPaused(): boolean;
addEventListener(event: TableauEventName.FILTER_CHANGE, f: ListenerFunction<FilterEvent>): void;
addEventListener(
event: TableauEventName.CUSTOM_VIEW_LOAD | TableauEventName.CUSTOM_VIEW_REMOVE | TableauEventName.CUSTOM_VIEW_SAVE | TableauEventName.CUSTOM_VIEW_SET_DEFAULT,
f: ListenerFunction<CustomViewEvent>): void;
addEventListener(event: TableauEventName.MARKS_SELECTION, f: ListenerFunction<MarksEvent>): void;
addEventListener(event: TableauEventName.PARAMETER_VALUE_CHANGE, f: ListenerFunction<ParameterEvent>): void;
addEventListener(event: TableauEventName.STORY_POINT_SWITCH, f: ListenerFunction<StoryPointSwitchEvent>): void;
addEventListener(event: TableauEventName.TAB_SWITCH, f: ListenerFunction<TabSwitchEvent>): void;
addEventListener(event: TableauEventName.TOOLBAR_STATE_CHANGE, f: ListenerFunction<ToolbarStateEvent>): void;
addEventListener(event: TableauEventName.VIZ_RESIZE, f: ListenerFunction<VizResizeEvent>): void;
/** Removes an event listener from the specified event. */
removeEventListener(type: TableauEventName, f: ListenerFunction<TableauEvent>): void;
/** Shows or hides the iframe element hosting the visualization. */
show(): void;
/** Shows or hides the iframe element hosting the visualization. */
hide(): void;
/**
* Cleans up any resources associated with the visualization,
* removes the visualization from the VizManager instance,
* and removes any DOM elements from the parentElement object.
* In effect, this method restores the page to what it was before a Viz object was instantiated.
*/
dispose(): void;
/** Pauses or resumes layout updates. This is useful if you are resizing the visualization or performing multiple calls that could affect the layout. */
pauseAutomaticUpdatesAsync(): void;
resumeAutomaticUpdatesAsync(): void;
toggleAutomaticUpdatesAsync(): void;
/** Equivalent to clicking on the Revert All toolbar button, which restores the workbook to its starting state. */
revertAllAsync(): Promise<void>;
/** Equivalent to clicking on the Refresh Data toolbar button. */
refreshDataAsync(): Promise<void>;
/** Equivalent to clicking on the Download toolbar button, which downloads a copy of the original workbook. */
showDownloadWorkbookDialog(): void;
/** Equivalent to clicking on the Export Image toolbar button, which creates a PNG file of the current visualization. */
showExportImageDialog(): void;
/** Equivalent to clicking on the Export PDF toolbar button, which shows a dialog allowing the user to select options for the export. */
showExportPDFDialog(): void;
/**
* Shows the Export Data dialog, which is currently a popup window. The worksheetInDashboard parameter is optional.
* If not specified, the currently active Worksheet is used.
*/
showExportDataDialog(worksheetInDashboard: Sheet | SheetInfo | string): void;
/** Shows the Export CrossTab dialog. The worksheetInDashboard parameter is optional. If not specified, the currently active Worksheet is used. */
showExportCrossTabDialog(worksheetInDashboard: Sheet | SheetInfo | string): void;
/**
* Equivalent to clicking on the Share toolbar button,
* which displays a dialog allowing the user to share the visualization by email or by embedding its HTML in a web page.
*/
showShareDialog(): void;
/**
* Sets the size of the iframe element, which causes the visualization to expand or
* collapse to fit the iframe element if the visualization size (current sheet's size) is set to AUTOMATIC.
*/
setFrameSize(width: number, height: number): void;
/** Gets the URL of the visualization asynchronously. */
getCurrentUrlAsync(): Promise<string>;
/** Redoes last action on a sheet, defaults to a single redo unless optional parameters is specified. */
redoAsync(): Promise<void>;
/** Undoes action on sheet, defaults to a single undo unless optional parameters is specified. */
undoAsync(): Promise<void>;
}
interface VizCreateOptions {
/** Undoes action on sheet, defaults to a single undo unless optional parameters is specified. */
hideTabs?: boolean;
/** Indicates whether the toolbar is hidden or shown. */
hideToolbar?: boolean;
/**
* Specifies the ID of an existing instance to make a copy (clone) of.
* This is useful if the user wants to continue analysis of an existing visualization without losing the state of the original.
* If the ID does not refer to an existing visualization, the cloned version is derived from the original visualization.
*/
instanceIdToClone?: string;
/** Can be any valid CSS size specifier. If not specified, defaults to the published height of the view. */
height?: string;
/** Can be any valid CSS size specifier. If not specified, defaults to the published height of the view. */
width?: string;
/**
* Specifies a device layout for a dashboard, if it exists.
* Values can be desktop, tablet, or phone.
* If not specified, defaults to loading a layout based on the smallest dimension of the hosting iframe element.
*/
device?: string;
/**
* Callback function that is invoked when the Viz object first becomes interactive.
* This is only called once, but it’s guaranteed to be called.
* If the Viz object is already interactive, it will be called immediately, but on a separate "thread."
*/
onFirstInteractive?: (e: TableauEvent) => void;
/**
* Callback function that's invoked when the size of the Viz object is known.
* You can use this callback to perform tasks such as resizing the elements surrounding the Viz object once the object's size has been established.
*/
onFirstVizSizeKnown?: (e: VizResizeEvent) => void;
/**
* Apply a filter that you specify to the view when it is first rendered.
* For example, if you have an Academic Year filter and only want to display data for 2017,
* you might enter "Academic Year": "2016". For more information, see Filtering.
*/
[filter: string]: any;
}
enum ToolbarPosition {
/** Positions the toolbar along the top of the visualization. */
TOP = 'top',
/** Positions the toolbar along the bottom of the visualization. */
BOTTOM = 'bottom',
}
class ToolbarState {
/** Gets the Viz object associated with the toolbar. */
getViz(): Viz;
/**
* Gets a value indicating whether the specified toolbar button is enabled.
* The supported buttons are defined in the ToobarButtonName enum.
* Currently, only Undo and Redo are supported.
* Checking this property with a toolbar button that is not supported causes an InvalidToolbarButtonName error.
*/
isButtonEnabled(toolbarButtonName: ToolbarButtonName): boolean;
}
enum ToolbarButtonName {
/** Specifies the Undo button in the toolbar. */
UNDO = 'undo',
/** Specifies the Redo button in the toolbar. */
REDO = 'redo',
}
//#endregion
//#region Viz Event Classes
/**
* Defines strings passed to the Viz.addEventListener and Viz.removeEventListener methods.
* The values of the enums are all lowercase strings with no underscores.
* For example, CUSTOM_VIEW_LOAD is customviewload.
* Either the fully-qualified enum (tableau.TableauEventName.FILTER_CHANGE) or the raw string (filterchange) is acceptable.
*/
enum TableauEventName {
/**
* Raised when a custom view has finished loading.
* This event is raised after the callback function for onFirstInteractive (if any) has been called.
*/
CUSTOM_VIEW_LOAD = 'customviewload',
/** Raised when the user removes a custom view. */
CUSTOM_VIEW_REMOVE = 'customviewremove',
/** Raised when the user saves a new or existing custom view. */
CUSTOM_VIEW_SAVE = 'customviewsave',
/** Raised when a custom view has been made the default view for this visualization. */
CUSTOM_VIEW_SET_DEFAULT = 'customviewsetdefault',
/** Raised when any filter has changed state. The Viz object may not be interactive yet. */
FILTER_CHANGE = 'filterchange',
/** Raised when marks are selected or deselected. */
MARKS_SELECTION = 'marksselection',
/** Raised when any parameter has changed state. */
PARAMETER_VALUE_CHANGE = 'parametervaluechange',
/** Raised after a story point becomes active. */
STORY_POINT_SWITCH = 'storypointswitch',
/** Raised after the tab switched, but the Viz object may not yet be interactive. */
TAB_SWITCH = 'tabswitch',
/** Raised when the state of the specified toolbar button changes. See API Reference. */
TOOLBAR_STATE_CHANGE = 'toolbarstatechange',
/** Raised every time the frame size is calculated from the available size and the Viz object's published size. */
VIZ_RESIZE = 'vizresize',
}
class TableauEvent {
/** Gets the Viz object associated with the event. */
getViz(): Viz;
/** Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum. */
getEventName(): TableauEventName;
}
class CustomViewEvent extends TableauEvent {
/** Gets the CustomView object associated with the event. */
getCustomViewAsync(): Promise<CustomView>;
}
class FilterEvent extends TableauEvent {
/** Gets the Worksheet object associated with the event. */
getWorksheet(): Worksheet;
/** Gets the name of the field. */
getFieldName(): string;
/** Gets the Filter object associated with the event. */
getFilterAsync(): Promise<ConcreteFilter>;
}
class MarksEvent extends TableauEvent {
/** Gets the Worksheet object associated with the event. */
getWorksheet(): Worksheet;
/** Gets the selected marks on the Worksheet that triggered the event. */
getMarksAsync(): Promise<Mark[]>;
}
class ParameterEvent extends TableauEvent {
/** Gets the name of the parameter that changed. */
getParameterName(): string;
/** Gets the Parameter object that triggered the event. */
getParameterAsync(): Promise<Parameter>;
}
class StoryPointSwitchEvent extends TableauEvent {
/**
* Gets the StoryPointInfo that was active before the story point switch event occurred.
* The returned object reflects the state of the story point before the switch occurred.
* The returned object reflects the state of the story point after the switch occured.
*/
getOldStoryPointInfo(): StoryPointInfo;
/** Gets the StoryPoint that is currently active. */
getNewStoryPoint(): StoryPoint;
}
class TabSwitchEvent extends TableauEvent {
/** Gets the name of the sheet that was active before the tab switch event occurred. */
getOldSheetName(): string;
/** Gets the name of the sheet that is currently active. */
getNewSheetName(): string;
}
class ToolbarStateEvent extends TableauEvent {
/** Returns the new ToolbarState. */
getToolbarState(): ToolbarState;
}
class VizResizeEvent extends TableauEvent {
/** Gets the Viz object associated with the event. */
getViz(): Viz;
/** Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum. */
getEventName(): TableauEventName;
/** Gets the sheetSize record for the current sheet. For more information, see SheetSizeOptions Record. */
getVizSize(): Size;
}
//#endregion
//#region Sheet Classes
class SheetInfo {
/** Gets the name of the sheet. */
getName(): string;
/** Gets the index of the sheet within the published tabs. Note that hidden tabs are still counted in the ordering, as long as they are published. */
getIndex(): number;
/**
* Gets a value indicating whether the sheet is the currently active sheet.Due to a technical limitation,
* this will always return false if the object is a Worksheet instance that is part of a Dashboard.
*/
getIsActive(): boolean;
/**
* Gets a value indicating whether the sheet is hidden in the UI. Note that if the entire tab control is hidden,
* it does not affect the state of this flag. This sheet may still report that it is visible even when the tabs control is hidden.
*/
getIsHidden(): boolean;
/** Gets the type of the sheet. SheetType is an enum with the following values: WORKSHEET, DASHBOARD and STORY. */
getSheetType(): SheetType;
/** Gets the size information that the author specified when publishing the workbook. */
getSize(): SheetSizeOptions;
/** Gets the URL for this sheet. */
getUrl(): string;
/** Gets the Workbook to which this Sheet belongs. */
getWorkbook(): Workbook;
}
class Sheet {
/** Gets the name of the sheet. */
getName(): string;
/** Gets the index of the sheet within the published tabs. Note that hidden tabs are still counted in the ordering, as long as they are published. */
getIndex(): number;
/** Gets a value indicating whether the sheet is the currently active sheet. */
getIsActive(): boolean;
/**
* Gets a value indicating whether the sheet is hidden in the UI.
* Note that if the entire tab control is hidden, it does not affect the state of this flag.
* This sheet may still report that it is visible even when the tabs control is hidden.
*/
getIsHidden(): boolean;
/** Gets the type of the sheet. SheetType is an enum with the following values: WORKSHEET , DASHBOARD and STORY. */
getSheetType(): SheetType;
/** Gets the size information that the author specified when publishing the workbook. */
getSize(): SheetSizeOptions;
/** Gets the URL for this sheet. */
getUrl(): string;
/** Gets the Workbook to which this Sheet belongs. */
getWorkbook(): Workbook;
/**
* Sets the size information on a sheet. Note that if the sheet is a Worksheet,
* only SheetSizeBehavior.AUTOMATIC is allowed since you can’t actually set a Worksheet to a fixed size.
*/
changeSizeAsync(options: SheetSizeOptions): Promise<SheetSizeOptions>;
}
enum SheetSizeBehaviour {
AUTOMATIC = 'automatic',
EXACTLY = 'exactly',
RANGE = 'range',
ATLEAST = 'atleast',
ATMOST = 'atmost',
}
interface SheetSizeOptions {
/** Contains an enumeration value of one of the following: AUTOMATIC, EXACTLY, RANGE, ATLEAST, and ATMOST. */
behavior: SheetSizeBehaviour;
/** This is only defined when behavior is EXACTLY, RANGE or ATMOST. */
maxSize: number;
/** This is only defined when behavior is EXACTLY, RANGE, or ATLEAST. */
minSize: number;
}
class DataTable {
/** Either "Underlying Data Table" or "Summary Data Table". */
getName(): string;
/**
* A two-dimensional array of data without the sheet or column metadata.
* The first array index is the row index and the second array index is the column index.
*/
getData(): any[];
/** The column information, including the name, data type, and index. */
getColumns(): Column[];
/** The number of rows in the returned data. */
getTotalRowCount(): number;
/** Whether the data is summary data or underlying data. Returns true for summary data. */
getIsSummaryData(): boolean;
}
class Column {
/** The name of the column. */
getFieldName(): string;
/** The data type of the column. Possible values are float, integer, string, boolean, date, and datetime. */
getDataType(): string;
/** Whether the column data is referenced in the visualization. */
getIsReferenced(): boolean;
/** The number of rows in the returned data. */
getIndex(): number;
}
class Worksheet extends Sheet {
/** Returns the Dashboard object to which this Worksheet belongs (if it’s on a dashboard). Otherwise, it returns null. */
getParentDashboard(): Dashboard;
/**
* Returns the StoryPoint object to which this Worksheet belongs (if it’s on a story sheet).
* Otherwise, it returns null. If the Worksheet instance does not come from a call to StoryPoint.getContainedSheet(), it also returns null.
*/
getParentStoryPoint(): StoryPoint;
/**
* Gets the primary and all of the secondary data sources for this worksheet.
* Note that by convention the primary data source should always be the first element.
*/
getDataSourcesAsync(): Promise<DataSource[]>;
/**
* Gets aggregated data for the fields used in the currently active sheet and returns it as an object.
* You can specify options with an optional parameter. This can only be called on sheets of the WORKSHEET type.
*/
getSummaryDataAsync(options: getSummaryDataOptions): Promise<DataTable>;
/**
* Gets data for all fields in the data source used by the currently active sheet and returns it as an object.
* You can specify options with an optional parameter. This can only be called on sheets of the WORKSHEET type.
*/
getUnderlyingDataAsync(options: getUnderlyingDataOptions): Promise<DataTable>;
/** Fetches the collection of filters used on the sheet. */
getFiltersAsync(): Promise<Filter[]>;
/**
* Applies a simple categorical filter (non-date).
* See the filtering examples for more details on these functions.
* Returns the fieldName that was filtered.
*/
applyFilterAsync(fieldName: string, values: object[] | object, updateType: FilterUpdateType, options?: FilterOptions): Promise<string>;
/**
* Applies a quantitative filter to a field or to a date.
* If a range is specified that is outside of the domain min/max values, no error is raised and the command is allowed.
* Subsequent calls to getFiltersAsync[] will return these values even if they are outside of the bounds of the domain.
* This is equivalent to the behavior in Tableau Desktop.
*/
applyRangeFilterAsync(fieldName: string, range: RangeFilterOptions): Promise<string>;
/** Applies a relative date filter. */
applyRelativeDateFilterAsync(fieldName: string, options: RelativeDateFilterOptions): Promise<string>;
/**
* Applies a hierarchical filter.
* The values parameter is either a single value, an array of values, or an object { levels: ["1", "2"] }.
*/
applyHierarchicalFilterAsync(fieldName: string, values: object, options: any): Promise<string>;
/**
* Clears the filter, no matter what kind of filter it is.
* Note that the filter is removed as long as no associated quick filter is showing for the field.
* If there is a quick filter showing, then the filter is kept, but it’s reset to the “All” state (effectually canceling the filter).
* For relative date filters, however, an error is returned since there is no “All” state for a relative date filter.
* To clear a relative date filter with a quick filter showing, you can call applyRelativeDateFilter()
* instead using a range that makes sense for the specific field.
*/
clearFilterAsync(fieldName: string): Promise<string>;
/** Clears the selection for this worksheet. */
clearSelectedMarksAsync(): Promise<void>;
/** Gets the collection of marks that are currently selected. */
getSelectedMarksAsync(): Promise<Mark[]>;
/** Selects the marks and returns them. */
selectMarksAsync(fieldName: string, value: object | object[], updateType: SelectionUpdateType): Promise<void>;
/**
* Allows selection based on this syntax for the first parameter:
* {
* "Field1": value,
* "Field2": [1, 2, 3]
* }
*/
selectMarksAsync(fieldValuesMap: object | Mark[], updateType: SelectionUpdateType): Promise<void>;
}
interface getSummaryDataOptions {
/** Do not use aliases specified in the data source in Tableau. Default is false. */
ignoreAliases?: boolean;
/** Only return data for the currently selected marks. Default is false. */
ignoreSelection?: boolean;
/** The number of rows of data that you want to return. Enter 0 to return all rows. */
maxRows: number;
}
interface getUnderlyingDataOptions {
/** Do not use aliases specified in the data source in Tableau. Default is false. */
ignoreAliases?: boolean;
/** Only return data for the currently selected marks. Default is false. */
ignoreSelection?: boolean;
/** Return all the columns for the data source. Default is false. */
ignoreAllColumns?: boolean;
/** The number of rows of data that you want to return. Enter 0 to return all rows. */
maxRows: number;
}
class Dashboard extends Sheet {
/** Gets the collection of objects. */
getObjects(): DashboardObject[];
/**
* Gets the collection of worksheets contained in the dashboard.
* Note that this is a helper method and is equivalent to looping through getObjects() and collecting all of
* the DashboardObject.Worksheet pointers when DashboardObject.getType() === tableau.DashboardObjectType.WORKSHEET.
*/
getWorksheets(): Worksheet[];
/**
* Returns the StoryPoint object to which this Dashboard belongs (if it’s on a story sheet).
* Otherwise, it returns null.
* If the Dashboard instance does not come from a call to StoryPoint.getContainedSheet(), it also returns null.
*/
getParentStoryPoint(): StoryPoint;
}
class DashboardObject {
/**
* Gets what the object represents, which is an enum with the following values:
* BLANK, WORKSHEET, QUICK_FILTER, PARAMETER_CONTROL, PAGE_FILTER, LEGEND, TITLE, TEXT, IMAGE, WEB_PAGE.
*/
getObjectType(): DashboardObjectType;
/** Gets the Dashboard object that contains this object. */
getDashboard(): Dashboard;
/** If getType() returns WORKSHEET, this contains a pointer to the Worksheet object. */
getWorksheet(): Worksheet;
/** Gets the coordinates relative to the top-left corner of the dashboard of the object. */
getPosition(): Point;
/** Gets the size of the object. */
getSize(): Size;
}
class Story extends Sheet {
/**
* Gets an array (not a collection) of StoryPointInfo objects.
* Note that this is not a collection, since we don’t have a unique string key for a story point.
* We only need ordinal access to the story points (by index).
*/
getStoryPointsInfo(): StoryPointInfo[];
/** Gets the currently active story point. */
getActiveStoryPoint(): StoryPoint;
/**
* Activates the story point at the specified index and returns a promise of the activated StoryPoint.
* Throws a tableau.ErrorCode.INDEX_OUT_OF_RANGE error if the index is less than zero or greater than or equal to the number of story points in the array.
*/
activateStoryPointAsync(index: number): Promise<StoryPoint>;
/** Activates the next story point if there is one. If the current story point is the last one, then is stays active. */
activateNextStoryPointAsync(): Promise<StoryPoint>;
/** Activates the previous story point if there is one. If the current story point is the first one, then it stays active. */
activatePreviousStoryPointAsync(): Promise<StoryPoint>;
/**
* Reverts the story point at the specified index and returns a promise of the reverted StoryPoint.
* Throws a tableau.ErrorCode.INDEX_OUT_OF_RANGE error if the index is less than zero or greater than or equal to the number of story points in the array.
*/
revertStoryPointAsync(index: number): Promise<StoryPoint>;
}
class StoryPointInfo {
/** Gets the zero-based index of this story point within the parent Story sheet. */
getIndex(): number;
/** Gets the content of the textual description for this story point. */
getCaption(): string;
/** Gets a value indicating whether the story point is the currently active point in the story. */
getIsActive(): boolean;
/** Gets a value indicating whether the story point is updated, meaning that there are no changes from the last time the story point was “captured”. */
getIsUpdated(): boolean;
/** Gets the Story object that contains the story point. */
getParentStory(): Story;
}
class StoryPoint {
/** Gets the zero-based index of this story point within the parent Story sheet. */
getIndex(): number;
/** Gets the content of the textual description for this story point. */
getCaption(): string;
/** Gets a value indicating whether the story point is the currently active point in the story. */
getIsActive(): boolean;
/** Gets a value indicating whether the story point is updated, meaning that there are no changes from the last time the story point was “captured”. */
getIsUpdated(): boolean;
/** Gets the sheet that this story point contains. This will be null if the story point does not have a contained sheet. */
getContainedSheet(): Sheet;
/** Gets the Story object that contains the story point. */
getParentStory(): Story;
}
//#endregion
//#region Workbook Classes
class Workbook {
/** Gets the Viz object that contains the workbook. */
getViz(): Viz;
/** Gets the currently active sheet (the active tab) */
getActiveSheet(): Sheet;
/** Gets the currently active custom view, or null if no custom view is active. */
getActiveCustomView(): CustomView;
/** Note that this is synchronous, meaning that all of the sheets are expected when loaded. */
getPublishedSheetsInfo(): SheetInfo[];
/** Gets the name of the workbook saved to the server. Note that this is not necessarily the file name. */
getName(): string;
/** Activates the sheet, either by name or index, and returns a promise of the sheet that was activated. */
activateSheetAsync(sheetNameOrIndex: string | number): Promise<Sheet>;
/** Reverts the workbook to its last saved state. */
revertAllAsync(): Promise<void>;
/** Fetches the parameters for this workbook. */
getParametersAsync(): Promise<Parameter[]>;
/**
* Changes the value of the parameter with the given name and returns the new Parameter.
* The value should be the same data type as the parameter and within the allowable range of values.
* It also needs to be the aliased value and not the raw value.
* For more information and examples, see changeParameterValueAsync() Additional Information
*/
changeParameterValueAsync(name: string, value: any): Promise<Parameter>;
/** Gets the collection of CustomView objects associated with the workbook. */
getCustomViewsAsync(): Promise<CustomView[]>;
/** Changes the visualization to show the named saved state. */
showCustomViewAsync(customViewName: string): Promise<CustomView>;
/** Removes the named custom view. */
removeCustomViewAsync(customViewName: string): Promise<CustomView>;
/** Remembers the current state of the workbook by assigning a custom view name. */
rememberCustomViewAsync(customViewName: string): Promise<CustomView>;
/** Sets the active custom view as the default. */
setActiveCustomViewAsDefaultAsync(): void;
}
class DataSource {
/** The name of the DataSource as seen in the UI. */
getName(): string;
/** Indicates whether this DataSource is a primary or a secondary data source. */
getIsPrimary(): boolean;
/** Gets an array of Fields associated with the DataSource. */
getFields(): Field[];
}
class Field {
/** Gets the field name (i.e. caption). */
getName(): string;
getAggregation(): FieldAggregationType;
/** Gets the data source to which this field belongs. */
getDataSource(): DataSource;
/** One of the following values: DIMENSION, MEASURE, UKNOWN */
getRole(): FieldRoleType;
}
class CustomView {
/** User-friendly name for the custom view */
getName(): string;
/** User-friendly name for the custom view */
setName(name: string): string;
/** Indicates whether the custom view is public or private. */
getAdvertised(): boolean;
/** Indicates whether the custom view is public or private. */
setAdvertised(bool: boolean): boolean;
/** Gets or sets whether this is the default custom view. */
getDefault(): boolean;
/** Gets the user that created the custom view. */
getOwnerName(): string;
/** Unique URL to load this view again. */
getUrl(): string;
/** Gets the Workbook to which this CustomView belongs. */
getWorkbook(): Workbook;
/** After saveAsync() is called, the result of the getUrl method is no longer blank. */
saveAsync(): Promise<CustomView>;
}
//#endregion
//#region Parameter Classes
class Parameter {
/** A unique identifier for the parameter, as specified by the user. */
getName(): string;
/** The current value of the parameter. */
getCurrentValue(): DataValue;
/** The data type of the parameter can be one of the following: FLOAT, INTEGER, STRING, BOOLEAN, DATE, DATETIME. */
getDataType(): ParameterDataType;
/** The type of allowable values that the parameter can accept. It can be one of the following enumeration items: ALL, LIST, RANGE. */
getAllowableValuesType(): ParameterAllowableValuesType;
/**
* If the parameter is restricted to a list of allowable values, this property contains the array of those values.
* Note that this is not a standard collection, but a JavaScript array.
*/
getAllowableValues(): DataValue[];
/** If getAllowableValuesType is RANGE, this defines the minimum allowable value, inclusive. Otherwise it’s undefined/null. */
getMinValue(): DataValue;
/** If getAllowableValuesType is RANGE, this defines the maximum allowable value, inclusive. Otherwise it’s undefined/null. */
getMaxValue(): DataValue;
/** If getAllowableValuesType is RANGE, this defines the step size used in the parameter UI control slider. Otherwise it’s undefined/null. */
getStepSize(): number;
/**
* If getAllowableValuesType is RANGE and getDataType is DATE or DATETIME,
* this defines the step date period used in the Parameter UI control slider.
* Otherwise it’s undefined/null.
*/
getDateStepPeriod(): PeriodType;
}
//#endregion
//#region Filtering
interface FilterOptions {
/**
* Determines whether the filter will apply in exclude mode or include mode.
* The default is include, which means that you use the fields as part of a filter.
* Exclude mode means that you include everything else except the specified fields.
*/
isExcludeMode: boolean;
}
interface RangeFilterOptions {
/** Minimum value for the range (inclusive). Optional. Leave blank if you want a <= filter. */
min: number | Date;
/** Maximum value for the range (inclusive). Optional. Leave blank if you want a >= filter. */
max: number | Date;
/** The null values to include */
nullOption: NullOption;
}
interface RelativeDateFilterOptions {
/** The UTC date from which to filter. */
anchorDate: Date;
/** Year, quarter, month, etc. */
periodType: PeriodType;
/** LAST, LASTN, NEXT, etc. */
rangeType: DateRangeType;
/** The number used when the rangeType is LASTN or NEXTN. */
rangeN: number;
}
class Filter {
/** Gets the parent worksheet */
getWorksheet(): Worksheet;
/** Gets the type of the filter. See FilterType Enum for the values in the enum. */
getFilterType(): FilterType;
/** Gets the name of the field being filtered. Note that this is the caption as shown in the UI and not the actual database field name. */
getFieldName(): string;
/** Gets the field that is currently being filtered. */
getFieldAsync(): Promise<Field>;
}
/** An enumeration that indicates what to do with null values for a given filter or mark selection call. */
enum NullOption {
/** Only include null values in the filter. */
NULL_VALUES = 'nullValues',
/** Only include non-null values in the filter. */
NON_NULL_VALUES = 'nonNullValues',
/** Include null and non-null values in the filter. */
ALL_VALUES = 'allValues',
}
class CategoricalFilter extends Filter {
/** Gets a value indicating whether the filter is exclude or include (default). */
getIsExcludeMode(): boolean;
/**
* Gets the collection of values that are currently set on the filter.
* This is a native JavaScript array and not a keyed collection.
* Note that only the first 200 values are returned.
*/
getAppliedValues(): DataValue[];
}
class QuantitativeFilter extends Filter {
/** Gets the minimum value as specified in the domain. */
getDomainMin(): DataValue;
/** Gets the maximum value as specified in the domain. */
getDomainMax(): DataValue;
/** Gets the minimum value, inclusive, applied to the filter. */
getMin(): DataValue;
/** Gets the maximum value, inclusive, applied to the filter. */
getMax(): DataValue;
/** Indicates whether null values are included in the filter. */
getIncludeNullValues(): boolean;
}
class RelativeDateFilter extends Filter {
/** The date period of the filter. See PeriodType Enum for the values in the enum. */
getPeriod(): PeriodType;
/** The range of the date filter (years, months, etc.). See DateRangeType Enum for the values in the enum. */
getRange(): DateRangeType;
/** When getRange returns LASTN or NEXTN, this is the N value (how many years, months, etc.). */
getRangeN(): number;
}
type ConcreteFilter = CategoricalFilter | QuantitativeFilter | RelativeDateFilter;
class DataValue {
/** Contains the raw native value as a JavaScript type, which is one of String, Number, Boolean, or Date */
value: any;
/** The value formatted according to the locale and the formatting applied to the field or parameter. */
formattedValue: string;
}
enum FilterType {
/** Categorical filters are used to filter to a set of values within the domain. */
CATEGORICAL = 'categorical',
/** Quantitative filters are used to filter to a range of values from a continuous domain. */
QUANTITATIVE = 'quantitative',
/** Hierarchical filters are used to filter to a set of values organized into a hierarchy within the domain. */
HIERARCHICAL = 'hierarchical',
/** Relative date filters are used to filter a date/time domain to a range of values relative to a fixed point in time. */
RELATIVE_DATE = 'relativedate',
}
enum FilterUpdateType {
/** Adds all values to the filter. Equivalent to checking the (All) value in a quick filter. */
ALL = 'all',
/** Replaces the current filter values with new ones specified in the call */
REPLACE = 'replace',
/** Adds the filter values as specified in the call to the current filter values. Equivalent to checking a value in a quick filter. */
ADD = 'add',
/** Removes the filter values as specified in the call from the current filter values. Equivalent to unchecking a value in a quick filter. */
REMOVE = 'remove',
}
enum PeriodType {
YEARS = 'years',
QUARTERS = 'quarters',
MONTHS = 'months',
WEEKS = 'weeks',
DAYS = 'days',
HOURS = 'hours',
MINUTES = 'minutes',
SECONDS = 'seconds',
}
enum DateRangeType {
LAST = 'last', /** Refers to the last day, week, month, etc. of the date period. */
LASTN = 'lastn', /** Refers to the last N days, weeks, months, etc. of the date period. */
NEXT = 'next', /** Refers to the next day, week, month, etc. of the date period. */
NEXTN = 'nextn', /** Refers to the next N days, weeks, months, etc. of the date period. */
CURRENT = 'current', /** Refers to the current day, week, month, etc. of the date period. */
TODATE = 'todate', /** Refers to everything up to and including the current day, week, month, etc. of the date period. */
}
//#endregion
//#region Marks Selection
/**
* A mark represents a single data point on the visualization.
* It is independent of the type of visualization (bar, line, pie, etc.).
*/
class Mark {
/** Creates a new Mark with the specified pairs. */
constructor(pairs: Pair[]);
/** Gets a collection of field name/value pairs associated with the mark. */
getPairs(): Pair[];
}
class Pair {
/** The value formatted according to the locale and the formatting applied to the field. */
formattedValue: string;
/** The field name to which the value is applied. */
fieldName: string;
/** Contains the raw native value for the field as a JavaScript type, which is one of String, Number, Boolean, or Date. */
value: string | number | boolean | Date;
/** Creates a new Pair with the specified field name/value pairing */
constructor(fieldName: string, value: string | number | boolean | Date);
}
enum SelectionUpdateType {
/** Replaces the current marks values with new ones specified in the call. */
REPLACE = 'replace',
/** Adds the values as specified in the call to the current selection. Equivalent to control-clicking in desktop. */
ADD = 'add',
/** Removes the values as specified in the call from the current selection. Equivalent to control-clicking an already selected mark in desktop. */
REMOVE = 'remove',
}
//#endregion
//#region Other
interface Size {
width: number;
height: number;
}
interface Point {
x: number;
y: number;
}
//#endregion
} | the_stack |
import { Board, Pin } from "johnny-five"
enum Protocol {I2C, SPI}
enum TransferType {Command, Data}
type Direction = 'left' | 'left diagonal' | 'right' | 'right diagonal'
type Black = 0x00
type White = 0x01 | 0xff
type Color = Black | White
type Pixel = [number, number, Color]
interface OledOptions {
height?: number
width?: number
address?: number
microview?: boolean
secondaryPin?: number
resetPin?: number
data?: number
command?: number
}
interface Font {
monospace: boolean
width: number
height: number
fontData: number[]
lookup: string[]
}
interface ScreenConfig {
multiplex: number
compins: number
coloffset: number
}
interface SPIConfig {
dcPin: number
ssPin: number
rstPin: number
clkPin: number
mosiPin: number
}
export = class Oled {
// Configuration
private readonly HEIGHT: number
private readonly WIDTH: number
private readonly ADDRESS: number
private readonly PROTOCOL: Protocol
private readonly MICROVIEW: boolean
private readonly SECONDARYPIN: number
private readonly RESETPIN: number
private readonly DATA: number
private readonly COMMAND: number
private readonly board: Board
private readonly five: any
private readonly screenConfig: ScreenConfig
private readonly SPIconfig: SPIConfig
private dcPin: Pin
private ssPin: Pin
private clkPin: Pin
private mosiPin: Pin
private rstPin: Pin
// Commands
private static readonly DISPLAY_OFF: number = 0xAE
private static readonly DISPLAY_ON: number = 0xAF
private static readonly SET_DISPLAY_CLOCK_DIV: number = 0xD5
private static readonly SET_MULTIPLEX: number = 0xA8
private static readonly SET_DISPLAY_OFFSET: number = 0xD3
private static readonly SET_START_LINE: number = 0x00
private static readonly CHARGE_PUMP: number = 0x8D
private static readonly EXTERNAL_VCC: boolean = false
private static readonly MEMORY_MODE: number = 0x20
private static readonly SEG_REMAP: number = 0xA1 // using 0xA0 will flip screen
private static readonly COM_SCAN_DEC: number = 0xC8
private static readonly COM_SCAN_INC: number = 0xC0
private static readonly SET_COM_PINS: number = 0xDA
private static readonly SET_CONTRAST: number = 0x81
private static readonly SET_PRECHARGE: number = 0xd9
private static readonly SET_VCOM_DETECT: number = 0xDB
private static readonly DISPLAY_ALL_ON_RESUME: number = 0xA4
private static readonly NORMAL_DISPLAY: number = 0xA6
private static readonly COLUMN_ADDR: number = 0x21
private static readonly PAGE_ADDR: number = 0x22
private static readonly INVERT_DISPLAY: number = 0xA7
private static readonly ACTIVATE_SCROLL: number = 0x2F
private static readonly DEACTIVATE_SCROLL: number = 0x2E
private static readonly SET_VERTICAL_SCROLL_AREA: number = 0xA3
private static readonly RIGHT_HORIZONTAL_SCROLL: number = 0x26
private static readonly LEFT_HORIZONTAL_SCROLL: number = 0x27
private static readonly VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL: number = 0x29
private static readonly VERTICAL_AND_LEFT_HORIZONTAL_SCROLL: number = 0x2A
// State
private buffer: Buffer
private cursor_x: number
private cursor_y: number
private dirtyBytes: number[]
public constructor (board: Board, five: any, opts: OledOptions) {
this.HEIGHT = opts.height || 32
this.WIDTH = opts.width || 128
this.ADDRESS = opts.address || 0x3C
this.PROTOCOL = (opts.address) ? Protocol.I2C : Protocol.SPI
this.MICROVIEW = opts.microview || false
this.SECONDARYPIN = opts.secondaryPin || 12
this.RESETPIN = opts.resetPin || 4
this.DATA = opts.data || 0x40
this.COMMAND = opts.command || 0x00
this.cursor_x = 0
this.cursor_y = 0
// new blank buffer
this.buffer = Buffer.alloc((this.WIDTH * this.HEIGHT) / 8)
this.buffer.fill(0x00)
this.dirtyBytes = []
// this is necessary as we're not natively sitting within johnny-five lib
this.board = board
this.five = five
const config: { [screenSize: string]: ScreenConfig; } = {
'128x32': {
'multiplex': 0x1F,
'compins': 0x02,
'coloffset': 0
},
'128x64': {
'multiplex': 0x3F,
'compins': 0x12,
'coloffset': 0
},
'96x16': {
'multiplex': 0x0F,
'compins': 0x2,
'coloffset': 0
},
// this is blended microview / normal 64 x 48, currently wip
'64x48': {
'multiplex': 0x2F,
'compins': 0x12,
'coloffset': (this.MICROVIEW) ? 32 : 0
}
}
// microview is wip
if (this.MICROVIEW) {
// microview spi pins
this.SPIconfig = {
'dcPin': 8,
'ssPin': 10,
'rstPin': 7,
'clkPin': 13,
'mosiPin': 11
}
} else if (this.PROTOCOL === Protocol.SPI) {
// generic spi pins
this.SPIconfig = {
'dcPin': 11,
'ssPin': this.SECONDARYPIN,
'rstPin': 13,
'clkPin': 10,
'mosiPin': 9
}
}
const screenSize = `${this.WIDTH}x${this.HEIGHT}`
this.screenConfig = config[screenSize]
if (this.PROTOCOL === Protocol.I2C) {
this._setUpI2C(opts)
} else {
this._setUpSPI()
}
this._initialise()
}
private _initialise (): void {
// sequence of bytes to initialise with
const initSeq = [
Oled.DISPLAY_OFF,
Oled.SET_DISPLAY_CLOCK_DIV, 0x80,
Oled.SET_MULTIPLEX, this.screenConfig.multiplex, // set the last value dynamically based on screen size requirement
Oled.SET_DISPLAY_OFFSET, 0x00, // sets offset pro to 0
Oled.SET_START_LINE,
Oled.CHARGE_PUMP, 0x14, // charge pump val
Oled.MEMORY_MODE, 0x00, // 0x0 act like ks0108
Oled.SEG_REMAP, // screen orientation
Oled.COM_SCAN_DEC, // screen orientation change to INC to flip
Oled.SET_COM_PINS, this.screenConfig.compins, // com pins val sets dynamically to match each screen size requirement
Oled.SET_CONTRAST, 0x8F, // contrast val
Oled.SET_PRECHARGE, 0xF1, // precharge val
Oled.SET_VCOM_DETECT, 0x40, // vcom detect
Oled.DISPLAY_ALL_ON_RESUME,
Oled.NORMAL_DISPLAY,
Oled.DISPLAY_ON
]
// write init seq commands
for (let i = 0; i < initSeq.length; i++) {
this._transfer(TransferType.Command, initSeq[i])
}
}
private _setUpSPI (): void {
// set up spi pins
this.dcPin = new this.five.Pin(this.SPIconfig.dcPin)
this.ssPin = new this.five.Pin(this.SPIconfig.ssPin)
this.clkPin = new this.five.Pin(this.SPIconfig.clkPin)
this.mosiPin = new this.five.Pin(this.SPIconfig.mosiPin)
// reset won't be used as it causes a bunch of default initialisations
this.rstPin = new this.five.Pin(this.SPIconfig.rstPin)
// get the screen out of default mode
this.rstPin.low()
this.rstPin.high()
// Set SS to high so a connected chip will be "deselected" by default
this.ssPin.high()
}
private _setUpI2C (opts: OledOptions): void {
// enable i2C in firmata
this.board.io.i2cConfig(opts)
// set up reset pin and hold high
this.rstPin = new this.five.Pin(this.RESETPIN)
this.rstPin.low()
this.rstPin.high()
}
// writes both commands and data buffers to this device
private _transfer (type: TransferType, val: number): void {
let control: number
if (type === TransferType.Data) {
control = this.DATA
} else if (type === TransferType.Command) {
control = this.COMMAND
} else {
return
}
if (this.PROTOCOL === Protocol.I2C) {
// send control and actual val
this.board.io.i2cWrite(this.ADDRESS, [control, val])
} else {
// send val via SPI, no control byte
this._writeSPI(val, type)
}
}
private _writeSPI (byte: number, mode: TransferType): void {
// set dc to low if command byte, high if data byte
if (mode === TransferType.Command) {
this.dcPin.low()
} else {
this.dcPin.high()
}
// select the device as secondary
this.ssPin.low()
for (let bit = 7; bit >= 0; bit--) {
// pull clock low
this.clkPin.low()
// shift out a bit for mosi
if (byte & (1 << bit)) {
this.mosiPin.high()
} else {
this.mosiPin.low()
}
// pull clock high to collect bit
this.clkPin.high()
}
// turn off ss so other devices can use SPI
// don't be an SPI hogging jerk basically
this.ssPin.high()
}
// read a byte from the oled
private _readI2C (fn: (data: number) => void): void {
this.board.io.i2cReadOnce(this.ADDRESS, 1, (data: number) => {
fn(data)
})
}
// sometimes the oled gets a bit busy with lots of bytes.
// Read the response byte to see if this is the case
private _waitUntilReady (callback: () => void): void {
const oled = this
const tick = (callback: () => void) => {
oled._readI2C((byte: number) => {
// read the busy byte in the response
const busy = byte >> 7 & 1
if (!busy) {
// if not busy, it's ready for callback
callback()
} else {
console.log('I\'m busy!')
setTimeout(tick, 0)
}
})
}
if (this.PROTOCOL === Protocol.I2C) {
setTimeout(() => { tick(callback) }, 0)
} else {
callback()
}
}
// set starting position of a text string on the oled
public setCursor (x: number, y: number): void {
this.cursor_x = x
this.cursor_y = y
}
private _invertColor(color: Color): Color {
return (color === 0) ? 1 : 0
}
// write text to the oled
public writeString (font: Font, size: number, string: string, color: Color, wrap: boolean, linespacing: number | null, sync?: boolean): void {
const immed = (typeof sync === 'undefined') ? true : sync
const wordArr = string.split(' ')
const len = wordArr.length
// start x offset at cursor pos
let offset = this.cursor_x
let padding = 0
const letspace = 1
const leading = linespacing || 2
// loop through words
for (let i = 0; i < len; i += 1) {
// put the word space back in
if (i < len -1 ) wordArr[i] += ' ';
const stringArr = wordArr[i].split('')
const slen = stringArr.length
const compare = (font.width * size * slen) + (size * (len - 1))
// wrap words if necessary
if (wrap && len > 1 && (offset >= (this.WIDTH - compare))) {
offset = 1
this.cursor_y += (font.height * size) + size + leading
this.setCursor(offset, this.cursor_y)
}
// loop through the array of each char to draw
for (let i = 0; i < slen; i += 1) {
// look up the position of the char, pull out the buffer slice
const charBuf = this._findCharBuf(font, stringArr[i])
// read the bits in the bytes that make up the char
const charBytes = this._readCharBytes(charBuf)
// draw the entire charactei
this._drawChar(font, charBytes, size, color, false)
// fills in background behind the text pixels so that it's easier to read the text
this.fillRect(offset - padding, this.cursor_y, padding, (font.height * size), this._invertColor(color), false)
// calc new x position for the next char, add a touch of padding too if it's a non space char
padding = (stringArr[i] === ' ') ? 0 : size + letspace
offset += (font.width * size) + padding
// wrap letters if necessary
if (wrap && (offset >= (this.WIDTH - font.width - letspace))) {
offset = 1
this.cursor_y += (font.height * size) + size + leading
}
// set the 'cursor' for the next char to be drawn, then loop again for next char
this.setCursor(offset, this.cursor_y)
}
}
if (immed) {
this._updateDirtyBytes(this.dirtyBytes)
}
}
// draw an individual character to the screen
private _drawChar (font: Font, byteArray: number[][], size: number, color: Color, sync?: boolean): void {
// take your positions...
const x = this.cursor_x
const y = this.cursor_y
let c = 0
let pagePos = 0
// loop through the byte array containing the hexes for the char
for (let i = 0; i < byteArray.length; i += 1) {
pagePos = Math.floor(i / font.width) * 8
for (let j = 0; j < 8; j += 1) {
// pull color out (invert the color if user chose black)
const pixelState = (byteArray[i][j] === 1) ? color : this._invertColor(color);
let xpos
let ypos
// standard font size
if (size === 1) {
xpos = x + c
ypos = y + j + pagePos
this.drawPixel([xpos, ypos, pixelState], false)
} else {
// MATH! Calculating pixel size multiplier to primitively scale the font
xpos = x + (i * size)
ypos = y + (j * size)
this.fillRect(xpos, ypos, size, size, pixelState, false)
}
}
c = (c < font.width - 1) ? c += 1 : 0
}
}
// get character bytes from the supplied font object in order to send to framebuffer
private _readCharBytes (byteArray: number[]): number[][] {
let bitArr = []
const bitCharArr = []
// loop through each byte supplied for a char
for (let i = 0; i < byteArray.length; i += 1) {
// set current byte
const byte = byteArray[i]
// read each byte
for (let j = 0; j < 8; j += 1) {
// shift bits right until all are read
const bit = byte >> j & 1
bitArr.push(bit)
}
// push to array containing flattened bit sequence
bitCharArr.push(bitArr)
// clear bits for next byte
bitArr = []
}
return bitCharArr
}
// find where the character exists within the font object
private _findCharBuf (font: Font, c: string): number[] {
const charLength = Math.ceil((font.width * font.height) / 8)
// use the lookup array as a ref to find where the current char bytes start
const cBufPos = font.lookup.indexOf(c) * charLength
// slice just the current char's bytes out of the fontData array and return
return font.fontData.slice(cBufPos, cBufPos + charLength)
}
// send the entire framebuffer to the oled
public update (): void {
// wait for oled to be ready
this._waitUntilReady(() => {
// set the start and endbyte locations for oled display update
const displaySeq = [
Oled.COLUMN_ADDR,
this.screenConfig.coloffset,
this.screenConfig.coloffset + this.WIDTH - 1, // column start and end address
Oled.PAGE_ADDR, 0, (this.HEIGHT / 8) - 1 // page start and end address
]
const displaySeqLen = displaySeq.length
const bufferLen = this.buffer.length
// send intro seq
for (let i = 0; i < displaySeqLen; i += 1) {
this._transfer(TransferType.Command, displaySeq[i])
}
// write buffer data
for (let i = 0; i < bufferLen; i += 1) {
this._transfer(TransferType.Data, this.buffer[i])
}
})
// now that all bytes are synced, reset dirty state
this.dirtyBytes = []
}
// send dim display command to oled
public dimDisplay (bool: boolean): void {
let contrast: number
if (bool) {
contrast = 0 // Dimmed display
} else {
contrast = 0xCF // Bright display
}
this._transfer(TransferType.Command, Oled.SET_CONTRAST)
this._transfer(TransferType.Command, contrast)
}
// turn oled off
public turnOffDisplay (): void {
this._transfer(TransferType.Command, Oled.DISPLAY_OFF)
}
// turn oled on
public turnOnDisplay (): void {
this._transfer(TransferType.Command, Oled.DISPLAY_ON)
}
// clear all pixels currently on the display
public clearDisplay (sync?: boolean): void {
const immed = (typeof sync === 'undefined') ? true : sync
// write off pixels
for (let i = 0; i < this.buffer.length; i += 1) {
if (this.buffer[i] !== 0x00) {
this.buffer[i] = 0x00
if (this.dirtyBytes.indexOf(i) === -1) {
this.dirtyBytes.push(i)
}
}
}
if (immed) {
this._updateDirtyBytes(this.dirtyBytes)
}
}
// invert pixels on oled
public invertDisplay (bool: boolean): void {
if (bool) {
this._transfer(TransferType.Command, Oled.INVERT_DISPLAY) // inverted
} else {
this._transfer(TransferType.Command, Oled.NORMAL_DISPLAY) // non inverted
}
}
// draw an image pixel array on the screen
public drawBitmap (pixels: Color[], sync?: boolean): void {
const immed = (typeof sync === 'undefined') ? true : sync
for (let i = 0; i < pixels.length; i++) {
const x = Math.floor(i % this.WIDTH)
const y = Math.floor(i / this.WIDTH)
this.drawPixel([x, y, pixels[i]], false)
}
if (immed) {
this._updateDirtyBytes(this.dirtyBytes)
}
}
private _isSinglePixel(pixels: Pixel | Pixel[]): pixels is Pixel {
return typeof pixels[0] !== 'object'
}
// draw one or many pixels on oled
public drawPixel (pixels: Pixel | Pixel[], sync?: boolean): void {
const immed = (typeof sync === 'undefined') ? true : sync
// handle lazy single pixel case
if (this._isSinglePixel(pixels)) pixels = [pixels]
pixels.forEach((el: Pixel) => {
// return if the pixel is out of range
const [ x, y, color ] = el
if (x > this.WIDTH || y > this.HEIGHT) return
// thanks, Martin Richards.
// I wanna can this, this tool is for devs who get 0 indexes
// x -= 1; y -=1;
let byte = 0
const page = Math.floor(y / 8)
const pageShift = 0x01 << (y - 8 * page);
// is the pixel on the first row of the page?
(page === 0) ? byte = x : byte = x + (this.WIDTH * page)
// colors! Well, monochrome.
if (color === 0) {
// BLACK pixel
this.buffer[byte] &= ~pageShift
} else {
// WHITE pixel
this.buffer[byte] |= pageShift
}
// push byte to dirty if not already there
if (this.dirtyBytes.indexOf(byte) === -1) {
this.dirtyBytes.push(byte)
}
}, this)
if (immed) {
this._updateDirtyBytes(this.dirtyBytes)
}
}
// looks at dirty bytes, and sends the updated bytes to the display
private _updateDirtyBytes (byteArray: number[]): void {
const blen = byteArray.length
this._waitUntilReady(() => {
let pageStart = Infinity
let pageEnd = 0
let colStart = Infinity
let colEnd = 0
let any = false
// iterate through dirty bytes
for (let i = 0; i < blen; i += 1) {
const b = byteArray[i]
if ((b >= 0) && (b < this.buffer.length)) {
const page = b / this.WIDTH | 0
if (page < pageStart) pageStart = page
if (page > pageEnd) pageEnd = page
const col = b % this.WIDTH
if (col < colStart) colStart = col
if (col > colEnd) colEnd = col
any = true
}
}
if (!any) return
const displaySeq = [
Oled.COLUMN_ADDR, colStart, colEnd, // column start and end address
Oled.PAGE_ADDR, pageStart, pageEnd // page start and end address
]
const displaySeqLen = displaySeq.length
// send intro seq
for (let i = 0; i < displaySeqLen; i += 1) {
this._transfer(TransferType.Command, displaySeq[i])
}
// send byte, then move on to next byte
for (let i = pageStart; i <= pageEnd; i += 1) {
for (let j = colStart; j <= colEnd; j += 1) {
this._transfer(TransferType.Data, this.buffer[this.WIDTH * i + j])
}
}
})
// now that all bytes are synced, reset dirty state
this.dirtyBytes = []
}
// using Bresenham's line algorithm
public drawLine (x0: number, y0: number, x1: number, y1: number, color: Color, sync?: boolean): void {
const immed = (typeof sync === 'undefined') ? true : sync
const dx = Math.abs(x1 - x0)
const sx = x0 < x1 ? 1 : -1
const dy = Math.abs(y1 - y0)
const sy = y0 < y1 ? 1 : -1
let err = (dx > dy ? dx : -dy) / 2
while (true) {
this.drawPixel([x0, y0, color], false)
if (x0 === x1 && y0 === y1) break
const e2 = err
if (e2 > -dx) { err -= dy; x0 += sx }
if (e2 < dy) { err += dx; y0 += sy }
}
if (immed) {
this._updateDirtyBytes(this.dirtyBytes)
}
}
// Draw an outlined rectangle
public drawRect (x: number, y: number, w: number, h: number, color: Color, sync?: boolean): void {
const immed = (typeof sync === 'undefined') ? true : sync
// top
this.drawLine(x, y, x + w, y, color, false)
// left
this.drawLine(x, y + 1, x, y + h - 1, color, false)
// right
this.drawLine(x + w, y + 1, x + w, y + h - 1, color, false)
// bottom
this.drawLine(x, y + h - 1, x + w, y + h - 1, color, false)
if (immed) {
this._updateDirtyBytes(this.dirtyBytes)
}
};
// draw a filled rectangle on the oled
public fillRect (x: number, y: number, w: number, h: number, color: Color, sync?: boolean): void {
const immed = (typeof sync === 'undefined') ? true : sync
// one iteration for each column of the rectangle
for (let i = x; i < x + w; i += 1) {
// draws a vert line
this.drawLine(i, y, i, y + h - 1, color, false)
}
if (immed) {
this._updateDirtyBytes(this.dirtyBytes)
}
}
/**
* Draw a circle outline
*
* This method is ad verbatim translation from the corresponding
* method on the Adafruit GFX library
* https://github.com/adafruit/Adafruit-GFX-Library
*/
public drawCircle (x0: number, y0: number, r: number, color: Color, sync?: boolean): void {
const immed = (typeof sync === 'undefined') ? true : sync
let f = 1 - r
let ddF_x = 1
let ddF_y = -2 * r
let x = 0
let y = r
this.drawPixel(
[[x0, y0 + r, color],
[x0, y0 - r, color],
[x0 + r, y0, color],
[x0 - r, y0, color]],
false
)
while (x < y) {
if (f >= 0) {
y--
ddF_y += 2
f += ddF_y
}
x++
ddF_x += 2
f += ddF_x
this.drawPixel(
[[x0 + x, y0 + y, color],
[x0 - x, y0 + y, color],
[x0 + x, y0 - y, color],
[x0 - x, y0 - y, color],
[x0 + y, y0 + x, color],
[x0 - y, y0 + x, color],
[x0 + y, y0 - x, color],
[x0 - y, y0 - x, color]],
false
)
}
if (immed) {
this._updateDirtyBytes(this.dirtyBytes)
}
};
// activate scrolling for rows start through stop
public startScroll (dir: Direction, start: number, stop: number): void {
const cmdSeq: number[] = []
switch (dir) {
case 'right':
cmdSeq.push(Oled.RIGHT_HORIZONTAL_SCROLL); break
case 'left':
cmdSeq.push(Oled.LEFT_HORIZONTAL_SCROLL); break
case 'left diagonal':
cmdSeq.push(
Oled.SET_VERTICAL_SCROLL_AREA,
0x00,
this.HEIGHT,
Oled.VERTICAL_AND_LEFT_HORIZONTAL_SCROLL,
0x00,
start,
0x00,
stop,
0x01,
Oled.ACTIVATE_SCROLL
)
break
case 'right diagonal':
cmdSeq.push(
Oled.SET_VERTICAL_SCROLL_AREA,
0x00,
this.HEIGHT,
Oled.VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL,
0x00,
start,
0x00,
stop,
0x01,
Oled.ACTIVATE_SCROLL
)
break
}
this._waitUntilReady(() => {
if (dir === 'right' || dir === 'left') {
cmdSeq.push(
0x00, start,
0x00, stop,
0x00, 0xFF,
Oled.ACTIVATE_SCROLL
)
}
for (let i = 0; i < cmdSeq.length; i += 1) {
this._transfer(TransferType.Command, cmdSeq[i])
}
})
}
// stop scrolling display contents
public stopScroll () {
this._transfer(TransferType.Command, Oled.DEACTIVATE_SCROLL) // stahp
}
} | the_stack |
import { CompilerHost, log } from '@bazel/typescript';
import * as tsSimple from 'ts-simple-type';
import * as ts from 'typescript';
import * as svelte from '@svelte-ts/common';
import {
createNonExistentPropertyDiagnostic,
createComponentTypesNotAssignableDiagnostic,
createDeclarationNotFoundDiagnostic,
} from './diagnostics';
export class SvelteTypeChecker {
constructor(
private readonly tsHost: ts.CompilerHost,
private readonly typeChecker: ts.TypeChecker,
private readonly rootDir: string,
private readonly files: string[],
private readonly compilerOpts: ts.CompilerOptions,
private readonly compilationCache: svelte.CompilationCache,
) {}
private isAssignableToType(
typeA: ts.Type | ts.Node,
typeB: ts.Type | ts.Node,
): boolean {
return tsSimple.isAssignableToType(typeA, typeB, this.typeChecker, {
strictFunctionTypes: this.compilerOpts.strictFunctionTypes,
strictNullChecks: this.compilerOpts.strictNullChecks,
strict: this.compilerOpts.strict,
});
}
private getDeclarationByNode(
declarations: ts.NamedDeclaration[],
node: svelte.Identifier | svelte.Component,
): ts.NamedDeclaration {
return declarations.find(
declaration => svelte.getDeclarationName(declaration) === node.name,
);
}
private gatherPropertyDiagnostics(
memberNames: string[],
declarationNames: string[],
declarations: ts.NamedDeclaration[],
component: ts.ClassDeclaration,
compiledSourceFile: ts.SourceFile,
node: svelte.Node,
): svelte.Diagnostic[] {
const diagnostics: svelte.Diagnostic[] = [];
// Attribute identifier does not exist
// This is the value we have to check if exist on the component
if (svelte.isIdentifier(node)) {
// FIX: Needs to find an actual declaration
const declaration = this.getDeclarationByNode(declarations, node);
// Identifier does not exist in context
if (!declaration) {
diagnostics.push(
createDeclarationNotFoundDiagnostic(
declarationNames,
node,
compiledSourceFile,
),
);
} else {
// Check if identifier is an object
// and if identifier contains strict member names
const declarationType = this.typeChecker.getTypeAtLocation(declaration);
const componentType = this.typeChecker.getTypeAtLocation(component);
if (svelte.isSpread(node.parent)) {
/**
* When attributes are spread, instead show that type is not assignable to component
*/
if (!this.isAssignableToType(componentType, declarationType)) {
// TODO
// log(this.typeChecker.typeToString(type));
// log(this.typeChecker.typeToString(compType));
/*const properties = type.getProperties().map(property => property.getName());
type.getProperties().forEach(property => {
property.valueDeclaration
});*/
/*properties.forEach(property => {
diagnostics.push(
createNonExistentPropertyDiagnostic(
memberNames,
property.,
component,
sourceFile,
),
);
});*/
//log(type.symbol.declarations.reduce((names, { properties }) => [...names, ...properties.map(property => getIdentifierName(property))], []));
}
} else {
const property = componentType
.getProperties()
.find(prop => prop.escapedName === node.name);
const propertyType = this.typeChecker.getTypeAtLocation(
property.valueDeclaration,
);
if (!this.isAssignableToType(propertyType, declarationType)) {
diagnostics.push(
createComponentTypesNotAssignableDiagnostic(
node,
declarationType,
node as any,
component,
propertyType,
compiledSourceFile,
this.typeChecker,
),
);
}
}
}
}
if (svelte.isAttribute(node)) {
// check that attribute exists
if (!memberNames.includes(node.name)) {
diagnostics.push(
createNonExistentPropertyDiagnostic(
memberNames,
node,
component,
compiledSourceFile,
),
);
} else {
node.value.forEach(value => {
diagnostics.push(
...this.gatherPropertyDiagnostics(
memberNames,
declarationNames,
declarations,
component,
compiledSourceFile,
value,
),
);
});
}
// if attribute name is the same as identifier, suggest using a short hand attribute instead
// name={name} can be replaced with the {name} shorthand
// we need a way to link to stuff in documentation
// log(value);
// Validates that identifier exists
// and if it does, then validate against the given type
/*if (value.expression && !identifiersHasNode(value.expression)) {
diagnostics.push(
createDeclarationNotFoundDiagnostic(
identifierNames,
value.expression,
sourceFile,
),
);
} else {
}*/
}
// if it's a short hand, check that both the identifier exists, and that the attribute does
/*if (isAttributeShortHand(node)) {
const identifier = getIdentifierByNode(node.expression);
// Identifier does not exist in context
if (!identifier) {
diagnostics.push(
createDeclarationNotFoundDiagnostic(
identifierNames,
node.expression,
sourceFile,
),
);
}
if (!memberNames.includes(node.expression.name)) {
diagnostics.push(
createNonExistentPropertyDiagnostic(
memberNames,
node.expression,
component,
sourceFile,
),
);
}
}*/
if (
svelte.isMustacheTag(node) ||
svelte.isSpread(node) ||
svelte.isAttributeShortHand(node)
) {
node.expression.parent = node;
diagnostics.push(
...this.gatherPropertyDiagnostics(
memberNames,
declarationNames,
declarations,
component,
compiledSourceFile,
node.expression,
),
);
}
return diagnostics;
}
// Gathers diagnostics for attributes on Svelte components
private gatherComponentPropertyDiagnostics(
scriptSourceFile: ts.SourceFile,
compiledSourceFile: ts.SourceFile,
componentDeclaration: ts.ClassDeclaration,
component: svelte.Component,
): svelte.Diagnostic[] {
// FIX: Needs to be declarations
const declarations = svelte.collectDeepNodes<ts.VariableDeclaration>(
scriptSourceFile,
ts.SyntaxKind.VariableDeclaration,
);
const memberNames = componentDeclaration.members.map(member =>
svelte.getDeclarationName(member),
);
const declarationNames = declarations.map(identifier =>
svelte.getDeclarationName(identifier),
);
// this should be recursive
return component.attributes.reduce(
(diagnostics, node) => {
node.parent = component;
return [
...diagnostics,
...this.gatherPropertyDiagnostics(
memberNames,
declarationNames,
declarations,
componentDeclaration,
compiledSourceFile,
node,
),
];
},
[] as svelte.Diagnostic[],
);
}
private gatherComponentDiagnostics(
scriptSourceFile: ts.SourceFile,
compiledSourceFile: ts.SourceFile,
node: svelte.Node,
): svelte.Diagnostic[] {
const componentNodes = svelte.getComponents(node);
const diagnostics: svelte.Diagnostic[] = [];
const getComponentNode = (
node: ts.ImportClause | ts.ImportSpecifier,
): svelte.Component =>
componentNodes.find(
({ name }) => name === svelte.getDeclarationName(node),
);
const removeComponentNode = (
componentNode: svelte.Component,
): svelte.Component[] =>
componentNodes.splice(componentNodes.indexOf(componentNode), 1);
if (componentNodes.length) {
const allImports = svelte.getAllImports(scriptSourceFile);
const componentImports = new Map<
svelte.Component,
ts.ImportClause | ts.ImportSpecifier
>();
const addComponentImport = (
node: ts.ImportClause | ts.ImportSpecifier,
) => {
const componentNode = getComponentNode(node);
// there can be either propertyName or name which reflects the real name of the import
// if it is a named import, it'll have a "propertyName", otherwise the real import will be "name"
if (componentNode) {
componentImports.set(componentNode, node);
removeComponentNode(componentNode);
}
};
// TODO: Check that components have been imported
for (const { importClause } of allImports) {
if (ts.isNamedImports(importClause.namedBindings)) {
for (const specifier of importClause.namedBindings.elements) {
// there can be either propertyName or name which reflects the real name of the import
// if it is a named import, it'll have a "propertyName", otherwise the real import will be "name"
addComponentImport(specifier);
}
} else {
addComponentImport(importClause);
}
}
componentNodes.forEach(component => {
const messageText = svelte.formatDiagnosticMessageTexts([
// Identifier
`Import declaration for '${component.name}' cannot be found.`,
]);
diagnostics.push({
file: compiledSourceFile,
category: ts.DiagnosticCategory.Error,
start: component.start,
length: component.end - component.start,
code: component.type,
messageText,
});
});
for (const [componentNode, declaration] of componentImports.entries()) {
const type = this.typeChecker.getTypeAtLocation(declaration);
const componentDeclaration = svelte.findComponentDeclaration(
type.symbol.declarations,
);
// TODO: Type check if import is a class which extends SvelteComponent/SvelteComponentDev
// TODO: Type check methods
// TODO: Type check props
if (componentDeclaration) {
// @ts-ignore
diagnostics.push(
...this.gatherComponentPropertyDiagnostics(
scriptSourceFile,
compiledSourceFile,
componentDeclaration,
componentNode,
),
);
}
// @ts-ignore
//log(type.symbol.heritageClauses);
/*if (!ts.isClassDeclaration) {
throw new Error('is not a class declaration');
} else {
if (symbol) {
log((identifier as ts.ClassLikeDeclarationBase).heritageClauses);
// log(symbol.valueDeclaration.members);
} else {
}
}*/
//log(getComponentNode(identifier));
/*const moduleId = this.bazelHost.fileNameToModuleId(
sourceFile.fileName,
);
const containingFile = path.join(this.bazelBin, moduleId);
const { resolvedModule } = ts.resolveModuleName(
moduleName,
containingFile,
this.compilerOpts,
this.bazelHost,
);*/
/*if (resolvedModule) {
const sourceFile = this.bazelHost.getSourceFile(
resolvedModule.resolvedFileName,
this.compilerOpts.target,
);
}*/
}
}
return diagnostics;
}
// private gatherIfBlockDiagnostics(node: IfBlock) {}
private getCompiledSourceFile(
sourceFile: ts.SourceFile,
compiledSource: string,
): ts.SourceFile {
const fileName = svelte.getInputFileFromOutputFile(
sourceFile.fileName,
this.rootDir,
this.files,
);
const source = this.tsHost
.readFile(fileName)
.replace(svelte.SCRIPT_TAG, `<script>${compiledSource}</script>`);
return ts.createSourceFile(fileName, source, this.compilerOpts.target);
}
private gatherNodeDiagnostics(
sourceFile: ts.SourceFile,
compiledSvelteFile: ts.SourceFile,
node: svelte.Node,
): svelte.Diagnostic[] {
const diagnostics: svelte.Diagnostic[] = [];
if (svelte.isInlineComponent(node)) {
diagnostics.push(
...this.gatherComponentDiagnostics(
sourceFile,
compiledSvelteFile,
node,
),
);
}
if (node.children) {
node.children.forEach(child => {
// HINT: Children will have node as parent, so referencing it for checking object property access will be fine
child.parent = node;
diagnostics.push(
...this.gatherNodeDiagnostics(sourceFile, compiledSvelteFile, child),
);
});
}
return diagnostics;
}
gatherAllDiagnostics(scriptSourceFile: ts.SourceFile): ts.Diagnostic[] {
if (!this.compilationCache.has(scriptSourceFile.fileName)) {
throw new Error(
`Script source file ${scriptSourceFile.fileName} doesn't exist in CompilationCache`,
);
}
const [compiledSource, compilation] = this.compilationCache.get(
scriptSourceFile.fileName,
);
const compiledSourceFile = this.getCompiledSourceFile(
scriptSourceFile,
compiledSource,
);
// HINT: There'll always be a top level fragment node
return <any[]>(
this.gatherNodeDiagnostics(
scriptSourceFile,
compiledSourceFile,
compilation.ast.html,
)
);
}
} | the_stack |
import Docker, { Container, ContainerInfo } from "dockerode";
import Joi from "joi";
import tar from "tar-stream";
import { EventEmitter } from "events";
import {
LogLevelDesc,
Logger,
LoggerProvider,
Bools,
} from "@hyperledger/cactus-common";
import { ITestLedger } from "../i-test-ledger";
import { Streams } from "../common/streams";
import { Containers } from "../common/containers";
/*
* Contains options for Postgres container
*/
export interface IPostgresTestContainerConstructorOptions {
readonly imageVersion?: string;
readonly imageName?: string;
readonly postgresPort?: number;
readonly envVars?: string[];
readonly logLevel?: LogLevelDesc;
readonly emitContainerLogs?: boolean;
}
/*
* Provides default options for Postgres container
*/
export const POSTGRES_TEST_CONTAINER_DEFAULT_OPTIONS = Object.freeze({
imageVersion: "9.5-alpine",
imageName: "postgres",
postgresPort: 5432,
envVars: ["POSTGRES_USER=postgres", "POSTGRES_PASSWORD=my-secret-password"],
});
/*
* Provides validations for Postgres container's options
*/
export const POSTGRES_TEST_CONTAINER_OPTIONS_JOI_SCHEMA: Joi.Schema = Joi.object().keys(
{
imageVersion: Joi.string().min(5).required(),
imageName: Joi.string().min(1).required(),
postgresPort: Joi.number().min(1024).max(65535).required(),
envVars: Joi.array().allow(null).required(),
},
);
export class PostgresTestContainer implements ITestLedger {
public readonly imageVersion: string;
public readonly imageName: string;
public readonly postgresPort: number;
public readonly envVars: string[];
public readonly emitContainerLogs: boolean;
private readonly log: Logger;
private container: Container | undefined;
private containerId: string | undefined;
constructor(
public readonly options: IPostgresTestContainerConstructorOptions = {},
) {
if (!options) {
throw new TypeError(`PostgresTestContainer#ctor options was falsy.`);
}
this.imageVersion =
options.imageVersion ||
POSTGRES_TEST_CONTAINER_DEFAULT_OPTIONS.imageVersion;
this.imageName =
options.imageName || POSTGRES_TEST_CONTAINER_DEFAULT_OPTIONS.imageName;
this.postgresPort =
options.postgresPort ||
POSTGRES_TEST_CONTAINER_DEFAULT_OPTIONS.postgresPort;
this.envVars =
options.envVars || POSTGRES_TEST_CONTAINER_DEFAULT_OPTIONS.envVars;
this.emitContainerLogs = Bools.isBooleanStrict(options.emitContainerLogs)
? (options.emitContainerLogs as boolean)
: true;
this.validateConstructorOptions();
const label = "postgres-test-container";
const level = options.logLevel || "INFO";
this.log = LoggerProvider.getOrCreate({ level, label });
}
public getContainer(): Container {
const fnTag = "PostgresTestContainer#getContainer()";
if (!this.container) {
throw new Error(`${fnTag} container not yet started by this instance.`);
} else {
return this.container;
}
}
public getimageName(): string {
return `${this.imageName}:${this.imageVersion}`;
}
public async getPostgresPortHost(): Promise<string> {
const ipAddress = "127.0.0.1";
const hostPort: number = await this.getPostgresPort();
return `http://${ipAddress}:${hostPort}`;
}
public async getFileContents(filePath: string): Promise<string> {
const response: any = await this.getContainer().getArchive({
path: filePath,
});
const extract: tar.Extract = tar.extract({ autoDestroy: true });
return new Promise((resolve, reject) => {
let fileContents = "";
extract.on("entry", async (header: any, stream, next) => {
stream.on("error", (err: Error) => {
reject(err);
});
const chunks: string[] = await Streams.aggregate<string>(stream);
fileContents += chunks.join("");
stream.resume();
next();
});
extract.on("finish", () => {
resolve(fileContents);
});
response.pipe(extract);
});
}
public async start(): Promise<Container> {
const imageFqn = this.getimageName();
if (this.container) {
await this.container.stop();
await this.container.remove();
}
const docker = new Docker();
this.log.debug(`Pulling container image ${imageFqn} ...`);
await this.pullContainerImage(imageFqn);
this.log.debug(`Pulled ${imageFqn} OK. Starting container...`);
return new Promise<Container>((resolve, reject) => {
const eventEmitter: EventEmitter = docker.run(
imageFqn,
[],
[],
{
Env: this.envVars,
Healthcheck: {
Test: ["CMD-SHELL", "pg_isready -U postgres"],
Interval: 1000000000, // 1 second
Timeout: 3000000000, // 3 seconds
Retries: 299,
StartPeriod: 3000000000, // 3 seconds
},
HostConfig: {
PublishAllPorts: true,
AutoRemove: true,
},
},
{},
(err: unknown) => {
if (err) {
reject(err);
}
},
);
eventEmitter.once("start", async (container: Container) => {
this.log.debug(`Started container OK. Waiting for healthcheck...`);
this.container = container;
this.containerId = container.id;
if (this.emitContainerLogs) {
const logOptions = { follow: true, stderr: true, stdout: true };
const logStream = await container.logs(logOptions);
logStream.on("data", (data: Buffer) => {
this.log.debug(`[${imageFqn}] %o`, data.toString("utf-8"));
});
}
try {
await this.waitForHealthCheck();
this.log.debug(`Healthcheck passing OK.`);
resolve(container);
} catch (ex) {
reject(ex);
}
});
});
}
public async waitForHealthCheck(timeoutMs = 180000): Promise<void> {
const fnTag = "PostgresTestContainer#waitForHealthCheck()";
const startedAt = Date.now();
let isHealthy = false;
do {
if (Date.now() >= startedAt + timeoutMs) {
throw new Error(`${fnTag} timed out (${timeoutMs}ms)`);
}
const containerInfo = await this.getContainerInfo();
this.log.debug(`ContainerInfo.Status=%o`, containerInfo.Status);
this.log.debug(`ContainerInfo.State=%o`, containerInfo.State);
isHealthy = containerInfo.Status.endsWith("(healthy)");
if (!isHealthy) {
await new Promise((resolve2) => setTimeout(resolve2, 1000));
}
} while (!isHealthy);
}
public stop(): Promise<unknown> {
return Containers.stop(this.container as Container);
}
public destroy(): Promise<unknown> {
const fnTag = "PostgresTestContainer#destroy()";
if (this.container) {
return this.container.remove();
} else {
const ex = new Error(`${fnTag} Container not found, nothing to destroy.`);
return Promise.reject(ex);
}
}
protected async getContainerInfo(): Promise<ContainerInfo> {
const docker = new Docker();
const image = this.getimageName();
const containerInfos = await docker.listContainers({});
let aContainerInfo;
if (this.containerId !== undefined) {
aContainerInfo = containerInfos.find((ci) => ci.Id === this.containerId);
}
if (aContainerInfo) {
return aContainerInfo;
} else {
throw new Error(
`PostgresTestContainer#getContainerInfo() no image "${image}"`,
);
}
}
public async getPostgresPort(): Promise<number> {
const fnTag = "PostgresTestContainer#getPostgresPort()";
const aContainerInfo = await this.getContainerInfo();
const { postgresPort: thePort } = this;
const { Ports: ports } = aContainerInfo;
if (ports.length < 1) {
throw new Error(`${fnTag} no ports exposed or mapped at all`);
}
const mapping = ports.find((x) => x.PrivatePort === thePort);
if (mapping) {
if (!mapping.PublicPort) {
throw new Error(`${fnTag} port ${thePort} mapped but not public`);
} else if (mapping.IP !== "0.0.0.0") {
throw new Error(`${fnTag} port ${thePort} mapped to localhost`);
} else {
return mapping.PublicPort;
}
} else {
throw new Error(`${fnTag} no mapping found for ${thePort}`);
}
}
public async getContainerIpAddress(): Promise<string> {
const fnTag = "PostgresTestContainer#getContainerIpAddress()";
const aContainerInfo = await this.getContainerInfo();
if (aContainerInfo) {
const { NetworkSettings } = aContainerInfo;
const networkNames: string[] = Object.keys(NetworkSettings.Networks);
if (networkNames.length < 1) {
throw new Error(`${fnTag} container not connected to any networks`);
} else {
// return IP address of container on the first network that we found
// it connected to. Make this configurable?
return NetworkSettings.Networks[networkNames[0]].IPAddress;
}
} else {
throw new Error(`${fnTag} cannot find image: ${this.imageName}`);
}
}
private pullContainerImage(containerNameAndTag: string): Promise<any[]> {
return new Promise((resolve, reject) => {
const docker = new Docker();
docker.pull(containerNameAndTag, (pullError: any, stream: any) => {
if (pullError) {
reject(pullError);
} else {
docker.modem.followProgress(
stream,
(progressError: any, output: any[]) => {
if (progressError) {
reject(progressError);
} else {
resolve(output);
}
},
);
}
});
});
}
private validateConstructorOptions(): void {
const validationResult = POSTGRES_TEST_CONTAINER_OPTIONS_JOI_SCHEMA.validate(
{
imageVersion: this.imageVersion,
imageName: this.imageName,
postgresPort: this.postgresPort,
envVars: this.envVars,
},
);
if (validationResult.error) {
throw new Error(
`PostgresTestContainer#ctor ${validationResult.error.annotate()}`,
);
}
}
} | the_stack |
import * as Common from '../../core/common/common.js';
import * as Host from '../../core/host/host.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/platform.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as ObjectUI from '../../ui/legacy/components/object_ui/object_ui.js';
// eslint-disable-next-line rulesdir/es_modules_import
import objectValueStyles from '../../ui/legacy/components/object_ui/objectValue.css.js';
import * as Components from '../../ui/legacy/components/utils/utils.js';
import * as UI from '../../ui/legacy/legacy.js';
import watchExpressionsSidebarPaneStyles from './watchExpressionsSidebarPane.css.js';
import type * as Protocol from '../../generated/protocol.js';
import {UISourceCodeFrame} from './UISourceCodeFrame.js';
const UIStrings = {
/**
*@description A context menu item in the Watch Expressions Sidebar Pane of the Sources panel
*/
addWatchExpression: 'Add watch expression',
/**
*@description Tooltip/screen reader label of a button in the Sources panel that refreshes all watch expressions.
*/
refreshWatchExpressions: 'Refresh watch expressions',
/**
*@description Empty element text content in Watch Expressions Sidebar Pane of the Sources panel
*/
noWatchExpressions: 'No watch expressions',
/**
*@description A context menu item in the Watch Expressions Sidebar Pane of the Sources panel
*/
deleteAllWatchExpressions: 'Delete all watch expressions',
/**
*@description A context menu item in the Watch Expressions Sidebar Pane of the Sources panel
*/
addPropertyPathToWatch: 'Add property path to watch',
/**
*@description A context menu item in the Watch Expressions Sidebar Pane of the Sources panel
*/
deleteWatchExpression: 'Delete watch expression',
/**
*@description Value element text content in Watch Expressions Sidebar Pane of the Sources panel
*/
notAvailable: '<not available>',
/**
*@description A context menu item in the Watch Expressions Sidebar Pane of the Sources panel and Network pane request.
*/
copyValue: 'Copy value',
};
const str_ = i18n.i18n.registerUIStrings('panels/sources/WatchExpressionsSidebarPane.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
let watchExpressionsSidebarPaneInstance: WatchExpressionsSidebarPane;
export class WatchExpressionsSidebarPane extends UI.ThrottledWidget.ThrottledWidget implements
UI.ActionRegistration.ActionDelegate, UI.Toolbar.ItemsProvider, UI.ContextMenu.Provider {
private watchExpressions: WatchExpression[];
private emptyElement!: HTMLElement;
private readonly watchExpressionsSetting: Common.Settings.Setting<string[]>;
private readonly addButton: UI.Toolbar.ToolbarButton;
private readonly refreshButton: UI.Toolbar.ToolbarButton;
private readonly treeOutline: ObjectUI.ObjectPropertiesSection.ObjectPropertiesSectionsTreeOutline;
private readonly expandController: ObjectUI.ObjectPropertiesSection.ObjectPropertiesSectionsTreeExpandController;
private readonly linkifier: Components.Linkifier.Linkifier;
private constructor() {
super(true);
// TODO(szuend): Replace with a Set once the web test
// panels/sources/debugger-ui/watch-expressions-preserve-expansion.js is either converted
// to an e2e test or no longer accesses this variable directly.
this.watchExpressions = [];
this.watchExpressionsSetting =
Common.Settings.Settings.instance().createLocalSetting<string[]>('watchExpressions', []);
this.addButton = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.addWatchExpression), 'largeicon-add');
this.addButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, _event => {
this.addButtonClicked();
});
this.refreshButton =
new UI.Toolbar.ToolbarButton(i18nString(UIStrings.refreshWatchExpressions), 'largeicon-refresh');
this.refreshButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, this.update, this);
this.contentElement.classList.add('watch-expressions');
this.contentElement.addEventListener('contextmenu', this.contextMenu.bind(this), false);
this.treeOutline = new ObjectUI.ObjectPropertiesSection.ObjectPropertiesSectionsTreeOutline();
this.treeOutline.setShowSelectionOnKeyboardFocus(/* show */ true);
this.expandController =
new ObjectUI.ObjectPropertiesSection.ObjectPropertiesSectionsTreeExpandController(this.treeOutline);
UI.Context.Context.instance().addFlavorChangeListener(SDK.RuntimeModel.ExecutionContext, this.update, this);
UI.Context.Context.instance().addFlavorChangeListener(SDK.DebuggerModel.CallFrame, this.update, this);
this.linkifier = new Components.Linkifier.Linkifier();
this.update();
}
static instance(): WatchExpressionsSidebarPane {
if (!watchExpressionsSidebarPaneInstance) {
watchExpressionsSidebarPaneInstance = new WatchExpressionsSidebarPane();
}
return watchExpressionsSidebarPaneInstance;
}
toolbarItems(): UI.Toolbar.ToolbarItem[] {
return [this.addButton, this.refreshButton];
}
focus(): void {
if (this.hasFocus()) {
return;
}
if (this.watchExpressions.length > 0) {
this.treeOutline.forceSelect();
}
}
hasExpressions(): boolean {
return Boolean(this.watchExpressionsSetting.get().length);
}
private saveExpressions(): void {
const toSave = [];
for (let i = 0; i < this.watchExpressions.length; i++) {
const expression = this.watchExpressions[i].expression();
if (expression) {
toSave.push(expression);
}
}
this.watchExpressionsSetting.set(toSave);
}
private async addButtonClicked(): Promise<void> {
await UI.ViewManager.ViewManager.instance().showView('sources.watch');
this.emptyElement.classList.add('hidden');
this.createWatchExpression(null).startEditing();
}
doUpdate(): Promise<void> {
this.linkifier.reset();
this.contentElement.removeChildren();
this.treeOutline.removeChildren();
this.watchExpressions = [];
this.emptyElement = (this.contentElement.createChild('div', 'gray-info-message') as HTMLElement);
this.emptyElement.textContent = i18nString(UIStrings.noWatchExpressions);
this.emptyElement.tabIndex = -1;
const watchExpressionStrings = this.watchExpressionsSetting.get();
if (watchExpressionStrings.length) {
this.emptyElement.classList.add('hidden');
}
for (let i = 0; i < watchExpressionStrings.length; ++i) {
const expression = watchExpressionStrings[i];
if (!expression) {
continue;
}
this.createWatchExpression(expression);
}
return Promise.resolve();
}
private createWatchExpression(expression: string|null): WatchExpression {
this.contentElement.appendChild(this.treeOutline.element);
const watchExpression = new WatchExpression(expression, this.expandController, this.linkifier);
watchExpression.addEventListener(Events.ExpressionUpdated, this.watchExpressionUpdated, this);
this.treeOutline.appendChild(watchExpression.treeElement());
this.watchExpressions.push(watchExpression);
return watchExpression;
}
private watchExpressionUpdated({data: watchExpression}: Common.EventTarget.EventTargetEvent<WatchExpression>): void {
if (!watchExpression.expression()) {
Platform.ArrayUtilities.removeElement(this.watchExpressions, watchExpression);
this.treeOutline.removeChild(watchExpression.treeElement());
this.emptyElement.classList.toggle('hidden', Boolean(this.watchExpressions.length));
if (this.watchExpressions.length === 0) {
this.treeOutline.element.remove();
}
}
this.saveExpressions();
}
private contextMenu(event: MouseEvent): void {
const contextMenu = new UI.ContextMenu.ContextMenu(event);
this.populateContextMenu(contextMenu, event);
contextMenu.show();
}
private populateContextMenu(contextMenu: UI.ContextMenu.ContextMenu, event: MouseEvent): void {
let isEditing = false;
for (const watchExpression of this.watchExpressions) {
isEditing = isEditing || watchExpression.isEditing();
}
if (!isEditing) {
contextMenu.debugSection().appendItem(i18nString(UIStrings.addWatchExpression), this.addButtonClicked.bind(this));
}
if (this.watchExpressions.length > 1) {
contextMenu.debugSection().appendItem(
i18nString(UIStrings.deleteAllWatchExpressions), this.deleteAllButtonClicked.bind(this));
}
const treeElement = this.treeOutline.treeElementFromEvent(event);
if (!treeElement) {
return;
}
const currentWatchExpression =
this.watchExpressions.find(watchExpression => treeElement.hasAncestorOrSelf(watchExpression.treeElement()));
if (currentWatchExpression) {
currentWatchExpression.populateContextMenu(contextMenu, event);
}
}
private deleteAllButtonClicked(): void {
this.watchExpressions = [];
this.saveExpressions();
this.update();
}
private async focusAndAddExpressionToWatch(expression: string): Promise<void> {
await UI.ViewManager.ViewManager.instance().showView('sources.watch');
this.createWatchExpression(expression);
this.saveExpressions();
this.update();
}
handleAction(_context: UI.Context.Context, _actionId: string): boolean {
const frame = UI.Context.Context.instance().flavor(UISourceCodeFrame);
if (!frame) {
return false;
}
const text = frame.textEditor.text(frame.textEditor.selection());
this.focusAndAddExpressionToWatch(text);
return true;
}
appendApplicableItems(event: Event, contextMenu: UI.ContextMenu.ContextMenu, target: Object): void {
if (target instanceof ObjectUI.ObjectPropertiesSection.ObjectPropertyTreeElement && !target.property.synthetic) {
contextMenu.debugSection().appendItem(
i18nString(UIStrings.addPropertyPathToWatch), () => this.focusAndAddExpressionToWatch(target.path()));
}
const frame = UI.Context.Context.instance().flavor(UISourceCodeFrame);
if (!frame || frame.textEditor.selection().isEmpty()) {
return;
}
contextMenu.debugSection().appendAction('sources.add-to-watch');
}
wasShown(): void {
super.wasShown();
this.treeOutline.registerCSSFiles([watchExpressionsSidebarPaneStyles]);
this.registerCSSFiles([watchExpressionsSidebarPaneStyles, objectValueStyles]);
}
}
export class WatchExpression extends Common.ObjectWrapper.ObjectWrapper<EventTypes> {
private treeElementInternal!: UI.TreeOutline.TreeElement;
private nameElement!: Element;
private valueElement!: Element;
private expressionInternal: string|null;
private readonly expandController: ObjectUI.ObjectPropertiesSection.ObjectPropertiesSectionsTreeExpandController;
private element: HTMLDivElement;
private editing: boolean;
private linkifier: Components.Linkifier.Linkifier;
private textPrompt?: ObjectUI.ObjectPropertiesSection.ObjectPropertyPrompt;
private result?: SDK.RemoteObject.RemoteObject|null;
private preventClickTimeout?: number;
constructor(
expression: string|null,
expandController: ObjectUI.ObjectPropertiesSection.ObjectPropertiesSectionsTreeExpandController,
linkifier: Components.Linkifier.Linkifier) {
super();
this.expressionInternal = expression;
this.expandController = expandController;
this.element = document.createElement('div');
this.element.classList.add('watch-expression');
this.element.classList.add('monospace');
this.editing = false;
this.linkifier = linkifier;
this.createWatchExpression();
this.update();
}
treeElement(): UI.TreeOutline.TreeElement {
return this.treeElementInternal;
}
expression(): string|null {
return this.expressionInternal;
}
update(): void {
const currentExecutionContext = UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext);
if (currentExecutionContext && this.expressionInternal) {
currentExecutionContext
.evaluate(
{
expression: this.expressionInternal,
objectGroup: WatchExpression.watchObjectGroupId,
includeCommandLineAPI: false,
silent: true,
returnByValue: false,
generatePreview: false,
allowUnsafeEvalBlockedByCSP: undefined,
disableBreaks: undefined,
replMode: undefined,
throwOnSideEffect: undefined,
timeout: undefined,
},
/* userGesture */ false,
/* awaitPromise */ false)
.then(result => {
if ('object' in result) {
this.createWatchExpression(result.object, result.exceptionDetails);
} else {
this.createWatchExpression();
}
});
} else {
this.createWatchExpression();
}
}
startEditing(): void {
this.editing = true;
this.treeElementInternal.setDisableSelectFocus(true);
this.element.removeChildren();
const newDiv = this.element.createChild('div');
newDiv.textContent = this.nameElement.textContent;
this.textPrompt = new ObjectUI.ObjectPropertiesSection.ObjectPropertyPrompt();
this.textPrompt.renderAsBlock();
const proxyElement = (this.textPrompt.attachAndStartEditing(newDiv, this.finishEditing.bind(this)) as HTMLElement);
this.treeElementInternal.listItemElement.classList.add('watch-expression-editing');
this.treeElementInternal.collapse();
proxyElement.classList.add('watch-expression-text-prompt-proxy');
proxyElement.addEventListener('keydown', this.promptKeyDown.bind(this), false);
const selection = this.element.getComponentSelection();
if (selection) {
selection.selectAllChildren(newDiv);
}
}
isEditing(): boolean {
return Boolean(this.editing);
}
private finishEditing(event: Event, canceled?: boolean): void {
if (event) {
event.consume(canceled);
}
this.editing = false;
this.treeElementInternal.setDisableSelectFocus(false);
this.treeElementInternal.listItemElement.classList.remove('watch-expression-editing');
if (this.textPrompt) {
this.textPrompt.detach();
const newExpression = canceled ? this.expressionInternal : this.textPrompt.text();
this.textPrompt = undefined;
this.element.removeChildren();
this.updateExpression(newExpression);
}
}
private dblClickOnWatchExpression(event: Event): void {
event.consume();
if (!this.isEditing()) {
this.startEditing();
}
}
private updateExpression(newExpression: string|null): void {
if (this.expressionInternal) {
this.expandController.stopWatchSectionsWithId(this.expressionInternal);
}
this.expressionInternal = newExpression;
this.update();
this.dispatchEventToListeners(Events.ExpressionUpdated, this);
}
private deleteWatchExpression(event: Event): void {
event.consume(true);
this.updateExpression(null);
}
private createWatchExpression(
result?: SDK.RemoteObject.RemoteObject, exceptionDetails?: Protocol.Runtime.ExceptionDetails): void {
this.result = result || null;
this.element.removeChildren();
const oldTreeElement = this.treeElementInternal;
this.createWatchExpressionTreeElement(result, exceptionDetails);
if (oldTreeElement && oldTreeElement.parent) {
const root = oldTreeElement.parent;
const index = root.indexOfChild(oldTreeElement);
root.removeChild(oldTreeElement);
root.insertChild(this.treeElementInternal, index);
}
this.treeElementInternal.select();
}
private createWatchExpressionHeader(
expressionValue?: SDK.RemoteObject.RemoteObject, exceptionDetails?: Protocol.Runtime.ExceptionDetails): Element {
const headerElement = this.element.createChild('div', 'watch-expression-header');
const deleteButton = UI.Icon.Icon.create('smallicon-cross', 'watch-expression-delete-button');
UI.Tooltip.Tooltip.install(deleteButton, i18nString(UIStrings.deleteWatchExpression));
deleteButton.addEventListener('click', this.deleteWatchExpression.bind(this), false);
const titleElement = headerElement.createChild('div', 'watch-expression-title tree-element-title');
titleElement.appendChild(deleteButton);
this.nameElement =
ObjectUI.ObjectPropertiesSection.ObjectPropertiesSection.createNameElement(this.expressionInternal);
if (Boolean(exceptionDetails) || !expressionValue) {
this.valueElement = document.createElement('span');
this.valueElement.classList.add('watch-expression-error');
this.valueElement.classList.add('value');
titleElement.classList.add('dimmed');
this.valueElement.textContent = i18nString(UIStrings.notAvailable);
if (exceptionDetails !== undefined && exceptionDetails.exception !== undefined &&
exceptionDetails.exception.description !== undefined) {
UI.Tooltip.Tooltip.install(this.valueElement as HTMLElement, exceptionDetails.exception.description);
}
} else {
const propertyValue =
ObjectUI.ObjectPropertiesSection.ObjectPropertiesSection.createPropertyValueWithCustomSupport(
expressionValue, Boolean(exceptionDetails), false /* showPreview */, titleElement, this.linkifier);
this.valueElement = propertyValue.element;
}
const separatorElement = document.createElement('span');
separatorElement.classList.add('watch-expressions-separator');
separatorElement.textContent = ': ';
titleElement.append(this.nameElement, separatorElement, this.valueElement);
return headerElement;
}
private createWatchExpressionTreeElement(
expressionValue?: SDK.RemoteObject.RemoteObject, exceptionDetails?: Protocol.Runtime.ExceptionDetails): void {
const headerElement = this.createWatchExpressionHeader(expressionValue, exceptionDetails);
if (!exceptionDetails && expressionValue && expressionValue.hasChildren && !expressionValue.customPreview()) {
headerElement.classList.add('watch-expression-object-header');
this.treeElementInternal = new ObjectUI.ObjectPropertiesSection.RootElement(expressionValue, this.linkifier);
this.expandController.watchSection(
(this.expressionInternal as string),
(this.treeElementInternal as ObjectUI.ObjectPropertiesSection.RootElement));
this.treeElementInternal.toggleOnClick = false;
this.treeElementInternal.listItemElement.addEventListener('click', this.onSectionClick.bind(this), false);
this.treeElementInternal.listItemElement.addEventListener('dblclick', this.dblClickOnWatchExpression.bind(this));
} else {
headerElement.addEventListener('dblclick', this.dblClickOnWatchExpression.bind(this));
this.treeElementInternal = new UI.TreeOutline.TreeElement();
}
this.treeElementInternal.title = this.element;
this.treeElementInternal.listItemElement.classList.add('watch-expression-tree-item');
this.treeElementInternal.listItemElement.addEventListener('keydown', event => {
if (event.key === 'Enter' && !this.isEditing()) {
this.startEditing();
event.consume(true);
}
});
}
private onSectionClick(event: Event): void {
event.consume(true);
const mouseEvent = (event as MouseEvent);
if (mouseEvent.detail === 1) {
this.preventClickTimeout = window.setTimeout(handleClick.bind(this), 333);
} else if (this.preventClickTimeout !== undefined) {
window.clearTimeout(this.preventClickTimeout);
this.preventClickTimeout = undefined;
}
function handleClick(this: WatchExpression): void {
if (!this.treeElementInternal) {
return;
}
if (this.treeElementInternal.expanded) {
this.treeElementInternal.collapse();
} else if (!this.editing) {
this.treeElementInternal.expand();
}
}
}
private promptKeyDown(event: KeyboardEvent): void {
if (event.key === 'Enter' || isEscKey(event)) {
this.finishEditing(event, isEscKey(event));
}
}
populateContextMenu(contextMenu: UI.ContextMenu.ContextMenu, event: Event): void {
if (!this.isEditing()) {
contextMenu.editSection().appendItem(
i18nString(UIStrings.deleteWatchExpression), this.updateExpression.bind(this, null));
}
if (!this.isEditing() && this.result && (this.result.type === 'number' || this.result.type === 'string')) {
contextMenu.clipboardSection().appendItem(
i18nString(UIStrings.copyValue), this.copyValueButtonClicked.bind(this));
}
const target = UI.UIUtils.deepElementFromEvent(event);
if (target && this.valueElement.isSelfOrAncestor(target) && this.result) {
contextMenu.appendApplicableItems(this.result);
}
}
private copyValueButtonClicked(): void {
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(this.valueElement.textContent);
}
private static readonly watchObjectGroupId = 'watch-group';
}
const enum Events {
ExpressionUpdated = 'ExpressionUpdated',
}
type EventTypes = {
[Events.ExpressionUpdated]: WatchExpression,
}; | the_stack |
import {test, expect, Page, Browser} from '@playwright/test';
import {
waitForPlaygroundPreviewToLoad,
freezeSnackbars,
freezeDialogs,
closeSnackbars,
readClipboardText,
} from './util';
const signInToGithub = async (page: Page): Promise<void> => {
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.click('#signInButton'),
]);
await popup.waitForLoadState();
await popup.click('text=Authorize lit');
await popup.waitForEvent('close');
};
const failNextGitHubRequest = async (browser: Browser): Promise<void> => {
const page = await browser.newPage();
await page.goto('http://localhost:6417/fail-next-request');
expect(await page.textContent('body')).toEqual('Next request will fail');
await page.close();
};
test.describe('Playground', () => {
test.beforeEach(async ({browser}) => {
const page = await browser.newPage();
await page.goto('http://localhost:6417/reset');
expect(await page.textContent('body')).toEqual(
'fake github successfully reset'
);
await page.close();
});
test('default example is simple-greeting.ts', async ({page}) => {
await page.goto(`/playground`);
await waitForPlaygroundPreviewToLoad(page);
const greetingExample = page.locator(
'#exampleContent > div:nth-child(1) > ul > li:nth-child(1)'
);
await expect(greetingExample).toHaveClass('exampleItem active');
const codeEditor = page.locator('playground-code-editor #focusContainer');
expect(
((await codeEditor.textContent()) ?? '').includes(
`@customElement('simple-greeting')`
)
).toBe(true);
const playgroundPreviewFrame = (await (await page
.locator('playground-preview iframe')
.elementHandle())!.contentFrame())!;
await expect(
playgroundPreviewFrame.locator('simple-greeting p')!
).toHaveText('Hello, World!');
await expect(playgroundPreviewFrame.locator('simple-greeting p')).toHaveCSS(
'color',
'rgb(0, 0, 255)'
);
});
test('updating the example code updates the preview', async ({page}) => {
await page.goto(`/playground`);
// Double click text=blue
await page.dblclick('text=blue');
// Change the text to red
await page.keyboard.type('red');
await waitForPlaygroundPreviewToLoad(page);
const playgroundPreviewFrame = (await (await page
.locator('playground-preview iframe')
.elementHandle())!.contentFrame())!;
await expect(
playgroundPreviewFrame.locator('simple-greeting p')
).toHaveText('Hello, World!');
await expect(playgroundPreviewFrame.locator('simple-greeting p')).toHaveCSS(
'color',
'rgb(255, 0, 0)'
);
});
test('Hello world project golden', async ({page}) => {
await page.goto('/playground');
await waitForPlaygroundPreviewToLoad(page);
// Because of shadow dom piercing, Playwright finds multiple '#content'
// nodes, i.e. the page, and within the playground shadow DOM.
await expect(
await page.locator('main > #content').screenshot()
).toMatchSnapshot('helloWorldPlaygroundProject.png');
});
test('share long url', async ({page}) => {
await page.goto('/playground/?mods=gists');
await freezeSnackbars(page);
// Type some new content
await page.click('playground-code-editor');
await page.keyboard.press('Control+A');
await page.keyboard.type('"my long url content";');
await waitForPlaygroundPreviewToLoad(page);
// Open the share menu
await page.click('litdev-playground-share-button');
await expect(await page.screenshot()).toMatchSnapshot(
'shareLongUrl-1-shareMenuOpen.png'
);
// Save the long URL
await page.click('litdev-playground-share-long-url copy-button');
await page.waitForURL(/#project=/);
expect(await readClipboardText(page)).toMatch(page.url());
await page.waitForSelector('litdev-playground-share-button litdev-flyout', {
state: 'hidden',
});
await expect(await page.screenshot()).toMatchSnapshot(
'shareLongUrl-2-snackbarOpen.png'
);
// Reload the page to confirm the new content is still there
await page.reload();
await waitForPlaygroundPreviewToLoad(page);
await expect(await page.screenshot()).toMatchSnapshot(
'shareLongUrl-3-pageReloaded.png'
);
});
test('share gist', async ({page}) => {
await page.goto('/playground/?mods=gists');
// Type some new content
await page.click('playground-code-editor');
await page.keyboard.press('Control+A');
await page.keyboard.type('"my gist content";');
await waitForPlaygroundPreviewToLoad(page);
// Open the share menu
await page.click('litdev-playground-share-button');
await page.waitForSelector('litdev-playground-share-button litdev-flyout', {
state: 'visible',
});
await expect(await page.screenshot()).toMatchSnapshot(
'shareGist-1-shareMenuOpen.png'
);
// Sign in to GitHub
await signInToGithub(page);
await page.waitForSelector('#createNewGistButton', {state: 'visible'});
await expect(await page.screenshot()).toMatchSnapshot(
'shareGist-2-signedIn.png'
);
// Save the gist
await page.click('#createNewGistButton');
await page.waitForURL(/#gist=/);
expect(await readClipboardText(page)).toMatch(page.url());
const firstUrl = page.url();
await page.waitForSelector('litdev-playground-share-button litdev-flyout', {
state: 'hidden',
});
await freezeSnackbars(page);
await expect(await page.screenshot()).toMatchSnapshot(
'shareGist-3-snackbarOpen.png'
);
// Reload the page to confirm the new content is still there
await page.reload();
await waitForPlaygroundPreviewToLoad(page);
await expect(await page.screenshot()).toMatchSnapshot(
'shareGist-4-pageReloaded.png'
);
// Type some more content
await page.click('playground-code-editor');
await page.keyboard.press('Control+A');
await page.keyboard.type('"my updated gist content";');
// Rename a file
await page.hover('text=simple-greeting.ts');
await page.click('text=simple-greeting.ts >> .menu-button');
await page.click('#renameButton');
await page.click('.filename-input');
await page.keyboard.press('Control+A');
await page.keyboard.type('new-name.ts');
await expect(await page.screenshot()).toMatchSnapshot(
'shareGist-5-renamingFile.png'
);
await page.keyboard.press('Enter');
// Add a new empty file
await page.click('.add-file-button');
await page.click('.filename-input');
await page.keyboard.type('empty.txt');
await expect(await page.screenshot()).toMatchSnapshot(
'shareGist-6-addingFile.png'
);
await page.keyboard.press('Enter');
// Open the share menu again
await waitForPlaygroundPreviewToLoad(page);
await page.click('litdev-playground-share-button');
await page.waitForSelector('litdev-playground-share-button litdev-flyout', {
state: 'visible',
});
await expect(await page.screenshot()).toMatchSnapshot(
'shareGist-7-shareMenuOpenAgain.png'
);
// Update the gist
await freezeSnackbars(page);
await page.click('#updateGistButton');
await page.waitForURL(/#gist=/);
expect(page.url()).toEqual(firstUrl);
expect(await readClipboardText(page)).toMatch(firstUrl);
await page.waitForSelector('litdev-playground-share-button litdev-flyout', {
state: 'hidden',
});
await expect(await page.screenshot()).toMatchSnapshot(
'shareGist-8-gistUpdated.png'
);
// Reload the page again to confirm the updated content is there
await page.reload();
await waitForPlaygroundPreviewToLoad(page);
await expect(await page.screenshot()).toMatchSnapshot(
'shareGist-9-pageReloadedAgain.png'
);
});
test('share long URL with keyboard shortcuts', async ({page}) => {
await page.goto('/playground/?mods=gists');
await waitForPlaygroundPreviewToLoad(page);
// On the first Ctrl+S, the share menu opens and we click the copy button
await page.keyboard.press('Control+S');
await page.waitForSelector('litdev-playground-share-button litdev-flyout', {
state: 'visible',
});
await page.click('litdev-playground-share-long-url copy-button');
await page.waitForURL(/#project=/);
expect(await readClipboardText(page)).toMatch(page.url());
const firstUrl = page.url();
// Change the content
await page.click('playground-code-editor');
await page.keyboard.press('Control+A');
await page.keyboard.type('"new content";');
await waitForPlaygroundPreviewToLoad(page);
// On the next Ctrl+S, the long URL share should happen automatically
await page.keyboard.press('Control+S');
await page.waitForURL(
(url) => url.href.match(/#project=/) !== null && url.href !== firstUrl
);
expect(await readClipboardText(page)).toMatch(page.url());
});
test('share gist with keyboard shortcuts', async ({page}) => {
await page.goto('/playground/?mods=gists');
await waitForPlaygroundPreviewToLoad(page);
// On the first Ctrl+S, the share menu opens and we click the new gist button
await page.keyboard.press('Control+S');
await page.waitForSelector('litdev-playground-share-button litdev-flyout', {
state: 'visible',
});
await signInToGithub(page);
await page.waitForSelector('#createNewGistButton', {state: 'visible'});
await page.click('#createNewGistButton');
await page.waitForURL(/#gist=/);
expect(await readClipboardText(page)).toMatch(page.url());
const firstUrl = page.url();
// Change the content
await page.click('playground-code-editor');
await page.keyboard.press('Control+A');
await page.keyboard.type('"new content";');
await waitForPlaygroundPreviewToLoad(page);
// On the next Ctrl+S, the new gist should be updated automatically
await page.keyboard.press('Control+S');
expect(page.url()).toEqual(firstUrl);
expect(await readClipboardText(page)).toMatch(firstUrl);
});
test('user declines github auth', async ({page}) => {
await page.goto('/playground/?mods=gists');
await waitForPlaygroundPreviewToLoad(page);
// Open the share menu
await page.click('litdev-playground-share-button');
await page.waitForSelector('litdev-playground-share-button litdev-flyout');
// Click share
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.click('#signInButton'),
]);
await popup.waitForLoadState();
// Decline authorization
await popup.click('text=Cancel');
await popup.waitForEvent('close');
// An informative dialog should display
await page.waitForSelector('[role=alertdialog]');
await freezeDialogs(page);
await expect(await page.screenshot()).toMatchSnapshot(
'userDeclinesGithubAuth.png'
);
});
test('user closes github auth window early', async ({page}) => {
await page.goto('/playground/?mods=gists');
await waitForPlaygroundPreviewToLoad(page);
// Open the share menu
await page.click('litdev-playground-share-button');
await page.waitForSelector('litdev-playground-share-button litdev-flyout');
// Click share
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.click('#signInButton'),
]);
await popup.waitForLoadState();
// Close the window
await popup.close();
// An informative dialog should display
await page.waitForSelector('[role=alertdialog]');
await freezeDialogs(page);
await expect(await page.screenshot()).toMatchSnapshot(
'userClosesGitHubAuthWindowTooEarly.png'
);
});
test('gist does not exist', async ({page}) => {
await page.goto('/playground/?mods=gists#gist=not-a-real-gist');
await waitForPlaygroundPreviewToLoad(page);
// An informative dialog should display
await page.waitForSelector('[role=alertdialog]');
await freezeDialogs(page);
await expect(await page.screenshot()).toMatchSnapshot(
'gistDoesNotExist.png'
);
});
test('backend error writing gist', async ({page, browser}) => {
await page.goto('/playground/?mods=gists');
// Type some new content
await page.click('playground-code-editor');
await page.keyboard.press('Control+A');
await page.keyboard.type('"my gist content";');
await waitForPlaygroundPreviewToLoad(page);
// Open the share menu
await page.click('litdev-playground-share-button');
await page.waitForSelector('litdev-playground-share-button litdev-flyout');
// Sign in to GitHub
await signInToGithub(page);
// Try to save the gist
await page.waitForSelector('#createNewGistButton');
await failNextGitHubRequest(browser);
await page.click('#createNewGistButton');
// An informative dialog should display
await page.waitForSelector('[role=alertdialog]');
await freezeDialogs(page);
await closeSnackbars(page);
await expect(await page.screenshot()).toMatchSnapshot(
'backendErrorWritingGist.png'
);
});
test('close share flyout by clicking outside of the flyout', async ({
page,
}) => {
await page.goto('/playground/?mods=gists');
await page.click('litdev-playground-share-button');
await page.waitForSelector('litdev-playground-share-button litdev-flyout', {
state: 'visible',
});
await page.click('main');
await page.waitForSelector('litdev-playground-share-button litdev-flyout', {
state: 'hidden',
});
});
test('close share flyout by clicking share button again', async ({page}) => {
await page.goto('/playground/?mods=gists');
await page.click('litdev-playground-share-button');
await page.waitForSelector('litdev-playground-share-button litdev-flyout', {
state: 'visible',
});
await page.click('litdev-playground-share-button');
await page.waitForSelector('litdev-playground-share-button litdev-flyout', {
state: 'hidden',
});
});
}); | the_stack |
import * as ts from 'typescript'
const IS_DEBUG_PRINT = false
export default class Helper{
static operatorOverload(
node: ts.Node,
program,
data,
overloader,
callback: (
node: ts.BinaryExpression,
interfaceVaraible: ts.Expression,
forceApplyTop?: boolean
) => ts.Expression | undefined
){
/**
* @description
* Operator Overload
* - Compare Function (Binary Expression)
* - Rule Condition
* - Value Condition
*/
let overrideContext =
overloader(
node,
data.interfaceVaraible,
callback
)
if(overrideContext){
// Check interface is used
data.interfaceVaraibleIsHoisted = true
return overrideContext
}
/**
* @description
* Operator Overload
* - Compare Function (UnaryExpression)
* - Rule Condition
* - Value Condition
*/
if(ts['isUnaryExpression'](node)){
// To Unary Rule Condition Definition Support
if(Helper.checkNodeIsTopCondition(node)){
let symbol = program.getTypeChecker().getSymbolAtLocation(node)
if(symbol != undefined){
if(ts.isVariableDeclaration(symbol.valueDeclaration)){
if(symbol.valueDeclaration.initializer != undefined){
let overrideContext =
overloader(
symbol.valueDeclaration.initializer,
data.interfaceVaraible,
callback,
true // Fore Apply Top Condition
)
if(overrideContext){
// Check interface is used
data.interfaceVaraibleIsHoisted = true
return overrideContext
}
}
}
}
}
}
return
}
static binaryExpressionOverload(
node: ts.Node,
interfaceVaraible: ts.Expression,
callback: (
node: ts.BinaryExpression,
interfaceVaraible: ts.Expression,
forceApplyTop?: boolean
) => ts.Expression | void,
forceApplyTop?: boolean,
): ts.Expression | undefined {
// Parse Nested Parenthesize
if(ts.isParenthesizedExpression(node)){
if(forceApplyTop === undefined)
forceApplyTop = Helper.checkNodeIsTopCondition(node)
return Helper.binaryExpressionOverload(
node.expression,
interfaceVaraible,
callback,
forceApplyTop
)
}
if(ts.isBinaryExpression(node)){
// Parse Nested Left Expression
if(ts.isParenthesizedExpression(node.left)
|| ts.isBinaryExpression(node.left)){
let overridedExpression =
Helper.binaryExpressionOverload(
node.left,
interfaceVaraible,
callback
)
if(overridedExpression)
node.left = overridedExpression
}
// Parse Nested Right Expression
if(ts.isParenthesizedExpression(node.right)
|| ts.isBinaryExpression(node.right)){
let overridedExpression =
Helper.binaryExpressionOverload(
node.right,
interfaceVaraible,
callback
)
if(overridedExpression)
node.right = overridedExpression
}
let overrideContext =
callback(
node,
interfaceVaraible,
forceApplyTop
)
if(overrideContext)
return overrideContext
}
return
}
/**
* @description
* Check node is top condition
* of overwatch workshop condition
*
* @example
*
* new Rule({
* condition: []
* })
*/
static checkNodeIsTopCondition(node: ts.Node): boolean {
// Check [...]
if(ts.isArrayLiteralExpression(node.parent)){
// Check :
if(ts.isPropertyAssignment(node.parent.parent)){
// Check condition:
if(node.parent.parent.name.getText() == 'condition'){
// Check {...}
if(ts.isObjectLiteralExpression(node.parent.parent.parent)){
// Check new
if(ts.isNewExpression(node.parent.parent.parent.parent)){
// Check Rule
if(node.parent.parent.parent.parent.expression.getText() == 'Rule')
return true
}
}
}
}
}
return false
}
static compareOverload(
node: ts.BinaryExpression,
interfaceVaraible: ts.Expression,
forceApplyTop?: boolean
){
let token = node.operatorToken.getText()
// No Deep Type Check
if(token == '===') token = '=='
if(token == '!==') token = '!='
switch(token){
case '==':
case '!=':
case '>=':
case '<=':
case '>':
case '<':
let compareProperty
/**
* Check Node Is Top of Rule.
*
* Each method of application is
* different when used in values
* and when used in rules.
*/
if(Helper.checkNodeIsTopCondition(node) || (forceApplyTop === true)){
// Rule Condition
compareProperty =
// interface_1.Value.compare
ts.createPropertyAccess(
// interface_1.Value
ts.createPropertyAccess(
interfaceVaraible,
// Yep Hard coding
ts.createIdentifier('Classes.Compiler')
),
ts.createIdentifier('ruleCompare')
)
}else{
// Value Condition
compareProperty =
// interface_1.Value.compare
ts.createPropertyAccess(
// interface_1.Value
ts.createPropertyAccess(
interfaceVaraible,
ts.createIdentifier('Value')
),
ts.createIdentifier('compare')
)
}
// interface_1.Value.compare()
return ts.createCall(
// FunctionName
compareProperty,
// Type
undefined,
// Paramaeter
[
node.left,
ts.createIdentifier(`'${token}'`),
node.right,
]
)
}
return
}
static arithmeticOverload(){
return (
node: ts.BinaryExpression,
interfaceVaraible: ts.Expression,
forceApplyTop?: boolean
) => {
// Check Token List
let tokenMap = {
and: '&&',
or: '||',
add: '+',
subtract: '-',
divide: '/',
multiply: '*',
modulo: '%',
raiseToPower: '**'
}
for(let type of Object.keys(tokenMap)){
let needToMatchToken = tokenMap[type]
if(needToMatchToken &&
(node.operatorToken.getText() == needToMatchToken)
){
// Value Condition
let property =
// interface_1.Value.compare
ts.createPropertyAccess(
// interface_1.Value
ts.createPropertyAccess(
interfaceVaraible,
ts.createIdentifier('Value')
),
ts.createIdentifier(type)
)
// interface_1.Value.and()
return ts.createCall(
// FunctionName
property,
// Type
undefined,
// Paramaeter
[
node.left,
node.right,
]
)
}
}
return
}
}
static statementTypeAnalyze(node){
let opt: any = []
let typeList = [
"isArray","isString","isNumber","isUnicodeIdentifierStart",
"isWhiteSpaceLike","isWhiteSpaceSingleLine","isLineBreak",
"isOctalDigit","isIdentifierStart","isIdentifierPart","isIdentifierText",
"isExternalModuleNameRelative","isStatementWithLocals","isFileLevelUniqueName",
"isRecognizedTripleSlashComment","isPinnedComment","isBlockOrCatchScoped",
"isCatchClauseVariableDeclarationOrBindingElement","isAmbientModule",
"isModuleWithStringLiteralName","isNonGlobalAmbientModule",
"isEffectiveModuleDeclaration","isShorthandAmbientModuleSymbol",
"isBlockScopedContainerTopLevel","isGlobalScopeAugmentation",
"isExternalModuleAugmentation","isModuleAugmentationExternal",
"isEffectiveExternalModule","isBlockScope","isDeclarationWithTypeParameters",
"isDeclarationWithTypeParameterChildren","isAnyImportSyntax",
"isLateVisibilityPaintedStatement","isAnyImportOrReExport",
"isExternalOrCommonJsModule","isJsonSourceFile","isEnumConst",
"isDeclarationReadonly","isVarConst","isLet","isSuperCall",
"isImportCall","isLiteralImportTypeNode","isPrologueDirective",
"isPartOfTypeNode","isChildOfNodeWithKind","isVariableLike",
"isVariableLikeOrAccessor","isVariableDeclarationInVariableStatement",
"isValidESSymbolDeclaration","isFunctionBlock","isObjectLiteralMethod",
"isObjectLiteralOrClassExpressionMethod","isIdentifierTypePredicate",
"isThisTypePredicate","isSuperProperty","isThisProperty","isJSXTagName",
"isExpressionNode","isInExpressionContext",
"isExternalModuleImportEqualsDeclaration",
"isInternalModuleImportEqualsDeclaration",
"isSourceFileJS","isSourceFileNotJS","isInJSFile","isInJsonFile",
"isInJSDoc","isJSDocIndexSignature","isRequireCall",
"isSingleOrDoubleQuote","isStringDoubleQuoted","isAssignmentDeclaration",
"isDefaultedExpandoInitializer","isExportsIdentifier",
"isModuleExportsPropertyAccessExpression","isBindableObjectDefinePropertyCall",
"isPrototypePropertyAssignment","isSpecialPropertyDeclaration",
"isFunctionSymbol","isDefaultImport","isJSDocConstructSignature",
"isJSDocTypeAlias","isTypeAlias","isRestParameter","isAssignmentTarget",
"isNodeWithPossibleHoistedDeclaration","isValueSignatureDeclaration",
"isDeleteTarget","isNodeDescendantOf","isDeclarationName",
"isLiteralComputedPropertyDeclarationName","isIdentifierName",
"isAliasSymbolDeclaration","isKeyword","isContextualKeyword",
"isNonContextualKeyword","isStringANonContextualKeyword",
"isIdentifierANonContextualKeyword","isTrivia","isAsyncFunction",
"isStringOrNumericLiteralLike","isDynamicName","isWellKnownSymbolSyntactically",
"isPropertyNameLiteral","isKnownSymbol","isESSymbolIdentifier",
"isPushOrUnshiftIdentifier","isParameterDeclaration",
"isIntrinsicJsxName","isThisIdentifier","isLogicalOperator",
"isAssignmentOperator","isAssignmentExpression",
"isDestructuringAssignment","isExpressionWithTypeArgumentsInClassExtendsClause",
"isEntityNameExpression","isPropertyAccessEntityNameExpression",
"isPrototypeAccess","isRightSideOfQualifiedNameOrPropertyAccess",
"isEmptyObjectLiteral","isEmptyArrayLiteral","isCollapsedRange",
"isDeclarationNameOfEnumOrNamespace","isWatchSet","isWriteOnlyAccess",
"isWriteAccess","isAbstractConstructorType","isAbstractConstructorSymbol",
"isUMDExportSymbol","isObjectTypeDeclaration","isTypeNodeKind",
"isParameterPropertyDeclaration","isEmptyBindingPattern",
"isEmptyBindingElement","isParseTreeNode","isNamedDeclaration",
"isNumericLiteral","isBigIntLiteral","isStringLiteral","isJsxText",
"isRegularExpressionLiteral","isNoSubstitutionTemplateLiteral",
"isTemplateHead","isTemplateMiddle","isTemplateTail","isIdentifier",
"isQualifiedName","isComputedPropertyName","isTypeParameterDeclaration",
"isParameter","isDecorator","isPropertySignature","isPropertyDeclaration",
"isMethodSignature","isMethodDeclaration","isConstructorDeclaration",
"isGetAccessorDeclaration","isSetAccessorDeclaration",
"isCallSignatureDeclaration","isConstructSignatureDeclaration",
"isIndexSignatureDeclaration","isGetOrSetAccessorDeclaration",
"isTypePredicateNode","isTypeReferenceNode","isFunctionTypeNode",
"isConstructorTypeNode","isTypeQueryNode","isTypeLiteralNode",
"isArrayTypeNode","isTupleTypeNode","isUnionTypeNode",
"isIntersectionTypeNode","isConditionalTypeNode","isInferTypeNode",
"isParenthesizedTypeNode","isThisTypeNode","isTypeOperatorNode",
"isIndexedAccessTypeNode","isMappedTypeNode","isLiteralTypeNode",
"isImportTypeNode","isObjectBindingPattern","isArrayBindingPattern",
"isBindingElement","isArrayLiteralExpression",
"isObjectLiteralExpression","isPropertyAccessExpression",
"isElementAccessExpression","isCallExpression","isNewExpression",
"isTaggedTemplateExpression","isTypeAssertion","isParenthesizedExpression",
"isFunctionExpression","isArrowFunction","isDeleteExpression",
"isTypeOfExpression","isVoidExpression","isAwaitExpression",
"isPrefixUnaryExpression","isPostfixUnaryExpression",
"isBinaryExpression","isConditionalExpression","isTemplateExpression",
"isYieldExpression","isSpreadElement","isClassExpression",
"isOmittedExpression","isExpressionWithTypeArguments","isAsExpression",
"isNonNullExpression","isMetaProperty","isTemplateSpan",
"isSemicolonClassElement","isBlock","isVariableStatement",
"isEmptyStatement","isExpressionStatement","isIfStatement",
"isDoStatement","isWhileStatement","isForStatement","isForInStatement",
"isForOfStatement","isContinueStatement","isBreakStatement",
"isBreakOrContinueStatement","isReturnStatement","isWithStatement",
"isSwitchStatement","isLabeledStatement","isThrowStatement",
"isTryStatement","isDebuggerStatement","isVariableDeclaration",
"isVariableDeclarationList","isFunctionDeclaration","isClassDeclaration",
"isInterfaceDeclaration","isTypeAliasDeclaration","isEnumDeclaration",
"isModuleDeclaration","isModuleBlock","isCaseBlock","isNamespaceExportDeclaration",
"isImportEqualsDeclaration","isImportDeclaration","isImportClause",
"isNamespaceImport","isNamedImports","isImportSpecifier","isExportAssignment",
"isExportDeclaration","isNamedExports","isExportSpecifier","isMissingDeclaration",
"isExternalModuleReference","isJsxElement","isJsxSelfClosingElement",
"isJsxOpeningElement","isJsxClosingElement","isJsxFragment","isJsxOpeningFragment",
"isJsxClosingFragment","isJsxAttribute","isJsxAttributes","isJsxSpreadAttribute",
"isJsxExpression","isCaseClause","isDefaultClause","isHeritageClause",
"isCatchClause","isPropertyAssignment","isShorthandPropertyAssignment",
"isSpreadAssignment","isEnumMember","isSourceFile","isBundle",
"isUnparsedSource","isJSDocTypeExpression","isJSDocAllType",
"isJSDocUnknownType","isJSDocNullableType","isJSDocNonNullableType",
"isJSDocOptionalType","isJSDocFunctionType","isJSDocVariadicType",
"isJSDoc","isJSDocAugmentsTag","isJSDocClassTag","isJSDocEnumTag",
"isJSDocThisTag","isJSDocParameterTag","isJSDocReturnTag","isJSDocTypeTag",
"isJSDocTemplateTag","isJSDocTypedefTag","isJSDocPropertyTag",
"isJSDocPropertyLikeTag","isJSDocTypeLiteral","isJSDocCallbackTag",
"isJSDocSignature","isSyntaxList","isNode","isNodeKind","isToken",
"isNodeArray","isLiteralKind","isLiteralExpression","isTemplateLiteralKind",
"isTemplateLiteralToken","isTemplateMiddleOrTemplateTail",
"isImportOrExportSpecifier","isStringTextContainingNode",
"isGeneratedIdentifier","isModifierKind","isParameterPropertyModifier",
"isClassMemberModifier","isModifier","isEntityName","isPropertyName",
"isBindingName","isFunctionLike","isFunctionLikeDeclaration",
"isFunctionLikeKind","isFunctionOrModuleBlock","isClassElement",
"isClassLike","isAccessor","isMethodOrAccessor","isTypeElement",
"isClassOrTypeElement","isObjectLiteralElementLike","isTypeNode",
"isFunctionOrConstructorTypeNode","isBindingPattern","isAssignmentPattern",
"isArrayBindingElement","isDeclarationBindingElement",
"isBindingOrAssignmentPattern","isObjectBindingOrAssignmentPattern",
"isArrayBindingOrAssignmentPattern",
"isPropertyAccessOrQualifiedNameOrImportTypeNode",
"isPropertyAccessOrQualifiedName","isCallLikeExpression",
"isCallOrNewExpression","isTemplateLiteral","isLeftHandSideExpression",
"isUnaryExpression","isUnaryExpressionWithWrite","isExpression",
"isAssertionExpression","isPartiallyEmittedExpression",
"isNotEmittedStatement","isNotEmittedOrPartiallyEmittedNode",
"isIterationStatement","isForInOrOfStatement","isConciseBody","isFunctionBody",
"isForInitializer","isModuleBody","isNamespaceBody","isJSDocNamespaceBody",
"isNamedImportBindings","isModuleOrEnumDeclaration","isDeclaration",
"isDeclarationStatement","isStatementButNotDeclaration","isStatement",
"isModuleReference","isJsxTagNameExpression","isJsxChild","isJsxAttributeLike",
"isStringLiteralOrJsxExpression","isJsxOpeningLikeElement",
"isCaseOrDefaultClause","isJSDocNode","isJSDocCommentContainingNode",
"isJSDocTag","isSetAccessor","isGetAccessor","isObjectLiteralElement",
"isTypeReferenceType","isStringLiteralLike","isNamedImportsOrExports",
"isUrl","isRootedDiskPath","isDiskPathRoot","isImplicitGlob",
"isSupportedSourceFileName","isAnySupportedFileExtension","isCheckJsEnabledForFile",
"isJsonEqual","isJSDocLikeText","isExternalModule","isDeclarationFileName",
"isTraceEnabled","isExportsOrModuleExportsOrAlias","isInstantiatedModule",
"isInternalName","isLocalName","isExportName","isCommaSequence",
"isOuterExpression","isRawSourceMap","isSourceMapping","isSimpleCopiableExpression",
"isEmittedFileOfProgram","isProgramUptoDate","isPathInNodeModulesStartingWithDot",
"isJsPrivate","isInRightSideOfInternalImportEqualsDeclaration",
"isCallExpressionTarget","isNewExpressionTarget","isCallOrNewExpressionTarget",
"isJumpStatementTarget","isLabelOfLabeledStatement","isLabelName","isTagName",
"isRightSideOfQualifiedName","isRightSideOfPropertyAccess",
"isNameOfModuleDeclaration","isNameOfFunctionDeclaration",
"isLiteralNameOfPropertyDeclarationOrIndexAccess",
"isExpressionOfExternalModuleImportEqualsDeclaration","isThis","isInString",
"isInsideJsxElementOrAttribute","isInTemplateString","isInJSXText",
"isPossiblyTypeArgumentPosition","isInComment","isComment",
"isStringOrRegularExpressionOrTemplateLiteral","isPunctuation",
"isInsideTemplateLiteral","isAccessibilityModifier",
"isArrayLiteralOrObjectLiteralDestructuringPattern",
"isInReferenceComment","isInNonReferenceComment","isTypeKeyword",
"isExternalModuleSymbol","isObjectBindingElementWithoutPropertyName",
"isMemberSymbolInBaseType","isFirstDeclarationOfSymbolParameter",
"isImportOrExportSpecifierName","isEqualityOperatorKind",
"isStringLiteralOrTemplate",
"isReturnStatementWithFixablePromiseHandler","isFixablePromiseHandler"
]
for(let typeItem of typeList){
try{
if(ts[typeItem](node))
opt.push(typeItem)
}catch(e){}
}
return opt
}
} | the_stack |
import {
Component,
Input,
Output,
ElementRef,
HostListener,
EventEmitter,
OnChanges,
SimpleChanges,
} from '@angular/core';
import { ISprkMastheadSelectorChoice } from '../sprk-masthead-selector/sprk-masthead-selector.interfaces';
@Component({
selector: 'sprk-masthead-selector',
template: `
<div [ngClass]="{ 'sprk-c-MastheadMask': isOpen && isFlush }">
<div [ngClass]="{ 'sprk-o-Box': isFlush }">
<a
sprkLink
variant="plain"
class="
sprk-c-Masthead__selector
sprk-o-Stack
sprk-o-Stack--split@xxs
sprk-o-Stack--center-column
"
(click)="toggle($event)"
[idString]="idString"
[analyticsString]="analyticsString"
aria-haspopup="listbox"
href="#"
[attr.aria-label]="
triggerText ? triggerText : screenReaderText || 'Choose One'
"
>
<span sprkStackItem class="sprk-o-Stack__item--flex@xxs">{{
triggerText
}}</span>
<span class="sprk-u-ScreenReaderText">{{ screenReaderText }}</span>
<sprk-icon
[iconName]="triggerIconName"
additionalClasses="sprk-Stack__item sprk-c-Masthead__selector-icon"
></sprk-icon>
</a>
</div>
<div class="sprk-c-Masthead__selector-dropdown" *ngIf="isOpen">
<div class="sprk-c-Masthead__selector-dropdown-header" *ngIf="heading">
<a
sprkLink
variant="plain"
class="sprk-o-Stack sprk-o-Stack--split@xxs sprk-o-Stack--center-column sprk-c-Masthead__selector-dropdown-header-link"
(click)="toggle($event)"
[attr.aria-label]="heading"
href="#"
>
<span
sprkStackItem
sprkText
variant="bodyTwo"
class="sprk-c-Masthead__selector-dropdown-title sprk-o-Stack__item--flex@xxs"
>{{ heading }}</span
>
<sprk-icon
[iconName]="triggerIconName"
additionalClasses="sprk-Stack__item sprk-c-Icon--toggle"
></sprk-icon>
</a>
</div>
<ul
class="sprk-c-Masthead__selector-dropdown-links"
role="listbox"
[attr.aria-label]="
heading ? heading : screenReaderText || 'My Choices'
"
>
<li
class="sprk-c-Masthead__selector-dropdown-item"
*ngFor="let choice of choices; let i = index"
(click)="choiceClick(i)"
[attr.aria-selected]="choice.active"
role="option"
>
<div *ngIf="choice.content; then content; else link"></div>
<ng-template #link>
<a
*ngIf="!choice.routerLink"
sprkLink
variant="unstyled"
[attr.href]="choice.href"
[analyticsString]="choice.analyticsString"
[ngClass]="{
'sprk-c-Masthead__selector-dropdown-link': true,
'sprk-c-Masthead__selector-dropdown-link--active':
choice.active
}"
[attr.aria-label]="choice.text"
>{{ choice.text }}
</a>
<a
*ngIf="choice.routerLink"
sprkLink
variant="unstyled"
[routerLink]="choice.routerLink"
[analyticsString]="choice.analyticsString"
[ngClass]="{
'sprk-c-Masthead__selector-dropdown-link': true,
'sprk-c-Masthead__selector-dropdown-link--active':
choice.active
}"
[attr.aria-label]="choice.text"
>{{ choice.text }}
</a>
</ng-template>
<ng-template #content>
<a
sprkLink
*ngIf="!choice.routerLink"
variant="unstyled"
[attr.href]="choice.href"
[analyticsString]="choice.analyticsString"
[ngClass]="{
'sprk-c-Masthead__selector-dropdown-link': true,
'sprk-c-Masthead__selector-dropdown-link--active':
choice.active
}"
[attr.aria-label]="choice.content.title"
>
<p sprkText variant="bodyOne">{{ choice.content.title }}</p>
<p sprkText variant="bodyTwo" *ngIf="choice.content.infoLine1">
{{ choice.content.infoLine1 }}
</p>
<p sprkText variant="bodyTwo" *ngIf="choice.content.infoLine2">
{{ choice.content.infoLine2 }}
</p>
</a>
<a
sprkLink
*ngIf="choice.routerLink"
variant="unstyled"
[routerLink]="choice.routerLink"
[analyticsString]="choice.analyticsString"
[ngClass]="{
'sprk-c-Masthead__selector-dropdown-link': true,
'sprk-c-Masthead__selector-dropdown-link--active':
choice.active
}"
[attr.aria-label]="choice.content.title"
>
<p sprkText variant="bodyOne">{{ choice.content.title }}</p>
<p sprkText variant="bodyTwo" *ngIf="choice.content.infoLine1">
{{ choice.content.infoLine1 }}
</p>
<p sprkText variant="bodyTwo" *ngIf="choice.content.infoLine2">
{{ choice.content.infoLine2 }}
</p>
</a>
</ng-template>
</li>
</ul>
<ng-content select="[sprkMastheadSelectorFooter]"></ng-content>
</div>
</div>
`,
})
export class SprkMastheadSelectorComponent implements OnChanges {
/**
* The value supplied will be visually hidden
* inside the trigger. Useful
* for when heading is empty,
* and only `triggerIconName` is supplied.
*/
@Input()
screenReaderText: string;
/**
* This value will be assigned to the Masthead Selector
* placeholder text and the dropdown heading.
*/
@Input()
heading: string;
/**
* The value supplied will be assigned
* to the `data-id` attribute on the
* component. This is intended to be
* used as a selector for automated
* tools. This value should be unique
* per page.
*/
@Input()
idString: string;
/**
* The value supplied will be assigned to the
* `data-analytics` attribute on the component.
* Intended for an outside
* library to capture data.
*/
@Input()
analyticsString: string;
/**
* Expects an array of
* [ISprkMastheadSelectorChoice](https://github.com/sparkdesignsystem/spark-design-system/blob/main/angular/projects/spark-angular/src/lib/components/sprk-masthead/components/sprk-masthead-selector/sprk-masthead-selector.interfaces.ts)
* objects.
*/
@Input()
choices: ISprkMastheadSelectorChoice[];
/**
* The name of the icon that
* renders the icon to the right
* of the trigger text.
*/
@Input()
triggerIconName: string;
/**
* The text that is initially rendered to the trigger.
*/
@Input()
triggerText: string;
/** Applies styles if the selector is flush with the sides of the viewport. */
@Input()
isFlush: boolean;
/**
* The event that is
* emitted from the Masthead Selector when a choice
* is clicked. The event contains the value
* of the choice that was clicked.
*/
@Output()
readonly choiceMade: EventEmitter<string> = new EventEmitter();
/**
* This event will be emitted
* when the Masthead Selector is opened.
*/
@Output()
readonly openedEvent: EventEmitter<any> = new EventEmitter();
/**
* This event will be emitted
* when the Masthead Selector is closed.
*/
@Output()
readonly closedEvent: EventEmitter<any> = new EventEmitter();
/**
* Keeps track of state on whether
* the selector is open or not.
*/
isOpen = false;
/**
* @ignore
*/
constructor(public ref: ElementRef) {}
/**
* @ignore
*/
ngOnChanges(changes: SimpleChanges): void {
if (this.choices && changes.choices) {
this._updateTriggerTextWithDefaultValue();
}
}
/**
* Updates the open state when the
* selector is toggled.
*/
toggle(event): void {
event.preventDefault();
this.isOpen = !this.isOpen;
if (this.isOpen) {
this.openedEvent.emit();
} else {
this.closedEvent.emit();
}
}
@HostListener('document:click', ['$event'])
onClick(event): void {
if (
!this.ref.nativeElement.contains(event.target) ||
event.target.classList.contains('sprk-c-MastheadMask')
) {
this.hideDropdown();
}
}
@HostListener('document:focusin', ['$event'])
onFocusin(event): void {
/* istanbul ignore next: angular focus event isnt setting e.target */
if (
!this.ref.nativeElement.contains(event.target) ||
event.target.classList.contains('sprk-c-MastheadMask')
) {
this.hideDropdown();
}
}
/**
* @ignore
*/
choiceClick(i) {
this.clearActiveChoices();
const clickedChoice = this.choices[i];
this.setActiveChoice(i);
this.updateTriggerText(i);
this.hideDropdown();
this.choiceMade.emit(clickedChoice['value']);
}
/**
* @ignore
*/
setActiveChoice(i): void {
this.choices[i]['active'] = true;
}
/**
* @ignore
*/
updateTriggerText(i): void {
this.triggerText = this.choices[i]['value'];
}
/**
* @ignore
*/
clearActiveChoices(): void {
this.choices.forEach((choice: ISprkMastheadSelectorChoice) => {
choice['active'] = false;
});
}
/**
* @ignore
*/
hideDropdown(): void {
this.isOpen = false;
}
/**
* Update trigger text with default choice value.
*/
protected _updateTriggerTextWithDefaultValue(): void {
const defaultChoice = this._lookupDefaultChoice();
if (defaultChoice) {
// Deactivate previously activated choices
this.clearActiveChoices();
// Mark default choice as active
defaultChoice.active = true;
// Update trigger text
this.triggerText = defaultChoice.value;
}
}
/**
* Lookup choice with specified `isDefault: true` field.
*/
protected _lookupDefaultChoice(): ISprkMastheadSelectorChoice | null {
return this.choices.find((choice) => choice.isDefault) || null;
}
} | the_stack |
import {FocusKeyManager} from '@angular/cdk/a11y';
import {Directionality} from '@angular/cdk/bidi';
import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
Input,
OnDestroy,
Optional,
QueryList,
ViewEncapsulation,
} from '@angular/core';
import {HasTabIndex, mixinTabIndex} from '@angular/material-experimental/mdc-core';
import {merge, Observable, Subject} from 'rxjs';
import {startWith, switchMap, takeUntil} from 'rxjs/operators';
import {MatChip, MatChipEvent} from './chip';
import {MatChipAction} from './chip-action';
/**
* Boilerplate for applying mixins to MatChipSet.
* @docs-private
*/
abstract class MatChipSetBase {
abstract disabled: boolean;
constructor(_elementRef: ElementRef) {}
}
const _MatChipSetMixinBase = mixinTabIndex(MatChipSetBase);
/**
* Basic container component for the MatChip component.
*
* Extended by MatChipListbox and MatChipGrid for different interaction patterns.
*/
@Component({
selector: 'mat-chip-set',
template: `
<span class="mdc-evolution-chip-set__chips" role="presentation">
<ng-content></ng-content>
</span>
`,
styleUrls: ['chip-set.css'],
host: {
'class': 'mat-mdc-chip-set mdc-evolution-chip-set',
'(keydown)': '_handleKeydown($event)',
'[attr.role]': 'role',
},
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatChipSet
extends _MatChipSetMixinBase
implements AfterViewInit, HasTabIndex, OnDestroy
{
/** Index of the last destroyed chip that had focus. */
private _lastDestroyedFocusedChipIndex: number | null = null;
/** Used to manage focus within the chip list. */
protected _keyManager: FocusKeyManager<MatChipAction>;
/** Subject that emits when the component has been destroyed. */
protected _destroyed = new Subject<void>();
/** Role to use if it hasn't been overwritten by the user. */
protected _defaultRole = 'presentation';
/** Combined stream of all of the child chips' focus events. */
get chipFocusChanges(): Observable<MatChipEvent> {
return this._getChipStream(chip => chip._onFocus);
}
/** Combined stream of all of the child chips' remove events. */
get chipDestroyedChanges(): Observable<MatChipEvent> {
return this._getChipStream(chip => chip.destroyed);
}
/** Whether the chip set is disabled. */
@Input()
get disabled(): boolean {
return this._disabled;
}
set disabled(value: BooleanInput) {
this._disabled = coerceBooleanProperty(value);
this._syncChipsState();
}
protected _disabled: boolean = false;
/** Whether the chip list contains chips or not. */
get empty(): boolean {
return this._chips.length === 0;
}
/** The ARIA role applied to the chip set. */
@Input()
get role(): string | null {
if (this._explicitRole) {
return this._explicitRole;
}
return this.empty ? null : this._defaultRole;
}
set role(value: string | null) {
this._explicitRole = value;
}
private _explicitRole: string | null = null;
/** Whether any of the chips inside of this chip-set has focus. */
get focused(): boolean {
return this._hasFocusedChip();
}
/** The chips that are part of this chip set. */
@ContentChildren(MatChip, {
// We need to use `descendants: true`, because Ivy will no longer match
// indirect descendants if it's left as false.
descendants: true,
})
_chips: QueryList<MatChip>;
/** Flat list of all the actions contained within the chips. */
_chipActions = new QueryList<MatChipAction>();
constructor(
protected _elementRef: ElementRef<HTMLElement>,
protected _changeDetectorRef: ChangeDetectorRef,
@Optional() private _dir: Directionality,
) {
super(_elementRef);
}
ngAfterViewInit() {
this._setUpFocusManagement();
this._trackChipSetChanges();
this._trackDestroyedFocusedChip();
}
ngOnDestroy() {
this._chipActions.destroy();
this._destroyed.next();
this._destroyed.complete();
}
/** Checks whether any of the chips is focused. */
protected _hasFocusedChip() {
return this._chips && this._chips.some(chip => chip._hasFocus());
}
/** Syncs the chip-set's state with the individual chips. */
protected _syncChipsState() {
if (this._chips) {
this._chips.forEach(chip => {
chip.disabled = this._disabled;
chip._changeDetectorRef.markForCheck();
});
}
}
/** Dummy method for subclasses to override. Base chip set cannot be focused. */
focus() {}
/** Handles keyboard events on the chip set. */
_handleKeydown(event: KeyboardEvent) {
if (this._originatesFromChip(event)) {
this._keyManager.onKeydown(event);
}
}
/**
* Utility to ensure all indexes are valid.
*
* @param index The index to be checked.
* @returns True if the index is valid for our list of chips.
*/
protected _isValidIndex(index: number): boolean {
return index >= 0 && index < this._chips.length;
}
/**
* Removes the `tabindex` from the chip grid and resets it back afterwards, allowing the
* user to tab out of it. This prevents the grid from capturing focus and redirecting
* it back to the first chip, creating a focus trap, if it user tries to tab away.
*/
protected _allowFocusEscape() {
const previousTabIndex = this.tabIndex;
if (this.tabIndex !== -1) {
this.tabIndex = -1;
setTimeout(() => {
this.tabIndex = previousTabIndex;
this._changeDetectorRef.markForCheck();
});
}
}
/**
* Gets a stream of events from all the chips within the set.
* The stream will automatically incorporate any newly-added chips.
*/
protected _getChipStream<T, C extends MatChip = MatChip>(
mappingFunction: (chip: C) => Observable<T>,
): Observable<T> {
return this._chips.changes.pipe(
startWith(null),
switchMap(() => merge(...(this._chips as QueryList<C>).map(mappingFunction))),
);
}
/** Checks whether an event comes from inside a chip element. */
protected _originatesFromChip(event: Event): boolean {
let currentElement = event.target as HTMLElement | null;
while (currentElement && currentElement !== this._elementRef.nativeElement) {
// Null check the classList, because IE and Edge don't support it on all elements.
if (currentElement.classList && currentElement.classList.contains('mdc-evolution-chip')) {
return true;
}
currentElement = currentElement.parentElement;
}
return false;
}
/** Sets up the chip set's focus management logic. */
private _setUpFocusManagement() {
// Create a flat `QueryList` containing the actions of all of the chips.
// This allows us to navigate both within the chip and move to the next/previous
// one using the existing `ListKeyManager`.
this._chips.changes.pipe(startWith(this._chips)).subscribe((chips: QueryList<MatChip>) => {
const actions: MatChipAction[] = [];
chips.forEach(chip => chip._getActions().forEach(action => actions.push(action)));
this._chipActions.reset(actions);
this._chipActions.notifyOnChanges();
});
this._keyManager = new FocusKeyManager(this._chipActions)
.withVerticalOrientation()
.withHorizontalOrientation(this._dir ? this._dir.value : 'ltr')
.withHomeAndEnd()
// Skip non-interactive and disabled actions since the user can't do anything with them.
.skipPredicate(action => !action.isInteractive || action.disabled);
// Keep the manager active index in sync so that navigation picks
// up from the current chip if the user clicks into the list directly.
this.chipFocusChanges.pipe(takeUntil(this._destroyed)).subscribe(({chip}) => {
const action = chip._getSourceAction(document.activeElement as Element);
if (action) {
this._keyManager.updateActiveItem(action);
}
});
this._dir?.change
.pipe(takeUntil(this._destroyed))
.subscribe(direction => this._keyManager.withHorizontalOrientation(direction));
}
/** Listens to changes in the chip set and syncs up the state of the individual chips. */
private _trackChipSetChanges() {
this._chips.changes.pipe(startWith(null), takeUntil(this._destroyed)).subscribe(() => {
if (this.disabled) {
// Since this happens after the content has been
// checked, we need to defer it to the next tick.
Promise.resolve().then(() => this._syncChipsState());
}
this._redirectDestroyedChipFocus();
});
}
/** Starts tracking the destroyed chips in order to capture the focused one. */
private _trackDestroyedFocusedChip() {
this.chipDestroyedChanges.pipe(takeUntil(this._destroyed)).subscribe((event: MatChipEvent) => {
const chipArray = this._chips.toArray();
const chipIndex = chipArray.indexOf(event.chip);
// If the focused chip is destroyed, save its index so that we can move focus to the next
// chip. We only save the index here, rather than move the focus immediately, because we want
// to wait until the chip is removed from the chip list before focusing the next one. This
// allows us to keep focus on the same index if the chip gets swapped out.
if (this._isValidIndex(chipIndex) && event.chip._hasFocus()) {
this._lastDestroyedFocusedChipIndex = chipIndex;
}
});
}
/**
* Finds the next appropriate chip to move focus to,
* if the currently-focused chip is destroyed.
*/
private _redirectDestroyedChipFocus() {
if (this._lastDestroyedFocusedChipIndex == null) {
return;
}
if (this._chips.length) {
const newIndex = Math.min(this._lastDestroyedFocusedChipIndex, this._chips.length - 1);
const chipToFocus = this._chips.toArray()[newIndex];
if (chipToFocus.disabled) {
// If we're down to one disabled chip, move focus back to the set.
if (this._chips.length === 1) {
this.focus();
} else {
this._keyManager.setPreviousItemActive();
}
} else {
chipToFocus.focus();
}
} else {
this.focus();
}
this._lastDestroyedFocusedChipIndex = null;
}
} | the_stack |
import { ActionContext } from './ActionContext';
import { Component } from '../EntityComponentSystem/Component';
import { Entity } from '../EntityComponentSystem/Entity';
import { Actor } from '../Actor';
import { MotionComponent } from '../EntityComponentSystem/Components/MotionComponent';
import { TransformComponent } from '../EntityComponentSystem/Components/TransformComponent';
import { Vector } from '../Math/vector';
import { EasingFunction } from '../Util/EasingFunctions';
import { ActionQueue } from './ActionQueue';
import { RotationType } from './RotationType';
export interface ActionContextMethods extends Pick<ActionContext, keyof ActionContext> { };
export class ActionsComponent extends Component<'ex.actions'> implements ActionContextMethods {
public readonly type = 'ex.actions';
dependencies = [TransformComponent, MotionComponent]
private _ctx: ActionContext;
onAdd(entity: Entity) {
this._ctx = new ActionContext(entity);
}
onRemove() {
this._ctx = null;
}
/**
* Returns the internal action queue
* @returns action queu
*/
public getQueue(): ActionQueue {
return this._ctx?.getQueue();
}
/**
* Updates the internal action context, performing action and moving through the internal queue
* @param elapsedMs
*/
public update(elapsedMs: number): void {
return this._ctx?.update(elapsedMs);
}
/**
* Clears all queued actions from the Actor
*/
public clearActions(): void {
this._ctx?.clearActions();
}
/**
* This method will move an actor to the specified `x` and `y` position over the
* specified duration using a given [[EasingFunctions]] and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param pos The x,y vector location to move the actor to
* @param duration The time it should take the actor to move to the new location in milliseconds
* @param easingFcn Use [[EasingFunctions]] or a custom function to use to calculate position, Default is [[EasingFunctions.Linear]]
*/
public easeTo(pos: Vector, duration: number, easingFcn?: EasingFunction): ActionContext;
/**
* This method will move an actor to the specified `x` and `y` position over the
* specified duration using a given [[EasingFunctions]] and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param x The x location to move the actor to
* @param y The y location to move the actor to
* @param duration The time it should take the actor to move to the new location in milliseconds
* @param easingFcn Use [[EasingFunctions]] or a custom function to use to calculate position, Default is [[EasingFunctions.Linear]]
*/
public easeTo(x: number, y: number, duration: number, easingFcn?: EasingFunction): ActionContext;
public easeTo(...args: any[]): ActionContext {
return this._ctx.easeTo.apply(this._ctx, args);
}
/**
* This method will move an actor to the specified x and y position at the
* speed specified (in pixels per second) and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param pos The x,y vector location to move the actor to
* @param speed The speed in pixels per second to move
*/
public moveTo(pos: Vector, speed: number): ActionContext;
/**
* This method will move an actor to the specified x and y position at the
* speed specified (in pixels per second) and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param x The x location to move the actor to
* @param y The y location to move the actor to
* @param speed The speed in pixels per second to move
*/
public moveTo(x: number, y: number, speed: number): ActionContext;
public moveTo(xOrPos: number | Vector, yOrSpeed: number, speedOrUndefined?: number): ActionContext {
return this._ctx.moveTo.apply(this._ctx, [xOrPos, yOrSpeed, speedOrUndefined]);
}
/**
* This method will move an actor by the specified x offset and y offset from its current position, at a certain speed.
* This method is part of the actor 'Action' fluent API allowing action chaining.
* @param offset The (x, y) offset to apply to this actor
* @param speed The speed in pixels per second the actor should move
*/
public moveBy(offset: Vector, speed: number): ActionContext;
/**
* This method will move an actor by the specified x offset and y offset from its current position, at a certain speed.
* This method is part of the actor 'Action' fluent API allowing action chaining.
* @param xOffset The x offset to apply to this actor
* @param yOffset The y location to move the actor to
* @param speed The speed in pixels per second the actor should move
*/
public moveBy(xOffset: number, yOffset: number, speed: number): ActionContext;
public moveBy(xOffsetOrVector: number | Vector, yOffsetOrSpeed: number, speedOrUndefined?: number): ActionContext {
return this._ctx.moveBy.apply(this._ctx, [xOffsetOrVector, yOffsetOrSpeed, speedOrUndefined]);
}
/**
* This method will rotate an actor to the specified angle at the speed
* specified (in radians per second) and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param angleRadians The angle to rotate to in radians
* @param speed The angular velocity of the rotation specified in radians per second
* @param rotationType The [[RotationType]] to use for this rotation
*/
public rotateTo(angleRadians: number, speed: number, rotationType?: RotationType): ActionContext {
return this._ctx.rotateTo(angleRadians, speed, rotationType);
}
/**
* This method will rotate an actor by the specified angle offset, from it's current rotation given a certain speed
* in radians/sec and return back the actor. This method is part
* of the actor 'Action' fluent API allowing action chaining.
* @param angleRadiansOffset The angle to rotate to in radians relative to the current rotation
* @param speed The speed in radians/sec the actor should rotate at
* @param rotationType The [[RotationType]] to use for this rotation, default is shortest path
*/
public rotateBy(angleRadiansOffset: number, speed: number, rotationType?: RotationType): ActionContext {
return this._ctx.rotateBy(angleRadiansOffset, speed, rotationType);
}
/**
* This method will scale an actor to the specified size at the speed
* specified (in magnitude increase per second) and return back the
* actor. This method is part of the actor 'Action' fluent API allowing
* action chaining.
* @param size The scale to adjust the actor to over time
* @param speed The speed of scaling specified in magnitude increase per second
*/
public scaleTo(size: Vector, speed: Vector): ActionContext;
/**
* This method will scale an actor to the specified size at the speed
* specified (in magnitude increase per second) and return back the
* actor. This method is part of the actor 'Action' fluent API allowing
* action chaining.
* @param sizeX The scaling factor to apply on X axis
* @param sizeY The scaling factor to apply on Y axis
* @param speedX The speed of scaling specified in magnitude increase per second on X axis
* @param speedY The speed of scaling specified in magnitude increase per second on Y axis
*/
public scaleTo(sizeX: number, sizeY: number, speedX: number, speedY: number): ActionContext;
public scaleTo(
sizeXOrVector: number | Vector,
sizeYOrSpeed: number | Vector,
speedXOrUndefined?: number,
speedYOrUndefined?: number): ActionContext {
return this._ctx.scaleTo.apply(this._ctx, [sizeXOrVector, sizeYOrSpeed, speedXOrUndefined, speedYOrUndefined]);
}
/**
* This method will scale an actor by an amount relative to the current scale at a certain speed in scale units/sec
* and return back the actor. This method is part of the
* actor 'Action' fluent API allowing action chaining.
* @param offset The scaling factor to apply to the actor
* @param speed The speed to scale at in scale units/sec
*/
public scaleBy(offset: Vector, speed: number): ActionContext;
/**
* This method will scale an actor by an amount relative to the current scale at a certain speed in scale units/sec
* and return back the actor. This method is part of the
* actor 'Action' fluent API allowing action chaining.
* @param sizeOffsetX The scaling factor to apply on X axis
* @param sizeOffsetY The scaling factor to apply on Y axis
* @param speed The speed to scale at in scale units/sec
*/
public scaleBy(sizeOffsetX: number, sizeOffsetY: number, speed: number): ActionContext;
public scaleBy(sizeOffsetXOrVector: number | Vector, sizeOffsetYOrSpeed: number, speed?: number): ActionContext {
return this._ctx.scaleBy.apply(this._ctx, [sizeOffsetXOrVector, sizeOffsetYOrSpeed, speed]);
}
/**
* This method will cause an actor to blink (become visible and not
* visible). Optionally, you may specify the number of blinks. Specify the amount of time
* the actor should be visible per blink, and the amount of time not visible.
* This method is part of the actor 'Action' fluent API allowing action chaining.
* @param timeVisible The amount of time to stay visible per blink in milliseconds
* @param timeNotVisible The amount of time to stay not visible per blink in milliseconds
* @param numBlinks The number of times to blink
*/
public blink(timeVisible: number, timeNotVisible: number, numBlinks?: number): ActionContext {
return this._ctx.blink(timeVisible, timeNotVisible, numBlinks);
}
/**
* This method will cause an actor's opacity to change from its current value
* to the provided value by a specified time (in milliseconds). This method is
* part of the actor 'Action' fluent API allowing action chaining.
* @param opacity The ending opacity
* @param time The time it should take to fade the actor (in milliseconds)
*/
public fade(opacity: number, time: number): ActionContext {
return this._ctx.fade(opacity, time);
}
/**
* This method will delay the next action from executing for a certain
* amount of time (in milliseconds). This method is part of the actor
* 'Action' fluent API allowing action chaining.
* @param time The amount of time to delay the next action in the queue from executing in milliseconds
*/
public delay(time: number): ActionContext {
return this._ctx.delay(time);
}
/**
* This method will add an action to the queue that will remove the actor from the
* scene once it has completed its previous Any actions on the
* action queue after this action will not be executed.
*/
public die(): ActionContext {
return this._ctx.die();
}
/**
* This method allows you to call an arbitrary method as the next action in the
* action queue. This is useful if you want to execute code in after a specific
* action, i.e An actor arrives at a destination after traversing a path
*/
public callMethod(method: () => any): ActionContext {
return this._ctx.callMethod(method);
}
/**
* This method will cause the actor to repeat all of the actions built in
* the `repeatBuilder` callback. If the number of repeats
* is not specified it will repeat forever. This method is part of
* the actor 'Action' fluent API allowing action chaining
*
* ```typescript
* // Move up in a zig-zag by repeated moveBy's
* actor.actions.repeat(repeatCtx => {
* repeatCtx.moveBy(10, 0, 10);
* repeatCtx.moveBy(0, 10, 10);
* }, 5);
* ```
*
* @param repeatBuilder The builder to specify the repeatable list of actions
* @param times The number of times to repeat all the previous actions in the action queue. If nothing is specified the actions
* will repeat forever
*/
public repeat(repeatBuilder: (repeatContext: ActionContext) => any, times?: number): ActionContext {
return this._ctx.repeat(repeatBuilder, times);
}
/**
* This method will cause the actor to repeat all of the actions built in
* the `repeatBuilder` callback. If the number of repeats
* is not specified it will repeat forever. This method is part of
* the actor 'Action' fluent API allowing action chaining
*
* ```typescript
* // Move up in a zig-zag by repeated moveBy's
* actor.actions.repeat(repeatCtx => {
* repeatCtx.moveBy(10, 0, 10);
* repeatCtx.moveBy(0, 10, 10);
* }, 5);
* ```
*
* @param repeatBuilder The builder to specify the repeatable list of actions
*/
public repeatForever(repeatBuilder: (repeatContext: ActionContext) => any): ActionContext {
return this._ctx.repeatForever(repeatBuilder);
}
/**
* This method will cause the entity to follow another at a specified distance
* @param entity The entity to follow
* @param followDistance The distance to maintain when following, if not specified the actor will follow at the current distance.
*/
public follow(entity: Actor, followDistance?: number): ActionContext {
return this._ctx.follow(entity, followDistance);
}
/**
* This method will cause the entity to move towards another until they
* collide "meet" at a specified speed.
* @param entity The entity to meet
* @param speed The speed in pixels per second to move, if not specified it will match the speed of the other actor
*/
public meet(entity: Actor, speed?: number): ActionContext {
return this._ctx.meet(entity, speed);
}
/**
* Returns a promise that resolves when the current action queue up to now
* is finished.
* @deprecated Use `toPromise()` will be removed in v0.26.0
*/
public asPromise(): Promise<void> {
return this.toPromise();
}
/**
* Returns a promise that resolves when the current action queue up to now
* is finished.
*/
public toPromise(): Promise<void> {
return this._ctx.toPromise();
}
} | the_stack |
* An [[Attestation]] certifies a [[Claim]], sent by a claimer in the form of a [[RequestForAttestation]]. [[Attestation]]s are **written on the blockchain** and are **revocable**.
* Note: once an [[Attestation]] is stored, it can be sent to and stored with the claimer as a [[Credential]].
*
* An [[Attestation]] can be queried from the chain. It's stored on-chain in a map:
* * the key is the hash of the corresponding claim;
* * the value is a tuple ([[CType]] hash, account, id of the Delegation, and revoked flag).
*
* @packageDocumentation
* @module Attestation
* @preferred
*/
import type { SubmittableExtrinsic } from '@polkadot/api/promise/types'
import type {
IAttestation,
IDelegationHierarchyDetails,
IRequestForAttestation,
CompressedAttestation,
} from '@kiltprotocol/types'
import { BN } from '@polkadot/util'
import {
revoke,
query,
store,
remove,
reclaimDeposit,
queryDepositAmount,
} from './Attestation.chain'
import * as AttestationUtils from './Attestation.utils'
import { DelegationNode } from '../delegation/DelegationNode'
export class Attestation implements IAttestation {
/**
* [STATIC] [ASYNC] Queries the chain for a given attestation, by `claimHash`.
*
* @param claimHash - The hash of the claim that corresponds to the attestation to query.
* @returns A promise containing the [[Attestation]] or null.
* @example ```javascript
* Attestation.query('0xd8024cdc147c4fa9221cd177').then((attestation) => {
* // now we can for example revoke `attestation`
* });
* ```
*/
public static async query(claimHash: string): Promise<Attestation | null> {
return query(claimHash)
}
/**
* [STATIC] [ASYNC] Revokes an attestation. Also available as an instance method.
*
* @param claimHash - The hash of the claim that corresponds to the attestation to revoke.
* @param maxDepth - The number of levels to walk up the delegation hierarchy until the delegation node is found.
* @returns A promise containing the unsigned SubmittableExtrinsic (submittable transaction).
* @example ```javascript
* Attestation.revoke('0xd8024cdc147c4fa9221cd177', 3).then(
* (revocationExtrinsic) => {
* // The attestation revocation tx was created, and it can now be signed by the attestation owner.
* attestationOwnerDid
* .authorizeExtrinsic(revocationExtrinsic, keystore, submitter.address)
* .then((authorizedExtrinsic) => {
* // The DID-authorized tx is ready to be submitted!
* BlockchainUtils.signAndSendTx(authorizedExtrinsic, submitter);
* });
* }
* );
* ```
*/
public static async revoke(
claimHash: string,
maxDepth: number
): Promise<SubmittableExtrinsic> {
return revoke(claimHash, maxDepth)
}
/**
* [STATIC] [ASYNC] Removes an attestation. Also available as an instance method.
*
* @param claimHash - The hash of the claim that corresponds to the attestation to remove.
* @param maxDepth - The number of levels to walk up the delegation hierarchy until the delegation node is found.
* @returns A promise containing the unsigned SubmittableExtrinsic (submittable transaction).
* @example ```javascript
* Attestation.remove('0xd8024cdc147c4fa9221cd177', 3).then((removalExtrinsic) => {
* // The attestation removal tx was created, and it can now be signed by the attestation owner.
* attestationOwnerDid
* .authorizeExtrinsic(removalExtrinsic, keystore, submitter.address)
* .then((authorizedExtrinsic) => {
* // The DID-authorized tx is ready to be submitted!
* BlockchainUtils.signAndSendTx(authorizedExtrinsic, submitter);
* });
* });
* ```
*/
public static async remove(
claimHash: string,
maxDepth: number
): Promise<SubmittableExtrinsic> {
return remove(claimHash, maxDepth)
}
/**
* [STATIC] [ASYNC] Reclaims the deposit of an attestation and removes the attestation. Also available as an instance method.
*
* This call can only be successfully executed if the submitter of the transaction is the original payer of the attestation deposit.
*
* @param claimHash - The hash of the claim that corresponds to the attestation to remove and its deposit to be returned to the original payer.
* @returns A promise containing the unsigned SubmittableExtrinsic (submittable transaction).
* @example ```javascript
* Attestation.reclaimDeposit('0xd8024cdc147c4fa9221cd177').then(
* (claimExtrinsic) => {
* // The deposit claiming tx was created, and it can now be submitted by the attestation deposit payer ONLY.
* BlockchainUtils.signAndSendTx(claimExtrinsic, submitter);
* }
* );
* ```
*/
public static async reclaimDeposit(
claimHash: string
): Promise<SubmittableExtrinsic> {
return reclaimDeposit(claimHash)
}
/**
* [STATIC] Builds an instance of [[Attestation]], from a simple object with the same properties.
* Used for deserialization.
*
* @param attestationInput - The base object from which to create the attestation.
* @returns A new [[Attestation]] object.
* @example ```javascript
* // create an Attestation object, so we can call methods on it (`serialized` is a serialized Attestation object )
* Attestation.fromAttestation(JSON.parse(serialized));
* ```
*/
public static fromAttestation(attestationInput: IAttestation): Attestation {
return new Attestation(attestationInput)
}
/**
* [STATIC] Builds a new instance of an [[Attestation]], from a complete set of input required for an attestation.
*
* @param request - The base request for attestation.
* @param attesterDid - The attester's did, used to attest to the underlying claim.
* @returns A new [[Attestation]] object.
* @example ```javascript
* // create a complete new attestation from the `RequestForAttestation` and all other needed properties
* Attestation.fromRequestAndDid(request, attesterDid);
* ```
*/
public static fromRequestAndDid(
request: IRequestForAttestation,
attesterDid: string
): Attestation {
return new Attestation({
claimHash: request.rootHash,
cTypeHash: request.claim.cTypeHash,
delegationId: request.delegationId,
owner: attesterDid,
revoked: false,
})
}
/**
* [STATIC] [ASYNC] Tries to query the delegationId and if successful query the rootId.
*
* @param delegationId - The Id of the Delegation stored in [[Attestation]].
* @returns A promise of either null if querying was not successful or the affiliated [[DelegationNode]].
*/
public static async getDelegationDetails(
delegationId: IAttestation['delegationId'] | null
): Promise<IDelegationHierarchyDetails | null> {
if (!delegationId) {
return null
}
const delegationNode: DelegationNode | null = await DelegationNode.query(
delegationId
)
if (!delegationNode) {
return null
}
return delegationNode.getHierarchyDetails()
}
public async getDelegationDetails(): Promise<IDelegationHierarchyDetails | null> {
return Attestation.getDelegationDetails(this.delegationId)
}
/**
* [STATIC] Custom Type Guard to determine input being of type IAttestation using the AttestationUtils errorCheck.
*
* @param input The potentially only partial IAttestation.
* @returns Boolean whether input is of type IAttestation.
*/
public static isIAttestation(input: unknown): input is IAttestation {
try {
AttestationUtils.errorCheck(input as IAttestation)
} catch (error) {
return false
}
return true
}
public claimHash: IAttestation['claimHash']
public cTypeHash: IAttestation['cTypeHash']
public delegationId: IAttestation['delegationId'] | null
public owner: IAttestation['owner']
public revoked: IAttestation['revoked']
/**
* Builds a new [[Attestation]] instance.
*
* @param attestationInput - The base object from which to create the attestation.
* @example ```javascript
* // create an attestation, e.g. to store it on-chain
* const attestation = new Attestation(attestationInput);
* ```
*/
public constructor(attestationInput: IAttestation) {
AttestationUtils.errorCheck(attestationInput)
this.claimHash = attestationInput.claimHash
this.cTypeHash = attestationInput.cTypeHash
this.delegationId = attestationInput.delegationId
this.owner = attestationInput.owner
this.revoked = attestationInput.revoked
}
/**
* [ASYNC] Prepares an extrinsic to store the attestation on chain.
*
* @returns A promise containing the unsigned SubmittableExtrinsic (submittable transaction).
* @example ```javascript
* // Use `store` to store an attestation on chain, and to create a `Credential` upon success:
* attestation.store().then((creationExtrinsic) => {
* // the attestation store tx was successfully prepared, so now we can sign and send it and subsequently create a `Credential`.
* attestationOwnerDid
* .authorizeExtrinsic(creationExtrinsic, keystore, submitter.address)
* .then((authorizedExtrinsic) => {
* // The DID-authorized tx is ready to be submitted!
* BlockchainUtils.signAndSendTx(authorizedExtrinsic, submitter);
* });
* });
* // The attestation creation tx was created, and it can now be signed by a DID owner.
* const authorizedExtrinsic = await attestationOwnerDid.authorizeExtrinsic(
* creationExtrinsic,
* keystore,
* submitter.address
* );
* // The DID-authorized tx is ready to be submitted!
* BlockchainUtils.signAndSendTx(authorizedExtrinsic, submitter);
* ```
*/
public async store(): Promise<SubmittableExtrinsic> {
return store(this)
}
/**
* [ASYNC] Prepares an extrinisc to revoke the attestation. Also available as a static method.
*
* @param maxDepth - The number of levels to walk up the delegation hierarchy until the delegation node is found.
* @returns A promise containing the unsigned SubmittableExtrinsic (submittable transaction).
* @example ```javascript
* attestation.revoke(3).then((revocationExtrinsic) => {
* // The attestation revocation tx was created, and it can now be signed by the attestation owner.
* attestationOwnerDid
* .authorizeExtrinsic(revocationExtrinsic, keystore, submitter.address)
* .then((authorizedExtrinsic) => {
* // The DID-authorized tx is ready to be submitted!
* BlockchainUtils.signAndSendTx(authorizedExtrinsic, submitter);
* });
* });
* ```
*/
public async revoke(maxDepth: number): Promise<SubmittableExtrinsic> {
return revoke(this.claimHash, maxDepth)
}
/**
* [ASYNC] Prepares an extrinsic to remove the attestation. Also available as a static method.
*
* @param maxDepth - The number of levels to walk up the delegation hierarchy until the delegation node is found.
* @returns A promise containing the unsigned SubmittableExtrinsic (submittable transaction).
* @example ```javascript
* attestation.remove(3).then((removalExtrinsic) => {
* // The attestation removal tx was created, and it can now be signed by the attestation owner.
* attestationOwnerDid
* .authorizeExtrinsic(removalExtrinsic, keystore, submitter.address)
* .then((authorizedExtrinsic) => {
* // The DID-authorized tx is ready to be submitted!
* BlockchainUtils.signAndSendTx(authorizedExtrinsic, submitter);
* });
* });
* ```
*/
public async remove(maxDepth: number): Promise<SubmittableExtrinsic> {
return remove(this.claimHash, maxDepth)
}
/**
* [STATIC] [ASYNC] Reclaims the deposit of an attestation and removes the attestation. Also available as an instance method.
*
* This call can only be successfully executed if the submitter of the transaction is the original payer of the attestation deposit.
*
* @returns A promise containing the unsigned SubmittableExtrinsic (submittable transaction).
* @example ```javascript
* attestation.reclaimDeposit().then((claimExtrinsic) => {
* // The deposit claiming tx was created, and it can now be submitted by the attestation deposit payer ONLY.
* BlockchainUtils.signAndSendTx(claimExtrinsic, submitter);
* });
* ```
*/
public async reclaimDeposit(): Promise<SubmittableExtrinsic> {
return reclaimDeposit(this.claimHash)
}
/**
* [STATIC] [ASYNC] Queries an attestation from the chain and checks its validity.
*
* @param attestation - The Attestation to verify.
* @param claimHash - The hash of the claim that corresponds to the attestation to check. Defaults to the claimHash for the attestation onto which "verify" is called.
* @returns A promise containing whether the attestation is valid.
* @example ```javascript
* Attestation.checkValidity(attestation).then((isVerified) => {
* // `isVerified` is true if the attestation is verified, false otherwise
* });
* ```
*/
public static async checkValidity(
attestation: IAttestation,
claimHash: string = attestation.claimHash
): Promise<boolean> {
// Query attestation by claimHash. null if no attestation is found on-chain for this hash
const chainAttestation: Attestation | null = await Attestation.query(
claimHash
)
return !!(
chainAttestation !== null &&
chainAttestation.owner === attestation.owner &&
!chainAttestation.revoked
)
}
public async checkValidity(): Promise<boolean> {
return Attestation.checkValidity(this)
}
/**
* Compresses an [[Attestation]] object.
*
* @returns An array that contains the same properties of an [[Attestation]].
*/
public compress(): CompressedAttestation {
return AttestationUtils.compress(this)
}
/**
* [STATIC] Builds an [[Attestation]] from the compressed array.
*
* @param attestation The [[CompressedAttestation]] that should get decompressed.
* @returns A new [[Attestation]] object.
*/
public static decompress(attestation: CompressedAttestation): Attestation {
const decompressedAttestation = AttestationUtils.decompress(attestation)
return Attestation.fromAttestation(decompressedAttestation)
}
/**
* [STATIC] Query and return the amount of KILTs (in femto notation) needed to deposit in order to create an attestation.
*
* @returns The amount of femtoKILTs required to deposit to create the attestation.
*/
public static queryDepositAmount(): Promise<BN> {
return queryDepositAmount()
}
} | the_stack |
import {assert} from 'chai';
import {StringSpan} from '../src/IonSpan';
import {ParserTextRaw} from '../src/IonParserTextRaw';
import {IonTypes} from "../src/IonTypes";
import {IonType} from "../src/IonType";
import JSBI from "jsbi";
import {SymbolToken} from "../src/IonSymbolToken";
// a few notes/surprises:
// - fieldNameType() always appears to return 9 (T_IDENTIFIER) when positioned on a field,
// and is otherwise null; consider removing it
// - get_value_as_string() throws for CLOBs, but no other scalars; its general contract
// appears to be to return the parsed text of the current value. blob seems special, too,
// as it returns 'aGVsbG8' for the Ion `{{aGVsbG8=}}`
// - get_value_as_uint8array() throws for BLOBs (why?)
describe('IonParserTextRaw', () => {
[
{
type: IonTypes.NULL, T_id: 1, // T_NULL
tests: [
{ion: 'null', expected: null},
{ion: 'null.null', expected: null},
],
},
{
type: IonTypes.BOOL, T_id: 2, // T_BOOL
tests: [
{ion: 'null.bool', expected: null},
{ion: 'true', expected: true},
{ion: 'false', expected: false},
],
},
{
type: IonTypes.INT, T_id: 3, // T_INT
tests: [
{ion: 'null.int', expected: null},
{ion: '0', expected: JSBI.BigInt('0')},
{ion: '1', expected: JSBI.BigInt('1')},
{ion: '-1', expected: JSBI.BigInt('-1')},
],
},
{
type: IonTypes.FLOAT, T_id: 5, // T_FLOAT
tests: [
{ion: 'null.float', expected: null},
{ion: '0e0', expected: 0},
{ion: '-0e0', expected: -0},
{ion: '1e0', expected: 1},
],
},
{
type: IonTypes.FLOAT, T_id: 6, // T_FLOAT_SPECIAL
tests: [
{ion: '+inf', expected: Infinity},
{ion: '-inf', expected: -Infinity},
{ion: 'nan', expected: NaN},
],
},
{
type: IonTypes.DECIMAL, T_id: 7, // T_DECIMAL
tests: [
{ion: 'null.decimal', expected: null},
{ion: '0d0', expected: 0},
{ion: '1d0', expected: 1},
{ion: '1d1', expected: 10},
{ion: '1d-1', expected: 0.1},
{ion: '-0.0001', expected: -0.0001},
],
},
{
type: IonTypes.TIMESTAMP, T_id: 8, // T_TIMESTAMP
tests: [
{ion: 'null.timestamp', expected: null},
{ion: '2017T'},
{ion: '2001-02-03T04:05:06.123456789-12:34'},
],
},
{
type: IonTypes.SYMBOL, T_id: 9, // T_IDENTIFIER
tests: [
{ion: 'null.symbol', expected: null},
{ion: 'hello'},
],
},
{
type: IonTypes.STRING, T_id: 12, // T_STRING2
tests: [
{ion: 'null.string', expected: null},
{ion: '"hello"', expectedStr: 'hello'},
],
},
{
type: IonTypes.CLOB, T_id: 14, // T_CLOB2
tests: [
{ion: 'null.clob', expected: null},
{ion: '{{"hello"}}', expected: Uint8Array.from([0x68, 0x65, 0x6c, 0x6c, 0x6f])},
],
},
{
type: IonTypes.BLOB, T_id: 16, // T_BLOB
tests: [
{ion: 'null.blob', expected: null},
{ion: '{{aGVsbG8=}}', expectedStr: 'aGVsbG8'},
],
},
{
type: IonTypes.LIST, T_id: 18, // T_LIST
tests: [
{ion: 'null.list', expected: null},
],
},
{
type: IonTypes.SEXP, T_id: 17, // T_SEXP
tests: [
{ion: 'null.sexp', expected: null},
],
},
{
type: IonTypes.STRUCT, T_id: 19, // T_STRUCT
tests: [
{ion: 'null.struct', expected: null},
],
},
].forEach((testSet: {type: IonType, T_id: number, tests: {ion: string, expected: any, expectedStr: string}[]}) => {
describe('Reads ' + testSet.type.name + ' value', () => {
testSet.tests.forEach((test: {ion: string, expected: any, expectedStr: string}) => {
it(test.ion, () => {
let p = new ParserTextRaw(new StringSpan(test.ion));
assert.equal(p.isNull(), false);
assert.equal(p.next(), testSet.T_id);
assert.equal(p.isNull(), test.expected === null);
assert.isNull(p.fieldName());
assert.isNull(p.fieldNameType());
assert.deepEqual([], p.annotations());
if (p.isNull()) {
assert.isNull(p.booleanValue());
assert.isNull(p.bigIntValue());
assert.isNull(p.numberValue());
switch (testSet.type) {
case IonTypes.NULL:
case IonTypes.BOOL:
case IonTypes.INT:
case IonTypes.FLOAT:
case IonTypes.DECIMAL:
case IonTypes.TIMESTAMP:
case IonTypes.SYMBOL:
case IonTypes.STRING:
case IonTypes.BLOB:
assert.equal(p.get_value_as_string(testSet.T_id), '');
break;
default:
assert.throws(() => p.get_value_as_string(testSet.T_id));
}
} else {
switch (testSet.type) {
case IonTypes.BOOL:
assert.equal(p.booleanValue(), test.expected);
break;
default:
assert.throws(() => p.booleanValue());
}
switch (testSet.type) {
case IonTypes.INT:
assert.equal(p.numberValue(), JSBI.toNumber(test.expected));
break;
case IonTypes.FLOAT:
isNaN(test.expected) ? assert.isNaN(p.numberValue())
: assert.equal(p.numberValue(), test.expected);
break;
default:
assert.throws(() => p.numberValue());
}
switch (testSet.type) {
case IonTypes.INT:
assert.deepEqual(p.bigIntValue(), test.expected);
break;
default:
assert.throws(() => p.bigIntValue());
}
switch (testSet.type) {
case IonTypes.CLOB:
assert.throws(() => p.get_value_as_string(testSet.T_id));
assert.deepEqual(p.get_value_as_uint8array(testSet.T_id), test.expected);
break;
default:
assert.equal(p.get_value_as_string(testSet.T_id),
test.expectedStr ? test.expectedStr : test.ion);
assert.throws(() => p.get_value_as_uint8array(testSet.T_id));
}
}
assert.equal(p.next(), -1 /* EOF */);
});
});
});
});
it('Reads list', () => {
let p = new ParserTextRaw(new StringSpan('[1, a, []]'));
assert.equal(p.next(), 18); // list
assert.equal(p.next(), 3); // int
assert.equal(p.next(), 9); // symbol
assert.equal(p.next(), 18); // list
assert.equal(p.next(), -1); // EOF
});
it('Reads sexp', () => {
let p = new ParserTextRaw(new StringSpan('(1 a {})'));
assert.equal(p.next(), 17); // sexp
assert.equal(p.next(), 3); // int
assert.equal(p.next(), 9); // symbol
assert.equal(p.next(), 19); // struct
assert.equal(p.next(), -1); // EOF
});
it('Reads struct', () => {
let p = new ParserTextRaw(new StringSpan('{a: 1, b: a, c: {d: true}}'));
assert.isNull(p.fieldNameType());
assert.equal(p.next(), 19); // list
assert.isNull(p.fieldNameType());
assert.equal(p.next(), 3); // int
assert.equal(p.fieldName(), 'a');
assert.equal(p.fieldNameType(), 9);
assert.equal(p.next(), 9); // symbol
assert.equal(p.fieldName(), 'b');
assert.equal(p.fieldNameType(), 9);
assert.equal(p.next(), 19); // struct
assert.equal(p.fieldName(), 'c');
assert.equal(p.fieldNameType(), 9);
assert.equal(p.next(), 2); // bool
assert.equal(p.fieldName(), 'd');
assert.equal(p.fieldNameType(), 9);
p.clearFieldName();
assert.isNull(p.fieldName());
assert.isNull(p.fieldNameType());
assert.equal(p.next(), -1); // EOF
assert.isNull(p.fieldNameType());
});
it('Reads annotations', () => {
let p = new ParserTextRaw(new StringSpan('z::[1, y::2, x::{a: w::3, b: v::(s::t::u::4)}, r::5]'));
p.next(); assert.deepEqual(p.annotations(), [new SymbolToken('z')]);
p.next(); assert.deepEqual(p.annotations(), []);
p.next(); assert.deepEqual(p.annotations(), [new SymbolToken('y')]);
p.next(); assert.deepEqual(p.annotations(), [new SymbolToken('x')]);
p.next(); assert.deepEqual(p.annotations(), [new SymbolToken('w')]);
p.next(); assert.deepEqual(p.annotations(), [new SymbolToken('v')]);
p.next(); assert.deepEqual(p.annotations(), [new SymbolToken('s'),
new SymbolToken('t'),
new SymbolToken('u')]);
assert.equal(p.next(), -1); // "EOF" (end of nested sexp)
assert.deepEqual(p.annotations(), []);
assert.equal(p.next(), -1); // "EOF" (end of nested struct)
assert.deepEqual(p.annotations(), []);
p.next(); assert.deepEqual(p.annotations(), [new SymbolToken('r')]);
assert.equal(p.next(), -1); // "EOF" (end of list)
assert.deepEqual(p.annotations(), []);
})
}); | the_stack |
import 'jest-extended';
import {
times, pDelay, DataEntity, Omit, TSError, debugLogger
} from '@terascope/utils';
import { Translator } from 'xlucene-translator';
import {
SimpleRecord, SimpleRecordInput, dataType, schema
} from './helpers/simple-index';
import { makeClient, cleanupIndexStore } from './helpers/elasticsearch';
import { TEST_INDEX_PREFIX } from './helpers/config';
import { IndexStore, IndexConfig } from '../src';
describe('IndexStore', () => {
const client = makeClient();
const logger = debugLogger('index-store-spec');
describe('when constructed with nothing', () => {
it('should throw an error', () => {
expect(() => {
new IndexStore(undefined as any, undefined as any);
}).toThrowWithMessage(TSError, 'IndexStore requires elasticsearch client');
});
});
describe('when constructed without a config', () => {
it('should throw an error', () => {
expect(() => {
new IndexStore(client as any, undefined as any);
}).toThrowError();
});
});
const index = `${TEST_INDEX_PREFIX}store-v1-s1`;
const config: IndexConfig<SimpleRecord> = {
name: `${TEST_INDEX_PREFIX}store`,
data_type: dataType,
index_schema: {
version: 1,
strict: true,
},
version: 1,
index_settings: {
'index.number_of_shards': 1,
'index.number_of_replicas': 0,
},
logger,
bulk_max_size: 50,
bulk_max_wait: 300,
id_field: 'test_id',
ingest_time_field: '_created',
event_time_field: '_updated',
};
describe('when constructed without a data schema', () => {
const _client = makeClient();
const indexStore = new IndexStore<SimpleRecord>(_client, config);
beforeAll(async () => {
await cleanupIndexStore(indexStore);
await indexStore.initialize();
});
afterAll(async () => {
await cleanupIndexStore(indexStore);
await indexStore.flush(true).catch((err) => {
// this should probably throw
// but it is not a deal breaker
console.error(err);
});
// it should be able to call shutdown twice
await indexStore.shutdown();
await indexStore.shutdown();
});
it('should create the versioned index', async () => {
const exists = await _client.indices.exists({ index });
expect(exists).toBeTrue();
});
describe('when dealing with a record', () => {
const record: SimpleRecordInput = {
test_id: 'hello-1234',
test_keyword: 'hello',
test_object: {
example: 'some-object',
},
test_number: 1234,
test_boolean: false,
_created: new Date().toISOString(),
_updated: new Date().toISOString(),
};
beforeAll(() => indexStore.createById(record.test_id, record));
it('should not be able to create a record again', async () => {
expect.hasAssertions();
try {
await indexStore.createById(record.test_id, record);
} catch (err) {
expect(err).toBeInstanceOf(TSError);
expect(err.message).toInclude('Document Already Exists');
expect(err.statusCode).toEqual(409);
}
});
it('should be able to index the same record', () => indexStore.indexById(record.test_id, record));
it('should be able to index the record without an id', async () => {
const lonelyRecord: SimpleRecordInput = {
test_id: 'lonely-1234',
test_keyword: 'other',
test_object: {},
test_number: 1234,
test_boolean: false,
};
await indexStore.index(lonelyRecord);
const count = await indexStore.count(`test_id: ${lonelyRecord.test_id}`);
expect(count).toBe(1);
});
it('should be able to index a different record with id', async () => {
const otherRecord: SimpleRecordInput = {
test_id: 'other-1234',
test_keyword: 'other',
test_object: {},
test_number: 1234,
test_boolean: false,
};
await indexStore.indexById(otherRecord.test_id, otherRecord);
const count = await indexStore.count(`test_id: ${otherRecord.test_id}`);
expect(count).toBe(1);
});
it('can use count with variables', async () => {
const testRecord: SimpleRecordInput = {
test_id: 'hello',
test_keyword: 'world',
test_object: {},
test_number: 5678,
test_boolean: true,
};
const variables = {
id: 'hello'
};
await indexStore.indexById(testRecord.test_id, testRecord);
const count = await indexStore.count('test_id: $id', { variables });
expect(count).toBe(1);
});
it('can use countBy with variables', async () => {
const testRecord: SimpleRecordInput = {
test_id: 'goodbye',
test_keyword: 'jimmy',
test_object: {},
test_number: 1111,
test_boolean: false,
};
const variables = {
id: 'goodbye'
};
await indexStore.indexById(testRecord.test_id, testRecord);
const count = await indexStore.countBy({ test_id: '$id' }, 'OR', { variables });
expect(count).toBe(1);
});
it('can use search with variables', async () => {
const testRecord: SimpleRecordInput = {
test_id: 'iamtest',
test_keyword: 'aloha',
test_object: {},
test_number: 111111111,
test_boolean: true,
};
const variables = {
word: 'aloha'
};
await indexStore.indexById(testRecord.test_id, testRecord);
const { results } = await indexStore.search('test_keyword:$word', { variables });
expect(results).toEqual([testRecord]);
});
it('can use findBy with variables', async () => {
const testRecord: SimpleRecordInput = {
test_id: 'iamfindby',
test_keyword: 'iamfindby',
test_object: {},
test_number: 1,
test_boolean: false,
};
const variables = {
word: 'iamfindby'
};
await indexStore.indexById(testRecord.test_id, testRecord);
const results = await indexStore.findBy({ test_keyword: '$word' }, 'OR', { variables });
expect(results).toEqual(testRecord);
});
it('should be able to get the count', () => expect(indexStore.count(`test_id: ${record.test_id}`)).resolves.toBe(1));
it('should get zero when the using the wrong id', () => expect(indexStore.count('test_id: wrong-id')).resolves.toBe(0));
it('should be able to update the record', async () => {
await indexStore.update(
record.test_id,
{
doc: {
test_number: 4231,
},
},
);
const updated = await indexStore.get(record.test_id);
expect(updated).toHaveProperty('test_number', 4231);
await indexStore.update(record.test_id, { doc: record });
});
it('should throw when updating a record that does not exist', async () => {
expect.hasAssertions();
try {
await indexStore.update(
'wrong-id',
{
doc: {
test_number: 1,
},
},
);
} catch (err) {
expect(err).toBeInstanceOf(TSError);
expect(err.message).toInclude('Not Found');
expect(err.statusCode).toEqual(404);
}
});
it('should be able to get the record by id', async () => {
const r: DataEntity<SimpleRecord> = (await indexStore.get(record.test_id)) as any;
expect(DataEntity.isDataEntity(r)).toBeTrue();
expect(r).toEqual(record);
const metadata = r.getMetadata();
expect(metadata).toMatchObject({
_index: index,
_key: record.test_id,
_type: indexStore.esVersion >= 7 ? '_doc' : indexStore.config.name,
});
expect(metadata._processTime).toBeNumber();
const ingestTime = record._created ? new Date(record._created).getTime() : null;
expect(metadata).toHaveProperty('_ingestTime', ingestTime);
const eventTime = record._updated ? new Date(record._updated).getTime() : null;
expect(metadata).toHaveProperty('_eventTime', eventTime);
});
it('should throw when getting a record that does not exist', async () => {
expect.hasAssertions();
try {
await indexStore.get('wrong-id');
} catch (err) {
expect(err).toBeInstanceOf(TSError);
expect(err.message).toInclude('Not Found');
expect(err.statusCode).toEqual(404);
}
});
it('should be able to remove the record', async () => {
await indexStore.deleteById(record.test_id);
});
it('should throw when trying to remove a record that does not exist', async () => {
expect.hasAssertions();
try {
await indexStore.deleteById('wrong-id');
} catch (err) {
expect(err).toBeInstanceOf(TSError);
expect(err.message).toInclude('Not Found');
expect(err.statusCode).toEqual(404);
}
});
});
describe('when dealing with multiple a records', () => {
const keyword = 'example-record';
const records: SimpleRecordInput[] = [
{
test_id: 'example-1',
test_keyword: keyword,
test_object: {
example: 'obj',
},
test_number: 5555,
test_boolean: true,
_created: new Date().toISOString(),
_updated: new Date().toISOString(),
},
{
test_id: 'example-2',
test_keyword: keyword,
test_object: {
example: 'obj',
},
test_number: 3333,
test_boolean: true,
_created: new Date().toISOString(),
_updated: new Date().toISOString(),
},
{
test_id: 'example-3',
test_keyword: keyword,
test_object: {
example: 'obj',
},
test_number: 999,
test_boolean: true,
_created: new Date().toISOString(),
_updated: new Date().toISOString(),
},
];
beforeAll(async () => {
await Promise.all(
records.map((record) => indexStore.createById(record.test_id, record, {
refresh: false,
}))
);
await indexStore.refresh();
});
it('should be able to mget all of the records', async () => {
const docs = records.map((r) => ({
_id: r.test_id,
}));
const result = await indexStore.mget({ docs });
expect(DataEntity.isDataEntityArray(result)).toBeTrue();
expect(result).toEqual(records);
});
it('should be able to search the records', async () => {
const {
results,
} = await indexStore.search(`test_keyword: ${keyword}`, {
sort: 'test_id',
});
expect(DataEntity.isDataEntityArray(results)).toBeTrue();
expect(results).toEqual(records);
});
it('should be able to search the records and get the total', async () => {
const {
results
} = await indexStore.search(`test_keyword: ${keyword}`, {
sort: 'test_id',
});
expect(results).toEqual(records);
});
});
describe('when bulk sending records', () => {
const keyword = 'bulk-record';
const records: SimpleRecordInput[] = times(100, (n) => ({
test_id: `bulk-${n + 1}`,
test_keyword: keyword,
test_object: { example: 'bulk', },
test_number: (n + 10) * 2,
test_boolean: n % 2 === 0,
_updated: new Date().toISOString(),
}));
beforeAll(async () => {
let useIndex = false;
for (const record of records) {
if (useIndex) {
await indexStore.bulk('index', record, record.test_id);
} else {
await indexStore.bulk('create', record, record.test_id);
}
useIndex = !useIndex;
}
await pDelay(500);
await indexStore.refresh();
});
afterAll(async () => {
for (const record of records.slice(0, 10)) {
await indexStore.bulk(
'update',
{
test_object: {
example: 'updateAfterShutdown'
},
},
record.test_id
);
}
});
// eslint-disable-next-line
xit('compare xlucene query', async () => {
const q = '_exists_:test_number OR test_number:<0 OR test_number:100000 NOT test_keyword:other-keyword';
const realResult = await indexStore.searchRequest({
q,
_sourceInclude: ['test_id', 'test_boolean'],
sort: 'test_number:asc',
size: 200,
});
const {
results: xluceneResult
} = await indexStore.search(q, {
size: 200,
includes: ['test_id', 'test_boolean'],
sort: 'test_number:asc',
});
await indexStore.searchRequest({
body: {
query: {
constant_score: {
filter: {
bool: {
filter: [
{
exists: {
field: 'test_number',
},
},
],
must_not: [
{
term: {
test_keyword: 'other-keyword',
},
},
],
should: [
{
range: {
test_number: {
gte: 10,
},
},
},
{
term: {
test_boolean: false,
},
},
],
},
},
},
},
},
_sourceInclude: ['test_id', 'test_boolean'],
sort: 'test_number:asc',
size: 200,
});
const translated = new Translator(q, {
type_config: indexStore.xLuceneTypeConfig
}).toElasticsearchDSL();
// eslint-disable-next-line no-console
console.log(JSON.stringify({ q, translated }, null, 4));
// expect(realResult).toEqual(modifiedResult);
expect(xluceneResult).toEqual(realResult);
// eslint-disable-next-line no-console
console.dir(xluceneResult);
});
// eslint-disable-next-line
xit('test lucene query', async () => {
const result = await indexStore.searchRequest({
q: '*rec?rd',
size: 200,
_sourceInclude: ['test_id', 'test_number'],
sort: 'test_number:asc',
});
// expect(result).toBeArrayOfSize(0);
// eslint-disable-next-line no-console
console.dir(result);
});
it('should be able to search the records', async () => {
const {
results
} = await indexStore.search(`test_keyword: ${keyword}`, {
sort: 'test_number',
size: records.length + 1,
});
expect(results).toBeArrayOfSize(records.length);
expect(DataEntity.isDataEntityArray(results)).toBeTrue();
});
it('should be able use exists and range xlucene syntax', async () => {
const {
results
} = await indexStore.search('_exists_:test_number AND test_number: <100', {
sort: 'test_number',
size: 5,
});
expect(results).toBeArrayOfSize(5);
expect(DataEntity.isDataEntityArray(results)).toBeTrue();
});
it('should be able use multi-term xlucene syntax', async () => {
const query = 'test_id:/bulk-.*/ AND test_number:(20 OR 22 OR 26)';
const {
results
} = await indexStore.search(query, {
sort: 'test_number',
});
expect(results).toBeArrayOfSize(3);
expect(DataEntity.isDataEntityArray(results)).toBeTrue();
});
it('should be able to bulk update the records', async () => {
for (const record of records) {
await indexStore.bulk(
'index',
Object.assign(record, {
test_object: {
example: 'updated',
},
}),
record.test_id
);
}
await indexStore.flush(true);
await indexStore.refresh();
const {
results
} = await indexStore.search(`test_keyword: ${keyword}`, {
sort: 'test_id',
size: records.length + 1,
});
expect(results[0]).toHaveProperty('test_object', {
example: 'updated',
});
});
it('should be able to bulk delete the records', async () => {
try {
for (const record of records) {
await indexStore.bulk('delete', record.test_id);
}
await indexStore.flush(true);
await indexStore.refresh();
const {
results
} = await indexStore.search(`test_keyword: ${keyword}`, {
sort: 'test_id',
size: records.length + 1,
});
expect(results).toBeArrayOfSize(0);
} finally {
// make sure always flush to avoid breaking afterAll
await indexStore.flush(true);
}
});
});
});
describe('when constructed with data schema', () => {
const _client = makeClient();
const configWithDataSchema = Object.assign(config, {
data_schema: {
schema,
all_formatters: true,
strict: true,
},
});
const indexStore = new IndexStore<SimpleRecord>(
_client,
configWithDataSchema
);
beforeAll(async () => {
await cleanupIndexStore(indexStore);
await indexStore.initialize();
});
afterAll(async () => {
await cleanupIndexStore(indexStore);
await indexStore.shutdown();
});
it('should fail when given an invalid record', async () => {
expect.hasAssertions();
const record: Partial<SimpleRecord> = {
test_id: 'invalid-record-id',
test_boolean: Buffer.from('wrong') as any,
test_number: '123' as any,
_created: 'wrong-date',
};
try {
await indexStore.indexById(record.test_id!, record);
} catch (err) {
expect(err).toBeInstanceOf(TSError);
expect(err.message).toMatch(/(test_keyword|_created)/);
expect(err.statusCode).toEqual(400);
}
});
type InputType = 'input' | 'output';
const cases: [InputType][] = [['input'], ['output']];
describe.each(cases)('when relying on data schema to transform the %s', (inputType) => {
const keyword = `data-schema-${inputType}-record`;
const input: SimpleRecordInput[] = [
{
test_id: `data-schema-${inputType}-1`,
test_keyword: keyword,
test_object: {
example: 'obj',
},
_created: new Date().toISOString(),
},
{
test_id: `data-schema-${inputType}-2`,
test_keyword: keyword,
test_object: {},
test_number: 3333,
_updated: new Date().toISOString(),
},
{
test_id: `data-schema-${inputType}-3`,
test_keyword: keyword,
test_object: {
example: 'obj',
},
test_boolean: false,
_created: new Date().toISOString(),
_updated: new Date().toISOString(),
},
];
type ExpectedRecord = Omit<SimpleRecord, '_created' | '_updated'>;
const expected: ExpectedRecord[] = input.map((record) => Object.assign(
{
test_boolean: true,
test_number: 676767,
},
record
));
beforeAll(async () => {
await Promise.all(
input.map((record, i) => {
if (inputType === 'input') {
if (i === 0) {
return indexStore.createById(record.test_id, record);
}
return indexStore.indexById(record.test_id, record, {
refresh: false,
});
}
if (inputType === 'output') {
const indexParams = {
index,
type: indexStore.config.name,
id: record.test_id,
body: record,
refresh: false,
};
if (indexStore.esVersion >= 7) {
delete (indexParams as any).type;
}
return _client.index(indexParams);
}
throw new Error('Invalid Input Type');
})
);
await indexStore.refresh();
});
it('should have created all of the records', async () => {
const {
results,
} = await indexStore.search(`test_keyword: ${keyword}`, {
sort: 'test_id',
});
expect(DataEntity.isDataEntityArray(results)).toBeTrue();
expect(results).toEqual(expected);
const record = await indexStore.get(expected[0].test_id);
expect(DataEntity.isDataEntity(record)).toBeTrue();
expect(record).toEqual(expected[0]);
const records = await indexStore.mget({
docs: expected.map((r) => ({
_id: r.test_id,
})),
});
expect(DataEntity.isDataEntityArray(records)).toBeTrue();
expect(records).toEqual(expected);
});
it('should be able to update a record with a proper field', async () => {
const result = await indexStore.update(
expected[2].test_id,
{
doc: {
test_number: 77777,
},
}
);
expect(result).toBeNil();
const record = await indexStore.get(expected[2].test_id);
expect(record).toMatchObject({
test_number: 77777,
});
});
});
});
}); | the_stack |
import { assertEquals, base64, date } from "./test_deps.ts";
import { getMainConfiguration } from "./config.ts";
import { generateSimpleClientTest } from "./helpers.ts";
import {
Box,
Circle,
Float4,
Float8,
Line,
LineSegment,
Path,
Point,
Polygon,
TID,
Timestamp,
} from "../query/types.ts";
// TODO
// Find out how to test char types
/**
* This will generate a random number with a precision of 2
*/
function generateRandomNumber(max_value: number) {
return Math.round((Math.random() * max_value + Number.EPSILON) * 100) / 100;
}
function generateRandomPoint(max_value = 100): Point {
return {
x: String(generateRandomNumber(max_value)) as Float8,
y: String(generateRandomNumber(max_value)) as Float8,
};
}
const CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function randomBase64(): string {
return base64.encode(
Array.from(
{ length: Math.ceil(Math.random() * 256) },
() => CHARS[Math.floor(Math.random() * CHARS.length)],
).join(""),
);
}
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const timezone_utc = new Date().toTimeString().slice(12, 17);
const testClient = generateSimpleClientTest(getMainConfiguration());
Deno.test(
"inet",
testClient(async (client) => {
const url = "127.0.0.1";
const selectRes = await client.queryArray(
"SELECT $1::INET",
url,
);
assertEquals(selectRes.rows[0], [url]);
}),
);
Deno.test(
"inet array",
testClient(async (client) => {
const { rows: result_1 } = await client.queryArray(
"SELECT '{ 127.0.0.1, 192.168.178.0/24 }'::inet[]",
);
assertEquals(result_1[0], [["127.0.0.1", "192.168.178.0/24"]]);
const { rows: result_2 } = await client.queryArray(
"SELECT '{{127.0.0.1},{192.168.178.0/24}}'::inet[]",
);
assertEquals(result_2[0], [[["127.0.0.1"], ["192.168.178.0/24"]]]);
}),
);
Deno.test(
"macaddr",
testClient(async (client) => {
const address = "08:00:2b:01:02:03";
const { rows } = await client.queryArray(
"SELECT $1::MACADDR",
address,
);
assertEquals(rows[0], [address]);
}),
);
Deno.test(
"macaddr array",
testClient(async (client) => {
const { rows: result_1 } = await client.queryArray(
"SELECT '{ 08:00:2b:01:02:03, 09:00:2b:01:02:04 }'::macaddr[]",
);
assertEquals(result_1[0], [[
"08:00:2b:01:02:03",
"09:00:2b:01:02:04",
]]);
const { rows: result_2 } = await client.queryArray(
"SELECT '{{08:00:2b:01:02:03},{09:00:2b:01:02:04}}'::macaddr[]",
);
assertEquals(
result_2[0],
[[["08:00:2b:01:02:03"], ["09:00:2b:01:02:04"]]],
);
}),
);
Deno.test(
"cidr",
testClient(async (client) => {
const host = "192.168.100.128/25";
const { rows } = await client.queryArray(
"SELECT $1::CIDR",
host,
);
assertEquals(rows[0], [host]);
}),
);
Deno.test(
"cidr array",
testClient(async (client) => {
const { rows: result_1 } = await client.queryArray(
"SELECT '{ 10.1.0.0/16, 11.11.11.0/24 }'::cidr[]",
);
assertEquals(result_1[0], [["10.1.0.0/16", "11.11.11.0/24"]]);
const { rows: result_2 } = await client.queryArray(
"SELECT '{{10.1.0.0/16},{11.11.11.0/24}}'::cidr[]",
);
assertEquals(result_2[0], [[["10.1.0.0/16"], ["11.11.11.0/24"]]]);
}),
);
Deno.test(
"name",
testClient(async (client) => {
const name = "some";
const result = await client.queryArray(`SELECT $1::name`, name);
assertEquals(result.rows[0], [name]);
}),
);
Deno.test(
"name array",
testClient(async (client) => {
const result = await client.queryArray(
`SELECT ARRAY['some'::name, 'none']`,
);
assertEquals(result.rows[0], [["some", "none"]]);
}),
);
Deno.test(
"oid",
testClient(async (client) => {
const result = await client.queryArray(`SELECT 1::oid`);
assertEquals(result.rows[0][0], "1");
}),
);
Deno.test(
"oid array",
testClient(async (client) => {
const result = await client.queryArray(`SELECT ARRAY[1::oid, 452, 1023]`);
assertEquals(result.rows[0][0], ["1", "452", "1023"]);
}),
);
Deno.test(
"regproc",
testClient(async (client) => {
const result = await client.queryArray(`SELECT 'now'::regproc`);
assertEquals(result.rows[0][0], "now");
}),
);
Deno.test(
"regproc array",
testClient(async (client) => {
const result = await client.queryArray(
`SELECT ARRAY['now'::regproc, 'timeofday']`,
);
assertEquals(result.rows[0][0], ["now", "timeofday"]);
}),
);
Deno.test(
"regprocedure",
testClient(async (client) => {
const result = await client.queryArray(
`SELECT 'sum(integer)'::regprocedure`,
);
assertEquals(result.rows[0][0], "sum(integer)");
}),
);
Deno.test(
"regprocedure array",
testClient(async (client) => {
const result = await client.queryArray(
`SELECT ARRAY['sum(integer)'::regprocedure, 'max(integer)']`,
);
assertEquals(result.rows[0][0], ["sum(integer)", "max(integer)"]);
}),
);
Deno.test(
"regoper",
testClient(async (client) => {
const operator = "!!";
const { rows } = await client.queryObject({
args: [operator],
fields: ["result"],
text: "SELECT $1::regoper",
});
assertEquals(rows[0], { result: operator });
}),
);
Deno.test(
"regoper array",
testClient(async (client) => {
const operator_1 = "!!";
const operator_2 = "|/";
const { rows } = await client.queryObject({
args: [operator_1, operator_2],
fields: ["result"],
text: "SELECT ARRAY[$1::regoper, $2]",
});
assertEquals(rows[0], { result: [operator_1, operator_2] });
}),
);
Deno.test(
"regoperator",
testClient(async (client) => {
const regoperator = "-(NONE,integer)";
const { rows } = await client.queryObject({
args: [regoperator],
fields: ["result"],
text: "SELECT $1::regoperator",
});
assertEquals(rows[0], { result: regoperator });
}),
);
Deno.test(
"regoperator array",
testClient(async (client) => {
const regoperator_1 = "-(NONE,integer)";
const regoperator_2 = "*(integer,integer)";
const { rows } = await client.queryObject({
args: [regoperator_1, regoperator_2],
fields: ["result"],
text: "SELECT ARRAY[$1::regoperator, $2]",
});
assertEquals(rows[0], { result: [regoperator_1, regoperator_2] });
}),
);
Deno.test(
"regclass",
testClient(async (client) => {
const object_name = "TEST_REGCLASS";
await client.queryArray(`CREATE TEMP TABLE ${object_name} (X INT)`);
const result = await client.queryObject<{ table_name: string }>({
args: [object_name],
fields: ["table_name"],
text: "SELECT $1::REGCLASS",
});
assertEquals(result.rows.length, 1);
// Objects in postgres are case insensitive unless indicated otherwise
assertEquals(
result.rows[0].table_name.toLowerCase(),
object_name.toLowerCase(),
);
}),
);
Deno.test(
"regclass array",
testClient(async (client) => {
const object_1 = "TEST_REGCLASS_1";
const object_2 = "TEST_REGCLASS_2";
await client.queryArray(`CREATE TEMP TABLE ${object_1} (X INT)`);
await client.queryArray(`CREATE TEMP TABLE ${object_2} (X INT)`);
const { rows: result } = await client.queryObject<
{ tables: [string, string] }
>({
args: [object_1, object_2],
fields: ["tables"],
text: "SELECT ARRAY[$1::REGCLASS, $2]",
});
assertEquals(result.length, 1);
assertEquals(result[0].tables.length, 2);
// Objects in postgres are case insensitive unless indicated otherwise
assertEquals(
result[0].tables.map((x) => x.toLowerCase()),
[object_1, object_2].map((x) => x.toLowerCase()),
);
}),
);
Deno.test(
"regtype",
testClient(async (client) => {
const result = await client.queryArray(`SELECT 'integer'::regtype`);
assertEquals(result.rows[0][0], "integer");
}),
);
Deno.test(
"regtype array",
testClient(async (client) => {
const result = await client.queryArray(
`SELECT ARRAY['integer'::regtype, 'bigint']`,
);
assertEquals(result.rows[0][0], ["integer", "bigint"]);
}),
);
// TODO
// Refactor test to look for users directly in the database instead
// of relying on config
Deno.test(
"regrole",
testClient(async (client) => {
const user = getMainConfiguration().user;
const result = await client.queryArray(
`SELECT ($1)::regrole`,
user,
);
assertEquals(result.rows[0][0], user);
}),
);
Deno.test(
"regrole array",
testClient(async (client) => {
const user = getMainConfiguration().user;
const result = await client.queryArray(
`SELECT ARRAY[($1)::regrole]`,
user,
);
assertEquals(result.rows[0][0], [user]);
}),
);
Deno.test(
"regnamespace",
testClient(async (client) => {
const result = await client.queryArray(`SELECT 'public'::regnamespace;`);
assertEquals(result.rows[0][0], "public");
}),
);
Deno.test(
"regnamespace array",
testClient(async (client) => {
const result = await client.queryArray(
`SELECT ARRAY['public'::regnamespace, 'pg_catalog'];`,
);
assertEquals(result.rows[0][0], ["public", "pg_catalog"]);
}),
);
Deno.test(
"regconfig",
testClient(async (client) => {
const result = await client.queryArray(`SElECT 'english'::regconfig`);
assertEquals(result.rows, [["english"]]);
}),
);
Deno.test(
"regconfig array",
testClient(async (client) => {
const result = await client.queryArray(
`SElECT ARRAY['english'::regconfig, 'spanish']`,
);
assertEquals(result.rows[0][0], ["english", "spanish"]);
}),
);
Deno.test(
"regdictionary",
testClient(async (client) => {
const result = await client.queryArray("SELECT 'simple'::regdictionary");
assertEquals(result.rows[0][0], "simple");
}),
);
Deno.test(
"regdictionary array",
testClient(async (client) => {
const result = await client.queryArray(
"SELECT ARRAY['simple'::regdictionary]",
);
assertEquals(result.rows[0][0], ["simple"]);
}),
);
Deno.test(
"bigint",
testClient(async (client) => {
const result = await client.queryArray("SELECT 9223372036854775807");
assertEquals(result.rows[0][0], 9223372036854775807n);
}),
);
Deno.test(
"bigint array",
testClient(async (client) => {
const result = await client.queryArray(
"SELECT ARRAY[9223372036854775807, 789141]",
);
assertEquals(result.rows[0][0], [9223372036854775807n, 789141n]);
}),
);
Deno.test(
"numeric",
testClient(async (client) => {
const number = "1234567890.1234567890";
const result = await client.queryArray(`SELECT $1::numeric`, number);
assertEquals(result.rows[0][0], number);
}),
);
Deno.test(
"numeric array",
testClient(async (client) => {
const numeric = ["1234567890.1234567890", "6107693.123123124"];
const result = await client.queryArray(
`SELECT ARRAY[$1::numeric, $2]`,
numeric[0],
numeric[1],
);
assertEquals(result.rows[0][0], numeric);
}),
);
Deno.test(
"integer",
testClient(async (client) => {
const int = 17;
const { rows: result } = await client.queryObject({
args: [int],
fields: ["result"],
text: "SELECT $1::INTEGER",
});
assertEquals(result[0], { result: int });
}),
);
Deno.test(
"integer array",
testClient(async (client) => {
const { rows: result_1 } = await client.queryArray(
"SELECT '{1,100}'::int[]",
);
assertEquals(result_1[0], [[1, 100]]);
const { rows: result_2 } = await client.queryArray(
"SELECT '{{1},{100}}'::int[]",
);
assertEquals(result_2[0], [[[1], [100]]]);
}),
);
Deno.test(
"char",
testClient(async (client) => {
await client.queryArray(
`CREATE TEMP TABLE CHAR_TEST (X CHARACTER(2));`,
);
await client.queryArray(
`INSERT INTO CHAR_TEST (X) VALUES ('A');`,
);
const result = await client.queryArray(
`SELECT X FROM CHAR_TEST`,
);
assertEquals(result.rows[0][0], "A ");
}),
);
Deno.test(
"char array",
testClient(async (client) => {
const result = await client.queryArray(
`SELECT '{"x","Y"}'::char[]`,
);
assertEquals(result.rows[0][0], ["x", "Y"]);
}),
);
Deno.test(
"text",
testClient(async (client) => {
const result = await client.queryArray(
`SELECT 'ABCD'::text`,
);
assertEquals(result.rows[0], ["ABCD"]);
}),
);
Deno.test(
"text array",
testClient(async (client) => {
const { rows: result_1 } = await client.queryArray(
`SELECT '{"(ZYX)-123-456","(ABC)-987-654"}'::text[]`,
);
assertEquals(result_1[0], [["(ZYX)-123-456", "(ABC)-987-654"]]);
const { rows: result_2 } = await client.queryArray(
`SELECT '{{"(ZYX)-123-456"},{"(ABC)-987-654"}}'::text[]`,
);
assertEquals(result_2[0], [[["(ZYX)-123-456"], ["(ABC)-987-654"]]]);
}),
);
Deno.test(
"varchar",
testClient(async (client) => {
const result = await client.queryArray(
`SELECT 'ABC'::varchar`,
);
assertEquals(result.rows[0][0], "ABC");
}),
);
Deno.test(
"varchar array",
testClient(async (client) => {
const { rows: result_1 } = await client.queryArray(
`SELECT '{"(ZYX)-(PQR)-456","(ABC)-987-(?=+)"}'::varchar[]`,
);
assertEquals(result_1[0], [["(ZYX)-(PQR)-456", "(ABC)-987-(?=+)"]]);
const { rows: result_2 } = await client.queryArray(
`SELECT '{{"(ZYX)-(PQR)-456"},{"(ABC)-987-(?=+)"}}'::varchar[]`,
);
assertEquals(result_2[0], [[["(ZYX)-(PQR)-456"], ["(ABC)-987-(?=+)"]]]);
}),
);
Deno.test(
"uuid",
testClient(async (client) => {
const uuid_text = "c4792ecb-c00a-43a2-bd74-5b0ed551c599";
const result = await client.queryArray(`SELECT $1::uuid`, uuid_text);
assertEquals(result.rows[0][0], uuid_text);
}),
);
Deno.test(
"uuid array",
testClient(async (client) => {
const { rows: result_1 } = await client.queryArray(
`SELECT '{"c4792ecb-c00a-43a2-bd74-5b0ed551c599",
"c9dd159e-d3d7-4bdf-b0ea-e51831c28e9b"}'::uuid[]`,
);
assertEquals(
result_1[0],
[[
"c4792ecb-c00a-43a2-bd74-5b0ed551c599",
"c9dd159e-d3d7-4bdf-b0ea-e51831c28e9b",
]],
);
const { rows: result_2 } = await client.queryArray(
`SELECT '{{"c4792ecb-c00a-43a2-bd74-5b0ed551c599"},
{"c9dd159e-d3d7-4bdf-b0ea-e51831c28e9b"}}'::uuid[]`,
);
assertEquals(
result_2[0],
[[
["c4792ecb-c00a-43a2-bd74-5b0ed551c599"],
["c9dd159e-d3d7-4bdf-b0ea-e51831c28e9b"],
]],
);
}),
);
Deno.test(
"void",
testClient(async (client) => {
const result = await client.queryArray`SELECT PG_SLEEP(0.01)`; // `pg_sleep()` returns void.
assertEquals(result.rows, [[""]]);
}),
);
Deno.test(
"bpchar",
testClient(async (client) => {
const result = await client.queryArray(
"SELECT cast('U7DV6WQ26D7X2IILX5L4LTYMZUKJ5F3CEDDQV3ZSLQVYNRPX2WUA' as char(52));",
);
assertEquals(
result.rows,
[["U7DV6WQ26D7X2IILX5L4LTYMZUKJ5F3CEDDQV3ZSLQVYNRPX2WUA"]],
);
}),
);
Deno.test(
"bpchar array",
testClient(async (client) => {
const { rows: result_1 } = await client.queryArray(
`SELECT '{"AB1234","4321BA"}'::bpchar[]`,
);
assertEquals(result_1[0], [["AB1234", "4321BA"]]);
const { rows: result_2 } = await client.queryArray(
`SELECT '{{"AB1234"},{"4321BA"}}'::bpchar[]`,
);
assertEquals(result_2[0], [[["AB1234"], ["4321BA"]]]);
}),
);
Deno.test(
"bool",
testClient(async (client) => {
const result = await client.queryArray(
`SELECT bool('y')`,
);
assertEquals(result.rows[0][0], true);
}),
);
Deno.test(
"bool array",
testClient(async (client) => {
const result = await client.queryArray(
`SELECT array[bool('y'), bool('n'), bool('1'), bool('0')]`,
);
assertEquals(result.rows[0][0], [true, false, true, false]);
}),
);
Deno.test(
"bytea",
testClient(async (client) => {
const base64_string = randomBase64();
const result = await client.queryArray(
`SELECT decode('${base64_string}','base64')`,
);
assertEquals(result.rows[0][0], base64.decode(base64_string));
}),
);
Deno.test(
"bytea array",
testClient(async (client) => {
const strings = Array.from(
{ length: Math.ceil(Math.random() * 10) },
randomBase64,
);
const result = await client.queryArray(
`SELECT array[ ${
strings.map((x) => `decode('${x}', 'base64')`).join(", ")
} ]`,
);
assertEquals(
result.rows[0][0],
strings.map(base64.decode),
);
}),
);
Deno.test(
"point",
testClient(async (client) => {
const selectRes = await client.queryArray<[Point]>(
"SELECT point(1, 2.5)",
);
assertEquals(selectRes.rows, [[{ x: "1", y: "2.5" }]]);
}),
);
Deno.test(
"point array",
testClient(async (client) => {
const result1 = await client.queryArray(
`SELECT '{"(1, 2)","(3.5, 4.1)"}'::point[]`,
);
assertEquals(result1.rows, [
[[{ x: "1", y: "2" }, { x: "3.5", y: "4.1" }]],
]);
const result2 = await client.queryArray(
`SELECT array[ array[ point(1,2), point(3.5, 4.1) ], array[ point(25, 50), point(-10, -17.5) ] ]`,
);
assertEquals(result2.rows[0], [
[
[{ x: "1", y: "2" }, { x: "3.5", y: "4.1" }],
[{ x: "25", y: "50" }, { x: "-10", y: "-17.5" }],
],
]);
}),
);
Deno.test(
"time",
testClient(async (client) => {
const result = await client.queryArray("SELECT '01:01:01'::TIME");
assertEquals(result.rows[0][0], "01:01:01");
}),
);
Deno.test(
"time array",
testClient(async (client) => {
const result = await client.queryArray("SELECT ARRAY['01:01:01'::TIME]");
assertEquals(result.rows[0][0], ["01:01:01"]);
}),
);
Deno.test(
"timestamp",
testClient(async (client) => {
const date = "1999-01-08 04:05:06";
const result = await client.queryArray<[Timestamp]>(
`SELECT $1::TIMESTAMP, 'INFINITY'::TIMESTAMP`,
date,
);
assertEquals(result.rows[0], [new Date(date), Infinity]);
}),
);
Deno.test(
"timestamp array",
testClient(async (client) => {
const timestamps = [
"2011-10-05T14:48:00.00",
new Date().toISOString().slice(0, -1),
];
const result = await client.queryArray<[[Timestamp, Timestamp]]>(
`SELECT ARRAY[$1::TIMESTAMP, $2]`,
...timestamps,
);
assertEquals(result.rows[0][0], timestamps.map((x) => new Date(x)));
}),
);
Deno.test(
"timestamptz",
testClient(async (client) => {
const timestamp = "1999-01-08 04:05:06+02";
const result = await client.queryArray<[Timestamp]>(
`SELECT $1::TIMESTAMPTZ, 'INFINITY'::TIMESTAMPTZ`,
timestamp,
);
assertEquals(result.rows[0], [new Date(timestamp), Infinity]);
}),
);
Deno.test(
"timestamptz array",
testClient(async (client) => {
const timestamps = [
"2012/04/10 10:10:30 +0000",
new Date().toISOString(),
];
const result = await client.queryArray<[[Timestamp, Timestamp]]>(
`SELECT ARRAY[$1::TIMESTAMPTZ, $2]`,
...timestamps,
);
assertEquals(result.rows[0][0], [
new Date(timestamps[0]),
new Date(timestamps[1]),
]);
}),
);
Deno.test(
"timetz",
testClient(async (client) => {
const result = await client.queryArray<[string]>(
`SELECT '01:01:01${timezone_utc}'::TIMETZ`,
);
assertEquals(result.rows[0][0].slice(0, 8), "01:01:01");
}),
);
Deno.test(
"timetz array",
testClient(async (client) => {
const result = await client.queryArray<[string]>(
`SELECT ARRAY['01:01:01${timezone_utc}'::TIMETZ]`,
);
assertEquals(typeof result.rows[0][0][0], "string");
assertEquals(result.rows[0][0][0].slice(0, 8), "01:01:01");
}),
);
Deno.test(
"xid",
testClient(async (client) => {
const result = await client.queryArray("SELECT '1'::xid");
assertEquals(result.rows[0][0], 1);
}),
);
Deno.test(
"xid array",
testClient(async (client) => {
const result = await client.queryArray(
"SELECT ARRAY['12'::xid, '4789'::xid]",
);
assertEquals(result.rows[0][0], [12, 4789]);
}),
);
Deno.test(
"float4",
testClient(async (client) => {
const result = await client.queryArray<[Float4, Float4]>(
"SELECT '1'::FLOAT4, '17.89'::FLOAT4",
);
assertEquals(result.rows[0], ["1", "17.89"]);
}),
);
Deno.test(
"float4 array",
testClient(async (client) => {
const result = await client.queryArray<[[Float4, Float4]]>(
"SELECT ARRAY['12.25'::FLOAT4, '4789']",
);
assertEquals(result.rows[0][0], ["12.25", "4789"]);
}),
);
Deno.test(
"float8",
testClient(async (client) => {
const result = await client.queryArray<[Float8, Float8]>(
"SELECT '1'::FLOAT8, '17.89'::FLOAT8",
);
assertEquals(result.rows[0], ["1", "17.89"]);
}),
);
Deno.test(
"float8 array",
testClient(async (client) => {
const result = await client.queryArray<[[Float8, Float8]]>(
"SELECT ARRAY['12.25'::FLOAT8, '4789']",
);
assertEquals(result.rows[0][0], ["12.25", "4789"]);
}),
);
Deno.test(
"tid",
testClient(async (client) => {
const result = await client.queryArray<[TID, TID]>(
"SELECT '(1, 19)'::TID, '(23, 17)'::TID",
);
assertEquals(result.rows[0], [[1n, 19n], [23n, 17n]]);
}),
);
Deno.test(
"tid array",
testClient(async (client) => {
const result = await client.queryArray<[[TID, TID]]>(
"SELECT ARRAY['(4681, 1869)'::TID, '(0, 17476)']",
);
assertEquals(result.rows[0][0], [[4681n, 1869n], [0n, 17476n]]);
}),
);
Deno.test(
"date",
testClient(async (client) => {
await client.queryArray(`SET SESSION TIMEZONE TO '${timezone}'`);
const date_text = "2020-01-01";
const result = await client.queryArray<[Timestamp, Timestamp]>(
"SELECT $1::DATE, 'Infinity'::Date",
date_text,
);
assertEquals(result.rows[0], [
date.parse(date_text, "yyyy-MM-dd"),
Infinity,
]);
}),
);
Deno.test(
"date array",
testClient(async (client) => {
await client.queryArray(`SET SESSION TIMEZONE TO '${timezone}'`);
const dates = ["2020-01-01", date.format(new Date(), "yyyy-MM-dd")];
const result = await client.queryArray<[Timestamp, Timestamp]>(
"SELECT ARRAY[$1::DATE, $2]",
...dates,
);
assertEquals(
result.rows[0][0],
dates.map((d) => date.parse(d, "yyyy-MM-dd")),
);
}),
);
Deno.test(
"line",
testClient(async (client) => {
const result = await client.queryArray<[Line]>(
"SELECT '[(1, 2), (3, 4)]'::LINE",
);
assertEquals(result.rows[0][0], { a: "1", b: "-1", c: "1" });
}),
);
Deno.test(
"line array",
testClient(async (client) => {
const result = await client.queryArray<[[Line, Line]]>(
"SELECT ARRAY['[(1, 2), (3, 4)]'::LINE, '41, 1, -9, 25.5']",
);
assertEquals(result.rows[0][0], [
{ a: "1", b: "-1", c: "1" },
{
a: "-0.49",
b: "-1",
c: "21.09",
},
]);
}),
);
Deno.test(
"line segment",
testClient(async (client) => {
const result = await client.queryArray<[LineSegment]>(
"SELECT '[(1, 2), (3, 4)]'::LSEG",
);
assertEquals(result.rows[0][0], {
a: { x: "1", y: "2" },
b: { x: "3", y: "4" },
});
}),
);
Deno.test(
"line segment array",
testClient(async (client) => {
const result = await client.queryArray<[[LineSegment, LineSegment]]>(
"SELECT ARRAY['[(1, 2), (3, 4)]'::LSEG, '41, 1, -9, 25.5']",
);
assertEquals(result.rows[0][0], [
{
a: { x: "1", y: "2" },
b: { x: "3", y: "4" },
},
{
a: { x: "41", y: "1" },
b: { x: "-9", y: "25.5" },
},
]);
}),
);
Deno.test(
"box",
testClient(async (client) => {
const result = await client.queryArray<[Box]>(
"SELECT '((1, 2), (3, 4))'::BOX",
);
assertEquals(result.rows[0][0], {
a: { x: "3", y: "4" },
b: { x: "1", y: "2" },
});
}),
);
Deno.test(
"box array",
testClient(async (client) => {
const result = await client.queryArray<[[Box, Box]]>(
"SELECT ARRAY['(1, 2), (3, 4)'::BOX, '41, 1, -9, 25.5']",
);
assertEquals(result.rows[0][0], [
{
a: { x: "3", y: "4" },
b: { x: "1", y: "2" },
},
{
a: { x: "41", y: "25.5" },
b: { x: "-9", y: "1" },
},
]);
}),
);
Deno.test(
"path",
testClient(async (client) => {
const points = Array.from(
{ length: Math.floor((Math.random() + 1) * 10) },
generateRandomPoint,
);
const selectRes = await client.queryArray<[Path]>(
`SELECT '(${points.map(({ x, y }) => `(${x},${y})`).join(",")})'::PATH`,
);
assertEquals(selectRes.rows[0][0], points);
}),
);
Deno.test(
"path array",
testClient(async (client) => {
const points = Array.from(
{ length: Math.floor((Math.random() + 1) * 10) },
generateRandomPoint,
);
const selectRes = await client.queryArray<[[Path]]>(
`SELECT ARRAY['(${
points.map(({ x, y }) => `(${x},${y})`).join(",")
})'::PATH]`,
);
assertEquals(selectRes.rows[0][0][0], points);
}),
);
Deno.test(
"polygon",
testClient(async (client) => {
const points = Array.from(
{ length: Math.floor((Math.random() + 1) * 10) },
generateRandomPoint,
);
const selectRes = await client.queryArray<[Polygon]>(
`SELECT '(${
points.map(({ x, y }) => `(${x},${y})`).join(",")
})'::POLYGON`,
);
assertEquals(selectRes.rows[0][0], points);
}),
);
Deno.test(
"polygon array",
testClient(async (client) => {
const points = Array.from(
{ length: Math.floor((Math.random() + 1) * 10) },
generateRandomPoint,
);
const selectRes = await client.queryArray<[[Polygon]]>(
`SELECT ARRAY['(${
points.map(({ x, y }) => `(${x},${y})`).join(",")
})'::POLYGON]`,
);
assertEquals(selectRes.rows[0][0][0], points);
}),
);
Deno.test(
"circle",
testClient(async (client) => {
const point = generateRandomPoint();
const radius = String(generateRandomNumber(100));
const { rows } = await client.queryArray<[Circle]>(
`SELECT '<(${point.x},${point.y}), ${radius}>'::CIRCLE`,
);
assertEquals(rows[0][0], { point, radius });
}),
);
Deno.test(
"circle array",
testClient(async (client) => {
const point = generateRandomPoint();
const radius = String(generateRandomNumber(100));
const { rows } = await client.queryArray<[[Circle]]>(
`SELECT ARRAY['<(${point.x},${point.y}), ${radius}>'::CIRCLE]`,
);
assertEquals(rows[0][0][0], { point, radius });
}),
);
Deno.test(
"unhandled type",
testClient(async (client) => {
const { rows: exists } = await client.queryArray(
"SELECT EXISTS (SELECT TRUE FROM PG_TYPE WHERE UPPER(TYPNAME) = 'DIRECTION')",
);
if (exists[0][0]) {
await client.queryArray("DROP TYPE DIRECTION;");
}
await client.queryArray(
"CREATE TYPE DIRECTION AS ENUM ( 'LEFT', 'RIGHT' )",
);
const { rows: result } = await client.queryArray(
"SELECT 'LEFT'::DIRECTION;",
);
await client.queryArray("DROP TYPE DIRECTION;");
assertEquals(result[0][0], "LEFT");
}),
);
Deno.test(
"json",
testClient(async (client) => {
const result = await client.queryArray
`SELECT JSON_BUILD_OBJECT( 'X', '1' )`;
assertEquals(result.rows[0], [{ X: "1" }]);
}),
);
Deno.test(
"json array",
testClient(async (client) => {
const json_array = await client.queryArray(
`SELECT ARRAY_AGG(A) FROM (
SELECT JSON_BUILD_OBJECT( 'X', '1' ) AS A
UNION ALL
SELECT JSON_BUILD_OBJECT( 'Y', '2' ) AS A
) A`,
);
assertEquals(json_array.rows[0][0], [{ X: "1" }, { Y: "2" }]);
const jsonArrayNested = await client.queryArray(
`SELECT ARRAY[ARRAY[ARRAY_AGG(A), ARRAY_AGG(A)], ARRAY[ARRAY_AGG(A), ARRAY_AGG(A)]] FROM (
SELECT JSON_BUILD_OBJECT( 'X', '1' ) AS A
UNION ALL
SELECT JSON_BUILD_OBJECT( 'Y', '2' ) AS A
) A`,
);
assertEquals(
jsonArrayNested.rows[0][0],
[
[
[{ X: "1" }, { Y: "2" }],
[{ X: "1" }, { Y: "2" }],
],
[
[{ X: "1" }, { Y: "2" }],
[{ X: "1" }, { Y: "2" }],
],
],
);
}),
); | the_stack |
import {
createMockLoggerClient,
mochaLocalRegistry,
mochaTmpdir as tmpdir,
MockLoggerClient,
repoVersions,
} from "@adpt/testutils";
import {
grep,
messagesToString,
MessageType,
yarn,
} from "@adpt/utils";
import * as fs from "fs-extra";
import * as path from "path";
import should from "should";
import { createDeployment, fetchStatus, updateDeployment } from "../../src/ops";
import { DeployError, DeployState, DeploySuccess, isDeploySuccess } from "../../src/ops/common";
import { destroyDeployment, listDeploymentIDs } from "../../src/server/deployment";
import { LocalServer } from "../../src/server/local_server";
import { adaptServer, AdaptServer, AdaptServerType, mockServerTypes_ } from "../../src/server/server";
const simplePackageJson = {
name: "test_project",
version: "1.0.0",
dependencies: {
"source-map-support": "^0.5.5",
"@types/node": "^8.10.20",
"@adpt/core": repoVersions.core,
"typescript": "^3.0.3",
}
};
const simpleIndexTsx = `
import Adapt, {
AdaptElementOrNull,
Component,
Constructor,
gql,
Group,
handle,
Handle,
Observer,
PrimitiveComponent,
registerObserver,
WithChildren,
useDependsOn,
} from "@adpt/core";
import MockObserver from "@adpt/core/dist/src/observers/MockObserver";
import "./simple_plugin";
export class Simple extends PrimitiveComponent<{}> {
async status() { return { status: "Here I am!" }; }
}
class ActError extends PrimitiveComponent<{}> {}
class AnalyzeError extends PrimitiveComponent<{}> {}
export class DeleteError extends PrimitiveComponent<{ dep?: Handle }> {
dependsOn = (goal, helpers) => {
if (this.props.dep) return helpers.dependsOn(this.props.dep);
};
}
class BuildNull extends Component<{}> {
build() { return null; }
}
class ObserverToSimple extends Component<{ observer: { observerName: string } }> {
static defaultProps = { observer: MockObserver };
build() {
return <Observer
observer={this.props.observer}
query={ gql\`query { mockById(id: "1") { idSquared } }\` }
build={ (err, props)=>{
console.log("Props:", JSON.stringify(props), err);
return makeTwo(Simple);
} } />;
}
}
registerObserver(new MockObserver(true), "neverObserve");
async function makeSimple() {
return makeTwo(Simple);
}
async function makeNull() {
return null;
}
async function makeErr(): Promise<AdaptElementOrNull> {
throw new Error("makeErr");
}
function BuildError(props: { error: boolean; }) {
if (props.error) throw new Error("This is a build error");
return <Simple />;
}
function makeTwo(Comp: Constructor<Component<WithChildren>>) {
const key = Comp.name;
return <Comp key={key}><Comp key={key} /></Comp>;
}
function DeleteErrorApp() {
const h = handle();
return (
<Group>
<DeleteError handle={h} />
<DeleteError dep={h} />
</Group>
);
}
function ToSimple({ dep }: { dep?: Handle; }) {
useDependsOn((goal, helpers) => dep && helpers.dependsOn(dep));
return <Simple />;
}
// This app tests the primitiveDependencies functionality by placing a
// dependency between non-primitive components. That means the dependency
// will only be saved in primitiveDependencies, not the DOM and must be
// re-hydrated correctly from storage in order for the delete of this app
// to occur in the correct order.
// Create order: 0, 2, 1
// Delete order: 1, 2, 0
function PrimDependsApp() {
const h = [ handle(), handle(), handle() ];
return (
<Group>
<ToSimple handle={h[0]} />
<ToSimple handle={h[1]} dep={h[2]} />
<ToSimple handle={h[2]} dep={h[0]} />
</Group>
)
}
Adapt.stack("default", makeTwo(Simple));
Adapt.stack("ActError", <Group><ActError /><ActError /></Group>);
Adapt.stack("AnalyzeError", <AnalyzeError />);
Adapt.stack("null", null);
Adapt.stack("BuildNull", <BuildNull />);
Adapt.stack("ObserverToSimple", <ObserverToSimple />);
Adapt.stack("NeverObserverToSimple", <ObserverToSimple observer={{ observerName: "neverObserve" }}/>);
Adapt.stack("promises", makeSimple(), makeNull());
Adapt.stack("promises-err", makeSimple(), makeErr());
Adapt.stack("promise-func", makeSimple(), makeNull);
Adapt.stack("promise-func-err", makeSimple(), makeErr);
Adapt.stack("BuildError", <BuildError error={true} />);
Adapt.stack("DeleteError", <DeleteErrorApp />);
Adapt.stack("PrimDepends", <PrimDependsApp />);
`;
function defaultDomXmlOutput(namespace: string[]) {
const ns2 = namespace.concat("Simple");
return `<Adapt>
<Simple key="Simple" xmlns="urn:Adapt:test_project:1.0.0::index.tsx:Simple">
<Simple key="Simple" xmlns="urn:Adapt:test_project:1.0.0::index.tsx:Simple">
<__lifecycle__>
<field name="stateNamespace">${JSON.stringify(ns2)}</field>
<field name="keyPath">["Simple","Simple"]</field>
<field name="path">"/Simple/Simple"</field>
</__lifecycle__>
</Simple>
<__lifecycle__>
<field name="stateNamespace">${JSON.stringify(namespace)}</field>
<field name="keyPath">["Simple"]</field>
<field name="path">"/Simple"</field>
</__lifecycle__>
</Simple>
</Adapt>
`;
}
const simplePluginTs = `
import {
Action,
AdaptElement,
AdaptElementOrNull,
AdaptMountedElement,
childrenToArray,
domDiff,
FinalDomElement,
ChangeType,
Plugin,
PluginOptions,
registerPlugin,
} from "@adpt/core";
class EchoPlugin implements Plugin<{}> {
_log?: PluginOptions["log"];
log(...args: any[]) {
if (this._log == null) throw new Error("Plugin has no log function");
this._log(this.constructor.name + ":", ...args);
}
async start(options: PluginOptions) {
if (options.log == null) throw new Error("Plugin start called without log");
this._log = options.log;
this.log("start");
}
async observe(_oldDom: AdaptElementOrNull, dom: AdaptElementOrNull) {
this.log("observe");
return {};
}
analyze(oldDom: AdaptMountedElement | null, dom: AdaptMountedElement | null, _obs: {}): Action[] {
this.log("analyze");
const { added, deleted, commonNew } = domDiff(oldDom, dom);
const actions: Action[] = [];
const actErrors = [
// First action is purposely NOT returning a promise and doing
// a synchronous throw
() => { throw new Error("ActError1"); },
// Second action is correctly implemented as an async function
// so will return a rejected promise.
async () => { throw new Error("ActError2"); },
];
let actErrNum = 0;
let elNum = 1;
const info = (el: AdaptElement, type: ChangeType, what = "action") => {
const detail = "echo " + what + elNum;
return {
detail,
type,
changes: [{
detail,
type,
element: el as FinalDomElement,
}],
};
};
for (const el of added) {
switch (el.componentType.name) {
case "Group":
continue;
case "AnalyzeError":
throw new Error("AnalyzeError");
case "ActError":
actions.push({ ...info(el, ChangeType.create, "error"), act: actErrors[actErrNum]});
actErrNum = (actErrNum + 1) % actErrors.length;
break;
default:
const actStr = "action" + elNum;
actions.push({ ...info(el, ChangeType.create), act: () => this.doAction(actStr)})
break;
}
elNum++;
}
for (const el of deleted) {
switch (el.componentType.name) {
case "Group":
continue;
case "DeleteError":
actions.push({ ...info(el, ChangeType.delete, "delete"), act: async () => { throw new Error("DeleteError"); } });
break;
default:
const actStr = "delete" + elNum;
actions.push({ ...info(el, ChangeType.delete, "delete"), act: () => this.doAction(actStr)})
break;
}
elNum++;
}
for (const el of commonNew) {
switch (el.componentType.name) {
case "Group":
continue;
default:
const actStr = "action" + elNum;
actions.push({ ...info(el, ChangeType.modify), act: () => this.doAction(actStr)})
break;
}
elNum++;
}
return actions;
}
async finish() {
this.log("finish");
}
async doAction(msg: string) {
this.log(msg);
}
}
export function create() {
return new EchoPlugin();
}
registerPlugin({
name: "echo",
module,
create,
});
`;
const simplePluginPackageJson = `
{
"name": "echo_plugin",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": { },
"author": ""
}
`;
type ExpectedMsg = string | RegExp;
function checkMessages(ds: DeployState, expected: ExpectedMsg[],
type: MessageType = MessageType.error) {
const msgs = ds.messages.filter((m) => m.type === type);
should(msgs).have.length(expected.length);
for (let i = 0; i < expected.length; i++) {
if (typeof expected[i] === "string") {
should(msgs[i].content).equal(expected[i]);
} else {
should(msgs[i].content).match(expected[i]);
}
}
should(ds.summary[type]).equal(expected.length);
}
describe("createDeployment Tests", async function () {
let origServerTypes: AdaptServerType[];
let client: MockLoggerClient;
let adaptUrl: string;
let server_: AdaptServer;
async function server(): Promise<AdaptServer> {
if (!server_) {
server_ = await adaptServer(adaptUrl, { init: true });
}
return server_;
}
const baseTimeout = 40 * 1000; // To do a single create
const opTimeout = 20 * 1000; // Additional ops like status or update
this.timeout(baseTimeout);
tmpdir.all("adapt-createDeployment");
const localRegistry = mochaLocalRegistry.all({
port: "shared",
});
before(async function () {
this.timeout(30 * 1000);
origServerTypes = mockServerTypes_();
mockServerTypes_([LocalServer]);
adaptUrl = `file://${process.cwd()}/`;
await createProject();
});
after("cleanup server", async () => {
mockServerTypes_(origServerTypes);
if (server_) await server_.destroy();
});
beforeEach(() => {
client = createMockLoggerClient();
});
afterEach(async function () {
this.timeout(10 * 1000);
const s = await server();
let list = await listDeploymentIDs(s);
for (const id of list) {
await destroyDeployment(s, id);
}
list = await listDeploymentIDs(await server());
should(list).have.length(0);
});
interface DoCreate {
deployID?: string;
stackName: string;
}
async function doCreate(ops: DoCreate): Promise<DeployState> {
return createDeployment({
...ops,
adaptUrl,
fileName: "index.tsx",
initLocalServer: true,
initialStateJson: "{}",
client,
projectName: "myproject",
});
}
async function createError(stackName: string, expectedErrs: ExpectedMsg[],
expectedWarnings?: ExpectedMsg[], actError = false): Promise<DeployError> {
const ds = await doCreate({ stackName });
if (isDeploySuccess(ds)) {
should(isDeploySuccess(ds)).be.False();
throw new Error();
}
checkMessages(ds, expectedErrs, MessageType.error);
if (expectedWarnings) checkMessages(ds, expectedWarnings, MessageType.warning);
const list = await listDeploymentIDs(await server());
// If the error occurred during the act phase, the deployment should
// still exist. If it occurred earlier, it should have been destroyed.
if (actError) {
should(list).have.length(1);
should(ds.deployID).not.be.Undefined();
should(list[0]).equal(ds.deployID);
} else {
should(list).have.length(0);
}
return ds;
}
async function createSuccess(stackNameOrOpts: string | DoCreate): Promise<DeploySuccess> {
const opts = typeof stackNameOrOpts === "object" ?
stackNameOrOpts : { stackName: stackNameOrOpts };
const ds = await doCreate(opts);
if (!isDeploySuccess(ds)) {
throw new Error("Failure: " + messagesToString(ds.messages));
}
const list = await listDeploymentIDs(await server());
should(list).have.length(1);
should(list[0]).equal(ds.deployID);
return ds;
}
async function createProject() {
await fs.writeFile("index.tsx", simpleIndexTsx);
await fs.writeFile("package.json",
JSON.stringify(simplePackageJson, null, 2));
await fs.outputFile(path.join("simple_plugin", "index.ts"), simplePluginTs);
await fs.outputFile(path.join("simple_plugin", "package.json"), simplePluginPackageJson);
await yarn.install(localRegistry.yarnProxyOpts);
}
it("Should build a single file", async () => {
const ds = await createSuccess("default");
should(ds.domXml).equal(defaultDomXmlOutput(["Simple"]));
should(ds.stateJson).equal("{}");
should(ds.deployID).match(/myproject::default-[a-z]{4}/);
should(ds.mountedOrigStatus).eql({ status: "Here I am!" });
const lstdout = client.stdout;
should(lstdout).match(/EchoPlugin: start/);
should(lstdout).match(/EchoPlugin: observe/);
should(lstdout).match(/EchoPlugin: analyze/);
should(lstdout).match(/action1/);
should(lstdout).match(/action2/);
should(lstdout).match(/EchoPlugin: finish/);
});
it("Should build stack that is a promise", async () => {
const ds = await createSuccess("promises");
should(ds.domXml).equal(defaultDomXmlOutput(["Simple"]));
should(ds.stateJson).equal("{}");
should(ds.deployID).match(/myproject::promises-[a-z]{4}/);
const lstdout = client.stdout;
should(lstdout).match(/EchoPlugin: start/);
should(lstdout).match(/EchoPlugin: observe/);
should(lstdout).match(/EchoPlugin: analyze/);
should(lstdout).match(/action1/);
should(lstdout).match(/action2/);
should(lstdout).match(/EchoPlugin: finish/);
});
it("Should error on stack that has a rejected style promise", async () => {
await createError("promises-err", [
/Error creating deployment: Error: Error generated by stack style: makeErr/,
], []);
});
it("Should build stack that has a style function", async () => {
const ds = await createSuccess("promise-func");
should(ds.domXml).equal(defaultDomXmlOutput(["Simple"]));
should(ds.stateJson).equal("{}");
should(ds.deployID).match(/myproject::promise-func-[a-z]{4}/);
const lstdout = client.stdout;
should(lstdout).match(/EchoPlugin: start/);
should(lstdout).match(/EchoPlugin: observe/);
should(lstdout).match(/EchoPlugin: analyze/);
should(lstdout).match(/action1/);
should(lstdout).match(/action2/);
should(lstdout).match(/EchoPlugin: finish/);
});
it("Should error on stack that has a style function error", async () => {
await createError("promise-func-err", [
/Error creating deployment: Error: Error generated by stack style: makeErr/,
], []);
});
it("Should build a single file with DeployID and error on existing DeployID", async () => {
const deployID = "someID";
const opts = {
stackName: "default",
deployID,
};
const ds = await createSuccess(opts);
should(ds.domXml).equal(defaultDomXmlOutput(["Simple"]));
should(ds.stateJson).equal("{}");
should(ds.deployID).equal(deployID);
should(ds.mountedOrigStatus).eql({ status: "Here I am!" });
const lstdout = client.stdout;
should(lstdout).match(/EchoPlugin: start/);
should(lstdout).match(/EchoPlugin: observe/);
should(lstdout).match(/EchoPlugin: analyze/);
should(lstdout).match(/action1/);
should(lstdout).match(/action2/);
should(lstdout).match(/EchoPlugin: finish/);
const ds2 = await doCreate(opts);
if (isDeploySuccess(ds2)) {
throw new Error("Second deployment should not have been created with same deployID");
}
checkMessages(ds2, [/Error creating deployment: DeployID 'someID' already exists/], MessageType.error);
});
it("Should log error on analyze", async () => {
await createError("AnalyzeError", [
/Error creating deployment: Error: AnalyzeError/
], []);
});
it("Should log error on action", async () => {
await createError("ActError", [
/Error: ActError[12]/,
/Error: ActError[12]/,
/Error while deploying Group: A dependency failed to deploy successfully/,
/Error creating deployment: Errors encountered during plugin action phase/
], [], true);
});
it("Should report status", async function () {
this.timeout(baseTimeout + opTimeout);
const ds = await createSuccess("default");
should(ds.domXml).equal(defaultDomXmlOutput(["Simple"]));
should(ds.stateJson).equal("{}");
should(ds.deployID).match(/myproject::default-[a-z]{4}/);
should(ds.mountedOrigStatus).eql({ status: "Here I am!" });
const dsStatus = await fetchStatus({
adaptUrl,
deployID: ds.deployID,
fileName: "index.tsx",
client,
});
if (!isDeploySuccess(dsStatus)) {
throw new Error("Failure: " + messagesToString(dsStatus.messages));
}
should(dsStatus.domXml).equal(defaultDomXmlOutput(["Simple"]));
should(dsStatus.stateJson).equal("{}");
should(dsStatus.deployID).match(/myproject::default-[a-z]{4}/);
should(dsStatus.mountedOrigStatus).eql({ status: "Here I am!" });
});
it("Should deploy and update a stack with null root", async function () {
this.timeout(baseTimeout + opTimeout);
const ds1 = await createSuccess("null");
should(ds1.summary.error).equal(0);
should(ds1.domXml).equal(`<Adapt/>\n`);
should(ds1.stateJson).equal("{}");
const lstdout = client.stdout;
should(lstdout).match(/EchoPlugin: start/);
should(lstdout).match(/EchoPlugin: observe/);
should(lstdout).match(/EchoPlugin: analyze/);
should(lstdout).not.match(/action1/);
should(lstdout).not.match(/action2/);
should(lstdout).match(/EchoPlugin: finish/);
// Now update the deployment
const ds2 = await updateDeployment({
adaptUrl,
deployID: ds1.deployID,
fileName: "index.tsx",
client,
prevStateJson: "{}",
stackName: "default",
});
if (!isDeploySuccess(ds2)) {
should(isDeploySuccess(ds2)).be.True();
return;
}
should(ds2.summary.error).equal(0);
should(ds2.domXml).equal(defaultDomXmlOutput(["Simple"]));
should(ds2.stateJson).equal("{}");
});
it("Should deploy a stack that builds to null", async () => {
const ds1 = await createSuccess("BuildNull");
should(ds1.summary.error).equal(0);
should(ds1.domXml).equal(`<Adapt/>\n`);
should(ds1.stateJson).equal("{}");
const lstdout = client.stdout;
should(lstdout).match(/EchoPlugin: start/);
should(lstdout).match(/EchoPlugin: observe/);
should(lstdout).match(/EchoPlugin: analyze/);
should(lstdout).not.match(/action1/);
should(lstdout).not.match(/action2/);
should(lstdout).match(/EchoPlugin: finish/);
});
it("Should deploy and update a stack with observer", async function () {
this.timeout(baseTimeout + opTimeout);
const ds1 = await createSuccess("ObserverToSimple");
should(ds1.summary.error).equal(0);
should(ds1.domXml).equal(defaultDomXmlOutput(["ObserverToSimple", "ObserverToSimple-Observer", "Simple"]));
let lstdout = client.stdout;
should(lstdout).match(/Props: undefined null/);
should(lstdout).match(/Props: {"mockById":{"idSquared":1}} null/);
should(lstdout).match(/EchoPlugin: start/);
should(lstdout).match(/EchoPlugin: observe/);
should(lstdout).match(/EchoPlugin: analyze/);
should(lstdout).match(/action1/);
should(lstdout).match(/action2/);
should(lstdout).match(/EchoPlugin: finish/);
// Now update the deployment
const ds2 = await updateDeployment({
adaptUrl,
deployID: ds1.deployID,
fileName: "index.tsx",
client,
prevStateJson: "{}",
stackName: "ObserverToSimple",
});
if (!isDeploySuccess(ds2)) {
should(isDeploySuccess(ds2)).be.True();
return;
}
should(ds2.summary.error).equal(0);
should(ds2.domXml).equal(defaultDomXmlOutput(["ObserverToSimple", "ObserverToSimple-Observer", "Simple"]));
lstdout = client.stdout;
should(lstdout).not.match(/Props: undefined null/);
should(lstdout).match(/Props: {"mockById":{"idSquared":1}} null/);
});
it("Should report queries that need data after observation pass", async () => {
const ds1 = await createSuccess("NeverObserverToSimple");
should(ds1.summary.error).equal(0);
should(ds1.domXml).equal(defaultDomXmlOutput(["ObserverToSimple", "ObserverToSimple-Observer", "Simple"]));
const lstdout = client.stdout;
should(lstdout).match(/Props: undefined null/);
should(ds1.needsData).eql({ neverObserve: [{ query: "{\n mockById(id: \"1\") {\n idSquared\n }\n}\n" }] });
should(lstdout).match(/EchoPlugin: start/);
should(lstdout).match(/EchoPlugin: observe/);
should(lstdout).match(/EchoPlugin: analyze/);
should(lstdout).match(/action1/);
should(lstdout).match(/action2/);
should(lstdout).match(/EchoPlugin: finish/);
});
it("Should log build error", async () => {
await createError("BuildError", [
"Error creating deployment: Error building Adapt project"
], [
"Component BuildError cannot be built with current props: SFC build failed: This is a build error"
]);
});
it("Should stop on delete error", async () => {
const ds1 = await createSuccess("DeleteError");
should(ds1.stateJson).equal("{}");
should(ds1.deployID).match(/myproject::DeleteError-[a-z]{4}/);
let lstdout = client.stdout;
let lstderr = client.stderr;
should(lstdout).match(/EchoPlugin: start/);
should(lstdout).match(/EchoPlugin: observe/);
should(lstdout).match(/EchoPlugin: analyze/);
should(lstdout).match(/Doing echo action1/);
should(lstdout).match(/Doing echo action2/);
should(lstdout).match(/EchoPlugin: finish/);
should(lstderr).equal("");
// Now stop the deployment
const ds2 = await updateDeployment({
adaptUrl,
deployID: ds1.deployID,
fileName: "index.tsx",
client,
prevStateJson: "{}",
stackName: "(null)",
});
lstdout = client.stdout;
lstderr = client.stderr;
// Should return an error
if (isDeploySuccess(ds2)) throw should(isDeploySuccess(ds2)).be.False();
should(ds2.summary.error).equal(4); // 3 components + 1 overall failure
should(ds2.summary.warning).equal(0);
// component2 depends on component1, so component 2 creates last but
// deletes first.
should(lstdout).match(/Doing echo delete2/);
should(lstderr).match(/Error while echo delete2/);
// Because component2 errors, we shouldn't even try to delete
// component1.
should(lstdout).not.match(/Doing echo delete1/);
should(lstderr).not.match(/Error while echo delete1/);
});
it("Should continue on delete error with ignoreDeleteErrors", async () => {
const ds1 = await createSuccess("DeleteError");
// should(ds.domXml).equal(defaultDomXmlOutput(["Simple"]));
should(ds1.stateJson).equal("{}");
should(ds1.deployID).match(/myproject::DeleteError-[a-z]{4}/);
let lstdout = client.stdout;
let lstderr = client.stderr;
should(lstdout).match(/EchoPlugin: start/);
should(lstdout).match(/EchoPlugin: observe/);
should(lstdout).match(/EchoPlugin: analyze/);
should(lstdout).match(/Doing echo action1/);
should(lstdout).match(/Doing echo action2/);
should(lstdout).match(/EchoPlugin: finish/);
should(lstderr).equal("");
// Now stop the deployment, but ignore errors
const ds2 = await updateDeployment({
adaptUrl,
deployID: ds1.deployID,
fileName: "index.tsx",
client,
ignoreDeleteErrors: true,
prevStateJson: "{}",
stackName: "(null)",
});
lstdout = client.stdout;
lstderr = client.stderr;
// should return success
if (!isDeploySuccess(ds2)) throw should(isDeploySuccess(ds2)).be.True();
should(ds2.summary.error).equal(0);
should(ds2.summary.warning).equal(2);
// Both components should try to delete
should(lstdout).match(/Doing echo delete1/);
should(lstdout).match(/Doing echo delete2/);
should(lstdout).match(/WARNING: --Error \(ignored\) while echo delete1/);
should(lstdout).match(/WARNING: --Error \(ignored\) while echo delete2/);
should(lstderr).equal("");
});
it("Should rehydrate primitive dependencies", async () => {
const ds1 = await createSuccess("PrimDepends");
should(ds1.stateJson).equal("{}");
should(ds1.deployID).match(/myproject::PrimDepends-[a-z]{4}/);
let lstdout = client.stdout;
let lstderr = client.stderr;
let actionLogs = grep(lstdout, "Doing");
should(actionLogs).have.length(3);
should(actionLogs[0]).match(/action1/);
should(actionLogs[1]).match(/action3/);
should(actionLogs[2]).match(/action2/);
should(lstderr).equal("");
// Now stop the deployment
const ds2 = await updateDeployment({
adaptUrl,
deployID: ds1.deployID,
fileName: "index.tsx",
client,
prevStateJson: "{}",
stackName: "(null)",
});
lstdout = client.stdout;
lstderr = client.stderr;
if (!isDeploySuccess(ds2)) throw should(isDeploySuccess(ds2)).be.True();
should(ds2.summary.error).equal(0);
should(ds2.summary.warning).equal(0);
actionLogs = grep(lstdout, "Doing");
should(actionLogs).have.length(3);
should(actionLogs[0]).match(/delete2/);
should(actionLogs[1]).match(/delete3/);
should(actionLogs[2]).match(/delete1/);
should(lstderr).equal("");
});
}); | the_stack |
import EventDispatcher from "./../../starling/events/EventDispatcher";
import MeshEffect from "./../../starling/rendering/MeshEffect";
import Point from "openfl/geom/Point";
import VertexDataFormat from "./../rendering/VertexDataFormat";
import IndexData from "./../rendering/IndexData";
import VertexData from "./../rendering/VertexData";
import RenderState from "./../rendering/RenderState";
import Matrix from "openfl/geom/Matrix";
import Texture from "./../textures/Texture";
import Mesh from "./../display/Mesh";
declare namespace starling.styles
{
/** Dispatched every frame on styles assigned to display objects connected to the stage. */
// @:meta(Event(name="enterFrame", type="starling.events.EnterFrameEvent"))
/** MeshStyles provide a means to completely modify the way a mesh is rendered.
* The base class provides Starling's standard mesh rendering functionality: colored and
* (optionally) textured meshes. Subclasses may add support for additional features like
* color transformations, normal mapping, etc.
*
* <p><strong>Using styles</strong></p>
*
* <p>First, create an instance of the desired style. Configure the style by updating its
* properties, then assign it to the mesh. Here is an example that uses a fictitious
* <code>ColorStyle</code>:</p>
*
* <listing>
* image:Image = new Image(heroTexture);
* colorStyle:ColorStyle = new ColorStyle();
* colorStyle.redOffset = 0.5;
* colorStyle.redMultiplier = 2.0;
* image.style = colorStyle;</listing>
*
* <p>Beware:</p>
*
* <ul>
* <li>A style instance may only be used on one object at a time.</li>
* <li>A style might require the use of a specific vertex format;
* when the style is assigned, the mesh is converted to that format.</li>
* </ul>
*
* <p><strong>Creating your own styles</strong></p>
*
* <p>To create custom rendering code in Starling, you need to extend two classes:
* <code>MeshStyle</code> and <code>MeshEffect</code>. While the effect class contains
* the actual AGAL rendering code, the style provides the API that other developers will
* interact with.</p>
*
* <p>Subclasses of <code>MeshStyle</code> will add specific properties that configure the
* style's outcome, like the <code>redOffset</code> and <code>redMultiplier</code> properties
* in the sample above. Here's how to properly create such a class:</p>
*
* <ul>
* <li>Always provide a constructor that can be called without any arguments.</li>
* <li>Override <code>copyFrom</code> — that's necessary for batching.</li>
* <li>Override <code>createEffect</code> — this method must return the
* <code>MeshEffect</code> that will do the actual Stage3D rendering.</li>
* <li>Override <code>updateEffect</code> — this configures the effect created above
* right before rendering.</li>
* <li>Override <code>canBatchWith</code> if necessary — this method figures out if one
* instance of the style can be batched with another. If they all can, you can leave
* this out.</li>
* </ul>
*
* <p>If the style requires a custom vertex format, you must also:</p>
*
* <ul>
* <li>add a static constant called <code>VERTEX_FORMAT</code> to the class and</li>
* <li>override <code>get vertexFormat</code> and let it return exactly that format.</li>
* </ul>
*
* <p>When that's done, you can turn to the implementation of your <code>MeshEffect</code>;
* the <code>createEffect</code>-override will return an instance of this class.
* Directly before rendering begins, Starling will then call <code>updateEffect</code>
* to set it up.</p>
*
* @see starling.rendering.MeshEffect
* @see starling.rendering.VertexDataFormat
* @see starling.display.Mesh
*/
export class MeshStyle extends EventDispatcher
{
/** The vertex format expected by this style (the same as found in the MeshEffect-class). */
public static VERTEX_FORMAT:VertexDataFormat;
/** Creates a new MeshStyle instance.
* Subclasses must provide a constructor that can be called without any arguments. */
public constructor();
/** Copies all properties of the given style to the current instance (or a subset, if the
* classes don't match). Must be overridden by all subclasses!
*/
public copyFrom(meshStyle:MeshStyle):void;
/** Creates a clone of this instance. The method will work for subclasses automatically,
* no need to override it. */
public clone():MeshStyle;
/** Creates the effect that does the actual, low-level rendering.
* To be overridden by subclasses!
*/
public createEffect():MeshEffect;
/** Updates the settings of the given effect to match the current style.
* The given <code>effect</code> will always match the class returned by
* <code>createEffect</code>.
*
* <p>To be overridden by subclasses!</p>
*/
public updateEffect(effect:MeshEffect, state:RenderState):void;
/** Indicates if the current instance can be batched with the given style.
* To be overridden by subclasses if default behavior is not sufficient.
* The base implementation just checks if the styles are of the same type
* and if the textures are compatible.
*/
public canBatchWith(meshStyle:MeshStyle):boolean;
/** Copies the vertex data of the style's current target to the target of another style.
* If you pass a matrix, all vertices will be transformed during the process.
*
* <p>This method is used when batching meshes together for rendering. The parameter
* <code>targetStyle</code> will point to the style of a <code>MeshBatch</code> (a
* subclass of <code>Mesh</code>). Subclasses may override this method if they need
* to modify the vertex data in that process.</p>
*/
public batchVertexData(targetStyle:MeshStyle, targetVertexID?:number,
matrix?:Matrix, vertexID?:number, numVertices?:number):void;
/** Copies the index data of the style's current target to the target of another style.
* The given offset value will be added to all indices during the process.
*
* <p>This method is used when batching meshes together for rendering. The parameter
* <code>targetStyle</code> will point to the style of a <code>MeshBatch</code> (a
* subclass of <code>Mesh</code>). Subclasses may override this method if they need
* to modify the index data in that process.</p>
*/
public batchIndexData(targetStyle:MeshStyle, targetIndexID?:number, offset?:number,
indexID?:number, numIndices?:number):void;
// enter frame event
/*override*/ public addEventListener(type:string, listener:Function):void;
/*override*/ public removeEventListener(type:string, listener:Function):void;
// vertex manipulation
/** The position of the vertex at the specified index, in the mesh's local coordinate
* system.
*
* <p>Only modify the position of a vertex if you know exactly what you're doing, as
* some classes might not work correctly when their vertices are moved. E.g. the
* <code>Quad</code> class expects its vertices to spawn up a perfectly rectangular
* area; some of its optimized methods won't work correctly if that premise is no longer
* fulfilled or the original bounds change.</p>
*/
public getVertexPosition(vertexID:number, out?:Point):Point;
public setVertexPosition(vertexID:number, x:number, y:number):void;
/** Returns the alpha value of the vertex at the specified index. */
public getVertexAlpha(vertexID:number):number;
/** Sets the alpha value of the vertex at the specified index to a certain value. */
public setVertexAlpha(vertexID:number, alpha:number):void;
/** Returns the RGB color of the vertex at the specified index. */
public getVertexColor(vertexID:number):number;
/** Sets the RGB color of the vertex at the specified index to a certain value. */
public setVertexColor(vertexID:number, color:number):void;
/** Returns the texture coordinates of the vertex at the specified index. */
public getTexCoords(vertexID:number, out?:Point):Point;
/** Sets the texture coordinates of the vertex at the specified index to the given values. */
public setTexCoords(vertexID:number, u:number, v:number):void;
// properties
/** Returns a reference to the vertex data of the assigned target (or <code>null</code>
* if there is no target). Beware: the style itself does not own any vertices;
* it is limited to manipulating those of the target mesh. */
public readonly vertexData:VertexData;
protected get_vertexData():VertexData;
/** Returns a reference to the index data of the assigned target (or <code>null</code>
* if there is no target). Beware: the style itself does not own any indices;
* it is limited to manipulating those of the target mesh. */
public readonly indexData:IndexData;
protected get_indexData():IndexData;
/** The actual class of this style. */
public readonly type:any;
protected get_type():any;
/** Changes the color of all vertices to the same value.
* The getter simply returns the color of the first vertex. */
public color:number;
protected get_color():number;
protected set_color(value:number):number;
/** The format used to store the vertices. */
public readonly vertexFormat:VertexDataFormat;
protected get_vertexFormat():VertexDataFormat;
/** The texture that is mapped to the mesh (or <code>null</code>, if there is none). */
public texture:Texture;
protected get_texture():Texture;
protected set_texture(value:Texture):Texture;
/** The smoothing filter that is used for the texture. @default bilinear */
public textureSmoothing:string;
protected get_textureSmoothing():string;
protected set_textureSmoothing(value:string):string;
/** Indicates if pixels at the edges will be repeated or clamped.
* Only works for power-of-two textures. @default false */
public textureRepeat:boolean;
protected get_textureRepeat():boolean;
protected set_textureRepeat(value:boolean):boolean;
/** The target the style is currently assigned to. */
public readonly target:Mesh;
protected get_target():Mesh;
}
}
export default starling.styles.MeshStyle; | the_stack |
import React from 'react';
import { toast } from 'react-toastify';
import userEvent from '@testing-library/user-event';
import { render, fireEvent, waitFor } from '../../../test-utils';
import { FREQUENCY_MULTIPLIER, HAInstanceTypes, HAReplicationForm } from './HAReplicationForm';
import { HAConfig, HAReplicationSchedule } from '../../../redesign/helpers/dtos';
import { api } from '../../../redesign/helpers/api';
jest.mock('../../../redesign/helpers/api');
const mockConfig = {
cluster_key: 'fake-key',
instances: [
{
uuid: 'instance-id-1',
address: 'http://fake.address',
is_leader: true,
is_local: true
}
]
} as HAConfig;
const mockSchedule: HAReplicationSchedule = {
frequency_milliseconds: 5 * FREQUENCY_MULTIPLIER,
is_running: false // intentionally set enable replication toggle fo "off" to test all edge cases
};
const setup = (config?: HAConfig, schedule?: HAReplicationSchedule) => {
const backToView = jest.fn();
const component = render(
<HAReplicationForm config={config} schedule={schedule} backToViewMode={backToView} />
);
const form = component.getByRole('form');
const formFields = {
instanceType: form.querySelector<HTMLInputElement>('input[name="instanceType"]:checked')!,
instanceAddress: form.querySelector<HTMLInputElement>('input[name="instanceAddress"]')!,
clusterKey: form.querySelector<HTMLInputElement>('input[name="clusterKey"]')!,
replicationFrequency: form.querySelector<HTMLInputElement>('input[name="replicationFrequency"]')!,
replicationEnabled: form.querySelector<HTMLInputElement>('input[name="replicationEnabled"]')!
};
const formValues = {
instanceType: formFields.instanceType.value,
instanceAddress: formFields.instanceAddress.value,
clusterKey: formFields.clusterKey.value,
replicationFrequency: formFields.replicationFrequency.value,
replicationEnabled: formFields.replicationEnabled.checked
};
return { component, formFields, formValues, backToView };
};
describe('HA replication configuration form', () => {
it('should render form with values matching INITIAL_VALUES when no data provided', () => {
const { component, formValues } = setup();
expect(formValues).toEqual({
instanceType: HAInstanceTypes.Active,
instanceAddress: 'http://localhost',
clusterKey: '',
replicationFrequency: '1',
replicationEnabled: true
});
expect(component.getByRole('button', { name: /create/i })).toBeDisabled();
});
it('should render form with values provided in config and schedule mocks', () => {
const { component, formValues } = setup(mockConfig, mockSchedule);
expect(formValues).toEqual({
instanceType: mockConfig.instances[0].is_leader
? HAInstanceTypes.Active
: HAInstanceTypes.Standby,
instanceAddress: mockConfig.instances[0].address,
clusterKey: mockConfig.cluster_key,
replicationFrequency: String(mockSchedule.frequency_milliseconds / FREQUENCY_MULTIPLIER),
replicationEnabled: mockSchedule.is_running
});
// although form is valid - the submit button should be initially disabled as form is pristine
expect(component.getByRole('button', { name: /save/i })).toBeDisabled();
});
it('should show error toast on incorrect config', () => {
const config = { instances: [{}] } as HAConfig;
const toastError = jest.fn();
jest.spyOn(toast, 'error').mockImplementation(toastError);
setup(config, {} as HAReplicationSchedule);
expect(toastError).toBeCalled();
});
it('should change the view on switching from active to standy mode', () => {
const { component } = setup();
// check active mode view
expect(component.queryByRole('alert')).not.toBeInTheDocument();
expect(component.getByTestId('ha-replication-config-form-schedule-section')).toBeVisible();
// switch to standby mode
userEvent.click(component.getByText(/standby/i));
// check standby mode view
expect(component.getByRole('alert')).toBeInTheDocument();
expect(component.queryByRole('button', { name: /generate key/i })).not.toBeInTheDocument();
expect(component.getByTestId('ha-replication-config-form-schedule-section')).not.toBeVisible();
});
it('should disable all form fields in edit mode when replication toggle is off', () => {
const { component } = setup(mockConfig, mockSchedule);
component.getAllByRole('radio').forEach((element) => expect(element).toBeDisabled());
component.getAllByRole('textbox').forEach((element) => expect(element).toBeDisabled());
});
it('should not show any validation messages initially', () => {
const { component } = setup();
component
.queryAllByTestId('yb-label-validation-error')
.forEach((element) => expect(element).not.toBeInTheDocument());
});
// formik validation is async, therefore use async/await
it('should validate address field', async () => {
const { component, formFields } = setup();
userEvent.clear(formFields.instanceAddress);
fireEvent.blur(formFields.instanceAddress);
expect(await component.findByText(/required field/i)).toBeInTheDocument();
userEvent.clear(formFields.instanceAddress);
userEvent.type(formFields.instanceAddress, 'lorem ipsum');
expect(await component.findByText(/should be a valid url/i)).toBeInTheDocument();
userEvent.clear(formFields.instanceAddress);
userEvent.type(formFields.instanceAddress, 'http://valid.url');
expect(await component.findByText(/should be a valid url/i)).not.toBeInTheDocument();
});
it('should validate cluster key field', async () => {
const { component, formFields } = setup();
// that fields is editable in standby mode only
userEvent.click(component.getByText(/standby/i));
fireEvent.blur(formFields.clusterKey);
expect(await component.findByText(/required field/i)).toBeInTheDocument();
userEvent.type(formFields.clusterKey, 'some-fake-key');
expect(await component.findByText(/required field/i)).not.toBeInTheDocument();
});
it('should validate replication frequency field', async () => {
const { component, formFields } = setup();
// check for required value validation
userEvent.clear(formFields.replicationFrequency);
fireEvent.blur(formFields.replicationFrequency);
expect(await component.findByText(/required field/i)).toBeInTheDocument();
// disable frequency input and make sure previously visible error message is gone
userEvent.click(formFields.replicationEnabled);
expect(formFields.replicationFrequency).toBeDisabled();
expect(await component.findByText(/required field/i)).not.toBeInTheDocument();
// enable frequency input back and assure it's enabled
userEvent.click(formFields.replicationEnabled);
expect(formFields.replicationFrequency).toBeEnabled();
// check for min value validation
userEvent.clear(formFields.replicationFrequency);
userEvent.type(formFields.replicationFrequency, '-1');
expect(await component.findByText(/minimum value is 1/i)).toBeInTheDocument();
// check if it filters non-number input and validation message is gone
userEvent.clear(formFields.replicationFrequency);
userEvent.type(formFields.replicationFrequency, 'qwerty 123');
expect(formFields.replicationFrequency).toHaveValue(123);
expect(await component.findByTestId('yb-label-validation-error')).not.toBeInTheDocument();
});
it('should disable submit button on validation failure', async () => {
const { component, formFields } = setup(mockConfig, mockSchedule);
// enable frequency field, type smth and check that submit button become enabled
userEvent.click(formFields.replicationEnabled);
userEvent.type(formFields.replicationFrequency, '10');
fireEvent.blur(formFields.replicationFrequency);
expect(component.getByRole('button', { name: /save/i })).toBeEnabled();
// force validation error and check if submit button become disabled
userEvent.clear(formFields.replicationFrequency);
fireEvent.blur(formFields.replicationFrequency);
expect(await component.findByRole('button', { name: /save/i })).toBeDisabled();
});
it('should check active config creation happy path', async () => {
const fakeValues = {
configId: 'fake-config-id',
instanceAddress: 'http://fake-address',
clusterKey: 'fake-key',
replicationFrequency: '30'
};
(api.generateHAKey as jest.Mock).mockResolvedValue({ cluster_key: fakeValues.clusterKey });
(api.createHAConfig as jest.Mock).mockResolvedValue({ uuid: fakeValues.configId });
(api.createHAInstance as jest.Mock).mockResolvedValue({});
(api.startHABackupSchedule as jest.Mock).mockResolvedValue({});
const { component, formFields, backToView } = setup();
// enter address
userEvent.clear(formFields.instanceAddress);
userEvent.type(formFields.instanceAddress, fakeValues.instanceAddress);
// generate cluster key and check form value
userEvent.click(component.queryByRole('button', { name: /generate key/i })!);
await waitFor(() => expect(api.generateHAKey).toBeCalled());
expect(formFields.clusterKey).toHaveValue(fakeValues.clusterKey);
// set replication frequency
userEvent.clear(formFields.replicationFrequency);
userEvent.type(formFields.replicationFrequency, fakeValues.replicationFrequency);
// click the submit button
expect(component.getByRole('button', { name: /create/i })).toBeEnabled();
userEvent.click(component.getByRole('button', { name: /create/i }));
await waitFor(() => {
expect(api.createHAConfig).toBeCalledWith(fakeValues.clusterKey);
expect(api.createHAInstance).toBeCalledWith(
fakeValues.configId,
fakeValues.instanceAddress,
true,
true
);
expect(api.startHABackupSchedule).toBeCalledWith(
fakeValues.configId,
Number(fakeValues.replicationFrequency) * FREQUENCY_MULTIPLIER
);
});
expect(backToView).toBeCalled();
});
it('should check standby config creation happy path', async () => {
const fakeValues = {
configId: 'fake-config-id',
instanceAddress: 'http://fake-address',
clusterKey: 'fake-key'
};
(api.createHAConfig as jest.Mock).mockResolvedValue({ uuid: fakeValues.configId });
(api.createHAInstance as jest.Mock).mockResolvedValue({});
const { component, formFields, backToView } = setup();
// select standby mode
userEvent.click(component.getByText(/standby/i));
// enter address
userEvent.clear(formFields.instanceAddress);
userEvent.type(formFields.instanceAddress, fakeValues.instanceAddress);
// enter cluster key
userEvent.type(formFields.clusterKey, fakeValues.clusterKey);
// click the submit button
expect(component.getByRole('button', { name: /create/i })).toBeEnabled();
userEvent.click(component.getByRole('button', { name: /create/i }));
await waitFor(() => {
expect(api.createHAConfig).toBeCalledWith(fakeValues.clusterKey);
expect(api.createHAInstance).toBeCalledWith(
fakeValues.configId,
fakeValues.instanceAddress,
false,
true
);
});
expect(backToView).toBeCalled();
});
it('should check enabling replication happy flow', async () => {
(api.startHABackupSchedule as jest.Mock).mockResolvedValue({});
const { component, formFields, backToView } = setup(mockConfig, mockSchedule);
userEvent.click(formFields.replicationEnabled);
expect(component.getByRole('button', { name: /save/i })).toBeEnabled();
userEvent.click(component.getByRole('button', { name: /save/i }));
await waitFor(() => {
expect(api.startHABackupSchedule).toBeCalledWith(
undefined,
mockSchedule.frequency_milliseconds
);
});
expect(backToView).toBeCalled();
});
it('should check disabling replication happy flow', async () => {
(api.stopHABackupSchedule as jest.Mock).mockResolvedValue({});
const { component, formFields, backToView } = setup(mockConfig, mockSchedule);
// make dummy changes to form to enable submit button with turned off replication toggle
userEvent.click(formFields.replicationEnabled);
userEvent.type(formFields.replicationFrequency, '1');
userEvent.click(formFields.replicationEnabled);
expect(component.getByRole('button', { name: /save/i })).toBeEnabled();
userEvent.click(component.getByRole('button', { name: /save/i }));
await waitFor(() => expect(api.stopHABackupSchedule).toBeCalledWith(undefined));
expect(backToView).toBeCalled();
});
it('should show toast on api call failure', async () => {
(api.startHABackupSchedule as jest.Mock).mockRejectedValue({});
const toastError = jest.fn();
jest.spyOn(toast, 'error').mockImplementation(toastError);
const consoleError = jest.fn();
jest.spyOn(console, 'error').mockImplementation(consoleError);
const { component, formFields, backToView } = setup(mockConfig, mockSchedule);
userEvent.click(formFields.replicationEnabled);
userEvent.click(component.getByRole('button', { name: /save/i }));
await waitFor(() => {
expect(toastError).toBeCalled();
expect(consoleError).toBeCalled();
});
expect(backToView).not.toBeCalled();
});
}); | the_stack |
import { existsSync, readFileSync } from 'fs'
import { request } from 'https'
import { copyFileAndCreateFolder, createFolderIfNotExists, writeFileAndCreateFolder } from './check_dependencies_fs'
import * as semver from './check_dependencies_semver'
function httpGet(params) {
return new Promise((resolve, reject) => {
const req = request(params, res => {
// reject on bad status
if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300)) {
return reject(new Error('statusCode=' + res.statusCode))
}
// cumulate data
let body: any[] = []
res.on('data', chunk => {
body.push(chunk)
})
// resolve on end
res.on('end', () => {
try {
body = JSON.parse(Buffer.concat(body).toString())
} catch (e) {
body = Buffer.concat(body).toString() as any
}
resolve(body)
})
})
// reject on request error
req.on('error', err => {
// This is not a "Second reject", just a different sort of failure
reject(err)
})
// IMPORTANT
req.end()
})
}
const cliCommand: string = process.argv[2]
const validCommands = [undefined, 'check']
if (!validCommands.some(validCommand => validCommand === cliCommand)) {
throw new Error('invalid command')
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // $& means the whole matched string
}
/*
function getStringDifference(a: string, b: string): string {
let i: number = 0
let j: number = 0
let result: string = ''
while (j < b.length) {
if (a[i] !== b[j] || i === a.length) {
result += b[j]
} else {
i++
}
j++
}
return result
}
*/
interface Dependency {
name: string // Name of the module
entrypoint: string
version: string
repository: string
commitHash: string
files: string[]
renameFiles?: [string, string][]
replaceInFiles?: { filename: string; replacements: { from: string; to: string; expectedReplacements: number }[] }[]
deps?: string[]
ignoredDeps: { module: string; reason: string }[]
}
interface DepsFile {
[key: string]: Dependency
}
function log(color: string, ...message: any[]): void {
const colors: { [key: string]: string } = {
black: '\x1b[30m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
white: '\x1b[37m'
}
const hasColor: string = colors[color]
if (hasColor) {
console.log(`${colors[color]}%s\x1b[0m`, ...message)
} else {
console.log(color, ...message)
}
}
// tslint:disable:cyclomatic-complexity
export const validateDepsJson = async (depsFile: DepsFile) => {
log(`
#############################
## ##
## VALIDATING DEPENDENCIES ##
## ##
#############################
`)
const verificationFailed = (prop: string, reason: string) => {
log('red', `${prop} is invalid because ${reason}`)
return false
}
const packageJson = JSON.parse(readFileSync(`./package.json`, 'utf-8'))
const topLevelPackages = Object.keys(packageJson.localDependencies).map(tlp => `${tlp}-${packageJson.localDependencies[tlp]}`)
topLevelPackages.forEach(pkgName => {
if (depsFile[pkgName]) {
log('green', `${pkgName} is in deps file`)
} else {
log('red', `${pkgName} is NOT in deps file`)
}
})
const keys = Object.keys(depsFile)
for (const prop of keys) {
log('blue', `--- ${prop} ---`)
let isValid = true
if (!prop.endsWith(depsFile[prop].version)) {
isValid =
isValid && verificationFailed(prop, `version in key doesn't match version in json. ${prop} should end in ${depsFile[prop].version}`)
}
if (!prop.startsWith(depsFile[prop].name)) {
isValid =
isValid &&
verificationFailed(prop, `name in key doesn't match name of repository. ${prop} should start with ${depsFile[prop].name}`)
}
const pkg = JSON.parse(readFileSync(`./src/dependencies/github/${prop}/package.json`, 'utf-8'))
if (!pkg) {
isValid = isValid && verificationFailed(prop, `package.json not found`)
}
if (pkg.dependencies) {
const dependencyKeys = Object.keys(pkg.dependencies)
for (const dependency of dependencyKeys) {
const key = keys.find(key => key.startsWith(dependency + '-')) // TODO: Handle packages that start with the same name
if (!key) {
if (depsFile[prop].ignoredDeps) {
const x = depsFile[prop].ignoredDeps.find(ignoredDep => ignoredDep.module === dependency)
if (x) {
log('green', `Ignored "${dependency}" because ${x.reason}`)
} else {
isValid = isValid && verificationFailed(prop, `${dependency}@${pkg.dependencies[dependency]} not found`)
}
} else {
isValid = isValid && verificationFailed(prop, `${dependency}@${pkg.dependencies[dependency]} not found`)
}
} else {
const packageDeps = depsFile[prop].deps
if (!(packageDeps && packageDeps.some(dep => dep.startsWith(dependency + '-')))) {
isValid = isValid && verificationFailed(dependency, `is not in deps!`)
} else {
const keyVersion = key.substr(key.lastIndexOf('-') + 1) // TODO: Handle multiple versions
const isSatisfied = semver.satisfies(keyVersion, pkg.dependencies[dependency])
if (!isSatisfied && pkg.dependencies[dependency].length < 20) {
console.log('FAIL', keyVersion, pkg.dependencies[dependency])
isValid = isValid && verificationFailed(dependency, `version is not satisfied`)
}
}
}
}
}
const deps = depsFile[prop].deps
if (deps) {
deps.forEach(dep => {
if (!depsFile[dep]) {
isValid = isValid && verificationFailed(prop, `dependency ${dep} doesn't exist`)
}
})
}
const renameFiles = depsFile[prop].renameFiles
if (renameFiles) {
renameFiles.forEach(([source, destination]) => {
if (!depsFile[prop].files.includes(source)) {
isValid = isValid && verificationFailed(prop, `renaming file that does not exist in files array ${source}`)
}
})
}
const parentPackages = keys.filter(key => {
const deps = depsFile[key].deps
if (deps) {
return deps.includes(prop)
}
return false
})
if (parentPackages.length === 0) {
// Check if it's a top level package
if (!topLevelPackages.includes(prop)) {
isValid = isValid && verificationFailed(prop, `is not used in any other package`)
}
}
if (isValid) {
log('green', `${prop} is valid`)
} else {
log('blue', `--- ${prop} ---`)
}
}
}
const simpleHash = (s: string): string => {
let h = 0xdeadbeef
for (let i = 0; i < s.length; i++) {
h = Math.imul(h ^ s.charCodeAt(i), 2654435761)
}
const code = (h ^ (h >>> 16)) >>> 0
const buff = Buffer.from(code.toString())
return buff
.toString('base64')
.split('=')
.join('')
}
const downloadFile = async (url: string) => {
const cachePath = './src/dependencies/cache/'
const cacheFile = `${cachePath}${simpleHash(url)}`
const fileExists = existsSync(cacheFile)
if (fileExists) {
log('cyan', `Using cache ${url}`)
return readFileSync(cacheFile, 'utf-8')
} else {
try {
log('magenta', `Downloading ${url}`)
const response: any = await httpGet(url)
writeFileAndCreateFolder(cacheFile, response)
return response
} catch (error) {
if (error.response && error.response.status) {
log('red', `Error: ${error.config.url} ${error.response.status}`)
} else {
throw error
}
}
}
}
// export const checkCacheAndDownload = (cachePath: string, localPath: string, remotePath: string) => {
// return new Promise((resolve, reject) => {
// exists(cachePath, exists => {
// if (!exists) {
// console.log('DOES NOT EXIST', localPath)
// downloadFile(remotePath)
// .then(data => {
// createFolderIfNotExists(localPath)
// resolve(data)
// })
// .catch((error: AxiosError) => {
// reject(error)
// })
// } else {
// console.log('ALREADY EXISTS')
// }
// })
// })
// }
export const getPackageJsonForDepsFiles = async (depsFile: DepsFile) => {
for (const prop of Object.keys(depsFile)) {
createFolderIfNotExists(`./src/dependencies/github/${prop}/`)
const localPath = `./src/dependencies/github/${prop}/package.json`
const fileExists = existsSync(localPath)
if (!fileExists) {
console.log('DOES NOT EXIST', prop)
const urlCommit: string = `https://raw.githubusercontent.com/${depsFile[prop].repository}/${depsFile[prop].commitHash}/package.json`
const data = await downloadFile(urlCommit)
writeFileAndCreateFolder(localPath, data)
log('green', `${prop} (commit): Saved package.json`)
} else {
console.log(`ALREADY EXISTS: ${prop}`)
}
}
}
export const getFilesForDepsFile = async (depsFile: DepsFile) => {
for (const prop of Object.keys(depsFile)) {
// const urlLatestCommits: string = `https://api.github.com/repos/${depsFile[prop].repository}/commits`
// Axios(urlLatestCommits)
// .then(response => {
// const { data }: { data: { sha: string }[] } = response
// const isSame: boolean = depsFile[prop].commitHash === data[0].sha
// const diffUrl: string = `https://github.com/${depsFile[prop].repository}/compare/${depsFile[prop].commitHash.substr(
// 0,
// 7
// )}..${data[0].sha.substr(0, 7)}`
// log(isSame ? 'green' : 'red', `${prop} (commit): ${isSame ? 'up to date' : diffUrl}`)
// })
// .catch((error: AxiosError) => {
// console.error(error)
// })
for (const file of depsFile[prop].files) {
const urlCommit: string = `https://raw.githubusercontent.com/${depsFile[prop].repository}/${depsFile[prop].commitHash}/${file}`
// const urlMaster: string = `https://raw.githubusercontent.com/${depsFile[prop].repository}/master/${file}`
// Rename files when copying
let renamedFile = file
const renamedFiles = depsFile[prop].renameFiles
if (renamedFiles) {
const replaceArray = renamedFiles.find(replace => replace[0] === file)
if (replaceArray) {
renamedFile = replaceArray[1]
}
}
const localPath = `./src/dependencies/src/${prop}/${renamedFile}`
const localCache = `./src/dependencies/github/${prop}/${file}`
const cacheExists = existsSync(localCache)
if (!cacheExists) {
const data = await downloadFile(urlCommit)
if (!data) {
return
}
writeFileAndCreateFolder(localCache, data)
log('green', `${prop} (commit): Cached file: ${file}`)
}
// const fileExists = existsSync(localPath)
// if (!fileExists) {
// console.log('DOES NOT EXIST, CHECKING CACHE ' + localPath)
copyFileAndCreateFolder(localCache, localPath)
// }
/*
downloadFile(urlCommit)
.then(data => {
const difference: string = getStringDifference(localContent.trim(), data.trim())
const isSame: boolean = difference.trim().length === 0
log(isSame ? 'green' : 'red', `${prop} (commit): ${file} is ${isSame ? 'unchanged' : 'CHANGED'}`)
})
.catch((error: AxiosError) => {
})
downloadFile(urlMaster)
.then(data => {
const difference: string = getStringDifference(localContent.trim(), data.trim())
const isSame: boolean = difference.trim().length === 0
log(isSame ? 'green' : 'red', `${prop} (master): ${file} is ${isSame ? 'unchanged' : 'CHANGED'}`)
})
.catch((error: AxiosError) => {
})*/
}
}
}
const replaceWithinContainer = (content: string, before: string, after: string) => {
const containers = [`require("PLACEHOLDER")`, `require('PLACEHOLDER')`, ` from "PLACEHOLDER"`, ` from 'PLACEHOLDER'`]
for (const container of containers) {
const searchString = container.split('PLACEHOLDER').join(before)
const replaceString = container.split('PLACEHOLDER').join(after)
content = content.split(searchString).join(replaceString)
}
return content
}
const replaceImports = async (depsFile: DepsFile) => {
for (const prop of Object.keys(depsFile)) {
const predefinedReplacements = depsFile[prop].replaceInFiles
for (const file of depsFile[prop].files) {
// Rename files
let renamedFile = file
const renamedFiles = depsFile[prop].renameFiles
if (renamedFiles) {
const replaceArray = renamedFiles.find(replace => replace[0] === file)
if (replaceArray) {
renamedFile = replaceArray[1]
}
}
const localPath = `./src/dependencies/src/${prop}/${renamedFile}`
let fileContent = readFileSync(localPath, 'utf-8')
// INCLUDE DEFINED REPLACEMENTS
if (predefinedReplacements) {
const replacements = predefinedReplacements.find(predefinedReplacement => predefinedReplacement.filename === renamedFile)
if (replacements) {
replacements.replacements.forEach(replacement => {
const count = (fileContent.match(new RegExp(escapeRegExp(replacement.from), 'g')) || []).length
if (count === replacement.expectedReplacements) {
fileContent = fileContent.split(replacement.from).join(replacement.to)
} else {
log('red', `EXPECTED ${replacement.expectedReplacements} MATCHES BUT HAVE ${count}`)
}
})
}
}
const dependencies = depsFile[prop].deps
if (dependencies) {
for (const dependency of dependencies) {
const dependencyDefinition = depsFile[dependency]
if (!dependencyDefinition) {
console.log('WOOPS', dependency)
} else {
const levels = (file.match(/\//g) || []).length + (prop.includes('/') ? 1 : 0)
const levelUpString = '../'
if (dependencyDefinition.entrypoint === '') {
dependencyDefinition.entrypoint = 'index'
}
const relativePath = `${levelUpString.repeat(levels + 1)}${dependencyDefinition.name}-${dependencyDefinition.version}/${
dependencyDefinition.entrypoint
}`
fileContent = replaceWithinContainer(fileContent, dependencyDefinition.name, relativePath)
}
}
}
writeFileAndCreateFolder(localPath, fileContent)
}
}
}
{
const dependencies: string = readFileSync('./src/dependencies/deps.json', 'utf-8')
const deps: DepsFile = JSON.parse(dependencies)
createFolderIfNotExists(`./src/dependencies/cache/`)
createFolderIfNotExists(`./src/dependencies/github/`)
createFolderIfNotExists(`./src/dependencies/src/`)
console.log('START')
getFilesForDepsFile(deps).then(() => {
console.log('MID')
getPackageJsonForDepsFiles(deps).then(() => {
console.log('END')
validateDepsJson(deps).then(() => {
console.log('VALIDATED')
replaceImports(deps).then(() => {
console.log('REPLACED IMPORTS')
})
})
})
})
} | the_stack |
import { Material } from './Material';
import { MeshView } from './meshView';
import { bufferToUint16Array, bufferToFloat32Array } from './bufferUtil';
import { Gltf } from './gltfType';
const Cesium = require('cesium');
const util = require('./utility');
const Cartesian3 = Cesium.Cartesian3;
const ComponentDatatype = Cesium.ComponentDatatype;
const defined = Cesium.defined;
const Matrix4 = Cesium.Matrix4;
const typeToNumberOfComponents = util.typeToNumberOfComponents;
const sizeOfUint16 = 2;
const sizeOfFloat32 = 4;
const whiteOpaqueMaterial = new Material([1.0, 1.0, 1.0, 1.0]);
export class Mesh {
private readonly scratchCartesian = new Cartesian3();
private readonly scratchMatrix = new Matrix4();
indices: number[];
positions: number[];
normals: number[];
uvs: number[];
vertexColors: number[];
batchIds?: number[];
material?: Material;
views?: MeshView[];
/**
* Stores the vertex attributes and indices describing a mesh.
*
* @param {Object} options Object with the following properties:
* @param {Number[]} options.indices An array of integers representing the
* mesh indices.
* @param {Number[]} options.positions A packed array of floats representing
* the mesh positions.
* @param {Number[]} options.normals A packed array of floats representing
* the mesh normals.
* @param {Number[]} options.uvs A packed array of floats representing the
* mesh UVs.
* @param {Number[]} options.vertexColors A packed array of integers
* representing the vertex colors.
* @param {Number[]} [options.batchIds] An array of integers representing
* the batch ids.
* @param {Material} [options.material] A material to apply to the mesh.
* @param {MeshView[]} [options.views] An array of MeshViews.
*
* @constructor
*/
private constructor(
indices: number[],
positions: number[],
normals: number[],
uvs: number[],
vertexColors: number[],
batchIds?: number[],
material?: Material,
views?: MeshView[]
) {
this.indices = indices;
this.positions = positions;
this.normals = normals;
this.uvs = uvs;
this.vertexColors = vertexColors;
this.batchIds = batchIds;
this.material = material;
this.views = views;
}
/**
* Transform the mesh with the provided transform.
*
* @param {Matrix4} transform The transform.
*/
transform(transform: object) {
let i;
const positions = this.positions;
const normals = this.normals;
const vertexCount = this.vertexCount;
// Transform positions
for (i = 0; i < vertexCount; ++i) {
const position = Cartesian3.unpack(
positions,
i * 3,
this.scratchCartesian
);
Matrix4.multiplyByPoint(transform, position, position);
Cartesian3.pack(position, positions, i * 3);
}
const inverseTranspose = this.scratchMatrix;
Matrix4.transpose(transform, inverseTranspose);
Matrix4.inverse(inverseTranspose, inverseTranspose);
// Transform normals
for (i = 0; i < vertexCount; ++i) {
const normal = Cartesian3.unpack(
normals,
i * 3,
this.scratchCartesian
);
Matrix4.multiplyByPointAsVector(inverseTranspose, normal, normal);
Cartesian3.normalize(normal, normal);
Cartesian3.pack(normal, normals, i * 3);
}
}
/**
* Set the positions relative to center.
*/
setPositionsRelativeToCenter() {
const positions = this.positions;
const center = this.center;
const vertexCount = this.vertexCount;
for (let i = 0; i < vertexCount; ++i) {
const position = Cartesian3.unpack(
positions,
i * 3,
this.scratchCartesian
);
Cartesian3.subtract(position, center, position);
Cartesian3.pack(position, positions, i * 3);
}
}
/**
* Get the number of vertices in the mesh.
*
* @returns {Number} The number of vertices.
*/
get vertexCount(): number {
return this.positions.length / 3;
}
/**
* Get the center of the mesh.
*
* @returns {Cartesian3} The center position
*/
get center() {
const center = new Cartesian3();
const positions = this.positions;
const vertexCount = this.vertexCount;
for (let i = 0; i < vertexCount; ++i) {
const position = Cartesian3.unpack(
positions,
i * 3,
this.scratchCartesian
);
Cartesian3.add(position, center, center);
}
Cartesian3.divideByScalar(center, vertexCount, center);
return center;
}
/**
* Bake materials as vertex colors. Use the default white opaque material.
*/
transferMaterialToVertexColors() {
const material = this.material;
this.material = whiteOpaqueMaterial;
const vertexCount = this.vertexCount;
const vertexColors = new Array(vertexCount * 4);
this.vertexColors = vertexColors;
for (let i = 0; i < vertexCount; ++i) {
vertexColors[i * 4 + 0] = Math.floor(material.baseColor[0] * 255);
vertexColors[i * 4 + 1] = Math.floor(material.baseColor[1] * 255);
vertexColors[i * 4 + 2] = Math.floor(material.baseColor[2] * 255);
vertexColors[i * 4 + 3] = Math.floor(material.baseColor[3] * 255);
}
}
/**
* Batch multiple meshes into a single mesh. Assumes the input meshes do
* not already have batch ids.
*
* @param {Mesh[]} meshes The meshes that will be batched together.
* @returns {Mesh} The batched mesh.
*/
static batch(meshes: Mesh[]) {
let batchedPositions = [];
let batchedNormals = [];
let batchedUvs = [];
let batchedVertexColors = [];
let batchedBatchIds = [];
let batchedIndices = [];
let startIndex = 0;
let indexOffset = 0;
const views = [];
let currentView;
const meshesLength = meshes.length;
for (let i = 0; i < meshesLength; ++i) {
const mesh = meshes[i];
const positions = mesh.positions;
const normals = mesh.normals;
const uvs = mesh.uvs;
const vertexColors = mesh.vertexColors;
const vertexCount = mesh.vertexCount;
// Generate batch ids for this mesh
const batchIds = new Array(vertexCount).fill(i);
batchedPositions = batchedPositions.concat(positions);
batchedNormals = batchedNormals.concat(normals);
batchedUvs = batchedUvs.concat(uvs);
batchedVertexColors = batchedVertexColors.concat(vertexColors);
batchedBatchIds = batchedBatchIds.concat(batchIds);
// Generate indices and mesh views
const indices = mesh.indices;
const indicesLength = indices.length;
if (
!defined(currentView) ||
currentView.material !== mesh.material
) {
currentView = new MeshView(
mesh.material,
indexOffset,
indicesLength
);
views.push(currentView);
} else {
currentView.indexCount += indicesLength;
}
for (let j = 0; j < indicesLength; ++j) {
const index = indices[j] + startIndex;
batchedIndices.push(index);
}
startIndex += vertexCount;
indexOffset += indicesLength;
}
return new Mesh(
batchedIndices,
batchedPositions,
batchedNormals,
batchedUvs,
batchedVertexColors,
batchedBatchIds,
undefined,
views
);
}
/**
* Clone the mesh geometry and create a new mesh.
* Assumes the input mesh does not already have batch ids.
*
* @param {Mesh} mesh The mesh to clone.
* @returns {Mesh} The cloned mesh.
*/
static clone(mesh: Mesh) {
return new Mesh(
mesh.indices.slice(),
mesh.positions.slice(),
mesh.normals.slice(),
mesh.uvs.slice(),
mesh.vertexColors.slice(),
undefined,
mesh.material
);
}
/**
* Creates a cube mesh.
*
* @returns {Mesh} A cube mesh.
*/
static createCube(): Mesh {
// prettier-ignore
const indices = [0, 1, 2, 0, 2, 3, 6, 5, 4, 7, 6, 4, 8, 9, 10, 8, 10,
11, 14, 13, 12, 15, 14, 12, 18, 17, 16, 19, 18, 16, 20, 21, 22, 20,
22, 23];
// prettier-ignore
const positions = [-0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5,
0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5,
0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5,
-0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5,
-0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5,
0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5,
0.5];
// prettier-ignore
const normals = [0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,
1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0,
1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0,
0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 1.0,
0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0,
0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0];
// prettier-ignore
const uvs = [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0,
1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0];
// prettier-ignore
const vertexColors = new Array(24 * 4).fill(0);
return new Mesh(indices, positions, normals, uvs, vertexColors);
}
/**
* Creates a mesh from a glTF. This utility is designed only for simple
* glTFs like those in the data folder.
*
* @param {Object} gltf The glTF.
* @returns {Mesh} The mesh.
*/
static fromGltf(gltf: Gltf): Mesh {
const gltfPrimitive = gltf.meshes[0].primitives[0];
const gltfMaterial = gltf.materials[gltfPrimitive.material];
const material = Material.fromGltf(gltfMaterial);
const indices = getAccessor(gltf, gltf.accessors[gltfPrimitive.indices]);
const positions = getAccessor(
gltf,
gltf.accessors[gltfPrimitive.attributes.POSITION]
);
const normals = getAccessor(
gltf,
gltf.accessors[gltfPrimitive.attributes.NORMAL]
);
const uvs = new Array((positions.length / 3) * 2).fill(0);
const vertexColors = new Array((positions.length / 3) * 4).fill(0);
return new Mesh(
indices,
positions,
normals,
uvs,
vertexColors,
undefined,
material
);
};
}
function getAccessor(gltf, accessor) {
const bufferView = gltf.bufferViews[accessor.bufferView];
const buffer = gltf.buffers[bufferView.buffer];
const byteOffset = accessor.byteOffset + bufferView.byteOffset;
const length = accessor.count * typeToNumberOfComponents(accessor.type);
const uriHeader = 'data:application/octet-stream;base64,';
const base64 = buffer.uri.substring(uriHeader.length);
const data = Buffer.from(base64, 'base64');
let typedArray;
if (accessor.componentType === ComponentDatatype.UNSIGNED_SHORT) {
typedArray = bufferToUint16Array(data, byteOffset, length);
} else if (accessor.componentType === ComponentDatatype.FLOAT) {
typedArray = bufferToFloat32Array(data, byteOffset, length);
}
return Array.prototype.slice.call(typedArray);
} | the_stack |
import { sqlRequest, translateSmartQuery } from '@app/api'
import { IconCommonCopy, IconCommonRefresh, IconCommonSave, IconMiscDragToExplore } from '@app/assets/icons'
import { FormButton } from '@app/components/kit/FormButton'
import { Icon } from '@app/components/kit/Icon'
import { ExploreSaveMenu } from '@app/components/menus/ExploreSaveMenu'
import { AllMetricsSection, DataAssestCardLoader, DataAssetItem } from '@app/components/SideBarDataAssets'
import { SmartQueryConfig } from '@app/components/SideBarSmartQuery'
import { VisualizationConfig } from '@app/components/SideBarVisualization'
import { charts, useChart } from '@app/components/v11n/charts'
import { SideBarTabHeader } from '@app/components/v11n/components/Tab'
import { Config, Data, Type } from '@app/components/v11n/types'
import { MouseSensorOptions } from '@app/context/blockDnd'
import { createEmptyBlock } from '@app/helpers/blockFactory'
import { useBlockSuspense } from '@app/hooks/api'
import { useDimensions } from '@app/hooks/useDimensions'
import { useSideBarRightState } from '@app/hooks/useSideBarQuestionEditor'
import { useWorkspace } from '@app/hooks/useWorkspace'
import { ThemingVariables } from '@app/styles'
import { Dimension, Editor } from '@app/types'
import { blockIdGenerator, TELLERY_MIME_TYPES } from '@app/utils'
import { DndBlocksFragment } from '@app/utils/dnd'
import {
closestCenter,
DndContext,
DragEndEvent,
DragOverlay,
DragStartEvent,
getBoundingClientRect,
MeasuringConfiguration,
MeasuringFrequency,
MeasuringStrategy,
MouseSensor,
useDroppable,
useSensor,
useSensors
} from '@dnd-kit/core'
import { css } from '@emotion/css'
import styled from '@emotion/styled'
import copy from 'copy-to-clipboard'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import PerfectScrollbar from 'react-perfect-scrollbar'
import { useMutation, useQueryClient } from 'react-query'
import { toast } from 'react-toastify'
import { Tab, TabList, TabPanel, useTabState } from 'reakit'
import { Updater, useImmer } from 'use-immer'
const Diagram: React.FC<{
className?: string
data: Data | null
config: Config<Type> | null
queryDimensions: Dimension[]
setVisBlock: Updater<Editor.VisualizationBlock | null>
}> = (props) => {
const chart = useChart(props.config?.type ?? Type.TABLE)
const ref = useRef(null)
const dimensions = useDimensions(ref, 0)
const defaultConfig = useMemo(() => {
// ensure snapshot data is valid
return (
props.config ?? charts[Type.TABLE].initializeConfig(props.data!, { cache: {}, dimensions: props.queryDimensions })
)
}, [props.config, props.data, props.queryDimensions])
const handleConfigChange = useCallback(
(
key1: keyof Config<Type>,
value1: Config<Type>[keyof Config<Type>],
key2: keyof Config<Type>,
value2: Config<Type>[keyof Config<Type>],
key3: keyof Config<Type>,
value3: Config<Type>[keyof Config<Type>]
) => {
props.setVisBlock((draft) => {
if (!draft) return
if (draft.content?.visualization) {
if (key1) {
draft.content.visualization[key1] = value1
}
if (key2) {
draft.content.visualization[key2] = value2
}
if (key3) {
draft.content.visualization[key3] = value3
}
}
})
},
[props]
)
return (
<div
ref={ref}
className={css`
width: 100%;
overflow: hidden;
height: 100%;
`}
>
<chart.Diagram
dimensions={dimensions}
data={props.data!}
config={defaultConfig as never}
onConfigChange={handleConfigChange as any}
/>
</div>
)
}
const DEFAULT_LAYOUT_MEASURING: MeasuringConfiguration = {
droppable: {
measure: getBoundingClientRect,
strategy: MeasuringStrategy.BeforeDragging,
frequency: MeasuringFrequency.Optimized
}
}
const CustomDndContext: React.FC<{ setQueryBuilderId: React.Dispatch<React.SetStateAction<string | null>> }> = ({
children,
setQueryBuilderId
}) => {
const [activeId, setActiveId] = useState<string | null>(null)
const mouseSensor = useSensor(MouseSensor, MouseSensorOptions)
const sensors = useSensors(mouseSensor)
const handleDragEnd = useCallback(
(event: DragEndEvent) => {
const item = event.active.data.current as DndBlocksFragment
setActiveId(null)
if (event.over) {
setQueryBuilderId(item.originalBlockId!)
}
},
[setQueryBuilderId]
)
const handleDragStart = useCallback((event: DragStartEvent) => {
const item = event.active.data.current as DndBlocksFragment
setActiveId(item.originalBlockId)
}, [])
const handleDragCancel = useCallback(() => {
setActiveId(null)
}, [])
return (
<DndContext
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
onDragStart={handleDragStart}
onDragCancel={handleDragCancel}
sensors={sensors}
measuring={DEFAULT_LAYOUT_MEASURING}
>
<DragOverlay dropAnimation={null}>
{activeId ? (
<React.Suspense key={activeId} fallback={<DataAssestCardLoader />}>
<DataAssetItem blockId={activeId} isExpanded={false} />
</React.Suspense>
) : null}
</DragOverlay>
{children}
</DndContext>
)
}
const Droppable: React.FC<{ className: string; style: React.CSSProperties }> = (props) => {
const { isOver, setNodeRef } = useDroppable({
id: 'explore'
})
return (
<div
ref={setNodeRef}
style={{
...props.style,
backgroundColor: isOver ? ThemingVariables.colors.gray[3] : props.style.backgroundColor
}}
className={props.className}
>
{props.children}
</div>
)
}
const ButtonsGroup = styled.div`
display: flex;
padding: 0 32px;
margin: auto;
justify-content: space-around;
> * + * {
margin-left: 11px;
}
`
const PageButton = styled(FormButton)`
display: flex;
align-items: center;
justify-content: center;
max-width: 230px;
> svg {
margin-right: 5px;
}
`
const Page = () => {
const workspace = useWorkspace()
const [queryBuilderId, setQueryBuilderId] = useState<string | null>(null)
const [queryBlock, setQueryBlock] = useImmer<Editor.SmartQueryBlock | null>(null)
const [visBlock, setVisBlock] = useImmer<Editor.VisualizationBlock | null>(null)
const [data, setData] = useState<Data | null>(null)
const [sql, setSql] = useState<string | null>(null)
const queryClient = useQueryClient()
const [autoRefresh, setAutoRefresh] = useState(false)
useEffect(() => {
if (!queryBuilderId) return
translateSmartQuery(
workspace.id,
workspace.preferences?.connectorId!,
queryBuilderId,
queryBlock?.content.metricIds,
queryBlock?.content.dimensions,
queryBlock?.content.filters
)
.then((response) => {
setSql(response.data.sql)
})
.catch(console.error)
}, [queryBlock, queryBuilderId, workspace])
const mutation = useMutation(sqlRequest, {
mutationKey: 'explore'
})
const cancelMutation = useCallback(() => {
const mutations = queryClient
.getMutationCache()
.getAll()
.filter(
(mutation) =>
(mutation.options.mutationKey as string)?.endsWith('explore') && mutation.state.status === 'loading'
)
mutations.forEach((mutation) => {
mutation.cancel()
})
}, [queryClient])
useEffect(() => {
setData(null)
if (queryBuilderId) {
setAutoRefresh(false)
cancelMutation()
const visBlockId = blockIdGenerator()
const newQueryBlock = createEmptyBlock<Editor.SmartQueryBlock>({
type: Editor.BlockType.SmartQuery,
content: {
queryBuilderId: queryBuilderId!,
metricIds: [],
dimensions: [],
title: []
},
parentId: visBlockId
})
setQueryBlock(newQueryBlock)
setVisBlock(
createEmptyBlock<Editor.VisualizationBlock>({
type: Editor.BlockType.Visualization,
content: { queryId: newQueryBlock.id, title: [['smart query from metrics exploration']] },
children: [newQueryBlock.id]
})
)
}
}, [cancelMutation, queryBuilderId, queryClient, setQueryBlock, setVisBlock])
const refresh = useCallback(() => {
if (!sql) {
return
}
cancelMutation()
mutation.mutate(
{
workspaceId: workspace.id,
sql,
connectorId: workspace.preferences.connectorId!,
profile: workspace.preferences.profile!
},
{
onSuccess: (data) => {
setData(data)
}
}
)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sql, workspace.id, workspace.preferences.connectorId, workspace.preferences.profile])
useEffect(() => {
if (autoRefresh) {
refresh()
}
// only refresh when sql changed and auto refresh is true
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sql])
const execute = useCallback(() => {
setAutoRefresh(true)
refresh()
}, [refresh])
const blockFragment = useMemo(() => {
if (!visBlock || !queryBlock) return null
return {
children: [visBlock.id],
data: {
[visBlock.id]: visBlock,
[queryBlock.id]: queryBlock
}
}
}, [queryBlock, visBlock])
const handleCopy = useCallback(() => {
if (!blockFragment) return
copy('tellery', {
debug: true,
onCopy: (clipboardData) => {
const fragment = {
type: TELLERY_MIME_TYPES.BLOCKS,
value: blockFragment
}
;(clipboardData as DataTransfer).setData(fragment.type, JSON.stringify(fragment.value))
}
})
toast.success('Success copied')
}, [blockFragment])
const handleSave = useCallback(() => {}, [])
return (
<CustomDndContext setQueryBuilderId={setQueryBuilderId}>
<div
className={css`
display: flex;
flex-direction: column;
height: 100vh;
width: 100%;
`}
>
<div
className={css`
background: #ffffff;
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.08);
font-family: Helvetica Neue;
font-style: normal;
font-weight: bold;
font-size: 24px;
line-height: 29px;
padding: 23px;
color: #333333;
z-index: 10;
`}
>
Metric explore
</div>
<div
className={css`
display: flex;
overflow: hidden;
`}
>
<AllMetricsSection
className={css`
width: 304px;
flex-shrink: 0;
border-right: solid 1px ${ThemingVariables.colors.gray[1]};
`}
/>
<div
className={css`
flex: 1;
overflow: hidden;
`}
>
<Droppable
className={css`
border-radius: 20px;
margin: 32px;
height: 50vh;
padding: 15px;
overflow: hidden;
border-radius: 20px;
position: relative;
`}
style={{
border: queryBuilderId ? '4px solid #dedede' : '4px dashed #dedede',
backgroundColor: queryBuilderId ? ThemingVariables.colors.gray[4] : 'none'
}}
>
<div
className={css`
width: 100%;
overflow: hidden;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
`}
>
{(!(queryBuilderId && data) || (mutation.isLoading && !data)) && (
<>
<IconMiscDragToExplore />
<div
className={css`
font-family: Helvetica Neue;
font-style: normal;
font-weight: 500;
font-size: 14px;
line-height: 17px;
color: #999999;
margin-top: 15px;
`}
>
{queryBuilderId
? 'Select Measures and Dimensions, click query to see your results'
: 'Drag here to explore'}
</div>
</>
)}
{data && (
<Diagram
config={visBlock?.content?.visualization ?? null}
data={data}
queryDimensions={queryBlock?.content.dimensions ?? []}
setVisBlock={setVisBlock}
/>
)}
</div>
</Droppable>
<ButtonsGroup>
<PageButton
variant={'secondary'}
className={css`
flex: 1;
`}
onClick={mutation.isLoading ? cancelMutation : execute}
>
<Icon
spin={mutation.isLoading}
icon={IconCommonRefresh}
className={css`
margin-right: 5px;
`}
/>
{mutation.isLoading ? 'Cancel' : 'Query'}
</PageButton>
<PageButton
variant={'secondary'}
className={css`
flex: 1;
`}
onClick={handleCopy}
>
<IconCommonCopy />
Copy
</PageButton>
<ExploreSaveMenu
blockFragment={blockFragment}
button={
<PageButton
variant={'secondary'}
className={css`
flex: 1;
`}
onClick={handleSave}
>
<IconCommonSave />
Save
</PageButton>
}
></ExploreSaveMenu>
</ButtonsGroup>
</div>
<div
className={css`
width: 304px;
flex-shrink: 0;
border-left: solid 1px ${ThemingVariables.colors.gray[1]};
`}
>
{queryBlock && visBlock && (
<ExploreSideBarRight
queryBlock={queryBlock}
data={data}
visBlock={visBlock}
setQueryBlock={setQueryBlock}
setVisBlock={setVisBlock}
/>
)}
</div>
</div>
</div>
</CustomDndContext>
)
}
const ExploreSideBarRight: React.FC<{
queryBlock: Editor.SmartQueryBlock
visBlock: Editor.VisualizationBlock
setQueryBlock: Updater<Editor.SmartQueryBlock | null>
data: Data | null
setVisBlock: Updater<Editor.VisualizationBlock | null>
}> = ({ queryBlock, visBlock, setQueryBlock, setVisBlock, data }) => {
const tab = useTabState()
const { t } = useTranslation()
const [sideBarEditorState, setSideBarEditorState] = useSideBarRightState('explore')
const queryBuilderBlock = useBlockSuspense(queryBlock.content.queryBuilderId)
useEffect(() => {
if (sideBarEditorState?.data?.activeTab) {
tab.setSelectedId(sideBarEditorState.data?.activeTab)
}
}, [sideBarEditorState, tab])
const changeTab = useCallback(
(tab: 'Visualization' | 'Query') => {
setSideBarEditorState((value) => {
if (value) {
return { ...value, activeTab: tab }
}
return value
})
},
[setSideBarEditorState]
)
return (
<div
className={css`
height: 100%;
display: flex;
background-color: #fff;
flex-direction: column;
`}
>
<TabList
{...tab}
className={css`
border-bottom: solid 1px ${ThemingVariables.colors.gray[1]};
overflow-x: auto;
white-space: nowrap;
padding-right: 16px;
`}
>
{queryBlock.type === Editor.BlockType.SmartQuery ? (
<Tab
as={SideBarTabHeader}
{...tab}
id="Query"
selected={tab.selectedId === 'Query'}
onClick={() => {
changeTab('Query')
}}
>
{t`Query`}
</Tab>
) : null}
<Tab
as={SideBarTabHeader}
{...tab}
id="Visualization"
selected={tab.selectedId === 'Visualization'}
onClick={() => {
changeTab('Visualization')
}}
>
{t`Visualization`}
</Tab>
</TabList>
<PerfectScrollbar
options={{ suppressScrollX: true }}
className={css`
flex: 1;
`}
>
<TabPanel {...tab}>
<SmartQueryConfig
queryBuilderBlock={queryBuilderBlock}
metricIds={queryBlock.content.metricIds}
dimensions={queryBlock.content.dimensions}
filters={queryBlock.content.filters}
onChange={setQueryBlock as any}
/>
</TabPanel>
<TabPanel {...tab}>
<VisualizationConfig
config={visBlock.content?.visualization}
data={data}
metricIds={queryBlock.content.metricIds}
dimensions={queryBlock.content.dimensions}
onChange={setVisBlock as any}
/>
</TabPanel>
</PerfectScrollbar>
</div>
)
}
export default Page | the_stack |
type Long = protobuf.Long;
// DO NOT EDIT! This is a generated file. Edit the JSDoc in src/*.js instead and run 'npm run types'.
/** Namespace pb_test. */
declare namespace pb_test {
/** Properties of a HeartBeat. */
interface IHeartBeat {
}
/** Represents a HeartBeat. */
class HeartBeat implements IHeartBeat {
/**
* Constructs a new HeartBeat.
* @param [properties] Properties to set
*/
constructor(properties?: pb_test.IHeartBeat);
/**
* Creates a new HeartBeat instance using the specified properties.
* @param [properties] Properties to set
* @returns HeartBeat instance
*/
public static create(properties?: pb_test.IHeartBeat): pb_test.HeartBeat;
/**
* Encodes the specified HeartBeat message. Does not implicitly {@link pb_test.HeartBeat.verify|verify} messages.
* @param message HeartBeat message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: pb_test.IHeartBeat, writer?: protobuf.Writer): protobuf.Writer;
/**
* Decodes a HeartBeat message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns HeartBeat
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.HeartBeat;
/**
* Verifies a HeartBeat message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
}
/** Properties of a Kick. */
interface IKick {
}
/** Represents a Kick. */
class Kick implements IKick {
/**
* Constructs a new Kick.
* @param [properties] Properties to set
*/
constructor(properties?: pb_test.IKick);
/**
* Creates a new Kick instance using the specified properties.
* @param [properties] Properties to set
* @returns Kick instance
*/
public static create(properties?: pb_test.IKick): pb_test.Kick;
/**
* Encodes the specified Kick message. Does not implicitly {@link pb_test.Kick.verify|verify} messages.
* @param message Kick message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: pb_test.IKick, writer?: protobuf.Writer): protobuf.Writer;
/**
* Decodes a Kick message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Kick
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Kick;
/**
* Verifies a Kick message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
}
/** Properties of a User. */
interface IUser {
/** User uid */
uid: number;
/** User name */
name: string;
}
/** Represents a User. */
class User implements IUser {
/**
* Constructs a new User.
* @param [properties] Properties to set
*/
constructor(properties?: pb_test.IUser);
/** User uid. */
public uid: number;
/** User name. */
public name: string;
/**
* Creates a new User instance using the specified properties.
* @param [properties] Properties to set
* @returns User instance
*/
public static create(properties?: pb_test.IUser): pb_test.User;
/**
* Encodes the specified User message. Does not implicitly {@link pb_test.User.verify|verify} messages.
* @param message User message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: pb_test.IUser, writer?: protobuf.Writer): protobuf.Writer;
/**
* Decodes a User message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns User
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.User;
/**
* Verifies a User message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
}
/** Properties of a Cs_Login. */
interface ICs_Login {
/** Cs_Login name */
name: string;
}
/** Represents a Cs_Login. */
class Cs_Login implements ICs_Login {
/**
* Constructs a new Cs_Login.
* @param [properties] Properties to set
*/
constructor(properties?: pb_test.ICs_Login);
/** Cs_Login name. */
public name: string;
/**
* Creates a new Cs_Login instance using the specified properties.
* @param [properties] Properties to set
* @returns Cs_Login instance
*/
public static create(properties?: pb_test.ICs_Login): pb_test.Cs_Login;
/**
* Encodes the specified Cs_Login message. Does not implicitly {@link pb_test.Cs_Login.verify|verify} messages.
* @param message Cs_Login message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: pb_test.ICs_Login, writer?: protobuf.Writer): protobuf.Writer;
/**
* Decodes a Cs_Login message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Cs_Login
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Cs_Login;
/**
* Verifies a Cs_Login message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
}
/** Properties of a Sc_Login. */
interface ISc_Login {
/** Sc_Login uid */
uid: number;
/** Sc_Login users */
users?: (pb_test.IUser[]|null);
}
/** Represents a Sc_Login. */
class Sc_Login implements ISc_Login {
/**
* Constructs a new Sc_Login.
* @param [properties] Properties to set
*/
constructor(properties?: pb_test.ISc_Login);
/** Sc_Login uid. */
public uid: number;
/** Sc_Login users. */
public users: pb_test.IUser[];
/**
* Creates a new Sc_Login instance using the specified properties.
* @param [properties] Properties to set
* @returns Sc_Login instance
*/
public static create(properties?: pb_test.ISc_Login): pb_test.Sc_Login;
/**
* Encodes the specified Sc_Login message. Does not implicitly {@link pb_test.Sc_Login.verify|verify} messages.
* @param message Sc_Login message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: pb_test.ISc_Login, writer?: protobuf.Writer): protobuf.Writer;
/**
* Decodes a Sc_Login message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Sc_Login
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Sc_Login;
/**
* Verifies a Sc_Login message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
}
/** Properties of a Sc_userEnter. */
interface ISc_userEnter {
/** Sc_userEnter user */
user: pb_test.IUser;
}
/** Represents a Sc_userEnter. */
class Sc_userEnter implements ISc_userEnter {
/**
* Constructs a new Sc_userEnter.
* @param [properties] Properties to set
*/
constructor(properties?: pb_test.ISc_userEnter);
/** Sc_userEnter user. */
public user: pb_test.IUser;
/**
* Creates a new Sc_userEnter instance using the specified properties.
* @param [properties] Properties to set
* @returns Sc_userEnter instance
*/
public static create(properties?: pb_test.ISc_userEnter): pb_test.Sc_userEnter;
/**
* Encodes the specified Sc_userEnter message. Does not implicitly {@link pb_test.Sc_userEnter.verify|verify} messages.
* @param message Sc_userEnter message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: pb_test.ISc_userEnter, writer?: protobuf.Writer): protobuf.Writer;
/**
* Decodes a Sc_userEnter message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Sc_userEnter
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Sc_userEnter;
/**
* Verifies a Sc_userEnter message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
}
/** Properties of a Sc_userLeave. */
interface ISc_userLeave {
/** Sc_userLeave uid */
uid: number;
}
/** Represents a Sc_userLeave. */
class Sc_userLeave implements ISc_userLeave {
/**
* Constructs a new Sc_userLeave.
* @param [properties] Properties to set
*/
constructor(properties?: pb_test.ISc_userLeave);
/** Sc_userLeave uid. */
public uid: number;
/**
* Creates a new Sc_userLeave instance using the specified properties.
* @param [properties] Properties to set
* @returns Sc_userLeave instance
*/
public static create(properties?: pb_test.ISc_userLeave): pb_test.Sc_userLeave;
/**
* Encodes the specified Sc_userLeave message. Does not implicitly {@link pb_test.Sc_userLeave.verify|verify} messages.
* @param message Sc_userLeave message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: pb_test.ISc_userLeave, writer?: protobuf.Writer): protobuf.Writer;
/**
* Decodes a Sc_userLeave message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Sc_userLeave
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Sc_userLeave;
/**
* Verifies a Sc_userLeave message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
}
/** Properties of a ChatMsg. */
interface IChatMsg {
/** ChatMsg uid */
uid: number;
/** ChatMsg msg */
msg: string;
}
/** Represents a ChatMsg. */
class ChatMsg implements IChatMsg {
/**
* Constructs a new ChatMsg.
* @param [properties] Properties to set
*/
constructor(properties?: pb_test.IChatMsg);
/** ChatMsg uid. */
public uid: number;
/** ChatMsg msg. */
public msg: string;
/**
* Creates a new ChatMsg instance using the specified properties.
* @param [properties] Properties to set
* @returns ChatMsg instance
*/
public static create(properties?: pb_test.IChatMsg): pb_test.ChatMsg;
/**
* Encodes the specified ChatMsg message. Does not implicitly {@link pb_test.ChatMsg.verify|verify} messages.
* @param message ChatMsg message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: pb_test.IChatMsg, writer?: protobuf.Writer): protobuf.Writer;
/**
* Decodes a ChatMsg message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ChatMsg
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.ChatMsg;
/**
* Verifies a ChatMsg message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
}
/** Properties of a Cs_SendMsg. */
interface ICs_SendMsg {
/** Cs_SendMsg msg */
msg: pb_test.IChatMsg;
}
/** Represents a Cs_SendMsg. */
class Cs_SendMsg implements ICs_SendMsg {
/**
* Constructs a new Cs_SendMsg.
* @param [properties] Properties to set
*/
constructor(properties?: pb_test.ICs_SendMsg);
/** Cs_SendMsg msg. */
public msg: pb_test.IChatMsg;
/**
* Creates a new Cs_SendMsg instance using the specified properties.
* @param [properties] Properties to set
* @returns Cs_SendMsg instance
*/
public static create(properties?: pb_test.ICs_SendMsg): pb_test.Cs_SendMsg;
/**
* Encodes the specified Cs_SendMsg message. Does not implicitly {@link pb_test.Cs_SendMsg.verify|verify} messages.
* @param message Cs_SendMsg message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: pb_test.ICs_SendMsg, writer?: protobuf.Writer): protobuf.Writer;
/**
* Decodes a Cs_SendMsg message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Cs_SendMsg
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Cs_SendMsg;
/**
* Verifies a Cs_SendMsg message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
}
/** Properties of a Sc_Msg. */
interface ISc_Msg {
/** Sc_Msg msg */
msg: pb_test.IChatMsg;
}
/** Represents a Sc_Msg. */
class Sc_Msg implements ISc_Msg {
/**
* Constructs a new Sc_Msg.
* @param [properties] Properties to set
*/
constructor(properties?: pb_test.ISc_Msg);
/** Sc_Msg msg. */
public msg: pb_test.IChatMsg;
/**
* Creates a new Sc_Msg instance using the specified properties.
* @param [properties] Properties to set
* @returns Sc_Msg instance
*/
public static create(properties?: pb_test.ISc_Msg): pb_test.Sc_Msg;
/**
* Encodes the specified Sc_Msg message. Does not implicitly {@link pb_test.Sc_Msg.verify|verify} messages.
* @param message Sc_Msg message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: pb_test.ISc_Msg, writer?: protobuf.Writer): protobuf.Writer;
/**
* Decodes a Sc_Msg message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Sc_Msg
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: (protobuf.Reader|Uint8Array), length?: number): pb_test.Sc_Msg;
/**
* Verifies a Sc_Msg message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
}
} | the_stack |
import React, { useState, useEffect } from 'react';
import { PrimaryButton, DefaultButton, Stack, TextField, Dropdown, Spinner, IconButton, Pivot, PivotItem, IColumn, DetailsList, DetailsListLayoutMode, CheckboxVisibility, Text, SelectionMode } from '@fluentui/react';
import { AlternateIdentity, User, UserRole } from 'teamcloud';
import { GraphUser } from '../model'
import { api } from '../API'
import { UserPersona, Lightbox } from '.';
import { prettyPrintCamlCaseString } from '../Utils';
import { useProjects } from '../hooks';
import { useQueryClient } from 'react-query';
export interface IUserFormProps {
me: boolean;
user?: User;
graphUser?: GraphUser;
panelIsOpen: boolean;
onFormClose: () => void;
}
export const UserForm: React.FC<IUserFormProps> = (props) => {
interface AlternateIdentityItem {
key: string
title: string
identity: AlternateIdentity
}
interface PropertyItem {
key: string
value: string
}
interface MembershipItem {
project: string
role: string
}
const detailsListTextStyle: React.CSSProperties = {
verticalAlign: 'middle',
lineHeight: '30px',
fontSize: '14px'
}
const queryClient = useQueryClient();
const { data: projects } = useProjects();
const [newPropertyKey, setNewPropertyKey] = useState<string>();
const [newPropertyAddEnabled, setNewPropertyAddEnabled] = useState<boolean>(false);
const [formEnabled, setFormEnabled] = useState<boolean>(true);
const [formUser, setFormUser] = useState<User>();
const [pivotKey, setPivotKey] = useState<string>('Details');
const [errorMessage, setErrorMessage] = useState<string>();
useEffect(() => {
if (props.user) {
// console.log("Updating form user: " + JSON.stringify(props.user));
setFormUser({ ...props.user });
} else {
setFormUser(undefined);
}
}, [props.user]);
useEffect(() => {
if (formUser && formUser.properties) {
var sanitized: string = (newPropertyKey ?? '').trim();
var enabled: boolean = (sanitized.length > 0 && (!Object.keys(formUser.properties).includes(sanitized) ?? false));
setNewPropertyAddEnabled(enabled);
} else {
setNewPropertyAddEnabled(false);
}
}, [formUser, newPropertyKey])
const _submitForm = async () => {
if (formUser) {
console.log(`Submitting: ${JSON.stringify(formUser)}`);
try {
setFormEnabled(false);
await api.updateOrganizationUserMe(formUser!.organization, {
body: formUser,
onResponse: (raw, flat) => {
if (raw.status >= 400)
throw new Error(raw.parsedBody || raw.bodyAsText || `Error: ${raw.status}`)
}
});
queryClient.invalidateQueries(['org', formUser!.organization, 'user', 'me']);
_resetAndCloseForm();
} catch (error) {
setErrorMessage(`${error}`);
} finally {
setFormEnabled(true);
}
} else {
_resetAndCloseForm();
}
};
const _resetAndCloseForm = () => {
setFormEnabled(true);
setFormUser(undefined);
props.onFormClose();
};
const _onRoleChange = (newRole?: UserRole) => {
if (formUser && newRole)
formUser.role = newRole ?? "None";
}
const _onPropertyAdd = (newValue?: string) => {
if (formUser?.properties && newValue) {
let sanitized = newValue.trim();
if (!Object.keys(formUser.properties).includes(sanitized)) {
formUser.properties[sanitized] = '';
setNewPropertyKey('');
}
}
}
const _onPropertyUpdate = (key: string, newValue?: string) => {
if (formUser?.properties) {
let sanitized = key.trim();
if (Object.keys(formUser.properties).includes(sanitized)) {
formUser.properties[sanitized] = newValue || '';
setFormUser({ ...formUser });
}
}
}
const _onPropertyDelete = (key: string) => {
if (formUser?.properties) {
let sanitized = key.trim();
if (Object.keys(formUser.properties).includes(sanitized)) {
delete formUser.properties[sanitized];
setFormUser({ ...formUser });
}
}
}
const _renderPropertyKeyColumn = (item?: PropertyItem, index?: number, column?: IColumn) => {
if (!item) return undefined;
return (<Stack><Text style={detailsListTextStyle}>{item.key}</Text></Stack>);
}
const _renderPropertyValueColumn = (item?: PropertyItem, index?: number, column?: IColumn) => {
if (!item) return undefined;
return (
<Stack horizontal>
<TextField
value={item.value}
styles={{ root: { width: '100%' } }}
onChange={(_ev, val) => _onPropertyUpdate(item.key, val)} />
<IconButton
iconProps={{ iconName: 'Delete' }}
style={{ backgroundColor: 'transparent' }}
onClick={() => _onPropertyDelete(item.key)} />
</Stack>);
}
const propertiesColums: IColumn[] = [
{
key: 'key', name: 'Key',
minWidth: 100, maxWidth: 200, isResizable: false,
onRender: _renderPropertyKeyColumn
},
{
key: 'value', name: 'Value',
minWidth: 400,
onRender: _renderPropertyValueColumn
}
];
const _renderPropertiesPivot = () => {
let items: PropertyItem[] = [];
if (formUser?.properties) {
for (const key in formUser.properties) {
items.push({
key: key,
value: formUser.properties[key] ?? ''
} as PropertyItem);
}
}
return (
<Stack>
<DetailsList
columns={propertiesColums}
items={items}
layoutMode={DetailsListLayoutMode.justified}
checkboxVisibility={CheckboxVisibility.hidden}
selectionMode={SelectionMode.none}
selectionPreservedOnEmptyClick
/>
<Stack horizontal style={{ marginTop: '10px' }}>
<TextField
value={newPropertyKey}
placeholder='Create a new property'
onKeyDown={(_ev) => { if (_ev.keyCode === 13) _onPropertyAdd(newPropertyKey) }}
onChange={(_ev, val) => setNewPropertyKey(val)} />
<IconButton
iconProps={{ iconName: 'AddTo' }}
disabled={!newPropertyAddEnabled}
style={{ backgroundColor: 'transparent' }}
onClick={() => _onPropertyAdd(newPropertyKey)} />
</Stack>
</Stack>)
};
const _renderDetailsPivot = () => {
const roleControl = props.me
? (<TextField
readOnly
label='Role'
value={formUser?.role} />)
: (<Dropdown
required
label='Role'
selectedKey={formUser?.role ?? undefined}
options={['Owner', 'Admin', 'Member', 'None'].map(r => ({ key: r, text: r, data: r }))}
onChange={(_ev, val) => _onRoleChange(val?.key ? val.key as UserRole : undefined)} />);
return formUser ? (
<Stack tokens={{ childrenGap: '12px' }}>
<Stack.Item>
<TextField
readOnly
label='Id'
value={props.user?.id} />
</Stack.Item>
<Stack.Item>
<TextField
readOnly
label='Login'
value={props.user?.loginName ?? undefined} />
</Stack.Item>
<Stack.Item>
<TextField
readOnly
label='E-Mail'
value={props.user?.mailAddress ?? undefined} />
</Stack.Item>
<Stack.Item>
{roleControl}
</Stack.Item>
</Stack>
) : (<></>);
};
const _renderMembershipValueColumn = (item?: MembershipItem, index?: number, column?: IColumn) => {
if (item && column) {
let property: string = column.fieldName ?? column.key ?? ''
return <Text style={detailsListTextStyle}>{(item as any)[property]}</Text>
}
return <></>
};
const membershipColums: IColumn[] = [
{
key: 'project', name: 'Project', fieldName: 'project',
minWidth: 100, maxWidth: 200, isResizable: false,
onRender: _renderMembershipValueColumn
},
{
key: 'role', name: 'Role', fieldName: 'role',
minWidth: 400,
onRender: _renderMembershipValueColumn
}
];
const _renderMembershipPivot = () => {
let items: MembershipItem[] = [];
if (projects && formUser?.projectMemberships) {
items = formUser.projectMemberships.map((membership) => ({
project: projects.find(p => p.id === membership.projectId)?.displayName ?? membership.projectId,
role: membership.role
} as MembershipItem));
}
return (
<DetailsList
columns={membershipColums}
items={items}
layoutMode={DetailsListLayoutMode.justified}
checkboxVisibility={CheckboxVisibility.hidden}
selectionPreservedOnEmptyClick />
)
};
const _renderAlternateIdentityServiceColumn = (item?: AlternateIdentityItem, index?: number, column?: IColumn) => {
if (!item) return undefined;
return <Stack verticalAlign='center'>
<Text style={detailsListTextStyle}>{item.title}</Text>
</Stack>
};
const _onAlternateIdentityLoginChange = (key: string, newValue?: string) => {
if (formUser?.alternateIdentities && Object.keys(formUser.alternateIdentities).includes(key)) {
let identity = (formUser.alternateIdentities as any)[key] as AlternateIdentity;
if (identity) {
identity.login = newValue || '';
setFormUser({ ...formUser });
}
}
}
const _renderAlternateIdentityLoginColumn = (item?: AlternateIdentityItem, index?: number, column?: IColumn) => {
if (!item || !item.identity) return undefined
return <TextField
value={item.identity.login ?? undefined}
onChange={(_ev, val) => _onAlternateIdentityLoginChange(item.key, val)} />;
};
const alternateIdentitiesColums: IColumn[] = [
{
key: 'title', name: 'Service',
minWidth: 100, maxWidth: 200, isResizable: false,
onRender: _renderAlternateIdentityServiceColumn
},
{
key: 'login', name: 'Login',
minWidth: 400,
onRender: _renderAlternateIdentityLoginColumn
}
];
const _renderAlternateIdentitiesPivot = () => {
let items: AlternateIdentityItem[] = [];
if (formUser?.alternateIdentities) {
items = Object.getOwnPropertyNames(formUser.alternateIdentities).map((name) => ({
key: name,
title: prettyPrintCamlCaseString(name),
identity: (formUser.alternateIdentities as any)[name]
}));
}
return (
<DetailsList
columns={alternateIdentitiesColums}
items={items}
layoutMode={DetailsListLayoutMode.justified}
checkboxVisibility={CheckboxVisibility.hidden}
selectionPreservedOnEmptyClick />
)
};
const _renderLightboxHeader = (): JSX.Element => {
return (<UserPersona principal={props.graphUser} large />);
};
const _renderLightboxFooter = (): JSX.Element => {
return (
<>
<Stack.Item><Text style={detailsListTextStyle}>{errorMessage}</Text></Stack.Item>
<Stack.Item><Spinner styles={{ root: { visibility: formEnabled ? 'hidden' : 'visible' } }} /></Stack.Item>
<PrimaryButton text='Ok' disabled={!formEnabled} onClick={() => _submitForm()} />
<DefaultButton text='Cancel' disabled={!formEnabled} onClick={() => _resetAndCloseForm()} />
</>
);
}
return (
<Lightbox
isOpen={props.panelIsOpen}
onDismiss={() => _resetAndCloseForm()}
onRenderHeader={_renderLightboxHeader}
onRenderFooter={_renderLightboxFooter}>
<Pivot selectedKey={pivotKey} onLinkClick={(i, e) => setPivotKey(i?.props.itemKey ?? 'Details')} styles={{ root: { height: '100%', marginBottom: '12px' } }}>
<PivotItem headerText='Details' itemKey='Details'>
{_renderDetailsPivot()}
</PivotItem>
<PivotItem headerText='Memberships' itemKey='Memberships'>
{_renderMembershipPivot()}
</PivotItem>
<PivotItem headerText='Properties' itemKey='Properties'>
{_renderPropertiesPivot()}
</PivotItem>
<PivotItem headerText='Alternate Identities' itemKey='AlternateIdentities'>
{_renderAlternateIdentitiesPivot()}
</PivotItem>
</Pivot>
</Lightbox>
);
} | the_stack |
class eKit {
/**
* 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
* @param {string} name
* @param {Object} settings?
*/
public static async createBitmapByPath(path: string, settings?: Object) {
let result = new egret.Bitmap();
let texture: egret.Texture = null;
await this.createTextureByPath(path).then((res: egret.Texture) => {
texture = res;
}).catch(err => { console.warn(err) });
result.texture = texture;
if (settings) {
for (let key in settings) {
result[key] = settings[key];
}
}
return result;
}
private static async createTextureByPath(path: string) {
return new Promise((resolve, reject) => {
let imgLoader = new egret.ImageLoader();
imgLoader.addEventListener(egret.Event.COMPLETE, (evt: egret.Event) => {
let imageLoader = <egret.ImageLoader>evt.currentTarget;
let textTure = new egret.Texture();
textTure._setBitmapData(imageLoader.data);
resolve(textTure);
}, this)
imgLoader.load(path);
})
}
/**
* 根据text创建TextField对象
* @param {string} text
* @param {Object} settings?
*/
public static createText(text: string, settings?: Object): egret.TextField {
let result = new egret.TextField();
result.text = text;
if (settings) {
for (let key in settings) {
result[key] = settings[key];
}
}
return result;
}
/**
* 根据参数绘制直线段
* @param {Array<any>} points
* @param {{beginFill?:{color:number} param
* @param {number}} alpha
* @param {{thickness?:number} lineStyle?
* @param {number} color?
* @param {number} alpha?
* @param {boolean} pixelHinting?
* @param {string} scaleMode?
* @param {string} caps?
* @param {string} joints?
* @param {number}}} miterLimit?
* @param {Object} settings?
* @returns egret
*/
public static createLine(points: Array<any>, param: { beginFill?: { color: number, alpha: number }, lineStyle?: { thickness?: number, color?: number, alpha?: number, pixelHinting?: boolean, scaleMode?: string, caps?: string, joints?: string, miterLimit?: number } }, settings?: Object): egret.Shape {
let shp = new egret.Shape();
if (param.beginFill) {
shp.graphics.beginFill(param.beginFill.color, param.beginFill.alpha);
}
if (param.lineStyle) {
shp.graphics.lineStyle(param.lineStyle.thickness, param.lineStyle.color, param.lineStyle.alpha, param.lineStyle.pixelHinting, param.lineStyle.scaleMode, param.lineStyle.caps, param.lineStyle.joints, param
.lineStyle.miterLimit);
}
shp.graphics.moveTo(points[0][0], points[0][1]);
points.map((point, index) => {
index > 0 && shp.graphics.lineTo(points[index][0], points[index][1]);
});
shp.graphics.endFill();
if (settings) {
for (let key in settings) {
shp[key] = settings[key];
}
}
return shp;
}
/**
* 根据参数绘制矩形
* @param {Array<any>} points
* @param {{beginFill?:{color:number} param
* @param {number}} alpha
* @param {{thickness?:number} lineStyle?
* @param {number} color?
* @param {number} alpha?
* @param {boolean} pixelHinting?
* @param {string} scaleMode?
* @param {string} caps?
* @param {string} joints?
* @param {number}}} miterLimit?
* @param {Object} settings?
* @returns egret
*/
public static createRect(points: Array<any>, param: { beginFill?: { color: number, alpha: number }, lineStyle?: { thickness?: number, color?: number, alpha?: number, pixelHinting?: boolean, scaleMode?: string, caps?: string, joints?: string, miterLimit?: number } }, settings?: Object): egret.Shape {
let shp = new egret.Shape();
if (param.beginFill) {
shp.graphics.beginFill(param.beginFill.color, param.beginFill.alpha);
}
if (param.lineStyle) {
shp.graphics.lineStyle(param.lineStyle.thickness, param.lineStyle.color, param.lineStyle.alpha, param.lineStyle.pixelHinting, param.lineStyle.scaleMode, param.lineStyle.caps, param.lineStyle.joints, param
.lineStyle.miterLimit);
}
shp.graphics.drawRect(points[0], points[1], points[2], points[3]);
if (settings) {
for (let key in settings) {
shp[key] = settings[key];
}
}
return shp;
}
/**
* 根据参数绘制圆形
* @param {Array<any>} points
* @param {{beginFill?:{color:number} param
* @param {number}} alpha
* @param {{thickness?:number} lineStyle?
* @param {number} color?
* @param {number} alpha?
* @param {boolean} pixelHinting?
* @param {string} scaleMode?
* @param {string} caps?
* @param {string} joints?
* @param {number}}} miterLimit?
* @param {Object} settings?
* @returns egret
*/
public static createCircle(points: Array<any>, param: { beginFill?: { color: number, alpha: number }, lineStyle?: { thickness?: number, color?: number, alpha?: number, pixelHinting?: boolean, scaleMode?: string, caps?: string, joints?: string, miterLimit?: number } }, settings?: Object): egret.Shape {
let shp = new egret.Shape();
if (param.beginFill) {
shp.graphics.beginFill(param.beginFill.color, param.beginFill.alpha);
}
if (param.lineStyle) {
shp.graphics.lineStyle(param.lineStyle.thickness, param.lineStyle.color, param.lineStyle.alpha, param.lineStyle.pixelHinting, param.lineStyle.scaleMode, param.lineStyle.caps, param.lineStyle.joints, param
.lineStyle.miterLimit);
}
shp.graphics.drawCircle(points[0], points[1], points[2]);
if (settings) {
for (let key in settings) {
shp[key] = settings[key];
}
}
return shp;
}
/**
* 根据参数绘制圆弧路径
* @param {Array<any>} points
* @param {{beginFill?:{color:number} param
* @param {number}} alpha
* @param {{thickness?:number} lineStyle?
* @param {number} color?
* @param {number} alpha?
* @param {boolean} pixelHinting?
* @param {string} scaleMode?
* @param {string} caps?
* @param {string} joints?
* @param {number}}} miterLimit?
* @param {Object} settings?
* @returns egret
*/
public static createArc(points: Array<any>, param: { beginFill?: { color: number, alpha: number }, lineStyle?: { thickness?: number, color?: number, alpha?: number, pixelHinting?: boolean, scaleMode?: string, caps?: string, joints?: string, miterLimit?: number } }, settings?: Object): egret.Shape {
let shp = new egret.Shape();
if (param.beginFill) {
shp.graphics.beginFill(param.beginFill.color, param.beginFill.alpha);
}
if (param.lineStyle) {
shp.graphics.lineStyle(param.lineStyle.thickness, param.lineStyle.color, param.lineStyle.alpha, param.lineStyle.pixelHinting, param.lineStyle.scaleMode, param.lineStyle.caps, param.lineStyle.joints, param
.lineStyle.miterLimit);
}
shp.graphics.drawArc(points[0], points[1], points[2], points[3], points[4], points[5]);
if (settings) {
for (let key in settings) {
shp[key] = settings[key];
}
}
return shp;
}
/**
* 根据参数绘制圆角矩形
* @param {Array<any>} points
* @param {{beginFill?:{color:number} param
* @param {number}} alpha
* @param {{thickness?:number} lineStyle?
* @param {number} color?
* @param {number} alpha?
* @param {boolean} pixelHinting?
* @param {string} scaleMode?
* @param {string} caps?
* @param {string} joints?
* @param {number}}} miterLimit?
* @param {Object} settings?
* @returns egret
*/
public static createRoundRect(points: Array<any>, param: { beginFill?: { color: number, alpha: number }, lineStyle?: { thickness?: number, color?: number, alpha?: number, pixelHinting?: boolean, scaleMode?: string, caps?: string, joints?: string, miterLimit?: number } }, settings?: Object): egret.Shape {
let shp = new egret.Shape();
if (param.beginFill) {
shp.graphics.beginFill(param.beginFill.color, param.beginFill.alpha);
}
if (param.lineStyle) {
shp.graphics.lineStyle(param.lineStyle.thickness, param.lineStyle.color, param.lineStyle.alpha, param.lineStyle.pixelHinting, param.lineStyle.scaleMode, param.lineStyle.caps, param.lineStyle.joints, param
.lineStyle.miterLimit);
}
shp.graphics.drawArc(points[0], points[1], points[2], points[3], points[4], points[5]);
if (settings) {
for (let key in settings) {
shp[key] = settings[key];
}
}
return shp;
}
/**
* 传入一个DisplayObject,将其从其父元素上移除
* @param {egret.DisplayObject} children
*/
public static removeChild(children: egret.DisplayObject) {
if (children.parent) {
children.parent.removeChild(children);
}
}
/**
* 清空显示容器内显示元素,可输入start防止索引号之前的元素被清空
* @param {egret.DisplayObjectContainer} displayObjectContainer
* @param {number} start?
*/
public static clearView(displayObjectContainer: egret.DisplayObjectContainer, start?: number) {
isNaN(start) && (start = -1);
while (displayObjectContainer.$children.length > start + 1) {
displayObjectContainer.removeChildAt(start + 1);
}
return true;
}
} | the_stack |
import {IconType, DocumentedType, UMLClassMemberVisibility, UMLClassMemberLifetime} from "../../common/types";
import {Icon} from "./icon";
/**
* This maps into the iconTypes.svg [x,y]
*
* (0,0)-------x
* |
* |
* y
*
*/
const iconLocations = {
[IconType.Global]: { x: 10, y: 0 },
[IconType.Namespace]: { x: 0, y: 6 },
[IconType.Variable]: { x: 0, y: 1 },
[IconType.Function]: { x: 8, y: 4 },
[IconType.FunctionGeneric]: { x: 8, y: 5 },
[IconType.Enum]: { x: 0, y: 7 },
[IconType.EnumMember]: { x: 0, y: 8 },
[IconType.Interface]: { x: 0, y: 4 },
[IconType.InterfaceGeneric]: { x: 0, y: 5 },
[IconType.InterfaceConstructor]: { x: 12, y: 6 },
[IconType.InterfaceProperty]: { x: 12, y: 0 },
[IconType.InterfaceMethod]: { x: 12, y: 4 },
[IconType.InterfaceMethodGeneric]: { x: 12, y: 5 },
[IconType.InterfaceIndexSignature]: { x: 12, y: 7 },
[IconType.Class]: { x: 0, y: 2 },
[IconType.ClassGeneric]: { x: 0, y: 3 },
[IconType.ClassConstructor]: { x: 3, y: 6 },
[IconType.ClassProperty]: { x: 3, y: 0 },
[IconType.ClassMethod]: { x: 3, y: 4 },
[IconType.ClassMethodGeneric]: { x: 3, y: 5 },
[IconType.ClassIndexSignature]: { x: 3, y: 7 },
}
const _typeIconLocations: { [key: number]: { x: number, y: number } } = iconLocations;
import * as ui from "../ui";
import * as React from "react";
import * as pure from "../../common/pure";
import * as csx from '../base/csx';
import * as styles from "../styles/styles";
interface Props {
iconType: IconType
}
interface State {
}
namespace TypeIconStyles {
export const spriteSize = 17; // px
/** We want to eat a bit of the icon otherwise we get neighbours at certain scales */
export const iconClipWidth = 1;
export const root = {
width: `${spriteSize - iconClipWidth}px`,
height: `${spriteSize}px`,
display: 'inline-block',
}
}
/**
* Draws the icon for a type
*/
export class TypeIcon extends ui.BaseComponent<Props, State>{
shouldComponentUpdate() {
return pure.shouldComponentUpdate.apply(this, arguments);
}
render() {
const imageLocation = iconLocations[this.props.iconType];
const left = imageLocation.x * -TypeIconStyles.spriteSize - TypeIconStyles.iconClipWidth;
const top = imageLocation.y * -TypeIconStyles.spriteSize;
const backgroundImage = 'url(assets/typeIcons.svg)';
const backgroundPosition = `${left}px ${top}px`;
const style = csx.extend(TypeIconStyles.root, { backgroundImage, backgroundPosition });
return <div style={style}></div>;
}
}
/**
* Draws an icon for `private` visibility indication
*/
class VisibilityIndicator extends ui.BaseComponent<{ visibility: UMLClassMemberVisibility }, State>{
shouldComponentUpdate() {
return pure.shouldComponentUpdate.apply(this, arguments);
}
render() {
// Maybe add others if needed. I doubt it though.
const classIconColorTheme = "#4DA6FF";
if (this.props.visibility === UMLClassMemberVisibility.Public)
return <span></span>;
if (this.props.visibility === UMLClassMemberVisibility.Private)
return <Icon name={"lock"} style={{ color: classIconColorTheme }}/>;
else
return <Icon name={"shield"} style={{ color: classIconColorTheme }}/>;
}
}
/**
* Draws an icon for `override` visibility indication
*/
class OverrideIndicator extends ui.BaseComponent<{}, State>{
shouldComponentUpdate() {
return pure.shouldComponentUpdate.apply(this, arguments);
}
render() {
// Maybe add others if needed. I doubt it though.
const classIconColorTheme = "#4DA6FF";
return <Icon name={"arrow-circle-up"} style={{ color: classIconColorTheme }}/>;
}
}
/**
* Draws an icon for `static` indication
*/
class LifetimeIndicator extends React.PureComponent<{ lifetime: UMLClassMemberLifetime }, State>{
render() {
// Maybe add others if needed. I doubt it though.
const classIconColorTheme = "#4DA6FF";
if (this.props.lifetime === UMLClassMemberLifetime.Instance)
return <span></span>;
else
return <Icon name={"bullhorn"} style={{ color: classIconColorTheme }}/>;
}
}
/**
* Draws the icon followed by name
*/
namespace DocumentedTypeHeaderStyles {
export const root = csx.extend(
{
fontWeight: 'bold',
fontSize: '.6rem',
color: styles.textColor,
// Center
display: 'flex',
alignItems: 'center',
whiteSpace: 'pre'
});
}
interface DocumentedTypeHeaderProps {
name: string, icon: IconType,
visibility?: UMLClassMemberVisibility,
lifetime?: UMLClassMemberLifetime,
override?: boolean,
}
export class DocumentedTypeHeader extends React.PureComponent<DocumentedTypeHeaderProps, State>{
render() {
const hasLifetime = (this.props.lifetime != null) && this.props.lifetime !== UMLClassMemberLifetime.Instance;
const hasVisibility = (this.props.visibility != null) && this.props.visibility !== UMLClassMemberVisibility.Public;
return <div style={DocumentedTypeHeaderStyles.root}>
<TypeIcon iconType={this.props.icon}/>
{hasLifetime && <LifetimeIndicator lifetime={this.props.lifetime}/>}
{hasLifetime && "\u00a0"}
{hasVisibility && <VisibilityIndicator visibility={this.props.visibility}/>}
{hasVisibility && "\u00a0"}
{" " + this.props.name}
{this.props.override && "\u00a0"}
{this.props.override && <OverrideIndicator/>}
</div>;
}
}
export const SectionHeader = (props:{text:string}) => {
return <div
style={{ fontSize: '1rem', fontWeight: 'bold'}}>
{props.text}
</div>
}
/**
* Draws the legend
*/
namespace TypeIconLegendStyles {
export const root = csx.extend(
{
fontWeight: 'bold',
fontSize: '.6rem',
color: styles.textColor,
});
export const legendColumnContainer = csx.horizontal;
export const legendColumn = csx.extend(
csx.vertical,
{
padding: '10px'
});
}
export class TypeIconLegend extends React.PureComponent<{}, {}>{
render() {
return (
<div style={TypeIconLegendStyles.root}>
<div style={{paddingLeft: '10px'}}><SectionHeader text="Legend"/></div>
<div style={TypeIconLegendStyles.legendColumnContainer}>
<div style={TypeIconLegendStyles.legendColumn}>
<DocumentedTypeHeader name={"Global"} icon={IconType.Global}/>
<DocumentedTypeHeader name={"Namespace"} icon={IconType.Namespace}/>
<DocumentedTypeHeader name="Variable" icon={IconType.Variable}/>
<DocumentedTypeHeader name="Function" icon={IconType.Function}/>
<DocumentedTypeHeader name="Function Generic" icon={IconType.FunctionGeneric}/>
<div style={{ height: TypeIconStyles.spriteSize + 'px' }}/>
<DocumentedTypeHeader name="Enum" icon={IconType.Enum}/>
<DocumentedTypeHeader name="Enum Member" icon={IconType.EnumMember}/>
</div>
<div style={TypeIconLegendStyles.legendColumn}>
<DocumentedTypeHeader name="Interface" icon={IconType.Interface}/>
<DocumentedTypeHeader name="Interface Generic" icon={IconType.InterfaceGeneric}/>
<DocumentedTypeHeader name="Interface Constructor" icon={IconType.InterfaceConstructor}/>
<DocumentedTypeHeader name="Interface Property" icon={IconType.InterfaceProperty}/>
<DocumentedTypeHeader name="Interface Method" icon={IconType.InterfaceMethod}/>
<DocumentedTypeHeader name="Interface Method Generic" icon={IconType.InterfaceMethodGeneric}/>
<DocumentedTypeHeader name="Interface Index Signature" icon={IconType.InterfaceIndexSignature}/>
</div>
<div style={TypeIconLegendStyles.legendColumn}>
<DocumentedTypeHeader name="Class" icon={IconType.Class}/>
<DocumentedTypeHeader name="Class Generic" icon={IconType.ClassGeneric}/>
<DocumentedTypeHeader name="Class Constructor" icon={IconType.ClassConstructor}/>
<DocumentedTypeHeader name="Class Property" icon={IconType.ClassProperty}/>
<DocumentedTypeHeader name="Class Method" icon={IconType.ClassMethod}/>
<DocumentedTypeHeader name="Class Method Generic" icon={IconType.ClassMethodGeneric}/>
<DocumentedTypeHeader name="Class Index Signature" icon={IconType.ClassIndexSignature}/>
</div>
</div>
</div>
);
}
}
export class TypeIconClassDiagramLegend extends React.PureComponent<{}, {}>{
render() {
return (
<div style={TypeIconLegendStyles.root}>
<div style={{paddingLeft: '10px'}}><SectionHeader text="Class Diagram Legend"/></div>
<div style={TypeIconLegendStyles.legendColumnContainer}>
<div style={TypeIconLegendStyles.legendColumn}>
<DocumentedTypeHeader name="Class" icon={IconType.Class}/>
<DocumentedTypeHeader name="Class Generic" icon={IconType.ClassGeneric}/>
<DocumentedTypeHeader name="Class Constructor" icon={IconType.ClassConstructor}/>
<DocumentedTypeHeader name="Class Property" icon={IconType.ClassProperty}/>
<DocumentedTypeHeader name="Class Method" icon={IconType.ClassMethod}/>
<DocumentedTypeHeader name="Class Method Generic" icon={IconType.ClassMethodGeneric}/>
<DocumentedTypeHeader name="Class Index Signature" icon={IconType.ClassIndexSignature}/>
</div>
<div style={TypeIconLegendStyles.legendColumn}>
<div>
<VisibilityIndicator visibility={UMLClassMemberVisibility.Private}/> Private
</div>
<div style={{marginTop: '5px' }}>
<VisibilityIndicator visibility={UMLClassMemberVisibility.Protected}/> Protected
</div>
<div style={{marginTop: '5px' }}>
<LifetimeIndicator lifetime={UMLClassMemberLifetime.Static}/> Static
</div>
<div style={{marginTop: '5px' }}>
<OverrideIndicator/> Override
</div>
</div>
</div>
</div>
);
}
} | the_stack |
import { Component, Type, ViewChild, OnInit, Directive } from '@angular/core';
import { ComponentFixture, TestBed, fakeAsync, tick, waitForAsync } from '@angular/core/testing';
import { NxMaskModule } from './mask.module';
import { NxMaskDirective } from './mask.directive';
import { FormsModule, FormGroup, FormControl, ReactiveFormsModule } from '@angular/forms';
import { BACKSPACE, DELETE, ZERO, ONE, NUMPAD_ONE, NUMPAD_ZERO, NINE, A, EIGHT, SEMICOLON } from '@angular/cdk/keycodes';
import { createKeyboardEvent, dispatchKeyboardEvent } from '../cdk-test-utils';
export function assertInputValue(nativeElement: HTMLInputElement, inputValue: string, asserted: string) {
let selectionPosition: number;
nativeElement.value = '';
for (let i = 0; i < inputValue.length; i++) {
selectionPosition = nativeElement.value.length;
nativeElement.selectionStart = selectionPosition;
nativeElement.selectionEnd = selectionPosition;
// keydown event
// I trigger this with key 'A' because the key currently is irrelevant in the keydown handler
// (besides DELETE and BACKSPACE, which are not entered here because it's only strings).
dispatchKeyboardEvent(nativeElement, 'keydown', A);
// input event
nativeElement.value = nativeElement.value + inputValue[i];
nativeElement.dispatchEvent(new Event('input'));
}
expect(nativeElement.value).toBe(asserted);
}
@Directive()
abstract class MaskTest {
@ViewChild(NxMaskDirective) maskInstance!: NxMaskDirective;
mask!: string;
separators: string[] = ['(', ')', ':', '-'];
dropSpecialCharacters: boolean = false;
validateMask: boolean = true;
modelVal!: string;
convertTo!: string;
deactivateMask: boolean = false;
testForm: FormGroup = new FormGroup({
maskInput: new FormControl('', {})
});
}
describe('NxMaskDirective', () => {
let fixture: ComponentFixture<MaskTest>;
let testInstance: MaskTest;
let maskInstance: NxMaskDirective;
let nativeElement: HTMLInputElement;
function createTestComponent(component: Type<MaskTest>) {
fixture = TestBed.createComponent(component);
fixture.detectChanges();
testInstance = fixture.componentInstance;
maskInstance = testInstance.maskInstance;
nativeElement = fixture.nativeElement.querySelector('input') as HTMLInputElement;
}
function setMask(mask: string) {
testInstance.mask = mask;
fixture.detectChanges();
}
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
BasicMaskComponent,
ConfigurableMaskComponent,
ValidationMaskComponent,
HookedMaskComponent
],
imports: [
FormsModule,
ReactiveFormsModule,
NxMaskModule
]
}).compileComponents();
})
);
it('creates the input', () => {
createTestComponent(BasicMaskComponent);
expect(maskInstance).toBeTruthy();
});
it('sets mask input', () => {
createTestComponent(BasicMaskComponent);
expect(maskInstance.mask).toBe('');
testInstance.mask = '00-00';
fixture.detectChanges();
expect(maskInstance.mask).toBe('00-00');
});
it('accepts only numbers', () => {
createTestComponent(BasicMaskComponent);
setMask('0000');
assertInputValue(nativeElement, '1', '1');
assertInputValue(nativeElement, '12', '12');
assertInputValue(nativeElement, '123', '123');
assertInputValue(nativeElement, '1234', '1234');
assertInputValue(nativeElement, '12345', '1234');
assertInputValue(nativeElement, '123456', '1234');
assertInputValue(nativeElement, '1abc', '1');
assertInputValue(nativeElement, 'aLD', '');
assertInputValue(nativeElement, '12-34', '1234'),
assertInputValue(nativeElement, '12-34-', '1234');
});
it('accepts only letters', () => {
createTestComponent(BasicMaskComponent);
setMask('SSSS');
assertInputValue(nativeElement, 'A', 'A');
assertInputValue(nativeElement, 'a', 'a');
assertInputValue(nativeElement, 'abc', 'abc');
assertInputValue(nativeElement, 'aAbBcC', 'aAbB');
assertInputValue(nativeElement, 'a123', 'a');
assertInputValue(nativeElement, 'a12b', 'ab');
assertInputValue(nativeElement, 'ab,cd', 'abcd');
});
it('accepts digits and letters', () => {
createTestComponent(BasicMaskComponent);
setMask('AAAA');
assertInputValue(nativeElement, '1', '1');
assertInputValue(nativeElement, '12', '12');
assertInputValue(nativeElement, '123', '123');
assertInputValue(nativeElement, '1234', '1234');
assertInputValue(nativeElement, '12345', '1234');
assertInputValue(nativeElement, '123456', '1234');
assertInputValue(nativeElement, 'A', 'A');
assertInputValue(nativeElement, 'a', 'a');
assertInputValue(nativeElement, 'abc', 'abc');
assertInputValue(nativeElement, 'aAbBcC', 'aAbB');
assertInputValue(nativeElement, 'A12BC', 'A12B');
assertInputValue(nativeElement, 'A12BC5', 'A12B');
assertInputValue(nativeElement, 'A1-1B', 'A11B');
assertInputValue(nativeElement, 'A1-1BC', 'A11B');
});
it('updates separators', () => {
createTestComponent(ConfigurableMaskComponent);
setMask('(00-00)');
expect(maskInstance.separators).toEqual(['(', ')', ':', '-']);
testInstance.separators = ['$', '%', '&'];
fixture.detectChanges();
expect(maskInstance.separators).toEqual(['$', '%', '&']);
});
it('updates value on separators change', () => {
createTestComponent(ConfigurableMaskComponent);
setMask('(00-00)');
assertInputValue(nativeElement, '1234', '(12-34)');
testInstance.separators = ['(', ')'];
fixture.detectChanges();
expect(nativeElement.value).toBe('(12');
});
it('adds separators', () => {
createTestComponent(BasicMaskComponent);
setMask('00-00');
assertInputValue(nativeElement, '1', '1');
assertInputValue(nativeElement, '12', '12-');
assertInputValue(nativeElement, '123', '12-3');
assertInputValue(nativeElement, '1234', '12-34');
assertInputValue(nativeElement, '12345', '12-34');
setMask('(SS) 00:00:00');
assertInputValue(nativeElement, 'A', '(A');
assertInputValue(nativeElement, 'OO', '(OO) ');
assertInputValue(nativeElement, 'oo1', '(oo) 1');
assertInputValue(nativeElement, 'oo1234', '(oo) 12:34:');
assertInputValue(nativeElement, 'ooabcd1234', '(oo) 12:34:');
assertInputValue(nativeElement, 'oo12345678', '(oo) 12:34:56');
});
it('removes last separator on BACKSPACE pressed', () => {
createTestComponent(BasicMaskComponent);
setMask('00-00');
assertInputValue(nativeElement, '11', '11-');
dispatchKeyboardEvent(nativeElement, 'keydown', BACKSPACE);
fixture.detectChanges();
expect(nativeElement.value).toBe('11');
});
it('updates value on mask change', () => {
createTestComponent(BasicMaskComponent);
setMask('00-00');
assertInputValue(nativeElement, '1234', '12-34');
setMask('AS.SS');
expect(nativeElement.value).toBe('1');
});
it('returns correct unmaskedValue', () => {
createTestComponent(BasicMaskComponent);
setMask('(SS) 00:00:00');
assertInputValue(nativeElement, 'oo12345678', '(oo) 12:34:56');
expect(maskInstance.getUnmaskedValue()).toBe('oo123456');
});
it('sets dropSpecialCharacters to false on default', () => {
createTestComponent(BasicMaskComponent);
expect(maskInstance.dropSpecialCharacters).toBe(false);
});
it('updates dropSpecialCharacters value on change', () => {
createTestComponent(ConfigurableMaskComponent);
setMask('00:00-00');
expect(maskInstance.dropSpecialCharacters).toBe(false);
assertInputValue(nativeElement, '123456', '12:34-56');
expect(testInstance.modelVal).toBe('12:34-56');
testInstance.dropSpecialCharacters = true;
fixture.detectChanges();
expect(maskInstance.dropSpecialCharacters).toBe(true);
expect(nativeElement.value).toBe('12:34-56');
expect(testInstance.modelVal).toBe('123456');
testInstance.dropSpecialCharacters = false;
fixture.detectChanges();
expect(maskInstance.dropSpecialCharacters).toBe(false);
expect(nativeElement.value).toBe('12:34-56');
expect(testInstance.modelVal).toBe('12:34-56');
});
it('sets deactivateMask to false on default', () => {
createTestComponent(BasicMaskComponent);
expect(maskInstance.deactivateMask).toBe(false);
});
describe('validation', () => {
it('sets validateMask to true on default', () => {
createTestComponent(BasicMaskComponent);
expect(maskInstance.validateMask).toBe(true);
});
it('should mark invalid if value is too short', () => {
createTestComponent(ValidationMaskComponent);
testInstance.mask = '00:00-00';
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(false);
expect(testInstance.testForm.get('maskInput')!.valid).toBe(false);
nativeElement.value = '1234';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(false);
expect(testInstance.testForm.get('maskInput')!.valid).toBe(false);
nativeElement.value = '123456';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(true);
expect(testInstance.testForm.get('maskInput')!.valid).toBe(true);
});
it('updates validateMask value on change', () => {
createTestComponent(ConfigurableMaskComponent);
expect(fixture.componentInstance.validateMask).toBe(true);
testInstance.validateMask = false;
expect(fixture.componentInstance.validateMask).toBe(false);
});
it('should not validate with validateMask turned off', () => {
createTestComponent(ValidationMaskComponent);
testInstance.mask = '00:00-00';
testInstance.validateMask = false;
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(true);
expect(testInstance.testForm.get('maskInput')!.valid).toBe(true);
nativeElement.value = '1234';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(true);
expect(testInstance.testForm.get('maskInput')!.valid).toBe(true);
});
it('updates the validated value after validateMask change', () => {
createTestComponent(ValidationMaskComponent);
testInstance.mask = '00:00-00';
fixture.detectChanges();
nativeElement.value = '1234';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(false);
expect(testInstance.testForm.get('maskInput')!.valid).toBe(false);
testInstance.validateMask = false;
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(true);
expect(testInstance.testForm.get('maskInput')!.valid).toBe(true);
testInstance.validateMask = true;
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(false);
expect(testInstance.testForm.get('maskInput')!.valid).toBe(false);
});
it('should validate when switching from deactive mask to active', () => {
createTestComponent(ValidationMaskComponent);
testInstance.mask = '00:00-00';
testInstance.validateMask = true;
testInstance.deactivateMask = true;
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(true);
expect(testInstance.testForm.get('maskInput')!.valid).toBe(true);
// mask deactive, the input should be valid even the value is incorrect.
nativeElement.value = '1234';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(true);
expect(testInstance.testForm.get('maskInput')!.valid).toBe(true);
// mask activate, the input should be invalid if the value is incorrect.
testInstance.deactivateMask = false;
nativeElement.value = '1234';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(false);
expect(testInstance.testForm.get('maskInput')!.valid).toBe(false);
});
});
describe('test ngModel', () => {
it('updates ngModel on backspace', () => {
createTestComponent(ConfigurableMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
expect(testInstance.modelVal).toBe('12:34:56');
nativeElement.setSelectionRange(8, 8);
const keydownEvent = createKeyboardEvent('keydown', BACKSPACE);
const spy = spyOn(keydownEvent, 'preventDefault');
nativeElement.dispatchEvent(keydownEvent);
fixture.detectChanges();
expect(nativeElement.value).toBe('12:34:5');
expect(testInstance.modelVal).toBe('12:34:5');
expect(spy).toHaveBeenCalledTimes(1);
nativeElement.dispatchEvent(keydownEvent);
nativeElement.dispatchEvent(keydownEvent);
fixture.detectChanges();
expect(nativeElement.value).toBe('12:34');
expect(testInstance.modelVal).toBe('12:34');
expect(spy).toHaveBeenCalledTimes(3);
});
it('updates ngModel on delete', () => {
createTestComponent(ConfigurableMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
expect(testInstance.modelVal).toBe('12:34:56');
nativeElement.setSelectionRange(7, 7);
const keydownEvent = createKeyboardEvent('keydown', DELETE);
const spy = spyOn(keydownEvent, 'preventDefault');
nativeElement.dispatchEvent(keydownEvent);
fixture.detectChanges();
expect(nativeElement.value).toBe('12:34:5');
expect(testInstance.modelVal).toBe('12:34:5');
expect(spy).toHaveBeenCalledTimes(1);
});
it('updates a ngModel value with mask value', fakeAsync(() => {
createTestComponent(ConfigurableMaskComponent);
setMask('00:00:00');
fixture.componentInstance.modelVal = '12:34:56';
fixture.detectChanges();
tick();
expect(nativeElement.value).toBe('12:34:56');
expect(testInstance.modelVal).toBe('12:34:56');
}));
it('updates model to uppercase', () => {
createTestComponent(ConfigurableMaskComponent);
setMask('AAAA');
testInstance.convertTo = 'upper';
fixture.detectChanges();
assertInputValue(nativeElement, 'test', 'TEST');
expect(testInstance.modelVal).toBe('TEST');
});
it('should not update model to uppercase if deactivateMask set', () => {
createTestComponent(ConfigurableMaskComponent);
setMask('AAAA');
testInstance.convertTo = 'upper';
testInstance.deactivateMask = true;
fixture.detectChanges();
assertInputValue(nativeElement, 'test', 'test');
expect(testInstance.modelVal).toBe('test');
});
});
it('should not accept characters if mask is filled up', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
nativeElement.setSelectionRange(3, 3);
const keydownEvent = createKeyboardEvent('keydown', ZERO);
nativeElement.dispatchEvent(keydownEvent);
nativeElement.value = '12:034:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:34:56');
expect(nativeElement.selectionStart).toBe(3);
expect(nativeElement.selectionEnd).toBe(3);
});
it('should accept one character if mask is filled up and one character is selected', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
nativeElement.setSelectionRange(3, 5);
const keydownEvent = createKeyboardEvent('keydown', ZERO);
nativeElement.dispatchEvent(keydownEvent);
nativeElement.value = '12:0:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:05:6');
expect(nativeElement.selectionStart).toBe(4);
expect(nativeElement.selectionEnd).toBe(4);
assertInputValue(nativeElement, '123456', '12:34:56');
nativeElement.setSelectionRange(3, 4);
nativeElement.dispatchEvent(keydownEvent);
nativeElement.value = '12:04:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:04:56');
expect(nativeElement.selectionStart).toBe(4);
expect(nativeElement.selectionEnd).toBe(4);
});
describe('mouse position', () => {
it('entering correct letter', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
nativeElement.dispatchEvent(new Event('focus'));
expect(nativeElement.selectionStart).toBe(0);
expect(nativeElement.selectionEnd).toBe(0);
dispatchKeyboardEvent(nativeElement, 'keydown', ONE);
nativeElement.value = '1';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.selectionStart).toBe(1);
expect(nativeElement.selectionEnd).toBe(1);
assertInputValue(nativeElement, '12345', '12:34:5');
nativeElement.setSelectionRange(3, 3);
dispatchKeyboardEvent(nativeElement, 'keydown', ZERO);
nativeElement.value = '12:034:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:03:45');
expect(nativeElement.selectionStart).toBe(4);
expect(nativeElement.selectionEnd).toBe(4);
});
it('entering correct numpad numbers', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
nativeElement.dispatchEvent(new Event('focus'));
expect(nativeElement.selectionStart).toBe(0);
expect(nativeElement.selectionEnd).toBe(0);
let eventData = { keyCode: NUMPAD_ONE, location: 3 };
let keyboardEvent = new KeyboardEvent('keydown', eventData);
nativeElement.dispatchEvent(keyboardEvent);
nativeElement.value = '1';
nativeElement.dispatchEvent(new Event('input'));
expect(nativeElement.selectionStart).toBe(1);
expect(nativeElement.selectionEnd).toBe(1);
assertInputValue(nativeElement, '12345', '12:34:5');
nativeElement.setSelectionRange(3, 3);
eventData = { keyCode: NUMPAD_ZERO, location: 3};
keyboardEvent = new KeyboardEvent('keydown', eventData);
nativeElement.dispatchEvent(keyboardEvent);
nativeElement.value = '12:034:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:03:45');
expect(nativeElement.selectionStart).toBe(4);
expect(nativeElement.selectionEnd).toBe(4);
});
it('switches position behind selector', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '12345', '12:34:5');
nativeElement.setSelectionRange(1, 1);
dispatchKeyboardEvent(nativeElement, 'keydown', NINE);
nativeElement.value = '192:34:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('19:23:45');
expect(nativeElement.selectionStart).toBe(3);
expect(nativeElement.selectionEnd).toBe(3);
// test multiple separators
setMask('00:-00:00');
assertInputValue(nativeElement, '12345', '12:-34:5');
nativeElement.setSelectionRange(1, 1);
dispatchKeyboardEvent(nativeElement, 'keydown', NINE);
nativeElement.value = '192:-34:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('19:-23:45');
expect(nativeElement.selectionStart).toBe(4);
expect(nativeElement.selectionEnd).toBe(4);
});
it('entering false letter', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
nativeElement.setSelectionRange(1, 1);
dispatchKeyboardEvent(nativeElement, 'keydown', A);
nativeElement.value = '1A2:34:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:34:56');
expect(nativeElement.selectionStart).toBe(1);
expect(nativeElement.selectionEnd).toBe(1);
});
it('entering backspace', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
// try to delete separator
nativeElement.setSelectionRange(3, 3);
const keydownEvent = createKeyboardEvent('keydown', BACKSPACE);
const spy = spyOn(keydownEvent, 'preventDefault');
nativeElement.dispatchEvent(keydownEvent);
fixture.detectChanges();
expect(nativeElement.value).toBe('12:34:56');
expect(nativeElement.selectionStart).toBe(2);
expect(nativeElement.selectionEnd).toBe(2);
expect(spy).toHaveBeenCalledTimes(1);
// try to delete letter
nativeElement.setSelectionRange(4, 4);
nativeElement.dispatchEvent(keydownEvent as KeyboardEvent);
nativeElement.value = '12:4:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:45:6');
expect(nativeElement.selectionStart).toBe(3);
expect(nativeElement.selectionEnd).toBe(3);
expect(spy).toHaveBeenCalledTimes(1);
});
it('entering delete', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
// try to delete separator
nativeElement.setSelectionRange(2, 2);
const keyEvent = createKeyboardEvent('keydown', DELETE);
const spy = spyOn(keyEvent, 'preventDefault');
nativeElement.dispatchEvent(keyEvent);
fixture.detectChanges();
expect(nativeElement.value).toBe('12:34:56');
expect(nativeElement.selectionStart).toBe(2);
expect(nativeElement.selectionEnd).toBe(2);
expect(spy).toHaveBeenCalledTimes(1);
// try to delete letter
nativeElement.setSelectionRange(3, 3);
nativeElement.dispatchEvent(keyEvent);
nativeElement.value = '12:4:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:45:6');
expect(nativeElement.selectionStart).toBe(3);
expect(nativeElement.selectionEnd).toBe(3);
expect(spy).toHaveBeenCalledTimes(1);
});
it('sets correct position when backspacing first character', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
nativeElement.setSelectionRange(1, 1);
dispatchKeyboardEvent(nativeElement, 'keydown', BACKSPACE);
nativeElement.value = '2:34:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('23:45:6');
expect(nativeElement.selectionStart).toBe(0);
expect(nativeElement.selectionEnd).toBe(0);
});
it('deletes marked row of characters (with delete pressed)', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
nativeElement.setSelectionRange(3, 5);
dispatchKeyboardEvent(nativeElement, 'keydown', DELETE);
nativeElement.value = '12::56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:56:');
expect(nativeElement.selectionStart).toBe(3);
expect(nativeElement.selectionEnd).toBe(3);
assertInputValue(nativeElement, '123456', '12:34:56');
nativeElement.setSelectionRange(2, 4);
dispatchKeyboardEvent(nativeElement, 'keydown', DELETE);
nativeElement.value = '124:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:45:6');
expect(nativeElement.selectionStart).toBe(3);
expect(nativeElement.selectionEnd).toBe(3);
setMask('00:-00:00');
assertInputValue(nativeElement, '123456', '12:-34:56');
nativeElement.setSelectionRange(2, 5);
dispatchKeyboardEvent(nativeElement, 'keydown', DELETE);
nativeElement.value = '12:4:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:-45:6');
expect(nativeElement.selectionStart).toBe(4);
expect(nativeElement.selectionEnd).toBe(4);
});
it('deletes marked row of characters (with backspace pressed)', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
nativeElement.setSelectionRange(3, 5);
dispatchKeyboardEvent(nativeElement, 'keydown', BACKSPACE);
nativeElement.value = '12::56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:56:');
expect(nativeElement.selectionStart).toBe(3);
expect(nativeElement.selectionEnd).toBe(3);
assertInputValue(nativeElement, '123456', '12:34:56');
nativeElement.setSelectionRange(2, 4);
dispatchKeyboardEvent(nativeElement, 'keydown', BACKSPACE);
nativeElement.value = '124:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:45:6');
expect(nativeElement.selectionStart).toBe(3);
expect(nativeElement.selectionEnd).toBe(3);
setMask('00:-00:00');
assertInputValue(nativeElement, '123456', '12:-34:56');
nativeElement.setSelectionRange(2, 5);
dispatchKeyboardEvent(nativeElement, 'keydown', BACKSPACE);
nativeElement.value = '12:4:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:-45:6');
expect(nativeElement.selectionStart).toBe(4);
expect(nativeElement.selectionEnd).toBe(4);
});
it('deletes marked row of characters (with character pressed)', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
// mark characters between two separators
nativeElement.setSelectionRange(3, 5);
dispatchKeyboardEvent(nativeElement, 'keydown', NINE);
nativeElement.value = '12:9:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:95:6');
expect(nativeElement.selectionStart).toBe(4);
expect(nativeElement.selectionEnd).toBe(4);
// separator contained in marked characters
assertInputValue(nativeElement, '123456', '12:34:56');
nativeElement.setSelectionRange(2, 5);
dispatchKeyboardEvent(nativeElement, 'keydown', EIGHT);
nativeElement.value = '12:8:6';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:86:');
expect(nativeElement.selectionStart).toBe(4);
expect(nativeElement.selectionEnd).toBe(4);
});
it('removes last character on backspace if separator', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '1234', '12:34:');
nativeElement.setSelectionRange(6, 6);
const keydownEvent = createKeyboardEvent('keydown', BACKSPACE);
const spy = spyOn(keydownEvent, 'preventDefault');
nativeElement.dispatchEvent(keydownEvent);
fixture.detectChanges();
expect(nativeElement.selectionStart).toBe(5);
expect(nativeElement.selectionEnd).toBe(5);
expect(nativeElement.value).toBe('12:34');
expect(spy).toHaveBeenCalled();
});
it('removes last character on delete if separator', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '1234', '12:34:');
nativeElement.setSelectionRange(5, 5);
const keydownEvent = createKeyboardEvent('keydown', DELETE);
const spy = spyOn(keydownEvent, 'preventDefault');
nativeElement.dispatchEvent(keydownEvent);
fixture.detectChanges();
expect(nativeElement.selectionStart).toBe(5);
expect(nativeElement.selectionEnd).toBe(5);
expect(nativeElement.value).toBe('12:34');
expect(spy).toHaveBeenCalled();
});
it('entering separator', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
nativeElement.setSelectionRange(2, 2);
dispatchKeyboardEvent(nativeElement, 'keydown', SEMICOLON);
nativeElement.value = '12::34:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('12:34:56');
expect(nativeElement.selectionStart).toBe(3);
expect(nativeElement.selectionEnd).toBe(3);
});
it('pasting something', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123', '12:3');
let data = new DataTransfer();
data.items.add('123', 'text/plain');
let pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(1, 1);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = '11232:3';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('11:23:23');
expect(nativeElement.selectionStart).toBe(6);
expect(nativeElement.selectionEnd).toBe(6);
assertInputValue(nativeElement, '123', '12:3');
data = new DataTransfer();
data.items.add('12ab3', 'text/plain');
pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(1, 1);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = '11232:3';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('11:23:23');
expect(nativeElement.selectionStart).toBe(6);
expect(nativeElement.selectionEnd).toBe(6);
});
it('does not paste if input is filled up', () => {
createTestComponent(BasicMaskComponent);
setMask('00:00:00');
assertInputValue(nativeElement, '123456', '12:34:56');
const data = new DataTransfer();
data.items.add('123', 'text/plain');
const pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
const spy = spyOn(pasteEvent, 'preventDefault');
nativeElement.setSelectionRange(3, 3);
nativeElement.dispatchEvent(pasteEvent);
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
// try with selectionStart !== selectionEnd
nativeElement.setSelectionRange(3, 5);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = '12:123:56';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1); // eventDefault is NOT called again
expect(nativeElement.value).toBe('12:12:56');
expect(nativeElement.selectionStart).toBe(6);
expect(nativeElement.selectionEnd).toBe(6);
});
});
describe('case-sensitivity', () => {
it('should not change case if none set', () => {
createTestComponent(BasicMaskComponent);
setMask('AAAA');
assertInputValue(nativeElement, 'TeSt', 'TeSt');
});
it('should change the user input', () => {
createTestComponent(ConfigurableMaskComponent);
setMask('AAAA');
testInstance.convertTo = 'lower';
fixture.detectChanges();
assertInputValue(nativeElement, 'TEST', 'test');
expect(testInstance.modelVal).toBe('test');
testInstance.convertTo = 'upper';
fixture.detectChanges();
assertInputValue(nativeElement, 'test', 'TEST');
expect(testInstance.modelVal).toBe('TEST');
testInstance.convertTo = '';
fixture.detectChanges();
assertInputValue(nativeElement, 'TeSt' , 'TeSt');
expect(testInstance.modelVal).toBe('TeSt');
});
it('should not change case if deactivateMask set', () => {
createTestComponent(ConfigurableMaskComponent);
setMask('AAAA');
testInstance.convertTo = 'lower';
testInstance.deactivateMask = true;
fixture.detectChanges();
assertInputValue(nativeElement, 'TeSt', 'TeSt');
expect(testInstance.modelVal).toBe('TeSt');
});
});
it('should update value on convertTo change', () => {
createTestComponent(ConfigurableMaskComponent);
setMask('AAAA');
assertInputValue(nativeElement, 'TeSt', 'TeSt');
testInstance.convertTo = 'upper';
fixture.detectChanges();
expect(nativeElement.value).toBe('TEST');
});
describe('test programmatic functions', () => {
it('should not call onChange on setMask() call', () => {
createTestComponent(HookedMaskComponent);
const component = fixture.componentInstance as HookedMaskComponent;
const spy = spyOn(component, 'customOnChange');
maskInstance.registerOnChange(component.customOnChange);
testInstance.mask = 'A';
fixture.detectChanges();
expect(testInstance.maskInstance.mask).toBe('A');
expect(spy).toHaveBeenCalledTimes(1);
testInstance.maskInstance.setMask('0');
fixture.detectChanges();
expect(testInstance.maskInstance.mask).toBe('0');
expect(spy).toHaveBeenCalledTimes(1);
});
});
describe('hooks', () => {
it('should register afterInputHook', () => {
createTestComponent(HookedMaskComponent);
setMask('A');
const component = fixture.componentInstance as HookedMaskComponent;
const spy = spyOn(component, 'customInputHook');
maskInstance.registerAfterInputHook(component.customInputHook);
assertInputValue(nativeElement, '1', '1');
expect(spy).toHaveBeenCalledTimes(1);
});
it('should register beforeInputHook', () => {
createTestComponent(HookedMaskComponent);
setMask('A');
const component = fixture.componentInstance as HookedMaskComponent;
const spy = spyOn(component, 'customPasteHook');
maskInstance.registerBeforePasteHook(component.customPasteHook);
const data = new DataTransfer();
data.items.add('1', 'text/plain');
const pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(1, 1);
nativeElement.dispatchEvent(pasteEvent);
expect(spy).toHaveBeenCalledTimes(1);
});
});
});
@Component({
template: `
<input [nxMask]="mask">
`
})
class BasicMaskComponent extends MaskTest {}
@Component({
template: `
<input
[nxMask]="mask"
[separators]="separators"
[dropSpecialCharacters]="dropSpecialCharacters"
[validateMask]="validateMask"
[nxConvertTo]="convertTo"
[deactivateMask]="deactivateMask"
[(ngModel)]="modelVal"
/>
`
})
class ConfigurableMaskComponent extends MaskTest {}
@Component({
template: `
<form [formGroup]="testForm">
<input [nxMask]="mask" formControlName="maskInput" [validateMask]="validateMask" [deactivateMask]="deactivateMask"/>
</form>
`
})
class ValidationMaskComponent extends MaskTest {}
@Component({
template: `
<input [nxMask]="mask" [separators]="separators">
`
})
class HookedMaskComponent extends MaskTest {
customInputHook = () => {};
customPasteHook = () => {};
customOnChange = () => {};
} | the_stack |
import { And } from "../shared/And";
import { AckCallback } from "./AckCallback";
import { AuthCallback } from "./AuthCallback";
import { IGunConstructorOptions } from "./IGunConstructorOptions";
import { IGunDataType, IGunNodeDataType } from "./IGunDataType";
import { IGunFinalTreeMethods } from "./IGunFinalTreeMethods";
import { IGunReturnObject } from "./IGunReturnObject";
import { IGunTree } from "./IGunTree";
import { IGunUserInstance } from "./IGunUserInstance";
export interface IGunInstance<
CurrentTreeDataType extends IGunNodeDataType,
TSoul extends string | undefined
>{
not?(callback: (key: TSoul) => void): IGunInstance<CurrentTreeDataType, TSoul> ;
/**
* Say you save some data, but want to do something with it later, like expire it or refresh it.
* Well, then `later` is for you! You could use this to easily implement a TTL or similar behavior.
*
* **Warning**: Not included by default! You must include it yourself via `require('gun/lib/later.js')` or
* `<script src="https://cdn.jsdelivr.net/npm/gun/lib/later.js"></script>`!
*/
later?(callback: (data: CurrentTreeDataType, key: TSoul) => void, seconds: number): IGunInstance<CurrentTreeDataType, TSoul> ;
off(): IGunInstance<CurrentTreeDataType, TSoul> ;
/* /**
* Save data into gun, syncing it with your connected peers.
*
* * You cannot save primitive values at the root level.
*
* @param data You do not need to re-save the entire object every time,
* gun will automatically merge your data into what already exists as a "partial" update.
*
* * `undefined`, `NaN`, `Infinity`, `array`, will be rejected.
* * Traditional arrays are dangerous in real-time apps. Use `gun.set` instead.
*
* @param callback invoked on each acknowledgment
* @param options additional options (used for specifying certs)
*/
put(data: Partial<CurrentTreeDataType>, callback?: AckCallback | null, options?: { opt?: { cert?: string } }): IGunInstance<CurrentTreeDataType, TSoul>
/**
* Subscribe to updates and changes on a node or property in real-time.
* @param option Currently, the only option is to filter out old data, and just be given the changes.
* If you're listening to a node with 100 fields, and just one changes,
* you'll instead be passed a node with a single property representing that change rather than the full node every time.
* @param callback
* Once initially and whenever the property or node you're focused on changes, this callback is immediately fired with the data as it is at that point in time.
*
* Since gun streams data, the callback will probably be called multiple times as new chunks come in.
* To remove a listener call .off() on the same property or node.
*/
on(callback: (data: IGunReturnObject<CurrentTreeDataType, TSoul>, key: TSoul, _msg:any, _ev:any) => void, option?: {
change: boolean;
} | boolean, eas?:{$?:any, subs?: unknown[] | { push(arg: unknown) }}, as?:any): IGunInstance<CurrentTreeDataType, TSoul> | Promise<IGunReturnObject<CurrentTreeDataType, TSoul>>;
/**
* Subscribe to database event.
* @param eventName event name that you want listen to (currently only 'auth')
* @param callback once event fire callback
*/
on(eventName: 'auth', cb: AuthCallback, eas?:{$?:any, subs?: unknown[] | { push(arg: unknown) }}, as?:any): IGunInstance<CurrentTreeDataType, TSoul>
/**
* Get the current data without subscribing to updates. Or `undefined` if it cannot be found.
* @returns In the document, it said the return value may change in the future. Don't rely on it.
*/
once(callback?: (data: IGunReturnObject<CurrentTreeDataType, TSoul>, key: TSoul) => void, option?: {
wait: number;
}): IGunInstance<CurrentTreeDataType, TSoul>| Promise<IGunReturnObject<CurrentTreeDataType, TSoul>>;
/**
* Open behaves very similarly to gun.on, except it gives you the **full depth of a document** on every update.
* It also works with graphs, tables, or other data structures. Think of it as opening up a live connection to a document.
*
* **Warning**: Not included by default! You must include it yourself via `require('gun/lib/open.js')` or
* `<script src="https://cdn.jsdelivr.net/npm/gun/lib/open.js"></script>`!
*/
open?(callback: (data: IGunReturnObject<CurrentTreeDataType, TSoul>) => any, opt?: { at?: any, key?: any, doc?: any, ids?: any, any?: any, meta?: any, ev?: { off?: () => {} } }, at?: Partial<CurrentTreeDataType>): IGunInstance<CurrentTreeDataType, TSoul> | Promise<IGunReturnObject<CurrentTreeDataType, TSoul>>;
/**
* Loads the full object once. It is the same as `open` but with the behavior of `once`.
*
* **Warning**: Not included by default! You must include it yourself via `require('gun/lib/load.js')` or
* `<script src="https://cdn.jsdelivr.net/npm/gun/lib/load.js"></script>`!
*/
load?(callback: (data: IGunReturnObject<CurrentTreeDataType, TSoul>) => void, opt?: { at?: any, key?: any, doc?: any, ids?: any, any?: any, meta?: any, ev?: { off?: () => {} } }, at?: Partial<CurrentTreeDataType>): IGunInstance<CurrentTreeDataType, TSoul> | Promise<IGunReturnObject<CurrentTreeDataType, TSoul>>
/**goes back user chain */
back(amount?:number) : IGunInstance<IGunDataType, string | undefined>
/**
* **.set does not mean 'set data', it means a Mathematical Set**
*
* Add a unique item to an unordered list.
* `gun.set` works like a mathematical set, where each item in the list is unique.
* If the item is added twice, it will be merged.
*
* **This means only objects, for now, are supported.**
* @param data the object to add to the set
* @param callback optional function to invoke when the operation is complete
* @param options additional options (used for specifying certs)
*/
set<K extends keyof CurrentTreeDataType>(data: CurrentTreeDataType[K], callback?: AckCallback | null, options?: { opt?: { cert?: string } }): CurrentTreeDataType[K] extends IGunDataType ? IGunInstance<CurrentTreeDataType[K], string>: IGunFinalTreeMethods<CurrentTreeDataType[K], K, string>;
/**
* Where to read data from.
* @param key The key is the ID or property name of the data that you saved from earlier
* (or that will be saved later).
* * Note that if you use .put at any depth after a get it first reads the data and then writes, merging the data as a partial update.
* @param callback You will usually be using gun.on or gun.once to actually retrieve your data,
* not this callback (it is intended for more low-level control, for module and extensions).
*
* **Avoid use callback. The type in the document may be wrong.**
*
* **Here the type of callback respect to the actual behavior**
*/
get<K extends keyof CurrentTreeDataType>(key: K, callback?: (
data: IGunReturnObject<CurrentTreeDataType[K], string>,
key: K) => any):
And< Promise<CurrentTreeDataType[K]>,
CurrentTreeDataType[K] extends IGunDataType ?
IGunInstance<CurrentTreeDataType[K], string> & IGunFinalTreeMethods<CurrentTreeDataType[K], K, string> :
IGunDataType extends CurrentTreeDataType[K] ?
IGunFinalTreeMethods<CurrentTreeDataType[K] , K, string> & IGunInstance<IGunDataType, string>
: IGunFinalTreeMethods<CurrentTreeDataType[K], K, string>>
map<T>(match: (data: CurrentTreeDataType) => T ): IGunFinalTreeMethods<T, keyof CurrentTreeDataType, string>
/**
* After you save some data in an unordered list, you may need to remove it.
*
* **Warning**: Not included by default! You must include it yourself via `require('gun/lib/unset.js')` or
* `<script src="https://cdn.jsdelivr.net/npm/gun/lib/unset.js"></script>`!
*/
unset?<K extends keyof CurrentTreeDataType>(data: K): CurrentTreeDataType[K] extends IGunDataType ? IGunInstance<CurrentTreeDataType[K], string>: IGunFinalTreeMethods<CurrentTreeDataType[K], K, string>;
/**
* Map iterates over each property and item on a node, passing it down the chain,
* behaving like a forEach on your data.
* It also subscribes to every item as well and listens for newly inserted items.
*/
map(match: IGunTree): CurrentTreeDataType[keyof CurrentTreeDataType] extends IGunDataType? IGunInstance<CurrentTreeDataType[keyof CurrentTreeDataType], string> : IGunFinalTreeMethods<CurrentTreeDataType[keyof CurrentTreeDataType], keyof CurrentTreeDataType, string>
opt(opt: IGunConstructorOptions): unknown
/**
*
* Path does the same thing as `.get` but has some conveniences built in.
* @deprecated This is not friendly with type system.
*
* **Warning**: This extension was removed from core, you probably shouldn't be using it!
*
* **Warning**: Not included by default! You must include it yourself via `require('gun/lib/path.js')` or
* `<script src="https://cdn.jsdelivr.net/npm/gun/lib/path.js"></script>`!
*/
path?(path: string | string[]): unknown;
/**
* Subscribes to all future events that occur on the Timegraph and retrieve a specified number of old events
*
* **Warning**: The Timegraph extension isn't required by default, you would need to include at "gun/lib/time.js"
*/
time?<K extends keyof CurrentTreeDataType>(callback: (data: CurrentTreeDataType[K], key: K, time: number) => void, alsoReceiveNOldEvents?: number): CurrentTreeDataType[K] extends IGunDataType ? IGunInstance<CurrentTreeDataType[K], string>: IGunFinalTreeMethods<CurrentTreeDataType[K], K, string>;
/** Pushes data to a Timegraph with it's time set to Gun.state()'s time */
time?<K extends keyof CurrentTreeDataType>(data: CurrentTreeDataType[K]): CurrentTreeDataType[K] extends IGunDataType ? IGunInstance<CurrentTreeDataType[K], string>: IGunFinalTreeMethods<CurrentTreeDataType[K], K, string>;
/**
* @param publicKey If you know a users publicKey you can get their user graph and see any unencrypted data they may have stored there.
*/
user<TUserGraph extends IGunDataType>(): IGunUserInstance<TUserGraph, undefined>
user(publicKey: string): IGunUserInstance<CurrentTreeDataType, undefined>
} | the_stack |
import { wethAddresses } from "@airswap/constants";
import { Server } from "@airswap/libraries";
import { Levels, LightOrder } from "@airswap/types";
import { toAtomicString } from "@airswap/utils";
import {
createAsyncThunk,
createSelector,
createSlice,
PayloadAction,
} from "@reduxjs/toolkit";
import BigNumber from "bignumber.js";
import { Transaction, providers } from "ethers";
import { AppDispatch, RootState } from "../../app/store";
import { notifyTransaction } from "../../components/Toasts/ToastController";
import { RFQ_EXPIRY_BUFFER_MS } from "../../constants/configParams";
import nativeETH from "../../constants/nativeETH";
import {
allowancesLightActions,
allowancesWrapperActions,
} from "../balances/balancesSlice";
import { gasUsedPerSwap } from "../gasCost/gasCostApi";
import { selectGasPriceInQuoteTokens } from "../gasCost/gasCostSlice";
import { selectBestPricing } from "../pricing/pricingSlice";
import {
clearTradeTerms,
selectTradeTerms,
} from "../tradeTerms/tradeTermsSlice";
import {
declineTransaction,
mineTransaction,
revertTransaction,
submitTransaction,
} from "../transactions/transactionActions";
import {
SubmittedApproval,
SubmittedDepositOrder,
SubmittedRFQOrder,
SubmittedWithdrawOrder,
submitTransactionWithExpiry,
} from "../transactions/transactionsSlice";
import {
setWalletConnected,
setWalletDisconnected,
} from "../wallet/walletSlice";
import {
approveToken,
depositETH,
orderSortingFunction,
requestOrders,
takeOrder,
withdrawETH,
} from "./orderApi";
export interface OrdersState {
orders: LightOrder[];
status: "idle" | "requesting" | "approving" | "taking" | "failed" | "reset";
reRequestTimerId: number | null;
}
const initialState: OrdersState = {
orders: [],
status: "idle",
reRequestTimerId: null,
};
const APPROVE_AMOUNT = "90071992547409910000000000";
// replaces WETH to ETH on Wrapper orders
const refactorOrder = (order: LightOrder, chainId: number) => {
let newOrder = { ...order };
if (order.senderToken === wethAddresses[chainId]) {
newOrder.senderToken = nativeETH[chainId].address;
} else if (order.signerToken === wethAddresses[chainId]) {
newOrder.signerToken = nativeETH[chainId].address;
}
return newOrder;
};
export const deposit = createAsyncThunk(
"orders/deposit",
async (
params: {
chainId: number;
senderAmount: string;
senderTokenDecimals: number;
provider: providers.Web3Provider;
},
{ getState, dispatch }
) => {
let tx: Transaction;
try {
tx = await depositETH(
params.chainId,
params.senderAmount,
params.senderTokenDecimals,
params.provider
);
if (tx.hash) {
const senderAmount = toAtomicString(
params.senderAmount,
params.senderTokenDecimals
);
// Since this is a Deposit, senderAmount === signerAmount
const transaction: SubmittedDepositOrder = {
type: "Deposit",
order: {
signerToken: wethAddresses[params.chainId],
signerAmount: senderAmount,
senderToken: nativeETH[params.chainId].address,
senderAmount: senderAmount,
},
hash: tx.hash,
status: "processing",
timestamp: Date.now(),
};
dispatch(submitTransaction(transaction));
params.provider.once(tx.hash, async () => {
const receipt = await params.provider.getTransactionReceipt(tx.hash!);
const state: RootState = getState() as RootState;
const tokens = Object.values(state.metadata.tokens.all);
if (receipt.status === 1) {
dispatch(
mineTransaction({
hash: receipt.transactionHash,
})
);
notifyTransaction(
"Deposit",
transaction,
tokens,
false,
params.chainId
);
} else {
dispatch(
revertTransaction({
hash: receipt.transactionHash,
reason: "Transaction reverted",
})
);
notifyTransaction(
"Deposit",
transaction,
tokens,
true,
params.chainId
);
}
});
}
} catch (e: any) {
console.error(e);
dispatch(declineTransaction(e.message));
throw e;
}
}
);
export const resetOrders = createAsyncThunk(
"orders/reset",
async (params: undefined, { getState, dispatch }) => {
await dispatch(setResetStatus());
dispatch(clear());
dispatch(clearTradeTerms());
}
);
export const withdraw = createAsyncThunk(
"orders/withdraw",
async (
params: {
chainId: number;
senderAmount: string;
senderTokenDecimals: number;
provider: any;
},
{ getState, dispatch }
) => {
let tx: Transaction;
try {
tx = await withdrawETH(
params.chainId,
params.senderAmount,
params.senderTokenDecimals,
params.provider
);
if (tx.hash) {
const transaction: SubmittedWithdrawOrder = {
type: "Withdraw",
order: {
signerToken: nativeETH[params.chainId].address,
signerAmount: toAtomicString(
params.senderAmount,
params.senderTokenDecimals
),
senderToken: wethAddresses[params.chainId],
senderAmount: toAtomicString(
params.senderAmount,
params.senderTokenDecimals
),
},
hash: tx.hash,
status: "processing",
timestamp: Date.now(),
};
dispatch(submitTransaction(transaction));
params.provider.once(tx.hash, async () => {
const receipt = await params.provider.getTransactionReceipt(tx.hash);
const state: RootState = getState() as RootState;
const tokens = Object.values(state.metadata.tokens.all);
if (receipt.status === 1) {
dispatch(
mineTransaction({
hash: receipt.transactionHash,
})
);
notifyTransaction(
"Withdraw",
transaction,
tokens,
false,
params.chainId
);
} else {
dispatch(revertTransaction(receipt.transactionHash));
notifyTransaction(
"Withdraw",
transaction,
tokens,
true,
params.chainId
);
}
});
}
} catch (e: any) {
console.error(e);
dispatch(declineTransaction(e.message));
throw e;
}
}
);
export const request = createAsyncThunk(
"orders/request",
async (
params: {
servers: Server[];
signerToken: string;
senderToken: string;
senderAmount: string;
senderTokenDecimals: number;
senderWallet: string;
},
{ dispatch }
) => {
const orders = await requestOrders(
params.servers,
params.signerToken,
params.senderToken,
params.senderAmount,
params.senderTokenDecimals,
params.senderWallet
);
if (orders.length) {
const bestOrder = [...orders].sort(orderSortingFunction)[0];
const expiry = parseInt(bestOrder.expiry) * 1000;
const timeTilReRequest = expiry - Date.now() - RFQ_EXPIRY_BUFFER_MS;
const reRequestTimerId = window.setTimeout(
() => dispatch(request(params)),
timeTilReRequest
);
dispatch(setReRequestTimerId(reRequestTimerId));
}
return orders;
}
);
export const approve = createAsyncThunk<
// Return type of the payload creator
void,
// Params
{
token: string;
library: any;
contractType: "Wrapper" | "Light";
chainId: number;
},
// Types for ThunkAPI
{
// thunkApi
dispatch: AppDispatch;
state: RootState;
}
>("orders/approve", async (params, { getState, dispatch }) => {
let tx: Transaction;
try {
tx = await approveToken(params.token, params.library, params.contractType);
if (tx.hash) {
const transaction: SubmittedApproval = {
type: "Approval",
hash: tx.hash,
status: "processing",
tokenAddress: params.token,
timestamp: Date.now(),
};
dispatch(submitTransaction(transaction));
params.library.once(tx.hash, async () => {
const receipt = await params.library.getTransactionReceipt(tx.hash);
const state: RootState = getState() as RootState;
const tokens = Object.values(state.metadata.tokens.all);
if (receipt.status === 1) {
dispatch(
mineTransaction({
hash: receipt.transactionHash,
})
);
// Optimistically update allowance (this is not really optimistic,
// but it preempts receiving the event)
if (params.contractType === "Light") {
dispatch(
allowancesLightActions.set({
tokenAddress: params.token,
amount: APPROVE_AMOUNT,
})
);
} else if (params.contractType === "Wrapper") {
dispatch(
allowancesWrapperActions.set({
tokenAddress: params.token,
amount: APPROVE_AMOUNT,
})
);
}
notifyTransaction(
"Approval",
transaction,
tokens,
false,
params.chainId
);
} else {
dispatch(revertTransaction(receipt.transactionHash));
notifyTransaction(
"Approval",
transaction,
tokens,
true,
params.chainId
);
}
});
}
} catch (e: any) {
console.error(e);
dispatch(declineTransaction(e.message));
throw e;
}
});
export const take = createAsyncThunk<
// Return type of the payload creator
void,
// Params
{
order: LightOrder;
library: any;
contractType: "Light" | "Wrapper";
onExpired: () => void;
},
// Types for ThunkAPI
{
dispatch: AppDispatch;
state: RootState;
}
>("orders/take", async (params, { getState, dispatch }) => {
let tx: Transaction;
try {
tx = await takeOrder(params.order, params.library, params.contractType);
// When dealing with the Wrapper, since the "actual" swap is ETH <-> ERC20,
// we should change the order tokens to WETH -> ETH
let newOrder =
params.contractType === "Light"
? params.order
: refactorOrder(params.order, params.library._network.chainId);
if (tx.hash) {
const transaction: SubmittedRFQOrder = {
type: "Order",
order: newOrder,
protocol: "request-for-quote",
hash: tx.hash,
status: "processing",
timestamp: Date.now(),
nonce: params.order.nonce,
expiry: params.order.expiry,
};
dispatch(
submitTransactionWithExpiry({
transaction,
signerWallet: params.order.signerWallet,
onExpired: params.onExpired,
})
);
}
} catch (e: any) {
dispatch(declineTransaction(e.message));
throw e;
}
});
export const ordersSlice = createSlice({
name: "orders",
initialState,
reducers: {
setResetStatus: (state) => {
state.status = "reset";
},
clear: (state) => {
state.orders = [];
state.status = "idle";
if (state.reRequestTimerId) {
clearTimeout(state.reRequestTimerId);
state.reRequestTimerId = null;
}
},
setReRequestTimerId: (state, action: PayloadAction<number>) => {
state.reRequestTimerId = action.payload;
},
},
extraReducers: (builder) => {
builder
.addCase(request.pending, (state) => {
state.status = "requesting";
})
.addCase(request.fulfilled, (state, action) => {
state.status = "idle";
state.orders = action.payload!;
})
.addCase(request.rejected, (state, action) => {
state.status = "failed";
state.orders = [];
})
.addCase(take.pending, (state) => {
state.status = "taking";
})
.addCase(take.fulfilled, (state, action) => {
state.status = "idle";
})
.addCase(take.rejected, (state, action) => {
state.status = "failed";
})
.addCase(approve.pending, (state) => {
state.status = "approving";
})
.addCase(approve.fulfilled, (state) => {
state.status = "idle";
})
.addCase(approve.rejected, (state) => {
state.status = "failed";
})
.addCase(setWalletConnected, (state) => {
state.status = "idle";
state.orders = [];
})
.addCase(setWalletDisconnected, (state) => {
state.status = "idle";
state.orders = [];
});
},
});
export const {
clear,
setResetStatus,
setReRequestTimerId,
} = ordersSlice.actions;
/**
* Sorts orders and returns the best order based on tokens received or sent
* then falling back to expiry.
*/
export const selectBestOrder = (state: RootState) =>
// Note that `.sort` mutates the array, so we need to clone it first to
// prevent mutating state.
[...state.orders.orders].sort(orderSortingFunction)[0];
export const selectSortedOrders = (state: RootState) =>
[...state.orders.orders].sort(orderSortingFunction);
export const selectFirstOrder = (state: RootState) => state.orders.orders[0];
export const selectBestOption = createSelector(
selectTradeTerms,
selectBestOrder,
selectBestPricing,
selectGasPriceInQuoteTokens,
(terms, bestRfqOrder, bestPricing, gasPriceInQuoteTokens) => {
if (!terms) return null;
if (terms.side === "buy") {
console.error(`Buy orders not implemented yet`);
return null;
}
let pricing = (bestPricing as unknown) as {
pricing: Levels;
locator: string;
quoteAmount: string;
} | null;
if (!bestRfqOrder && !pricing) return null;
let lastLookOrder;
if (pricing) {
lastLookOrder = {
quoteAmount: pricing!.quoteAmount,
protocol: "last-look",
pricing: pricing!,
};
if (!bestRfqOrder) return lastLookOrder;
}
let rfqOrder;
let bestRFQQuoteTokens: BigNumber | undefined;
if (bestRfqOrder) {
bestRFQQuoteTokens = new BigNumber(bestRfqOrder.signerAmount).div(
new BigNumber(10).pow(terms.quoteToken.decimals)
);
rfqOrder = {
quoteAmount: bestRFQQuoteTokens.toString(),
protocol: "request-for-quote",
order: bestRfqOrder,
};
if (!lastLookOrder) return rfqOrder;
}
if (
pricing &&
bestRFQQuoteTokens!
.minus(gasPriceInQuoteTokens?.multipliedBy(gasUsedPerSwap) || 0)
.lte(new BigNumber(pricing.quoteAmount))
) {
return lastLookOrder;
} else {
return rfqOrder;
}
}
);
export const selectOrdersStatus = (state: RootState) => state.orders.status;
export default ordersSlice.reducer; | the_stack |
import { IDocumentStore } from "../../../src";
import { disposeTestDocumentStore, testContext } from "../../Utils/TestUtil";
import moment = require("moment");
import { User } from "../../Assets/Entities";
import { assertThat } from "../../Utils/AssertExtensions";
describe("RavenDB_14164Test", function () {
let store: IDocumentStore;
beforeEach(async function () {
store = await testContext.getDocumentStore();
});
afterEach(async () =>
await disposeTestDocumentStore(store));
it("canGetTimeSeriesWithIncludeTagDocuments", async () => {
const tags = ["watches/fitbit", "watches/apple", "watches/sony"];
const baseLine = testContext.utcToday();
const documentId = "users/ayende";
{
const session = store.openSession();
await session.store(new User(), documentId);
const watch1 = new Watch();
watch1.name = "FitBit";
watch1.accuracy = 0.855;
await session.store(watch1, tags[0]);
const watch2 = new Watch();
watch2.name = "Apple";
watch2.accuracy = 0.9;
await session.store(watch2, tags[1]);
const watch3 = new Watch();
watch3.name = "Sony";
watch3.accuracy = 0.78;
await session.store(watch3, tags[2]);
await session.saveChanges();
}
{
const session = store.openSession();
const tsf = session.timeSeriesFor(documentId, "heartRate");
for (let i = 0; i <= 120; i++) {
tsf.append(baseLine.clone().add(i, "minutes").toDate(), i, tags[i % 3]);
}
await session.saveChanges();
}
{
const session = store.openSession();
const getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(baseLine.toDate(), baseLine.clone().add(2, "hours").toDate(), b => b.includeTags());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(getResults)
.hasSize(121);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "hours").toDate().getTime());
// should not go to server
const tagDocuments = await session.load(tags, Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
// assert tag documents
assertThat(tagDocuments)
.hasSize(3);
let tagDoc = tagDocuments["watches/fitbit"];
assertThat(tagDoc.name)
.isEqualTo("FitBit");
assertThat(tagDoc.accuracy)
.isEqualTo(0.855);
tagDoc = tagDocuments["watches/apple"];
assertThat(tagDoc.name)
.isEqualTo("Apple");
assertThat(tagDoc.accuracy)
.isEqualTo(0.9);
tagDoc = tagDocuments["watches/sony"];
assertThat(tagDoc.name)
.isEqualTo("Sony");
assertThat(tagDoc.accuracy)
.isEqualTo(0.78);
}
});
it("canGetTimeSeriesWithIncludeTagsAndParentDocument", async function () {
const tags = ["watches/fitbit", "watches/apple", "watches/sony"];
const baseLine = testContext.utcToday();
const documentId = "users/ayende";
{
const session = store.openSession();
const user = new User();
user.name = "ayende";
await session.store(user, documentId);
const watch1 = new Watch();
watch1.name = "FitBit";
watch1.accuracy = 0.855;
await session.store(watch1, tags[0]);
const watch2 = new Watch();
watch2.name = "Apple";
watch2.accuracy = 0.9;
await session.store(watch2, tags[1]);
const watch3 = new Watch();
watch3.name = "Sony";
watch3.accuracy = 0.78;
await session.store(watch3, tags[2]);
await session.saveChanges();
}
{
const session = store.openSession();
const tsf = session.timeSeriesFor(documentId, "heartRate");
for (let i = 0; i <= 120; i++) {
tsf.append(baseLine.clone().add(i, "minutes").toDate(), i, tags[i % 3]);
}
await session.saveChanges();
}
{
const session = store.openSession();
const getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(baseLine.toDate(), baseLine.clone().add(2, "hours").toDate(), b => b.includeTags().includeDocument());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(getResults)
.hasSize(121);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "hours").toDate().getTime());
// should not go to server
const user = await session.load(documentId, User);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(user.name)
.isEqualTo("ayende");
// should not go to server
const tagDocuments = await session.load(tags, Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
// assert tag documents
assertThat(tagDocuments)
.hasSize(3);
let tagDoc = tagDocuments["watches/fitbit"];
assertThat(tagDoc.name)
.isEqualTo("FitBit");
assertThat(tagDoc.accuracy)
.isEqualTo(0.855);
tagDoc = tagDocuments["watches/apple"];
assertThat(tagDoc.name)
.isEqualTo("Apple");
assertThat(tagDoc.accuracy)
.isEqualTo(0.9);
tagDoc = tagDocuments["watches/sony"];
assertThat(tagDoc.name)
.isEqualTo("Sony");
assertThat(tagDoc.accuracy)
.isEqualTo(0.78);
}
});
it("canGetTimeSeriesWithInclude_CacheNotEmpty", async function() {
const tags = ["watches/fitbit", "watches/apple", "watches/sony"];
const baseLine = testContext.utcToday();
const documentId = "users/ayende";
{
const session = store.openSession();
await session.store(new User(), documentId);
const watch1 = new Watch();
watch1.name = "FitBit";
watch1.accuracy = 0.855;
await session.store(watch1, tags[0]);
const watch2 = new Watch();
watch2.name = "Apple";
watch2.accuracy = 0.9;
await session.store(watch2, tags[1]);
const watch3 = new Watch();
watch3.name = "Sony";
watch3.accuracy = 0.78;
await session.store(watch3, tags[2]);
await session.saveChanges();
}
{
const session = store.openSession();
const tsf = session.timeSeriesFor(documentId, "heartRate");
for (let i = 0; i <= 120; i++) {
let tag: string;
if (i < 60) {
tag = tags[0];
} else if (i < 90) {
tag = tags[1];
} else {
tag = tags[2];
}
tsf.append(baseLine.clone().add(i, "minutes").toDate(), i, tag);
}
await session.saveChanges();
}
{
const session = store.openSession();
// get [00:00 - 01:00]
let getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(baseLine.toDate(), baseLine.clone().add(1, "hours").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(getResults)
.hasSize(61);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(1, "hours").toDate().getTime());
// get [01:15 - 02:00] with includes
getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(
baseLine.clone().add(75, "minutes").toDate(),
baseLine.clone().add(2, "hours").toDate(),
i => i.includeTags());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(2);
assertThat(getResults)
.hasSize(46);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(75, "minutes").toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "hours").toDate().getTime());
// should not go to server
const tagsDocuments = await session.load([tags[1], tags[2]], Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(2);
// assert tag documents
assertThat(tagsDocuments)
.hasSize(2);
let tagDoc = tagsDocuments["watches/apple"];
assertThat(tagDoc.name)
.isEqualTo("Apple");
assertThat(tagDoc.accuracy)
.isEqualTo(0.9);
tagDoc = tagsDocuments["watches/sony"];
assertThat(tagDoc.name)
.isEqualTo("Sony");
assertThat(tagDoc.accuracy)
.isEqualTo(0.78);
// "watches/fitbit" should not be in cache
const watch = await session.load(tags[0], Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(3);
assertThat(watch.name)
.isEqualTo("FitBit");
assertThat(watch.accuracy)
.isEqualTo(0.855);
}
});
it("canGetTimeSeriesWithInclude_CacheNotEmpty2", async function () {
const tags = ["watches/fitbit", "watches/apple", "watches/sony"];
const baseLine = testContext.utcToday();
const documentId = "users/ayende";
{
const session = store.openSession();
await session.store(new User(), documentId);
const watch1 = new Watch();
watch1.name = "FitBit";
watch1.accuracy = 0.855;
await session.store(watch1, tags[0]);
const watch2 = new Watch();
watch2.name = "Apple";
watch2.accuracy = 0.9;
await session.store(watch2, tags[1]);
const watch3 = new Watch();
watch3.name = "Sony";
watch3.accuracy = 0.78;
await session.store(watch3, tags[2]);
await session.saveChanges();
}
{
const session = store.openSession();
const tsf = session.timeSeriesFor(documentId, "heartRate");
for (let i = 0; i <= 120; i++) {
let tag: string;
if (i < 60) {
tag = tags[0];
} else if (i < 90) {
tag = tags[1];
} else {
tag = tags[2];
}
tsf.append(baseLine.clone().add(i, "minutes").toDate(), i, tag);
}
await session.saveChanges();
}
{
const session = store.openSession();
// get [00:00 - 01:00]
let getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(baseLine.toDate(), baseLine.clone().add(1, "hours").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(getResults)
.hasSize(61);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(1, "hours").toDate().getTime());
// get [01:30 - 02:00]
getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(baseLine.clone().add(90, "minutes").toDate(), baseLine.clone().add(2, "hours").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(2);
assertThat(getResults)
.hasSize(31);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(90, "minutes").toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "hours").toDate().getTime());
// get [01:00 - 01:15] with includes
getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(
baseLine.clone().add(1, "hour").toDate(),
baseLine.clone().add(75, "minutes").toDate(),
i => i.includeTags());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(3);
assertThat(getResults)
.hasSize(16);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(1, "hours").toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(75, "minutes").toDate().getTime());
// should not go to server
let watch = await session.load(tags[1], Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(3);
assertThat(watch.name)
.isEqualTo("Apple");
assertThat(watch.accuracy)
.isEqualTo(0.9);
// tags[0] and tags[2] should not be in cache
watch = await session.load(tags[0], Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(4);
assertThat(watch.name)
.isEqualTo("FitBit");
assertThat(watch.accuracy)
.isEqualTo(0.855);
watch = await session.load(tags[2], Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(5);
assertThat(watch.name)
.isEqualTo("Sony");
assertThat(watch.accuracy)
.isEqualTo(0.78);
}
});
it("canGetMultipleRangesWithIncludes", async function () {
const tags = [ "watches/fitbit", "watches/apple", "watches/sony" ];
const baseLine = testContext.utcToday();
const documentId = "users/ayende";
{
const session = store.openSession();
const user = new User();
user.name = "ayende";
await session.store(user, documentId);
const watch1 = new Watch();
watch1.name = "FitBit";
watch1.accuracy = 0.855;
await session.store(watch1, tags[0]);
const watch2 = new Watch();
watch2.name = "Apple";
watch2.accuracy = 0.9;
await session.store(watch2, tags[1]);
const watch3 = new Watch();
watch3.name = "Sony";
watch3.accuracy = 0.78;
await session.store(watch3, tags[2]);
await session.saveChanges();
}
{
const session = store.openSession();
const tsf = session.timeSeriesFor(documentId, "heartRate");
for (let i = 0; i <= 120; i++) {
tsf.append(baseLine.clone().add(i, "minutes").toDate(), i, tags[i % 3]);
}
await session.saveChanges();
}
{
const session = store.openSession();
// get range [00:00 - 00:30]
let getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(baseLine.toDate(), baseLine.clone().add(30, "minutes").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(getResults)
.hasSize(31);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(30, "minutes").toDate().getTime());
// get range [00:45 - 00:60]
getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(baseLine.clone().add(45, "minutes").toDate(), baseLine.clone().add(1, "hour").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(2);
assertThat(getResults)
.hasSize(16);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(45, "minutes").toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(1, "hour").toDate().getTime());
// get range [01:30 - 02:00]
getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(baseLine.clone().add(90, "minutes").toDate(), baseLine.clone().add(2, "hour").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(3);
assertThat(getResults)
.hasSize(31);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(90, "minutes").toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "hour").toDate().getTime());
// get multiple ranges with includes
// ask for entire range [00:00 - 02:00] with includes
// this will go to server to get the "missing parts" - [00:30 - 00:45] and [01:00 - 01:30]
getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(
baseLine.toDate(),
baseLine.clone().add(2, "hours").toDate(),
i => i.includeTags().includeDocument());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(4);
assertThat(getResults)
.hasSize(121);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "hours").toDate().getTime());
// should not go to server
const user = await session.load(documentId, User);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(4);
assertThat(user.name)
.isEqualTo("ayende");
// should not go to server
const tagDocuments = await session.load(tags, Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(4);
// assert tag documents
assertThat(tagDocuments)
.hasSize(3);
let tagDoc = tagDocuments["watches/fitbit"];
assertThat(tagDoc.name)
.isEqualTo("FitBit");
assertThat(tagDoc.accuracy)
.isEqualTo(0.855);
tagDoc = tagDocuments["watches/apple"];
assertThat(tagDoc.name)
.isEqualTo("Apple");
assertThat(tagDoc.accuracy)
.isEqualTo(0.9);
tagDoc = tagDocuments["watches/sony"];
assertThat(tagDoc.name)
.isEqualTo("Sony");
assertThat(tagDoc.accuracy)
.isEqualTo(0.78);
}
});
it("canGetTimeSeriesWithIncludeTags_WhenNotAllEntriesHaveTags", async function () {
const tags = ["watches/fitbit", "watches/apple", "watches/sony"];
const baseLine = testContext.utcToday();
const documentId = "users/ayende";
{
const session = store.openSession();
await session.store(new User(), documentId);
const watch1 = new Watch();
watch1.name = "FitBit";
watch1.accuracy = 0.855;
await session.store(watch1, tags[0]);
const watch2 = new Watch();
watch2.name = "Apple";
watch2.accuracy = 0.9;
await session.store(watch2, tags[1]);
const watch3 = new Watch();
watch3.name = "Sony";
watch3.accuracy = 0.78;
await session.store(watch3, tags[2]);
await session.saveChanges();
}
{
const session = store.openSession();
const tsf = session.timeSeriesFor(documentId, "heartRate");
for (let i = 0; i <= 120; i++) {
const tag = i % 10 === 0
? null
: tags[i % 3];
tsf.append(baseLine.clone().add(i, "minutes").toDate(), i, tag);
}
await session.saveChanges();
}
{
const session = store.openSession();
const getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(baseLine.toDate(), baseLine.clone().add(2, "hours").toDate(), i => i.includeTags());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(getResults)
.hasSize(121);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "hours").toDate().getTime());
// should not go to server
const tagDocuments = await session.load(tags, Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
// assert tag documents
assertThat(tagDocuments)
.hasSize(3);
let tagDoc = tagDocuments["watches/fitbit"];
assertThat(tagDoc.name)
.isEqualTo("FitBit");
assertThat(tagDoc.accuracy)
.isEqualTo(0.855);
tagDoc = tagDocuments["watches/apple"];
assertThat(tagDoc.name)
.isEqualTo("Apple");
assertThat(tagDoc.accuracy)
.isEqualTo(0.9);
tagDoc = tagDocuments["watches/sony"];
assertThat(tagDoc.name)
.isEqualTo("Sony");
assertThat(tagDoc.accuracy)
.isEqualTo(0.78);
}
});
it("includesShouldAffectTimeSeriesGetCommandEtag", async function () {
const tags = ["watches/fitbit", "watches/apple", "watches/sony"];
const baseLine = testContext.utcToday();
const documentId = "users/ayende";
{
const session = store.openSession();
await session.store(new User(), documentId);
const watch1 = new Watch();
watch1.name = "FitBit";
watch1.accuracy = 0.855;
await session.store(watch1, tags[0]);
const watch2 = new Watch();
watch2.name = "Apple";
watch2.accuracy = 0.9;
await session.store(watch2, tags[1]);
const watch3 = new Watch();
watch3.name = "Sony";
watch3.accuracy = 0.78;
await session.store(watch3, tags[2]);
await session.saveChanges();
}
{
const session = store.openSession();
const tsf = session.timeSeriesFor(documentId, "heartRate");
for (let i = 0; i <= 120; i++) {
tsf.append(baseLine.clone().add(i, "minutes").toDate(), i, tags[i % 3]);
}
await session.saveChanges();
}
{
const session = store.openSession();
const getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(baseLine.toDate(), baseLine.clone().add(2, "hours").toDate(), i => i.includeTags());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(getResults)
.hasSize(121);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "hours").toDate().getTime());
// should not go to server
const tagDocuments = await session.load(tags, Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
// assert tag documents
assertThat(tagDocuments)
.hasSize(3);
let tagDoc = tagDocuments["watches/fitbit"];
assertThat(tagDoc.name)
.isEqualTo("FitBit");
assertThat(tagDoc.accuracy)
.isEqualTo(0.855);
tagDoc = tagDocuments["watches/apple"];
assertThat(tagDoc.name)
.isEqualTo("Apple");
assertThat(tagDoc.accuracy)
.isEqualTo(0.9);
tagDoc = tagDocuments["watches/sony"];
assertThat(tagDoc.name)
.isEqualTo("Sony");
assertThat(tagDoc.accuracy)
.isEqualTo(0.78);
}
{
const session = store.openSession();
// update tags[0]
const watch = await session.load(tags[0], Watch);
watch.accuracy += 0.05;
await session.saveChanges();
}
{
const session = store.openSession();
const getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(
baseLine.toDate(),
baseLine.clone().add(2, "hours").toDate(),
b => b.includeTags());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(getResults)
.hasSize(121);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "hours").toDate().getTime());
// should not go to server
const tagDocuments = await session.load(tags, Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
// assert tag documents
assertThat(tagDocuments)
.hasSize(3);
const tagDoc = tagDocuments["watches/fitbit"];
assertThat(tagDoc.name)
.isEqualTo("FitBit");
assertThat(tagDoc.accuracy)
.isEqualTo(0.905);
}
const newTag = "watches/google";
{
const session = store.openSession();
// add new watch
const watch = new Watch();
watch.accuracy = 0.75;
watch.name = "Google Watch";
await session.store(watch, newTag);
// update a time series entry to have the new tag
session.timeSeriesFor(documentId, "heartRate")
.append(baseLine.clone().add(45, "minutes").toDate(), 90, newTag);
await session.saveChanges();
}
{
const session = store.openSession();
const getResults = await session.timeSeriesFor(documentId, "heartRate")
.get(
baseLine.toDate(),
baseLine.clone().add(2, "hours").toDate(),
i => i.includeTags());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(getResults)
.hasSize(121);
assertThat(getResults[0].timestamp.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(getResults[getResults.length - 1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "hours").toDate().getTime());
// should not go to server
await session.load(tags, Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
// assert that newTag is in cache
const watch = await session.load(newTag, Watch);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(watch.name)
.isEqualTo("Google Watch");
assertThat(watch.accuracy)
.isEqualTo(0.75);
}
});
});
class Watch {
public name: string;
public accuracy: number;
} | the_stack |
import type { RuleConfig } from '../rule-config';
/**
* Option.
*/
export interface MemberOrderingOption {
default?:
| 'never'
| (
| 'signature'
| 'field'
| 'public-field'
| 'public-decorated-field'
| 'decorated-field'
| 'static-field'
| 'public-static-field'
| 'instance-field'
| 'public-instance-field'
| 'abstract-field'
| 'public-abstract-field'
| 'protected-field'
| 'protected-decorated-field'
| 'protected-static-field'
| 'protected-instance-field'
| 'protected-abstract-field'
| 'private-field'
| 'private-decorated-field'
| 'private-static-field'
| 'private-instance-field'
| 'private-abstract-field'
| 'method'
| 'public-method'
| 'public-decorated-method'
| 'decorated-method'
| 'static-method'
| 'public-static-method'
| 'instance-method'
| 'public-instance-method'
| 'abstract-method'
| 'public-abstract-method'
| 'protected-method'
| 'protected-decorated-method'
| 'protected-static-method'
| 'protected-instance-method'
| 'protected-abstract-method'
| 'private-method'
| 'private-decorated-method'
| 'private-static-method'
| 'private-instance-method'
| 'private-abstract-method'
| 'call-signature'
| 'public-call-signature'
| 'static-call-signature'
| 'public-static-call-signature'
| 'instance-call-signature'
| 'public-instance-call-signature'
| 'abstract-call-signature'
| 'public-abstract-call-signature'
| 'protected-call-signature'
| 'protected-static-call-signature'
| 'protected-instance-call-signature'
| 'protected-abstract-call-signature'
| 'private-call-signature'
| 'private-static-call-signature'
| 'private-instance-call-signature'
| 'private-abstract-call-signature'
| 'constructor'
| 'public-constructor'
| 'protected-constructor'
| 'private-constructor'
| 'get'
| 'public-get'
| 'public-decorated-get'
| 'decorated-get'
| 'static-get'
| 'public-static-get'
| 'instance-get'
| 'public-instance-get'
| 'abstract-get'
| 'public-abstract-get'
| 'protected-get'
| 'protected-decorated-get'
| 'protected-static-get'
| 'protected-instance-get'
| 'protected-abstract-get'
| 'private-get'
| 'private-decorated-get'
| 'private-static-get'
| 'private-instance-get'
| 'private-abstract-get'
| 'set'
| 'public-set'
| 'public-decorated-set'
| 'decorated-set'
| 'static-set'
| 'public-static-set'
| 'instance-set'
| 'public-instance-set'
| 'abstract-set'
| 'public-abstract-set'
| 'protected-set'
| 'protected-decorated-set'
| 'protected-static-set'
| 'protected-instance-set'
| 'protected-abstract-set'
| 'private-set'
| 'private-decorated-set'
| 'private-static-set'
| 'private-instance-set'
| 'private-abstract-set'
)[]
| {
memberTypes?:
| (
| 'signature'
| 'field'
| 'public-field'
| 'public-decorated-field'
| 'decorated-field'
| 'static-field'
| 'public-static-field'
| 'instance-field'
| 'public-instance-field'
| 'abstract-field'
| 'public-abstract-field'
| 'protected-field'
| 'protected-decorated-field'
| 'protected-static-field'
| 'protected-instance-field'
| 'protected-abstract-field'
| 'private-field'
| 'private-decorated-field'
| 'private-static-field'
| 'private-instance-field'
| 'private-abstract-field'
| 'method'
| 'public-method'
| 'public-decorated-method'
| 'decorated-method'
| 'static-method'
| 'public-static-method'
| 'instance-method'
| 'public-instance-method'
| 'abstract-method'
| 'public-abstract-method'
| 'protected-method'
| 'protected-decorated-method'
| 'protected-static-method'
| 'protected-instance-method'
| 'protected-abstract-method'
| 'private-method'
| 'private-decorated-method'
| 'private-static-method'
| 'private-instance-method'
| 'private-abstract-method'
| 'call-signature'
| 'public-call-signature'
| 'static-call-signature'
| 'public-static-call-signature'
| 'instance-call-signature'
| 'public-instance-call-signature'
| 'abstract-call-signature'
| 'public-abstract-call-signature'
| 'protected-call-signature'
| 'protected-static-call-signature'
| 'protected-instance-call-signature'
| 'protected-abstract-call-signature'
| 'private-call-signature'
| 'private-static-call-signature'
| 'private-instance-call-signature'
| 'private-abstract-call-signature'
| 'constructor'
| 'public-constructor'
| 'protected-constructor'
| 'private-constructor'
| 'get'
| 'public-get'
| 'public-decorated-get'
| 'decorated-get'
| 'static-get'
| 'public-static-get'
| 'instance-get'
| 'public-instance-get'
| 'abstract-get'
| 'public-abstract-get'
| 'protected-get'
| 'protected-decorated-get'
| 'protected-static-get'
| 'protected-instance-get'
| 'protected-abstract-get'
| 'private-get'
| 'private-decorated-get'
| 'private-static-get'
| 'private-instance-get'
| 'private-abstract-get'
| 'set'
| 'public-set'
| 'public-decorated-set'
| 'decorated-set'
| 'static-set'
| 'public-static-set'
| 'instance-set'
| 'public-instance-set'
| 'abstract-set'
| 'public-abstract-set'
| 'protected-set'
| 'protected-decorated-set'
| 'protected-static-set'
| 'protected-instance-set'
| 'protected-abstract-set'
| 'private-set'
| 'private-decorated-set'
| 'private-static-set'
| 'private-instance-set'
| 'private-abstract-set'
)[]
| 'never';
order?:
| 'alphabetically'
| 'alphabetically-case-insensitive'
| 'as-written';
};
classes?:
| 'never'
| (
| 'signature'
| 'field'
| 'public-field'
| 'public-decorated-field'
| 'decorated-field'
| 'static-field'
| 'public-static-field'
| 'instance-field'
| 'public-instance-field'
| 'abstract-field'
| 'public-abstract-field'
| 'protected-field'
| 'protected-decorated-field'
| 'protected-static-field'
| 'protected-instance-field'
| 'protected-abstract-field'
| 'private-field'
| 'private-decorated-field'
| 'private-static-field'
| 'private-instance-field'
| 'private-abstract-field'
| 'method'
| 'public-method'
| 'public-decorated-method'
| 'decorated-method'
| 'static-method'
| 'public-static-method'
| 'instance-method'
| 'public-instance-method'
| 'abstract-method'
| 'public-abstract-method'
| 'protected-method'
| 'protected-decorated-method'
| 'protected-static-method'
| 'protected-instance-method'
| 'protected-abstract-method'
| 'private-method'
| 'private-decorated-method'
| 'private-static-method'
| 'private-instance-method'
| 'private-abstract-method'
| 'call-signature'
| 'public-call-signature'
| 'static-call-signature'
| 'public-static-call-signature'
| 'instance-call-signature'
| 'public-instance-call-signature'
| 'abstract-call-signature'
| 'public-abstract-call-signature'
| 'protected-call-signature'
| 'protected-static-call-signature'
| 'protected-instance-call-signature'
| 'protected-abstract-call-signature'
| 'private-call-signature'
| 'private-static-call-signature'
| 'private-instance-call-signature'
| 'private-abstract-call-signature'
| 'constructor'
| 'public-constructor'
| 'protected-constructor'
| 'private-constructor'
| 'get'
| 'public-get'
| 'public-decorated-get'
| 'decorated-get'
| 'static-get'
| 'public-static-get'
| 'instance-get'
| 'public-instance-get'
| 'abstract-get'
| 'public-abstract-get'
| 'protected-get'
| 'protected-decorated-get'
| 'protected-static-get'
| 'protected-instance-get'
| 'protected-abstract-get'
| 'private-get'
| 'private-decorated-get'
| 'private-static-get'
| 'private-instance-get'
| 'private-abstract-get'
| 'set'
| 'public-set'
| 'public-decorated-set'
| 'decorated-set'
| 'static-set'
| 'public-static-set'
| 'instance-set'
| 'public-instance-set'
| 'abstract-set'
| 'public-abstract-set'
| 'protected-set'
| 'protected-decorated-set'
| 'protected-static-set'
| 'protected-instance-set'
| 'protected-abstract-set'
| 'private-set'
| 'private-decorated-set'
| 'private-static-set'
| 'private-instance-set'
| 'private-abstract-set'
)[]
| {
memberTypes?:
| (
| 'signature'
| 'field'
| 'public-field'
| 'public-decorated-field'
| 'decorated-field'
| 'static-field'
| 'public-static-field'
| 'instance-field'
| 'public-instance-field'
| 'abstract-field'
| 'public-abstract-field'
| 'protected-field'
| 'protected-decorated-field'
| 'protected-static-field'
| 'protected-instance-field'
| 'protected-abstract-field'
| 'private-field'
| 'private-decorated-field'
| 'private-static-field'
| 'private-instance-field'
| 'private-abstract-field'
| 'method'
| 'public-method'
| 'public-decorated-method'
| 'decorated-method'
| 'static-method'
| 'public-static-method'
| 'instance-method'
| 'public-instance-method'
| 'abstract-method'
| 'public-abstract-method'
| 'protected-method'
| 'protected-decorated-method'
| 'protected-static-method'
| 'protected-instance-method'
| 'protected-abstract-method'
| 'private-method'
| 'private-decorated-method'
| 'private-static-method'
| 'private-instance-method'
| 'private-abstract-method'
| 'call-signature'
| 'public-call-signature'
| 'static-call-signature'
| 'public-static-call-signature'
| 'instance-call-signature'
| 'public-instance-call-signature'
| 'abstract-call-signature'
| 'public-abstract-call-signature'
| 'protected-call-signature'
| 'protected-static-call-signature'
| 'protected-instance-call-signature'
| 'protected-abstract-call-signature'
| 'private-call-signature'
| 'private-static-call-signature'
| 'private-instance-call-signature'
| 'private-abstract-call-signature'
| 'constructor'
| 'public-constructor'
| 'protected-constructor'
| 'private-constructor'
| 'get'
| 'public-get'
| 'public-decorated-get'
| 'decorated-get'
| 'static-get'
| 'public-static-get'
| 'instance-get'
| 'public-instance-get'
| 'abstract-get'
| 'public-abstract-get'
| 'protected-get'
| 'protected-decorated-get'
| 'protected-static-get'
| 'protected-instance-get'
| 'protected-abstract-get'
| 'private-get'
| 'private-decorated-get'
| 'private-static-get'
| 'private-instance-get'
| 'private-abstract-get'
| 'set'
| 'public-set'
| 'public-decorated-set'
| 'decorated-set'
| 'static-set'
| 'public-static-set'
| 'instance-set'
| 'public-instance-set'
| 'abstract-set'
| 'public-abstract-set'
| 'protected-set'
| 'protected-decorated-set'
| 'protected-static-set'
| 'protected-instance-set'
| 'protected-abstract-set'
| 'private-set'
| 'private-decorated-set'
| 'private-static-set'
| 'private-instance-set'
| 'private-abstract-set'
)[]
| 'never';
order?:
| 'alphabetically'
| 'alphabetically-case-insensitive'
| 'as-written';
};
classExpressions?:
| 'never'
| (
| 'signature'
| 'field'
| 'public-field'
| 'public-decorated-field'
| 'decorated-field'
| 'static-field'
| 'public-static-field'
| 'instance-field'
| 'public-instance-field'
| 'abstract-field'
| 'public-abstract-field'
| 'protected-field'
| 'protected-decorated-field'
| 'protected-static-field'
| 'protected-instance-field'
| 'protected-abstract-field'
| 'private-field'
| 'private-decorated-field'
| 'private-static-field'
| 'private-instance-field'
| 'private-abstract-field'
| 'method'
| 'public-method'
| 'public-decorated-method'
| 'decorated-method'
| 'static-method'
| 'public-static-method'
| 'instance-method'
| 'public-instance-method'
| 'abstract-method'
| 'public-abstract-method'
| 'protected-method'
| 'protected-decorated-method'
| 'protected-static-method'
| 'protected-instance-method'
| 'protected-abstract-method'
| 'private-method'
| 'private-decorated-method'
| 'private-static-method'
| 'private-instance-method'
| 'private-abstract-method'
| 'call-signature'
| 'public-call-signature'
| 'static-call-signature'
| 'public-static-call-signature'
| 'instance-call-signature'
| 'public-instance-call-signature'
| 'abstract-call-signature'
| 'public-abstract-call-signature'
| 'protected-call-signature'
| 'protected-static-call-signature'
| 'protected-instance-call-signature'
| 'protected-abstract-call-signature'
| 'private-call-signature'
| 'private-static-call-signature'
| 'private-instance-call-signature'
| 'private-abstract-call-signature'
| 'constructor'
| 'public-constructor'
| 'protected-constructor'
| 'private-constructor'
| 'get'
| 'public-get'
| 'public-decorated-get'
| 'decorated-get'
| 'static-get'
| 'public-static-get'
| 'instance-get'
| 'public-instance-get'
| 'abstract-get'
| 'public-abstract-get'
| 'protected-get'
| 'protected-decorated-get'
| 'protected-static-get'
| 'protected-instance-get'
| 'protected-abstract-get'
| 'private-get'
| 'private-decorated-get'
| 'private-static-get'
| 'private-instance-get'
| 'private-abstract-get'
| 'set'
| 'public-set'
| 'public-decorated-set'
| 'decorated-set'
| 'static-set'
| 'public-static-set'
| 'instance-set'
| 'public-instance-set'
| 'abstract-set'
| 'public-abstract-set'
| 'protected-set'
| 'protected-decorated-set'
| 'protected-static-set'
| 'protected-instance-set'
| 'protected-abstract-set'
| 'private-set'
| 'private-decorated-set'
| 'private-static-set'
| 'private-instance-set'
| 'private-abstract-set'
)[]
| {
memberTypes?:
| (
| 'signature'
| 'field'
| 'public-field'
| 'public-decorated-field'
| 'decorated-field'
| 'static-field'
| 'public-static-field'
| 'instance-field'
| 'public-instance-field'
| 'abstract-field'
| 'public-abstract-field'
| 'protected-field'
| 'protected-decorated-field'
| 'protected-static-field'
| 'protected-instance-field'
| 'protected-abstract-field'
| 'private-field'
| 'private-decorated-field'
| 'private-static-field'
| 'private-instance-field'
| 'private-abstract-field'
| 'method'
| 'public-method'
| 'public-decorated-method'
| 'decorated-method'
| 'static-method'
| 'public-static-method'
| 'instance-method'
| 'public-instance-method'
| 'abstract-method'
| 'public-abstract-method'
| 'protected-method'
| 'protected-decorated-method'
| 'protected-static-method'
| 'protected-instance-method'
| 'protected-abstract-method'
| 'private-method'
| 'private-decorated-method'
| 'private-static-method'
| 'private-instance-method'
| 'private-abstract-method'
| 'call-signature'
| 'public-call-signature'
| 'static-call-signature'
| 'public-static-call-signature'
| 'instance-call-signature'
| 'public-instance-call-signature'
| 'abstract-call-signature'
| 'public-abstract-call-signature'
| 'protected-call-signature'
| 'protected-static-call-signature'
| 'protected-instance-call-signature'
| 'protected-abstract-call-signature'
| 'private-call-signature'
| 'private-static-call-signature'
| 'private-instance-call-signature'
| 'private-abstract-call-signature'
| 'constructor'
| 'public-constructor'
| 'protected-constructor'
| 'private-constructor'
| 'get'
| 'public-get'
| 'public-decorated-get'
| 'decorated-get'
| 'static-get'
| 'public-static-get'
| 'instance-get'
| 'public-instance-get'
| 'abstract-get'
| 'public-abstract-get'
| 'protected-get'
| 'protected-decorated-get'
| 'protected-static-get'
| 'protected-instance-get'
| 'protected-abstract-get'
| 'private-get'
| 'private-decorated-get'
| 'private-static-get'
| 'private-instance-get'
| 'private-abstract-get'
| 'set'
| 'public-set'
| 'public-decorated-set'
| 'decorated-set'
| 'static-set'
| 'public-static-set'
| 'instance-set'
| 'public-instance-set'
| 'abstract-set'
| 'public-abstract-set'
| 'protected-set'
| 'protected-decorated-set'
| 'protected-static-set'
| 'protected-instance-set'
| 'protected-abstract-set'
| 'private-set'
| 'private-decorated-set'
| 'private-static-set'
| 'private-instance-set'
| 'private-abstract-set'
)[]
| 'never';
order?:
| 'alphabetically'
| 'alphabetically-case-insensitive'
| 'as-written';
};
interfaces?:
| 'never'
| ('signature' | 'field' | 'method' | 'constructor')[]
| {
memberTypes?:
| ('signature' | 'field' | 'method' | 'constructor')[]
| 'never';
order?:
| 'alphabetically'
| 'alphabetically-case-insensitive'
| 'as-written';
};
typeLiterals?:
| 'never'
| ('signature' | 'field' | 'method' | 'constructor')[]
| {
memberTypes?:
| ('signature' | 'field' | 'method' | 'constructor')[]
| 'never';
order?:
| 'alphabetically'
| 'alphabetically-case-insensitive'
| 'as-written';
};
}
/**
* Options.
*/
export type MemberOrderingOptions = [MemberOrderingOption?];
/**
* Require a consistent member declaration order.
*
* @see [member-ordering](https://typescript-eslint.io/rules/member-ordering)
*/
export type MemberOrderingRuleConfig = RuleConfig<MemberOrderingOptions>;
/**
* Require a consistent member declaration order.
*
* @see [member-ordering](https://typescript-eslint.io/rules/member-ordering)
*/
export interface MemberOrderingRule {
/**
* Require a consistent member declaration order.
*
* @see [member-ordering](https://typescript-eslint.io/rules/member-ordering)
*/
'@typescript-eslint/member-ordering': MemberOrderingRuleConfig;
} | the_stack |
import http from 'http'
import crypto from 'crypto'
import querystring from 'querystring'
const randomUserAgent = (): string => {
const userAgentList = [
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1",
"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1",
"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36",
"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Mobile/14F89;GameHelper",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4",
"Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A300 Safari/602.1",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)",
"Mozilla/5.0 (Windows NT 6.3; Win64, x64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/13.10586",
"Mozilla/5.0 (iPad; CPU OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A300 Safari/602.1"
]
const num = Math.floor(Math.random() * userAgentList.length)
return userAgentList[num]
}
const randomCookies = (musicU: string): string => {
const CookiesList = [
'os=pc; osver=Microsoft-Windows-10-Professional-build-10586-64bit; appver=2.0.3.131777; channel=netease; __remember_me=true',
'MUSIC_U=' + musicU + '; buildver=1506310743; resolution=1920x1080; mobilename=MI5; osver=7.0.1; channel=coolapk; os=android; appver=4.2.0',
'osver=%E7%89%88%E6%9C%AC%2010.13.3%EF%BC%88%E7%89%88%E5%8F%B7%2017D47%EF%BC%89; os=osx; appver=1.5.9; MUSIC_U=' + musicU + '; channel=netease;'
]
const num = Math.floor(Math.random() * CookiesList.length)
return CookiesList[num]
}
type songId = string
interface NeteaseMusicOption {
cookie?: string;
}
// DONT CHANGE!!
const SECRET = '7246674226682325323F5E6544673A51'
// private functions
const neteaseAESECB = Symbol('neteaseAESECB')
const getHttpOption = Symbol('getHttpOption')
const getRandomHex = Symbol('getRandomHex')
const makeRequest = Symbol('makeRequest')
export default class NeteaseMusic {
private cookie = ''
constructor(options: NeteaseMusicOption = {}) {
if (options.cookie) {
this.cookie = options.cookie
}
}
/**
* 私有方法,加密
* @param {Object} body 表单数据
* @return {String} 加密后的表单数据
*/
private [neteaseAESECB](body: http.RequestOptions): string {
const password = Buffer.from(SECRET, 'hex').toString('utf8');
const cipher = crypto.createCipheriv('aes-128-ecb', password, '')
const hex = cipher.update(JSON.stringify(body), 'utf8', 'hex') + cipher.final('hex')
const form = querystring.stringify({
eparams: hex.toUpperCase()
})
return form
}
/**
* 获取请求选项
* @param {String} method GET | POST
* @param {String} path http 请求路径
* @param {Integer} contentLength 如何是 POST 请求,参数长度
* @return Object
*/
private [getHttpOption](method: string, path: string, contentLength?: number): http.RequestOptions {
const options = {
port: 80,
path,
method,
hostname: 'music.163.com',
headers: {
'referer': 'https://music.163.com/',
'cookie': this.cookie || randomCookies(this[getRandomHex](128)),
'user-agent': randomUserAgent()
} as http.OutgoingHttpHeaders
}
if ('POST' === method) {
options.headers['Content-Type'] = 'application/x-www-form-urlencoded'
if (contentLength) {
options.headers['Content-Length'] = contentLength
}
}
return options
}
/**
* 获取随机字符串
* @param {Integer} length 生成字符串的长度
*/
private [getRandomHex](length: number): string {
const isOdd = length % 2;
const randHex = crypto.randomFillSync(Buffer.alloc((length + isOdd) / 2)).toString('hex')
return isOdd ? randHex.slice(1) : randHex;
}
/**
* 发送请求
* @param {Object} options 请求选项
* @param {String} form 表单数据
* @return Promise
*/
private [makeRequest](options: http.RequestOptions, form?: string): Promise<any> {
return new Promise((resolve, reject) => {
const request = http.request(options, response => {
response.setEncoding('utf8')
let responseBody = ''
const hasResponseFailed = response.statusCode && response.statusCode >= 400
if (hasResponseFailed) {
reject(`Request to ${response.url} failed with HTTP ${response.statusCode}`)
}
/* the response stream's (an instance of Stream) current data. See:
* https://nodejs.org/api/stream.html#stream_event_data */
response.on('data', chunk => responseBody += chunk.toString())
// once all the data has been read, resolve the Promise
response.on('end', () => {
if (!responseBody) {
return reject('remote result empty')
}
try {
return resolve(JSON.parse(responseBody));
} catch (error) {
return resolve(responseBody);
}
})
})
request.on('error', err => {
console.error(`problem with request: ${err.message}`)
})
// write data to request body
if (form) {
request.write(form)
}
request.end()
})
}
/**
* 根据关键词获取歌曲列表
* @param {Integer} string 关键词
* @return {Promise}
*/
search(keyword?: string, page = 1, limit = 3) {
const body = {
method: 'POST',
params: {
s: keyword,
type: 1,
limit,
total: true,
offset: page - 1
},
url: 'https://music.163.com/api/cloudsearch/pc'
}
const form = this[neteaseAESECB](body)
const options = this[getHttpOption](
'POST',
'/api/linux/forward',
Buffer.byteLength(form)
)
return this[makeRequest](options, form)
}
/**
* 根据艺术家 id 获取艺术家信息
* @param {Integer} string 艺术家 id
* @return {Promise}
*/
artist(id: songId, limit = 50) {
const body = {
method: 'GET',
params: {
id,
ext: true,
top: limit
},
url: `https://music.163.com/api/v1/artist/${id}`
}
const form = this[neteaseAESECB](body)
const options = this[getHttpOption](
'POST',
'/api/linux/forward',
Buffer.byteLength(form)
)
return this[makeRequest](options, form)
}
/**
* Get playlist by playlist ID
* @param {Integer} string 歌单 id
* @return {Promise}
*/
playlist(id: songId, limit = 1000) {
const body = {
method: 'POST',
params: {
id,
n: limit
},
url: 'https://music.163.com/api/v3/playlist/detail'
}
const form = this[neteaseAESECB](body)
const options = this[getHttpOption](
'POST',
'/api/linux/forward',
Buffer.byteLength(form)
)
return this[makeRequest](options, form)
}
/**
* HACK: Get playlist by playlist ID
* @param {Integer} string 歌单 id
* @return {Promise}
*/
_playlist(id: songId, limit = 1000) {
const body = {
method: 'POST',
params: {
id,
n: limit
},
url: '/api/v2/playlist/detail'
}
body.url += '?' + querystring.stringify(body.params)
const options = this[getHttpOption](body.method, body.url)
return this[makeRequest](options)
}
/**
* 根据专辑 id 获取专辑信息及歌曲列表
* @param {Integer} string 专辑 id
* @return {Promise}
*/
album(id: songId) {
const body = {
method: 'GET',
params: { id },
url: `https://music.163.com/api/v1/album/${id}`
}
const form = this[neteaseAESECB](body)
const options = this[getHttpOption](
'POST',
'/api/linux/forward',
Buffer.byteLength(form)
)
return this[makeRequest](options, form)
}
/**
* 根据歌曲 id 获取歌曲信息
* @param {Integer} string 歌曲 id
* @return {Promise}
*/
song(id: songId | songId[]) {
const ids = Array.isArray(id) ? id : [id]
const body = {
method: 'POST',
params: {
c: `[${ids.map(_id => `{id: ${_id}}`).join(',')}]`,
},
url: 'https://music.163.com/api/v3/song/detail'
}
const form = this[neteaseAESECB](body)
const options = this[getHttpOption](
'POST',
'/api/linux/forward',
Buffer.byteLength(form)
)
return this[makeRequest](options, form)
}
/**
* 根据歌曲 id 获取歌曲资源地址
* @param {Integer} string 歌曲 id
* @return {Promise}
*/
url(id: songId | songId[], br = 320) {
const body = {
method: 'POST',
params: {
ids: Array.isArray(id) ? id : [id],
br: br * 1000
},
url: 'https://music.163.com/api/song/enhance/player/url'
}
const form = this[neteaseAESECB](body)
const options = this[getHttpOption](
'POST',
'/api/linux/forward',
Buffer.byteLength(form)
)
return this[makeRequest](options, form)
}
/**
* 根据歌曲 id 获取歌词
* @param {Integer} string 歌曲 id
* @return {Object}
*/
lyric(id: songId) {
const body = {
method: 'POST',
params: {
id,
os: 'linux',
lv: -1,
kv: -1,
tv: -1,
},
url: 'https://music.163.com/api/song/lyric',
}
const form = this[neteaseAESECB](body)
const options = this[getHttpOption](
'POST',
'/api/linux/forward',
Buffer.byteLength(form)
)
return this[makeRequest](options, form)
}
/**
* 根据封面图片 id 获取图片地址
* @param {Integer} string 图片 id
* @return {Object}
*/
picture(id: songId, size = 300) {
const md5 = (data: string): string => {
const buf = Buffer.from(data)
const str = buf.toString('binary')
return crypto.createHash('md5').update(str).digest('base64')
}
const neteasePickey = (id: songId): string => {
id = String(id)
const magic = '3go8&$8*3*3h0k(2)2'.split('')
const songId = id
.split('')
.map((item, index) => String.fromCharCode(
item.charCodeAt(0) ^ (magic[index % magic.length]).charCodeAt(0)
))
return md5(songId.join(''))
.replace(/\//g, '_')
.replace(/\+/g, '-')
}
return Promise.resolve({
url: `https://p3.music.126.net/${neteasePickey(id)}/${id}.jpg?param=${size}y${size}`
})
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Diagnostic } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ApiManagementClient } from "../apiManagementClient";
import {
DiagnosticContract,
DiagnosticListByServiceNextOptionalParams,
DiagnosticListByServiceOptionalParams,
DiagnosticListByServiceResponse,
DiagnosticGetEntityTagOptionalParams,
DiagnosticGetEntityTagResponse,
DiagnosticGetOptionalParams,
DiagnosticGetResponse,
DiagnosticCreateOrUpdateOptionalParams,
DiagnosticCreateOrUpdateResponse,
DiagnosticUpdateOptionalParams,
DiagnosticUpdateResponse,
DiagnosticDeleteOptionalParams,
DiagnosticListByServiceNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Diagnostic operations. */
export class DiagnosticImpl implements Diagnostic {
private readonly client: ApiManagementClient;
/**
* Initialize a new instance of the class Diagnostic class.
* @param client Reference to the service client
*/
constructor(client: ApiManagementClient) {
this.client = client;
}
/**
* Lists all diagnostics of the API Management service instance.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
public listByService(
resourceGroupName: string,
serviceName: string,
options?: DiagnosticListByServiceOptionalParams
): PagedAsyncIterableIterator<DiagnosticContract> {
const iter = this.listByServicePagingAll(
resourceGroupName,
serviceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
);
}
};
}
private async *listByServicePagingPage(
resourceGroupName: string,
serviceName: string,
options?: DiagnosticListByServiceOptionalParams
): AsyncIterableIterator<DiagnosticContract[]> {
let result = await this._listByService(
resourceGroupName,
serviceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByServiceNext(
resourceGroupName,
serviceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByServicePagingAll(
resourceGroupName: string,
serviceName: string,
options?: DiagnosticListByServiceOptionalParams
): AsyncIterableIterator<DiagnosticContract> {
for await (const page of this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
)) {
yield* page;
}
}
/**
* Lists all diagnostics of the API Management service instance.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
private _listByService(
resourceGroupName: string,
serviceName: string,
options?: DiagnosticListByServiceOptionalParams
): Promise<DiagnosticListByServiceResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, options },
listByServiceOperationSpec
);
}
/**
* Gets the entity state (Etag) version of the Diagnostic specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param diagnosticId Diagnostic identifier. Must be unique in the current API Management service
* instance.
* @param options The options parameters.
*/
getEntityTag(
resourceGroupName: string,
serviceName: string,
diagnosticId: string,
options?: DiagnosticGetEntityTagOptionalParams
): Promise<DiagnosticGetEntityTagResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, diagnosticId, options },
getEntityTagOperationSpec
);
}
/**
* Gets the details of the Diagnostic specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param diagnosticId Diagnostic identifier. Must be unique in the current API Management service
* instance.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
serviceName: string,
diagnosticId: string,
options?: DiagnosticGetOptionalParams
): Promise<DiagnosticGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, diagnosticId, options },
getOperationSpec
);
}
/**
* Creates a new Diagnostic or updates an existing one.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param diagnosticId Diagnostic identifier. Must be unique in the current API Management service
* instance.
* @param parameters Create parameters.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
serviceName: string,
diagnosticId: string,
parameters: DiagnosticContract,
options?: DiagnosticCreateOrUpdateOptionalParams
): Promise<DiagnosticCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, diagnosticId, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* Updates the details of the Diagnostic specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param diagnosticId Diagnostic identifier. Must be unique in the current API Management service
* instance.
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param parameters Diagnostic Update parameters.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
serviceName: string,
diagnosticId: string,
ifMatch: string,
parameters: DiagnosticContract,
options?: DiagnosticUpdateOptionalParams
): Promise<DiagnosticUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
serviceName,
diagnosticId,
ifMatch,
parameters,
options
},
updateOperationSpec
);
}
/**
* Deletes the specified Diagnostic.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param diagnosticId Diagnostic identifier. Must be unique in the current API Management service
* instance.
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
serviceName: string,
diagnosticId: string,
ifMatch: string,
options?: DiagnosticDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, diagnosticId, ifMatch, options },
deleteOperationSpec
);
}
/**
* ListByServiceNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param nextLink The nextLink from the previous successful call to the ListByService method.
* @param options The options parameters.
*/
private _listByServiceNext(
resourceGroupName: string,
serviceName: string,
nextLink: string,
options?: DiagnosticListByServiceNextOptionalParams
): Promise<DiagnosticListByServiceNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, nextLink, options },
listByServiceNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByServiceOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.DiagnosticCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.filter,
Parameters.top,
Parameters.skip,
Parameters.apiVersion
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const getEntityTagOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}",
httpMethod: "HEAD",
responses: {
200: {
headersMapper: Mappers.DiagnosticGetEntityTagHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.diagnosticId
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.DiagnosticContract,
headersMapper: Mappers.DiagnosticGetHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.diagnosticId
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.DiagnosticContract,
headersMapper: Mappers.DiagnosticCreateOrUpdateHeaders
},
201: {
bodyMapper: Mappers.DiagnosticContract,
headersMapper: Mappers.DiagnosticCreateOrUpdateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters8,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.diagnosticId
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch
],
mediaType: "json",
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.DiagnosticContract,
headersMapper: Mappers.DiagnosticUpdateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters8,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.diagnosticId
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch1
],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/diagnostics/{diagnosticId}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.diagnosticId
],
headerParameters: [Parameters.accept, Parameters.ifMatch1],
serializer
};
const listByServiceNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.DiagnosticCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.filter,
Parameters.top,
Parameters.skip,
Parameters.apiVersion
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { Block } from "./Block";
import { Vector2 } from "../Vector2";
import { Connector } from "./Connector";
import { BlockPortRegData, BlockParameterEditorRegData } from "./BlockDef";
import { BlockEditor } from "../Editor/BlockEditor";
import { BlockRunContextData } from "../Runner/BlockRunContextData";
import logger from "../../utils/Logger";
import CommonUtils from "../../utils/CommonUtils";
import ParamTypeServiceInstance, { ParamTypeService } from "../../sevices/ParamTypeService";
import { BlockParameterSetType, BlockParameterType } from "./BlockParameterType";
import { CustomStorageObject } from "./CommonDefine";
/**
* 端口的方向
*
* input:入端口,
* output:出端口
*/
export type BlockPortDirection = 'input'|'output';
/**
* 单元端口
*/
export class BlockPort {
[index : string]: any;
/**
* 名称
*/
public name = "";
/**
* 说明
*/
public description = "This is a block port. Useage: unknow.";
/**
* 端口ID
*/
public guid = "";
public constructor(block : Block) {
this.parent = block;
}
/**
* 获取端口的方向
*/
public direction : BlockPortDirection = null;
/**
* 获取端口是否是动态添加的
*/
public isDyamicAdd = false;
/**
* 被连接的端口
*/
public connectedFromPort : Array<BlockPortConnectorData> = [];
/**
* 连接至的端口
*/
public connectedToPort : Array<BlockPortConnectorData> = [];
public parent : Block = null;
public regData : BlockPortRegData = null;
public isConnectToPort(port : BlockPort) : BlockPortConnectorData {
for(let i = this.connectedToPort.length - 1; i >= 0; i--) {
if(this.connectedToPort[i].port == port)
return this.connectedToPort[i];
}
return null;
}
public isConnectByPort(port : BlockPort) : BlockPortConnectorData {
for(let i = this.connectedFromPort.length - 1; i >= 0; i--) {
if(this.connectedFromPort[i].port == port)
return this.connectedFromPort[i];
}
return null;
}
public removeConnectToPort(port : BlockPort) {
for(let i = this.connectedToPort.length - 1; i >= 0; i--) {
if(this.connectedToPort[i].port == port) {
this.connectedToPort.remove(this.connectedToPort[i]);
}
}
}
public removeConnectByPort(port : BlockPort) {
for(let i = this.connectedFromPort.length - 1; i >= 0; i--) {
if(this.connectedFromPort[i].port == port) {
this.connectedFromPort.remove(this.connectedFromPort[i]);
}
}
}
public isConnected() {
if(this.direction == 'input')
return this.connectedFromPort.length > 0;
else if(this.direction == 'output')
return this.connectedToPort.length > 0;
return false;
}
//参数以及更新
/**
* 参数类型
*/
public paramType = new BlockParameterType('any');
/**
* 参数集合类型
*/
public paramSetType : BlockParameterSetType = 'variable';
/**
* 当端口为Dictionary时的键类型
*/
public paramDictionaryKeyType = new BlockParameterType('any');
/**
* 参数用户设置的值
*/
public paramUserSetValue : any = null;
/**
* 参数默认值
*/
public paramDefaultValue : any = null;
/**
* 参数是否引用传递(仅入端口)
*/
public paramRefPassing = false;
/**
* 参数值是否为全局变量
*/
public paramStatic = false;
private paramStaticValue : any = null;
public portAnyFlexable : { [ index: string ] : boolean|{ get: string, set: string } } = {};
public getUserSetValue() {
if(CommonUtils.isDefined(this.paramUserSetValue))
return this.paramUserSetValue;
return this.paramDefaultValue;
}
public getTypeFriendlyString() {
let str = '';
let typeName = ParamTypeServiceInstance.getTypeNameForUserMapping(this.paramType.getType());
if(this.paramSetType == 'dictionary')
str = '<i>' + ParamTypeServiceInstance.getTypeNameForUserMapping(this.paramDictionaryKeyType.getType()) + '</i>到<i>' + typeName + '</i><b>的映射</b>';
else if(this.paramSetType == 'array')
str = typeName + '<b>数组</b>';
else if(this.paramSetType == 'set')
str = typeName + '<b>集</b>';
else
str = typeName;
return str;
}
public getName(withBlockName = true) {
return `${withBlockName ? this.parent.getName(true) : ''}-${this.name}(${this.guid})`;
}
/**
* 对于这个执行端口,是否在新上下文执行端口。
*/
public executeInNewContext = false;
/**
* 获取当前端口变量在栈中的索引
*/
public stack = -1;
/**
* 获取当前端口变量在栈中的数据。
*/
public getValue(runningContext: BlockRunContextData) : any {
if(this.paramStatic)
return this.paramStaticValue;
if(runningContext.graphBlockParamIndexs[this.stack] === -1) //未初始化栈
return this.paramUserSetValue;
//遍历调用栈,找到数据
let context = runningContext;
if(context == null) {
logger.error(this.getName(), 'Port.getValue : Context not provided', logger.makeSrcPort(this))
return undefined;
}
do {
if(this.stack < context.graphBlockParamIndexs.length)
return context.graphBlockParamStack[context.graphBlockParamIndexs[this.stack]];
else if(context != null && context.parentContext != null)
context = context.parentContext.graph == context.graph ? context.parentContext : null;
else context = null;
} while(context != null);
logger.error(this.getName(), 'Port.getValue : Not found param in context (Position: ' + this.stack + ')', logger.makeSrcPort(this))
return undefined;
}
/**
* 设置当前端口变量在栈中的数据。
* 设置后必须调用 updateOnputValue 才能更新下一级。
*/
public setValue(runningContext: BlockRunContextData, value : any) {
if(this.paramStatic) {
let oldV = this.paramStaticValue;
if(oldV !== value) this.paramStaticValue = value;
return oldV;
}
if(runningContext.graphBlockParamIndexs[this.stack] === -1) {//未初始化栈
logger.error(this.getName(), 'Port.setValue : Port stack not initialized', logger.makeSrcPort(this))
return undefined;
}
let context = runningContext;
if(context == null) {
logger.error(this.getName(), 'Port.setValue : Context not provided', logger.makeSrcPort(this))
return undefined;
}
do {
if(this.stack < context.graphBlockParamIndexs.length) {
let index = context.graphBlockParamIndexs[this.stack];
let oldV = context.graphBlockParamStack[index];
if(oldV !== value)
context.graphBlockParamStack[index] = value;
return oldV;
} else if(context != null && context.parentContext != null)
context = context.parentContext.graph == context.graph ? context.parentContext : null;
else context = null;
} while(context != null);
logger.error(this.getName(), 'Port.setValue : Not found param in context (Position: ' + this.stack + ')', logger.makeSrcPort(this))
return undefined;
}
/**
* 是否强制不显示编辑参数控件
*/
public forceNoEditorControl = false;
/**
* 是否强制在输出端口显示编辑参数控件
*/
public forceEditorControlOutput = false;
/**
* 强制不检查循环调用
*/
public forceNoCycleDetection = false;
/**
* 获取当前端口是不是在编辑器模式中
*/
public isEditorPort = false;
/**
* 自定义单元数据供代码使用(不会保存至文件中)
*/
public data : CustomStorageObject = {};
/**
* 自定义参数端口属性供代码使用(会保存至文件中)
*/
public options : CustomStorageObject = {};
/**
* 获取当前端口已缓存的参数(仅有上下文单元)
* @param runningContext 正在运行的上下文
*/
public getValueCached(runningContext: BlockRunContextData) {
if(runningContext === null) {
logger.error(this.getName(), 'Port.getValueCached: Must provide a context in non-context block.');
return undefined;
}
if(this.direction == 'input') {
if(this.connectedFromPort.length == 0)
return this.getValue(runningContext);
let port = this.connectedFromPort[0].port;
if(this.paramRefPassing || port.paramRefPassing)
return port.getValue(runningContext);
return this.getValue(runningContext);
}else if(this.direction == 'output') {
return this.getValue(runningContext);
}
return null;
}
/**
* 强制请求出端口参数
* @param runningContext 正在运行的上下文
*/
public rquestOutputValue(runningContext: BlockRunContextData) {
if(runningContext === null) {
logger.error(this.getName(), 'Port.rquestOutputValue: Must provide a context in non-context block.');
return undefined;
}
let retVal = this.parent.onPortParamRequest.invoke(this.parent, this, runningContext);
return CommonUtils.isDefined(retVal) ? retVal : this.getValueCached(runningContext);
}
/**
* 请求当前入端口参数
* @param runningContext 正在运行的上下文
*/
public rquestInputValue(runningContext: BlockRunContextData) {
if(this.direction !== 'input') {
logger.error(this.getName(), 'Port.rquestInputValue: Can not rquestInputValue on a non-input port.');
return undefined;
}
if(runningContext === null && this.parent.currentRunningContext === null) {
logger.error(this.getName(), 'Port.rquestInputValue: Must provide a context in non-context block.');
return undefined;
}
//没有连接,仅请求当前端口参数
if(this.connectedFromPort.length == 0)
return this.getValue(runningContext);
//请求连接的端口参数
let port = this.connectedFromPort[0].port;
let retVal = port.parent.onPortParamRequest.invoke(port.parent, port, runningContext);
//端口是直接回传数据,直接回传
if(CommonUtils.isDefined(retVal) )
return retVal;
//检测直接引用请求
if(this.paramRefPassing || port.paramRefPassing || this.parent.currentRunningContext === null) {
return CommonUtils.isDefined(retVal) ? retVal : port.getValue(runningContext);
}
//防止循环更新
let connector = this.connectedFromPort[0].connector;
let iChangedChangedContext = connector.checkParamChangedChangedContext(runningContext);
if(iChangedChangedContext >= 0) {
let v = CommonUtils.isDefined(retVal) ? retVal : port.getValue(runningContext);
this.setValue(runningContext, v);
connector.deleteParamChangedChangedContext(iChangedChangedContext);
return v;
} else {
//重复请求时只返回当前数据
let thisValue = this.getValue(runningContext);
if(CommonUtils.isDefinedAndNotNull(thisValue)) {
return thisValue
} else {
let v = CommonUtils.isDefined(retVal) ? retVal : port.getValue(runningContext);
this.setValue(runningContext, v);
return v;
}
}
}
/**
* 更新当前出端口参数值
* @param runningContext 正在运行的上下文
* @param v 参数值
*/
public updateOnputValue(runningContext: BlockRunContextData, v : any) {
if(this.direction != 'output') {
logger.warning(this.getName(), 'Port.updateOnputValue: Can not updateOnputValue on a non-output port.');
return;
}
if(runningContext === null) {
logger.error(this.getName(), 'Port.updateOnputValue: Must provide a context in non-context block.');
return;
}
if(CommonUtils.isDefined(v) && runningContext.graphBlockParamIndexs[this.stack] >= 0)
this.setValue(runningContext, v);
this.connectedToPort.forEach((p) => {
p.connector.paramChangedContext.addOnce(runningContext);
});
}
/**
* 检查当前入端口参数是否更改
* @param runningContext 正在运行的上下文
*/
public checkInputValueChanged(runningContext: BlockRunContextData) {
let connector = this.connectedFromPort[0].connector;
return connector.checkParamChangedChangedContext(runningContext) >= 0;
}
/**
* 检查目标端口参数类型是否与本端口匹配
* @param targetPort 目标端口
*/
public checkTypeAllow(targetPort : BlockPort) : boolean {
//判断是否是执行
if(this.paramType.isExecute()) return targetPort.paramType.isExecute();
if(targetPort.paramType.isExecute()) return this.paramType.isExecute();
//判断集合类型是否一致
if(this.paramSetType != targetPort.paramSetType) return false;
//映射特殊处理
if(this.paramSetType == 'dictionary') {
return (this.paramType.equals(targetPort.paramType) || (this.paramType.isAny() || targetPort.paramType.isAny()))
&& (this.paramDictionaryKeyType.equals(targetPort.paramDictionaryKeyType) || (this.paramDictionaryKeyType.isAny() || targetPort.paramDictionaryKeyType.isAny())) ;
}else {
//any判断
if(this.paramType.isAny() && !targetPort.paramType.isExecute())
return true;
if(targetPort.paramType.isAny() && !targetPort.paramType.isExecute())
return true;
return this.paramType.equals(targetPort.paramType) && this.paramSetType == targetPort.paramSetType;
}
}
//执行激活
/**
* 在新队列中激活当前执行端口
* (通常用于延时任务完成后的回调)
*/
public activeInNewContext() {
if(!this.paramType.isExecute()) {
logger.error(this.getName(),'Port.activeInNewContext: Cannot execute port because it is not execute port.');
return;
}
if(!this.executeInNewContext) {
logger.error(this.getName(),'Port.activeInNewContext: Cannot execute port in new context because executeInNewContext is not set to true.');
return;
}
let context = this.parent.currentRunningContext;
context.runner.activeOutputPortInNewContext(context, this);
}
/**
* 在当前队列中激活当前执行端口
* @param runningContext 当前运行上下文
*/
public active(runningContext: BlockRunContextData) {
if(!this.paramType.isExecute()) {
logger.error(this.getName(), 'Port.active: Cannot execute port because it is not execute port.');
return;
}
if(this.direction == 'input')
runningContext.runner.activeInputPort(runningContext, this);
else if(this.direction == 'output')
runningContext.runner.activeOutputPort(runningContext, this);
}
}
/**
* 连接数据
*/
export class BlockPortConnectorData {
public port : BlockPort = null;
public connector : Connector = null;
} | the_stack |
import { AppointmentSchema } from "./AppointmentSchema";
import { ComplexPropertyDefinition } from "../../../PropertyDefinitions/ComplexPropertyDefinition";
import { Dictionary, DictionaryWithPropertyDefitionKey, PropertyDefinitionDictionary } from "../../../AltDictionary";
import { EwsLogging } from "../../EwsLogging";
import { EwsUtilities } from "../../EwsUtilities";
import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion";
import { ExtendedPropertyCollection } from "../../../ComplexProperties/ExtendedPropertyCollection";
import { IEnumerable } from "../../../Interfaces/IEnumerable";
import { IOutParam } from "../../../Interfaces/IOutParam";
import { IndexedPropertyDefinition } from "../../../PropertyDefinitions/IndexedPropertyDefinition";
import { LazyMember } from "../../LazyMember";
import { PropertyDefinition } from "../../../PropertyDefinitions/PropertyDefinition";
import { PropertyDefinitionBase } from "../../../PropertyDefinitions/PropertyDefinitionBase";
import { PropertyDefinitionFlags } from "../../../Enumerations/PropertyDefinitionFlags";
import { StringHelper } from "../../../ExtensionMethods";
import { XmlElementNames } from "../../XmlElementNames";
/**
* Represents the base class for all item and folder schemas.
*/
export abstract class ServiceObjectSchema implements IEnumerable<PropertyDefinition> {
//todo: fixing difficulties with following c# code. - ref: added as delegate PropertyDefinitionDictionary in AltDictionary
//using PropertyDefinitionDictionary = LazyMember < System.Collections.Generic.Dictionary<string, PropertyDefinitionBase>>;
//type SchemaTypeList = LazyMember <string[]>;
private properties: Dictionary<string, PropertyDefinition> = new Dictionary<string, PropertyDefinition>((key) => key);// System.Collections.Generic.Dictionary<TKey, TValue>;
private visibleProperties: PropertyDefinition[] = [];//System.Collections.Generic.List<PropertyDefinition>;
private firstClassProperties: PropertyDefinition[] = [];//System.Collections.Generic.List<PropertyDefinition>;
private firstClassSummaryProperties: PropertyDefinition[] = [];//System.Collections.Generic.List<PropertyDefinition>;
private indexedProperties: IndexedPropertyDefinition[] = [];//System.Collections.Generic.List<IndexedPropertyDefinition>;
//static appointmentSchema: AppointmentSchema; - moved to Schemas
/**
* @internal Gets the list of first class properties for this service object type.
*/
get FirstClassProperties(): PropertyDefinition[] { return this.firstClassProperties; }//System.Collections.Generic.List<PropertyDefinition>;
/**
* @internal Gets the list of first class summary properties for this service object type.
*/
get FirstClassSummaryProperties(): PropertyDefinition[] { return this.firstClassSummaryProperties; }//System.Collections.Generic.List<PropertyDefinition>;
/**
* @internal Gets the list of indexed properties for this service object type.
*/
get IndexedProperties(): IndexedPropertyDefinition[] { return this.indexedProperties; }//System.Collections.Generic.List<IndexedPropertyDefinition>;
/**
* Defines the **ExtendedProperties** property.
*/
static ExtendedProperties: PropertyDefinition = new ComplexPropertyDefinition<ExtendedPropertyCollection>(
"ExtendedProperties",
XmlElementNames.ExtendedProperty,
PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.ReuseInstance | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate,
ExchangeVersion.Exchange2007_SP1,
() => { return new ExtendedPropertyCollection(); }
);
private static allSchemaProperties = new PropertyDefinitionDictionary((s) => s);
// private static lockObject: any = {};
// private static allSchemaTypes: LazyMember<string[]> = new LazyMember<string[]>(() => { //SchemaTypeList - LazyMember<T>; - using typenames[] temporarily
// var typeList: string[] = [];
// return typeList;
// typeList.push("AppointmentSchema");
// typeList.push("CalendarResponseObjectSchema");
// typeList.push("CancelMeetingMessageSchema");
// typeList.push("ContactGroupSchema");
// typeList.push("ContactSchema");
// typeList.push("ConversationSchema");
// typeList.push("EmailMessageSchema");
// typeList.push("FolderSchema");
// typeList.push("ItemSchema");
// typeList.push("MeetingMessageSchema");
// typeList.push("MeetingRequestSchema");
// typeList.push("MeetingCancellationSchema");
// typeList.push("MeetingResponseSchema");
// typeList.push("PostItemSchema");
// typeList.push("PostReplySchema");
// typeList.push("ResponseMessageSchema");
// typeList.push("ResponseObjectSchema");
// typeList.push("ServiceObjectSchema");
// typeList.push("SearchFolderSchema");
// typeList.push("TaskSchema");
//
// return typeList;
// });
//
//// private static allSchemaTypes: LazyMember<any[]> = new LazyMember<any[]>(() => { //SchemaTypeList - LazyMember<T>; - using typenames[] temporarily
//// var typeList: any[] = [];
//// return typeList;
//// typeList.push(AppointmentSchema);
//// typeList.push(CalendarResponseObjectSchema);
//// typeList.push(CancelMeetingMessageSchema);
//// typeList.push(ContactGroupSchema);
//// typeList.push(ContactSchema);
//// typeList.push(ConversationSchema);
//// typeList.push(EmailMessageSchema);
//// typeList.push(FolderSchema);
//// typeList.push(ItemSchema);
//// typeList.push(MeetingMessageSchema);
//// typeList.push(MeetingRequestSchema);
//// typeList.push(MeetingCancellationSchema);
//// typeList.push(MeetingResponseSchema);
//// typeList.push(PostItemSchema);
//// typeList.push(PostReplySchema);
//// typeList.push(ResponseMessageSchema);
//// typeList.push(ResponseObjectSchema);
//// typeList.push(ServiceObjectSchema);
//// typeList.push(SearchFolderSchema);
//// typeList.push(TaskSchema);
////
//// return typeList;
//// });
// private static allSchemaProperties = new LazyMember<StringPropertyDefinitionBaseDictionary<string, PropertyDefinitionBase>>(()=> {// string[] //LazyMember<T>;PropertyDefinitionDictionary => LazyMember<System.Collections.Generic.Dictionary<string, PropertyDefinitionBase>>;
// var propDefDictionary: StringPropertyDefinitionBaseDictionary<string, PropertyDefinitionBase> = new StringPropertyDefinitionBaseDictionary<string, PropertyDefinitionBase>();
// for (var type of ServiceObjectSchema.allSchemaTypes.Member) {
// //var type: string = item;
// ServiceObjectSchema.AddSchemaPropertiesToDictionary(type, propDefDictionary);
// }
//
// return propDefDictionary;
// });
// static AddSchemaPropertiesToDictionary(type: string /*System.Type*/, propDefDictionary: StringPropertyDefinitionBaseDictionary<string, PropertyDefinitionBase> /*System.Collections.Generic.Dictionary<TKey, TValue>*/): void {
// ServiceObjectSchema.ForeachPublicStaticPropertyFieldInType(
// type,
// (propertyDefinition: PropertyDefinition, fieldName: string) => {
// // Some property definitions descend from ServiceObjectPropertyDefinition but don't have
// // a Uri, like ExtendedProperties. Ignore them.
// if (!StringHelper.IsNullOrEmpty(propertyDefinition.Uri)) {
// var existingPropertyDefinition: IOutParam<PropertyDefinitionBase> = { outValue: null };
// if (propDefDictionary.tryGetValue(propertyDefinition.Uri, existingPropertyDefinition)) {
// EwsLogging.Assert(
// existingPropertyDefinition == propertyDefinition,
// "Schema.allSchemaProperties.delegate",
// StringHelper.Format("There are at least two distinct property definitions with the following URI: {0}", propertyDefinition.Uri));
// }
// else {
// propDefDictionary.add(propertyDefinition.Uri, propertyDefinition);
//
// // The following is a "generic hack" to register properties that are not public and
// // thus not returned by the above GetFields call. It is currently solely used to register
// // the MeetingTimeZone property.
// var associatedInternalProperties: PropertyDefinition[] = propertyDefinition.GetAssociatedInternalProperties();
//
// for (var associatedInternalProperty of associatedInternalProperties) {
// //var associatedInternalProperty: PropertyDefinition = item;
// propDefDictionary.add(associatedInternalProperty.Uri, associatedInternalProperty);
// }
// }
// }
// });
// }
// private static AddSchemaPropertyNamesToDictionary(type: string /*System.Type*/, propertyNameDictionary: PropDictionary<PropertyDefinition, string> /*System.Collections.Generic.Dictionary<TKey, TValue>*/): void {
// ServiceObjectSchema.ForeachPublicStaticPropertyFieldInType(
// type,
// (propertyDefinition: PropertyDefinition, fieldName: string) =>
// { propertyNameDictionary.add(propertyDefinition, fieldName); });
// }
/**
* @internal Finds the property definition.
*
* @param {string} uri The URI.
* @return {PropertyDefinitionBase} Property definition.
*/
static FindPropertyDefinition(uri: string): PropertyDefinitionBase {
return ServiceObjectSchema.allSchemaProperties.get(uri);
}
// static ForeachPublicStaticPropertyFieldInType(type: string /*System.Type*/, propFieldDelegate: (propertyDefinition: PropertyDefinition, fieldInfo: any /*FieldInfo*/) => void /*ServiceObjectSchema.PropertyFieldInfoDelegate*/): void {
//
// var keys = Object.keys(type);
// keys.forEach((s) => {
// if (typeof (type[s]) != "function" && type[s] instanceof (PropertyDefinition)) {
// var propertyDefinition = <PropertyDefinition> type[s];
// propFieldDelegate(propertyDefinition, s);
// }
// });
// //var staticfields = TypeSystem.GetObjectStaticPropertiesByClassName("Microsoft.Exchange.WebServices.Data." + type);
//
// //for (var field in staticfields) {
// // if (fieldInfo.FieldType == typeof (PropertyDefinition) || fieldInfo.FieldType.IsSubclassOf(typeof (PropertyDefinition))) {
// // PropertyDefinition propertyDefinition = (PropertyDefinition) fieldInfo.GetValue(null);
// // propFieldDelegate(propertyDefinition, fieldInfo);
// // }
// //}
// }
// static InitializeSchemaPropertyNames(): void {
//
// //lock(lockObject)
// //{
// for (var type of ServiceObjectSchema.allSchemaTypes.Member) {
// //var type: string = item;
// ServiceObjectSchema.ForeachPublicStaticPropertyFieldInType(
// type,
// (propDef: PropertyDefinition, fieldName: string) => { propDef.Name = fieldName; });
// }
// //}
// }
/**
* @internal Initializes a new instance of the **ServiceObjectSchema** class.
*/
constructor() {
this.RegisterProperties();
}
/**
* Returns an enumerator that iterates through the collection. this case this.visibleProperties
*/
GetEnumerator(): PropertyDefinition[] {
return this.visibleProperties;
}
protected init() { }
/**
* @internal Registers an indexed property.
*
* @param {IndexedPropertyDefinition} indexedProperty The indexed property to register.
*/
RegisterIndexedProperty(indexedProperty: IndexedPropertyDefinition): void { this.indexedProperties.push(indexedProperty); }
/**
* @internal Registers an internal schema property.
*
* @param {any} registeringSchemaClass SchemaClass calling this method - workaround for fieldUri registration oterhwise it registers super/parent class static properties as well. TypeScript does not provide a way to detect inherited property, hasOwnProperty returns true for parent static property
* @param {PropertyDefinition} property The property to register.
*/
RegisterInternalProperty(registeringSchemaClass: any, property: PropertyDefinition): void { this.RegisterProperty(registeringSchemaClass, property, true); }
/**
* @internal Registers properties.
*
* /remarks/ IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd)
*/
RegisterProperties(): void {/** Virtual */ }
/**
* @internal Registers a schema property. - workaround for fieldUri registration oterhwise it registers super/parent class static properties as well. TypeScript does not provide a way to detect inherited property, hasOwnProperty returns true
*
* @param {any} registeringSchemaClass SchemaClass calling this method - workaround for fieldUri registration oterhwise it registers super/parent class static properties as well. TypeScript does not provide a way to detect inherited property, hasOwnProperty returns true for parent static property
* @param {PropertyDefinition} property The property to register.
*/
RegisterProperty(registeringSchemaClass: any, property: PropertyDefinition): void;
/**
* @private Registers a schema property.
*
* @param {any} registeringSchemaClass SchemaClass calling this method - workaround for fieldUri registration oterhwise it registers super/parent class static properties as well. TypeScript does not provide a way to detect inherited property, hasOwnProperty returns true for parent static property
* @param {PropertyDefinition} property The property to register.
* @param {boolean} isInternal Indicates whether the property is internal or should be visible to developers.
*/
RegisterProperty(registeringSchemaClass: any, property: PropertyDefinition, isInternal: boolean): void;
RegisterProperty(registeringSchemaClass: any, property: PropertyDefinition, isInternal: boolean = false): void {
this.properties.Add(property.XmlElementName, property);
if (!StringHelper.IsNullOrEmpty(property.Uri) && registeringSchemaClass === this.constructor) {
if (ServiceObjectSchema.allSchemaProperties.containsKey(property.Uri)) {
EwsLogging.Assert(
ServiceObjectSchema.allSchemaProperties.get(property.Uri) == property,
"Schema.allSchemaProperties.delegate",
StringHelper.Format("There are at least two distinct property definitions with the following URI: {0}", property.Uri));
}
else {
ServiceObjectSchema.allSchemaProperties.Add(property.Uri, property);
}
}
if (!isInternal) {
this.visibleProperties.push(property);
}
// If this property does not have to be requested explicitly, add
// it to the list of firstClassProperties.
if (!property.HasFlag(PropertyDefinitionFlags.MustBeExplicitlyLoaded)) {
this.firstClassProperties.push(property);
}
// If this property can be found, add it to the list of firstClassSummaryProperties
if (property.HasFlag(PropertyDefinitionFlags.CanFind)) {
this.firstClassSummaryProperties.push(property);
}
}
/**
* @internal Tries to get property definition.
*
* @param {string} xmlElementName Name of the XML element.
* @param {IOutParam<PropertyDefinition>} propertyDefinition The property definition.
* @return {boolean} True if property definition exists.
*/
TryGetPropertyDefinition(xmlElementName: string, propertyDefinition: IOutParam<PropertyDefinition>): boolean {
return this.properties.tryGetValue(xmlElementName, propertyDefinition);
}
}
/**
* Represents the base class for all item and folder schemas.
*/
export interface ServiceObjectSchema {
/**
* Defines the **ExtendedProperties** property.
*/
ExtendedProperties: PropertyDefinition;
/**
* @internal Finds the property definition.
*
* @param {string} uri The URI.
* @return {PropertyDefinitionBase} Property definition.
*/
FindPropertyDefinition(uri: string): PropertyDefinitionBase;
}
/**
* Represents the base class for all item and folder schemas.
*/
export interface ServiceObjectSchemaStatic extends ServiceObjectSchema {
} | the_stack |
import * as React from 'react';
import { injectIntl } from 'react-intl';
import Typography from 'antd/lib/typography';
import Drawer from '@synerise/ds-drawer';
import Button from '@synerise/ds-button';
import Icon from '@synerise/ds-icon';
import ItemFilter from '@synerise/ds-item-filter';
import { CloseM, FolderM, SearchM } from '@synerise/ds-icon/dist/icons';
import Scrollbar from '@synerise/ds-scrollbar';
import SearchBar from '@synerise/ds-search-bar';
import theme from '@synerise/ds-core/dist/js/DSProvider/ThemeProvider/theme';
import Tooltip from '@synerise/ds-tooltip';
import ColumnManagerActions from './ColumnManagerActions/ColumnManagerActions';
import ColumnManagerList from './ColumnManagerList/ColumnManagerList';
import { ColumnManagerProps, State, Texts } from './ColumnManager.types';
import { Column } from './ColumnManagerItem/ColumManagerItem.types';
import * as S from './styles/ColumnManager.styles';
import ColumnManagerGroupSettings from './ColumnManagerGroupSettings/ColumnManagerGroupSettings';
const DEFAULT_STATE: State = {
searchQuery: '',
visibleList: [],
hiddenList: [],
itemFilterVisible: false,
selectedFilterId: undefined,
activeColumn: undefined,
groupSettings: undefined,
};
class ColumnManager extends React.Component<ColumnManagerProps, State> {
constructor(props: ColumnManagerProps) {
super(props);
// eslint-disable-next-line react/state-in-constructor
this.state = {
...DEFAULT_STATE,
groupSettings: props.groupSettings || undefined,
visibleList: props.columns.filter((column: Column) => column.visible),
hiddenList: props.columns.filter((column: Column) => !column.visible),
selectedFilterId: props.itemFilterConfig && props.itemFilterConfig.selectedItemId,
};
}
static getDerivedStateFromProps(props: ColumnManagerProps, state: State): Partial<State> | null {
if (props.itemFilterConfig && props.itemFilterConfig.selectedItemId !== state.selectedFilterId) {
const visible = props.columns.filter((column: Column) => column.visible);
const hidden = props.columns.filter((column: Column) => !column.visible);
return {
visibleList: visible,
hiddenList: hidden,
selectedFilterId: (props.itemFilterConfig && props.itemFilterConfig.selectedItemId) || undefined,
groupSettings: props.groupSettings,
};
}
return null;
}
get texts(): { [k in Texts]: string | React.ReactNode } {
const { texts, intl } = this.props;
return {
title: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.TITLE' }),
savedViews: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.SAVED-VIEWS', defaultMessage: 'Saved views' }),
searchPlaceholder: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.SEARCH-PLACEHOLDER' }),
searchClearTooltip: intl.formatMessage({ id: 'DS.ITEM-FILTER.SEARCH-CLEAR' }),
noResults: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.NO-RESULTS' }),
searchResults: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.SEARCH-RESULTS' }),
visible: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.VISIBLE' }),
hidden: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.HIDDEN' }),
saveView: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.SAVE-VIEW' }),
cancel: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.CANCEL' }),
apply: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.APPLY' }),
fixedLeft: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.FIXED-LEFT' }),
fixedRight: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.FIXED-RIGHT' }),
group: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.GROUP' }),
clear: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.CLEAR' }),
viewName: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.VIEW-NAME' }),
viewDescription: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.VIEW-DESCRIPTION' }),
viewNamePlaceholder: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.VIEW-NAME-PLACEHOLDER' }),
viewDescriptionPlaceholder: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.VIEW-DESCRIPTION-PLACEHOLDER' }),
mustNotBeEmpty: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.MUST-NOT-BE-EMPTY' }),
switchOn: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.SWITCH-ON' }),
switchOff: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.SWITCH-OFF' }),
groupByValue: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.GROUP_BY_VALUE' }),
groupByRanges: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.GROUP_BY_RANGERS' }),
groupByIntervals: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.GROUP_BY_INTERVALS' }),
groupDisabled: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.GROUP_DISABLED' }),
groupTitle: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.GROUP_TITLE' }),
selectPlaceholder: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.SELECT_PLACEHOLDER' }),
intervalPlaceholder: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.INTERVAL_PLACEHOLDER' }),
groupingType: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.SET_GROUPING_TYPE' }),
groupingTypeTooltip: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.GROUPING_TYPE_TOOLTIP' }),
from: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.FROM' }),
to: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.TO' }),
remove: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.REMOVE' }),
addRange: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.ADD_RANGE' }),
errorEmptyRange: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.ERROR_EMPTY_RANGE' }),
errorEmptyFromField: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.ERROR_EMPTY_FROM_FIELD' }),
errorEmptyToField: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.ERROR_EMPTY_TO_FIELD' }),
errorChooseGrouping: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.ERROR_CHOOSE_GROUPING' }),
errorInterval: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.ERROR_INTERVAL' }),
errorRange: intl.formatMessage({ id: 'DS.COLUMN-MANAGER.ERROR_RANGE' }),
...texts,
};
}
updateVisibleColumns = (newVisibleList: Column[]): void => {
this.setState({
visibleList: newVisibleList.map((column: Column): Column => ({ ...column, visible: true })),
});
};
updateHiddenColumns = (newHiddenList: Column[]): void => {
this.setState({
hiddenList: newHiddenList.map((column: Column): Column => ({ ...column, visible: false })),
});
};
hideColumn = (id: string): void => {
const { visibleList, hiddenList } = this.state;
const column = visibleList.find(col => col.id === id);
column &&
this.setState({
visibleList: visibleList.filter(visibleColumn => visibleColumn.id !== column.id),
hiddenList: [...hiddenList, { ...column, visible: false }],
});
};
showColumn = (id: string): void => {
const { visibleList, hiddenList } = this.state;
const column = hiddenList.find(col => col.id === id);
column &&
this.setState({
hiddenList: hiddenList.filter(hiddenColumn => hiddenColumn.id !== column.id),
visibleList: [...visibleList, { ...column, visible: true }],
});
};
toggleColumn = (id: string, columnVisible: boolean): void => {
if (columnVisible) {
this.hideColumn(id);
} else {
this.showColumn(id);
}
};
setFixed = (id: string, fixed?: string): void => {
const { visibleList } = this.state;
this.setState({
visibleList: visibleList.map(visibleColumn => {
if (visibleColumn.id === id) {
return visibleColumn.fixed === fixed ? { ...visibleColumn, fixed: undefined } : { ...visibleColumn, fixed };
}
return visibleColumn;
}),
});
};
showGroupSettings = (column: Column): void => {
this.setState({ activeColumn: column });
};
hideItemFilter = (): void => {
const { hideSavedViews } = this.props;
hideSavedViews && hideSavedViews();
this.setState({
itemFilterVisible: false,
});
};
handleShowItemFilter = (): void => {
this.setState({
itemFilterVisible: true,
});
};
handleSearchChange = (query: string): void => {
this.setState({
searchQuery: query,
});
};
handleSave = (viewMeta: { name: string; description: string }): void => {
const { onSave } = this.props;
const { visibleList, hiddenList, groupSettings } = this.state;
onSave({
meta: viewMeta,
groupSettings,
columns: [...visibleList, ...hiddenList],
});
};
handleApply = (): void => {
const { onApply } = this.props;
const { visibleList, hiddenList, groupSettings } = this.state;
onApply([...visibleList, ...hiddenList], groupSettings);
};
render(): React.ReactElement {
const { visible, hide, itemFilterConfig, savedViewsVisible } = this.props;
const { visibleList, hiddenList, searchQuery, itemFilterVisible, activeColumn, groupSettings } = this.state;
const searchResults = [...visibleList, ...hiddenList].filter(column =>
column.name.toLowerCase().includes(searchQuery.toLowerCase())
);
const visibleListWithGroup = visibleList.map(column => {
if (column.id === groupSettings?.column?.id) {
return {
...column,
group: true,
};
}
return column;
});
return (
<>
<S.ColumnManager visible={visible || savedViewsVisible} width={338} onClose={hide}>
<Drawer.DrawerHeader>
<Drawer.DrawerHeaderBar>
<Typography.Title style={{ flex: 1, margin: 0 }} level={4}>
{this.texts.title}
</Typography.Title>
<Tooltip title={this.texts.savedViews} placement="bottom">
<Button
data-testid="ds-column-manager-show-filters"
type="ghost"
mode="single-icon"
onClick={this.handleShowItemFilter}
>
<Icon component={<FolderM />} />
</Button>
</Tooltip>
<Button
data-testid="ds-column-manager-close"
style={{ marginLeft: '8px' }}
mode="single-icon"
type="ghost"
onClick={hide}
>
<Icon component={<CloseM />} />
</Button>
</Drawer.DrawerHeaderBar>
</Drawer.DrawerHeader>
<SearchBar
onSearchChange={this.handleSearchChange}
placeholder={this.texts.searchPlaceholder as string}
value={searchQuery}
onClearInput={(): void => this.handleSearchChange('')}
iconLeft={<Icon component={<SearchM />} color={theme.palette['grey-600']} />}
clearTooltip={(this.texts.searchClearTooltip as string) || ''}
/>
<Scrollbar absolute>
<Drawer.DrawerContent style={{ padding: '0 0 80px' }}>
<ColumnManagerList
texts={this.texts}
searchQuery={searchQuery}
searchResults={searchResults}
visibleList={visibleListWithGroup}
hiddenList={hiddenList}
setFixed={this.setFixed}
showGroupSettings={this.showGroupSettings}
groupSettings={groupSettings}
toggleColumn={this.toggleColumn}
updateVisibleList={this.updateVisibleColumns}
updateHiddenList={this.updateHiddenColumns}
/>
</Drawer.DrawerContent>
</Scrollbar>
<ColumnManagerActions
onSave={this.handleSave}
onApply={this.handleApply}
onCancel={hide}
texts={this.texts}
/>
{itemFilterConfig && (
<ItemFilter
{...itemFilterConfig}
visible={itemFilterVisible || Boolean(savedViewsVisible)}
hide={this.hideItemFilter}
/>
)}
</S.ColumnManager>
<ColumnManagerGroupSettings
texts={this.texts}
hide={(): void => {
this.setState({ activeColumn: undefined });
}}
visible={activeColumn !== undefined}
column={activeColumn}
settings={activeColumn?.key === groupSettings?.column?.key ? groupSettings : undefined}
onOk={(settings): void => {
this.setState({ groupSettings: settings, activeColumn: undefined });
}}
/>
</>
);
}
}
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
export default injectIntl(ColumnManager); | the_stack |
/// <reference path="../guisprite.ts" />
module EZGUI.Component {
export class Layout extends GUISprite {
public guiMask;
constructor(public settings, public themeId) {
super(settings, themeId);
}
protected handleEvents() {
super.handleEvents();
}
protected draw() {
super.draw();
this.guiMask = { width: 0, height: 0 };
var settings = this._settings;
if (settings) {
var padding = settings.padding || 0;
if (this._settings.mask !== false) {
var myMask = new (<any>PIXI).Graphics();
myMask.beginFill();
myMask.drawRect(padding, padding, settings.width - padding * 2, settings.height - padding * 2);
myMask.endFill();
this.addChild(myMask);
if (this._settings.anchor) {
myMask.position.x = this.container.position.x + padding;
myMask.position.y = this.container.position.y + padding;
}
this.container.mask = myMask;
}
this.guiMask.x = padding;
this.guiMask.y = padding;
this.guiMask.width = settings.width - padding * 2;
this.guiMask.height = settings.height - padding * 2;
}
//move container back to the top
this.addChild(this.container);
}
public createChild(childSettings, order?) {
if (!childSettings) return null;
var i = order;
//console.log('adding ', i);
var padTop = this._settings['padding-top'] || this._settings.padding || 0;
var padLeft= this._settings['padding-left'] || this._settings.padding || 0;
var swidth = this._settings.width - padLeft;
var sheight = this._settings.height - padTop;
var dx = padLeft;
var dy = padTop;
var lx = 1;
var ly = 1;
if (this._settings.layout != undefined) {
lx = this._settings.layout[0];
ly = this._settings.layout[1];
var x, y;
//horizontal layout
if (ly == null ) {
x = i;
y = 0;
} else if (lx == null) {
x = 0;
y = i;
}
else {
var adjust = Math.floor(i / (lx * ly));
if (this._settings.dragY === false) {
dx += adjust * swidth;
dy -= adjust * sheight;
//ly = 1;
} else if (this._settings.dragX === false) {
//lx = 1;
//dx -= adjust * this._settings.width;
//dy += adjust * this._settings.height;
}
x = i % lx;
y = Math.floor(i / lx);
}
ly = ly || 1;
lx = lx || 1;
dx += x * (swidth / lx);
dy += y * (sheight / ly);
}
var pos = childSettings.position;
if (typeof pos == 'string') {
var parts = pos.split(' ');
var pos1 = parts[0];
var pos2 = parts[1];
//normalize pos
if (parts[0] == parts[1]) {
pos2 = undefined;
}
if ((parts[0] == 'top' && parts[2] == 'bottom') ||
(parts[0] == 'bottom' && parts[2] == 'top') ||
(parts[0] == 'left' && parts[2] == 'right') ||
(parts[0] == 'right' && parts[2] == 'left')
) {
pos1 = 'center';
pos2 = 'undefined';
}
if ((parts[0] == 'left' || parts[0] == 'right') && (parts[1] == 'top' || parts[1] == 'bottom')) {
pos1 = parts[1];
pos2 = parts[0];
}
if ((pos1 == 'left' || pos1 == 'right') && pos2 === undefined) {
pos2 = pos1;
pos1 = 'left';
}
childSettings.position = { x: dx, y: dy };
switch (pos1) {
case 'center':
childSettings.position.y = dy + (this._settings.height / ly) / 2 - childSettings.height / 2;
if (pos2 === undefined) childSettings.position.x = dx + (this._settings.width / lx) / 2 - childSettings.width / 2;
break;
case 'bottom':
childSettings.position.y = dy + (this._settings.height / ly) - childSettings.height - this._settings.padding;
break;
}
switch (pos2) {
case 'center':
childSettings.position.x = dx + (this._settings.width / lx) / 2 - childSettings.width / 2;
break;
case 'right':
childSettings.position.x = dx + (this._settings.width / lx) - childSettings.width - this._settings.padding;
break;
}
}
//if (childSettings.position == 'center') {
// childSettings.position = { x: 0, y: 0 };
// childSettings.position.x = dx + (this._settings.width / lx) / 2 - childSettings.width / 2;
// childSettings.position.y = dy + (this._settings.height / ly) / 2 - childSettings.height / 2;
//}
else {
childSettings.position.x = dx + childSettings.position.x;
childSettings.position.y = dy + childSettings.position.y;
}
//console.log(' >> ', dx.toFixed(2), dy.toFixed(2), childSettings.position.x.toFixed(2), childSettings.position.y.toFixed(2));
var child = EZGUI.create(childSettings, this.theme);
return child;
}
public addChild(child) {
if (child instanceof GUISprite) {
return this.addChildAt(child, this.container.children.length);
}
else {
return super.addChild(child);
}
}
public addChildAt(child, index) {
if (child instanceof GUISprite) {
var i = index;
//console.log('adding ', i);
var padTop = this._settings['padding-top'] || this._settings.padding || 0;
var padLeft = this._settings['padding-left'] || this._settings.padding || 0;
var swidth = this._settings.width - padLeft;
var sheight = this._settings.height - padTop;
var dx = padLeft;
var dy = padTop;
var lx = 1;
var ly = 1;
if (this._settings.layout != undefined) {
lx = this._settings.layout[0];
ly = this._settings.layout[1];
var x, y;
//horizontal layout
if (ly == null) {
x = i;
y = 0;
} else if (lx == null) {
x = 0;
y = i;
}
else {
var adjust = Math.floor(i / (lx * ly));
if (this._settings.dragY === false) {
dx += adjust * swidth;
dy -= adjust * sheight;
//ly = 1;
} else if (this._settings.dragX === false) {
//lx = 1;
//dx -= adjust * this._settings.width;
//dy += adjust * this._settings.height;
}
x = i % lx;
y = Math.floor(i / lx);
}
ly = ly || 1;
lx = lx || 1;
dx += x * (swidth / lx);
dy += y * (sheight / ly);
}
var childSettings = child._settings;
var pos = childSettings.position;
if (typeof pos == 'string') {
var parts = pos.split(' ');
var pos1 = parts[0];
var pos2 = parts[1];
//normalize pos
if (parts[0] == parts[1]) {
pos2 = undefined;
}
if ((parts[0] == 'top' && parts[2] == 'bottom') ||
(parts[0] == 'bottom' && parts[2] == 'top') ||
(parts[0] == 'left' && parts[2] == 'right') ||
(parts[0] == 'right' && parts[2] == 'left')
) {
pos1 = 'center';
pos2 = 'undefined';
}
if ((parts[0] == 'left' || parts[0] == 'right') && (parts[1] == 'top' || parts[1] == 'bottom')) {
pos1 = parts[1];
pos2 = parts[0];
}
if ((pos1 == 'left' || pos1 == 'right') && pos2 === undefined) {
pos2 = pos1;
pos1 = 'left';
}
childSettings.position = { x: dx, y: dy };
switch (pos1) {
case 'center':
childSettings.position.y = dy + (this._settings.height / ly) / 2 - childSettings.height / 2;
if (pos2 === undefined) childSettings.position.x = dx + (this._settings.width / lx) / 2 - childSettings.width / 2;
break;
case 'bottom':
childSettings.position.y = dy + (this._settings.height / ly) - childSettings.height - this._settings.padding;
break;
}
switch (pos2) {
case 'center':
childSettings.position.x = dx + (this._settings.width / lx) / 2 - childSettings.width / 2;
break;
case 'right':
childSettings.position.x = dx + (this._settings.width / lx) - childSettings.width - this._settings.padding;
break;
}
}
//if (childSettings.position == 'center') {
// childSettings.position = { x: 0, y: 0 };
// childSettings.position.x = dx + (this._settings.width / lx) / 2 - childSettings.width / 2;
// childSettings.position.y = dy + (this._settings.height / ly) / 2 - childSettings.height / 2;
//}
else {
childSettings.position.x = dx + childSettings.position.x;
childSettings.position.y = dy + childSettings.position.y;
}
child.position.x = childSettings.position.x;
child.position.y = childSettings.position.y;
child.guiParent = this;
if (child.phaserGroup) return this.container.addChild(child.phaserGroup);
else return this.container.addChild(child);
//return super.addChild(child);
}
else {
//return Compatibility.GUIDisplayObjectContainer.prototype.addChild.call(this, child, index);
return super.addChildAt(child, index);
}
}
}
EZGUI.registerComponents(Layout, 'Layout');
} | the_stack |
import * as React from "react";
import { animated, to } from "@react-spring/web";
import { Box } from "@chakra-ui/react";
import { useControls, useCreateStore, LevaInputs } from "leva";
import graphql from "babel-plugin-relay/macro";
import { useMutation, useQuery } from "relay-hooks";
import create from "zustand";
import { persist } from "zustand/middleware";
import * as Json from "fp-ts/Json";
import { flow, identity } from "fp-ts/function";
import * as E from "fp-ts/Either";
import * as io from "io-ts";
import { ThemedLevaPanel } from "./themed-leva-panel";
import { ChatPositionContext } from "./authenticated-app-shell";
import { useSelectedItems } from "./shared-token-state";
import { levaPluginTokenImage } from "./leva-plugin/leva-plugin-token-image";
import type { sharedTokenMenuUpdateManyMapTokenMutation } from "./__generated__/sharedTokenMenuUpdateManyMapTokenMutation.graphql";
import type { sharedTokenMenuReferenceNoteQuery } from "./__generated__/sharedTokenMenuReferenceNoteQuery.graphql";
import { State, StoreType } from "leva/dist/declarations/src/types";
import { levaPluginNotePreview } from "./leva-plugin/leva-plugin-note-preview";
const firstMapValue = <TItemValue extends any>(
map: Map<any, TItemValue>
): TItemValue => map.values().next().value as TItemValue;
const referenceIdSelector = (state: State): string | null =>
(state.data["referenceId"] as any)?.value ?? null;
const TokenMenuExpandedStateModel = io.type({
isTokenNoteDescriptionExpanded: io.boolean,
isTokenMenuExpanded: io.boolean,
});
const PersistedValue = <TType extends io.Type<any>>(stateModel: TType) =>
io.type({
version: io.number,
state: stateModel,
});
type TokenMenuExpandedStateModelType = io.TypeOf<
typeof TokenMenuExpandedStateModel
>;
type TokenMenuExpandedState = TokenMenuExpandedStateModelType & {
setIsTokenNoteDescriptionExpanded: (isExpanded: boolean) => void;
setIsTokenMenuExpanded: (isExpanded: boolean) => void;
};
const defaultTokenMenuExpandedStateModel: Readonly<TokenMenuExpandedStateModelType> =
{
isTokenNoteDescriptionExpanded: true,
isTokenMenuExpanded: true,
};
const deserializeTokenMenuExpandedState = flow(
Json.parse,
E.chainW(PersistedValue(TokenMenuExpandedStateModel).decode),
E.fold(
() => ({
version: 0,
state: { ...defaultTokenMenuExpandedStateModel },
}),
identity
)
);
const useTokenMenuExpandedState = create<TokenMenuExpandedState>(
persist(
(set) => ({
...defaultTokenMenuExpandedStateModel,
setIsTokenNoteDescriptionExpanded: (isTokenNoteDescriptionExpanded) =>
set({ isTokenNoteDescriptionExpanded }),
setIsTokenMenuExpanded: (isTokenMenuExpanded) =>
set({ isTokenMenuExpanded }),
}),
{
name: "tokenMenuExpandedState",
// we deserialize the value in a safe way :)
deserialize: deserializeTokenMenuExpandedState as any,
}
)
);
const tokenMenuStateSelector = (state: TokenMenuExpandedState) =>
[state.isTokenMenuExpanded, state.setIsTokenMenuExpanded] as const;
const useTokenMenuState = () =>
useTokenMenuExpandedState(tokenMenuStateSelector);
const tokenNoteDescriptionStateSelector = (state: TokenMenuExpandedState) =>
[
state.isTokenNoteDescriptionExpanded,
state.setIsTokenNoteDescriptionExpanded,
] as const;
const useTokenNoteDescriptionState = () =>
useTokenMenuExpandedState(tokenNoteDescriptionStateSelector);
export const SharedTokenMenu = (props: { currentMapId: string }) => {
const chatPosition = React.useContext(ChatPositionContext);
const [selectedItems] = useSelectedItems();
return (
<animated.div
style={{
position: "absolute",
bottom: 100,
right:
chatPosition !== null
? to(chatPosition.x, (value) => -value + 10 + chatPosition.width)
: 10,
// @ts-ignore
zIndex: 1,
width: 300,
}}
onKeyDown={(ev) => ev.stopPropagation()}
>
{selectedItems.size === 0 ? null : selectedItems.size === 1 ? (
<SingleTokenPanels store={firstMapValue(selectedItems)} />
) : (
<MultiTokenPanel currentMapId={props.currentMapId} />
)}
</animated.div>
);
};
const SharedTokenMenuReferenceNoteQuery = graphql`
query sharedTokenMenuReferenceNoteQuery($noteId: ID!) {
note(documentId: $noteId) {
id
documentId
title
content
}
}
`;
const TokenNotePreview = (props: {
id: string;
markdown: string;
title: string;
}) => {
const store = useCreateStore();
useControls(
{
" ": levaPluginNotePreview({
value: {
id: props.id,
markdown: props.markdown,
},
}),
},
{ store }
);
const [show, setShow] = useTokenNoteDescriptionState();
return (
<Box marginBottom="3">
<ThemedLevaPanel
store={store}
fill={true}
hideCopyButton
titleBar={{
filter: false,
drag: false,
title: props.title,
}}
collapsed={{
collapsed: !show,
onChange: (collapsed) => setShow(!collapsed),
}}
/>
</Box>
);
};
const NoteAsidePreview = (props: { noteId: string }) => {
const noteProps = useQuery<sharedTokenMenuReferenceNoteQuery>(
SharedTokenMenuReferenceNoteQuery,
{ noteId: props.noteId }
);
if (noteProps.data?.note == null) {
return null;
}
return (
<TokenNotePreview
id={noteProps.data.note.documentId}
markdown={noteProps.data.note.content}
title={noteProps.data.note.title}
/>
);
};
const SingleTokenPanels = (props: { store: StoreType }) => {
const referenceId = props.store.useStore(referenceIdSelector);
const [show, setShow] = useTokenMenuState();
return (
<>
{referenceId == null ? null : <NoteAsidePreview noteId={referenceId} />}
<ThemedLevaPanel
store={props.store}
fill={true}
hideCopyButton
titleBar={{
filter: false,
drag: false,
title: "Token Properties",
}}
collapsed={{
collapsed: !show,
onChange: (collapsed) => setShow(!collapsed),
}}
/>
</>
);
};
const SharedTokenMenuUpdateManyMapTokenMutation = graphql`
mutation sharedTokenMenuUpdateManyMapTokenMutation(
$input: MapTokenUpdateManyInput!
) {
mapTokenUpdateMany(input: $input)
}
`;
const MultiTokenPanel = (props: { currentMapId: string }) => {
const store = useCreateStore();
const [selectedItems] = useSelectedItems();
const allSelectedItemsRef = React.useRef(selectedItems);
React.useEffect(() => {
allSelectedItemsRef.current = selectedItems;
});
let tokenImageId: null | string = null;
for (const store of selectedItems.values()) {
let currentTokenImageId = store.get("tokenImageId");
if (currentTokenImageId) {
tokenImageId = "__ID_THAT_WILL_NOT_COLLIDE_SO_WE_CAN_CHOOSE_ANY_IMAGE__";
break;
}
}
const [mutate] = useMutation<sharedTokenMenuUpdateManyMapTokenMutation>(
SharedTokenMenuUpdateManyMapTokenMutation
);
const [, set] = useControls(
() => {
const firstItem = selectedItems.values().next().value;
return {
color: {
type: LevaInputs.COLOR,
label: "Color",
value: firstItem.get("color"),
onChange: (color: string, _, { initial, fromPanel }) => {
if (initial || !fromPanel) {
return;
}
for (const store of allSelectedItemsRef.current.values()) {
store.set({ color }, false);
}
},
onEditEnd: (color: string) => {
mutate({
variables: {
input: {
mapId: props.currentMapId,
tokenIds: Array.from(allSelectedItemsRef.current.keys()),
properties: {
color,
},
},
},
});
},
},
isVisibleForPlayers: {
type: LevaInputs.BOOLEAN,
label: "Visible to players",
value: firstItem.get("isVisibleForPlayers"),
onChange: (
isVisibleForPlayers: boolean,
_,
{ initial, fromPanel }
) => {
if (initial || !fromPanel) {
return;
}
for (const store of allSelectedItemsRef.current.values()) {
store.set({ isVisibleForPlayers }, false);
}
mutate({
variables: {
input: {
mapId: props.currentMapId,
tokenIds: Array.from(allSelectedItemsRef.current.keys()),
properties: {
isVisibleForPlayers,
},
},
},
});
},
},
isMovableByPlayers: {
type: LevaInputs.BOOLEAN,
label: "Movable by players",
value: firstItem.get("isMovableByPlayers"),
onChange: (
isMovableByPlayers: boolean,
_,
{ initial, fromPanel }
) => {
if (initial || !fromPanel) {
return;
}
for (const store of allSelectedItemsRef.current.values()) {
store.set({ isMovableByPlayers }, false);
}
mutate({
variables: {
input: {
mapId: props.currentMapId,
tokenIds: Array.from(allSelectedItemsRef.current.keys()),
properties: {
isMovableByPlayers,
},
},
},
});
},
},
tokenImageId: levaPluginTokenImage({
value: tokenImageId,
onChange: (
tokenImageId: null | string,
_,
{ initial, fromPanel }
) => {
if (initial || !fromPanel) {
return;
}
for (const store of allSelectedItemsRef.current.values()) {
store.set({ tokenImageId }, false);
}
mutate({
variables: {
input: {
mapId: props.currentMapId,
tokenIds: Array.from(allSelectedItemsRef.current.keys()),
properties: {
tokenImageId,
},
},
},
});
},
transient: false,
}),
};
},
{ store }
);
// Workaround as dependency array does not seem to work atm :(
React.useEffect(() => {
set({ tokenImageId });
}, [tokenImageId]);
const [show, setShow] = useTokenMenuState();
return (
<ThemedLevaPanel
store={store}
fill={true}
hideCopyButton
titleBar={{
filter: false,
drag: false,
title: `${selectedItems.size} Token selected`,
}}
collapsed={{
collapsed: !show,
onChange: (collapsed) => setShow(!collapsed),
}}
/>
);
}; | the_stack |
import '../../../test/common-test-setup-karma';
import './gr-formatted-text';
import {
GrFormattedText,
Block,
ListBlock,
TextBlock,
QuoteBlock,
} from './gr-formatted-text';
const basicFixture = fixtureFromElement('gr-formatted-text');
suite('gr-formatted-text tests', () => {
let element: GrFormattedText;
function assertTextBlock(block: Block, type: string, text: string) {
assert.equal(block.type, type);
const textBlock = block as TextBlock;
assert.equal(textBlock.text, text);
}
function assertListBlock(block: Block, items: string[]) {
assert.equal(block.type, 'list');
const listBlock = block as ListBlock;
assert.deepEqual(listBlock.items, items);
}
function assertQuoteBlock(block: Block): QuoteBlock {
assert.equal(block.type, 'quote');
return block as QuoteBlock;
}
setup(() => {
element = basicFixture.instantiate();
});
test('parse empty', () => {
assert.lengthOf(element._computeBlocks(''), 0);
});
test('parse simple', () => {
const comment = 'Para1';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
assertTextBlock(result[0], 'paragraph', comment);
});
test('parse multiline para', () => {
const comment = 'Para 1\nStill para 1';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
assertTextBlock(result[0], 'paragraph', comment);
});
test('parse para break without special blocks', () => {
const comment = 'Para 1\n\nPara 2\n\nPara 3';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
assertTextBlock(result[0], 'paragraph', comment);
});
test('parse quote', () => {
const comment = '> Quote text';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
const quoteBlock = assertQuoteBlock(result[0]);
assert.lengthOf(quoteBlock.blocks, 1);
assertTextBlock(quoteBlock.blocks[0], 'paragraph', 'Quote text');
});
test('parse quote lead space', () => {
const comment = ' > Quote text';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
const quoteBlock = assertQuoteBlock(result[0]);
assert.lengthOf(quoteBlock.blocks, 1);
assertTextBlock(quoteBlock.blocks[0], 'paragraph', 'Quote text');
});
test('parse multiline quote', () => {
const comment = '> Quote line 1\n> Quote line 2\n > Quote line 3\n';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
const quoteBlock = assertQuoteBlock(result[0]);
assert.lengthOf(quoteBlock.blocks, 1);
assertTextBlock(
quoteBlock.blocks[0],
'paragraph',
'Quote line 1\nQuote line 2\nQuote line 3'
);
});
test('parse pre', () => {
const comment = ' Four space indent.';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
assertTextBlock(result[0], 'pre', comment);
});
test('parse one space pre', () => {
const comment = ' One space indent.\n Another line.';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
assertTextBlock(result[0], 'pre', comment);
});
test('parse tab pre', () => {
const comment = '\tOne tab indent.\n\tAnother line.\n Yet another!';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
assertTextBlock(result[0], 'pre', comment);
});
test('parse star list', () => {
const comment = '* Item 1\n* Item 2\n* Item 3';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
assertListBlock(result[0], ['Item 1', 'Item 2', 'Item 3']);
});
test('parse dash list', () => {
const comment = '- Item 1\n- Item 2\n- Item 3';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
assertListBlock(result[0], ['Item 1', 'Item 2', 'Item 3']);
});
test('parse mixed list', () => {
const comment = '- Item 1\n* Item 2\n- Item 3\n* Item 4';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
assertListBlock(result[0], ['Item 1', 'Item 2', 'Item 3', 'Item 4']);
});
test('parse mixed block types', () => {
const comment =
'Paragraph\nacross\na\nfew\nlines.' +
'\n\n' +
'> Quote\n> across\n> not many lines.' +
'\n\n' +
'Another paragraph' +
'\n\n' +
'* Series\n* of\n* list\n* items' +
'\n\n' +
'Yet another paragraph' +
'\n\n' +
'\tPreformatted text.' +
'\n\n' +
'Parting words.';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 7);
assertTextBlock(
result[0],
'paragraph',
'Paragraph\nacross\na\nfew\nlines.\n'
);
const quoteBlock = assertQuoteBlock(result[1]);
assert.lengthOf(quoteBlock.blocks, 1);
assertTextBlock(
quoteBlock.blocks[0],
'paragraph',
'Quote\nacross\nnot many lines.'
);
assertTextBlock(result[2], 'paragraph', 'Another paragraph\n');
assertListBlock(result[3], ['Series', 'of', 'list', 'items']);
assertTextBlock(result[4], 'paragraph', 'Yet another paragraph\n');
assertTextBlock(result[5], 'pre', '\tPreformatted text.');
assertTextBlock(result[6], 'paragraph', 'Parting words.');
});
test('bullet list 1', () => {
const comment = 'A\n\n* line 1';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertTextBlock(result[0], 'paragraph', 'A\n');
assertListBlock(result[1], ['line 1']);
});
test('bullet list 2', () => {
const comment = 'A\n\n* line 1\n* 2nd line';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertTextBlock(result[0], 'paragraph', 'A\n');
assertListBlock(result[1], ['line 1', '2nd line']);
});
test('bullet list 3', () => {
const comment = 'A\n* line 1\n* 2nd line\n\nB';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 3);
assertTextBlock(result[0], 'paragraph', 'A');
assertListBlock(result[1], ['line 1', '2nd line']);
assertTextBlock(result[2], 'paragraph', 'B');
});
test('bullet list 4', () => {
const comment = '* line 1\n* 2nd line\n\nB';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertListBlock(result[0], ['line 1', '2nd line']);
assertTextBlock(result[1], 'paragraph', 'B');
});
test('bullet list 5', () => {
const comment =
'To see this bug, you have to:\n' +
'* Be on IMAP or EAS (not on POP)\n' +
'* Be very unlucky\n';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertTextBlock(result[0], 'paragraph', 'To see this bug, you have to:');
assertListBlock(result[1], [
'Be on IMAP or EAS (not on POP)',
'Be very unlucky',
]);
});
test('bullet list 6', () => {
const comment =
'To see this bug,\n' +
'you have to:\n' +
'* Be on IMAP or EAS (not on POP)\n' +
'* Be very unlucky\n';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertTextBlock(result[0], 'paragraph', 'To see this bug,\nyou have to:');
assertListBlock(result[1], [
'Be on IMAP or EAS (not on POP)',
'Be very unlucky',
]);
});
test('dash list 1', () => {
const comment = 'A\n- line 1\n- 2nd line';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertTextBlock(result[0], 'paragraph', 'A');
assertListBlock(result[1], ['line 1', '2nd line']);
});
test('dash list 2', () => {
const comment = 'A\n- line 1\n- 2nd line\n\nB';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 3);
assertTextBlock(result[0], 'paragraph', 'A');
assertListBlock(result[1], ['line 1', '2nd line']);
assertTextBlock(result[2], 'paragraph', 'B');
});
test('dash list 3', () => {
const comment = '- line 1\n- 2nd line\n\nB';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertListBlock(result[0], ['line 1', '2nd line']);
assertTextBlock(result[1], 'paragraph', 'B');
});
test('nested list will NOT be recognized', () => {
// will be rendered as two separate lists
const comment = '- line 1\n - line with indentation\n- line 2';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 3);
assertListBlock(result[0], ['line 1']);
assertTextBlock(result[1], 'pre', ' - line with indentation');
assertListBlock(result[2], ['line 2']);
});
test('pre format 1', () => {
const comment = 'A\n This is pre\n formatted';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertTextBlock(result[0], 'paragraph', 'A');
assertTextBlock(result[1], 'pre', ' This is pre\n formatted');
});
test('pre format 2', () => {
const comment = 'A\n This is pre\n formatted\n\nbut this is not';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 3);
assertTextBlock(result[0], 'paragraph', 'A');
assertTextBlock(result[1], 'pre', ' This is pre\n formatted');
assertTextBlock(result[2], 'paragraph', 'but this is not');
});
test('pre format 3', () => {
const comment = 'A\n Q\n <R>\n S\n\nB';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 3);
assertTextBlock(result[0], 'paragraph', 'A');
assertTextBlock(result[1], 'pre', ' Q\n <R>\n S');
assertTextBlock(result[2], 'paragraph', 'B');
});
test('pre format 4', () => {
const comment = ' Q\n <R>\n S\n\nB';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertTextBlock(result[0], 'pre', ' Q\n <R>\n S');
assertTextBlock(result[1], 'paragraph', 'B');
});
test('pre format 5', () => {
const comment = ' Q\n <R>\n S\n \nB';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertTextBlock(result[0], 'pre', ' Q\n <R>\n S');
assertTextBlock(result[1], 'paragraph', ' \nB');
});
test('quote 1', () => {
const comment = "> I'm happy with quotes!!";
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
const quoteBlock = assertQuoteBlock(result[0]);
assert.lengthOf(quoteBlock.blocks, 1);
assertTextBlock(
quoteBlock.blocks[0],
'paragraph',
"I'm happy with quotes!!"
);
});
test('quote 2', () => {
const comment = "> I'm happy\n > with quotes!\n\nSee above.";
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
const quoteBlock = assertQuoteBlock(result[0]);
assert.lengthOf(quoteBlock.blocks, 1);
assertTextBlock(
quoteBlock.blocks[0],
'paragraph',
"I'm happy\nwith quotes!"
);
assertTextBlock(result[1], 'paragraph', 'See above.');
});
test('quote 3', () => {
const comment = 'See this said:\n > a quoted\n > string block\n\nOK?';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 3);
assertTextBlock(result[0], 'paragraph', 'See this said:');
const quoteBlock = assertQuoteBlock(result[1]);
assert.lengthOf(quoteBlock.blocks, 1);
assertTextBlock(
quoteBlock.blocks[0],
'paragraph',
'a quoted\nstring block'
);
assertTextBlock(result[2], 'paragraph', 'OK?');
});
test('nested quotes', () => {
const comment = ' > > prior\n > \n > next\n';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
const outerQuoteBlock = assertQuoteBlock(result[0]);
assert.lengthOf(outerQuoteBlock.blocks, 2);
const nestedQuoteBlock = assertQuoteBlock(outerQuoteBlock.blocks[0]);
assert.lengthOf(nestedQuoteBlock.blocks, 1);
assertTextBlock(nestedQuoteBlock.blocks[0], 'paragraph', 'prior');
assertTextBlock(outerQuoteBlock.blocks[1], 'paragraph', 'next');
});
test('code 1', () => {
const comment = '```\n// test code\n```';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
assertTextBlock(result[0], 'code', '// test code');
});
test('code 2', () => {
const comment = 'test code\n```// test code```';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertTextBlock(result[0], 'paragraph', 'test code');
assertTextBlock(result[1], 'code', '// test code');
});
test('not a code block', () => {
const comment = 'test code\n```// test code';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 1);
assertTextBlock(result[0], 'paragraph', 'test code\n```// test code');
});
test('not a code block 2', () => {
const comment = 'test code\n```\n// test code';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertTextBlock(result[0], 'paragraph', 'test code');
assertTextBlock(result[1], 'paragraph', '```\n// test code');
});
test('not a code block 3', () => {
const comment = 'test code\n```';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 2);
assertTextBlock(result[0], 'paragraph', 'test code');
assertTextBlock(result[1], 'paragraph', '```');
});
test('mix all 1', () => {
const comment =
' bullets:\n- bullet 1\n- bullet 2\n\ncode example:\n' +
'```// test code```\n\n> reference is here';
const result = element._computeBlocks(comment);
assert.lengthOf(result, 5);
assert.equal(result[0].type, 'pre');
assert.equal(result[1].type, 'list');
assert.equal(result[2].type, 'paragraph');
assert.equal(result[3].type, 'code');
assert.equal(result[4].type, 'quote');
});
}); | the_stack |
import {Observable} from "data/observable";
import {ObservableArray} from "data/observable-array";
import TypeUtils = require("utils/types");
import {VirtualArray} from "data/virtual-array";
/**
* Regular expression for trimming a string
* at the beginning and the end.
*/
export const REGEX_TRIM: RegExp = /^\s+|\s+$/gm;
/**
* Describes a grouping.
*/
export interface IGrouping<K, T> extends IEnumerable<T> {
/**
* Gets the key.
*/
key: K;
}
/**
* Describes a sequence.
*/
export interface IEnumerable<T> {
/**
* Applies an accumulator function over the sequence.
*
* @param {Function} accumulator The accumulator.
* @param any [defaultValue] The value to return if sequence is empty.
*
* @return any The final accumulator value or the default value.
*/
aggregate(accumulator: any, defaultValue?: any): any;
/**
* Checks if all elements of the sequence match a condition.
*
* @param {Function} predicate The condition.
*
* @return {Boolean} All items match condition or not. If sequence is empty (true) is returned.
*/
all(predicate: any): boolean;
/**
* Checks if at least one element of the sequence matches a condition.
*
* @param {Function} [predicate] The condition.
*
* @return {Boolean} At least one element was found that matches the condition.
* If condition is not defined, the method checks if sequence contains at least one element.
*/
any(predicate?: any): boolean;
/**
* Computes the average of that sequence.
*
* @param any [defaultValue] The (default) value to return if sequence is empty.
*
* @return any The average of the sequence or the default value.
*/
average(defaultValue?: any): any;
/**
* Casts all items to a specific type.
*
* @param {String} type The target type.
*
* @return any The new sequence with the casted items.
*/
cast(type: string): IEnumerable<any>;
/**
* Concats the items of that sequence with the items of another one.
*
* @param any second The other sequence.
*
* @throws Value for other sequence is invalid.
*
* @return {IEnumerable} The new sequence.
*/
concat(second: any): IEnumerable<T>;
/**
* Checks if that sequence contains an item.
*
* @param any item The item to search for.
* @param {Function} [equalityComparer] The custom equality comparer to use.
*
* @return {Boolean} Contains item or not.
*/
contains(item: T, equalityComparer?: any): boolean;
/**
* Returns the number of elements.
*
* @param {Function} [predicate] The custom condition to use.
*
* @return {Number} The number of (matching) elements.
*/
count(predicate?: any): number;
/**
* Gets the current element.
*/
current: T;
/**
* Returns a default sequence if that sequence is empty.
*
* @param ...any [defaultItem] One or more items for the default sequence.
*
* @return {IEnumerable} A default sequence or that sequence if it is not empty.
*/
defaultIfEmpty(...defaultItems: T[]): IEnumerable<T>;
/**
* Removes the duplicates from that sequence.
*
* @param {Function} [equalityComparer] The custom equality comparer to use.
*
* @throws No valid equality comparer.
*
* @return {IEnumerable} The new sequence.
*/
distinct(equalityComparer?: any): IEnumerable<T>;
/**
* Iterates over the elements of that sequence.
*
* @param {Function} action The callback that is executed for an item.
*
* @return any The result of the last execution.
*/
each(action: any): any;
/**
* Return an element of the sequence at a specific index.
*
* @param {Number} index The zero based index.
*
* @throws Element was not found.
*
* @return any The element.
*/
elementAt(index: number): T;
/**
* Tries to return an element of the sequence at a specific index.
*
* @param {Number} index The zero based index.
* @param any [defaultValue] The (default) value to return if no matching element was found.
*
* @return any The element or the default value.
*/
elementAtOrDefault(index: number, defaultValue?: any): any;
/**
* Returns the items of that sequence except a list of specific ones.
*
* @param any second The sequence with the items to remove.
* @param any [equalityComparer] The custom equality comparer to use.
*
* @throws The second sequence and/or the equality comparer is invalid.
*
* @return {IEnumerable} The new sequence.
*/
except(second: any, equalityComparer?: any): IEnumerable<T>;
/**
* Returns the first element of the sequence.
*
* @param {Function} [predicate] The custom condition to use.
*
* @throws Sequence contains no (matching) element.
*
* @return any The first (matching) element.
*/
first(predciate?: any): T;
/**
* Tries to return the first element of the sequence.
*
* @param {Function} [predicateOrDefaultValue] The custom condition to use.
* If only one argument is defined and that value is NO function it will be handled as default value.
* @param any [defaultValue] The (default) value to return if no matching element was found.
*
* @return any The first (matching) element or the default value.
*/
firstOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any;
/**
* Groups the elements of the sequence.
*
* @param any keySelector The group key selector.
* @param any [keyEqualityComparer] The custom equality comparer for the keys to use.
*
* @throw At least one argument is invalid.
*
* @return {IEnumerable} The new sequence.
*/
groupBy<K>(keySelector: any, keyEqualityComparer?: any): IEnumerable<IGrouping<K, T>>;
/**
* Correlates the elements of that sequence and another based on matching keys and groups them.
*
* @param any inner The other sequence.
* @param any outerKeySelector The key selector for the items of that sequence.
* @param any innerKeySelector The key selector for the items of the other sequence.
* @param any resultSelector The function that provides the result value for two matching elements.
* @param any [keyEqualityComparer] The custom equality comparer for the keys to use.
*
* @throw At least one argument is invalid.
*
* @return {IEnumerable} The new sequence.
*/
groupJoin<U>(inner: any,
outerKeySelector: any, innerKeySelector: any,
resultSelector: any,
keyEqualityComparer?: any): IEnumerable<U>;
/**
* Returns the intersection between this and a second sequence.
*
* @param any second The second sequence.
* @param any [equalityComparer] The custom equality comparer to use.
*
* @throws The second sequence and/or the equality comparer is invalid.
*
* @return {IEnumerable} The new sequence.
*/
intersect(second: any, equalityComparer?: any): IEnumerable<T>;
/**
* Gets the item key.
*/
itemKey: any;
/**
* Gets if the current state of that sequence is valid or not.
*/
isValid: boolean;
/**
* Correlates the elements of that sequence and another based on matching keys.
*
* @param any inner The other sequence.
* @param any outerKeySelector The key selector for the items of that sequence.
* @param any innerKeySelector The key selector for the items of the other sequence.
* @param any resultSelector The function that provides the result value for two matching elements.
* @param any [keyEqualityComparer] The custom equality comparer for the keys to use.
*
* @throw At least one argument is invalid.
*
* @return {IEnumerable} The new sequence.
*/
join<U>(inner: any,
outerKeySelector: any, innerKeySelector: any,
resultSelector: any,
keyEqualityComparer?: any);
/**
* Returns the last element of the sequence.
*
* @param {Function} [predicate] The custom condition to use.
*
* @throws Sequence contains no (matching) element.
*
* @return any The last (matching) element.
*/
last(predicate?: any): any;
/**
* Tries to return the last element of the sequence.
*
* @param {Function} [predicateOrDefaultValue] The custom condition to use.
* If only one argument is defined and that value is NO function it will be handled as default value.
* @param any [defaultValue] The (default) value to return if no matching element was found.
*
* @return any The last (matching) element or the default value.
*/
lastOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any;
/**
* Tries to return the maximum value of the sequence.
*
* @param any [defaultValue] The (default) value to return if sequence is empty.
*
* @return any The maximum or the default value.
*/
max(defaultValue?: any): any;
/**
* Tries to return the minimum value of the sequence.
*
* @param any [defaultValue] The (default) value to return if sequence is empty.
*
* @return any The minimum or the default value.
*/
min(defaultValue?: any): any;
/**
* Tries to move to the next item.
*
* @return {Boolean} Operation was successful or not.
*/
moveNext(): boolean;
/**
* Returns elements of a specific type.
*
* @param {String} type The type.
*
* @return {IEnumerable} The new sequence.
*/
ofType(type: string): IEnumerable<any>;
/**
* Sorts the elements of that sequence in ascending order by using the values itself as keys.
*
* @param any [comparer] The custom key comparer to use.
*
* @throws The comparer is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
order(comparer?: any): IOrderedEnumerable<T>;
/**
* Sorts the elements of that sequence in ascending order.
*
* @param any selector The key selector.
* @param any [comparer] The custom key comparer to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
orderBy(selector: any, comparer?: any): IOrderedEnumerable<T>;
/**
* Sorts the elements of that sequence in descending order.
*
* @param any selector The key selector.
* @param any [comparer] The custom key comparer to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
orderByDescending(selector: any, comparer?: any): IOrderedEnumerable<T>;
/**
* Sorts the elements of that sequence in descending order by using the values as keys.
*
* @param any [comparer] The custom key comparer to use.
*
* @throws The comparer is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
orderDescending(comparer?: any): IOrderedEnumerable<T>;
/**
* Pushes the items of that sequence to an array.
*
* @param {any} arr The target array.
*
* @chainable
*/
pushToArray(arr: T[] | ObservableArray<T>): IEnumerable<T>;
/**
* Resets the sequence.
*
* @throws Reset is not possible.
*/
reset();
/**
* Reverses the order of the elements.
*
* @method reverse
*
* @return {IOrderedEnumerable} The new sequence.
*/
reverse(): IEnumerable<T>;
/**
* Projects the elements of that sequence to new values.
*
* @param {Function} selector The selector.
*
* @throws Selector is no valid value for use as function.
*
* @return {IEnumerable} The new sequence.
*/
select<U>(selector: any): IEnumerable<U>;
/**
* Projects the elements of that sequence to new sequences that converted to one flatten sequence.
*
* @param {Function} selector The selector.
*
* @throws Selector is no valid value for use as function.
*
* @return {IEnumerable} The new sequence.
*/
selectMany<U>(selector: any): IEnumerable<U>;
/**
* Checks if that sequence has the same elements as another one.
*
* @param any other The other sequence.
* @param any [equalityComparer] The custom equality comparer to use.
*
* @throws Other sequence and/or equality comparer are invalid values.
*
* @return {IEnumerable} Both sequences are the same or not
*/
sequenceEqual(other: any, equalityComparer?: any): boolean;
/**
* Returns the one and only element of the sequence.
*
* @param {Function} [predicate] The custom condition to use.
*
* @throws Sequence contains more than one matching element or no element.
*
* @return T The only (matching) element or the default value.
*/
single(predicate?: any): T;
/**
* Tries to return the one and only element of the sequence.
*
* @param {Function} [predicateOrDefaultValue] The custom condition to use.
* If only one argument is defined and that value is NO function it will be handled as default value.
* @param any [defaultValue] The (default) value to return if no matching element was found.
*
* @throws Sequence contains more than one matching element.
*
* @return any The only (matching) element or the default value.
*/
singleOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any;
/**
* Skips a number of elements.
*
* @param {Number} cnt The number of elements to skip.
*
* @return {IEnumerable} The new sequence.
*/
skip(cnt: number): IEnumerable<T>;
/**
* Takes all elements but the last one.
*
* @return {IEnumerable} The new sequence.
*/
skipLast(): IEnumerable<T>;
/**
* Skips elements of that sequence while a condition matches.
*
* @method skipWhile
*
* @param {Function} predicate The condition to use.
*
* @throws Predicate is no valid value.
*
* @return {IEnumerable} The new sequence.
*/
skipWhile(predicate: any): IEnumerable<T>;
/**
* Calculates the sum of the elements.
*
* @param any defaultValue The value to return if sequence is empty.
*
* @return any The sum or the default value.
*/
sum(defaultValue?: any): any;
/**
* Takes a number of elements.
*
* @param {Number} cnt The number of elements to take.
*
* @return {IEnumerable} The new sequence.
*/
take(cnt: number): IEnumerable<T>;
/**
* Takes elements while a condition matches.
*
* @param {Function} predicate The condition to use.
*
* @throws Predicate is no valid value.
*
* @return {IEnumerable} The new sequence.
*/
takeWhile(predicate: any): IEnumerable<T>;
/**
* Returns the elements of that sequence as array.
*
* @return {Array} The sequence as new array.
*/
toArray(): T[];
/**
* Creates a lookup object from the sequence.
*
* @param any keySelector The group key selector.
* @param any [keyEqualityComparer] The custom equality comparer for the keys to use.
*
* @throw At least one argument is invalid.
*
* @return {Object} The lookup array.
*/
toLookup(keySelector: any, keyEqualityComparer?: any): any;
/**
* Creates a new object from the items of that sequence.
*
* @param any [keySelector] The custom key selector to use.
*
* @throws Key selector is invalid.
*
* @return {Object} The new object.
*/
toObject(keySelector?: any): any;
/**
* Creates a new observable object from the items of that sequence.
*
* @param any [keySelector] The custom key selector to use.
*
* @throws Key selector is invalid.
*
* @return {Observable} The new object.
*/
toObservable(keySelector?: any): Observable;
/**
* Creates a new observable array from the items of that sequence.
*
* @return {ObservableArray} The new array.
*/
toObservableArray(): ObservableArray<T>;
/**
* Creates a new virtual array from the items of that sequence.
*
* @return {VirtualArray} The new array.
*/
toVirtualArray(): VirtualArray<T>;
/**
* Produces the set union of that sequence and another.
*
* @param any second The second sequence.
* @param {Function} [equalityComparer] The custom equality comparer to use.
*
* @throws Sequence or equality comparer are no valid values.
*
* @return {IEnumerable} The new sequence.
*/
union(second: any, equalityComparer?: any): IEnumerable<T>;
/**
* Filters the elements of that sequence.
*
* @param {Function} predicate The predicate to use.
*
* @throws Predicate is no valid function / lambda expression.
*
* @return {IEnumerable} The new sequence.
*/
where(predicate: any): IEnumerable<T>;
/**
* Applies a specified function to the corresponding elements of that sequence
* and another, producing a sequence of the results.
*
* @param any second The second sequence.
* @param {Function} selector The selector for the combined result items of the elements of the two sequences.
*
* @throws Sequence or selector are no valid values.
*
* @return {IEnumerable} The new sequence.
*/
zip<U>(second: any, selector: any): IEnumerable<U>;
}
/**
* Describes the context of a current sequence item.
*/
export interface IEnumerableItemContext<T> {
/**
* Gets or sets if operation should be cancelled or not.
*/
cancel?: boolean;
/**
* Gets the zero based index.
*/
index?: number;
/**
* Gets the underlying item.
*/
item: T;
/**
* Gets the underlying key.
*/
key: any;
/**
* Gets the underlying sequence.
*/
sequence: IEnumerable<T>;
}
/**
* Describes an ordered sequence.
*/
export interface IOrderedEnumerable<T> extends IEnumerable<T> {
/**
* Performs a subsequent ordering of the elements in that sequence in ascending order,
* using the values itself as keys.
*
* @param any [comparer] The custom key comparer to use.
*
* @throws The comparer is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
then(comparer?: any): IOrderedEnumerable<T>;
/**
* Performs a subsequent ordering of the elements in that sequence in ascending order, according to a key.
*
* @param any selector The key selector.
* @param any [comparer] The custom key comparer to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
thenBy(selector: any, comparer?: any): IOrderedEnumerable<T>;
/**
* Performs a subsequent ordering of the elements in that sequence in descending order, according to a key.
*
* @param any selector The key selector.
* @param any [comparer] The custom key comparer to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
thenByDescending(selector: any, comparer?: any): IOrderedEnumerable<T>;
/**
* Performs a subsequent ordering of the elements in that sequence in descending order,
* using the values as keys.
*
* @param any [comparer] The custom key comparer to use.
*
* @throws The comparer is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
thenDescending(comparer?: any): IOrderedEnumerable<T>;
}
/**
* A basic sequence.
*/
export abstract class Sequence<T> implements IEnumerable<T> {
/**
* The custom selector.
*/
protected _selector: (x: T) => any;
/** @inheritdoc */
public aggregate(accumulator: any, defaultValue?: any) {
var acc: (result: any, x: T, index: number, ctx: IEnumerableItemContext<T>) => any = asFunc(accumulator);
var index = -1;
var aggResult = defaultValue;
var isFirst = true;
while (this.moveNext()) {
var ctx = new EnumerableItemContext<T>(this, ++index);
if (!isFirst) {
aggResult = acc(aggResult,
ctx.item, ctx.index, ctx);
}
else {
aggResult = ctx.item;
isFirst = false;
}
if (ctx.cancel) {
break;
}
}
return aggResult;
}
/** @inheritdoc */
public all(predicate: any): boolean {
predicate = asFunc(predicate);
var index = -1;
while (this.moveNext()) {
var ctx = new EnumerableItemContext<T>(this, ++index);
if (!predicate(ctx.item, ctx.index, ctx)) {
return false;
}
if (ctx.cancel) {
break;
}
}
return true;
}
/** @inheritdoc */
public any(predicate?: any): boolean {
predicate = toPredicateSafe(predicate);
var index = -1;
while (this.moveNext()) {
var ctx = new EnumerableItemContext<T>(this, ++index);
if (predicate(ctx.item, ctx.index, ctx)) {
return true;
}
if (ctx.cancel) {
break;
}
}
return false;
}
/** @inheritdoc */
public average(defaultValue?: any): any {
var cnt = 0;
var sum = 0;
while (this.moveNext()) {
sum += parseFloat("" + this.current);
++cnt;
}
return cnt > 0 ? (sum / cnt)
: defaultValue;
}
/** @inheritdoc */
public cast(type: string): IEnumerable<any> {
if (type !== null) {
if (TypeUtils.isUndefined(type)) {
type = '';
}
else {
type = type.replace(REGEX_TRIM, '');
}
}
return this.select(function(x) {
if (typeof x === type) {
return x;
}
if (type === null) {
return null;
}
switch (type) {
case '':
return x;
case 'null':
return null;
case 'undefined':
return undefined;
case 'number':
if (!x) {
return 0.0;
}
if (!isNaN(x)) {
return x;
}
return parseFloat(x);
case 'float':
if (!x) {
return 0.0;
}
return parseFloat(x);
case 'int':
case 'integer':
if (!x) {
return 0;
}
return parseInt(x);
case 'str':
case 'string':
if (!x) {
return "";
}
return "" + x;
case 'enumerable':
case 'seq':
case 'sequence':
return asEnumerable(x);
case 'array':
case 'Array':
return asEnumerable(x).toArray();
case 'Observable':
case 'observable':
return asEnumerable(x).toObservable();
case 'observablearray':
case 'observableArray':
case 'ObservableArray':
return asEnumerable(x).toObservableArray();
case 'bool':
case 'boolean':
return x ? true : false;
case 'func':
case 'function':
return function() { return x; };
default:
throw "Cannot not cast '" + x + "' to '" + type + "'!";
}
});
}
/** @inheritdoc */
public concat(second: any): IEnumerable<T> {
var newItems: T[] = [];
var appendItems = function(seq: IEnumerable<T>) {
while (seq.moveNext()) {
newItems.push(seq.current);
}
};
appendItems(this);
appendItems(asEnumerable(second));
return fromArray(newItems);
}
/** @inheritdoc */
public contains(item: T, equalityComparer?: any): boolean {
equalityComparer = toEqualityComparerSafe(equalityComparer);
return this.any((x: T) => equalityComparer(x, item));
}
/** @inheritdoc */
public count(predicate?: any): number {
predicate = toPredicateSafe(predicate);
var index = -1;
var cnt = 0;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
if (predicate(ctx.item, ctx.index, ctx)) {
++cnt;
}
if (ctx.cancel) {
break;
}
}
return cnt;
}
/** @inheritdoc */
public get current(): T {
return this.selectInner(this.getCurrent());
}
/** @inheritdoc */
public defaultIfEmpty(...defaultItems: T[]): IEnumerable<T> {
if (!this.isValid) {
return fromArray(arguments);
}
return this;
}
/** @inheritdoc */
public distinct(equalityComparer?: any): IEnumerable<T> {
equalityComparer = toEqualityComparerSafe(equalityComparer);
var distinctedItems: T[] = [];
while (this.moveNext()) {
var curItem = this.current;
var alreadyInList = false;
for (var i = 0; i < distinctedItems.length; i++) {
if (equalityComparer(curItem, distinctedItems[i])) {
alreadyInList = true;
break;
}
}
if (!alreadyInList) {
distinctedItems.push(curItem);
}
}
return fromArray(distinctedItems);
}
/** @inheritdoc */
public each(action: any): any {
action = asFunc(action);
var index = -1;
var result;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
result = action(ctx.item, ctx.index, ctx);
if (ctx.cancel) {
break;
}
}
return result;
}
/** @inheritdoc */
public elementAt(index: number): T {
return this.first((x: T, i: number) => {
return i == index;
});
}
/** @inheritdoc */
public elementAtOrDefault(index: number, defaultValue?: any): any {
return this.firstOrDefault((x: T, i: number) => {
return i == index;
}, defaultValue);
}
/** @inheritdoc */
public except(second: any, equalityComparer?: any): IEnumerable<T> {
var ec: (x: T, y: T) => boolean = toEqualityComparerSafe(equalityComparer);
second = asEnumerable(second).distinct(ec)
.toArray();
var newItems: T[] = [];
while (this.moveNext()) {
var curItem = this.current;
var found = false;
for (var i = 0; i < second.length; i++) {
var secondItem = second[i];
if (ec(curItem, secondItem)) {
found = true;
break;
}
}
if (!found) {
newItems.push(curItem);
}
}
return fromArray(newItems);
}
/** @inheritdoc */
public first(predicate?: any): T {
predicate = toPredicateSafe(predicate);
var index = -1;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
if (predicate(ctx.item, ctx.index, ctx)) {
return ctx.item;
}
if (ctx.cancel) {
break;
}
}
throw "Sequence contains NO element!";
}
/** @inheritdoc */
public firstOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any {
var odObj = createObjectForOrDefaultMethod<T>(arguments);
var index = -1;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
if (odObj.predicate(ctx.item, ctx.index, ctx)) {
return ctx.item;
}
if (ctx.cancel) {
break;
}
}
return odObj.defaultValue;
}
/**
* Gets the current item.
*
* @return any The current item.
*/
protected abstract getCurrent(): any;
/** @inheritdoc */
public groupBy<K>(keySelector: any, keyEqualityComparer?: any): IEnumerable<IGrouping<K, T>> {
var ks: (x: T, index: number, ctx: IEnumerableItemContext<T>) => K = asFunc(keySelector);
var kc: (x: K, y: K) => boolean = toEqualityComparerSafe(keyEqualityComparer);
var index = -1;
var groupList = [];
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
var key = ks(ctx.item, ctx.index, ctx);
var grp = null;
for (var i = 0; i < groupList.length; i++) {
var g = groupList[i];
if (kc(g.key, key)) {
grp = g;
break;
}
}
if (null === grp) {
grp = {
key: key,
values: []
};
groupList.push(grp);
}
grp.values.push(ctx.item);
if (ctx.cancel) {
break;
}
}
return fromArray(groupList.map((x: { key: any, values: T[] }) => {
return new Grouping<K, T>(x.key,
asEnumerable(x.values));
}));
}
/** @inheritdoc */
public groupJoin<U>(inner: any,
outerKeySelector: any, innerKeySelector: any,
resultSelector: any,
keyEqualityComparer?: any): IEnumerable<U> {
inner = asEnumerable(inner);
var rc: (x: T, inner: IEnumerable<T>) => U = asFunc(resultSelector);
var kc: (x: any, y: any) => boolean = toEqualityComparerSafe(keyEqualityComparer);
var createGroupsForSequence = (seq, keySelector): { key: any, values: T[] }[] => {
return seq.groupBy(keySelector)
.select((grouping: IGrouping<any, T>) => {
return {
key: grouping.key,
values: grouping.toArray()
};
})
.toArray();
};
var outerGroups = createGroupsForSequence(this, outerKeySelector);
var innerGroups = createGroupsForSequence(inner, innerKeySelector);
var joinedItems: U[] = [];
for (var i = 0; i < outerGroups.length; i++) {
var outerGrp = outerGroups[i];
for (var ii = 0; ii < innerGroups.length; ii++) {
var innerGrp = innerGroups[ii];
if (!kc(outerGrp.key, innerGrp.key)) {
continue;
}
for (var iii = 0; iii < outerGrp.values.length; iii++) {
joinedItems.push(rc(outerGrp.values[iii],
fromArray<T>(innerGrp.values)));
}
}
}
return fromArray(joinedItems);
}
/** @inheritdoc */
public intersect(second: any, equalityComparer?: any): IEnumerable<T> {
var ec: (x: T, y: T) => boolean = toEqualityComparerSafe(equalityComparer);
second = asEnumerable(second).distinct(ec)
.toArray();
var newItems: T[] = [];
while (this.moveNext()) {
var curItem = this.current;
for (var i = 0; i < second.length; i++) {
var secondItem = second[i];
if (ec(curItem, secondItem)) {
newItems.push(curItem);
break;
}
}
}
return fromArray(newItems);
}
/** @inheritdoc */
public isValid: boolean;
/** @inheritdoc */
public itemKey: any;
/** @inheritdoc */
public join<U>(inner: any,
outerKeySelector: any, innerKeySelector: any,
resultSelector: any,
keyEqualityComparer?: any) {
inner = asEnumerable(inner);
var rc: (x: T, y: T) => U = asFunc(resultSelector);
var kc: (x: any, y: any) => boolean = toEqualityComparerSafe(keyEqualityComparer);
var createGroupsForSequence = function(seq, keySelector) {
return seq.groupBy(keySelector)
.select((grouping: IGrouping<any, T>) => {
return {
key: grouping.key,
values: grouping.toArray()
};
})
.toArray();
};
var outerGroups = createGroupsForSequence(this, outerKeySelector);
var innerGroups = createGroupsForSequence(inner, innerKeySelector);
var joinedItems = [];
for (var i = 0; i < outerGroups.length; i++) {
var outerGrp = outerGroups[i];
for (var ii = 0; ii < innerGroups.length; ii++) {
var innerGrp = innerGroups[ii];
if (!kc(outerGrp.key, innerGrp.key)) {
continue;
}
for (var iii = 0; iii < outerGrp.values.length; iii++) {
for (var iv = 0; iv < innerGrp.values.length; iv++) {
joinedItems.push(rc(outerGrp.values[iii],
innerGrp.values[iv]));
}
}
}
}
return fromArray(joinedItems);
}
/** @inheritdoc */
public last(predicate?: any): any {
predicate = toPredicateSafe(predicate);
var index = -1;
var lastItem;
var found = false;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
if (predicate(ctx.item, ctx.index, ctx)) {
lastItem = ctx.item;
found = true;
}
if (ctx.cancel) {
break;
}
}
if (!found) {
throw "Sequence contains NO element!";
}
return lastItem;
}
/** @inheritdoc */
public lastOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any {
var odObj = createObjectForOrDefaultMethod(arguments);
var index = -1;
var lastItem = odObj.defaultValue;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
if (odObj.predicate(ctx.item, ctx.index, ctx)) {
lastItem = ctx.item;
}
if (ctx.cancel) {
break;
}
}
return lastItem;
}
/** @inheritdoc */
public max(defaultValue?: any): any {
return this.aggregate(function(result, x) {
if (x > result) {
result = x;
}
return result;
}, defaultValue);
}
/** @inheritdoc */
public min(defaultValue?: any): any {
return this.aggregate(function(result, x) {
if (x < result) {
result = x;
}
return result;
}, defaultValue);
}
/** @inheritdoc */
public abstract moveNext(): boolean;
/** @inheritdoc */
public ofType(type: string) {
type = type.replace(REGEX_TRIM, '');
var checkType = function(x) {
return typeof x === type;
};
switch (type) {
case 'bool':
type = 'boolean';
break;
case 'float':
case 'int':
case 'integer':
type = 'number';
break;
case 'str':
type = 'string';
break;
case 'enumerable':
case 'seq':
case 'sequence':
checkType = function(x) {
return isEnumerable(x);
};
break;
}
return this.where(checkType);
}
/** @inheritdoc */
public order(comparer?: any): IOrderedEnumerable<T> {
return this.orderBy('x => x', comparer);
}
/** @inheritdoc */
public orderBy(selector: any, comparer?: any): IOrderedEnumerable<T> {
return new OrderedSequence(this, selector, comparer);
}
/** @inheritdoc */
public orderByDescending(selector: any, comparer?: any): IOrderedEnumerable<T> {
var c: (x: T, y: T) => number = toComparerSafe(comparer);
return this.orderBy(selector,
(x: T, y: T): number => {
return c(y, x);
});
}
/** @inheritdoc */
public orderDescending(comparer?: any): IOrderedEnumerable<T> {
return this.orderByDescending('x => x', comparer);
}
/** @inheritdoc */
public pushToArray(arr: T[] | ObservableArray<T>): Sequence<T> {
while (this.moveNext()) {
arr.push(this.current);
}
return this;
}
/** @inheritdoc */
public abstract reset();
/** @inheritdoc */
public reverse(): IEnumerable<T> {
var reverseItems: T[] = [];
while (this.moveNext()) {
reverseItems.unshift(this.current);
}
return fromArray(reverseItems);
}
/** @inheritdoc */
public select<U>(selector: any): IEnumerable<U> {
this._selector = asFunc(selector);
return <any>this;
}
/**
* Projects an item to another type based on the inner selector.
*
* @param {T} x The input value.
*
* @return any The output value.
*/
protected selectInner(item: T): any {
var s = this._selector;
if (TypeUtils.isNullOrUndefined(s)) {
s = (x) => x;
}
return s(item);
}
/** @inheritdoc */
public selectMany<U>(selector: any): IEnumerable<U> {
selector = asFunc(selector);
var flattenItems: U[] = [];
var index = -1;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
var items = asEnumerable(selector(ctx.item, ctx.index, ctx));
while (items.moveNext()) {
flattenItems.push(items.current);
}
if (ctx.cancel) {
break;
}
}
return fromArray(flattenItems);
}
/** @inheritdoc */
public sequenceEqual(other: any, equalityComparer?: any): boolean {
var o: IEnumerable<T> = asEnumerable(other);
var ec: (x:T, y: T) => boolean = toEqualityComparerSafe(equalityComparer);
while (this.moveNext()) {
var x = this.current;
if (!o.moveNext()) {
return false;
}
var y = o.current;
if (!ec(x, y)) {
return false;
}
}
if (o.moveNext()) {
return false;
}
return true;
}
/** @inheritdoc */
public single(predicate?: any): T {
predicate = toPredicateSafe(predicate);
var index = -1;
var item;
var found = false;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
if (predicate(ctx.item, ctx.index, ctx)) {
if (found) {
throw "Sequence contains more that one matching element!";
}
item = this.current;
found = true;
}
if (ctx.cancel) {
break;
}
}
if (!found) {
throw "Sequence contains NO element!";
}
return item;
}
/** @inheritdoc */
public singleOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any {
var odObj = createObjectForOrDefaultMethod(arguments);
var item = odObj.defaultValue;
var index = -1;
var found = false;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
if (odObj.predicate(ctx.item, ctx.index, ctx)) {
if (found) {
throw "Sequence contains more that one matching element!";
}
item = this.current;
found = true;
}
if (ctx.cancel) {
break;
}
}
return item;
}
/** @inheritdoc */
public skip(cnt: number): IEnumerable<T> {
return this.skipWhile(function() {
if (cnt > 0) {
--cnt;
return true;
}
return false;
});
}
/** @inheritdoc */
public skipLast(): IEnumerable<T> {
var hasRemainingItems;
var isFirst = true;
var item;
var newItemList: T[] = [];
do
{
hasRemainingItems = this.moveNext();
if (!hasRemainingItems) {
continue;
}
if (!isFirst) {
newItemList.push(item);
}
else {
isFirst = false;
}
item = this.current;
}
while (hasRemainingItems);
return fromArray(newItemList);
}
/** @inheritdoc */
public skipWhile(predicate: any): IEnumerable<T> {
predicate = asFunc(predicate);
var newItems: T[] = [];
var index = -1;
var flag = false;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
if (!flag && !predicate(ctx.item, ctx.index, ctx)) {
flag = true;
}
if (flag) {
newItems.push(ctx.item);
}
if (ctx.cancel) {
break;
}
}
return fromArray(newItems);
}
/** @inheritdoc */
public sum(defaultValue?: any): any {
return this.aggregate((result, x) => {
return result + x;
}, defaultValue);
}
/** @inheritdoc */
public take(cnt: number): IEnumerable<T> {
return this.takeWhile(function() {
if (cnt > 0) {
--cnt;
return true;
}
return false;
});
}
/** @inheritdoc */
public takeWhile(predicate: any): IEnumerable<T> {
predicate = asFunc(predicate);
var newItems: T[] = [];
var index = -1;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
if (!predicate(ctx.item, ctx.index, ctx)) {
break;
}
newItems.push(ctx.item);
if (ctx.cancel) {
break;
}
}
return fromArray(newItems);
}
/** @inheritdoc */
public toArray(): T[] {
var arr = [];
while (this.moveNext()) {
arr.push(this.current);
}
return arr;
}
/** @inheritdoc */
public toLookup(keySelector: any, keyEqualityComparer?: any): any {
var lu = {};
this.groupBy(keySelector, keyEqualityComparer)
.each(function(grouping: IGrouping<any, T>) {
lu[grouping.key] = grouping;
});
return lu;
}
/** @inheritdoc */
public toObject(keySelector?: any): any {
if (arguments.length < 1) {
keySelector = function(x: T, index: number, key: any) {
return key;
};
}
var ks: (x: T, index: number, key: any) => any = asFunc(keySelector);
var obj = {};
this.each(function(x, index, ctx) {
var key = ks(x, index, ctx.key);
obj[key] = x;
});
return obj;
}
/** @inheritdoc */
public toObservable(keySelector?: any): Observable {
if (arguments.length < 1) {
keySelector = function(x: T, index: number, key: any) {
return key;
};
}
var ks: (x: T, index: number, key: any) => any = asFunc(keySelector);
var ob = new Observable();
this.each(function(x, index, ctx) {
var key = ks(x, index, ctx.key);
ob.set(key, x);
});
return ob;
}
/** @inheritdoc */
public toObservableArray(): ObservableArray<T> {
return new ObservableArray(this.toArray());
}
/** @inheritdoc */
public toVirtualArray(): VirtualArray<T> {
var arr = this.toArray();
var va = new VirtualArray<T>(arr.length);
for (var i = 0; i < va.length; i++) {
va.setItem(i, arr[i]);
}
return va;
}
/** @inheritdoc */
public union(second: any, equalityComparer?: any): IEnumerable<T> {
return this.concat(second)
.distinct(equalityComparer);
}
/** @inheritdoc */
public where(predicate: any): IEnumerable<T> {
predicate = asFunc(predicate);
var filteredItems: T[] = [];
var index = -1;
while (this.moveNext()) {
var ctx = new EnumerableItemContext(this, ++index);
if (predicate(ctx.item, ctx.index, ctx)) {
filteredItems.push(ctx.item);
}
if (ctx.cancel) {
break;
}
}
return fromArray(filteredItems);
}
/** @inheritdoc */
public zip<U>(second: any, selector: any): IEnumerable<U> {
second = asEnumerable(second);
selector = asFunc(selector);
var zippedItems: U[] = [];
var index = -1;
while (this.moveNext() && second.moveNext()) {
++index;
var ctx1 = new EnumerableItemContext(this, index);
var ctx2 = new EnumerableItemContext(second, index);
var zipped = selector(ctx1.item, ctx2.item,
index,
ctx1, ctx2);
zippedItems.push(zipped);
if (ctx1.cancel || ctx2.cancel) {
break;
}
}
return fromArray(zippedItems);
}
}
class ArrayEnumerable<T> extends Sequence<T> implements IEnumerable<T> {
protected _arr: T[] | ObservableArray<T> | VirtualArray<T> | IArguments | string;
protected _getter: (index: number) => T;
protected _index;
constructor(arr: T[] | ObservableArray<T> | VirtualArray<T> | IArguments | string,
getter: (index: number) => T) {
super();
this._arr = arr;
this._getter = getter;
this.reset();
}
protected getCurrent(): any {
return this._getter(this._index);
}
public get isValid(): boolean {
return (this._index + 1) < this._arr.length;
}
public get itemKey(): number {
return this._index;
}
public moveNext(): boolean {
if (this.isValid) {
++this._index;
return true;
}
return false;
}
public reset() {
this._index = -1;
}
}
class EnumerableItemContext<T> implements IEnumerableItemContext<T> {
private _index: number;
private _seq: IEnumerable<T>;
constructor(seq: IEnumerable<T>, index?: number) {
this._seq = seq;
this._index = index;
}
public cancel: boolean = false;
public get index(): number {
return this._index;
}
public get item(): T {
return this._seq.current;
}
public get key(): any {
return this._seq.itemKey;
}
public get sequence(): IEnumerable<T> {
return this._seq;
}
}
/**
* A grouping.
*/
export class Grouping<K, T> extends Sequence<T> implements IGrouping<K, T> {
private _key: K;
private _seq: IEnumerable<T>;
/**
* Initializes a new instance of that class.
*
* @param {K} key The key.
* @param {IEnumerable} seq The items of the grouping.
*/
constructor(key: K, seq: IEnumerable<T>) {
super();
this._key = key;
this._seq = seq;
}
/** @inheritdoc */
protected getCurrent(): T {
return this._seq.current;
}
/** @inheritdoc */
public get isValid(): boolean {
return this._seq.isValid;
}
/** @inheritdoc */
public get key(): K {
return this._key;
}
/** @inheritdoc */
public moveNext(): boolean {
return this._seq.moveNext();
}
/** @inheritdoc */
public reset() {
return this._seq.reset();
}
}
class ObjectEnumerable extends Sequence<any> {
private _index: number;
private _obj: any;
private _properties: any[];
constructor(obj: any) {
super();
this._properties = [];
for (var p in obj) {
this._properties.push(p);
}
this.reset();
}
protected getCurrent(): any {
return this._obj[this.itemKey];
}
public get isValid(): boolean {
return (this._index + 1) < this._properties.length;
}
public get itemKey(): number {
return this._properties[this._index];
}
public moveNext(): boolean {
if (this.isValid) {
++this._index;
return true;
}
return false;
}
public reset() {
this._index = -1;
}
}
/**
* An ordered sequence.
*/
export class OrderedSequence<T> extends Sequence<T> implements IOrderedEnumerable<T> {
private _items: IEnumerable<T>;
private _originalItems: T[];
private _orderComparer: (x: any, y: any) => number;
private _orderSelector: (x: T) => any;
/**
* Initializes a new instance of that class.
*
* @param {IEnumerable} seq The source sequence.
* @param {Function} selector The selector for the sort values.
* @param {Function} comparer The comparer to use.
*/
constructor(seq: IEnumerable<T>, selector: any, comparer: any) {
super();
var me = this;
this._orderComparer = toComparerSafe(comparer);
if (true === selector) {
selector = x => x;
}
this._orderSelector = asFunc(selector);
this._originalItems = seq.toArray();
this._items = fromArray(this._originalItems.map(function(x: T) {
return {
sortBy: me.selector(x),
value: x
};
}).sort(function(x: { sortBy: any, value: T },
y: { sortBy: any, value: T }) {
return me.comparer(x.sortBy, y.sortBy);
}).map(function(x: { sortBy: any, value: T }) {
return x.value;
}));
}
/**
* Gets the comparer.
*/
public get comparer(): (x: any, y: any) => number {
return this._orderComparer;
}
/** @inheritdoc */
protected getCurrent(): T {
return this._items.current;
}
/** @inheritdoc */
public moveNext(): boolean {
return this._items
.moveNext();
}
/** @inheritdoc */
public reset() {
return this._items.reset();
}
/**
* Gets the selector.
*/
public get selector(): (x: T) => any {
return this._orderSelector;
}
/** @inheritdoc */
public then(comparer?: any): IOrderedEnumerable<T> {
return this.thenBy('x => x', comparer);
}
/** @inheritdoc */
public thenBy(selector: any, comparer?: any): IOrderedEnumerable<T> {
var c: (x: any, y: any) => number = toComparerSafe(comparer);
if (true === selector) {
selector = x => x;
}
selector = asFunc(selector);
var thisSelector = this._orderSelector;
var thisComparer = this._orderComparer;
return fromArray(this._originalItems)
.orderBy((x: T): { level_0: any, level_1: any } => {
return {
level_0: thisSelector(x),
level_1: selector(x),
};
},
function(x: { level_0: any, level_1: any },
y: { level_0: any, level_1: any }): number {
var comp0 = thisComparer(x.level_0, y.level_0);
if (0 != comp0) {
return comp0;
}
var comp1 = c(x.level_1, y.level_1);
if (0 != comp1) {
return comp1;
}
return 0;
});
}
/** @inheritdoc */
public thenByDescending(selector: any, comparer?: any): IOrderedEnumerable<T> {
var c: (x: T, y: T) => number = toComparerSafe(comparer);
return this.thenBy(selector,
(x: T, y: T): number => {
return comparer(y, x);
});
}
/** @inheritdoc */
public thenDescending(comparer?: any): IOrderedEnumerable<T> {
return this.thenByDescending('x => x', comparer);
}
}
/**
* Returns a value as sequence.
*
* @param any v The input value.
* @param {Boolean} [throwException] Throws an exception if input value is no valid value.
*
* @throws Invalid value.
*
* @return any The value as sequence or (false) if input value is no valid object.
*/
export function asEnumerable(v: any, throwException: boolean = true): IEnumerable<any> {
if (isEnumerable(v)) {
return v;
}
if ((v instanceof Array) ||
(v instanceof ObservableArray) ||
(v instanceof VirtualArray) ||
(typeof v === 'string') ||
!v) {
return fromArray(v);
}
if (typeof v === 'object') {
return fromObject(v);
}
// at this point we have no valid value to use as sequence
if (throwException) {
throw "'" + v + "' is no valid value to use as sequence!";
}
return <any>false;
}
/**
* Returns a value as function.
*
* @param any v The value to convert. Can be a function or a string that is handled as lambda expression.
* @param {Boolean} [throwException] Throw an exception if value is no valid function or not.
*
* @throws Value is no valid function / lambda expression.
*
* @return {Function} Value as function or (false) if value is invalid.
*/
export function asFunc(v: any, throwException: boolean = true): any {
if (typeof v === "function") {
return v;
}
if (!v) {
return v;
}
// now handle as lambda...
var lambda = "" + v;
var matches = lambda.match(/^(\s*)([\(]?)([^\)]*)([\)]?)(\s*)(=>)/m);
if (matches) {
if ((("" === matches[2]) && ("" !== matches[4])) ||
(("" !== matches[2]) && ("" === matches[4]))) {
if (throwException) {
throw "Syntax error in '" + lambda + "' expression!";
}
return null;
}
var lambdaBody = lambda.substr(matches[0].length)
.replace(/^[\s|{|}]+|[\s|{|}]+$/g, ''); // trim
if ("" !== lambdaBody) {
if (';' !== lambdaBody.substr(-1)) {
lambdaBody = 'return ' + lambdaBody + ';';
}
}
var func;
eval('func = function(' + matches[3] + ') { ' + lambdaBody + ' };');
return func;
}
if (throwException) {
throw "'" + v + "' is NO valid lambda expression!";
}
return false;
}
/**
* Creates a new sequence from a list of values.
*
* @param any ...items One or more item to add.
*
* @return {IEnumerable} The new sequence.
*/
export function create<T>(...items: any[]): IEnumerable<T> {
return fromArray<T>(items);
}
function createObjectForOrDefaultMethod<T>(args: IArguments): { defaultValue?: any,
predicate?: (x: T, index: number, ctx: IEnumerableItemContext<T>) => boolean } {
var odObj: any = {
predicate: () => true,
};
if (args.length > 0) {
if (args.length < 2) {
var func = asFunc(args[0], false);
if (typeof func !== "function") {
odObj.defaultValue = args[0];
}
else {
odObj.predicate = func;
}
}
else {
odObj.predicate = asFunc(args[0]);
odObj.defaultValue = args[1];
}
}
return odObj;
}
/**
* Short hand version for 'each' method of a sequence.
*
* @param items any The sequence of items to iterate.
* @param action any The action to invoke for each item.
*
* @throws At least one argument is invalid.
*
* @return any The result of the last invocation.
*/
export function each(items: any, action: any): any {
return asEnumerable(items).each(action);
}
/**
* Creates a new sequence from an array.
*
* @param {Array} arr The array.
*
* @return {IEnumerable} The new sequence.
*/
export function fromArray<T>(arr?: T[] | ObservableArray<T> | VirtualArray<T> | IArguments | string): IEnumerable<T> {
if (arguments.length < 1) {
arr = [];
}
var getter: (index: number) => T;
if ((arr instanceof ObservableArray) ||
(arr instanceof VirtualArray)) {
getter = (i) => (<any>arr).getItem(i);
}
else {
getter = (i) => arr[i];
}
return new ArrayEnumerable<T>(arr, getter);
}
/**
* Creates a new sequence from an object.
*
* @param {Object} obj The object.
*
* @return {Sequence} The new sequence.
*/
export function fromObject(obj?: any): IEnumerable<any> {
if (arguments.length < 1) {
obj = {};
}
return new ObjectEnumerable(obj);
}
/**
* Checks if a value is a sequence.
*
* @param any v The value to check.
*
* @return {Boolean} Is sequence or not.
*/
export function isEnumerable(v: any): boolean {
return v instanceof Sequence;
}
/**
* Creates a sequence with a range of items.
*
* @param any start The start value.
* @param {Number} cnt The number of items to return.
* @param any [incrementor] The custom function (or value) that increments the current value.
*
* @return {Object} The new sequence.
*/
function range(start: number, cnt: number, incrementor?: any): IEnumerable<number> {
if (arguments.length < 3) {
incrementor = (x): number => {
return x + 1;
};
}
else {
var funcOrValue = asFunc(incrementor, false);
if (false === funcOrValue) {
var incrementBy = incrementor;
incrementor = (x): number => {
return x + incrementBy;
};
}
else {
incrementor = funcOrValue;
}
}
var numbers: number[] = [];
var remainingCnt = cnt;
var val: number = start;
while (remainingCnt > 0) {
numbers.push(val);
val = incrementor(val, {
remainingCount: remainingCnt,
startValue: start,
totalCount: cnt
});
--remainingCnt;
}
return fromArray(numbers);
}
/**
* Creates a sequence with a number of specific values.
*
* @param any v The value.
* @param {Number} cnt The number of items to return.
*
* @return {Object} The new sequence.
*/
function repeat<T>(v: T, cnt: number): IEnumerable<T> {
var items: T[] = [];
while (cnt > 0) {
items.push(v);
--cnt;
}
return fromArray(items);
}
/**
* Short hand version for 'order(By)' methods of a sequence.
*
* @param items any The sequence of items to iterate.
* @param [comparer] any The custom comparer to use.
* @param [selector] any The custom key selector to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The sequences with the sorted items.
*/
export function sort<T>(items, comparer?: any, selector?: any): IOrderedEnumerable<T> {
return asEnumerable(items).orderBy(selector, comparer);
}
/**
* Short hand version for 'order(By)Descending' methods of a sequence.
*
* @param items any The sequence of items to iterate.
* @param [comparer] any The custom comparer to use.
* @param [selector] any The custom key selector to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The sequences with the sorted items.
*/
export function sortDesc<T>(items: any, comparer?: any, selector?: any): IOrderedEnumerable<T> {
return asEnumerable(items).orderByDescending(selector, comparer);
}
/**
* Returns a value as comparer.
*
* @param any predicate The input value.
*
* @throws Input value is no valid function / lambda expression.
*
* @return {Function} Input value as comparer.
*/
export function toComparerSafe(comparer: any) {
comparer = asFunc(comparer);
if (TypeUtils.isNullOrUndefined(comparer)) {
return function(x, y) {
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
};
}
return comparer;
};
/**
* Returns a value as equality comparer.
*
* @param any equalityComparer The input value.
*
* @throws Input value is no valid function / lambda expression.
*
* @return {Function} Input value as equality comparer.
*/
export function toEqualityComparerSafe(equalityComparer: any) {
if (true === equalityComparer) {
return function(x, y) {
return x === y;
};
}
equalityComparer = asFunc(equalityComparer);
if (TypeUtils.isNullOrUndefined(equalityComparer)) {
return function(x, y) {
return x == y;
};
}
return equalityComparer;
}
/**
* Returns a value as predicate.
*
* @param any predicate The input value.
*
* @throws Input value is no valid function / lambda expression.
*
* @return {Function} Input value as predicate.
*/
export function toPredicateSafe(predicate: any) {
if (TypeUtils.isNullOrUndefined(predicate)) {
predicate = () => true;
}
return asFunc(predicate);
} | the_stack |
import twemoji from 'twemoji';
import * as remixicons from '../remixicons';
import * as faLine from '../fontawesome/index-line';
import * as faFill from '../fontawesome/index-fill';
import * as faBrands from '../fontawesome/index-brands';
import IconFolderPlugin, { FolderIconObject } from './main';
import { ExplorerLeaf } from './@types/obsidian';
import { IconFolderSettings } from './settings';
/**
* `transformedIcons` includes all the icon packs with their corresponding prefix.
*/
const transformedIcons = {
faFill: Object.keys(faFill).map((iconName) => 'Fa' + iconName),
faLine: Object.keys(faLine).map((iconName) => 'Fa' + iconName),
faBrands: Object.keys(faBrands).map((iconName) => 'Fa' + iconName),
remixIcons: Object.keys(remixicons).map((iconName) => 'Ri' + iconName),
};
/**
* This function checks whether the passed `iconName` is a `fill` or `line` icon.
* Based on this condition it will return `true` or `false` based on the enabled settings.
*
* @private
* @param {string} iconName - Represents the icon name like `RiAB`.
* @param {IconFolderSettings} settings - The saved settings of the plugin.
* @returns {boolean} If the icon should be included/enabled or not.
*/
const mapRemixicons = (iconName: string, settings: IconFolderSettings): boolean => {
if (iconName.toLowerCase().includes('fill')) {
return settings.enableRemixiconsFill;
} else if (iconName.toLowerCase().includes('line')) {
return settings.enableRemixiconsLine;
}
return true;
};
/**
* This function returns all enabled icons.
*
* For example: if `Remixicons Fill` and `Fontawesome Fill` is activated, it will return all these icons.
*
* @public
* @param {IconFolderPlugin} plugin - The main plugin file.
* @returns {string[]} The enabled icons.
*/
export const getEnabledIcons = (plugin: IconFolderPlugin): string[] => {
const settings = plugin.getSettings();
const icons = transformedIcons.remixIcons.filter((key) => {
return mapRemixicons(key, settings);
});
if (settings.enableFontawesomeFill) {
icons.push(...transformedIcons.faFill);
}
if (settings.enableFontawesomeLine) {
icons.push(...transformedIcons.faLine);
}
if (settings.enableFontawesomeBrands) {
icons.push(...transformedIcons.faBrands);
}
return icons;
};
/**
* This function transforms an icon that includes a prefix and returns the correct svg string.
*
* For example: This input: `RiAB` will return only `AB` as a svg.
*
* @public
* @param {string} name - The icon name.
* @returns {string | null} The transformed svg or null if it cannot find any iconpack.
*/
export const getIcon = (name: string): string | null => {
const prefix = name.substr(0, 2);
let iconSvg: string = null;
if (prefix === 'Fa') {
if (name.toLowerCase().substr(name.length - 4) === 'line') {
iconSvg = faLine[name.substr(2)];
} else if (name.toLowerCase().substr(name.length - 4) === 'fill') {
iconSvg = faFill[name.substr(2)];
} else {
iconSvg = faBrands[name.substr(2)];
}
} else if (prefix === 'Ri') {
iconSvg = remixicons[name.substr(2)];
}
return iconSvg;
};
/**
* This function returns the svg string with the user defined css settings.
* It handles from the settings the `padding`, `color`, and `size`.
*
* In addition, this function manipulates the passed element with the user defined setting `padding`.
*
* @public
* @param {IconFolderPlugin} plugin - The main plugin.
* @param {string} icon - The to be styled icon.
* @param {HTMLElement} el - The element that will include the padding from the user settings.
* @returns {string} The svg with the customized css settings.
*/
export const customizeIconStyle = (plugin: IconFolderPlugin, icon: string, el: HTMLElement): string => {
// Allow custom font size
const sizeRe = new RegExp(/width="\d+" height="\d+"/g);
if (icon.match(sizeRe)) {
icon = icon.replace(sizeRe, `width="${plugin.getSettings().fontSize}" height="${plugin.getSettings().fontSize}"`);
} else {
// If match is null, it should be an image.
const sizeRe = new RegExp(/width="\d+px" height="\d+px"/g);
icon = icon.replace(
sizeRe,
`width="${plugin.getSettings().fontSize}px" height="${plugin.getSettings().fontSize}px"`,
);
}
// Allow custom icon color
const colorRe = new RegExp(/fill="(\w|#)+"/g);
icon = icon.replace(colorRe, `fill="${plugin.getSettings().iconColor ?? 'currentColor'}"`);
// Change padding of icon
if (plugin.getSettings().extraPadding) {
el.style.padding = `${plugin.getSettings().extraPadding.top ?? 2}px ${
plugin.getSettings().extraPadding.right ?? 2
}px ${plugin.getSettings().extraPadding.bottom ?? 2}px ${plugin.getSettings().extraPadding.left ?? 2}px`;
}
return icon;
};
/**
* This function adds the icons to the DOM.
* For that, it will create a `div` element with the class `obsidian-icon-folder-icon` that will be customized based on the user settings.
*
* @public
* @param {IconFolderPlugin} plugin - The main plugin.
* @param {[string, string | FolderIconObject][]} data - The data that includes the icons.
* @param {WeakMap<ExplorerLeaf, boolean>} registeredFileExplorers - The already registered file explorers.
*/
export const addIconsToDOM = (
plugin: IconFolderPlugin,
data: [string, string | FolderIconObject][],
registeredFileExplorers: WeakMap<ExplorerLeaf, boolean>,
callback?: () => void,
): void => {
const fileExplorers = plugin.app.workspace.getLeavesOfType('file-explorer');
fileExplorers.forEach((fileExplorer) => {
if (registeredFileExplorers.has(fileExplorer)) {
return;
}
registeredFileExplorers.set(fileExplorer, true);
// create a map with registered file paths to have constant look up time
const registeredFilePaths: Record<string, boolean> = {};
data.forEach(([path]) => {
registeredFilePaths[path] = true;
});
data.forEach(([dataPath, value]) => {
const fileItem = fileExplorer.view.fileItems[dataPath];
if (fileItem) {
const titleEl = fileItem.titleEl;
const titleInnerEl = fileItem.titleInnerEl;
// needs to check because of the refreshing the plugin will duplicate all the icons
if (titleEl.children.length === 2 || titleEl.children.length === 1) {
const iconName = typeof value === 'string' ? value : value.iconName;
if (iconName) {
const iconNode = titleEl.createDiv();
iconNode.classList.add('obsidian-icon-folder-icon');
insertIconToNode(plugin, iconName, iconNode);
titleEl.insertBefore(iconNode, titleInnerEl);
}
if (typeof value === 'object' && value.inheritanceIcon) {
const files = plugin.app.vault.getFiles().filter((f) => f.path.includes(dataPath));
const inheritanceIconName = value.inheritanceIcon;
files.forEach((f) => {
if (!registeredFilePaths[f.path]) {
const inheritanceFileItem = fileExplorer.view.fileItems[f.path];
const iconNode = inheritanceFileItem.titleEl.createDiv();
iconNode.classList.add('obsidian-icon-folder-icon');
insertIconToNode(plugin, inheritanceIconName, iconNode);
inheritanceFileItem.titleEl.insertBefore(iconNode, inheritanceFileItem.titleInnerEl);
}
});
}
}
}
});
if (callback) {
callback();
}
});
};
export const addInheritanceIconToFile = (
plugin: IconFolderPlugin,
registeredFileExplorers: WeakMap<ExplorerLeaf, boolean>,
filePath: string,
iconName: string,
): void => {
const fileExplorers = plugin.app.workspace.getLeavesOfType('file-explorer');
fileExplorers.forEach((fileExplorer) => {
if (registeredFileExplorers.has(fileExplorer)) {
const fileItem = fileExplorer.view.fileItems[filePath];
if (fileItem) {
const iconNode = fileItem.titleEl.createDiv();
iconNode.classList.add('obsidian-icon-folder-icon');
insertIconToNode(plugin, iconName, iconNode);
fileItem.titleEl.insertBefore(iconNode, fileItem.titleInnerEl);
}
}
});
};
/**
* This function refreshes the icon style.
* For that, it will manipulate the `innerHTML` of the icon and will customize the style.
*
* @public
* @param {IconFolderPlugin} plugin - The main plugin.
*/
export const refreshIconStyle = (plugin: IconFolderPlugin): void => {
const data = Object.entries(plugin.getData()) as [string, string];
const fileExplorers = plugin.app.workspace.getLeavesOfType('file-explorer');
fileExplorers.forEach((fileExplorer) => {
data.forEach(([key]) => {
const fileItem = fileExplorer.view.fileItems[key];
if (fileItem) {
const titleEl = fileItem.titleEl;
const iconNode = titleEl.querySelector('.obsidian-icon-folder-icon') as HTMLElement;
iconNode.innerHTML = customizeIconStyle(plugin, iconNode.innerHTML, iconNode);
}
});
});
};
/**
* This function removes the icon node from the DOM based on the passed in path.
*
* @public
* @param {string} path - The path toe the to be removed DOM element.
*/
export const removeFromDOM = (path: string): void => {
const node = document.querySelector(`[data-path="${path}"]`);
if (!node) {
console.error('element with data path not found', path);
return;
}
const iconNode = node.querySelector('.obsidian-icon-folder-icon');
if (!iconNode) {
return;
}
iconNode.remove();
};
/**
* This function adds an icon to the DOM based on a specific path.
* In addition, before added to the DOM, it will customize the icon style.
*
* @public
* @param {IconFolderPlugin} plugin - The main plugin.
* @param {string} path - The path in the DOM where the icon will be added.
* @param {string} icon - The icon that will be added to the DOM - can be an icon id or codepoint for twemoji.
*/
export const addToDOM = (plugin: IconFolderPlugin, path: string, icon: string): void => {
if (plugin.getData()[path]) {
removeFromDOM(path);
}
const node = document.querySelector(`[data-path="${path}"]`);
if (!node) {
console.error('element with data path not found', path);
return;
}
let titleNode = node.querySelector('.nav-folder-title-content');
if (!titleNode) {
titleNode = node.querySelector('.nav-file-title-content');
if (!titleNode) {
console.error('element with title not found');
return;
}
}
// check if there is a possible inheritance icon in the DOM
const possibleInheritanceIcon = node.querySelector('.obsidian-icon-folder-icon');
if (possibleInheritanceIcon) {
possibleInheritanceIcon.remove();
}
const iconNode = document.createElement('div');
iconNode.classList.add('obsidian-icon-folder-icon');
insertIconToNode(plugin, icon, iconNode);
node.insertBefore(iconNode, titleNode);
};
/**
* This function inserts a specific icon into the specified node.
*
* @param {IconFolderPlugin} plugin - The main plugin.
* @param {string} icon - The icon string (can be an icon id or a unicode for twemoji).
* @param {HTMLElement} node - The element where the icon will be inserted.
*/
const insertIconToNode = (plugin: IconFolderPlugin, icon: string, node: HTMLElement): void => {
// Check for earlier versions (related to issue #30).
if (icon.substring(0, 4) === 'RiRi') {
icon = icon.substring(2);
}
const possibleIcon = getIcon(icon);
if (possibleIcon) {
node.innerHTML = customizeIconStyle(plugin, possibleIcon, node);
} else {
const emoji = twemoji.parse(icon, {
folder: 'svg',
ext: '.svg',
attributes: () => ({
width: '16px',
height: '16px',
}),
});
node.innerHTML = customizeIconStyle(plugin, emoji, node);
}
};
/**
* This function will add inheritance functionality to a specific folder.
* It will add the inheritance icon to all child files.
*
* @param {IconFolderPlugin} plugin - The main plugin.
* @param {string} folderPath - The path in the DOM where the icon will be added.
*/
export const addInheritanceForFolder = (plugin: IconFolderPlugin, folderPath: string): void => {
const folder = plugin.getData()[folderPath];
if (!folder || typeof folder !== 'object') {
return;
}
// add icons for all the child files
const files = plugin.app.vault.getFiles().filter((f) => f.path.includes(folderPath));
files.forEach((f) => {
if (plugin.getData()[f.path]) {
removeFromDOM(f.path);
plugin.removeFolderIcon(f.path);
}
addToDOM(plugin, f.path, (folder as any).inheritanceIcon);
});
};
/**
* This function removes inheritance from a folder.
* It will delete all the icons in the sub files of this folder.
*
* @param {IconFolderPlugin} plugin - The main plugin.
* @param {string} folderPath - The path in the DOM where the icon will be added.
*/
export const removeInheritanceForFolder = (plugin: IconFolderPlugin, folderPath: string): void => {
const folder = plugin.getData()[folderPath];
if (!folder || typeof folder !== 'object') {
return;
}
// remove icons from all the child files
const files = plugin.app.vault.getFiles().filter((f) => f.path.includes(folderPath));
files.forEach((f) => {
// when the file path is not registered in the data it should remove the icon
if (!plugin.getData()[f.path]) {
removeFromDOM(f.path);
}
});
};
export const isEmoji = (str: string): boolean => {
const ranges = [
'(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|[\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|[\ud83c[\ude32-\ude3a]|[\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])', // U+1F680 to U+1F6FF
];
if (str.match(ranges.join('|'))) {
return true;
} else {
return false;
}
}; | the_stack |
import { WebGLRenderer, Scene, PerspectiveCamera, Object3D, Vector2, Raycaster, MeshPhongMaterial, WebGLRenderTarget, PMREMGenerator, RGBFormat, sRGBEncoding, EquirectangularReflectionMapping, DirectionalLight, Mesh, PlaneBufferGeometry, MeshPhysicalMaterial, DoubleSide, UnsignedByteType, AxesHelper, GridHelper, Texture, Color, Vector3, PointLight } from 'three';
// import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"
import { TransformControls } from "three/examples/jsm/controls/TransformControls"
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer"
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass';
import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
const raycaster = new Raycaster();
const mouse = new Vector2();
const selectMaterial = new MeshPhongMaterial({ color: 0xaa3366 });
const PMREM = {
Scene: 0,
Equirectangular: 1,
CubeMap: 2
}
export class GLView {
private _scene: Scene;
private _modelScene: Object3D;
private _helperScene: Object3D;
renderer: WebGLRenderer;
container: HTMLElement;
[x: string]: any;
_controls!: OrbitControls;
constructor(settings: any = {}) {
this.allowSelected = true;
this.renderer = new WebGLRenderer({
antialias: true
});
this.container = settings.container;
if (this.container) this.container.appendChild(this.renderer.domElement);
this._scene = settings.scene || new Scene();
this._scene.name = "默认场景";
this._modelScene = new Object3D();
this._modelScene.name = "模型场景";
this._scene.add(this._modelScene);
this._helperScene = new Object3D();
this._helperScene.add(new AxesHelper(1000000));
this._scene.add(this._helperScene);
this.clearColor = settings.clearColor;
this.selectedObject = new Object3D();
this.selectedObject.parent = this._scene;
this.selecteds = this.selectedObject.children;
this.updates = [];
// Prefiltered, Mipmapped Radiance Environment Map
this._pmremGenerator = null
this._enablePostProcessing = settings._enablePostProcessing || false;
this.effectComposer = new EffectComposer(this.renderer)
this.init(settings);
this.onResize();
this.domElement.addEventListener("mousedown", this.onMousedown.bind(this));
window.addEventListener("resize", this.onResize.bind(this));
}
init(settings: any) {
this._camera = settings.camera || new PerspectiveCamera(45, 1, 0.1, 20000);
this._camera.position.set(16, 4, -30);
this._camera.name = "默认相机";
this._controls = new OrbitControls(this._camera, this.domElement);
this._controls.addEventListener("change", (e) => {
// console.log(e);
const oc: OrbitControls = e.target;
console.log(oc.target);
console.log(oc.object.position);
})
this._controls.minDistance = 10;
this._transfromControl = new TransformControls(this._camera, this.domElement)
this.scene.add(this._transfromControl);
this.scene.add(this._camera);
var light = new DirectionalLight();
light.name = "默认方向光";
light.position.set(1, 1, 1);
this.scene.add(light);
var pl = new PointLight();
pl.distance = 1000;
this._camera.add(pl);
this.scene.add(this._camera)
this.scene.add(new AxesHelper(10000))
this.scene.add(new GridHelper(100, 20, 0xff0000, 0xaaaaaa))
//添加一个地板
// var gdGeo = new PlaneBufferGeometry(1000000, 1000000);
// gdGeo.rotateX(-Math.PI / 2)
// var mesh = new Mesh(gdGeo, new MeshPhysicalMaterial({
// color: 0xffffff,
// transparency: 0.7,
// transparent: true,
// metalness: 0.0,
// roughness: 0.7,
// polygonOffset: true,
// polygonOffsetFactor: -1,
// polygonOffsetUnits: -1
// // side: DoubleSide
// } as any));
// (<any>mesh).isHelper = true;
// mesh.position.set(0, -1, 0)
// this.add(mesh);
//添加一个环境光
// new RGBELoader()
// .setDataType(UnsignedByteType)
// .load('../../assets/textures/env/quarry_01_1k.hdr', (texture) => {
// this.pmrenvMap(texture)
// })
}
set modelScene(val: Object3D) {
this._modelScene = val;
this.add(val);
}
get modelScene(): Object3D {
return this._modelScene;
}
set helperScene(val: Object3D) {
this._helperScene = val;
this.add(val);
}
get helperScene(): Object3D {
return this._helperScene;
}
set clearColor(val: Color | number) {
val = val || 0xaaeeff
this.renderer.setClearColor(<Color>val)
}
setTransfromMode(mode: any) {
this._transfromControl.setMode(mode);
}
attach(model: any) {
if (!model) {
this.detach(model)
} else {
this._transfromControl.attach(model);
this._controls.enabled = false;
}
}
detach(model: any) {
this._transfromControl.detach(model);
this._controls.enabled = true;
}
pmrenvMap(texture: Texture, type = PMREM.Equirectangular) {
texture.mapping = EquirectangularReflectionMapping;
if (!this._pmremGenerator)
this._pmremGenerator = new PMREMGenerator(this.renderer);
let renderTarget;
switch (type) {
case PMREM.CubeMap:
this._pmremGenerator.compileCubemapShader();
renderTarget = this._pmremGenerator.fromCubemap(texture)
break;
case PMREM.Equirectangular:
renderTarget = this._pmremGenerator.fromEquirectangular(texture);
this._pmremGenerator.compileEquirectangularShader();
break;
default:
throw ("pmrem error");
}
// this.scene.background = renderTarget.texture;
this.scene.environment = renderTarget.texture;
}
set toneExposure(val: any) {
this.renderer.toneMappingExposure = val;
}
get camera() {
return this._camera;
}
set camera(value) {
this._camera = value;
this._controls.object = value;
}
get scene() {
return this._scene;
}
get width() {
return this.domElement.width;
}
get height() {
return this.domElement.height;
}
set scene(value) {
this._scene = value;
}
get domElement() {
return this.renderer.domElement;
}
get enablePostProcessing() { return this._enablePostProcessing }
set enablePostProcessing(value) {
this._enablePostProcessing = value;
if (!value)
return
if (!this.renderPass) {
this.renderPass = new RenderPass(this._scene, this._camera);
this.effectComposer.addPass(this.renderPass);
this.effectComposer.setSize(this.width, this.height);
}
}
addPass(pass: any) {
this.effectComposer.addPass(pass)
}
addPassEx(name: string, params = { threshold: 0.01, strength: 0.1, radius: 0.4 }) {
if (name === "Bloom") {
var bloomPass = new UnrealBloomPass(new Vector2(this.width, this.height), 1.5, 0.4, 0.85);
bloomPass.threshold = params.threshold;
bloomPass.strength = params.strength;
bloomPass.radius = params.radius;
this.effectComposer.addPass(bloomPass);
return bloomPass
}
}
/**
* 向场景添加模型
* @param {Object3D} object 模型
*/
add(...object: any[] | Object3D[] | Mesh[]) {
for (let i = 0; i < object.length; i++) {
const object_i = object[i];
if (object_i.isSequence) {
this._modelScene.add(object_i.renderObject);
this.addUpdates(object_i)
}
if (object_i.isBody) {
this._modelScene.add(object_i.renderObject);
} else if (object_i.isHelper) {
this._helperScene.add(object_i)
} else {
this._modelScene.add(object_i)
}
}
return this;
}
/**
* 场景移除模型
* @param {Object3D} object 模型
*/
remove(...object: any[] | Object3D[] | Mesh[]) {
for (let i = 0; i < object.length; i++) {
const object_i = object[i];
if (object_i.isSequence) {
this._modelScene.remove(object_i.renderObject);
this.removeUpdates(object_i)
}
if (object_i.isBody) {
this._modelScene.remove(object_i.renderObject);
} else if (object_i.isHelper) {
this._helperScene.remove(object_i)
} else {
this._modelScene.remove(object_i)
}
}
return this;
}
/**
* 设置渲染DOM的宽高 更新相机
* @param {} width
* @param {} height
*/
size(width: number, height: number) {
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(width, height);
if (this._enablePostProcessing)
this.effectComposer.setSize(width, height);
}
/**
* 添加更新函数
* @param {} ...updates
*/
addUpdates(...updates: any[]) {
this.updates.push(...updates);
}
removeUpdates(...updates: any[]) {
for (let i = 0; i < updates.length; i++) {
const upm = updates[i];
var upos = this.updates.indexOf(upm)
if (upos >= 0)
this.updates.splice(upos, 1);
}
}
onMousedown(event: MouseEvent) {
let rect = this.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / this.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / this.height) * 2 + 1;
if (event.button === 0) {
let intersect = this.getSelect(mouse, false);
}
}
onResize() {
this.size(window.innerWidth, window.innerHeight);
}
/**
* 世界坐标投影到屏幕坐标
* @param {Vector3} v3 世界坐标
*/
project(v3: Vector3) {
return v3.project(this.camera);
}
/**
* 世界坐标中的点对应document坐标
* @param {} v3
*/
getScreenPosition(v3: Vector3) {
v3 = this.project(v3);
let rect = this.domElement.getBoundingClientRect();
let x = ((v3.x + 1) / 2) * this.width + rect.left;
let y = -((v3.y - 1) / 2) * this.height + rect.top;
return new Vector2(x, y);
}
/**
* 从一个坐标点获取模型
* @param {} v2
* @param {} first=true
*/
getSelect(v2: Vector2, isMousePos = true, first = true) {
if (isMousePos) {
let rect = this.domElement.getBoundingClientRect();
v2.x = ((v2.x - rect.left) / this.width) * 2 - 1;
v2.y = -((v2.y - rect.top) / this.height) * 2 + 1;
}
//渲染区域之外
if (v2.x < -1 || v2.x > 1 || v2.y < -1 || v2.y > 1) return null;
raycaster.setFromCamera(v2, this.camera);
var intersects = raycaster.intersectObject(this.modelScene, true);
if (intersects.length > 0) {
if (first) return intersects[0];
else return intersects;
}
return null;
}
/**
* 将屏幕点反投影到世界坐标
* @param {} v3
*/
unproject(v3: Vector3) {
return v3.unproject(this.camera);
}
selectMD(mulSelected = false) {
if (!this.allowSelected) return null;
raycaster.setFromCamera(mouse, this.camera);
var intersects = raycaster.intersectObject(this.modelScene, true);
if (intersects.length > 0) {
var intersect = intersects[0];
const itrObj = this.getUserParent(intersect.object);
console.log(intersect.point);
if (!mulSelected) {
// 不允许多选
this.unselect();
}
if (!itrObj.selected) {
this.select(itrObj);
} else {
itrObj.selected = false;
var idx = this.selecteds.indexOf(itrObj);
this.selecteds.splice(idx, 1);
itrObj.material = itrObj.orgMaterial;
}
return itrObj;
} else {
this.unselect();
}
return null;
}
/**
* 设置要选中的模型为选中状态
* @param {} models
*/
selectModels(models: any) {
let ary = Array.isArray(models) ? models : [models];
//unselected
this.unselect();
//selected
this.select(ary);
}
select(models: any[] | undefined) {
if (!this.allowSelected) return;
if (models && !Array.isArray(models))
this._modelControl.attach(this.getUserParent(models));
let ary;
if (models === undefined) ary = this.selecteds;
else ary = Array.isArray(models) ? models : [models];
ary = ary.map((o: any) => this.getUserParent(o));
this.selecteds.push(...ary);
for (let i = 0; i < ary.length; i++) {
var model = ary[i];
//显示开始和结束的控制点
var model_bone;
model.children.forEach((cm: { name: string | string[]; }) => {
if (cm.name.indexOf("bone_start") !== -1) {
model_bone = cm;
return;
}
});
if (model_bone) {
this.startControl.attach(model_bone);
}
//End----------------------------------------------
for (let j = 0; j < model.children.length; j++) {
var m = model.children[j];
//当前层级的选中
if (m.name.indexOf("hide_node") !== -1) {
m.traverse((obj: { orgMaterial: any; material: MeshPhongMaterial; selected: boolean; }) => {
if (!obj.orgMaterial) obj.orgMaterial = obj.material;
obj.selected = true;
obj.material = selectMaterial;
});
}
//显示骨骼操作点
if (m.name.indexOf("bone") !== -1) m.visible = true;
}
}
}
/**
* 取消模型的选中状态
* @param {} models
*/
unselect(models?: any) {
this._modelControl.detach();
let ary;
if (models === undefined) ary = this.selecteds;
else ary = Array.isArray(models) ? models : [models];
for (let i = 0; i < ary.length; i++) {
var model = ary[i];
for (let j = 0; j < model.children.length; j++) {
var m = model.children[j];
//当前层级的选中
if (m.name.indexOf("hide_node") !== -1) {
if (m.orgMaterial && m.selected) m.material = m.orgMaterial;
}
//显示骨骼操作点
if (m.name.indexOf("bone") !== -1) m.visible = false;
}
}
// this.selectedObject.remove(...ary);
while (ary.length > 0) {
const objs = ary.pop();
objs.traverse((obj: { orgMaterial: any; selected: boolean; material: any; }) => {
if (obj.orgMaterial && obj.selected) obj.material = obj.orgMaterial;
obj.selected = false;
});
}
this.startControl.detach();
this.endControl.detach();
}
/**
* 判断点是否在渲染区域(是否可见)
* @param {} v3
*/
inRendererArea(v3: Vector3) {
v3 = this.project(v3);
return !(v3.x > 1 || v3.x < -1 || v3.y > 1 || v3.y < -1);
}
render() {
if (this._enablePostProcessing)
this.effectComposer.render()
else
this.renderer.render(this._scene, this._camera);
}
run() {
for (let i = 0; i < this.updates.length; i++) {
this.updates[i]();
}
this.render();
requestAnimationFrame(this.run.bind(this));
}
hide(obj: { visible: boolean; }) {
obj.visible = false;
}
hideOther(obj: { traverse: (arg0: (e: any) => void) => void; visible: boolean; parent: any; }) {
this.modelScene.traverse((e: { visible: boolean; }) => {
e.visible = false;
});
obj.traverse((e: { visible: boolean; }) => {
e.visible = true;
});
this.modelScene.visible = true;
while (obj !== this.modelScene) {
obj.visible = true;
obj = obj.parent;
}
}
showAll() {
this.modelScene.traverse((e: { visible: boolean; }) => {
e.visible = true;
});
}
//---模型转化使用API-----------------------------------------------------------------------
} | the_stack |
import { ArrayHelper } from '../../../ExtensionMethods';
import { DateTime } from "../../../DateTime";
import { EmailAddress } from "../../../ComplexProperties/EmailAddress";
import { ExchangeService } from "../../ExchangeService";
import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion";
import { ItemAttachment } from "../../../ComplexProperties/ItemAttachment";
import { ItemId } from "../../../ComplexProperties/ItemId";
import { MessageBody } from "../../../ComplexProperties/MessageBody";
import { PostReply } from '../ResponseObjects/PostReply';
import { Promise } from "../../../Promise";
import { PropertySet } from "../../PropertySet";
import { ResponseMessage } from "../ResponseObjects/ResponseMessage";
import { ResponseMessageType } from "../../../Enumerations/ResponseMessageType";
import { Schemas } from "../Schemas/Schemas";
import { ServiceObjectSchema } from "../Schemas/ServiceObjectSchema";
import { XmlElementNames } from "../../XmlElementNames";
import { Item } from "./Item";
/**
* Represents a post item. Properties available on post items are defined in the PostItemSchema class.
*
* @sealed
*/
export class PostItem extends Item {
/** required to check [Attachable] attribute, AttachmentCollection.AddItemAttachment<TItem>() checks for non inherited [Attachable] attribute. */
public static get Attachable(): boolean { return (<any>this).name === "PostItem"; };
/**
* Gets the conversation index of the post item.
*/
get ConversationIndex(): number[] {
return <number[]>this.PropertyBag._getItem(Schemas.EmailMessageSchema.ConversationIndex);
}
/**
* Gets the conversation topic of the post item.
*/
get ConversationTopic(): string {
return <string>this.PropertyBag._getItem(Schemas.EmailMessageSchema.ConversationTopic);
}
/**
* Gets or sets the "on behalf" poster of the post item.
*/
get From(): EmailAddress {
return <EmailAddress>this.PropertyBag._getItem(Schemas.EmailMessageSchema.From);
}
set From(value: EmailAddress) {
this.PropertyBag._setItem(Schemas.EmailMessageSchema.From, value);
}
/**
* Gets the Internet message Id of the post item.
*/
get InternetMessageId(): string {
return <string>this.PropertyBag._getItem(Schemas.EmailMessageSchema.InternetMessageId);
}
/**
* Gets or sets a value indicating whether the post item is read.
*/
get IsRead(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.EmailMessageSchema.IsRead);
}
set IsRead(value: boolean) {
this.PropertyBag._setItem(Schemas.EmailMessageSchema.IsRead, value);
}
/**
* Gets the the date and time when the post item was posted.
*/
get PostedTime(): DateTime {
return <DateTime>this.PropertyBag._getItem(Schemas.PostItemSchema.PostedTime);
}
/**
* Gets or sets the references of the post item.
*/
get References(): string {
return <string>this.PropertyBag._getItem(Schemas.EmailMessageSchema.References);
}
set References(value: string) {
this.PropertyBag._setItem(Schemas.EmailMessageSchema.References, value);
}
/**
* Gets or sets the sender (poster) of the post item.
*/
get Sender(): EmailAddress {
return <EmailAddress>this.PropertyBag._getItem(Schemas.EmailMessageSchema.Sender);
}
set Sender(value: EmailAddress) {
this.PropertyBag._setItem(Schemas.EmailMessageSchema.Sender, value);
}
/**
* Initializes an unsaved local instance of **PostItem**. To bind to an existing post item, use PostItem.Bind() instead.
*
* @param {ExchangeService} service The ExchangeService object to which the e-mail message will be bound.
*/
constructor(service: ExchangeService);
/**
* @internal Initializes a new instance of the **PostItem** class.
*
* @param {ItemAttachment} parentAttachment The parent attachment.
*/
constructor(parentAttachment: ItemAttachment);
constructor(serviceOrParentAttachment: any) {
super(serviceOrParentAttachment);
}
/**
* Binds to an existing post item and loads the specified set of properties.
* Calling this method results in a call to EWS.
*
* @param {ExchangeService} service The service to use to bind to the post item.
* @param {ItemId} id The Id of the post item to bind to.
* @param {PropertySet} propertySet The set of properties to load.
* @return {Promise<PostItem>} An PostItem instance representing the post item corresponding to the specified Id :Promise.
*/
public static Bind(service: ExchangeService, id: ItemId, propertySet: PropertySet): Promise<PostItem>;
/**
* Binds to an existing post item and loads its first class properties.
* Calling this method results in a call to EWS.
*
* @param {ExchangeService} service The service to use to bind to the post item.
* @param {ItemId} id The Id of the post item to bind to.
* @return {Promise<PostItem>} An PostItem instance representing the post item corresponding to the specified Id :Promise.
*/
public static Bind(service: ExchangeService, id: ItemId): Promise<PostItem>;
public static Bind(service: ExchangeService, id: ItemId, propertySet: PropertySet = PropertySet.FirstClassProperties): Promise<PostItem> {
return service.BindToItem<PostItem>(id, propertySet, PostItem);
}
/**
* Creates a forward response to the post item.
*
* @return {ResponseMessage} A ResponseMessage representing the forward response that can subsequently be modified and sent.
*/
CreateForward(): ResponseMessage {
this.ThrowIfThisIsNew();
return new ResponseMessage(this, ResponseMessageType.Forward);
}
/**
* Creates a post reply to this post item.
*
* @return {PostReply} A PostReply that can be modified and saved.
*/
CreatePostReply(): PostReply {
this.ThrowIfThisIsNew();
return new PostReply(this);
}
/**
* Creates a e-mail reply response to the post item.
*
* @param {boolean} replyAll Indicates whether the reply should go to everyone involved in the thread.
* @return {ResponseMessage} A ResponseMessage representing the e-mail reply response that can subsequently be modified and sent.
*/
CreateReply(replyAll: boolean): ResponseMessage {
this.ThrowIfThisIsNew();
return new ResponseMessage(
this,
replyAll ? ResponseMessageType.ReplyAll : ResponseMessageType.Reply);
}
/**
* Forwards the post item. Calling this method results in a call to EWS.
*
* @param {MessageBody} bodyPrefix The prefix to prepend to the original body of the post item.
* @param {...EmailAddress[]} toRecipients The recipients to forward the post item to.
* @return {Promise<void>} :Promise.
*/
Forward(bodyPrefix: MessageBody, ...toRecipients: EmailAddress[]): Promise<void>;
/**
* Forwards the post item. Calling this method results in a call to EWS.
*
* @param {MessageBody} bodyPrefix The prefix to prepend to the original body of the post item.
* @param {EmailAddress[]} toRecipients The recipients to forward the post item to.
* @return {Promise<void>} :Promise.
*/
Forward(bodyPrefix: MessageBody, toRecipients: EmailAddress[]): Promise<void>;
Forward(bodyPrefix: MessageBody, _toRecipients: EmailAddress[] | EmailAddress): Promise<void> {
let toRecipients: EmailAddress[] = [];
if (arguments.length <= 2) {
if (ArrayHelper.isArray(_toRecipients)) {
toRecipients = _toRecipients;
}
else {
toRecipients.push(arguments[1]);
}
}
else {
for (var _i = 1; _i < arguments.length; _i++) {
toRecipients[_i - 1] = arguments[_i];
}
}
let responseMessage: ResponseMessage = this.CreateForward();
responseMessage.BodyPrefix = bodyPrefix;
responseMessage.ToRecipients.AddRange(toRecipients);
return responseMessage.SendAndSaveCopy();
}
/**
* @internal Gets the minimum required server version.
*
* @return {ExchangeVersion} Earliest Exchange version in which this service object type is supported.
*/
GetMinimumRequiredServerVersion(): ExchangeVersion {
return ExchangeVersion.Exchange2007_SP1;
}
/**
* @internal Internal method to return the schema associated with this type of object.
*
* @return {ServiceObjectSchema} The schema associated with this type of object.
*/
GetSchema(): ServiceObjectSchema {
return Schemas.PostItemSchema.Instance;
}
/**
* @internal Gets the element name of item in XML
*
* @return {string} name of elelment
*/
GetXmlElementName(): string {
return XmlElementNames.PostItem;
}
/**
* Posts a reply to this post item. Calling this method results in a call to EWS.
*
* @param {MessageBody} bodyPrefix Body prefix.
* @return {Promise<void>} :Promise.
*/
PostReply(bodyPrefix: MessageBody): Promise<void> {
let postReply: PostReply = this.CreatePostReply();
postReply.BodyPrefix = bodyPrefix;
return <any>postReply.Save();
}
/**
* Replies to the post item. Calling this method results in a call to EWS.
*
* @param {MessageBody} bodyPrefix The prefix to prepend to the original body of the post item.
* @param {boolean} replyAll Indicates whether the reply should be sent to everyone involved in the thread.
* @return {Promise<void>} :Promise.
*/
Reply(bodyPrefix: MessageBody, replyAll: boolean): Promise<void> {
let responseMessage: ResponseMessage = this.CreateReply(replyAll);
responseMessage.BodyPrefix = bodyPrefix;
return responseMessage.SendAndSaveCopy();
}
} | the_stack |
import {
DocumentStore,
IDocumentStore,
PutConnectionStringOperation,
RavenConnectionString,
AddEtlOperation,
UpdateEtlOperation,
ResetEtlOperation,
RavenEtlConfiguration, Transformation, GetOngoingTaskInfoOperation
} from "../../../../../src";
import { disposeTestDocumentStore, RavenTestContext, testContext } from "../../../../Utils/TestUtil";
import { assertThat } from "../../../../Utils/AssertExtensions";
import { User } from "../../../../Assets/Entities";
import { ReplicationTestContext } from "../../../../Utils/ReplicationTestContext";
import { DeleteOngoingTaskOperation } from "../../../../../src/Documents/Operations/OngoingTasks/DeleteOngoingTaskOperation";
import { OngoingTaskRavenEtlDetails } from "../../../../../src/Documents/Operations/OngoingTasks/OngoingTask";
(RavenTestContext.isPullRequest ? describe.skip : describe)(
`${RavenTestContext.isPullRequest ? "[Skipped on PR] " : ""}` +
"EtlTest", function () {
let store: IDocumentStore;
let replication: ReplicationTestContext;
beforeEach(async function () {
store = await testContext.getDocumentStore();
replication = new ReplicationTestContext();
});
afterEach(async () =>
await disposeTestDocumentStore(store));
it("canAddEtl", async () => {
let src: DocumentStore;
let dst: DocumentStore;
try {
src = await testContext.getDocumentStore();
try {
dst = await testContext.getDocumentStore();
await insertDocument(src);
const result = await createConnectionString(src, dst);
assertThat(result)
.isNotNull();
const etlConfiguration = Object.assign(new RavenEtlConfiguration(), {
connectionStringName: "toDst",
disabled: false,
name: "etlToDst"
} as Partial<RavenEtlConfiguration>);
const transformation: Transformation = {
applyToAllDocuments: true,
name: "Script #1"
};
etlConfiguration.transforms = [ transformation ];
const operation = new AddEtlOperation(etlConfiguration);
const etlResult = await src.maintenance.send(operation);
assertThat(etlResult)
.isNotNull();
assertThat(etlResult.raftCommandIndex)
.isGreaterThan(0);
assertThat(etlResult.taskId)
.isGreaterThan(0);
assertThat(await replication.waitForDocumentToReplicate(dst, "users/1", 10 * 1000, User))
.isNotNull();
const ongoingTask = await src.maintenance.send(new GetOngoingTaskInfoOperation(etlResult.taskId, "RavenEtl")) as OngoingTaskRavenEtlDetails;
assertThat(ongoingTask)
.isNotNull();
assertThat(ongoingTask.taskId)
.isEqualTo(etlResult.taskId);
assertThat(ongoingTask.taskType)
.isEqualTo("RavenEtl");
assertThat(ongoingTask.responsibleNode)
.isNotNull();
assertThat(ongoingTask.taskState)
.isEqualTo("Enabled");
assertThat(ongoingTask.taskName)
.isEqualTo("etlToDst");
const deleteResult = await src.maintenance.send(
new DeleteOngoingTaskOperation(etlResult.taskId, "RavenEtl"));
assertThat(deleteResult.taskId)
.isEqualTo(etlResult.taskId);
} finally {
dst.dispose()
}
} finally {
src.dispose();
}
});
it ("canAddEtlWithScript", async () => {
let src: DocumentStore;
let dst: DocumentStore;
try {
src = await testContext.getDocumentStore();
try {
dst = await testContext.getDocumentStore();
await insertDocument(src);
const result = await createConnectionString(src, dst);
assertThat(result)
.isNotNull();
const etlConfiguration = Object.assign(new RavenEtlConfiguration(), {
connectionStringName: "toDst",
disabled: false,
name: "etlToDst"
} as Partial<RavenEtlConfiguration>);
const transformation: Transformation = {
applyToAllDocuments: false,
collections: ["Users"],
name: "Script #1",
script: "loadToUsers(this);"
};
etlConfiguration.transforms = [ transformation ];
const operation = new AddEtlOperation(etlConfiguration);
const etlResult = await src.maintenance.send(operation);
assertThat(etlResult)
.isNotNull();
assertThat(etlResult.raftCommandIndex)
.isGreaterThan(0);
assertThat(etlResult.taskId)
.isGreaterThan(0);
assertThat(await replication.waitForDocumentToReplicate(dst, "users/1", 10 * 1000, User))
.isNotNull();
} finally {
dst.dispose();
}
} finally {
src.dispose();
}
});
it("canUpdateEtl", async () => {
let src: DocumentStore;
let dst: DocumentStore;
try {
src = await testContext.getDocumentStore();
try {
dst = await testContext.getDocumentStore();
await insertDocument(src);
const result = await createConnectionString(src, dst);
assertThat(result)
.isNotNull();
const etlConfiguration = Object.assign(new RavenEtlConfiguration(), {
connectionStringName: "toDst",
disabled: false,
name: "etlToDst"
} as Partial<RavenEtlConfiguration>);
const transformation: Transformation = {
applyToAllDocuments: false,
collections: ["Users"],
name: "Script #1",
script: "loadToUsers(this);"
};
etlConfiguration.transforms = [ transformation ];
const operation = new AddEtlOperation(etlConfiguration);
const etlResult = await src.maintenance.send(operation);
assertThat(await replication.waitForDocumentToReplicate(dst, "users/1", 10 * 1000, User))
.isNotNull();
// now change ETL configuration
transformation.collections = ["Cars"];
transformation.script = "loadToCars(this);";
const updateResult = await src.maintenance.send(new UpdateEtlOperation(etlResult.taskId, etlConfiguration));
assertThat(updateResult)
.isNotNull();
assertThat(updateResult.raftCommandIndex)
.isGreaterThan(0);
assertThat(updateResult.taskId)
.isGreaterThan(etlResult.taskId);
// this document shouldn't be replicated via ETL
{
const session = src.openSession();
const user1 = Object.assign(new User(), { name: "John" });
await session.store(user1, "users/2");
await session.saveChanges();
}
assertThat(await replication.waitForDocumentToReplicate(dst, "users/2", 4000, User))
.isNull();
} finally {
dst.dispose();
}
} finally {
src.dispose();
}
});
it("canResetEtlTask", async () => {
let src: DocumentStore;
let dst: DocumentStore;
try {
src = await testContext.getDocumentStore();
try {
dst = await testContext.getDocumentStore();
await insertDocument(src);
const result = await createConnectionString(src, dst);
assertThat(result)
.isNotNull();
const transformation = {
applyToAllDocuments: true,
name: "Script Q&A"
} as Transformation;
const etlConfiguration = Object.assign(new RavenEtlConfiguration(), {
connectionStringName: "toDst",
disabled: false,
name: "etlToDst",
transforms: [ transformation ]
} as Partial<RavenEtlConfiguration>);
const operation = new AddEtlOperation(etlConfiguration);
const etlResult = await src.maintenance.send(operation);
assertThat(etlResult)
.isNotNull();
assertThat(etlResult.raftCommandIndex)
.isGreaterThan(0);
assertThat(etlResult.taskId)
.isGreaterThan(0);
await replication.waitForDocumentToReplicate(dst, "users/1", 10_000, User);
{
const session = dst.openSession();
await session.delete("users/1");
}
await src.maintenance.send(
new ResetEtlOperation("etlToDst", "Script Q&A"));
// etl was reset - waiting again for users/1 doc
await replication.waitForDocumentToReplicate(dst, "users/1", 10_000, User);
} finally {
dst.dispose();
}
} finally {
src.dispose();
}
});
});
function createConnectionString(src: IDocumentStore, dst: IDocumentStore) {
const toDstLink = new RavenConnectionString();
toDstLink.database = dst.database;
toDstLink.topologyDiscoveryUrls = [ ...dst.urls ];
toDstLink.name = "toDst";
return src.maintenance.send(new PutConnectionStringOperation(toDstLink));
}
async function insertDocument(src: IDocumentStore) {
const session = src.openSession();
const user1 = new User();
user1.name = "Marcin";
await session.store(user1, "users/1");
await session.saveChanges();
} | the_stack |
import { Application } from "spectron";
import {
startApp,
stopApp,
setupElectronLogs,
testSolutionPath,
addSolution,
clearSolutions,
} from "./hooks";
import path from "path";
import fs from "fs/promises";
const expectedWCFProgram: string =`
using CoreWCF.Configuration;
using System.Net;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
namespace WCFTCPSelfHost
{
public class Program
{
public static void Main(string[] args)
{
//All Ports set are default.
IWebHost host = CreateWebHostBuilder(args).Build();
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel(options => { })
.UseNetTcp(8000) .UseStartup<Startup>();
}
}
`;
const expectedWCFStartup: string =`
using CoreWCF.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace WCFTCPSelfHost
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
string pathToXml = @"C:\\testsolutions\\wcftcpselfhost\\WCFTCPSelfHost\\corewcf_ported.config";
services.AddServiceModelServices();
services.AddServiceModelConfigurationManagerFile(pathToXml);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseServiceModel();
}
}
}
`;
const expectedWCFConfig: string =
`<?xml version="1.0" encoding="utf-16" standalone="yes"?>
<configuration>
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="EndPointConfiguration">
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="mexBehavior">
<serviceMetadata httpGetEnabled="true" policyVersion="Policy15" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WcfServiceLibrary1.Service1" behaviorConfiguration="mexBehavior">
<endpoint address="/Service1" binding="netTcpBinding" bindingConfiguration="EndPointConfiguration" contract="WcfServiceLibrary1.IService1" />
</service>
</services>
</system.serviceModel>
</configuration>`;
describe("stability check, assess a solution, reassess the solution, check all solution tabs make sure loaded, check all projects for all solution, make sure loaded, check porting for all projects", () => {
let app: Application;
const escapeNonAlphaNumeric = (solutionPath: string) => {
return solutionPath.replace(/[^0-9a-zA-Z]/gi, "");
};
const selectProfile = async () => {
await app.client.pause(3000);
await (await app.client.$("#start-btn")).click();
await addNamedProfileCheck();
await (await app.client.$("#profile-selection")).click();
await (await app.client.$('[title="default"]')).click();
await (await app.client.$("#next-btn")).click();
await(await app.client.$("=Assess a new solution")).waitForDisplayed({
timeout: 60000,
});
};
const addNamedProfileCheck = async () => {
// profile selection model element is on top of add named profile link
// and will intercept the click so we offset by 3 pixels down
await (
await app.client.$("#add-named-profile")
).click({
button: "left",
x: 0,
y: 3,
});
await (await app.client.$("#add-profile-button")).click();
await (
await app.client.$("span=Profile is required")
).waitForExist({
timeout: 1000,
});
await app.client.keys(["Escape"]);
await (
await app.client.$("#profile-selection")
).waitForExist({
timeout: 1000,
});
};
const emptyEmailCheck = async () => {
await (await app.client.$("#feedback-btn")).click();
await (await app.client.$('#email-btn')).click();
await (
await app.client.$("span=Invalid e-mail format.")
).waitForExist({
timeout: 1000,
});
await app.client.keys(["Escape"]);
};
const invalidEmailCheck = async () => {
await (await app.client.$("#feedback-btn")).click();
await (await app.client.$('#email-input input')).setValue("integration.test.com");
await (await app.client.$('#email-btn')).click();
await (
await app.client.$("span=Invalid e-mail format.")
).waitForExist({
timeout: 1000,
});
await app.client.keys(["Escape"]);
}
const setupEmail = async () => {
await (await app.client.$('#email-input input')).setValue("integration@test.com");
await (await app.client.$('#email-btn')).click();
};
const sendFeedbackCheck = async () => {
await (await app.client.$("#feedback-btn")).click();
await setupEmail();
await (await app.client.$("#fb-category-selection")).click();
await (await app.client.$('[data-testid="general"]')).click();
await (await app.client.$('#fb-text input')).setValue("integration-test-feedback");
await (await app.client.$("#send-feedback-btn")).click();
console.log("Sent customer feedback success");
};
const emptyFeedbackCheck = async () => {
await (await app.client.$("#feedback-btn")).click();
await (await app.client.$("#send-feedback-btn")).click();
await app.client.keys(["Escape"]);
};
const sendRuleContributionCheck = async () => {
await (await app.client.$(`a[data-testid="nuget-packages"]`)).click();
await (await app.client.$("=NuGet packages")).waitForDisplayed();
await (await app.client.$('._input_wtz7u_3')).setValue('jQuery.vsdoc');
await (await app.client.$('._label_4pfx5_7')).click();
await (await app.client.$('#rule-contribution-btn')).click();
await (await app.client.$("=Suggest replacement")).waitForDisplayed();
await (await app.client.$('#rc-package-name input')).setValue("Azure.ImageOptimizer");
await (await app.client.$('#rc-version-check-box')).click();
await (await app.client.$('#rc-comment input')).setValue("integration-test-rule-contribution");
await (await app.client.$("#rc-send-btn")).click();
console.log("Sent rule contribution success");
};
const runThroughSolution = async (
solutionPath: string,
portingPlace: string,
targetFramework: string,
sendFeedback: boolean,
sendRuleContribution: boolean,
) => {
const solutionNameTagId = `#solution-link-${escapeNonAlphaNumeric(
solutionPath
)}`;
console.log(`assessing solution ${solutionNameTagId}....`);
await assessSolutionCheck(solutionNameTagId);
console.log(`assess solution ${solutionNameTagId} success`);
if (sendFeedback) {
await invalidEmailCheck();
await emptyEmailCheck();
await sendFeedbackCheck();
await emptyFeedbackCheck();
}
if (sendRuleContribution) {
await sendRuleContributionCheck();
}
console.log(`reassessing solution ${solutionNameTagId}....`);
const assessmentResults = await reassessSolutionCheck(
solutionNameTagId,
solutionPath
);
console.log(`reassess solution ${solutionNameTagId} success`);
console.log(`checking tabs in solution ${solutionNameTagId}`);
const numSourceFiles = await solutionTabCheck();
assessmentResults.push(numSourceFiles);
const projectName = await app.client.$(".project-name");
if (!projectName.isExisting()) {
return;
}
let projectstring: string = await projectName.getAttribute("id");
const projects: string[] = projectstring.toString().split(",");
const solutionPage = `=${solutionPath.split("\\").pop()}`;
console.log(`checking projects for ${solutionNameTagId}`);
for (let i = 0; i < 2 && i < projects.length; i++) {
const project = projects[i];
await projectTabCheck();
await (await app.client.$(`#${project}`)).click();
if (project == projects[0]) {
await portingProjectsCheck(portingPlace);
} else {
await portingProjectsCheck("other");
}
await app.client.pause(2000);
await (
await app.client.$("._circle_oh9fc_75")
).waitForExist({
reverse: true,
timeout: 1000000,
});
await (await app.client.$(solutionNameTagId)).click();
}
await checkPortingProjectResults(
solutionNameTagId,
projects[0],
targetFramework
);
return assessmentResults;
};
const checkAssessmentResults = async (solutionPath: string) => {
const escapedSolutionPath = escapeNonAlphaNumeric(solutionPath);
return await Promise.all([
await (
await app.client.$(`#ported-projects-${escapedSolutionPath}`)
).getText(),
await (
await app.client.$(`#incompatible-packages-${escapedSolutionPath}`)
).getText(),
await (
await app.client.$(`#incompatible-apis-${escapedSolutionPath}`)
).getText(),
await (
await app.client.$(`#build-error-${escapedSolutionPath}`)
).getText(),
]);
};
const assessSolutionCheck = async (solutionNameTagId: string) => {
await (
await app.client.$("._circle_oh9fc_75")
).waitForExist({
reverse: true,
timeout: 800000,
});
await (await app.client.$(solutionNameTagId)).click();
};
const reassessSolutionCheck = async (
solutionNameTagId: string,
solutionPath: string
) => {
const reassessSolution = await app.client.$("#reassess-solution");
await reassessSolution.waitForEnabled({ timeout: 600000 });
await reassessSolution.click();
await (
await app.client.$("._circle_oh9fc_75")
).waitForExist({
reverse: true,
timeout: 1000000,
});
const results = await checkAssessmentResults(solutionPath);
await (await app.client.$(solutionNameTagId)).click();
return results;
};
const solutionTabCheck = async () => {
const projectReferenceTab = await app.client.$(
`a[data-testid="project-references"]`
);
await projectReferenceTab.waitForExist({ timeout: 100000 });
await projectReferenceTab.click();
await (
await app.client.$("#project-dependencies")
).waitForExist({
timeout: 600000,
});
await (await app.client.$(`a[data-testid="nuget-packages"]`)).click();
await (await app.client.$("=NuGet packages")).waitForDisplayed();
await (await app.client.$(`a[data-testid="apis"]`)).click();
await (await app.client.$("=APIs")).waitForDisplayed();
await (await app.client.$(`a[data-testid="source-files"]`)).click();
await (await app.client.$("=Source files")).waitForDisplayed();
const numSourceFiles = await (
await app.client.$("._counter_14rjr_108")
).getText();
await (await app.client.$(`a[data-testid="projects"]`)).click();
await (await app.client.$("=Projects")).waitForDisplayed();
return numSourceFiles;
};
const projectTabCheck = async () => {
await (await app.client.$(`a[data-testid="project-references"]`)).click();
await (
await app.client.$("#project-dependencies")
).waitForExist({
timeout: 400000,
});
await (await app.client.$(`a[data-testid="nuget-packages"]`)).click();
await (await app.client.$("=NuGet packages")).waitForDisplayed();
await (await app.client.$(`a[data-testid="apis"]`)).click();
await (await app.client.$("=APIs")).waitForDisplayed();
await (await app.client.$(`a[data-testid="source-files"]`)).click();
await (await app.client.$("=Source files")).waitForDisplayed();
await (await app.client.$(`a[data-testid="projects"]`)).click();
await (await app.client.$("=Projects")).waitForDisplayed();
};
const portingProjectsCheck = async (selectLocation: string) => {
await (await app.client.$("#port-project-button")).click();
if (selectLocation == "inplace") {
await (await app.client.$("#select-location-button")).click();
await (await app.client.$(`div[data-value="inplace"]`)).click();
await (await app.client.$("#save-button")).click();
} else if (selectLocation == "copy") {
await (await app.client.$("#select-location-button")).click();
await (await app.client.$(`div[data-value="copy"]`)).click();
await (await app.client.$(`icon="folder-open"`)).click();
await (await app.client.$("#save-button")).click();
await app.client.pause(3000);
await (
await app.client.$("#incompatible")
).waitForExist({
timeout: 50000,
});
}
await (await app.client.$("#port-project-title")).waitForExist();
await (await app.client.$("#port-button")).click();
};
const checkPortingProjectResults = async (
solutionNameTagId: string,
firstProjectId: string,
expectedTargetFramework: string
) => {
// porting will kick off a new assessment, wait for it to finish before
// clicking into the solution
const solutionLink = await app.client.$(solutionNameTagId);
if (await solutionLink.isExisting()) {
await (
await app.client.$("._circle_oh9fc_75")
).waitForExist({
reverse: true,
timeout: 800000,
});
await solutionLink.click();
}
// should be 'project-name-[projectfilepath]'
const projectFilePath = firstProjectId.split("-")[2];
const targetFramework = await (
await app.client.$(`#target-framework-${projectFilePath}`)
).getText();
expect(targetFramework).toBe(expectedTargetFramework);
};
const validateHighLevelResults = async (
results: string[] | undefined,
expectedValues: string[]
) => {
// [portedProjects, incompatiblePackages, incompatibleApis, buildErrors, numSourceFiles]
expect(results).toBeTruthy();
expect(results ? results[0] : "").toBe(expectedValues[0]);
expect(results ? results[1] : "").toBe(expectedValues[1]);
expect(results ? results[2] : "").toBe(expectedValues[2]);
expect(results ? results[3] : "").toBe(expectedValues[3]);
expect(results ? results[4] : "").toBe(expectedValues[4]);
};
beforeAll(async () => {
app = await startApp();
await selectProfile();
return app;
});
beforeEach(async () => {
await app.client.refresh();
});
afterEach(async () => {
setupElectronLogs(app);
await clearSolutions(app);
await app.client.pause(1000);
await app.client.refresh();
});
afterAll(async () => {
await app.client.execute("window.test.clearState();");
await stopApp(app);
});
test("run through NopCommerce 3.1.0", async () => {
const solutionFolderPath: string = path.join(
testSolutionPath(),
"nopCommerce-release-3.10",
"src"
);
const solutionPath: string = path.join(
solutionFolderPath,
"NopCommerce.sln"
);
await addSolution(app, solutionPath);
await app.client.refresh();
const results = await runThroughSolution(
solutionPath,
"inplace",
"netcoreapp3.1",
false,
false
);
await validateHighLevelResults(results, [
"0 of 40",
"37 of 38",
"447 of 1256",
"0",
"(1565)",
]);
const getCatalogController = fs.readFile(
path.join(solutionFolderPath, "Libraries", "Nop.Core", "Nop.Core.csproj"),
"utf8"
);
expect(
(await getCatalogController).indexOf('Include="Autofac" Version="4.0.0"')
).not.toBe(-1);
});
test("run through mvcmusicstore", async () => {
const solutionFolderPath: string = path.join(
testSolutionPath(),
"mvcmusicstore",
"sourceCode",
"mvcmusicstore"
);
const solutionPath: string = path.join(
solutionFolderPath,
"MvcMusicStore.sln"
);
await addSolution(app, solutionPath);
await app.client.refresh();
const results = await runThroughSolution(
solutionPath,
"inplace",
"netcoreapp3.1",
true,
true
);
await validateHighLevelResults(results, [
"0 of 1",
"2 of 6",
"50 of 81",
"0",
"(21)",
]);
const controllerFolderPath: string = path.join(
solutionFolderPath,
"MvcMusicStore",
"Controllers"
);
const getAccountController = fs.readFile(
path.join(controllerFolderPath, "AccountController.cs"),
"utf8"
);
const getStoreManagerController = fs.readFile(
path.join(controllerFolderPath, "StoreManagerController.cs"),
"utf8"
);
expect(
(await getAccountController).indexOf("Microsoft.AspNetCore.Mvc")
).not.toBe(-1);
expect(
(await getStoreManagerController).indexOf("Microsoft.EntityFrameworkCore")
).not.toBe(-1);
});
test("run through Miniblog", async () => {
const solutionPath: string = path.join(
testSolutionPath(),
"Miniblog.Core-master",
"Miniblog.Core.sln"
);
await addSolution(app, solutionPath);
await app.client.refresh();
const results = await runThroughSolution(
solutionPath,
"inplace",
"netcoreapp3.1",
false,
false
);
await validateHighLevelResults(results, [
"1 of 1",
"0 of 13",
"5 of 249",
"0",
"(21)",
]);
});
test("run through wcf", async () => {
const solutionFolderPath: string = path.join(
testSolutionPath(),
"wcftcpselfhost"
);
const solutionPath: string = path.join(
solutionFolderPath,
"WCFTCPSelfHost.sln"
);
await addSolution(app, solutionPath);
await app.client.refresh();
const results = await runThroughSolution(
solutionPath,
"inplace",
"netcoreapp3.1",
false,
false
);
await validateHighLevelResults(results, [
"0 of 3",
"0 of 0",
"8 of 26",
"0",
"(11)",
]);
const selfHostProjectPath: string = path.join(
solutionFolderPath,
"WCFTCPSelfHost",
)
const getCsProj = fs.readFile(
path.join(selfHostProjectPath, "WCFTCPSelfHost.csproj"),
"utf-8"
)
expect((await getCsProj).indexOf("CoreWCF.Primitives")).not.toBe(-1);
expect((await getCsProj).indexOf("CoreWCF.Http")).not.toBe(-1);
expect((await getCsProj).indexOf("CoreWCF.NetTcp")).not.toBe(-1);
const getStartup = fs.readFile(
path.join(selfHostProjectPath, "Startup.cs"),
"utf-8"
)
const getProgram = fs.readFile(
path.join(selfHostProjectPath, "Program.cs"),
"utf-8"
)
const getConfig = fs.readFile(
path.join(selfHostProjectPath, "corewcf_ported.config"),
"utf-8"
)
expect((await getStartup)).toBe(expectedWCFStartup);
expect((await getProgram)).toBe(expectedWCFProgram);
expect((await getConfig).replace(/(\r\n|\n|\r)/gm, "")).toBe(expectedWCFConfig.replace(/(\r\n|\n|\r)/gm, ""));
});
test("run through wcf on net 6.0", async () => {
const solutionFolderPath: string = path.join(
testSolutionPath(),
"wcftcpselfhost"
);
const solutionPath: string = path.join(
solutionFolderPath,
"WCFTCPSelfHost.sln"
);
await addSolution(app, solutionPath);
await app.client.refresh();
const results = await runThroughSolution(
solutionPath,
"inplace",
"netcoreapp3.1",
false,
false
);
await validateHighLevelResults(results, [
"0 of 3",
"0 of 0",
"8 of 26",
"0",
"(11)",
]);
});
test("run through mvcmusicstore on net 6.0", async () => {
const solutionFolderPath: string = path.join(
testSolutionPath(),
"mvcmusicstore",
"sourceCode",
"mvcmusicstore"
);
const solutionPath: string = path.join(
solutionFolderPath,
"MvcMusicStore.sln"
);
await addSolution(app, solutionPath);
await app.client.refresh();
const results = await runThroughSolution(
solutionPath,
"inplace",
"net6.0",
false,
false
);
await validateHighLevelResults(results, [
"0 of 1",
"2 of 6",
"50 of 81",
"0",
"(21)",
]);
});
}); | the_stack |
import { IExceptionContext, ITableSection, range } from 'lineupengine';
import { IGroupData, IGroupItem, IOrderedGroup, isGroup, Ranking } from '../model';
import { aria, cssClass, engineCssClass, SLOPEGRAPH_WIDTH } from '../styles';
import { IRankingHeaderContextContainer, EMode } from './interfaces';
import { forEachIndices, filterIndices } from '../model/internal';
interface ISlope {
isSelected(selection: { has(dataIndex: number): boolean }): boolean;
update(path: SVGPathElement, width: number): void;
readonly dataIndices: number[];
}
class ItemSlope implements ISlope {
constructor(private readonly left: number, private readonly right: number, public readonly dataIndices: number[]) {}
isSelected(selection: { has(dataIndex: number): boolean }) {
return this.dataIndices.length === 1
? selection.has(this.dataIndices[0])
: this.dataIndices.some((s) => selection.has(s));
}
update(path: SVGPathElement, width: number) {
path.setAttribute('data-i', String(this.dataIndices[0]));
path.setAttribute('class', cssClass('slope'));
path.setAttribute('d', `M0,${this.left}L${width},${this.right}`);
}
}
class GroupSlope implements ISlope {
constructor(
private readonly left: [number, number],
private readonly right: [number, number],
public readonly dataIndices: number[]
) {}
isSelected(selection: { has(dataIndex: number): boolean }) {
return this.dataIndices.some((s) => selection.has(s));
}
update(path: SVGPathElement, width: number) {
path.setAttribute('class', cssClass('group-slope'));
path.setAttribute('d', `M0,${this.left[0]}L${width},${this.right[0]}L${width},${this.right[1]}L0,${this.left[1]}Z`);
}
}
interface IPos {
start: number;
heightPerRow: number;
rows: number[]; // data indices
offset: number;
ref: number[];
group: IOrderedGroup;
}
export interface ISlopeGraphOptions {
mode: EMode;
}
export default class SlopeGraph implements ITableSection {
readonly node: SVGSVGElement;
private leftSlopes: ISlope[][] = [];
// rendered row to one ore multiple slopes
private rightSlopes: ISlope[][] = [];
private readonly pool: SVGPathElement[] = [];
private scrollListener: ((act: { top: number; height: number }) => void) | null = null;
readonly width = SLOPEGRAPH_WIDTH;
readonly height = 0;
private current: {
leftRanking: Ranking;
left: (IGroupItem | IGroupData)[];
leftContext: IExceptionContext;
rightRanking: Ranking;
right: (IGroupItem | IGroupData)[];
rightContext: IExceptionContext;
} | null = null;
private chosen = new Set<ISlope>();
private chosenSelectionOnly = new Set<ISlope>();
private _mode: EMode = EMode.ITEM;
constructor(
public readonly header: HTMLElement,
public readonly body: HTMLElement,
public readonly id: string,
private readonly ctx: IRankingHeaderContextContainer,
options: Partial<ISlopeGraphOptions> = {}
) {
this.node = header.ownerDocument!.createElementNS('http://www.w3.org/2000/svg', 'svg');
this.node.innerHTML = `<g transform="translate(0,0)"></g>`;
header.classList.add(cssClass('slopegraph-header'));
this._mode = options.mode === EMode.BAND ? EMode.BAND : EMode.ITEM;
this.initHeader(header);
body.classList.add(cssClass('slopegraph'));
this.body.style.height = `1px`;
body.appendChild(this.node);
}
init() {
this.hide(); // hide by default
const scroller = this.body.parentElement! as any;
//sync scrolling of header and body
// use internals from lineup engine
const scroll = scroller.__le_scroller__;
let old: { top: number; height: number } = scroll.asInfo();
scroll.push(
'animation',
(this.scrollListener = (act: { top: number; height: number }) => {
if (Math.abs(old.top - act.top) < 5) {
return;
}
old = act;
this.onScrolledVertically(act.top, act.height);
})
);
}
private initHeader(header: HTMLElement) {
const active = cssClass('active');
header.innerHTML = `<i title="Item" class="${this._mode === EMode.ITEM ? active : ''}">${aria('Item')}</i>
<i title="Band" class="${this._mode === EMode.BAND ? active : ''}">${aria('Band')}</i>`;
const icons = Array.from(header.children) as HTMLElement[];
icons.forEach((n: HTMLElement, i) => {
n.onclick = (evt) => {
evt.preventDefault();
evt.stopPropagation();
if (n.classList.contains(active)) {
return;
}
this.mode = i === 0 ? EMode.ITEM : EMode.BAND;
icons.forEach((d, j) => d.classList.toggle(active, j === i));
};
});
}
get mode() {
return this._mode;
}
set mode(value: EMode) {
if (value === this._mode) {
return;
}
this._mode = value;
if (this.current) {
this.rebuild(
this.current.leftRanking,
this.current.left,
this.current.leftContext,
this.current.rightRanking,
this.current.right,
this.current.rightContext
);
}
}
get hidden() {
return this.header.classList.contains(engineCssClass('loading'));
}
set hidden(value: boolean) {
this.header.classList.toggle(engineCssClass('loading'), value);
this.body.classList.toggle(engineCssClass('loading'), value);
}
hide() {
this.hidden = true;
}
show() {
const was = this.hidden;
this.hidden = false;
if (was) {
this.revalidate();
}
}
destroy() {
this.header.remove();
if (this.scrollListener) {
//sync scrolling of header and body
// use internals from lineup engine
const scroll = (this.body.parentElement! as any).__le_scroller__;
scroll.remove(this.scrollListener);
}
this.body.remove();
}
rebuild(
leftRanking: Ranking,
left: (IGroupItem | IGroupData)[],
leftContext: IExceptionContext,
rightRanking: Ranking,
right: (IGroupItem | IGroupData)[],
rightContext: IExceptionContext
) {
this.current = { leftRanking, left, leftContext, right, rightRanking, rightContext };
const lookup: Map<number, IPos> = this.prepareRightSlopes(right, rightContext);
this.computeSlopes(left, leftContext, lookup);
this.revalidate();
}
private computeSlopes(left: (IGroupItem | IGroupData)[], leftContext: IExceptionContext, lookup: Map<number, IPos>) {
const mode = this.mode;
const fakeGroups = new Map<IOrderedGroup, ISlope[]>();
const createFakeGroup = (first: number, group: IOrderedGroup) => {
let count = 0;
let height = 0;
// find all items in this group, assuming that they are in order
for (let i = first; i < left.length; ++i) {
const item = left[i];
if (isGroup(item) || (item as IGroupItem).group !== group) {
break;
}
count++;
height += leftContext.exceptionsLookup.get(i) || leftContext.defaultRowHeight;
}
const padded = height - leftContext.padding(first + count - 1);
const gr = group;
return { gr, padded, height };
};
let acc = 0;
this.leftSlopes = left.map((r, i) => {
let height = leftContext.exceptionsLookup.get(i) || leftContext.defaultRowHeight;
let padded = height - 0; //leftContext.padding(i);
const slopes: ISlope[] = [];
const start = acc;
// shift by item height
acc += height;
let offset = 0;
const push = (s: ISlope, right: IPos, common = 1, heightPerRow = 0) => {
// store slope in both
slopes.push(s);
forEachIndices(right.ref, (r) => this.rightSlopes[r].push(s));
// update the offset of myself and of the right side
right.offset += common * right.heightPerRow;
offset += common * heightPerRow;
};
let gr: IGroupData;
if (isGroup(r)) {
gr = r;
} else {
const item = r as IGroupItem;
const dataIndex = item.dataIndex;
const right = lookup.get(dataIndex);
if (!right) {
// no match
return slopes;
}
if (mode === EMode.ITEM) {
const s = new ItemSlope(start + padded / 2, right.start + right.offset + right.heightPerRow / 2, [dataIndex]);
push(s, right);
return slopes;
}
if (fakeGroups.has(item.group)) {
// already handled by the first one, take the fake slopes
return fakeGroups.get(item.group)!;
}
const fakeGroup = createFakeGroup(i, item.group);
gr = fakeGroup.gr;
height = fakeGroup.height;
padded = fakeGroup.padded;
fakeGroups.set(item.group, slopes);
}
// free group items to share
const free = new Set(gr.order);
const heightPerRow = padded / gr.order.length;
forEachIndices(gr.order, (d: number) => {
if (!free.has(d)) {
return; // already handled
}
free.delete(d);
const right = lookup.get(d);
if (!right) {
return; // no matching
}
// find all of this group
const intersection = filterIndices(right.rows, (r) => free.delete(r));
intersection.push(d); //self
const common = intersection.length;
let s: ISlope;
if (common === 1) {
s = new ItemSlope(start + offset + heightPerRow / 2, right.start + right.offset + right.heightPerRow / 2, [
d,
]);
} else if (mode === EMode.ITEM) {
// fake item
s = new ItemSlope(
start + offset + (heightPerRow * common) / 2,
right.start + right.offset + (right.heightPerRow * common) / 2,
intersection
);
} else {
s = new GroupSlope(
[start + offset, start + offset + heightPerRow * common],
[right.start + right.offset, right.start + right.offset + right.heightPerRow * common],
intersection
);
}
push(s, right, common, heightPerRow);
});
return slopes;
});
}
private prepareRightSlopes(right: (IGroupItem | IGroupData)[], rightContext: IExceptionContext) {
const lookup = new Map<number, IPos>();
const mode = this.mode;
const fakeGroups = new Map<IOrderedGroup, IPos>();
let acc = 0;
this.rightSlopes = right.map((r, i) => {
const height = rightContext.exceptionsLookup.get(i) || rightContext.defaultRowHeight;
const padded = height - 0; //rightContext.padding(i);
const start = acc;
acc += height;
const slopes: ISlope[] = [];
const base = {
start,
offset: 0,
ref: [i],
};
if (isGroup(r)) {
const p = Object.assign(base, {
rows: Array.from(r.order),
heightPerRow: padded / r.order.length,
group: r,
});
forEachIndices(r.order, (ri) => lookup.set(ri, p));
return slopes;
}
// item
const item = r as IGroupItem;
const dataIndex = r.dataIndex;
let p = Object.assign(base, {
rows: [dataIndex],
heightPerRow: padded,
group: item.group,
});
if (mode === EMode.ITEM) {
lookup.set(dataIndex, p);
return slopes;
}
// forced band mode
// merge with the 'ueber' band
if (!fakeGroups.has(item.group)) {
p.heightPerRow = height; // include padding
// TODO just support uniform item height
fakeGroups.set(item.group, p);
} else {
// reuse old
p = fakeGroups.get(item.group)!;
p.rows.push(dataIndex);
p.ref.push(i);
}
lookup.set(dataIndex, p);
return slopes;
});
return lookup;
}
private revalidate() {
if (!this.current || this.hidden) {
return;
}
const p = this.body.parentElement!;
this.onScrolledVertically(p.scrollTop, p.clientHeight);
}
highlight(dataIndex: number) {
const highlight = engineCssClass('highlighted');
const old = this.body.querySelector(`[data-i].${highlight}`);
if (old) {
old.classList.remove(highlight);
}
if (dataIndex < 0) {
return false;
}
const item = this.body.querySelector(`[data-i="${dataIndex}"]`);
if (item) {
item.classList.add(highlight);
}
return item != null;
}
private onScrolledVertically(scrollTop: number, clientHeight: number) {
if (!this.current) {
return;
}
// which lines are currently shown
const { leftContext, rightContext } = this.current;
const left = range(
scrollTop,
clientHeight,
leftContext.defaultRowHeight,
leftContext.exceptions,
leftContext.numberOfRows
);
const right = range(
scrollTop,
clientHeight,
rightContext.defaultRowHeight,
rightContext.exceptions,
rightContext.numberOfRows
);
const start = Math.min(left.firstRowPos, right.firstRowPos);
const end = Math.max(left.endPos, right.endPos);
// move to right position
this.body.style.transform = `translate(0, ${start.toFixed(0)}px)`;
this.body.style.height = `${(end - start).toFixed(0)}px`;
this.node.firstElementChild!.setAttribute('transform', `translate(0,-${start.toFixed(0)})`);
this.chosen = this.choose(left.first, left.last, right.first, right.last);
this.render(this.chosen, this.chooseSelection(left.first, left.last, this.chosen));
}
private choose(
leftVisibleFirst: number,
leftVisibleLast: number,
rightVisibleFirst: number,
rightVisibleLast: number
) {
// assume no separate scrolling
const slopes = new Set<ISlope>();
for (let i = leftVisibleFirst; i <= leftVisibleLast; ++i) {
for (const s of this.leftSlopes[i]) {
slopes.add(s);
}
}
for (let i = rightVisibleFirst; i <= rightVisibleLast; ++i) {
for (const s of this.rightSlopes[i]) {
slopes.add(s);
}
}
return slopes;
}
private chooseSelection(leftVisibleFirst: number, leftVisibleLast: number, alreadyVisible: Set<ISlope>) {
const slopes = new Set<ISlope>();
// ensure selected slopes are always part of
const p = this.ctx.provider;
if (p.getSelection().length === 0) {
return slopes;
}
const selectionLookup = { has: (dataIndex: number) => p.isSelected(dataIndex) };
// try all not visible ones
for (let i = 0; i < leftVisibleFirst; ++i) {
for (const s of this.leftSlopes[i]) {
if (s.isSelected(selectionLookup) && !alreadyVisible.has(s)) {
slopes.add(s);
}
}
}
for (let i = leftVisibleLast + 1; i < this.leftSlopes.length; ++i) {
for (const s of this.leftSlopes[i]) {
if (s.isSelected(selectionLookup) && !alreadyVisible.has(s)) {
slopes.add(s);
}
}
}
return slopes;
}
private updatePath(
p: SVGPathElement,
g: SVGGElement,
s: ISlope,
width: number,
selection: { has(dataIndex: number): boolean }
) {
s.update(p, width);
(p as any).__data__ = s; // data binding
const selected = s.isSelected(selection);
p.classList.toggle(cssClass('selected'), selected);
if (selected) {
g.appendChild(p); // to put it on top
}
}
private render(visible: Set<ISlope>, selectionSlopes: Set<ISlope>) {
const g = this.node.firstElementChild! as SVGGElement;
const width = g.ownerSVGElement!.getBoundingClientRect()!.width;
const paths = this.matchLength(visible.size + selectionSlopes.size, g);
const p = this.ctx.provider;
const selectionLookup = { has: (dataIndex: number) => p.isSelected(dataIndex) };
// update paths
let i = 0;
const updatePath = (s: ISlope) => {
this.updatePath(paths[i++], g, s, width, selectionLookup);
};
visible.forEach(updatePath);
selectionSlopes.forEach(updatePath);
}
private addPath(g: SVGGElement) {
const elem = this.pool.pop();
if (elem) {
g.appendChild(elem);
return elem;
}
const path = g.ownerDocument!.createElementNS('http://www.w3.org/2000/svg', 'path');
path.onclick = (evt) => {
// d3 style
const s: ISlope = (path as any).__data__;
const p = this.ctx.provider;
const ids = s.dataIndices;
if (evt.ctrlKey) {
ids.forEach((id) => p.toggleSelection(id, true));
} else {
// either unset or set depending on the first state
const isSelected = p.isSelected(ids[0]!);
p.setSelection(isSelected ? [] : ids);
}
};
g.appendChild(path);
return path;
}
private matchLength(slopes: number, g: SVGGElement) {
const paths = Array.from(g.children) as SVGPathElement[];
for (let i = slopes; i < paths.length; ++i) {
const elem = paths[i];
this.pool.push(elem);
elem.remove();
}
for (let i = paths.length; i < slopes; ++i) {
paths.push(this.addPath(g));
}
return paths;
}
updateSelection(selectedDataIndices: Set<number>) {
const g = this.node.firstElementChild! as SVGGElement;
const paths = Array.from(g.children) as SVGPathElement[];
const openDataIndices = new Set(selectedDataIndices);
if (selectedDataIndices.size === 0) {
// clear
for (const p of paths) {
const s: ISlope = (p as any).__data__;
p.classList.toggle(cssClass('selected'), false);
if (this.chosenSelectionOnly.has(s)) {
p.remove();
}
}
this.chosenSelectionOnly.clear();
return;
}
for (const p of paths) {
const s: ISlope = (p as any).__data__;
const selected = s.isSelected(selectedDataIndices);
p.classList.toggle(cssClass('selected'), selected);
if (!selected) {
if (this.chosenSelectionOnly.delete(s)) {
// was only needed because of the selection
p.remove();
}
continue;
}
g.appendChild(p); // to put it on top
// remove already handled
s.dataIndices.forEach((d) => openDataIndices.delete(d));
}
if (openDataIndices.size === 0) {
return;
}
// find and add missing slopes
const width = g.ownerSVGElement!.getBoundingClientRect()!.width;
for (const ss of this.leftSlopes) {
for (const s of ss) {
if (this.chosen.has(s) || this.chosenSelectionOnly.has(s) || !s.isSelected(openDataIndices)) {
// not visible or not selected -> skip
continue;
}
// create new path for it
this.chosenSelectionOnly.add(s);
const p = this.addPath(g);
this.updatePath(p, g, s, width, openDataIndices);
}
}
}
} | the_stack |
import chai from 'chai';
import 'mocha';
const expect = chai.expect;
import { Game } from '../src/Game';
import { Resource } from '../src/Resource';
import { DEFAULT_CONFIGS } from '../src/defaults';
describe('Test resource collection and distribution', () => {
let game: Game;
const rates = DEFAULT_CONFIGS.parameters.WORKER_COLLECTION_RATE;
beforeEach(() => {
game = new Game({
width: 16,
height: 16,
});
});
it('should distribute evenly given all workers have space and abundance of resource', () => {
const cell = game.map.getCell(4, 4);
cell.setResource(Resource.Types.WOOD, rates.WOOD * 10);
const w1 = game.spawnWorker(0, 4, 4);
const w2 = game.spawnWorker(1, 4, 5);
game.distributeAllResources();
expect(w1.cargo.wood).to.equal(rates.WOOD);
expect(w2.cargo.wood).to.equal(rates.WOOD);
expect(cell.resource.amount).to.equal(rates.WOOD * 8);
});
it('should distribute evenly given all workers have space and limited resources ', () => {
const cell = game.map.getCell(4, 4);
cell.setResource(Resource.Types.WOOD, rates.WOOD);
const w1 = game.spawnWorker(0, 4, 4);
const w2 = game.spawnWorker(1, 4, 5);
game.distributeAllResources();
expect(w1.cargo.wood).to.equal(Math.floor(rates.WOOD / 2));
expect(w2.cargo.wood).to.equal(Math.floor(rates.WOOD / 2));
expect(cell.resource.amount).to.equal(0);
});
it('should distribute evenly given all workers have space and limited odd resources ', () => {
const cell = game.map.getCell(4, 4);
cell.setResource(Resource.Types.WOOD, rates.WOOD + 1);
const w1 = game.spawnWorker(0, 4, 4);
const w2 = game.spawnWorker(1, 4, 5);
game.distributeAllResources();
expect(w1.cargo.wood).to.equal(Math.floor(rates.WOOD / 2));
expect(w2.cargo.wood).to.equal(Math.floor(rates.WOOD / 2));
expect(cell.resource.amount).to.equal(0);
});
it('should distribute evenly given some workers have limited space and abundance of resources ', () => {
const cell = game.map.getCell(4, 4);
cell.setResource(Resource.Types.WOOD, rates.WOOD * 10);
const w1 = game.spawnWorker(0, 4, 4);
w1.cargo.wood =
DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.WORKER - rates.WOOD / 2;
const w2 = game.spawnWorker(1, 4, 5);
const w3 = game.spawnWorker(1, 4, 3);
game.distributeAllResources();
// shouldn't be able to go over cargo capacity and only mine half as much as usual
expect(w1.cargo.wood).to.equal(
DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.WORKER
);
// while w1 takes less resources, it should still get max rates.WOOD
expect(w2.cargo.wood).to.equal(Math.floor(rates.WOOD));
expect(w3.cargo.wood).to.equal(Math.floor(rates.WOOD));
expect(cell.resource.amount).to.equal(rates.WOOD * 7.5);
});
it('should distribute evenly given some workers have limited space and limited resources ', () => {
const cell = game.map.getCell(4, 4);
cell.setResource(Resource.Types.WOOD, rates.WOOD);
const w1 = game.spawnWorker(0, 4, 4);
w1.cargo.wood =
DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.WORKER -
Math.floor(rates.WOOD / 6);
const w2 = game.spawnWorker(1, 4, 5);
const w3 = game.spawnWorker(1, 4, 3);
game.distributeAllResources();
expect(w1.cargo.wood).to.equal(
DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.WORKER
);
// due to w1 reaching cargo cap and there's limited resources, all other units take a little more than w1
expect(w2.cargo.wood).to.equal(Math.floor((5 * rates.WOOD) / 12));
expect(w3.cargo.wood).to.equal(Math.floor((5 * rates.WOOD) / 12));
expect(cell.resource.amount).to.equal(0);
});
it('should distribute equally to cargo capacity', () => {
const cellC = game.map.getCell(4, 4);
game.map.addResource(4, 4, Resource.Types.WOOD, rates.WOOD);
const cellN = game.map.getCell(4, 3);
game.map.addResource(4, 3, Resource.Types.WOOD, rates.WOOD);
const cellS = game.map.getCell(4, 5);
game.map.addResource(4, 5, Resource.Types.WOOD, rates.WOOD);
game.map.sortResourcesDeterministically();
const w1 = game.spawnWorker(0, 4, 4);
w1.cargo.wood =
DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.WORKER -
rates.WOOD * 2;
game.distributeAllResources();
expect(w1.cargo.wood).to.equal(
DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.WORKER
);
// w1 has space to receive 40 wood, so it's split evenly
// evenly to fill at 14
expect(cellC.resource.amount).to.equal(6);
expect(cellN.resource.amount).to.equal(6);
expect(cellS.resource.amount).to.equal(6);
});
it('should distribute equally to cargo capacity between units with varying space left', () => {
const cellC = game.map.getCell(4, 4);
game.map.addResource(4, 4, Resource.Types.WOOD, rates.WOOD);
const cellN = game.map.getCell(4, 3);
game.map.addResource(4, 3, Resource.Types.WOOD, rates.WOOD);
const cellS = game.map.getCell(4, 5);
game.map.addResource(4, 5, Resource.Types.WOOD, rates.WOOD);
game.map.sortResourcesDeterministically();
const w1 = game.spawnWorker(0, 4, 4);
const w2 = game.spawnWorker(0, 4, 5);
// w1 is at the center and requests 14 from all adjacent wood
// w2 is down south and requests 20 from 2 tiles.
// total, 2/3 wood tiles are contested.
// the contested ones need to give 14 to w1 and 20 to w2. Since this is not possible, it divy's up what it has and gives 10 to each
// the uncontested one then simply gives w1 what it requested (despite being suboptimal but this is fair)
w1.cargo.wood =
DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.WORKER -
rates.WOOD * 2;
game.distributeAllResources();
expect(w1.cargo.wood).to.equal(
94
);
expect(w2.cargo.wood).to.equal(
20
);
expect(cellC.resource.amount).to.equal(0);
expect(cellN.resource.amount).to.equal(6);
expect(cellS.resource.amount).to.equal(0);
});
it('should distribute equally ', () => {
const cellC = game.map.getCell(4, 4);
game.map.addResource(4, 4, Resource.Types.WOOD, rates.WOOD);
const cellN = game.map.getCell(4, 3);
game.map.addResource(4, 3, Resource.Types.WOOD, rates.WOOD);
const cellW = game.map.getCell(3, 4);
game.map.addResource(3, 4, Resource.Types.WOOD, rates.WOOD);
const cellE = game.map.getCell(5, 4);
game.map.addResource(5, 4, Resource.Types.WOOD, rates.WOOD);
const cellS = game.map.getCell(4, 5);
game.map.addResource(4, 5, Resource.Types.WOOD, rates.WOOD);
game.map.sortResourcesDeterministically();
const w1 = game.spawnWorker(0, 4, 4);
w1.cargo.wood =
DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.WORKER -
rates.WOOD * 2;
game.distributeAllResources();
expect(w1.cargo.wood).to.equal(
DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.WORKER
);
// w1 has space to receive 40 wood, so it's split evenly
// to fill
expect(cellC.resource.amount).to.equal(12);
expect(cellN.resource.amount).to.equal(12);
expect(cellW.resource.amount).to.equal(12);
expect(cellE.resource.amount).to.equal(12);
expect(cellS.resource.amount).to.equal(12);
});
it('should distribute resources to a CityTile with at least 1 unit on there ', () => {
const cellN = game.map.getCell(4, 3);
game.map.addResource(4, 3, Resource.Types.WOOD, rates.WOOD * 2);
const cellW = game.map.getCell(3, 4);
game.map.addResource(3, 4, Resource.Types.WOOD, rates.WOOD);
const cellE = game.map.getCell(5, 4);
game.map.addResource(5, 4, Resource.Types.URANIUM, rates.URANIUM * 2);
const cellS = game.map.getCell(4, 5);
game.map.addResource(4, 5, Resource.Types.COAL, rates.COAL);
const cityTile = game.spawnCityTile(0, 4, 4);
game.map.sortResourcesDeterministically();
game.state.teamStates[0].researchPoints = 60;
game.state.teamStates[0].researched.coal = true;
const w1 = game.spawnWorker(0, 4, 4);
const w2 = game.spawnWorker(0, 4, 4);
w1.cargo.wood = rates.WOOD;
game.distributeAllResources();
// Worker does not get any resources, so it still has rates.Wood amount, which gets deposited later if we run the deposite command
expect(w1.cargo.wood).to.equal(
rates.WOOD
);
// w2 does not get any either and is left empty
expect(w2.getCargoSpaceLeft()).to.equal(
DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.WORKER
);
// should take out rates.Wood out of each tile, rates.Coal, and no uranium as it is not researched
expect(cellN.resource.amount).to.equal(rates.WOOD);
expect(cellW.resource.amount).to.equal(0);
expect(cellE.resource.amount).to.equal(rates.URANIUM * 2);
expect(cellS.resource.amount).to.equal(0);
expect(game.cities.get(cityTile.cityid).fuel).to.equal(rates.WOOD * 2 + rates.COAL * DEFAULT_CONFIGS.parameters.RESOURCE_TO_FUEL_RATE.COAL);
game.handleResourceDeposit(w1);
expect(w1.getCargoSpaceLeft()).to.equal(DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.WORKER);
});
it('should not distribute resources to a CityTile with no units on there or carts on there', () => {
const cellN = game.map.getCell(4, 3);
game.map.addResource(4, 3, Resource.Types.WOOD, rates.WOOD * 2);
const cellW = game.map.getCell(3, 4);
game.map.addResource(3, 4, Resource.Types.WOOD, rates.WOOD);
const cellE = game.map.getCell(5, 4);
game.map.addResource(5, 4, Resource.Types.URANIUM, rates.URANIUM * 2);
const cellS = game.map.getCell(4, 5);
game.map.addResource(4, 5, Resource.Types.COAL, rates.COAL);
const cityTile = game.spawnCityTile(0, 4, 4);
const cityTileWithCart = game.spawnCityTile(0, 3, 3);
const cart = game.spawnCart(0, 3, 3);
game.map.sortResourcesDeterministically();
game.state.teamStates[0].researchPoints = 60;
game.state.teamStates[0].researched.coal = true;
game.distributeAllResources();
// should take out rates.Wood out of each tile, rates.Coal, and no uranium as it is not researched
expect(cellN.resource.amount).to.equal(rates.WOOD * 2);
expect(cellW.resource.amount).to.equal(rates.WOOD);
expect(cellE.resource.amount).to.equal(rates.URANIUM * 2);
expect(cellS.resource.amount).to.equal(rates.COAL);
expect(game.cities.get(cityTile.cityid).fuel).to.equal(0);
expect(game.cities.get(cityTileWithCart.cityid).fuel).to.equal(0);
expect(cart.getCargoSpaceLeft()).to.equal(DEFAULT_CONFIGS.parameters.RESOURCE_CAPACITY.CART);
});
}); | the_stack |
import { RedisClient, ClientOpts, ServerInfo } from 'redis';
import {EventEmitter} from "events";
type Callback<T> = (err: Error | null, reply: T) => void;
type AsyncCallback<T> = (err: Error | null, reply: T) => Promise<void>;
type OkOrError = 'OK'|Error
export interface OverloadedCommand<T, U, R> {
(arg1: T, arg2: T, arg3: T, arg4: T, arg5: T, arg6: T, cb?: Callback<U>): R;
(arg1: T, arg2: T, arg3: T, arg4: T, arg5: T, cb?: Callback<U>): R;
(arg1: T, arg2: T, arg3: T, arg4: T, cb?: Callback<U>): R;
(arg1: T, arg2: T, arg3: T, cb?: Callback<U>): R;
(arg1: T, arg2: T | T[], cb?: Callback<U>): R;
(arg1: T | T[], cb?: Callback<U>): R;
(...args: Array<T | Callback<U>>): R;
}
export interface OverloadedKeyCommand<T, U, R> {
(key: string, arg1: T, arg2: T, arg3: T, arg4: T, arg5: T, arg6: T, cb?: Callback<U>): Promise<R>;
(key: string, arg1: T, arg2: T, arg3: T, arg4: T, arg5: T, cb?: Callback<U>): Promise<R>;
(key: string, arg1: T, arg2: T, arg3: T, arg4: T, cb?: Callback<U>): Promise<R>;
(key: string, arg1: T, arg2: T, arg3: T, cb?: Callback<U>): Promise<R>;
(key: string, arg1: T, arg2: T, cb?: Callback<U>): Promise<R>;
(key: string, arg1: T | T[], cb?: Callback<U>): Promise<R>;
(key: string, ...args: Array<T | Callback<U>>): Promise<R>;
(...args: Array<string | T | Callback<U>>): Promise<R>;
}
export interface OverloadedListCommand<T, U, R> {
(arg1: T, arg2: T, arg3: T, arg4: T, arg5: T, arg6: T, cb?: Callback<U>): Promise<R>;
(arg1: T, arg2: T, arg3: T, arg4: T, arg5: T, cb?: Callback<U>): Promise<R>;
(arg1: T, arg2: T, arg3: T, arg4: T, cb?: Callback<U>): Promise<R>;
(arg1: T, arg2: T, arg3: T, cb?: Callback<U>): Promise<R>;
(arg1: T, arg2: T, cb?: Callback<U>): Promise<R>;
(arg1: T | T[], cb?: Callback<U>): Promise<R>;
(...args: Array<T | Callback<U>>): Promise<R>;
}
export interface OverloadedSetCommand<T, U, R> {
(key: string, arg1: T, arg2: T, arg3: T, arg4: T, arg5: T, arg6: T, cb?: Callback<U>): Promise<R>;
(key: string, arg1: T, arg2: T, arg3: T, arg4: T, arg5: T, cb?: Callback<U>): Promise<R>;
(key: string, arg1: T, arg2: T, arg3: T, arg4: T, cb?: Callback<U>): Promise<R>;
(key: string, arg1: T, arg2: T, arg3: T, cb?: Callback<U>): Promise<R>;
(key: string, arg1: T, arg2: T, cb?: Callback<U>): Promise<R>;
(key: string, arg1: T | { [key: string]: T } | T[], cb?: Callback<U>): Promise<R>;
(key: string, ...args: Array<T | Callback<U>>): Promise<R>;
(args: [string, ...T[]], cb?: Callback<U>): Promise<R>;
}
export interface OverloadedLastCommand<T1, T2, U, R> {
(arg1: T1, arg2: T1, arg3: T1, arg4: T1, arg5: T1, arg6: T2, cb?: Callback<U>): Promise<R>;
(arg1: T1, arg2: T1, arg3: T1, arg4: T1, arg5: T2, cb?: Callback<U>): Promise<R>;
(arg1: T1, arg2: T1, arg3: T1, arg4: T2, cb?: Callback<U>): Promise<R>;
(arg1: T1, arg2: T1, arg3: T2, cb?: Callback<U>): Promise<R>;
(arg1: T1, arg2: T2 | Array<T1 | T2>, cb?: Callback<U>): Promise<R>;
(args: Array<T1 | T2>, cb?: Callback<U>): Promise<R>;
(...args: Array<T1 | T2 | Callback<U>>): Promise<R>;
}
interface AsyncRedisConstructor {
new (port: number, host?: string, options?: ClientOpts): AsyncRedis;
new (unix_socket: string, options?: ClientOpts): AsyncRedis;
new (redis_url: string, options?: ClientOpts): AsyncRedis;
new (options?: ClientOpts): AsyncRedis;
createClient(port: number, host?: string, options?: ClientOpts): AsyncRedis;
createClient(unix_socket: string, options?: ClientOpts): AsyncRedis;
createClient(redis_url: string, options?: ClientOpts): AsyncRedis;
createClient(options?: ClientOpts): AsyncRedis;
decorate: (client: RedisClient) => AsyncRedis;
}
interface AsyncRedisEventHandlers extends EventEmitter {
on(event: 'message' | 'message_buffer', listener: (channel: string, message: string) => void): this;
on(event: 'pmessage' | 'pmessage_buffer', listener: (pattern: string, channel: string, message: string) => void): this;
on(event: 'subscribe' | 'unsubscribe', listener: (channel: string, count: number) => void): this;
on(event: 'psubscribe' | 'punsubscribe', listener: (pattern: string, count: number) => void): this;
on(event: string, listener: (...args: any[]) => void): this;
}
interface AsyncRedisCommands<R> {
/**
* Listen for all requests received by the server in real time.
*/
monitor(cb?: Callback<undefined>): any;
MONITOR(cb?: Callback<undefined>): any;
/**
* Get information and statistics about the server.
*/
info(): Promise<ServerInfo|boolean>;
info(section?: string | string[]): Promise<ServerInfo|boolean>;
INFO(): Promise<ServerInfo|boolean>;
INFO(section?: string | string[]): Promise<ServerInfo|boolean>;
/**
* Ping the server.
*/
ping(): Promise<string|boolean>;
ping(message: string): Promise<string|boolean>;
PING(): Promise<string|boolean>;
PING(message: string): Promise<string|boolean>;
/**
* Authenticate to the server.
*/
auth(password: string): Promise<string>;
AUTH(password: string): Promise<string>;
/**
* Asynchronously rewrite the append-only file.
*/
bgrewriteaof(): Promise<OkOrError>;
BGREWRITEAOF(): Promise<OkOrError>;
/**
* Asynchronously save the dataset to disk.
*/
bgsave(): Promise<OkOrError>;
BGSAVE(): Promise<OkOrError>;
/**
* Get array of Redis command details.
*
* COUNT - Get total number of Redis commands.
* GETKEYS - Extract keys given a full Redis command.
* INFO - Get array of specific REdis command details.
*/
command(cb?: Callback<Array<[string, number, string[], number, number, number]>>): Promise<R>;
COMMAND(cb?: Callback<Array<[string, number, string[], number, number, number]>>): Promise<R>;
/**
* Get array of Redis command details.
*
* COUNT - Get array of Redis command details.
* GETKEYS - Extract keys given a full Redis command.
* INFO - Get array of specific Redis command details.
* GET - Get the value of a configuration parameter.
* REWRITE - Rewrite the configuration file with the in memory configuration.
* SET - Set a configuration parameter to the given value.
* RESETSTAT - Reset the stats returned by INFO.
*/
config: OverloadedCommand<string | number, any, R>;
CONFIG: OverloadedCommand<string | number, any, R>;
/**
* Return the number of keys in the selected database.
*/
dbsize(): Promise<number>;
DBSIZE(): Promise<number>;
/**
* OBJECT - Get debugging information about a key.
* SEGFAULT - Make the server crash.
*/
debug: OverloadedCommand<string | number, any, R>;
DEBUG: OverloadedCommand<string | number, any, R>;
/**
* Return a serialized version of the value stored at the specified key.
*/
dump(key: string, cb?: Callback<string>): Promise<R>;
DUMP(key: string, cb?: Callback<string>): Promise<R>;
/**
* Echo the given string.
*/
echo<T extends string>(message: T, cb?: Callback<T>): Promise<R>;
ECHO<T extends string>(message: T, cb?: Callback<T>): Promise<R>;
/**
* Execute a Lua script server side.
*/
eval: OverloadedCommand<string | number, any, R>;
EVAL: OverloadedCommand<string | number, any, R>;
/**
* Execute a Lue script server side.
*/
evalsha: OverloadedCommand<string | number, any, R>;
EVALSHA: OverloadedCommand<string | number, any, R>;
/**
* PubSub Commands TODO
*/
/**
* Post a message to a channel.
*/
publish(channel: string, value: string): Promise<number|boolean>;
PUBLISH(channel: string, value: string): Promise<number|boolean>;
/**
* Discard all commands issued after MULTI.
*/
discard(cb?: Callback<'OK'>): Promise<R>;
DISCARD(cb?: Callback<'OK'>): Promise<R>;
}
interface CountingCommands<R> {
/**
* Decrement the integer value of a key by one.
*/
decr(key: string, cb?: Callback<number>): Promise<R>;
DECR(key: string, cb?: Callback<number>): Promise<R>;
/**
* Decrement the integer value of a key by the given number.
*/
decrby(key: string, decrement: number, cb?: Callback<number>): Promise<R>;
DECRBY(key: string, decrement: number, cb?: Callback<number>): Promise<R>;
/**
* Increment the integer value of a key by one.
*/
incr(key: string, cb?: Callback<number>): Promise<R>;
INCR(key: string, cb?: Callback<number>): Promise<R>;
/**
* Increment the integer value of a key by the given amount.
*/
incrby(key: string, increment: number, cb?: Callback<number>): Promise<R>;
INCRBY(key: string, increment: number, cb?: Callback<number>): Promise<R>;
/**
* Increment the float value of a key by the given amount.
*/
incrbyfloat(key: string, increment: number, cb?: Callback<string>): Promise<R>;
INCRBYFLOAT(key: string, increment: number, cb?: Callback<string>): Promise<R>;
}
interface CrudCommands<R> {
/**
* Append a value to a key.
*/
append(key: string, value: string): Promise<number>;
APPEND(key: string, value: string): Promise<number>;
/**
* Determine if a key exists.
*/
exists: OverloadedCommand<string | number, any, R>;
EXISTS: OverloadedCommand<string | number, any, R>;
/**
* Set the string value of a key.
*/
set(key: string, value: string): Promise<string|boolean>;
set(key: string, value: string, flag: string): Promise<string|boolean>;
set(key: string, value: string, mode: string, duration: number): Promise<string|undefined>;
set(key: string, value: string, mode: string, duration: number, flag: string): Promise<string|undefined>;
SET(key: string, value: string): Promise<string|boolean>;
SET(key: string, value: string, flag: string): Promise<string|boolean>;
SET(key: string, value: string, mode: string, duration: number): Promise<string|undefined>;
SET(key: string, value: string, mode: string, duration: number, flag: string): Promise<string|undefined>;
/**
* Set a key's time to live in seconds.
*/
expire(key: string, seconds: number, cb?: Callback<number>): Promise<R>;
EXPIRE(key: string, seconds: number, cb?: Callback<number>): Promise<R>;
/**
* Set the expiration for a key as a UNIX timestamp.
*/
expireat(key: string, timestamp: number, cb?: Callback<number>): Promise<R>;
EXPIREAT(key: string, timestamp: number, cb?: Callback<number>): Promise<R>;
/**
* Remove all keys from all databases.
*/
flushall(cb?: Callback<string>): Promise<R>;
flushall(async: "ASYNC", cb?: Callback<string>): Promise<R>;
FLUSHALL(cb?: Callback<string>): Promise<R>;
FLUSHALL(async: 'ASYNC', cb?: Callback<string>): Promise<R>;
/**
* Remove all keys from the current database.
*/
flushdb(cb?: Callback<'OK'>): Promise<R>;
flushdb(async: "ASYNC", cb?: Callback<string>): Promise<R>;
FLUSHDB(cb?: Callback<'OK'>): Promise<R>;
FLUSHDB(async: 'ASYNC', cb?: Callback<string>): Promise<R>;
/**
* Get the value of a key.
*/
get(key: string, cb?: Callback<string | null>): Promise<R>;
GET(key: string, cb?: Callback<string | null>): Promise<R>;
/**
* Returns the bit value at offset in the string value stored at key.
*/
getbit(key: string, offset: number, cb?: Callback<number>): Promise<R>;
GETBIT(key: string, offset: number, cb?: Callback<number>): Promise<R>;
/**
* Get a substring of the string stored at a key.
*/
getrange(key: string, start: number, end: number, cb?: Callback<string>): Promise<R>;
GETRANGE(key: string, start: number, end: number, cb?: Callback<string>): Promise<R>;
/**
* Set the string value of a key and return its old value.
*/
getset(key: string, value: string, cb?: Callback<string>): Promise<R>;
GETSET(key: string, value: string, cb?: Callback<string>): Promise<R>;
/**
* Find all keys matching the given pattern.
*/
keys(pattern: string, cb?: Callback<string[]>): Promise<R>;
KEYS(pattern: string, cb?: Callback<string[]>): Promise<R>;
}
interface HashCrudCommands<R> {
/**
* Delete on or more hash fields.
*/
hdel: OverloadedKeyCommand<string, number, R>;
HDEL: OverloadedKeyCommand<string, number, R>;
/**
* Determine if a hash field exists.
*/
hexists(key: string, field: string, cb?: Callback<number>): Promise<R>;
HEXISTS(key: string, field: string, cb?: Callback<number>): Promise<R>;
/**
* Get the value of a hash field.
*/
hget(key: string, field: string, cb?: Callback<string | null>): Promise<R>;
HGET(key: string, field: string, cb?: Callback<string | null>): Promise<R>;
/**
* Get all fields and values in a hash.
*/
hgetall(key: string, cb?: Callback<{ [key: string]: string } | null>): Promise<R>;
HGETALL(key: string, cb?: Callback<{ [key: string]: string } | null>): Promise<R>;
/**
* Increment the integer value of a hash field by the given number.
*/
hincrby(key: string, field: string, increment: number, cb?: Callback<number>): Promise<R>;
HINCRBY(key: string, field: string, increment: number, cb?: Callback<number>): Promise<R>;
/**
* Increment the float value of a hash field by the given amount.
*/
hincrbyfloat(key: string, field: string, increment: number, cb?: Callback<string>): Promise<R>;
HINCRBYFLOAT(key: string, field: string, increment: number, cb?: Callback<string>): Promise<R>;
/**
* Get all the fields of a hash.
*/
hkeys(key: string, cb?: Callback<string[]>): Promise<R>;
HKEYS(key: string, cb?: Callback<string[]>): Promise<R>;
/**
* Get the number of fields in a hash.
*/
hlen(key: string, cb?: Callback<number>): Promise<R>;
HLEN(key: string, cb?: Callback<number>): Promise<R>;
/**
* Get the values of all the given hash fields.
*/
hmget: OverloadedKeyCommand<string, string[], R>;
HMGET: OverloadedKeyCommand<string, string[], R>;
/**
* Set the string value of a hash field.
*/
hset: OverloadedSetCommand<string, number, R>;
HSET: OverloadedSetCommand<string, number, R>;
/**
* Set the value of a hash field, only if the field does not exist.
*/
hsetnx(key: string, field: string, value: string, cb?: Callback<number>): Promise<R>;
HSETNX(key: string, field: string, value: string, cb?: Callback<number>): Promise<R>;
/**
* Get the length of the value of a hash field.
*/
hstrlen(key: string, field: string, cb?: Callback<number>): Promise<R>;
HSTRLEN(key: string, field: string, cb?: Callback<number>): Promise<R>;
/**
* Get all the values of a hash.
*/
hvals(key: string, cb?: Callback<string[]>): Promise<R>;
HVALS(key: string, cb?: Callback<string[]>): Promise<R>;
}
interface GeoCommands<R> {
/**
* Add one or more geospatial items in the geospatial index represented using a sorted set.
*/
geoadd: OverloadedKeyCommand<string | number, number, R>;
GEOADD: OverloadedKeyCommand<string | number, number, R>;
/**
* Returns members of a geospatial index as standard geohash strings.
*/
geohash: OverloadedKeyCommand<string, string, R>;
GEOHASH: OverloadedKeyCommand<string, string, R>;
/**
* Returns longitude and latitude of members of a geospatial index.
*/
geopos: OverloadedKeyCommand<string, Array<[number, number]>, R>;
GEOPOS: OverloadedKeyCommand<string, Array<[number, number]>, R>;
/**
* Returns the distance between two members of a geospatial index.
*/
geodist: OverloadedKeyCommand<string, string, R>;
GEODIST: OverloadedKeyCommand<string, string, R>;
/**
* Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a point.
*/
georadius: OverloadedKeyCommand<string | number, Array<string | [string, string | [string, string]]>, R>;
GEORADIUS: OverloadedKeyCommand<string | number, Array<string | [string, string | [string, string]]>, R>;
/**
* Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a member.
*/
georadiusbymember: OverloadedKeyCommand<string | number, Array<string | [string, string | [string, string]]>, R>;
GEORADIUSBYMEMBER: OverloadedKeyCommand<string | number, Array<string | [string, string | [string, string]]>, R>;
}
export const AsyncRedis: new (options: ClientOpts) => AsyncRedis;
export interface AsyncRedis extends AsyncRedisConstructor, AsyncRedisEventHandlers, AsyncRedisCommands<boolean> {
/**
* Mark the start of a transaction block.
*/
multi(args?: Array<Array<string | number | Callback<any>>>): Multi;
MULTI(args?: Array<Array<string | number | Callback<any>>>): Multi;
batch(args?: Array<Array<string | number | Callback<any>>>): Multi;
BATCH(args?: Array<Array<string | number | Callback<any>>>): Multi;
}
export const Multi: new () => Multi;
export interface Multi extends AsyncRedisEventHandlers, AsyncRedisCommands<boolean>
{
exec(): Promise<number|boolean>;
EXEC(): Promise<number|boolean>;
exec_atomic(): Promise<number|boolean>;
EXEC_ATOMIC(): Promise<number|boolean>;
} | the_stack |
import React from 'react'
import {
Text,
View,
StyleSheet
} from 'react-native'
import htmlparser from 'htmlparser2-without-node-native'
import entities from 'entities'
import ResizableImgComponent from './resizableImage'
import InlineImgComponent from './inlineImage'
import Web from './webview'
import MarkText from './markText'
const LINE_BREAK = '\n'
const PARAGRAPH_BREAK = '\n\n'
const BULLET = '\u2022 '
const inlineElements = ['a', 'span', 'em', 'font', 'label', 'b', 'strong', 'i', 'small', 'img', 'u']
const blockLevelElements = ['pre', 'p', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'blockquote']
export default function htmlToElement(rawHtml, opts, done) {
function domToElement(dom, parent, inInsideView = true, depth = 0, parentIframe = 0) {
// debug开关函数
const log: (...args) => any = () => {}
// const log = (text, ...args) => console.log(`第${depth}层 ${Array(depth).fill(' ').join('')}${text} ${args.join(' ')}`)
log('是否在View内', inInsideView)
// inInsideView为是否为第一层, 是第一层则图片外联并且支持返回View组件, 否则只支持返回Text和内联图片组件
if (!dom) return null
let domLen = dom.length
// 缓存是否已经被内联渲染的对象数组
let domTemp = {}
// 获得嵌套标签的子内容, 仅支持其中第一个子组件
let getNodeData = function (node) {
let nodeData = null
if (node.children && node.children.length) {
let nodeChild = node.children[0]
if (nodeChild && nodeChild.data) {
nodeData = nodeChild.data
} else {
nodeData = getNodeData(nodeChild)
}
}
return nodeData
}
// 向parent递归查找class和style, 最终得到文字应有的样式
let renderInlineStyle = function (innerParent, styleObj) {
// p9目前只有span的嵌套, 因此暂时只处理span
if (innerParent && inlineElements.includes(innerParent.name)) {
const classNameArr = (innerParent.attribs.class || '').split(' ')
for (const name of classNameArr) {
switch (name) {
case 'font12':
styleObj.fontSize = 12
break
case 'mark':
styleObj.backgroundColor = opts.modeInfo.backgroundColor
styleObj.color = opts.modeInfo.reverseModeInfo.backgroundColor
styleObj.isMark = true
break
case 'dd_price_plus':
styleObj.color = '#ffc926'
break
default:
break
}
}
const styles = (innerParent.attribs.style || '').split(';')
for (const style of styles) {
if (!style) continue
const splited = style.split(':')
if (splited.length !== 2) continue
splited[0] = splited[0].replace(/\-([a-z])/, (matched) => matched[1].toUpperCase())
if (splited[1].includes('px')) {
splited[1] = parseInt(splited[1], 10)
} else {
splited[1] = splited[1].toLowerCase()
}
styleObj[splited[0]] = splited[1]
}
renderInlineStyle(innerParent.parent, styleObj)
}
}
// 渲染可以被内联的组件
let renderInlineNode = function (index, result: any[] = [], isInsideView = false) {
let thisIndex = index + 1
if (thisIndex < domLen) {
let nextNode = dom[thisIndex]
if (domTemp[thisIndex] === true) {
return result
}
if (inlineElements.includes(nextNode.name) || nextNode.type === 'text') {
// 设置缓存标识
domTemp[thisIndex] = true
const isNestedImage = nextNode.name === 'a' && nextNode.children && nextNode.children.length === 1 && nextNode.children[0].name === 'img'
// console.log(isNestedImage, nextNode.name, (nextNode.children || []).length,
// nextNode.children && nextNode.children.length === 1 && nextNode.children[0].name
// ,'isNestedImage')
if (isNestedImage) {
log('渲染内联组件', isInsideView)
domTemp[thisIndex] = false
return result
}
result.push(
<Text key={index}>
{ domToElement([nextNode], nextNode.parent, false, depth + 1) }
</Text>
)
} else if (nextNode.name === 'br') {
// 内联的换行, 由于内联只存在文字和图片, 因此不用考虑其他标签
domTemp[thisIndex] = true
result.push(<Text key={index}>{LINE_BREAK}</Text>)
}
if (nextNode.next && nextNode.name !== 'div') {
const name = nextNode.next.name
const type = nextNode.next.type
// console.log(name , type)
if (type === 'text' || inlineElements.includes(name) || name === 'br') {
renderInlineNode(thisIndex, result)
}
}
}
return result
}
let renderText = (node, index, innerParent) => {
if (node.type === 'text' && node.data.trim() !== '') {
let linkPressHandler: any = null
// console.log(parent && parent.name === 'a' && parent.attribs && parent.attribs.href, '==>')
if (innerParent && innerParent.name === 'a' && innerParent.attribs && innerParent.attribs.href) {
// console.log('???', parent.attribs.href)
linkPressHandler = () => opts.linkHandler(entities.decodeHTML(innerParent.attribs.href))
}
const classStyle: any = {}
renderInlineStyle(innerParent, classStyle)
let inlineArr = renderInlineNode(index)
const content = entities.decodeHTML(node.data)
const isMark = classStyle.isMark === true
if (isMark) delete classStyle.isMark
const text = isMark ? (
<MarkText {...{
color: classStyle.color,
backgroundColor: classStyle.backgroundColor,
text: content,
forceMark: opts.forceMark
}}/>
) : content
return (
<Text key={index} onPress={linkPressHandler} style={[
{ color: opts.modeInfo.standardTextColor },
innerParent ? opts.styles[innerParent.name] : null,
classStyle
]}>{innerParent && innerParent.name === 'pre' ? LINE_BREAK : null}
{innerParent && innerParent.name === 'li' ? BULLET : null}
{innerParent && innerParent.name === 'br' ? LINE_BREAK : null}
{innerParent && innerParent.name === 'p' && index < innerParent.length - 1 ? PARAGRAPH_BREAK : null}
{innerParent && innerParent.name === 'h1' || innerParent && innerParent.name === 'h2' || innerParent && innerParent.name === 'h3'
|| innerParent && innerParent.name === 'h4' || innerParent && innerParent.name === 'h5' ? PARAGRAPH_BREAK : null}
{text}
{inlineArr}
</Text>
)
}
return null
}
return dom.map((node, index, list) => {
if (domTemp[index] === true) {
return
}
if (opts.customRenderer) {
const rendered = opts.customRenderer(node, index, list, parent, domToElement)
if (rendered || rendered === null) return rendered
}
log('尝试渲染renderText', node.type, node.name, inInsideView)
const textComponent = renderText(node, index, parent)
if (textComponent) return textComponent
if (node.type === 'tag') {
if (node.name === 'img') {
let linkPressHandler: any = null
let shouldForceInlineEmotion = false
if (parent && parent.name === 'a' && parent.attribs.href) {
const parentHref = parent.attribs.href
const imgSrc = node.attribs.src
const type = imgSrc === parentHref ? 'onImageLongPress' : 'linkHandler'
linkPressHandler = () => opts[type](entities.decodeHTML(parentHref))
} else if (node.attribs && node.attribs.src) {
// 内联p9的默认表情图片
if (node.attribs.src.includes('//photo.psnine.com/face/')) {
shouldForceInlineEmotion = true
}
linkPressHandler = () => opts.onImageLongPress(entities.decodeHTML(node.attribs.src))
}
let ImageComponent = inInsideView ? ResizableImgComponent : InlineImgComponent
if (shouldForceInlineEmotion) {
ImageComponent = InlineImgComponent
}
if (ImageComponent === ResizableImgComponent) {
let src = node.attribs.src
if (/^(.*?):\/\//.exec(src)) {} else {
src = 'https://psnine.com' + src
}
// console.log('pushing', src)
opts.imageArr.push({ url: src })
const len = opts.imageArr.length
linkPressHandler = () => opts.onImageLongPress({
imageUrls: opts.imageArr,
index: len - 1
})
}
log('渲染Img标签', '此时是否在View中?', inInsideView, ImageComponent === ResizableImgComponent)
// console.log(parentIframe)
return (
<ImageComponent key={index} attribs={node.attribs}
isLoading={opts.shouldShowLoadingIndicator}
linkPressHandler={linkPressHandler}
alignCenter={opts.alignCenter}
modeInfo={opts.modeInfo}
imageArr={opts.imageArr}
imagePaddingOffset={opts.imagePaddingOffset + parentIframe}
/>
)
} else if (node.name === 'embed' || node.name === 'iframe') {
if (inInsideView) {
const target = Object.assign({}, node.attribs)
return (
<Web key={index} attribs={target}
linkPressHandler={opts.linkHandler}
imagePaddingOffset={opts.imagePaddingOffset} modeInfo={opts.modeInfo} name={node.name} />
)
} else {
return (
<Text style={{
color: opts.modeInfo.accentColor,
textDecorationLine: 'underline'
}} onPress={() => opts.linkHandler(entities.decodeHTML(node.attribs.src))}>
打开网页
</Text>
)
}
}
let linkPressHandler: any = null
if (node.name === 'a' && node.attribs && node.attribs.href) {
linkPressHandler = () => opts.linkHandler(entities.decodeHTML(node.attribs.href))
}
let linebreakBefore: null | string = null
let linebreakAfter: null | string = null
if (blockLevelElements.includes(node.name)) {
switch (node.name) {
case 'blockquote':
case 'pre':
linebreakBefore = LINE_BREAK
break
case 'p':
if (index < list.length - 1) {
linebreakAfter = PARAGRAPH_BREAK
}
break
case 'br':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
linebreakAfter = LINE_BREAK
break
default:
break
}
}
let listItemPrefix: null | string = null
if (node.name === 'li') {
if (parent.name === 'ol') {
listItemPrefix = `${index + 1}. `
} else if (parent.name === 'ul') {
listItemPrefix = BULLET
}
}
let shouldSetLineAfter = false
const classStyle: any = {}
let isIframe = parentIframe || 0
if (node.name === 'div') {
if (node.attribs.align === 'center') {
classStyle.alignItems = 'center'
classStyle.justifyContent = 'center'
classStyle.flex = 1
}
if (node.attribs.class) {
const classNameArr = node.attribs.class.split(' ')
for (const name of classNameArr) {
switch (name) {
case 'ml64':
classStyle.paddingLeft = 10
classStyle.flex = 5
classStyle.flexWrap = 'wrap'
break
case 'pd10':
classStyle.padding = 8
break
case 't4':
case 't3':
case 't2':
case 't1':
classStyle.maxWidth = opts.modeInfo.width - opts.imagePaddingOffset
classStyle.flexDirection = 'row'
classStyle.justifyContent = 'center'
classStyle.alignItems = 'flex-start'
classStyle.elevation = 1
classStyle.marginTop = 2
classStyle.marginBottom = 2
classStyle.backgroundColor = opts.modeInfo.backgroundColor
isIframe = 104
break
default:
break
}
}
}
} else if (inlineElements.includes(node.name) === false) {
switch (node.name) {
case 'table':
classStyle.backgroundColor = opts.modeInfo.brighterLevelOne
// classStyle.minWidth = (opts.modeInfo.width - opts.imagePaddingOffset) / 4 * 3
// const { width: SCEEN_WIDTH } = Dimensions.get('window')
classStyle.width = opts.modeInfo.width - opts.imagePaddingOffset - isIframe
classStyle.minWidth = opts.modeInfo.width - opts.imagePaddingOffset - isIframe
break
case 'tr':
classStyle.flexDirection = 'row'
classStyle.flexWrap = 'wrap'
classStyle.justifyContent = 'space-between'
classStyle.alignItems = 'stretch'
break
case 'td':
classStyle.flex = index === 1 ? 2 : 1
classStyle.alignItems = 'center'
classStyle.justifyContent = 'flex-start'
classStyle.padding = 2
classStyle.borderWidth = 1
classStyle.borderColor = opts.modeInfo.backgroundColor
inInsideView = false
break
default:
// console.log(node.name, node.children.length)
break
}
}
const flattenStyles: any = StyleSheet.flatten([
parent ? opts.styles[parent.name] : null,
classStyle
])
const isNestedImage = inInsideView && node.name === 'a' && node.children
&& node.children.length !== 0 && node.children.some(item => item.name === 'img')
// log('判断是渲染View还是渲染Text',inInsideView, node.name === 'a' && node.children && node.children.length === 1 && node.children[0].name === 'img',
// node.name === 'a' && node.children && node.children.length !==0 && node.children.some(item => item.name === 'img')
// , 'wow', depth)
if (inInsideView && (inlineElements.includes(node.name) === false || isNestedImage)) {
if (node.name === 'br') {
// P9内容的换行规则
if (node.prev && ['br'].includes(node.prev.name)) {
shouldSetLineAfter = true
}
}
if (flattenStyles.fontSize) delete flattenStyles.fontSize
if (flattenStyles.fontFamily) delete flattenStyles.fontFamily
if (flattenStyles.fontWeight) delete flattenStyles.fontWeight
if (node.children && node.children.length === 0) {
if (node.prev && inlineElements.includes(node.prev.name)) {
return
}
return <Text key={index}>{'\n'}</Text>
}
log('渲染View组件', node.name, isNestedImage, depth)
return (
<View key={index} style={flattenStyles}>
{domToElement(node.children, node, inInsideView, depth + 1, isIframe)}
{
shouldSetLineAfter && linebreakAfter && (
<Text key={index} onPress={linkPressHandler} style={parent ? opts.styles[parent.name] : null}>{linebreakAfter}</Text>
)
}
</View>
)
} else {
log('渲染Text组件', inInsideView, node.name, depth)
let inlineNode = renderInlineNode(index, [], inInsideView)
// console.log('???', parent && parent.attribs && parent.attribs.href, parent && parent.name, '====>')
return (
<Text key={index} style={flattenStyles}>{domToElement(node.children, node, false, depth + 1, isIframe)}
{inlineNode.length !== 0 && inlineNode}
</Text>
)
}
}
})
}
const handler = new htmlparser.DomHandler(function (err, dom) {
if (err) done(err)
done(null, domToElement(dom, null, !opts.shouldForceInline))
})
const parser = new htmlparser.Parser(handler)
parser.write(rawHtml)
parser.done()
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.