text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Decimal } from 'decimal.js';
import { getDefaultFunctions } from './default/functions';
import { getDefaultUnits } from './default/units';
import { Constant } from './evaluator/constants';
import { Converter, converterFuncFmt } from './evaluator/converter';
import { EnvInputType, Environment } from './evaluator/environment';
import { Evaluator } from './evaluator/evaluator';
import { FcalFunction, IUseFunction } from './evaluator/function';
import { Scale } from './evaluator/scale';
import { Entity, SymbolTable } from './evaluator/symboltable';
import { JSONParser } from './json/JSONParser';
import { TT, Token } from './parser/lex/token';
import { Type } from './types/datatype';
import { Phrases } from './types/phrase';
import { IUseUnit, Unit, UnitMeta } from './types/units';
import { Lexer } from './parser/lex/lex';
/**
* Math expression evaluator.
* It evaluates various arithmetic operations, percentage operations,
* variables and functions with units
*/
class Fcal {
/**
* Quick math expression evaluator
* @param {string} source expression
* @returns {Type} result
*/
public static eval(source: string): Type {
return new Fcal().evaluate(source);
}
/**
* register new fcal Functions
* @param {Array<FcalFunction | Object>} functions list of fcal function definitions
*/
public static UseFunctions(functions: (FcalFunction | IUseFunction)[]): void {
for (const func of functions) {
this.UseFunction(func);
}
}
/**
* Register new Fcal function
* @param {FcalFunction | Object} function fcal function definitions
*/
public static UseFunction(func: FcalFunction | IUseFunction): void {
Fcal.gst.set(func.name, Entity.FUNCTION);
if (func instanceof FcalFunction) {
this.functions.push(func);
return;
}
this.functions.push(new FcalFunction(func.name, func.arity, func.func));
}
/**
* Register new units
* @param {Array<Unit | Object>} units
*/
public static UseUnits(units: (Unit | IUseUnit)[]): void {
for (const unit of units) {
this.UseUnit(unit);
}
}
/**
* Register new unit
* @param {Unit | Object} unit
*/
public static UseUnit(unit: Unit | IUseUnit): void {
if (unit instanceof Unit) {
return this.units.push(unit);
}
const u = new Unit(unit.id, unit.ratio, unit.type, unit.phrases);
if (unit.bias) {
u.setBias(unit.bias);
}
if (unit.plural) {
u.Plural(unit.plural);
}
if (unit.singular) {
u.Singular(unit.singular);
}
this.units.push(u);
}
/**
* Get unit meta by its phrase
* @param {string} unit phrase
* @returns {UnitMeta | null}
*/
public static getUnit(unit: string): UnitMeta | null {
return this.units.get(unit);
}
/**
* useConstants set the constants in fcal
* @param { { [index: string]: Type | Decimal | number | string } } constants
*/
public static useConstants(constants: EnvInputType): void {
this.constants.use(constants);
}
/**
* useScales register new scale in fcal
* @param { { [index: string]: Type | Decimal | number | string } } scales
*/
public static useScales(scales: EnvInputType): void {
this.scales.use(scales);
}
/**
* Register new converter function
* @param {string}id id of the converter function
* @param {converterFuncFmt}f function
*/
public static useConverter(id: string, f: converterFuncFmt): void {
this.converters.set(id, f);
}
/**
* Get the units list
* @returns {Unit.List} units
*/
public static getUnits(): Unit.List {
return this.units;
}
/**
* Get the constants
* @returns {Constant} constants
*/
public static getConstants(): Constant {
return this.constants;
}
/**
* Get the functions
* @returns {FcalFunction.List} functions
*/
public static getFunctions(): FcalFunction.List {
return this.functions;
}
/**
* Get the scales
* @returns {Scale} scales
*/
public static getScales(): Scale {
return this.scales;
}
/**
* Get the converters
* @returns {Converter} converters
*/
public static getConverters(): Converter {
return this.converters;
}
/**
* Scan the math expression and gets array of tokens
* @param {string} expression math expression
* @returns {Token[]} array of tokens
*/
public static getTokensForExpression(expression: string): Token[] {
const lexer = new Lexer(expression, this.phrases, this.units, this.converters, this.scales);
return lexer.getTokens();
}
public static initialize(): void {
if (!this.gst) {
this.gst = new SymbolTable();
}
if (!this.phrases) {
this.phrases = this.getDefaultPhrases();
}
if (!this.units) {
this.units = new Unit.List(Fcal.gst);
this.setDefaultUnits();
}
if (!this.functions) {
this.functions = new FcalFunction.List();
this.setDefaultFunctions();
}
if (!this.constants) {
this.constants = new Constant(this.gst);
this.setDefaultConstants();
}
if (!this.converters) {
this.converters = new Converter(this.gst);
this.setDefaultConverter();
}
if (!this.scales) {
this.scales = new Scale(this.gst);
this.setDefaultScales();
}
}
/*=========================== Private static =================================== */
private static gst: SymbolTable;
private static units: Unit.List;
private static functions: FcalFunction.List;
private static phrases: Phrases;
private static constants: Constant;
private static converters: Converter;
private static scales: Scale;
private static getDefaultPhrases(): Phrases {
const phrases = new Phrases(this.gst);
phrases.push(TT.PLUS, ['PLUS', 'WITH', 'ADD']);
phrases.push(TT.MINUS, ['MINUS', 'SUBTRACT', 'WITHOUT']);
phrases.push(TT.TIMES, ['TIMES', 'MULTIPLIEDBY', 'mul']);
phrases.push(TT.SLASH, ['DIVIDE', 'DIVIDEBY']);
phrases.push(TT.CAP, ['POW']);
phrases.push(TT.MOD, ['mod']);
phrases.push(TT.OF, ['of']);
phrases.push(TT.IN, ['in', 'as', 'to']);
phrases.push(TT.AND, ['and']);
phrases.push(TT.OR, ['or']);
phrases.push(TT.NOT, ['not']);
return phrases;
}
private static setDefaultFunctions(): void {
this.UseFunctions(getDefaultFunctions());
}
private static setDefaultUnits(): void {
this.UseUnits(getDefaultUnits());
}
private static setDefaultConstants(): void {
this.useConstants({
E: Type.BNumber.New('2.718281828459045235360287'),
PI: Type.BNumber.New('3.141592653589793238462645'),
PI2: Type.BNumber.New('6.2831853071795864769'),
false: Type.FcalBoolean.FALSE,
true: Type.FcalBoolean.TRUE,
});
}
private static setDefaultScales(): void {
const thousand = 1000;
const million = 10_00_000;
const billion = 1_00_00_000;
this.useScales({ k: thousand, M: million, B: billion, thousand, million, billion });
}
private static setDefaultConverter() {
const num = (v: Type): Type => {
return Type.BNumber.New((v as Type.Numeric).n);
};
const per = (v: Type): Type => {
return Type.Percentage.New((v as Type.Numeric).n);
};
this.useConverter('number', num);
this.useConverter('num', num);
this.useConverter('percentage', per);
this.useConverter('percent', per);
}
/* ========================= Class attributes =============================== */
private environment: Environment;
private lst: SymbolTable;
private strict: boolean;
constructor() {
this.lst = new SymbolTable(Fcal.gst);
this.strict = false;
this.environment = new Environment(Fcal.functions, this.lst, Fcal.constants);
}
/**
* Evaluates given expression
* it appends new line character if not present
* @param {string} expression Math expression
* @returns {Type} result of expression
*/
public evaluate(source: string): Type {
source = prefixNewLIne(source);
return this.rawEvaluate(source);
}
/**
* rawEvaluates given expression
* it does not appends new line character if not present
* @param {string} expression Math expression
* @returns {Type} result of expression
*/
public rawEvaluate(source: string): Type {
return new Evaluator(
source /*expression */,
Fcal.phrases,
Fcal.units,
this.environment,
Fcal.converters,
Fcal.scales,
this.strict,
).evaluateExpression();
}
/**
* Create new expression with copy of Fcal.Environment
* @param {string} source Math expression
* @returns {Expression} Expression with parsed AST
*/
public expression(source: string): Expression {
// Cloning fcal session
const symbolTable = new SymbolTable(this.lst);
// Creating new environment
const env = new Environment(Fcal.functions, symbolTable, Fcal.constants);
// coping values from fcal
env.values = new Map<string, Type>(this.environment.values);
source = prefixNewLIne(source);
return new Expression(
new Evaluator(
source /* expression */,
Fcal.phrases,
Fcal.units,
env /* environment */,
Fcal.converters /* converters */,
Fcal.scales,
this.strict,
),
);
}
/**
* Create new Expression in sync with Fcal.Environment
* @param {string} source Math expression
* @returns {Expression} Expression with parsed AST
*/
public expressionSync(source: string): Expression {
source = prefixNewLIne(source);
return new Expression(
new Evaluator(
source /* expression */,
Fcal.phrases /* environment */,
Fcal.units,
this.environment,
Fcal.converters /* converters */,
Fcal.scales,
this.strict,
),
);
}
/**
* create a new variable with value or assign value to variable
* @param {Object | EnvInputType} values variables
*/
public setValues(values: EnvInputType) {
this.environment.use(values);
}
/**
* Get the environment of this fcal session
* @returns {Environment} env
*/
public getEnvironment(): Environment {
return this.environment;
}
/**
* Import expression from JSON
* @param {string} source json
* @returns {Expression}
*/
public fromJSON(source: string): Expression {
const parser = new JSONParser(source, Fcal.units, Fcal.converters);
const symbolTable = new SymbolTable(this.lst);
const env = new Environment(Fcal.functions, symbolTable, Fcal.constants);
env.values = new Map<string, Type>(this.environment.values);
source = prefixNewLIne(source);
return new Expression(
new Evaluator(parser.parse(), Fcal.phrases, Fcal.units, env, Fcal.converters, Fcal.scales, this.strict),
);
}
/**
* Set strict mode
* @param v
*/
public setStrict(v: boolean): void {
this.strict = v;
}
}
function prefixNewLIne(source: string): string {
if (source.endsWith('\n')) {
return source;
}
return source + '\n';
}
/**
* Expression takes AST created from Parser and
* evaluate AST with its state
*/
class Expression {
private readonly evaluator: Evaluator;
constructor(evaluator: Evaluator) {
this.evaluator = evaluator;
}
/**
* Evaluate AST of Math expression
* @returns {Type} result of Math expression
*/
public evaluate(): Type {
return this.evaluator.evaluateExpression();
}
/**
* Change state of variables
* if variable is not found, it will create a new variable
* @param {Object | Map} values variables
*/
public setValues(values: EnvInputType): void {
this.evaluator.environment.use(values);
}
/**
* Get the environment of this expression
* @returns {Environment} environment
*/
public getValues(): Environment {
return this.evaluator.environment;
}
/**
* Get the AST tree view of the formula expression
* @returns {string} AST tree view
*/
public getAST(): string {
return this.evaluator.getAST();
}
/**
* Convert the expression into JSON
* @returns {string} JSON
*/
public toJSON(): string {
return this.evaluator.toJSON();
}
/**
* Convert the expression into an Object
*/
public toObj(): object {
return this.evaluator.toObj();
}
/**
* Get scanned tokens
* @returns {Token[] | undefined} tokens
*/
public getScannedTokens(): Token[] | undefined {
return this.evaluator.getScannedTokens();
}
public toString(): string {
return this.getAST();
}
}
/**
* FcalError represents Error in Fcal
*/
class FcalError extends Error {
private static mark(start: number, end: number): string {
return '^'.repeat(start === end ? 1 : end - start).padStart(end, '.');
}
public source?: string;
public start?: number;
public end?: number;
constructor(message: string, start?: number, end?: number) {
super(message);
this.start = start;
this.end = end;
this.message = message;
if (!start) {
this.name = 'FcalError';
return;
}
if (!end) {
this.end = start;
}
this.name = `FcalError [${this.start}, ${this.end}]`;
}
/**
* info gets more information about FcalError
*/
public info(): string {
const values: string[] = Array<string>();
values.push(`err: ${this.message}\n`);
if (this.source !== undefined && this.start !== undefined && this.end !== undefined) {
values.push(`| ${this.source}`);
values.push(`| ${FcalError.mark(this.start, this.end)}\n`);
}
return values.join('');
}
}
/***************************************************************/
Fcal.initialize();
export { Fcal, FcalError, Expression, FcalFunction, Environment, Unit, Type, Decimal }; | the_stack |
import * as cfnDiff from '@aws-cdk/cloudformation-diff';
import { ResourceDifference } from '@aws-cdk/cloudformation-diff';
import * as cxapi from '@aws-cdk/cx-api';
import * as chalk from 'chalk';
import * as fs from 'fs-extra';
import * as promptly from 'promptly';
import { CloudFormationDeployments, DeployStackOptions } from './api/cloudformation-deployments';
import { ResourceIdentifierProperties, ResourcesToImport } from './api/util/cloudformation';
import { error, print, success, warning } from './logging';
/**
* Parameters that uniquely identify a physical resource of a given type
* for the import operation, example:
*
* ```
* {
* "AWS::S3::Bucket": ["BucketName"],
* "AWS::IAM::Role": ["RoleName"],
* "AWS::EC2::VPC": ["VpcId"]
* }
* ```
*/
export type ResourceIdentifiers = { [resourceType: string]: string[] };
/**
* Mapping of CDK resources (L1 constructs) to physical resources to be imported
* in their place, example:
*
* ```
* {
* "MyStack/MyS3Bucket/Resource": {
* "BucketName": "my-manually-created-s3-bucket"
* },
* "MyStack/MyVpc/Resource": {
* "VpcId": "vpc-123456789"
* }
* }
* ```
*/
export type ResourceMap = { [logicalResource: string]: ResourceIdentifierProperties };
export interface ResourceImporterOptions {
/**
* Name of toolkit stack if non-default
*
* @default - Default toolkit stack name
*/
readonly toolkitStackName?: string;
}
/**
* Resource importing utility class
*
* - Determines the resources added to a template (compared to the deployed version)
* - Look up the identification information
* - Load them from a file, or
* - Ask the user, based on information supplied to us by CloudFormation's GetTemplateSummary
* - Translate the input to a structure expected by CloudFormation, update the template to add the
* importable resources, then run an IMPORT changeset.
*/
export class ResourceImporter {
private _currentTemplate: any;
constructor(
private readonly stack: cxapi.CloudFormationStackArtifact,
private readonly cfn: CloudFormationDeployments,
private readonly options: ResourceImporterOptions = {}) { }
/**
* Ask the user for resources to import
*/
public async askForResourceIdentifiers(available: ImportableResource[]): Promise<ImportMap> {
const ret: ImportMap = { importResources: [], resourceMap: {} };
const resourceIdentifiers = await this.resourceIdentifiers();
for (const resource of available) {
const identifier = await this.askForResourceIdentifier(resourceIdentifiers, resource);
if (!identifier) {
continue;
}
ret.importResources.push(resource);
ret.resourceMap[resource.logicalId] = identifier;
}
return ret;
}
/**
* Load the resources to import from a file
*/
public async loadResourceIdentifiers(available: ImportableResource[], filename: string): Promise<ImportMap> {
const contents = await fs.readJson(filename);
const ret: ImportMap = { importResources: [], resourceMap: {} };
for (const resource of available) {
const descr = this.describeResource(resource.logicalId);
const idProps = contents[resource.logicalId];
if (idProps) {
print('%s: importing using %s', chalk.blue(descr), chalk.blue(fmtdict(idProps)));
ret.importResources.push(resource);
ret.resourceMap[resource.logicalId] = idProps;
delete contents[resource.logicalId];
} else {
print('%s: skipping', chalk.blue(descr));
}
}
const unknown = Object.keys(contents);
if (unknown.length > 0) {
warning(`Unrecognized resource identifiers in mapping file: ${unknown.join(', ')}`);
}
return ret;
}
/**
* Based on the provided resource mapping, prepare CFN structures for import (template,
* ResourcesToImport structure) and perform the import operation (CloudFormation deployment)
*
* @param resourceMap Mapping from CDK construct tree path to physical resource import identifiers
* @param options Options to pass to CloudFormation deploy operation
*/
public async importResources(importMap: ImportMap, options: DeployStackOptions) {
const resourcesToImport: ResourcesToImport = await this.makeResourcesToImport(importMap);
const updatedTemplate = await this.currentTemplateWithAdditions(importMap.importResources);
try {
const result = await this.cfn.deployStack({
...options,
overrideTemplate: updatedTemplate,
resourcesToImport,
});
const message = result.noOp
? ' ✅ %s (no changes)'
: ' ✅ %s';
success('\n' + message, options.stack.displayName);
} catch (e) {
error('\n ❌ %s failed: %s', chalk.bold(options.stack.displayName), e);
throw e;
}
}
/**
* Perform a diff between the currently running and the new template, enusre that it is valid
* for importing and return a list of resources that are being added in the new version
*
* @return mapping logicalResourceId -> resourceDifference
*/
public async discoverImportableResources(allowNonAdditions = false): Promise<DiscoverImportableResourcesResult> {
const currentTemplate = await this.currentTemplate();
const diff = cfnDiff.diffTemplate(currentTemplate, this.stack.template);
// Ignore changes to CDKMetadata
const resourceChanges = Object.entries(diff.resources.changes)
.filter(([logicalId, _]) => logicalId !== 'CDKMetadata');
// Split the changes into additions and non-additions. Imports only make sense
// for newly-added resources.
const nonAdditions = resourceChanges.filter(([_, dif]) => !dif.isAddition);
const additions = resourceChanges.filter(([_, dif]) => dif.isAddition);
if (nonAdditions.length) {
const offendingResources = nonAdditions.map(([logId, _]) => this.describeResource(logId));
if (allowNonAdditions) {
warning(`Ignoring updated/deleted resources (--force): ${offendingResources.join(', ')}`);
} else {
throw new Error('No resource updates or deletes are allowed on import operation. Make sure to resolve pending changes ' +
`to existing resources, before attempting an import. Updated/deleted resources: ${offendingResources.join(', ')} (--force to override)`);
}
}
// Resources in the new template, that are not present in the current template, are a potential import candidates
return {
additions: additions.map(([logicalId, resourceDiff]) => ({
logicalId,
resourceDiff,
resourceDefinition: addDefaultDeletionPolicy(this.stack.template?.Resources?.[logicalId] ?? {}),
})),
hasNonAdditions: nonAdditions.length > 0,
};
}
/**
* Get currently deployed template of the given stack (SINGLETON)
*
* @returns Currently deployed CloudFormation template
*/
private async currentTemplate(): Promise<any> {
if (!this._currentTemplate) {
this._currentTemplate = await this.cfn.readCurrentTemplate(this.stack);
}
return this._currentTemplate;
}
/**
* Return teh current template, with the given resources added to it
*/
private async currentTemplateWithAdditions(additions: ImportableResource[]): Promise<any> {
const template = await this.currentTemplate();
if (!template.Resources) {
template.Resources = {};
}
for (const add of additions) {
template.Resources[add.logicalId] = add.resourceDefinition;
}
return template;
}
/**
* Get a list of import identifiers for all resource types used in the given
* template that do support the import operation (SINGLETON)
*
* @returns a mapping from a resource type to a list of property names that together identify the resource for import
*/
private async resourceIdentifiers(): Promise<ResourceIdentifiers> {
const ret: ResourceIdentifiers = {};
const resourceIdentifierSummaries = await this.cfn.resourceIdentifierSummaries(this.stack, this.options.toolkitStackName);
for (const summary of resourceIdentifierSummaries) {
if ('ResourceType' in summary && summary.ResourceType && 'ResourceIdentifiers' in summary && summary.ResourceIdentifiers) {
ret[summary.ResourceType] = summary.ResourceIdentifiers;
}
}
return ret;
}
private async askForResourceIdentifier(
resourceIdentifiers: ResourceIdentifiers,
chg: ImportableResource,
): Promise<ResourceIdentifierProperties | undefined> {
const resourceName = this.describeResource(chg.logicalId);
// Skip resources that do not support importing
const resourceType = chg.resourceDiff.newResourceType;
if (resourceType === undefined || !(resourceType in resourceIdentifiers)) {
warning(`${resourceName}: unsupported resource type ${resourceType}, skipping import.`);
return undefined;
}
const idProps = resourceIdentifiers[resourceType];
const resourceProps = chg.resourceDefinition.Properties ?? {};
const fixedIdProps = idProps.filter(p => resourceProps[p]);
const fixedIdInput: ResourceIdentifierProperties = Object.fromEntries(fixedIdProps.map(p => [p, resourceProps[p]]));
const missingIdProps = idProps.filter(p => !resourceProps[p]);
if (missingIdProps.length === 0) {
// We can auto-import this, but ask the user to confirm
const props = fmtdict(fixedIdInput);
if (!await promptly.confirm(
`${chalk.blue(resourceName)} (${resourceType}): import with ${chalk.yellow(props)} (yes/no) [default: yes]? `,
{ default: 'yes' },
)) {
print(chalk.grey(`Skipping import of ${resourceName}`));
return undefined;
}
}
// Ask the user to provide missing props
const userInput: ResourceIdentifierProperties = {};
for (const missingIdProp of missingIdProps) {
const response = (await promptly.prompt(
`${chalk.blue(resourceName)} (${resourceType}): enter ${chalk.blue(missingIdProp)} to import (empty to skip):`,
{ default: '', trim: true },
));
if (!response) {
print(chalk.grey(`Skipping import of ${resourceName}`));
return undefined;
}
userInput[missingIdProp] = response;
}
return {
...fixedIdInput,
...userInput,
};
}
/**
* Convert the internal "resource mapping" structure to CloudFormation accepted "ResourcesToImport" structure
*/
private async makeResourcesToImport(resourceMap: ImportMap): Promise<ResourcesToImport> {
return resourceMap.importResources.map(res => ({
LogicalResourceId: res.logicalId,
ResourceType: res.resourceDiff.newResourceType!,
ResourceIdentifier: resourceMap.resourceMap[res.logicalId],
}));
}
/**
* Convert CloudFormation logical resource ID to CDK construct tree path
*
* @param logicalId CloudFormation logical ID of the resource (the key in the template's Resources section)
* @returns Forward-slash separated path of the resource in CDK construct tree, e.g. MyStack/MyBucket/Resource
*/
private describeResource(logicalId: string): string {
return this.stack.template?.Resources?.[logicalId]?.Metadata?.['aws:cdk:path'] ?? logicalId;
}
}
/**
* Information about a resource in the template that is importable
*/
export interface ImportableResource {
/**
* The logical ID of the resource
*/
readonly logicalId: string;
/**
* The resource definition in the new template
*/
readonly resourceDefinition: any;
/**
* The diff as reported by `cloudformation-diff`.
*/
readonly resourceDiff: ResourceDifference;
}
/**
* The information necessary to execute an import operation
*/
export interface ImportMap {
/**
* Mapping logical IDs to physical names
*/
readonly resourceMap: ResourceMap;
/**
* The selection of resources we are actually importing
*
* For each of the resources in this list, there is a corresponding entry in
* the `resourceMap` map.
*/
readonly importResources: ImportableResource[];
}
function fmtdict<A>(xs: Record<string, A>) {
return Object.entries(xs).map(([k, v]) => `${k}=${v}`).join(', ');
}
/**
* Add a default 'Delete' policy, which is required to make the import succeed
*/
function addDefaultDeletionPolicy(resource: any): any {
if (resource.DeletionPolicy) { return resource; }
return {
...resource,
DeletionPolicy: 'Delete',
};
}
export interface DiscoverImportableResourcesResult {
readonly additions: ImportableResource[];
readonly hasNonAdditions: boolean;
} | the_stack |
import 'slickgrid/plugins/slick.rowdetailview';
import 'slickgrid/plugins/slick.rowselectionmodel';
import {
addToArrayWhenNotExists,
Column,
EventSubscription,
GetSlickEventType,
RowDetailViewExtension as UniversalRowDetailViewExtension,
SharedService,
SlickEventHandler,
SlickNamespace,
SlickRowDetailView,
SlickRowSelectionModel,
unsubscribeAll,
} from '@slickgrid-universal/common';
import { EventPubSubService } from '@slickgrid-universal/event-pub-sub';
import { inject, singleton } from 'aurelia-framework';
import * as DOMPurify from 'dompurify';
import { AureliaViewOutput, GridOption, RowDetailView, SlickGrid, ViewModelBindableInputData } from '../models/index';
import { AureliaUtilService } from '../services/aureliaUtil.service';
// using external non-typed js libraries
declare const Slick: SlickNamespace;
const ROW_DETAIL_CONTAINER_PREFIX = 'container_';
const PRELOAD_CONTAINER_PREFIX = 'container_loading';
export interface CreatedView extends AureliaViewOutput {
id: string | number;
dataContext: any;
}
@singleton(true)
@inject(
AureliaUtilService,
EventPubSubService,
SharedService,
)
export class RowDetailViewExtension implements UniversalRowDetailViewExtension {
private _addon: SlickRowDetailView | null = null;
private _eventHandler: SlickEventHandler;
private _preloadView = '';
private _slots: CreatedView[] = [];
private _viewModel = '';
private _subscriptions: EventSubscription[] = [];
private _userProcessFn?: (item: any) => Promise<any>;
constructor(
private readonly aureliaUtilService: AureliaUtilService,
private readonly eventPubSubService: EventPubSubService,
private readonly sharedService: SharedService,
) {
this._eventHandler = new Slick.EventHandler();
}
private get datasetIdPropName(): string {
return this.gridOptions.datasetIdPropertyName || 'id';
}
get eventHandler(): SlickEventHandler {
return this._eventHandler;
}
get gridOptions(): GridOption {
return this.sharedService?.gridOptions ?? {};
}
get rowDetailViewOptions(): RowDetailView | undefined {
return this.gridOptions.rowDetailView;
}
/** Dispose of the RowDetailView Extension */
dispose() {
// unsubscribe all SlickGrid events
this._eventHandler.unsubscribeAll();
if (this._addon?.destroy) {
this._addon.destroy();
this._addon = null;
}
this.disposeAllViewSlot();
unsubscribeAll(this._subscriptions);
}
/** Dispose of all the opened Row Detail Panels Aurelia View Slots */
disposeAllViewSlot() {
if (Array.isArray(this._slots)) {
this._slots.forEach((slot) => this.disposeViewSlot(slot));
}
this._slots = [];
}
/**
* Create the plugin before the Grid creation, else it will behave oddly.
* Mostly because the column definitions might change after the grid creation
*/
create(columnDefinitions: Column[], gridOptions: GridOption): SlickRowDetailView | null {
if (columnDefinitions && gridOptions) {
if (!gridOptions.rowDetailView) {
throw new Error('The Row Detail View requires options to be passed via the "rowDetailView" property of the Grid Options');
}
if (gridOptions && gridOptions.rowDetailView) {
if (!this._addon) {
if (typeof gridOptions.rowDetailView.process === 'function') {
// we need to keep the user "process" method and replace it with our own execution method
// we do this because when we get the item detail, we need to call "onAsyncResponse.notify" for the plugin to work
this._userProcessFn = gridOptions.rowDetailView.process as (item: any) => Promise<any>; // keep user's process method
gridOptions.rowDetailView.process = (item) => this.onProcessing(item); // replace process method & run our internal one
} else {
throw new Error('You need to provide a "process" function for the Row Detail Extension to work properly');
}
// load the Preload & RowDetail Templates (could be straight HTML or Aurelia View/ViewModel)
// when those are Aurelia View/ViewModel, we need to create View Slot & provide the html containers to the Plugin (preTemplate/postTemplate methods)
if (!gridOptions.rowDetailView.preTemplate) {
this._preloadView = gridOptions && gridOptions.rowDetailView && gridOptions.rowDetailView.preloadView || '';
gridOptions.rowDetailView.preTemplate = () => DOMPurify.sanitize(`<div class="${PRELOAD_CONTAINER_PREFIX}"></div>`);
}
if (!gridOptions.rowDetailView.postTemplate) {
this._viewModel = gridOptions && gridOptions.rowDetailView && gridOptions.rowDetailView.viewModel || '';
gridOptions.rowDetailView.postTemplate = (itemDetail: any) => DOMPurify.sanitize(`<div class="${ROW_DETAIL_CONTAINER_PREFIX}${itemDetail[this.datasetIdPropName]}"></div>`);
}
// finally register the Row Detail View Plugin
this._addon = new Slick.Plugins.RowDetailView(gridOptions.rowDetailView);
}
const iconColumn: Column = this._addon.getColumnDefinition();
if (typeof iconColumn === 'object') {
iconColumn.excludeFromExport = true;
iconColumn.excludeFromColumnPicker = true;
iconColumn.excludeFromGridMenu = true;
iconColumn.excludeFromQuery = true;
iconColumn.excludeFromHeaderMenu = true;
// column index position in the grid
const columnPosition = gridOptions && gridOptions.rowDetailView && gridOptions.rowDetailView.columnIndexPosition || 0;
if (columnPosition > 0) {
columnDefinitions.splice(columnPosition, 0, iconColumn);
} else {
columnDefinitions.unshift(iconColumn);
}
}
}
return this._addon;
}
return null;
}
/** Get the instance of the SlickGrid addon (control or plugin). */
getAddonInstance(): SlickRowDetailView | null {
return this._addon;
}
register(rowSelectionPlugin?: SlickRowSelectionModel): SlickRowDetailView | null {
if (this.sharedService && this.sharedService.slickGrid && this.sharedService.gridOptions) {
// the plugin has to be created BEFORE the grid (else it behaves oddly), but we can only watch grid events AFTER the grid is created
this.sharedService.slickGrid.registerPlugin(this._addon);
// this also requires the Row Selection Model to be registered as well
if (!rowSelectionPlugin || !this.sharedService.slickGrid.getSelectionModel()) {
rowSelectionPlugin = new Slick.RowSelectionModel(this.sharedService.gridOptions.rowSelectionOptions || { selectActiveRow: true });
this.sharedService.slickGrid.setSelectionModel(rowSelectionPlugin);
}
this.sharedService.slickGrid.registerPlugin(this._addon);
// hook all events
if (this._addon && this.sharedService.slickGrid && this.rowDetailViewOptions) {
if (this.rowDetailViewOptions.onExtensionRegistered) {
this.rowDetailViewOptions.onExtensionRegistered(this._addon);
}
const onAsyncResponseHandler = this._addon.onAsyncResponse;
if (onAsyncResponseHandler) {
(this._eventHandler as SlickEventHandler<GetSlickEventType<typeof onAsyncResponseHandler>>).subscribe(onAsyncResponseHandler, (event, args) => {
if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onAsyncResponse === 'function') {
this.rowDetailViewOptions.onAsyncResponse(event, args);
}
});
}
const onAsyncEndUpdateHandler = this._addon.onAsyncEndUpdate;
if (onAsyncEndUpdateHandler) {
(this._eventHandler as SlickEventHandler<GetSlickEventType<typeof onAsyncEndUpdateHandler>>).subscribe(onAsyncEndUpdateHandler, (event, args) => {
// triggers after backend called "onAsyncResponse.notify()"
this.renderViewModel(args && args.item);
if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onAsyncEndUpdate === 'function') {
this.rowDetailViewOptions.onAsyncEndUpdate(event, args);
}
});
}
const onAfterRowDetailToggleHandler = this._addon.onAfterRowDetailToggle;
if (onAfterRowDetailToggleHandler) {
(this._eventHandler as SlickEventHandler<GetSlickEventType<typeof onAfterRowDetailToggleHandler>>).subscribe(onAfterRowDetailToggleHandler, (event, args) => {
// display preload template & re-render all the other Detail Views after toggling
// the preload View will eventually go away once the data gets loaded after the "onAsyncEndUpdate" event
this.renderPreloadView();
this.renderAllViewModels();
if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onAfterRowDetailToggle === 'function') {
this.rowDetailViewOptions.onAfterRowDetailToggle(event, args);
}
});
}
const onBeforeRowDetailToggleHandler = this._addon.onBeforeRowDetailToggle;
if (onBeforeRowDetailToggleHandler) {
(this._eventHandler as SlickEventHandler<GetSlickEventType<typeof onBeforeRowDetailToggleHandler>>).subscribe(onBeforeRowDetailToggleHandler, (event, args) => {
// before toggling row detail, we need to create View Slot if it doesn't exist
this.onBeforeRowDetailToggle(event, args);
if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onBeforeRowDetailToggle === 'function') {
this.rowDetailViewOptions.onBeforeRowDetailToggle(event, args);
}
});
}
const onRowBackToViewportRangeHandler = this._addon.onRowBackToViewportRange;
if (onRowBackToViewportRangeHandler) {
(this._eventHandler as SlickEventHandler<GetSlickEventType<typeof onRowBackToViewportRangeHandler>>).subscribe(onRowBackToViewportRangeHandler, (event, args) => {
// when row is back to viewport range, we will re-render the View Slot(s)
this.onRowBackToViewportRange(event, args);
if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onRowBackToViewportRange === 'function') {
this.rowDetailViewOptions.onRowBackToViewportRange(event, args);
}
});
}
const onRowOutOfViewportRangeHandler = this._addon.onRowOutOfViewportRange;
if (onRowOutOfViewportRangeHandler) {
(this._eventHandler as SlickEventHandler<GetSlickEventType<typeof onRowOutOfViewportRangeHandler>>).subscribe(onRowOutOfViewportRangeHandler, (event, args) => {
if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onRowOutOfViewportRange === 'function') {
this.rowDetailViewOptions.onRowOutOfViewportRange(event, args);
}
});
}
// --
// hook some events needed by the Plugin itself
// we need to redraw the open detail views if we change column position (column reorder)
this._eventHandler.subscribe(this.sharedService.slickGrid.onColumnsReordered, this.redrawAllViewSlots.bind(this));
// on row selection changed, we also need to redraw
if (this.gridOptions.enableRowSelection || this.gridOptions.enableCheckboxSelector) {
this._eventHandler.subscribe(this.sharedService.slickGrid.onSelectedRowsChanged, this.redrawAllViewSlots.bind(this));
}
// on column sort/reorder, all row detail are collapsed so we can dispose of all the Views as well
this._eventHandler.subscribe(this.sharedService.slickGrid.onSort, this.disposeAllViewSlot.bind(this));
// on filter changed, we need to re-render all Views
this._subscriptions.push(
this.eventPubSubService.subscribe('onFilterChanged', this.redrawAllViewSlots.bind(this))
);
}
return this._addon;
}
return null;
}
/** Redraw (re-render) all the expanded row detail View Slots */
redrawAllViewSlots() {
this._slots.forEach((slot) => {
this.redrawViewSlot(slot);
});
}
/** Render all the expanded row detail View Slots */
renderAllViewModels() {
this._slots.forEach((slot) => {
if (slot && slot.dataContext) {
this.renderViewModel(slot.dataContext);
}
});
}
/** Redraw the necessary View Slot */
redrawViewSlot(slot: CreatedView) {
const containerElement = document.getElementsByClassName(`${ROW_DETAIL_CONTAINER_PREFIX}${slot.id}`);
if (containerElement && containerElement.length >= 0) {
this.renderViewModel(slot.dataContext);
}
}
/** Render (or re-render) the View Slot (Row Detail) */
renderPreloadView() {
const containerElements = document.getElementsByClassName(`${PRELOAD_CONTAINER_PREFIX}`);
if (containerElements && containerElements.length >= 0) {
this.aureliaUtilService.createAureliaViewAddToSlot(this._preloadView, containerElements[containerElements.length - 1], true);
}
}
/** Render (or re-render) the View Slot (Row Detail) */
renderViewModel(item: any) {
const containerElements = document.getElementsByClassName(`${ROW_DETAIL_CONTAINER_PREFIX}${item[this.datasetIdPropName]}`);
if (containerElements && containerElements.length > 0) {
const bindableData = {
model: item,
addon: this._addon,
grid: this.sharedService.slickGrid,
dataView: this.sharedService.dataView,
parent: this.rowDetailViewOptions && this.rowDetailViewOptions.parent,
} as ViewModelBindableInputData;
const aureliaComp = this.aureliaUtilService.createAureliaViewModelAddToSlot(this._viewModel, bindableData, containerElements[containerElements.length - 1], true);
const slotObj = this._slots.find(obj => obj.id === item[this.datasetIdPropName]);
if (slotObj && aureliaComp) {
slotObj.view = aureliaComp.view;
slotObj.viewSlot = aureliaComp.viewSlot;
}
}
}
// --
// private functions
// ------------------
private disposeViewSlot(expandedView: CreatedView) {
if (expandedView && expandedView.view && expandedView.viewSlot && expandedView.view.unbind && expandedView.viewSlot.remove) {
const container = document.getElementsByClassName(`${ROW_DETAIL_CONTAINER_PREFIX}${this._slots[0].id}`);
if (container && container.length > 0) {
expandedView.viewSlot.remove(expandedView.view);
expandedView.view.unbind();
container[0].innerHTML = '';
return expandedView;
}
}
return null;
}
/**
* notify the onAsyncResponse with the "args.item" (required property)
* the plugin will then use item to populate the row detail panel with the "postTemplate"
* @param item
*/
private notifyTemplate(item: any) {
if (this._addon?.onAsyncResponse) {
this._addon.onAsyncResponse.notify({ item }, new Slick.EventData(), this);
}
}
/**
* On Processing, we will notify the plugin with the new item detail once backend server call completes
* @param item
*/
private async onProcessing(item: any) {
if (item && typeof this._userProcessFn === 'function') {
let awaitedItemDetail: any;
const userProcessFn = this._userProcessFn(item);
// wait for the "userProcessFn", once resolved we will save it into the "collection"
const response: any | any[] = await userProcessFn;
if (response.hasOwnProperty(this.datasetIdPropName)) {
awaitedItemDetail = response; // from Promise
} else if (response instanceof Response && typeof response['json'] === 'function') {
awaitedItemDetail = await response['json'](); // from Fetch
} else if (response && response['content']) {
awaitedItemDetail = response['content']; // from aurelia-http-client
}
if (!awaitedItemDetail || !awaitedItemDetail.hasOwnProperty(this.datasetIdPropName)) {
throw new Error(`[Aurelia-Slickgrid] could not process the Row Detail, you must make sure that your "process" callback
(a Promise or an HttpClient call returning an Observable) returns an item object that has an "${this.datasetIdPropName}" property`);
}
// notify the plugin with the new item details
this.notifyTemplate(awaitedItemDetail || {});
}
}
/**
* Just before the row get expanded or collapsed we will do the following
* First determine if the row is expanding or collapsing,
* if it's expanding we will add it to our View Slots reference array if we don't already have it
* or if it's collapsing we will remove it from our View Slots reference array
*/
private onBeforeRowDetailToggle(_e: Event, args: { grid: SlickGrid; item: any; }) {
// expanding
if (args && args.item && args.item.__collapsed) {
// expanding row detail
if (args && args.item) {
const viewInfo: CreatedView = {
id: args.item[this.datasetIdPropName],
dataContext: args.item
};
const idPropName = this.gridOptions.datasetIdPropertyName || 'id';
addToArrayWhenNotExists(this._slots, viewInfo, idPropName);
}
} else {
// collapsing, so dispose of the View/ViewSlot
const foundSlotIndex = this._slots.findIndex((slot: CreatedView) => slot.id === args.item[this.datasetIdPropName]);
if (foundSlotIndex >= 0) {
if (this.disposeViewSlot(this._slots[foundSlotIndex])) {
this._slots.splice(foundSlotIndex, 1);
}
}
}
}
/** When Row comes back to Viewport Range, we need to redraw the View */
private onRowBackToViewportRange(_e: Event, args: {
item: any;
rowId: string | number;
rowIndex: number;
expandedRows: (string | number)[];
rowIdsOutOfViewport: (string | number)[];
grid: SlickGrid;
}) {
if (args && args.item) {
this._slots.forEach((slot) => {
if (slot.id === args.item[this.datasetIdPropName]) {
this.redrawViewSlot(slot);
}
});
}
}
} | the_stack |
import { CommandRegistry } from '@phosphor/commands';
import { Menu, MenuBar } from '@phosphor/widgets';
import { CompletionHandler } from '@jupyterlab/completer';
import { NotebookPanel, NotebookActions } from '@jupyterlab/notebook';
import {
SearchInstance,
NotebookSearchProvider
} from '@jupyterlab/documentsearch';
import { dismissTooltip, invokeTooltip } from './tooltip';
/**
* The map of command ids used by the notebook.
*/
const cmdIds = {
invoke: 'completer:invoke',
select: 'completer:select',
invokeNotebook: 'completer:invoke-notebook',
selectNotebook: 'completer:select-notebook',
dismissTooltip: 'tooltip:dismiss',
invokeTooltip: 'tooltip:invoke',
startSearch: 'documentsearch:start-search',
findNext: 'documentsearch:find-next',
findPrevious: 'documentsearch:find-previous',
save: 'notebook:save',
undo: 'notebook-cells:undo',
redo: 'notebook-cells:redo',
cut: 'notebook:cut-cell',
copy: 'notebook:copy-cell',
pasteAbove: 'notebook:paste-cell-above',
pasteBelow: 'notebook:paste-cell-below',
pasteAndReplace: 'notebook:paste-and-replace-cell',
deleteCell: 'notebook:delete-cell',
selectAll: 'notebook:select-all',
deselectAll: 'notebook:deselect-all',
moveUp: 'notebook:move-cell-up',
moveDown: 'notebook:move-cell-down',
split: 'notebook:split-cell-at-cursor',
merge: 'notebook:merge-cells',
clearOutputs: 'notebook:clear-cell-output',
clearAllOutputs: 'notebook:clear-all-cell-outputs',
hideCode: 'notebook:hide-cell-code',
hideOutput: 'notebook:hide-cell-outputs',
hideAllCode: 'notebook:hide-all-cell-code',
hideAllOutputs: 'notebook:hide-all-cell-outputs',
showCode: 'notebook:show-cell-code',
showOutput: 'notebook:show-cell-outputs',
showAllCode: 'notebook:show-all-cell-code',
showAllOutputs: 'notebook:show-all-cell-outputs',
runAndAdvance: 'notebook-cells:run-and-advance',
run: 'notebook:run-cell',
runAndInsert: 'notebook-cells:run-cell-and-insert-below',
runAllAbove: 'notebook-cells:run-all-above',
runAllBelow: 'notebook-cells:run-all-below',
renderAllMarkdown: 'notebook-cells:render-all-markdown',
runAll: 'notebook-cells:run-all-cells',
restartRunAll: 'notebook:restart-run-all',
interrupt: 'notebook:interrupt-kernel',
restart: 'notebook:restart-kernel',
restartClear: 'notebook:restart-clear-output',
shutdown: 'notebook:shutdown-kernel',
switchKernel: 'notebook:switch-kernel',
selectAbove: 'notebook-cells:select-above',
selectBelow: 'notebook-cells:select-below',
extendAbove: 'notebook-cells:extend-above',
extendTop: 'notebook-cells:extend-top',
extendBelow: 'notebook-cells:extend-below',
extendBottom: 'notebook-cells:extend-bottom',
editMode: 'notebook:edit-mode',
commandMode: 'notebook:command-mode',
toCode: 'notebook:change-cell-to-code',
markdown1: 'notebook:change-cell-to-heading-1',
markdown2: 'notebook:change-cell-to-heading-2',
markdown3: 'notebook:change-cell-to-heading-3',
markdown4: 'notebook:change-cell-to-heading-4',
markdown5: 'notebook:change-cell-to-heading-5',
markdown6: 'notebook:change-cell-to-heading-6',
toMarkdown: 'notebook:change-cell-to-markdown',
toRaw: 'notebook:change-cell-to-raw',
insertAbove: 'notebook:insert-cell-above',
insertBelow: 'notebook:insert-cell-below',
toggleAllLines: 'notebook:toggle-all-cell-line-numbers'
};
export const SetupCommands = (
commands: CommandRegistry,
menuBar: MenuBar,
nbWidget: NotebookPanel,
handler: CompletionHandler
) => {
/**
* Whether notebook has a single selected cell.
*/
function isSingleSelected(): boolean {
const content = nbWidget.content;
const index = content.activeCellIndex;
// If there are selections that are not the active cell,
// this command is confusing, so disable it.
for (let i = 0; i < content.widgets.length; ++i) {
if (content.isSelected(content.widgets[i]) && i !== index) {
return false;
}
}
return true;
}
// Commands in Edit menu.
commands.addCommand(cmdIds.undo, {
label: 'Undo',
execute: () => NotebookActions.undo(nbWidget.content)
});
commands.addCommand(cmdIds.redo, {
label: 'Redo',
execute: () => NotebookActions.redo(nbWidget.content)
});
commands.addCommand(cmdIds.cut, {
label: 'Cut Cells',
execute: () => NotebookActions.cut(nbWidget.content)
});
commands.addCommand(cmdIds.copy, {
label: 'Copy Cells',
execute: () => NotebookActions.copy(nbWidget.content)
});
commands.addCommand(cmdIds.pasteBelow, {
label: 'Paste Cells Below',
execute: () => NotebookActions.paste(nbWidget.content, 'below')
});
commands.addCommand(cmdIds.pasteAbove, {
label: 'Paste Cells Above',
execute: () => NotebookActions.paste(nbWidget.content, 'above')
});
commands.addCommand(cmdIds.pasteAndReplace, {
label: 'Paste Cells and Replace',
execute: () => NotebookActions.paste(nbWidget.content, 'replace')
});
commands.addCommand(cmdIds.deleteCell, {
label: 'Delete Cells',
execute: () => NotebookActions.deleteCells(nbWidget.content)
});
commands.addCommand(cmdIds.selectAll, {
label: 'Select All Cells',
execute: () => NotebookActions.selectAll(nbWidget.content)
});
commands.addCommand(cmdIds.deselectAll, {
label: 'Deselect All Cells',
execute: () => NotebookActions.deselectAll(nbWidget.content)
});
commands.addCommand(cmdIds.moveUp, {
label: 'Move Cells Up',
execute: () => NotebookActions.moveUp(nbWidget.content)
});
commands.addCommand(cmdIds.moveDown, {
label: 'Move Cells Down',
execute: () => NotebookActions.moveDown(nbWidget.content)
});
commands.addCommand(cmdIds.split, {
label: 'Split Cell',
execute: () => NotebookActions.splitCell(nbWidget.content)
});
commands.addCommand(cmdIds.merge, {
label: 'Merge Selected Cells',
execute: () => NotebookActions.mergeCells(nbWidget.content)
});
commands.addCommand(cmdIds.clearOutputs, {
label: 'Clear Outputs',
execute: () => NotebookActions.clearOutputs(nbWidget.content)
});
commands.addCommand(cmdIds.clearAllOutputs, {
label: 'Clear All Outputs',
execute: () => NotebookActions.clearAllOutputs(nbWidget.content)
});
// Commands in View menu.
commands.addCommand(cmdIds.hideCode, {
label: 'Collapse Selected Code',
execute: () => NotebookActions.hideCode(nbWidget.content)
});
commands.addCommand(cmdIds.hideOutput, {
label: 'Collapse Selected Outputs',
execute: () => NotebookActions.hideOutput(nbWidget.content)
});
commands.addCommand(cmdIds.hideAllCode, {
label: 'Collapse All Code',
execute: () => NotebookActions.hideAllCode(nbWidget.content)
});
commands.addCommand(cmdIds.hideAllOutputs, {
label: 'Collapse All Outputs',
execute: () => NotebookActions.hideAllOutputs(nbWidget.content)
});
commands.addCommand(cmdIds.showCode, {
label: 'Expand Selected Code',
execute: () => NotebookActions.showCode(nbWidget.content)
});
commands.addCommand(cmdIds.showOutput, {
label: 'Expand Selected Outputs',
execute: () => NotebookActions.showOutput(nbWidget.content)
});
commands.addCommand(cmdIds.showAllCode, {
label: 'Expand All Code',
execute: () => NotebookActions.showAllCode(nbWidget.content)
});
commands.addCommand(cmdIds.showAllOutputs, {
label: 'Expand All Outputs',
execute: () => NotebookActions.showAllOutputs(nbWidget.content)
});
// Commands in Run menu.
commands.addCommand(cmdIds.runAndAdvance, {
label: 'Run Selected Cells',
execute: () => {
return NotebookActions.runAndAdvance(
nbWidget.content,
nbWidget.context.session
);
}
});
commands.addCommand(cmdIds.run, {
label: "Run Selected Cells and Don't Advance",
execute: () => {
return NotebookActions.run(
nbWidget.content,
nbWidget.context.session
);
}
});
commands.addCommand(cmdIds.runAndInsert, {
label: 'Run Selected Cells and Insert Below',
execute: () => {
return NotebookActions.runAndInsert(
nbWidget.content,
nbWidget.context.session
);
}
});
commands.addCommand(cmdIds.runAllAbove, {
label: 'Run All Above Selected Cell',
execute: () => {
return NotebookActions.runAllAbove(
nbWidget.content,
nbWidget.context.session
);
},
isEnabled: () => {
// Can't run above if there are multiple cells selected,
// or if we are at the top of the notebook.
return isSingleSelected() && nbWidget.content.activeCellIndex !== 0;
}
});
commands.addCommand(cmdIds.runAllBelow, {
label: 'Run Selected Cell and All Below',
execute: () => {
return NotebookActions.runAllBelow(
nbWidget.content,
nbWidget.context.session
);
},
isEnabled: () => {
// Can't run below if there are multiple cells selected,
// or if we are at the bottom of the notebook.
return (
isSingleSelected() &&
nbWidget.content.activeCellIndex !==
nbWidget.content.widgets.length - 1
);
}
});
commands.addCommand(cmdIds.renderAllMarkdown, {
label: 'Render All Markdown Cells',
execute: () => {
return NotebookActions.renderAllMarkdown(
nbWidget.content,
nbWidget.context.session
);
}
});
commands.addCommand(cmdIds.runAll, {
label: 'Run All Cells',
execute: () => {
return NotebookActions.runAll(
nbWidget.content,
nbWidget.context.session
);
}
});
commands.addCommand(cmdIds.restartRunAll, {
label: 'Restart Kernel and Run All Cells…',
execute: () => {
return nbWidget.session.restart().then(restarted => {
if (restarted) {
void NotebookActions.runAll(
nbWidget.content,
nbWidget.context.session
);
}
return restarted;
});
}
});
// Commands in Kernel menu.
commands.addCommand(cmdIds.interrupt, {
label: 'Interrupt Kernel',
execute: async () => {
if (nbWidget.context.session.kernel) {
await nbWidget.context.session.kernel.interrupt();
}
}
});
commands.addCommand(cmdIds.restart, {
label: 'Restart Kernel…',
execute: () => nbWidget.context.session.restart()
});
commands.addCommand(cmdIds.restartClear, {
label: 'Restart Kernel and Clear All Outputs…',
execute: () => nbWidget.context.session.restart().then(() => {
NotebookActions.clearAllOutputs(nbWidget.content);
})
});
commands.addCommand(cmdIds.shutdown, {
label: 'Shutdown Kernel',
execute: () => nbWidget.context.session.shutdown()
});
commands.addCommand(cmdIds.switchKernel, {
label: 'Change Kernel…',
execute: () => nbWidget.context.session.selectKernel()
});
// Tooltip commands
commands.addCommand(cmdIds.dismissTooltip, {
label: 'Dismiss Tooltip',
execute: () => dismissTooltip()
});
commands.addCommand(cmdIds.invokeTooltip, {
label: 'Invoke Tooltip',
execute: () => invokeTooltip(nbWidget)
});
// Add other commands.
commands.addCommand(cmdIds.invoke, {
label: 'Completer: Invoke',
execute: () => handler.invoke()
});
commands.addCommand(cmdIds.select, {
label: 'Completer: Select',
execute: () => handler.completer.selectActive()
});
commands.addCommand(cmdIds.invokeNotebook, {
label: 'Invoke Notebook',
execute: () => {
if (nbWidget.content.activeCell.model.type === 'code') {
return commands.execute(cmdIds.invoke);
}
}
});
commands.addCommand(cmdIds.selectNotebook, {
label: 'Select Notebook',
execute: () => {
if (nbWidget.content.activeCell.model.type === 'code') {
return commands.execute(cmdIds.select);
}
}
});
commands.addCommand(cmdIds.save, {
label: 'Save',
execute: () => nbWidget.context.save()
});
let searchInstance: SearchInstance;
commands.addCommand(cmdIds.startSearch, {
label: 'Find...',
execute: () => {
if (searchInstance) {
searchInstance.focusInput();
return;
}
const provider = new NotebookSearchProvider();
searchInstance = new SearchInstance(nbWidget, provider);
searchInstance.disposed.connect(() => {
searchInstance = undefined;
// find next and previous are now not enabled
commands.notifyCommandChanged();
});
// find next and previous are now enabled
commands.notifyCommandChanged();
searchInstance.focusInput();
}
});
commands.addCommand(cmdIds.findNext, {
label: 'Find Next',
isEnabled: () => !!searchInstance,
execute: async () => {
if (!searchInstance) {
return;
}
await searchInstance.provider.highlightNext();
searchInstance.updateIndices();
}
});
commands.addCommand(cmdIds.findPrevious, {
label: 'Find Previous',
isEnabled: () => !!searchInstance,
execute: async () => {
if (!searchInstance) {
return;
}
await searchInstance.provider.highlightPrevious();
searchInstance.updateIndices();
}
});
commands.addCommand(cmdIds.editMode, {
label: 'Edit Mode',
execute: () => {
nbWidget.content.mode = 'edit';
}
});
commands.addCommand(cmdIds.commandMode, {
label: 'Command Mode',
execute: () => {
nbWidget.content.mode = 'command';
}
});
commands.addCommand(cmdIds.selectBelow, {
label: 'Select Below',
execute: () => NotebookActions.selectBelow(nbWidget.content)
});
commands.addCommand(cmdIds.selectAbove, {
label: 'Select Above',
execute: () => NotebookActions.selectAbove(nbWidget.content)
});
commands.addCommand(cmdIds.extendAbove, {
label: 'Extend Above',
execute: () => NotebookActions.extendSelectionAbove(nbWidget.content)
});
commands.addCommand(cmdIds.extendTop, {
label: 'Extend to Top',
execute: () => NotebookActions.extendSelectionAbove(nbWidget.content, true)
});
commands.addCommand(cmdIds.extendBelow, {
label: 'Extend Below',
execute: () => NotebookActions.extendSelectionBelow(nbWidget.content)
});
commands.addCommand(cmdIds.extendBottom, {
label: 'Extend to Bottom',
execute: () => NotebookActions.extendSelectionBelow(nbWidget.content, true)
});
commands.addCommand(cmdIds.toCode, {
label: 'Change to Code Cell Type',
execute: () => NotebookActions.changeCellType(nbWidget.content, 'code')
});
commands.addCommand(cmdIds.toMarkdown, {
label: 'Change to Markdown Cell Type',
execute: () => NotebookActions.changeCellType(nbWidget.content, 'markdown')
});
commands.addCommand(cmdIds.toRaw, {
label: 'Change to Raw Cell Type',
execute: () => NotebookActions.changeCellType(nbWidget.content, 'raw')
});
commands.addCommand(cmdIds.markdown1, {
label: 'Change to Heading 1',
execute: () => NotebookActions.setMarkdownHeader(nbWidget.content, 1)
});
commands.addCommand(cmdIds.markdown2, {
label: 'Change to Heading 2',
execute: () => NotebookActions.setMarkdownHeader(nbWidget.content, 2)
});
commands.addCommand(cmdIds.markdown3, {
label: 'Change to Heading 3',
execute: () => NotebookActions.setMarkdownHeader(nbWidget.content, 3)
});
commands.addCommand(cmdIds.markdown4, {
label: 'Change to Heading 4',
execute: () => NotebookActions.setMarkdownHeader(nbWidget.content, 4)
});
commands.addCommand(cmdIds.markdown5, {
label: 'Change to Heading 5',
execute: () => NotebookActions.setMarkdownHeader(nbWidget.content, 5)
});
commands.addCommand(cmdIds.markdown6, {
label: 'Change to Heading 6',
execute: () => NotebookActions.setMarkdownHeader(nbWidget.content, 6)
});
commands.addCommand(cmdIds.insertAbove, {
label: 'Insert Cell Above',
execute: () => NotebookActions.insertAbove(nbWidget.content)
});
commands.addCommand(cmdIds.insertBelow, {
label: 'Insert Cell Below',
execute: () => NotebookActions.insertBelow(nbWidget.content)
});
commands.addCommand(cmdIds.toggleAllLines, {
label: 'Toggle All Line Numbers',
execute: () => NotebookActions.toggleAllLineNumbers(nbWidget.content)
});
let bindings = [
{
selector: '.jp-Notebook.jp-mod-editMode .jp-mod-completer-enabled',
keys: ['Tab'],
command: cmdIds.invokeNotebook
},
{
selector: `.jp-mod-completer-active`,
keys: ['Enter'],
command: cmdIds.selectNotebook
},
{
selector: 'body.jp-mod-tooltip .jp-Notebook',
keys: ['Escape'],
command: cmdIds.dismissTooltip
},
{
selector: '.jp-Notebook.jp-mod-editMode .jp-InputArea-editor:not(.jp-mod-has-primary-selection):not(.jp-mod-in-leading-whitespace)',
keys: ['Shift Tab'],
command: cmdIds.invokeTooltip
},
{
selector: '.jp-Notebook',
keys: ['Shift Enter'],
command: cmdIds.runAndAdvance
},
{
selector: '.jp-Notebook',
keys: ['Accel S'],
command: cmdIds.save
},
{
selector: '.jp-Notebook',
keys: ['Accel F'],
command: cmdIds.startSearch
},
{
selector: '.jp-Notebook',
keys: ['Accel G'],
command: cmdIds.findNext
},
{
selector: '.jp-Notebook',
keys: ['Accel Shift G'],
command: cmdIds.findPrevious
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['I', 'I'],
command: cmdIds.interrupt
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['0', '0'],
command: cmdIds.restart
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Enter'],
command: cmdIds.editMode
},
{
selector: '.jp-Notebook.jp-mod-editMode',
keys: ['Escape'],
command: cmdIds.commandMode
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Shift M'],
command: cmdIds.merge
},
{
selector: '.jp-Notebook.jp-mod-editMode',
keys: ['Ctrl Shift -'],
command: cmdIds.split
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['J'],
command: cmdIds.selectBelow
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['ArrowDown'],
command: cmdIds.selectBelow
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['K'],
command: cmdIds.selectAbove
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['ArrowUp'],
command: cmdIds.selectAbove
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Shift K'],
command: cmdIds.extendAbove
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Shift J'],
command: cmdIds.extendBelow
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Z'],
command: cmdIds.undo
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Shift Z'],
command: cmdIds.redo
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Y'],
command: cmdIds.toCode
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['1'],
command: cmdIds.markdown1
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['2'],
command: cmdIds.markdown2
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['3'],
command: cmdIds.markdown3
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['4'],
command: cmdIds.markdown4
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['5'],
command: cmdIds.markdown5
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['6'],
command: cmdIds.markdown6
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['M'],
command: cmdIds.toMarkdown
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['R'],
command: cmdIds.toRaw
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['C'],
command: cmdIds.copy
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['X'],
command: cmdIds.cut
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['D', 'D'],
command: cmdIds.deleteCell
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Shift ArrowUp'],
command: cmdIds.extendAbove
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Shift Home'],
command: cmdIds.extendTop
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Shift ArrowDown'],
command: cmdIds.extendBelow
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Shift End'],
command: cmdIds.extendBottom
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['A'],
command: cmdIds.insertAbove
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['B'],
command: cmdIds.insertBelow
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['V'],
command: cmdIds.pasteBelow
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Ctrl Enter'],
command: cmdIds.run
},
{
selector: '.jp-Notebook.jp-mod-editMode',
keys: ['Ctrl Enter'],
command: cmdIds.run
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Alt Enter'],
command: cmdIds.runAndInsert
},
{
selector: '.jp-Notebook.jp-mod-editMode',
keys: ['Alt Enter'],
command: cmdIds.runAndInsert
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['A', 'A'],
command: cmdIds.selectAll
},
{
selector: '.jp-Notebook.jp-mod-commandMode:focus',
keys: ['Shift L'],
command: cmdIds.toggleAllLines
}
];
bindings.map(binding => commands.addKeyBinding(binding));
// Create Edit menu.
let editMenu = new Menu({ commands });
editMenu.title.label = 'Edit';
editMenu.insertItem(0, { command: cmdIds.undo });
editMenu.insertItem(1, { command: cmdIds.redo });
editMenu.insertItem(2, { type: 'separator' });
editMenu.insertItem(3, { command: cmdIds.cut });
editMenu.insertItem(4, { command: cmdIds.copy });
editMenu.insertItem(5, { command: cmdIds.pasteAbove });
editMenu.insertItem(6, { command: cmdIds.pasteBelow});
editMenu.insertItem(7, { command: cmdIds.pasteAndReplace });
editMenu.insertItem(8, { type: 'separator' });
editMenu.insertItem(9, { command: cmdIds.deleteCell });
editMenu.insertItem(10, { type: 'separator' });
editMenu.insertItem(11, { command: cmdIds.moveUp });
editMenu.insertItem(12, { command: cmdIds.moveDown });
editMenu.insertItem(13, { type: 'separator' });
editMenu.insertItem(14, { command: cmdIds.split});
editMenu.insertItem(15, { command: cmdIds.merge});
editMenu.insertItem(16, { type: 'separator' });
editMenu.insertItem(17, { command: cmdIds.clearOutputs });
editMenu.insertItem(18, { command: cmdIds.clearAllOutputs });
// Create View menu.
let viewMenu = new Menu({ commands });
viewMenu.title.label = 'View';
viewMenu.insertItem(0, { command: cmdIds.hideCode });
viewMenu.insertItem(1, { command: cmdIds.hideOutput });
viewMenu.insertItem(2, { command: cmdIds.hideAllCode });
viewMenu.insertItem(3, { command: cmdIds.hideAllOutputs });
viewMenu.insertItem(4, { type: 'separator' });
viewMenu.insertItem(5, { command: cmdIds.showCode });
viewMenu.insertItem(6, { command: cmdIds.showOutput });
viewMenu.insertItem(7, { command: cmdIds.showAllCode });
viewMenu.insertItem(8, { command: cmdIds.showAllOutputs });
// Create Run menu.
let runMenu = new Menu({ commands });
runMenu.title.label = 'Run';
runMenu.insertItem(0, { command: cmdIds.runAndAdvance });
runMenu.insertItem(1, { command: cmdIds.run });
runMenu.insertItem(2, { command: cmdIds.runAndInsert });
runMenu.insertItem(3, { command: cmdIds.runAllAbove });
runMenu.insertItem(4, { command: cmdIds.runAllBelow });
runMenu.insertItem(5, { command: cmdIds.renderAllMarkdown });
runMenu.insertItem(6, { command: cmdIds.runAll });
runMenu.insertItem(7, { command: cmdIds.restartRunAll });
// Create Kernel menu.
let kernelMenu = new Menu({ commands });
kernelMenu.title.label = 'Kernel';
kernelMenu.insertItem(0, { command: cmdIds.interrupt });
kernelMenu.insertItem(1, { command: cmdIds.restart });
kernelMenu.insertItem(2, { command: cmdIds.restartClear });
kernelMenu.insertItem(3, { command: cmdIds.restartRunAll});
kernelMenu.insertItem(4, { command: cmdIds.shutdown });
kernelMenu.insertItem(4, { command: cmdIds.switchKernel });
// Insert menus in menu bar.
menuBar.insertMenu(0, editMenu);
menuBar.insertMenu(1, viewMenu);
menuBar.insertMenu(2, runMenu);
menuBar.insertMenu(3, kernelMenu);
}; | the_stack |
import {
AfterViewInit,
ContentChild,
Directive,
ElementRef,
EventEmitter,
HostListener,
Input,
NgZone,
OnDestroy,
Output,
Renderer2
} from "@angular/core";
import {
DndEvent,
DragDropData,
getDirectChildElement,
getDropData,
shouldPositionPlaceholderBeforeElement
} from "./dnd-utils";
import { getDndType, getDropEffect, isExternalDrag, setDropEffect } from "./dnd-state";
import { DropEffect, EffectAllowed } from "./dnd-types";
export interface DndDropEvent {
event:DragEvent;
dropEffect:DropEffect;
isExternal:boolean;
data?:any;
index?:number;
type?:any;
}
@Directive( {
selector: "[dndPlaceholderRef]"
} )
export class DndPlaceholderRefDirective {
constructor( public readonly elementRef:ElementRef ) {
}
}
@Directive( {
selector: "[dndDropzone]"
} )
export class DndDropzoneDirective implements AfterViewInit, OnDestroy {
@Input()
dndDropzone?:string[];
@Input()
dndEffectAllowed:EffectAllowed;
@Input()
dndAllowExternal:boolean = false;
@Input()
dndHorizontal:boolean = false;
@Input()
dndDragoverClass:string = "dndDragover";
@Input()
dndDropzoneDisabledClass = "dndDropzoneDisabled";
@Output()
readonly dndDragover:EventEmitter<DragEvent> = new EventEmitter<DragEvent>();
@Output()
readonly dndDrop:EventEmitter<DndDropEvent> = new EventEmitter<DndDropEvent>();
@ContentChild( DndPlaceholderRefDirective )
private readonly dndPlaceholderRef?:DndPlaceholderRefDirective;
private placeholder:Element | null = null;
private disabled:boolean = false;
private readonly dragEnterEventHandler:( event:DragEvent ) => void = ( event:DragEvent ) => this.onDragEnter( event );
private readonly dragOverEventHandler:( event:DragEvent ) => void = ( event:DragEvent ) => this.onDragOver( event );
private readonly dragLeaveEventHandler:( event:DragEvent ) => void = ( event:DragEvent ) => this.onDragLeave( event );
@Input()
set dndDisableIf( value:boolean ) {
this.disabled = !!value;
if( this.disabled ) {
this.renderer.addClass( this.elementRef.nativeElement, this.dndDropzoneDisabledClass );
}
else {
this.renderer.removeClass( this.elementRef.nativeElement, this.dndDropzoneDisabledClass );
}
}
@Input()
set dndDisableDropIf( value:boolean ) {
this.dndDisableIf = value;
}
constructor( private ngZone:NgZone,
private elementRef:ElementRef,
private renderer:Renderer2 ) {
}
ngAfterViewInit():void {
this.placeholder = this.tryGetPlaceholder();
this.removePlaceholderFromDOM();
this.ngZone.runOutsideAngular( () => {
this.elementRef.nativeElement.addEventListener( "dragenter", this.dragEnterEventHandler );
this.elementRef.nativeElement.addEventListener( "dragover", this.dragOverEventHandler );
this.elementRef.nativeElement.addEventListener( "dragleave", this.dragLeaveEventHandler );
} );
}
ngOnDestroy():void {
this.elementRef.nativeElement.removeEventListener( "dragenter", this.dragEnterEventHandler );
this.elementRef.nativeElement.removeEventListener( "dragover", this.dragOverEventHandler );
this.elementRef.nativeElement.removeEventListener( "dragleave", this.dragLeaveEventHandler );
}
onDragEnter( event:DndEvent ) {
// check if another dropzone is activated
if( event._dndDropzoneActive === true ) {
this.cleanupDragoverState();
return;
}
// set as active if the target element is inside this dropzone
if( typeof event._dndDropzoneActive === "undefined" ) {
const newTarget = document.elementFromPoint( event.clientX, event.clientY );
if( this.elementRef.nativeElement.contains( newTarget ) ) {
event._dndDropzoneActive = true;
}
}
// check if this drag event is allowed to drop on this dropzone
const type = getDndType( event );
if( this.isDropAllowed( type ) === false ) {
return;
}
// allow the dragenter
event.preventDefault();
}
onDragOver( event:DragEvent ) {
// With nested dropzones, we want to ignore this event if a child dropzone
// has already handled a dragover. Historically, event.stopPropagation() was
// used to prevent this bubbling, but that prevents any dragovers outside the
// ngx-drag-drop component, and stops other use cases such as scrolling on drag.
// Instead, we can check if the event was already prevented by a child and bail early.
if( event.defaultPrevented ) {
return;
}
// check if this drag event is allowed to drop on this dropzone
const type = getDndType( event );
if( this.isDropAllowed( type ) === false ) {
return;
}
this.checkAndUpdatePlaceholderPosition( event );
const dropEffect = getDropEffect( event, this.dndEffectAllowed );
if( dropEffect === "none" ) {
this.cleanupDragoverState();
return;
}
// allow the dragover
event.preventDefault();
// set the drop effect
setDropEffect( event, dropEffect );
this.dndDragover.emit( event );
this.renderer.addClass( this.elementRef.nativeElement, this.dndDragoverClass );
}
@HostListener( "drop", [ "$event" ] )
onDrop( event:DragEvent ) {
try {
// check if this drag event is allowed to drop on this dropzone
const type = getDndType( event );
if( this.isDropAllowed( type ) === false ) {
return;
}
const data:DragDropData = getDropData( event, isExternalDrag() );
if( this.isDropAllowed( data.type ) === false ) {
return;
}
// signal custom drop handling
event.preventDefault();
const dropEffect = getDropEffect( event );
setDropEffect( event, dropEffect );
if( dropEffect === "none" ) {
return;
}
const dropIndex = this.getPlaceholderIndex();
// if for whatever reason the placeholder is not present in the DOM but it should be there
// we don't allow/emit the drop event since it breaks the contract
// seems to only happen if drag and drop is executed faster than the DOM updates
if( dropIndex === -1 ) {
return;
}
this.dndDrop.emit( {
event: event,
dropEffect: dropEffect,
isExternal: isExternalDrag(),
data: data.data,
index: dropIndex,
type: type,
} );
event.stopPropagation();
}
finally {
this.cleanupDragoverState();
}
}
onDragLeave( event:DndEvent ) {
// check if still inside this dropzone and not yet handled by another dropzone
if( typeof event._dndDropzoneActive === "undefined" ) {
const newTarget = document.elementFromPoint( event.clientX, event.clientY );
if( this.elementRef.nativeElement.contains( newTarget ) ) {
event._dndDropzoneActive = true;
return;
}
}
this.cleanupDragoverState();
// cleanup drop effect when leaving dropzone
setDropEffect( event, "none" );
}
private isDropAllowed( type?:string ):boolean {
// dropzone is disabled -> deny it
if( this.disabled === true ) {
return false;
}
// if drag did not start from our directive
// and external drag sources are not allowed -> deny it
if( isExternalDrag() === true
&& this.dndAllowExternal === false ) {
return false;
}
// no filtering by types -> allow it
if( !this.dndDropzone ) {
return true;
}
// no type set -> allow it
if( !type ) {
return true;
}
if( Array.isArray( this.dndDropzone ) === false ) {
throw new Error( "dndDropzone: bound value to [dndDropzone] must be an array!" );
}
// if dropzone contains type -> allow it
return this.dndDropzone.indexOf( type ) !== -1;
}
private tryGetPlaceholder():Element | null {
if( typeof this.dndPlaceholderRef !== "undefined" ) {
return this.dndPlaceholderRef.elementRef.nativeElement as Element;
}
// TODO nasty workaround needed because if ng-container / template is used @ContentChild() or DI will fail because
// of wrong context see angular bug https://github.com/angular/angular/issues/13517
return this.elementRef.nativeElement.querySelector( "[dndPlaceholderRef]" );
}
private removePlaceholderFromDOM() {
if( this.placeholder !== null
&& this.placeholder.parentNode !== null ) {
this.placeholder.parentNode.removeChild( this.placeholder );
}
}
private checkAndUpdatePlaceholderPosition( event:DragEvent ):void {
if( this.placeholder === null ) {
return;
}
// make sure the placeholder is in the DOM
if( this.placeholder.parentNode !== this.elementRef.nativeElement ) {
this.renderer.appendChild( this.elementRef.nativeElement, this.placeholder );
}
// update the position if the event originates from a child element of the dropzone
const directChild = getDirectChildElement( this.elementRef.nativeElement, event.target as Element );
// early exit if no direct child or direct child is placeholder
if( directChild === null
|| directChild === this.placeholder ) {
return;
}
const positionPlaceholderBeforeDirectChild = shouldPositionPlaceholderBeforeElement( event, directChild, this.dndHorizontal );
if( positionPlaceholderBeforeDirectChild ) {
// do insert before only if necessary
if( directChild.previousSibling !== this.placeholder ) {
this.renderer.insertBefore( this.elementRef.nativeElement, this.placeholder, directChild );
}
}
else {
// do insert after only if necessary
if( directChild.nextSibling !== this.placeholder ) {
this.renderer.insertBefore( this.elementRef.nativeElement, this.placeholder, directChild.nextSibling );
}
}
}
private getPlaceholderIndex():number | undefined {
if( this.placeholder === null ) {
return undefined;
}
const element = this.elementRef.nativeElement as HTMLElement;
return Array.prototype.indexOf.call( element.children, this.placeholder );
}
private cleanupDragoverState() {
this.renderer.removeClass( this.elementRef.nativeElement, this.dndDragoverClass );
this.removePlaceholderFromDOM();
}
} | the_stack |
import { MapFn, min } from '@collectable/core';
import { COMMIT_MODE, CONST, OFFSET_ANCHOR, modulo, shiftDownRoundUp } from './common';
import { TreeWorker } from './traversal';
import { ExpansionParameters, Slot } from './slot';
import { View } from './view';
import { ListStructure, setView } from './list';
export class Collector<T> {
private static _default = new Collector<any>();
static default<T> (count: number, prepend: boolean) {
var c = Collector._default;
c.elements = new Array<T[]>(count);
c.index = prepend ? count : 0;
return c;
}
static one<T> (elements: T[]): Collector<T> {
var c = this._default;
c.elements = [elements];
return c;
}
elements: Array<T[]> = <any>void 0;
index = 0;
marker = 0;
private constructor () {}
set (elements: T[]): void {
this.elements[this.index] = elements;
this.index++;
}
mark () {
this.marker = this.index;
}
restore () {
this.index = this.marker;
}
populate (values: T[], innerIndex: number): void {
var elements = this.elements;
for(var i = 0, outerIndex = 0, inner = elements[0]; i < values.length;
i++, innerIndex >= inner.length - 1 ? (innerIndex = 0, inner = elements[++outerIndex]) : (++innerIndex)) {
inner[innerIndex] = values[i];
}
this.elements = <any>void 0;
}
populateMapped<U> (fn: MapFn<U, T>, values: U[], innerIndex: number): void {
var elements = this.elements;
for(var i = 0, outerIndex = 0, inner = elements[0]; i < values.length;
i++, innerIndex >= inner.length - 1 ? (innerIndex = 0, inner = elements[++outerIndex]) : (++innerIndex)) {
inner[innerIndex] = fn(values[i], i);
}
this.elements = <any>void 0;
}
}
/**
* Increases the capacity of the list by appending or prepending additional slots/nodes. An array of arrays is returned,
* one per added or updated leaf node, ready for population with values to be added to the list.
*
* @export
* @template T The type of elements present in the list
* @param {ListStructure<T>} list The list to be modified
* @param {number} increaseBy The additional capacity to add to the list
* @param {boolean} prepend true if the capacity should be added to the front of the list
* @returns {T[][]} An array of leaf node element arrays (one per leaf node, in left-to-right sequential order) to which
* values should be written to populate the additional list capacity. The first (if appending) or last array (if
* prepending) will be a reference to a pre-existing head or tail leaf node element array if that node was expanded
* with additional elements as part of the operation.
*/
export function increaseCapacity<T> (list: ListStructure<T>, increaseBy: number, prepend: boolean): Collector<T> {
var view = prepend ? list._left : list._right;
var slot = view.slot;
var group = list._group;
var numberOfAddedSlots = calculateSlotsToAdd(slot.slots.length, increaseBy);
list._size += numberOfAddedSlots;
if(!view.isEditable(group)) {
view = view.cloneToGroup(group);
setView(list, view);
}
// If the leaf node was already full, it does not need to be modified.
if(numberOfAddedSlots > 0) {
if(slot.isEditable(group)) {
slot.adjustRange(prepend ? numberOfAddedSlots : 0, prepend ? 0 : numberOfAddedSlots, true);
}
else {
view.slot = slot = slot.cloneWithAdjustedRange(slot.isReserved() ? -group : group, prepend ? numberOfAddedSlots : 0, prepend ? 0 : numberOfAddedSlots, true);
}
// The changes to the size of the leaf node need to be propagated to its parent the next time the tree is ascended.
if(!view.isRoot()) {
view.sizeDelta += numberOfAddedSlots;
view.slotsDelta += numberOfAddedSlots;
}
// If the leaf node had sufficient room for the additional requested capacity, then we're done.
if(numberOfAddedSlots === increaseBy) {
return Collector.one<T>(<T[]>slot.slots);
}
}
return increaseUpperCapacity(list, increaseBy, numberOfAddedSlots, prepend);
}
function increaseUpperCapacity<T> (list: ListStructure<T>, increaseBy: number, numberOfAddedSlots: number, prepend: boolean): Collector<T> {
var view = prepend ? list._left : list._right;
var slot = view.slot;
// An array will be used to collect the list element arrays of all the leaf nodes to be populated by the caller.
// var nextElementsIndex = 0;
var collector = Collector.default<T>((numberOfAddedSlots > 0 ? 1 : 0) + shiftDownRoundUp(increaseBy - numberOfAddedSlots, CONST.BRANCH_INDEX_BITCOUNT), prepend);
if(numberOfAddedSlots > 0) {
if(prepend) {
collector.index--;
collector.mark();
}
collector.set(<T[]>slot.slots);
if(prepend) {
collector.restore();
}
}
// The ascend function is capable of expanding the parent slot during ascension. An expansion argument is provided and
// updated with output values by the ascend function to allow the calling function to keep track of what was changed.
// var expand = ExpansionState.reset(state.size, increaseBy - numberOfAddedSlots, 0, prepend);
var expand = ExpansionParameters.get(0, 0, 0);
var shift = 0, level = 0;
var remainingSize = increaseBy - numberOfAddedSlots;
var worker = TreeWorker.defaultPrimary<T>().reset(list, view, list._group, COMMIT_MODE.NO_CHANGE);
// Starting with the head or tail, ascend to each node along the edge, expanding any nodes with additional slots until
// the requested capacity has been added. At each level, the additional slots are populated with a subtree of the
// appropriate size and depth, and the value arrays for added leaf nodes are saved to the `nodes` array for population
// of list element values by the calling function. If the root is reached and additional capacity is still required,
// additional nodes are added above the root, increasing the depth of the tree.
do {
shift += CONST.BRANCH_INDEX_BITCOUNT;
var isRoot = view.isRoot();
numberOfAddedSlots = calculateSlotsToAdd(isRoot ? 1 : view.parent.slotCount(), shiftDownRoundUp(remainingSize, shift));
expand.sizeDelta = min(remainingSize, numberOfAddedSlots << shift);
remainingSize -= expand.sizeDelta;
if(prepend) {
expand.padLeft = numberOfAddedSlots;
}
else {
expand.padRight = numberOfAddedSlots;
}
var ascendMode = worker.hasOtherView() && ((worker.other.slot.isReserved() && isRoot) || worker.committedOther)
? COMMIT_MODE.RESERVE : COMMIT_MODE.RELEASE_DISCARD;
view = worker.ascend(ascendMode, expand);
var wasFlipped = numberOfAddedSlots && (prepend && view.anchor === OFFSET_ANCHOR.LEFT) || (!prepend && view.anchor === OFFSET_ANCHOR.RIGHT);
if(wasFlipped) view.flipAnchor(list._size);
if(prepend) {
collector.index -= shiftDownRoundUp(expand.sizeDelta, CONST.BRANCH_INDEX_BITCOUNT);
collector.mark();
}
level++;
if(numberOfAddedSlots > 0) {
populateSubtrees(list, collector, view, level,
prepend ? -numberOfAddedSlots : view.slotCount() - numberOfAddedSlots,
expand.sizeDelta + remainingSize, remainingSize === 0);
if(prepend) {
collector.restore();
}
if(wasFlipped) view.flipAnchor(list._size);
}
} while(remainingSize > 0);
if(view.isRoot()) {
view.sizeDelta = 0;
view.slotsDelta = 0;
}
worker.dispose();
return collector;
}
/**
* Populates a set of expanded node slots with subtrees.
*
* @template T
* @param {View<T>[]} viewPath An array of views; one per level, starting with a leaf node and ending at the current subtree root
* @param {T[][]} nodes An array of leaf node element arrays to be updated as leaf nodes are added to each subtree
* @param {number} nodeIndex The next index that should be assigned to in the `nodes` array
* @param {number} level The level of the subtree root being populated
* @param {number} slotIndexBoundary A positive number indicates the first slot to be populated during an append
* operation. A negative number indicates the upper slot bound (exclusive) to use during a prepend operation.
* @param {number} remaining The total capacity represented by this set of subtrees
* @returns {number} An updated `nodeIndex` value to be used in subsequent subtree population operations
*/
function populateSubtrees<T> (list: ListStructure<T>, collector: Collector<T>, view: View<T>, topLevelIndex: number, slotIndexBoundary: number, capacity: number, isFinalStage: boolean): void {
var levelIndex = topLevelIndex - 1;
var remaining = capacity;
var shift = CONST.BRANCH_INDEX_BITCOUNT * topLevelIndex;
var slot = view.slot;
var slots = slot.slots;
var prepend = slotIndexBoundary < 0;
var slotCount = prepend ? -slotIndexBoundary : slot.slots.length;
var slotIndex = prepend ? 0 : slotIndexBoundary;
var slotIndices = new Array<number>(topLevelIndex);
var slotCounts = new Array<number>(topLevelIndex);
var slotPath = new Array<Slot<T>>(topLevelIndex);
var group = list._group;
var subcount = 0;
var isEdge: boolean;
slotIndices[levelIndex] = slotIndex;
slotCounts[levelIndex] = slotCount;
slotPath[levelIndex] = slot;
do {
// If the current subtree is fully populated, ascend to the next tree level to populate the next adjacent subtree.
// The last slot at each level should be reserved for writing when remaining capacity to add reaches zero.
if(slotIndex === slotCount) {
isEdge = isFinalStage && ((prepend && remaining === capacity - slot.size) || (remaining === 0 && (!prepend || levelIndex >= topLevelIndex)));
if(levelIndex === 0) {
slot.subcount += subcount;
}
levelIndex++;
if(levelIndex < topLevelIndex) {
slotIndex = ++slotIndices[levelIndex];
subcount = slotCount;
slotCount = slotCounts[levelIndex];
shift += CONST.BRANCH_INDEX_BITCOUNT;
slot = slotPath[levelIndex];
slot.subcount += subcount;
slots = slot.slots;
}
}
// Create new slots for each unpopulated slot index in the current node, and recursively descend and populate them
else {
// If we're currently at leaf parent level, just populate the leaf nodes, then ascend when done
if(levelIndex === 0) {
isEdge = isFinalStage && ((prepend && capacity === remaining) || (!prepend && remaining <= CONST.BRANCH_FACTOR));
var elementCount = isEdge ? (remaining & CONST.BRANCH_INDEX_MASK) || CONST.BRANCH_FACTOR : min(remaining, CONST.BRANCH_FACTOR);
var leafSlots = new Array<T>(elementCount);
collector.set(leafSlots);
var leafSlot = new Slot<T>(group, elementCount, 0, -1, 0, leafSlots);
slots[slotIndex] = leafSlot;
if(isEdge) {
if(prepend && elementCount < CONST.BRANCH_FACTOR && slots.length > 1) {
view.slot.recompute = view.slotCount();
}
view.slot.slots[slotIndex] = leafSlot.cloneAsPlaceholder(group);
view = View.create<T>(group, 0, prepend ? OFFSET_ANCHOR.LEFT : OFFSET_ANCHOR.RIGHT, slotIndex, 0, 0, view, leafSlot);
view.slot.group = -group;
setView(list, view);
}
remaining -= elementCount;
subcount += elementCount;
slotIndex++;
}
// Descend and populate the subtree of the current slot at this level
else {
isEdge = isFinalStage && ((prepend && capacity === remaining) || (!prepend && slotIndex === slots.length - 1 && remaining <= (1 << shift)));
shift -= CONST.BRANCH_INDEX_BITCOUNT;
subcount = 0;
levelIndex--;
var size = isEdge && modulo(remaining, shift) || min(remaining, CONST.BRANCH_FACTOR << shift);
if(prepend && isEdge && slots.length > 1 && size < CONST.BRANCH_FACTOR << shift) {
slot.recompute = slots.length;
}
slotCount = shiftDownRoundUp(size, shift);
slot = new Slot<T>(group, size, 0, -1, 0, new Array<T>(slotCount));
slotPath[levelIndex] = slot;
if(isEdge) {
view = View.create<T>(group, 0, prepend ? OFFSET_ANCHOR.LEFT : OFFSET_ANCHOR.RIGHT, slotIndex, 0, 0, view, slot);
slots[slotIndex] = slot.cloneAsPlaceholder(group);
slot.group = -group;
}
else {
slots[slotIndex] = slot;
}
slots = slot.slots;
slotCounts[levelIndex] = slotCount;
slotIndex = 0;
slotIndices[levelIndex] = slotIndex;
}
}
} while(levelIndex < topLevelIndex);
}
function calculateSlotsToAdd (initialSlotCount: number, totalAdditionalSlots: number): number {
return min(CONST.BRANCH_FACTOR - initialSlotCount, totalAdditionalSlots);
} | the_stack |
import lercWasm, { LercFactory } from "./lerc-wasm";
type PixelTypedArray =
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array;
type PixelTypedArrayCtor =
| Int8ArrayConstructor
| Uint8ArrayConstructor
| Uint8ClampedArrayConstructor
| Int16ArrayConstructor
| Uint16ArrayConstructor
| Int32ArrayConstructor
| Uint32ArrayConstructor
| Float32ArrayConstructor
| Float64ArrayConstructor;
interface BandStats {
minValue: number;
maxValue: number;
dimStats?: {
// Note the type change compared to the JS version which used typed array that fits the data's pixel type
minValues: Float64Array;
maxValues: Float64Array;
};
}
interface LercHeaderInfo {
version: number;
dimCount: number;
width: number;
height: number;
validPixelCount: number;
bandCount: number;
blobSize: number;
maskCount: number;
dataType: number;
minValue: number;
maxValue: number;
maxZerror: number;
statistics: BandStats[];
}
type LercPixelType =
| "S8"
| "U8"
| "S16"
| "U16"
| "S32"
| "U32"
| "F32"
| "F64";
interface LercData {
width: number;
height: number;
bandCount: number;
pixelType: LercPixelType;
dimCount: number;
statistics: BandStats[];
pixels: PixelTypedArray[];
mask: Uint8Array;
bandMasks?: Uint8Array[];
}
interface PixelTypeInfo {
pixelType: LercPixelType;
size: 1 | 2 | 4 | 8;
ctor: PixelTypedArrayCtor;
range: [number, number];
}
const pixelTypeInfoMap: PixelTypeInfo[] = [
{
pixelType: "S8",
size: 1,
ctor: Int8Array,
range: [-128, 128]
},
{
pixelType: "U8",
size: 1,
ctor: Uint8Array,
range: [0, 255]
},
{
pixelType: "S16",
size: 2,
ctor: Int16Array,
range: [-32768, 32767]
},
{
pixelType: "U16",
size: 2,
ctor: Uint16Array,
range: [0, 65536]
},
{
pixelType: "S32",
size: 4,
ctor: Int32Array,
range: [-2147483648, 2147483647]
},
{
pixelType: "U32",
size: 4,
ctor: Uint32Array,
range: [0, 4294967296]
},
{
pixelType: "F32",
size: 4,
ctor: Float32Array,
range: [-3.4027999387901484e38, 3.4027999387901484e38]
},
{
pixelType: "F64",
size: 8,
ctor: Float64Array,
range: [-1.7976931348623157e308, 1.7976931348623157e308]
}
];
let loadPromise: Promise<void> = null;
let loaded = false;
export function load(
options: {
locateFile?: (wasmFileName?: string, scriptDir?: string) => string;
} = {}
): Promise<void> {
if (loadPromise) {
return loadPromise;
}
const locateFile =
options.locateFile ||
((wasmFileName: string, scriptDir: string) =>
`${scriptDir}${wasmFileName}`);
loadPromise = lercWasm({ locateFile }).then((lercFactory) =>
lercFactory.ready.then(() => {
initLercLib(lercFactory);
loaded = true;
})
);
return loadPromise;
}
export function isLoaded(): boolean {
return loaded;
}
const lercLib: {
getBlobInfo: (_blob: Uint8Array) => LercHeaderInfo;
decode: (
_blob: Uint8Array,
_blobInfo: LercHeaderInfo
) => { data: Uint8Array; maskData: Uint8Array };
} = {
getBlobInfo: null,
decode: null
};
function normalizeByteLength(n: number): number {
// extra buffer on top of 8 byte boundary: https://stackoverflow.com/questions/56019003/why-malloc-in-webassembly-requires-4x-the-memory
return ((n >> 3) << 3) + 16;
}
function initLercLib(lercFactory: LercFactory): void {
const {
_malloc,
_free,
_lerc_getBlobInfo,
_lerc_getDataRanges,
_lerc_decode,
asm
} = lercFactory;
// do not use HeapU8 as memory dynamically grows from the initial 16MB
// test case: landsat_6band_8bit.24
let heapU8: Uint8Array;
const memory = Object.values(asm).find(
(val) => val && "buffer" in val && val.buffer === lercFactory.HEAPU8.buffer
);
const mallocMultiple = (byteLengths: number[]) => {
// malloc once to avoid pointer for detached memory when it grows to allocate next chunk
const lens = byteLengths.map((len) => normalizeByteLength(len));
const byteLength = lens.reduce((a, b) => a + b);
const ret = _malloc(byteLength);
heapU8 = new Uint8Array(memory.buffer);
let prev = lens[0];
lens[0] = ret;
// pointers for each allocated block
for (let i = 1; i < lens.length; i++) {
const next = lens[i];
lens[i] = lens[i - 1] + prev;
prev = next;
}
return lens;
};
lercLib.getBlobInfo = (blob: Uint8Array) => {
// copy data to wasm. info: 10 * Uint32, range: 3 * F64
const infoArr = new Uint8Array(10 * 4);
const rangeArr = new Uint8Array(3 * 8);
const [ptr, ptr_info, ptr_range] = mallocMultiple([
blob.length,
infoArr.length,
rangeArr.length
]);
heapU8.set(blob, ptr);
heapU8.set(infoArr, ptr_info);
heapU8.set(rangeArr, ptr_range);
// decode
let hr = _lerc_getBlobInfo(ptr, blob.length, ptr_info, ptr_range, 10, 3);
if (hr) {
_free(ptr);
throw `lerc-getBlobInfo: error code is ${hr}`;
}
heapU8 = new Uint8Array(memory.buffer);
infoArr.set(heapU8.slice(ptr_info, ptr_info + 10 * 4));
rangeArr.set(heapU8.slice(ptr_range, ptr_range + 3 * 8));
const lercInfoArr = new Uint32Array(infoArr.buffer);
const statsArr = new Float64Array(rangeArr.buffer);
const [
version,
dataType,
dimCount,
width,
height,
bandCount,
validPixelCount,
blobSize,
maskCount
] = lercInfoArr;
const headerInfo: LercHeaderInfo = {
version,
dimCount,
width,
height,
validPixelCount,
bandCount,
blobSize,
maskCount,
dataType,
minValue: statsArr[0],
maxValue: statsArr[1],
maxZerror: statsArr[2],
statistics: []
};
if (dimCount === 1 && bandCount === 1) {
_free(ptr);
headerInfo.statistics.push({
minValue: statsArr[0],
maxValue: statsArr[1]
});
return headerInfo;
}
// get data ranges for nband / ndim blob
// to reuse blob ptr we need to handle dynamic memory allocation
const numStatsBytes = dimCount * bandCount * 8;
const bandStatsMinArr = new Uint8Array(numStatsBytes);
const bandStatsMaxArr = new Uint8Array(numStatsBytes);
let ptr_blob = ptr,
ptr_min = 0,
ptr_max,
blob_freed = false;
if (heapU8.byteLength < ptr + numStatsBytes * 2) {
_free(ptr);
blob_freed = true;
[ptr_blob, ptr_min, ptr_max] = mallocMultiple([
blob.length,
numStatsBytes,
numStatsBytes
]);
heapU8.set(blob, ptr_blob);
} else {
[ptr_min, ptr_max] = mallocMultiple([numStatsBytes, numStatsBytes]);
}
heapU8.set(bandStatsMinArr, ptr_min);
heapU8.set(bandStatsMaxArr, ptr_max);
hr = _lerc_getDataRanges(
ptr_blob,
blob.length,
dimCount,
bandCount,
ptr_min,
ptr_max
);
if (hr) {
_free(ptr_blob);
if (!blob_freed) {
// we have two pointers in two wasm function calls
_free(ptr_min);
}
throw `lerc-getDataRanges: error code is ${hr}`;
}
heapU8 = new Uint8Array(memory.buffer);
bandStatsMinArr.set(heapU8.slice(ptr_min, ptr_min + numStatsBytes));
bandStatsMaxArr.set(heapU8.slice(ptr_max, ptr_max + numStatsBytes));
const allMinValues = new Float64Array(bandStatsMinArr.buffer);
const allMaxValues = new Float64Array(bandStatsMaxArr.buffer);
const statistics = headerInfo.statistics;
for (let i = 0; i < bandCount; i++) {
if (dimCount > 1) {
const minValues = allMinValues.slice(i * dimCount, (i + 1) * dimCount);
const maxValues = allMaxValues.slice(i * dimCount, (i + 1) * dimCount);
const minValue = Math.min.apply(null, minValues);
const maxValue = Math.max.apply(null, maxValues);
statistics.push({
minValue,
maxValue,
dimStats: { minValues, maxValues }
});
} else {
statistics.push({
minValue: allMinValues[i],
maxValue: allMaxValues[i]
});
}
}
_free(ptr_blob);
if (!blob_freed) {
// we have two pointers in two wasm function calls
_free(ptr_min);
}
return headerInfo;
};
lercLib.decode = (blob: Uint8Array, blobInfo: LercHeaderInfo) => {
const { maskCount, dimCount, bandCount, width, height, dataType } =
blobInfo;
// if the heap is increased dynamically between raw data, mask, and data, the malloc pointer is invalid as it will raise error when accessing mask:
// Cannot perform %TypedArray%.prototype.slice on a detached ArrayBuffer
const pixelTypeInfo = pixelTypeInfoMap[dataType];
const numPixels = width * height;
const maskData = new Uint8Array(numPixels * bandCount);
const numDataBytes = numPixels * dimCount * bandCount * pixelTypeInfo.size;
const data = new Uint8Array(numDataBytes);
const [ptr, ptr_mask, ptr_data] = mallocMultiple([
blob.length,
maskData.length,
data.length
]);
heapU8.set(blob, ptr);
heapU8.set(maskData, ptr_mask);
heapU8.set(data, ptr_data);
const hr = _lerc_decode(
ptr,
blob.length,
maskCount,
ptr_mask,
dimCount,
width,
height,
bandCount,
dataType,
ptr_data
);
if (hr) {
_free(ptr);
throw `lerc-decode: error code is ${hr}`;
}
heapU8 = new Uint8Array(memory.buffer);
data.set(heapU8.slice(ptr_data, ptr_data + numDataBytes));
maskData.set(heapU8.slice(ptr_mask, ptr_mask + numPixels));
_free(ptr);
return {
data,
maskData
};
};
}
function swapDimensionOrder(
pixels: PixelTypedArray,
numPixels: number,
numDims: number,
OutPixelTypeArray: PixelTypedArrayCtor,
inputIsBIP: boolean
): PixelTypedArray {
if (numDims < 2) {
return pixels;
}
const swap = new OutPixelTypeArray(numPixels * numDims);
if (inputIsBIP) {
for (let i = 0, j = 0; i < numPixels; i++) {
for (let iDim = 0, temp = i; iDim < numDims; iDim++, temp += numPixels) {
swap[temp] = pixels[j++];
}
}
} else {
for (let i = 0, j = 0; i < numPixels; i++) {
for (let iDim = 0, temp = i; iDim < numDims; iDim++, temp += numPixels) {
swap[j++] = pixels[temp];
}
}
}
return swap;
}
interface DecodeOptions {
inputOffset?: number;
returnPixelInterleavedDims?: boolean;
noDataValue?: number;
pixelType?: LercPixelType;
}
/**
* Decoding a LERC1/LERC2 byte stream and return an object containing the pixel data.
*
* @alias module:Lerc
* @param {ArrayBuffer} input The LERC input byte stream
* @param {object} [options] The decoding options below are optional.
* @param {number} [options.inputOffset] The number of bytes to skip in the input byte stream. A valid Lerc file is expected at that position.
* @param {string} [options.pixelType] (LERC1 only) Default value is F32. Valid pixel types for input are U8/S8/S16/U16/S32/U32/F32.
* @param {number} [options.noDataValue] (LERC1 only). It is recommended to use the returned mask instead of setting this value.
* @param {boolean} [options.returnPixelInterleavedDims] (nDim LERC2 only) If true, returned dimensions are pixel-interleaved, a.k.a [p1_dim0, p1_dim1, p1_dimn, p2_dim0...], default is [p1_dim0, p2_dim0, ..., p1_dim1, p2_dim1...]
* @returns {{width, height, pixels, pixelType, mask, statistics}}
* @property {number} width Width of decoded image.
* @property {number} height Height of decoded image.
* @property {array} pixels [band1, band2, …] Each band is a typed array of width*height.
* @property {string} pixelType The type of pixels represented in the output: U8/S8/S16/U16/S32/U32/F32.
* @property {mask} mask Typed array with a size of width*height, or null if all pixels are valid.
* @property {array} statistics [statistics_band1, statistics_band2, …] Each element is a statistics object representing min and max values
**/
export function decode(
input: ArrayBuffer,
options: DecodeOptions = {}
): LercData {
// get blob info
const inputOffset = options.inputOffset ?? 0;
const blob =
input instanceof Uint8Array
? input.subarray(inputOffset)
: new Uint8Array(input, inputOffset);
const blobInfo = lercLib.getBlobInfo(blob);
// decode
const { data, maskData } = lercLib.decode(blob, blobInfo);
const {
width,
height,
bandCount,
dimCount,
dataType,
maskCount,
statistics
} = blobInfo;
// get pixels, per-band masks, and statistics
const pixelTypeInfo = pixelTypeInfoMap[dataType];
const data1 = new pixelTypeInfo.ctor(data.buffer);
const pixels = [];
const masks = [];
const numPixels = width * height;
const numElementsPerBand = numPixels * dimCount;
for (let i = 0; i < bandCount; i++) {
const band = data1.subarray(
i * numElementsPerBand,
(i + 1) * numElementsPerBand
);
if (options.returnPixelInterleavedDims) {
pixels.push(band);
} else {
const bsq = swapDimensionOrder(
band,
numPixels,
dimCount,
pixelTypeInfo.ctor,
true
);
pixels.push(bsq);
}
masks.push(
maskData.subarray(i * numElementsPerBand, (i + 1) * numElementsPerBand)
);
}
// get unified mask
const mask =
maskCount === 0
? null
: maskCount === 1
? masks[0]
: new Uint8Array(numPixels);
if (maskCount > 1) {
mask.set(masks[0]);
for (let i = 1; i < masks.length; i++) {
const bandMask = masks[i];
for (let j = 0; j < numPixels; j++) {
mask[j] = mask[j] & bandMask[j];
}
}
}
// apply no data value
const { noDataValue } = options;
const applyNoDataValue =
noDataValue != null &&
pixelTypeInfo.range[0] <= noDataValue &&
pixelTypeInfo.range[1] >= noDataValue;
if (maskCount > 0 && applyNoDataValue) {
for (let i = 0; i < bandCount; i++) {
const band = pixels[i];
const bandMask = masks[i] || mask;
for (let j = 0; j < numPixels; j++) {
if (bandMask[j] === 0) {
band[j] = noDataValue;
}
}
}
}
// only keep band masks when there's per-band unique mask
const bandMasks = maskCount === bandCount && bandCount > 1 ? masks : null;
// lerc2.0 was never released
const pixelType =
options.pixelType && blobInfo.version === 0
? options.pixelType
: pixelTypeInfo.pixelType;
return {
width,
height,
bandCount,
pixelType,
dimCount,
statistics,
pixels,
mask,
bandMasks
};
}
/**
* Get the header information of a LERC1/LERC2 byte stream.
*
* @alias module:Lerc
* @param {ArrayBuffer} input The LERC input byte stream
* @param {object} [options] The decoding options below are optional.
* @param {number} [options.inputOffset] The number of bytes to skip in the input byte stream. A valid Lerc file is expected at that position.
* @returns {{version, width, height, bandCount, dimCount, validPixelCount, blobSize, dataType, mask, minValue, maxValue, maxZerror, statistics}}
* @property {number} version Compression algorithm version.
* @property {number} width Width of decoded image.
* @property {number} height Height of decoded image.
* @property {number} bandCount Number of bands.
* @property {number} dimCount Number of dimensions.
* @property {number} validPixelCount Number of valid pixels.
* @property {number} blobSize Lerc blob size in bytes.
* @property {number} dataType Data type represented in number.
* @property {number} minValue Minimum pixel value.
* @property {number} maxValue Maximum pixel value.
* @property {number} maxZerror Maximum Z error.
* @property {array} statistics [statistics_band1, statistics_band2, …] Each element is a statistics object representing min and max values
**/
export function getBlobInfo(
input: ArrayBuffer,
options: { inputOffset?: number } = {}
): LercHeaderInfo {
const blob = new Uint8Array(input, options.inputOffset ?? 0);
return lercLib.getBlobInfo(blob);
}
export function getBandCount(
input: ArrayBuffer | Uint8Array,
options: { inputOffset?: number } = {}
): number {
// this was available in the old JS version but not documented. Keep as is for backward compatiblity
const info = getBlobInfo(input, options);
return info.bandCount;
} | the_stack |
import { Color } from "../../parts";
import { Dialogue } from "../../types/dialogue";
import { Style } from "../../types/style";
import { RendererSettings } from "../settings";
import { AnimationCollection } from "./animation-collection";
import { fontSizeForLineHeight } from "./font-size";
import { WebRenderer } from "./renderer";
/**
* This class represents the style attribute of a span.
* As a Dialogue's div is rendered, individual parts are added to span's, and this class is used to maintain the style attribute of those.
*
* @param {!libjass.renderers.NullRenderer} renderer The renderer that this set of styles is associated with
* @param {!libjass.Dialogue} dialogue The Dialogue that this set of styles is associated with
* @param {number} scaleX The horizontal scaling of the subtitles
* @param {number} scaleY The vertical scaling of the subtitles
* @param {!libjass.renderers.RendererSettings} settings The renderer settings
* @param {!HTMLDivElement} fontSizeElement A <div> element to measure font sizes with
* @param {!SVGDefsElement} svgDefsElement An SVG <defs> element to append filter definitions to
* @param {!Map<string, [number, number]>} fontMetricsCache Font metrics cache
*/
export class SpanStyles {
private _id: string;
private _defaultStyle: Style;
private _italic: boolean;
private _bold: boolean | number;
private _underline: boolean;
private _strikeThrough: boolean;
private _outlineWidth: number;
private _outlineHeight: number;
private _shadowDepthX: number;
private _shadowDepthY: number;
private _fontName: string;
private _fontSize: number;
private _fontScaleX: number;
private _fontScaleY: number;
private _letterSpacing: number;
private _rotationX: number;
private _rotationY: number;
private _rotationZ: number;
private _skewX: number;
private _skewY: number;
private _primaryColor: Color;
private _secondaryColor: Color;
private _outlineColor: Color;
private _shadowColor: Color;
private _primaryAlpha: number;
private _secondaryAlpha: number;
private _outlineAlpha: number;
private _shadowAlpha: number;
private _blur: number;
private _gaussianBlur: number;
private _nextFilterId: number = 0;
constructor(renderer: WebRenderer, dialogue: Dialogue, private _scaleX: number, private _scaleY: number, private _settings: RendererSettings, private _fontSizeElement: HTMLDivElement, private _svgDefsElement: SVGDefsElement, private _fontMetricsCache: Map<string, [number, number]>) {
this._id = `${ renderer.id }-${ dialogue.id }`;
this._defaultStyle = dialogue.style;
this.reset(null);
}
/**
* Resets the styles to the defaults provided by the argument.
*
* @param {libjass.Style} newStyle The new defaults to reset the style to. If null, the styles are reset to the default style of the Dialogue.
*/
reset(newStyle: Style | undefined | null): void {
if (newStyle === undefined || newStyle === null) {
newStyle = this._defaultStyle;
}
this.italic = newStyle.italic;
this.bold = newStyle.bold;
this.underline = newStyle.underline;
this.strikeThrough = newStyle.strikeThrough;
this.outlineWidth = newStyle.outlineThickness;
this.outlineHeight = newStyle.outlineThickness;
this.shadowDepthX = newStyle.shadowDepth;
this.shadowDepthY = newStyle.shadowDepth;
this.fontName = newStyle.fontName;
this.fontSize = newStyle.fontSize;
this.fontScaleX = newStyle.fontScaleX;
this.fontScaleY = newStyle.fontScaleY;
this.letterSpacing = newStyle.letterSpacing;
this.rotationX = 0;
this.rotationY = 0;
this.rotationZ = newStyle.rotationZ;
this.skewX = 0;
this.skewY = 0;
this.primaryColor = newStyle.primaryColor;
this.secondaryColor = newStyle.secondaryColor;
this.outlineColor = newStyle.outlineColor;
this.shadowColor = newStyle.shadowColor;
this.primaryAlpha = newStyle.primaryColor.alpha;
this.secondaryAlpha = newStyle.secondaryColor.alpha;
this.outlineAlpha = newStyle.outlineColor.alpha;
this.shadowAlpha = newStyle.shadowColor.alpha;
this.blur = null as any as number;
this.gaussianBlur = null as any as number;
}
/**
* Sets the style attribute on the given span element.
*
* @param {!HTMLSpanElement} span
* @param {!AnimationCollection} animationCollection
* @return {!HTMLSpanElement} The resulting <span> with the CSS styles applied. This may be a wrapper around the input <span> if the styles were applied using SVG filters.
*/
setStylesOnSpan(span: HTMLSpanElement, animationCollection: AnimationCollection): HTMLSpanElement {
const isTextOnlySpan = span.childNodes[0] instanceof Text;
let fontStyleOrWeight = "";
if (this._italic) {
fontStyleOrWeight += "italic ";
}
if (this._bold === true) {
fontStyleOrWeight += "bold ";
}
else if (this._bold !== false) {
fontStyleOrWeight += this._bold.toFixed(0) + " ";
}
const lineHeight = this._scaleY * (isTextOnlySpan ? this._fontScaleX : 1) * this._fontSize;
const fontSize = fontSizeForLineHeight(this._fontName, lineHeight, this._settings.fallbackFonts, this._fontSizeElement, this._fontMetricsCache);
let fonts = this._fontName;
// Quote the font family unless it's a generic family, as those must never be quoted
switch (fonts) {
case "cursive":
case "fantasy":
case "monospace":
case "sans-serif":
case "serif":
break;
default:
fonts = `"${ fonts }"`;
break;
}
if (this._settings.fallbackFonts !== "") {
fonts += `, ${ this._settings.fallbackFonts }`;
}
span.style.font = `${ fontStyleOrWeight }${ fontSize.toFixed(3) }px/${ lineHeight.toFixed(3) }px ${ fonts }`;
let textDecoration = "";
if (this._underline) {
textDecoration = "underline";
}
if (this._strikeThrough) {
textDecoration += " line-through";
}
span.style.textDecoration = textDecoration.trim();
let transform = "";
if (isTextOnlySpan) {
if (this._fontScaleY !== this._fontScaleX) {
transform += `scaleY(${ (this._fontScaleY / this._fontScaleX).toFixed(3) }) `;
}
}
else {
if (this._fontScaleX !== 1) {
transform += `scaleX(${ this._fontScaleX }) `;
}
if (this._fontScaleY !== 1) {
transform += `scaleY(${ this._fontScaleY }) `;
}
}
if (this._skewX !== 0 || this._skewY !== 0) {
transform += `matrix(1, ${ this._skewY }, ${ this._skewX }, 1, 0, 0) `;
}
if (transform !== "") {
span.style.webkitTransform = transform;
span.style.webkitTransformOrigin = "50% 50%";
span.style.transform = transform;
span.style.transformOrigin = "50% 50%";
span.style.display = "inline-block";
}
span.style.letterSpacing = `${ (this._scaleX * this._letterSpacing).toFixed(3) }px`;
const outlineWidth = this._scaleX * this._outlineWidth;
const outlineHeight = this._scaleY * this._outlineHeight;
const shadowDepthX = this._scaleX * this._shadowDepthX;
const shadowDepthY = this._scaleY * this._shadowDepthY;
let primaryColor = this._primaryColor.withAlpha(this._primaryAlpha);
let outlineColor = this._outlineColor.withAlpha(this._outlineAlpha);
let shadowColor = this._shadowColor.withAlpha(this._shadowAlpha);
// If we're in non-SVG mode and all colors have the same alpha, then set all colors to alpha === 1 and set the common alpha as the span's opacity property instead
if (
!this._settings.enableSvg &&
((outlineWidth === 0 && outlineHeight === 0) || outlineColor.alpha === primaryColor.alpha) &&
((this._shadowDepthX === 0 && this._shadowDepthY === 0) || shadowColor.alpha === primaryColor.alpha)
) {
primaryColor = this._primaryColor.withAlpha(1);
outlineColor = this._outlineColor.withAlpha(1);
shadowColor = this._shadowColor.withAlpha(1);
span.style.opacity = this._primaryAlpha.toFixed(3);
}
span.style.color = primaryColor.toString();
if (this._settings.enableSvg) {
this._svg(
span,
outlineWidth, outlineHeight, outlineColor,
shadowDepthX, shadowDepthY, shadowColor,
);
}
else {
this._textShadow(
span,
outlineWidth, outlineHeight, outlineColor,
shadowDepthX, shadowDepthY, shadowColor,
);
}
if (this._rotationX !== 0 || this._rotationY !== 0) {
// Perspective needs to be set on a "transformable element"
span.style.display = "inline-block";
}
span.style.webkitAnimation = animationCollection.animationStyle;
span.style.animation = animationCollection.animationStyle;
return span;
}
/**
* @return {!HTMLBRElement}
*/
makeNewLine(): HTMLBRElement {
const result = document.createElement("br");
result.style.lineHeight = `${ (this._scaleY * this._fontSize).toFixed(3) }px`;
return result;
}
/**
* @param {!HTMLSpanElement} span
* @param {number} outlineWidth
* @param {number} outlineHeight
* @param {!libjass.parts.Color} outlineColor
* @param {number} shadowDepthX
* @param {number} shadowDepthY
* @param {!libjass.parts.Color} shadowColor
*/
private _svg(
span: HTMLSpanElement,
outlineWidth: number, outlineHeight: number, outlineColor: Color,
shadowDepthX: number, shadowDepthY: number, shadowColor: Color,
): void {
const filterElement = document.createElementNS("http://www.w3.org/2000/svg", "filter");
if (outlineWidth > 0 || outlineHeight > 0 || shadowDepthX > 0 || shadowDepthY > 0) {
// Start with SourceAlpha. Leave the alpha as 0 if it's 0, and set it to 1 if it's greater than 0
const source = document.createElementNS("http://www.w3.org/2000/svg", "feComponentTransfer");
filterElement.appendChild(source);
source.in1.baseVal = "SourceAlpha";
source.result.baseVal = "source";
const sourceAlphaTransferNode = document.createElementNS("http://www.w3.org/2000/svg", "feFuncA");
source.appendChild(sourceAlphaTransferNode);
sourceAlphaTransferNode.type.baseVal = SVGComponentTransferFunctionElement.SVG_FECOMPONENTTRANSFER_TYPE_LINEAR;
sourceAlphaTransferNode.intercept.baseVal = 0;
/* The alphas of all colored pixels of the SourceAlpha should be made as close to 1 as possible. This way the summed outlines below will be uniformly dark.
* Multiply the pixels by 1 / primaryAlpha so that the primaryAlpha pixels become 1. A higher value would make the outline larger and too sharp,
* leading to jagged outer edge and transparent space around the inner edge between itself and the SourceGraphic.
*/
sourceAlphaTransferNode.slope.baseVal = (this._primaryAlpha === 0) ? 1 : (1 / this._primaryAlpha);
/* Construct an elliptical border by merging together many rectangles. The border is creating using dilate morphology filters, but these only support
* generating rectangles. http://lists.w3.org/Archives/Public/public-fx/2012OctDec/0003.html
*/
// Merge the individual outlines
const mergedOutlines = document.createElementNS("http://www.w3.org/2000/svg", "feMerge");
filterElement.appendChild(mergedOutlines);
mergedOutlines.result.baseVal = "outline-alpha";
let outlineNumber = 0;
const increment = (!this._settings.preciseOutlines && this._gaussianBlur > 0) ? this._gaussianBlur : 1;
((addOutline: (x: number, y: number) => void) => {
if (outlineWidth <= outlineHeight) {
if (outlineWidth > 0) {
let x: number;
for (x = 0; x <= outlineWidth; x += increment) {
addOutline(x, outlineHeight / outlineWidth * Math.sqrt(outlineWidth * outlineWidth - x * x));
}
if (x !== outlineWidth + increment) {
addOutline(outlineWidth, 0);
}
}
else {
addOutline(0, outlineHeight);
}
}
else {
if (outlineHeight > 0) {
let y: number;
for (y = 0; y <= outlineHeight; y += increment) {
addOutline(outlineWidth / outlineHeight * Math.sqrt(outlineHeight * outlineHeight - y * y), y);
}
if (y !== outlineHeight + increment) {
addOutline(0, outlineHeight);
}
}
else {
addOutline(outlineWidth, 0);
}
}
})((x: number, y: number): void => {
const outlineId = `outline${ outlineNumber }`;
const outlineFilter = document.createElementNS("http://www.w3.org/2000/svg", "feMorphology");
filterElement.insertBefore(outlineFilter, mergedOutlines);
outlineFilter.in1.baseVal = "source";
outlineFilter.operator.baseVal = SVGFEMorphologyElement.SVG_MORPHOLOGY_OPERATOR_DILATE;
outlineFilter.radiusX.baseVal = x;
outlineFilter.radiusY.baseVal = y;
outlineFilter.result.baseVal = outlineId;
const outlineReferenceNode = document.createElementNS("http://www.w3.org/2000/svg", "feMergeNode");
mergedOutlines.appendChild(outlineReferenceNode);
outlineReferenceNode.in1.baseVal = outlineId;
outlineNumber++;
});
((addOutline: (x: number, y: number) => void) => {
if ((outlineWidth % 1) > 0) {
addOutline(outlineWidth, 0);
addOutline(-outlineWidth, 0);
}
if ((outlineHeight % 1) > 0) {
addOutline(0, outlineHeight);
addOutline(0, -outlineHeight);
}
})((x: number, y: number): void => {
const outlineId = `outline${ outlineNumber }`;
const outlineFilter = document.createElementNS("http://www.w3.org/2000/svg", "feOffset");
filterElement.insertBefore(outlineFilter, mergedOutlines);
outlineFilter.in1.baseVal = "source";
outlineFilter.dx.baseVal = x;
outlineFilter.dy.baseVal = y;
outlineFilter.result.baseVal = outlineId;
const outlineReferenceNode = document.createElementNS("http://www.w3.org/2000/svg", "feMergeNode");
mergedOutlines.appendChild(outlineReferenceNode);
outlineReferenceNode.in1.baseVal = outlineId;
outlineNumber++;
});
// Color it with the outline color
const coloredOutline = createComponentTransferFilter(outlineColor);
filterElement.appendChild(coloredOutline);
coloredOutline.in1.baseVal = "outline-alpha";
// Blur the merged outline
if (this._gaussianBlur > 0) {
const gaussianBlurFilter = document.createElementNS("http://www.w3.org/2000/svg", "feGaussianBlur");
filterElement.appendChild(gaussianBlurFilter);
// Don't use setStdDeviation - cloneNode() clears it in Chrome
gaussianBlurFilter.stdDeviationX.baseVal = this._gaussianBlur;
gaussianBlurFilter.stdDeviationY.baseVal = this._gaussianBlur;
}
for (let i = 0; i < this._blur; i++) {
const blurFilter = document.createElementNS("http://www.w3.org/2000/svg", "feConvolveMatrix");
filterElement.appendChild(blurFilter);
blurFilter.setAttribute("kernelMatrix", "1 2 1 2 4 2 1 2 1");
blurFilter.edgeMode.baseVal = SVGFEConvolveMatrixElement.SVG_EDGEMODE_NONE;
}
// Cut out the source, so only the exterior remains
const cutoutNode = document.createElementNS("http://www.w3.org/2000/svg", "feComposite");
filterElement.appendChild(cutoutNode);
cutoutNode.in2.baseVal = "source";
cutoutNode.operator.baseVal = SVGFECompositeElement.SVG_FECOMPOSITE_OPERATOR_OUT;
cutoutNode.result.baseVal = "outline-colored";
if (shadowDepthX > 0 || shadowDepthY > 0) {
const shadowFilter = document.createElementNS("http://www.w3.org/2000/svg", "feOffset");
filterElement.appendChild(shadowFilter);
shadowFilter.in1.baseVal = "outline-alpha";
shadowFilter.dx.baseVal = shadowDepthX;
shadowFilter.dy.baseVal = shadowDepthY;
// Color it with the shadow color
const coloredShadow = createComponentTransferFilter(shadowColor);
filterElement.appendChild(coloredShadow);
let lastFilter: SVGFEComponentTransferElement | SVGFEGaussianBlurElement | SVGFEConvolveMatrixElement = coloredShadow;
// Blur the shadow
if (this._gaussianBlur > 0) {
const gaussianBlurFilter = document.createElementNS("http://www.w3.org/2000/svg", "feGaussianBlur");
filterElement.appendChild(gaussianBlurFilter);
// Don't use setStdDeviation - cloneNode() clears it in Chrome
gaussianBlurFilter.stdDeviationX.baseVal = this._gaussianBlur;
gaussianBlurFilter.stdDeviationY.baseVal = this._gaussianBlur;
lastFilter = gaussianBlurFilter;
}
for (let i = 0; i < this._blur; i++) {
const blurFilter = document.createElementNS("http://www.w3.org/2000/svg", "feConvolveMatrix");
filterElement.appendChild(blurFilter);
blurFilter.setAttribute("kernelMatrix", "1 2 1 2 4 2 1 2 1");
blurFilter.edgeMode.baseVal = SVGFEConvolveMatrixElement.SVG_EDGEMODE_NONE;
lastFilter = blurFilter;
}
lastFilter.result.baseVal = "shadow";
}
// Merge the main text, outline and shadow
const mergedResult = document.createElementNS("http://www.w3.org/2000/svg", "feMerge");
filterElement.appendChild(mergedResult);
if (shadowDepthX > 0 || shadowDepthY > 0) {
const shadowReferenceNode = document.createElementNS("http://www.w3.org/2000/svg", "feMergeNode");
mergedResult.appendChild(shadowReferenceNode);
shadowReferenceNode.in1.baseVal = "shadow";
}
const outlineReferenceNode = document.createElementNS("http://www.w3.org/2000/svg", "feMergeNode");
mergedResult.appendChild(outlineReferenceNode);
outlineReferenceNode.in1.baseVal = "outline-colored";
const sourceGraphicReferenceNode = document.createElementNS("http://www.w3.org/2000/svg", "feMergeNode");
mergedResult.appendChild(sourceGraphicReferenceNode);
sourceGraphicReferenceNode.in1.baseVal = "SourceGraphic";
}
else {
// Blur the source graphic directly
if (this._gaussianBlur > 0) {
const gaussianBlurFilter = document.createElementNS("http://www.w3.org/2000/svg", "feGaussianBlur");
filterElement.appendChild(gaussianBlurFilter);
// Don't use setStdDeviation - cloneNode() clears it in Chrome
gaussianBlurFilter.stdDeviationX.baseVal = this._gaussianBlur;
gaussianBlurFilter.stdDeviationY.baseVal = this._gaussianBlur;
}
for (let i = 0; i < this._blur; i++) {
const blurFilter = document.createElementNS("http://www.w3.org/2000/svg", "feConvolveMatrix");
filterElement.appendChild(blurFilter);
blurFilter.setAttribute("kernelMatrix", "1 2 1 2 4 2 1 2 1");
blurFilter.edgeMode.baseVal = SVGFEConvolveMatrixElement.SVG_EDGEMODE_NONE;
}
}
if (filterElement.childElementCount > 0) {
const filterId = `libjass-svg-filter-${ this._id }-${ this._nextFilterId++ }`;
this._svgDefsElement.appendChild(filterElement);
filterElement.id = filterId;
filterElement.x.baseVal.valueAsString = "-50%";
filterElement.width.baseVal.valueAsString = "200%";
filterElement.y.baseVal.valueAsString = "-50%";
filterElement.height.baseVal.valueAsString = "200%";
const filterProperty = `url("#${ filterId }")`;
span.style.webkitFilter = filterProperty;
span.style.filter = filterProperty;
}
}
/**
* @param {!HTMLSpanElement} span
* @param {number} outlineWidth
* @param {number} outlineHeight
* @param {!libjass.parts.Color} outlineColor
* @param {number} shadowDepthX
* @param {number} shadowDepthY
* @param {!libjass.parts.Color} shadowColor
*/
private _textShadow(
span: HTMLSpanElement,
outlineWidth: number, outlineHeight: number, outlineColor: Color,
shadowDepthX: number, shadowDepthY: number, shadowColor: Color,
): void {
if (outlineWidth > 0 || outlineHeight > 0) {
let outlineCssString = "";
let shadowCssString = "";
((addOutline: (x: number, y: number) => void) => {
for (let x = 0; x <= outlineWidth; x++) {
const maxY = (outlineWidth === 0) ? outlineHeight : outlineHeight * Math.sqrt(1 - ((x * x) / (outlineWidth * outlineWidth)));
for (let y = 0; y <= maxY; y++) {
addOutline(x, y);
if (x !== 0) {
addOutline(-x, y);
}
if (y !== 0) {
addOutline(x, -y);
}
if (x !== 0 && y !== 0) {
addOutline(-x, -y);
}
}
}
if ((outlineWidth % 1) > 0) {
addOutline(outlineWidth, 0);
addOutline(-outlineWidth, 0);
}
if ((outlineHeight % 1) > 0) {
addOutline(0, outlineHeight);
addOutline(0, -outlineHeight);
}
})((x: number, y: number): void => {
outlineCssString += `, ${ outlineColor.toString() } ${ x.toFixed(3) }px ${ y.toFixed(3) }px ${ this._gaussianBlur.toFixed(3) }px`;
if (this._shadowDepthX !== 0 || this._shadowDepthY !== 0) {
shadowCssString += `, ${ shadowColor.toString() } ${ (x + shadowDepthX).toFixed(3) }px ${ (y + shadowDepthY).toFixed(3) }px ${ this._gaussianBlur.toFixed(3) }px`;
}
});
span.style.textShadow = (outlineCssString + shadowCssString).substr(", ".length);
}
else if (this._shadowDepthX !== 0 || this._shadowDepthY !== 0) {
const shadowCssString = `${ shadowColor.toString() } ${ shadowDepthX.toFixed(3) }px ${ shadowDepthY.toFixed(3) }px 0px`;
if (span.style.textShadow === "") {
span.style.textShadow = shadowCssString;
}
else {
span.style.textShadow += ", " + shadowCssString;
}
}
}
/**
* Sets the italic property. null defaults it to the default style's value.
*
* @type {?boolean}
*/
set italic(value: boolean) {
this._italic = valueOrDefault(value, this._defaultStyle.italic);
}
/**
* Sets the bold property. null defaults it to the default style's value.
*
* @type {(?boolean|?number)}
*/
set bold(value: boolean | number | null) {
this._bold = valueOrDefault(value, this._defaultStyle.bold);
}
/**
* Sets the underline property. null defaults it to the default style's value.
*
* @type {?boolean}
*/
set underline(value: boolean) {
this._underline = valueOrDefault(value, this._defaultStyle.underline);
}
/**
* Sets the strike-through property. null defaults it to the default style's value.
*
* @type {?boolean}
*/
set strikeThrough(value: boolean) {
this._strikeThrough = valueOrDefault(value, this._defaultStyle.strikeThrough);
}
/**
* Gets the outline width property.
*
* @type {number}
*/
get outlineWidth(): number {
return this._outlineWidth;
}
/**
* Sets the outline width property. null defaults it to the style's original outline width value.
*
* @type {?number}
*/
set outlineWidth(value: number) {
this._outlineWidth = valueOrDefault(value, this._defaultStyle.outlineThickness);
}
/**
* Gets the outline height property.
*
* @type {number}
*/
get outlineHeight(): number {
return this._outlineHeight;
}
/**
* Sets the outline height property. null defaults it to the style's original outline height value.
*
* @type {?number}
*/
set outlineHeight(value: number) {
this._outlineHeight = valueOrDefault(value, this._defaultStyle.outlineThickness);
}
/**
* Gets the shadow width property.
*
* @type {number}
*/
get shadowDepthX(): number {
return this._shadowDepthX;
}
/**
* Sets the shadow width property. null defaults it to the style's original shadow depth value.
*
* @type {?number}
*/
set shadowDepthX(value: number) {
this._shadowDepthX = valueOrDefault(value, this._defaultStyle.shadowDepth);
}
/**
* Gets the shadow height property.
*
* @type {number}
*/
get shadowDepthY(): number {
return this._shadowDepthY;
}
/**
* Sets the shadow height property. null defaults it to the style's original shadow depth value.
*
* @type {?number}
*/
set shadowDepthY(value: number) {
this._shadowDepthY = valueOrDefault(value, this._defaultStyle.shadowDepth);
}
/**
* Gets the blur property.
*
* @type {number}
*/
get blur(): number {
return this._blur;
}
/**
* Sets the blur property. null defaults it to 0.
*
* @type {?number}
*/
set blur(value: number) {
this._blur = valueOrDefault<number>(value, 0);
}
/**
* Gets the Gaussian blur property.
*
* @type {number}
*/
get gaussianBlur(): number {
return this._gaussianBlur;
}
/**
* Sets the Gaussian blur property. null defaults it to 0.
*
* @type {?number}
*/
set gaussianBlur(value: number) {
this._gaussianBlur = valueOrDefault<number>(value, 0);
}
/**
* Sets the font name property. null defaults it to the default style's value.
*
* @type {?string}
*/
set fontName(value: string | null) {
this._fontName = valueOrDefault(value, this._defaultStyle.fontName);
}
/**
* Gets the font size property.
*
* @type {number}
*/
get fontSize(): number {
return this._fontSize;
}
/**
* Sets the font size property. null defaults it to the default style's value.
*
* @type {?number}
*/
set fontSize(value: number) {
this._fontSize = valueOrDefault(value, this._defaultStyle.fontSize);
}
/**
* Gets the horizontal font scaling property.
*
* @type {number}
*/
get fontScaleX(): number {
return this._fontScaleX;
}
/**
* Sets the horizontal font scaling property. null defaults it to the default style's value.
*
* @type {?number}
*/
set fontScaleX(value: number) {
this._fontScaleX = valueOrDefault(value, this._defaultStyle.fontScaleX);
}
/**
* Gets the vertical font scaling property.
*
* @type {number}
*/
get fontScaleY(): number {
return this._fontScaleY;
}
/**
* Sets the vertical font scaling property. null defaults it to the default style's value.
*
* @type {?number}
*/
set fontScaleY(value: number) {
this._fontScaleY = valueOrDefault(value, this._defaultStyle.fontScaleY);
}
/**
* Gets the letter spacing property.
*
* @type {number}
*/
get letterSpacing(): number {
return this._letterSpacing;
}
/**
* Sets the letter spacing property. null defaults it to the default style's value.
*
* @type {?number}
*/
set letterSpacing(value: number) {
this._letterSpacing = valueOrDefault(value, this._defaultStyle.letterSpacing);
}
/**
* Gets the X-axis rotation property.
*
* @type {number}
*/
get rotationX(): number {
return this._rotationX;
}
/**
* Sets the X-axis rotation property.
*
* @type {?number}
*/
set rotationX(value: number) {
this._rotationX = valueOrDefault<number>(value, 0);
}
/**
* Gets the Y-axis rotation property.
*
* @type {number}
*/
get rotationY(): number {
return this._rotationY;
}
/**
* Sets the Y-axis rotation property.
*
* @type {?number}
*/
set rotationY(value: number) {
this._rotationY = valueOrDefault<number>(value, 0);
}
/**
* Gets the Z-axis rotation property.
*
* @type {number}
*/
get rotationZ(): number {
return this._rotationZ;
}
/**
* Sets the Z-axis rotation property.
*
* @type {?number}
*/
set rotationZ(value: number) {
this._rotationZ = valueOrDefault(value, this._defaultStyle.rotationZ);
}
/**
* Gets the X-axis skew property.
*
* @type {number}
*/
get skewX(): number {
return this._skewX;
}
/**
* Sets the X-axis skew property.
*
* @type {?number}
*/
set skewX(value: number) {
this._skewX = valueOrDefault<number>(value, 0);
}
/**
* Gets the Y-axis skew property.
*
* @type {number}
*/
get skewY(): number {
return this._skewY;
}
/**
* Sets the Y-axis skew property.
*
* @type {?number}
*/
set skewY(value: number) {
this._skewY = valueOrDefault<number>(value, 0);
}
/**
* Gets the primary color property.
*
* @type {!libjass.Color}
*/
get primaryColor(): Color {
return this._primaryColor;
}
/**
* Sets the primary color property. null defaults it to the default style's value.
*
* @type {libjass.Color}
*/
set primaryColor(value: Color) {
this._primaryColor = valueOrDefault(value, this._defaultStyle.primaryColor);
}
/**
* Gets the secondary color property.
*
* @type {!libjass.Color}
*/
get secondaryColor(): Color {
return this._secondaryColor;
}
/**
* Sets the secondary color property. null defaults it to the default style's value.
*
* @type {libjass.Color}
*/
set secondaryColor(value: Color) {
this._secondaryColor = valueOrDefault(value, this._defaultStyle.secondaryColor);
}
/**
* Gets the outline color property.
*
* @type {!libjass.Color}
*/
get outlineColor(): Color {
return this._outlineColor;
}
/**
* Sets the outline color property. null defaults it to the default style's value.
*
* @type {libjass.Color}
*/
set outlineColor(value: Color) {
this._outlineColor = valueOrDefault(value, this._defaultStyle.outlineColor);
}
/**
* Gets the shadow color property.
*
* @type {!libjass.Color}
*/
get shadowColor(): Color {
return this._shadowColor;
}
/**
* Sets the shadow color property. null defaults it to the default style's value.
*
* @type {libjass.Color}
*/
set shadowColor(value: Color) {
this._shadowColor = valueOrDefault(value, this._defaultStyle.shadowColor);
}
/**
* Gets the primary alpha property.
*
* @type {number}
*/
get primaryAlpha(): number {
return this._primaryAlpha;
}
/**
* Sets the primary alpha property.
*
* @type {?number}
*/
set primaryAlpha(value: number) {
this._primaryAlpha = valueOrDefault(value, this._defaultStyle.primaryColor.alpha);
}
/**
* Gets the secondary alpha property.
*
* @type {number}
*/
get secondaryAlpha(): number {
return this._secondaryAlpha;
}
/**
* Sets the secondary alpha property.
*
* @type {?number}
*/
set secondaryAlpha(value: number) {
this._secondaryAlpha = valueOrDefault(value, this._defaultStyle.secondaryColor.alpha);
}
/**
* Gets the outline alpha property.
*
* @type {number}
*/
get outlineAlpha(): number {
return this._outlineAlpha;
}
/**
* Sets the outline alpha property.
*
* @type {?number}
*/
set outlineAlpha(value: number) {
this._outlineAlpha = valueOrDefault(value, this._defaultStyle.outlineColor.alpha);
}
/**
* Gets the shadow alpha property.
*
* @type {number}
*/
get shadowAlpha(): number {
return this._shadowAlpha;
}
/**
* Sets the shadow alpha property.
*
* @type {?number}
*/
set shadowAlpha(value: number) {
this._shadowAlpha = valueOrDefault(value, this._defaultStyle.shadowColor.alpha);
}
}
/**
* @param {!libjass.parts.Color} color
* @return {!SVGFEComponentTransferElement}
*/
function createComponentTransferFilter(color: Color): SVGFEComponentTransferElement {
const result = document.createElementNS("http://www.w3.org/2000/svg", "feComponentTransfer");
const redTransferNode = document.createElementNS("http://www.w3.org/2000/svg", "feFuncR");
result.appendChild(redTransferNode);
redTransferNode.type.baseVal = SVGComponentTransferFunctionElement.SVG_FECOMPONENTTRANSFER_TYPE_LINEAR;
redTransferNode.slope.baseVal = 0;
redTransferNode.intercept.baseVal = color.red / 255;
const greenTransferNode = document.createElementNS("http://www.w3.org/2000/svg", "feFuncG");
result.appendChild(greenTransferNode);
greenTransferNode.type.baseVal = SVGComponentTransferFunctionElement.SVG_FECOMPONENTTRANSFER_TYPE_LINEAR;
greenTransferNode.slope.baseVal = 0;
greenTransferNode.intercept.baseVal = color.green / 255;
const blueTransferNode = document.createElementNS("http://www.w3.org/2000/svg", "feFuncB");
result.appendChild(blueTransferNode);
blueTransferNode.type.baseVal = SVGComponentTransferFunctionElement.SVG_FECOMPONENTTRANSFER_TYPE_LINEAR;
blueTransferNode.slope.baseVal = 0;
blueTransferNode.intercept.baseVal = color.blue / 255;
const alphaTransferNode = document.createElementNS("http://www.w3.org/2000/svg", "feFuncA");
result.appendChild(alphaTransferNode);
alphaTransferNode.type.baseVal = SVGComponentTransferFunctionElement.SVG_FECOMPONENTTRANSFER_TYPE_LINEAR;
alphaTransferNode.slope.baseVal = color.alpha;
alphaTransferNode.intercept.baseVal = 0;
return result;
}
/**
* @param {?T} newValue
* @param {!T} defaultValue
* @return {!T}
*/
function valueOrDefault<T>(newValue: T | null, defaultValue: T): T {
return ((newValue !== null) ? newValue : defaultValue);
} | the_stack |
import {
CdkConnectedOverlay,
ConnectedPosition,
Overlay,
RepositionScrollStrategy,
} from '@angular/cdk/overlay';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
HostBinding,
Input,
OnChanges,
OnDestroy,
Output,
TemplateRef,
ViewChild,
} from '@angular/core';
import {fromEvent, of, Subject, timer} from 'rxjs';
import {filter, map, switchMap, takeUntil, tap} from 'rxjs/operators';
import {MouseEventButtons} from '../../../util/dom';
import {
DataSeries,
DataSeriesMetadata,
DataSeriesMetadataMap,
Dimension,
Extent,
Point,
Rect,
Scale,
} from '../lib/public_types';
import {getScaleRangeFromDomDim} from './chart_view_utils';
import {
findClosestIndex,
getProposedViewExtentOnZoom,
} from './line_chart_interactive_utils';
export interface TooltipDatum<
Metadata extends DataSeriesMetadata = DataSeriesMetadata,
PointDatum extends Point = Point
> {
id: string;
metadata: Metadata;
closestPointIndex: number;
point: PointDatum;
}
enum InteractionState {
NONE,
DRAG_ZOOMING,
SCROLL_ZOOMING,
PANNING,
}
const SCROLL_ZOOM_SPEED_FACTOR = 0.01;
export function scrollStrategyFactory(
overlay: Overlay
): RepositionScrollStrategy {
return overlay.scrollStrategies.reposition();
}
export interface TooltipTemplateContext {
cursorLocationInDataCoord: {x: number; y: number};
data: TooltipDatum[];
}
export type TooltipTemplate = TemplateRef<TooltipTemplateContext>;
@Component({
selector: 'line-chart-interactive-view',
templateUrl: './line_chart_interactive_view.ng.html',
styleUrls: ['./line_chart_interactive_view.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
{
provide: RepositionScrollStrategy,
useFactory: scrollStrategyFactory,
deps: [Overlay],
},
],
})
export class LineChartInteractiveViewComponent
implements OnChanges, OnDestroy, AfterViewInit
{
@ViewChild('dots', {static: true, read: ElementRef})
dotsContainer!: ElementRef<SVGElement>;
@ViewChild(CdkConnectedOverlay)
overlay!: CdkConnectedOverlay;
@Input()
seriesData!: DataSeries[];
@Input()
seriesMetadataMap!: DataSeriesMetadataMap;
@Input()
viewExtent!: Extent;
@Input()
xScale!: Scale;
@Input()
yScale!: Scale;
@Input()
domDim!: Dimension;
@Input()
tooltipOriginEl!: ElementRef;
@Input()
tooltipTemplate?: TooltipTemplate;
@Output()
onViewExtentChange = new EventEmitter<{dataExtent: Extent}>();
@Output()
onViewExtentReset = new EventEmitter<void>();
readonly InteractionState = InteractionState;
state: InteractionState = InteractionState.NONE;
// Whether alt or shiftKey is pressed down.
specialKeyPressed: boolean = false;
// Gray box that shows when user drags with mouse down
zoomBoxInUiCoordinate: Rect = {x: 0, width: 0, height: 0, y: 0};
readonly tooltipPositions: ConnectedPosition[] = [
// Prefer align at bottom edge of the line chart
{
offsetY: 5,
originX: 'start',
overlayX: 'start',
originY: 'bottom',
overlayY: 'top',
},
// bottom, right aligned
{
offsetY: 5,
originX: 'end',
overlayX: 'end',
originY: 'bottom',
overlayY: 'top',
},
// Then top left
{
offsetY: -15,
originX: 'start',
overlayX: 'start',
originY: 'top',
overlayY: 'bottom',
},
// then top, right aligned
{
offsetY: -15,
originX: 'end',
overlayX: 'end',
originY: 'top',
overlayY: 'bottom',
},
// then right
{
offsetX: 5,
originX: 'end',
overlayX: 'start',
originY: 'top',
overlayY: 'top',
},
// then left
{
offsetX: -5,
originX: 'start',
overlayX: 'end',
originY: 'top',
overlayY: 'top',
},
];
cursorLocationInDataCoord: {x: number; y: number} | null = null;
cursoredData: TooltipDatum[] = [];
tooltipDisplayAttached: boolean = false;
@HostBinding('class.show-zoom-instruction')
showZoomInstruction: boolean = false;
private dragStartCoord: {x: number; y: number} | null = null;
private isCursorInside = false;
private readonly ngUnsubscribe = new Subject<void>();
constructor(
private readonly changeDetector: ChangeDetectorRef,
readonly scrollStrategy: RepositionScrollStrategy
) {}
ngAfterViewInit() {
// dblclick event cannot be prevented. Using css to disallow selecting instead.
fromEvent<MouseEvent>(this.dotsContainer.nativeElement, 'dblclick', {
passive: true,
})
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(() => {
this.onViewExtentReset.emit();
this.state = InteractionState.NONE;
this.changeDetector.markForCheck();
});
fromEvent<MouseEvent>(window, 'keydown', {
passive: true,
})
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((event) => {
const newState = this.shouldPan(event);
if (newState !== this.specialKeyPressed) {
this.specialKeyPressed = newState;
this.changeDetector.markForCheck();
}
});
fromEvent<MouseEvent>(window, 'keyup', {
passive: true,
})
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((event) => {
const newState = this.shouldPan(event);
if (newState !== this.specialKeyPressed) {
this.specialKeyPressed = newState;
this.changeDetector.markForCheck();
}
});
fromEvent<MouseEvent>(this.dotsContainer.nativeElement, 'mousedown', {
passive: true,
})
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((event) => {
const prevState = this.state;
const nextState = this.shouldPan(event)
? InteractionState.PANNING
: InteractionState.DRAG_ZOOMING;
// Override the dragStartCoord and zoomBox only when started to zoom.
// For instance, if you press left button then right, drag zoom should start at
// the left button down so the second mousedown is ignored.
if (
prevState === InteractionState.NONE &&
nextState === InteractionState.DRAG_ZOOMING
) {
this.dragStartCoord = {x: event.offsetX, y: event.offsetY};
this.zoomBoxInUiCoordinate = {
x: event.offsetX,
width: 0,
y: event.offsetY,
height: 0,
};
}
if (prevState !== nextState) {
this.state = nextState;
this.changeDetector.markForCheck();
}
});
fromEvent<MouseEvent>(this.dotsContainer.nativeElement, 'mouseup', {
passive: true,
})
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((event) => {
const leftClicked =
(event.buttons & MouseEventButtons.LEFT) === MouseEventButtons.LEFT;
this.dragStartCoord = null;
const zoomBox = this.zoomBoxInUiCoordinate;
if (
!leftClicked &&
this.state === InteractionState.DRAG_ZOOMING &&
zoomBox.width > 0 &&
zoomBox.height > 0
) {
const xMin = this.getDataX(zoomBox.x);
const xMax = this.getDataX(zoomBox.x + zoomBox.width);
const yMin = this.getDataY(zoomBox.y + zoomBox.height);
const yMax = this.getDataY(zoomBox.y);
this.onViewExtentChange.emit({
dataExtent: {
x: [xMin, xMax],
y: [yMin, yMax],
},
});
}
if (this.state !== InteractionState.NONE) {
this.state = InteractionState.NONE;
this.changeDetector.markForCheck();
}
});
fromEvent<MouseEvent>(this.dotsContainer.nativeElement, 'mouseenter', {
passive: true,
})
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((event) => {
this.isCursorInside = true;
this.updateTooltip(event);
this.changeDetector.markForCheck();
});
fromEvent<MouseEvent>(this.dotsContainer.nativeElement, 'mouseleave', {
passive: true,
})
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((event) => {
this.dragStartCoord = null;
this.isCursorInside = false;
this.updateTooltip(event);
this.state = InteractionState.NONE;
this.changeDetector.markForCheck();
});
fromEvent<MouseEvent>(this.dotsContainer.nativeElement, 'mousemove', {
passive: true,
})
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((event) => {
switch (this.state) {
case InteractionState.SCROLL_ZOOMING: {
this.state = InteractionState.NONE;
this.updateTooltip(event);
this.changeDetector.markForCheck();
break;
}
case InteractionState.NONE:
this.updateTooltip(event);
this.changeDetector.markForCheck();
break;
case InteractionState.PANNING: {
const deltaX = -event.movementX;
const deltaY = -event.movementY;
const {width: domWidth, height: domHeight} = this.domDim;
const xMin = this.getDataX(deltaX);
const xMax = this.getDataX(domWidth + deltaX);
const yMin = this.getDataY(domHeight + deltaY);
const yMax = this.getDataY(deltaY);
this.onViewExtentChange.emit({
dataExtent: {
x: [xMin, xMax],
y: [yMin, yMax],
},
});
break;
}
case InteractionState.DRAG_ZOOMING:
{
if (!this.dragStartCoord) {
break;
}
const xs = [this.dragStartCoord.x, event.offsetX];
const ys = [this.dragStartCoord.y, event.offsetY];
this.zoomBoxInUiCoordinate = {
x: Math.min(...xs),
width: Math.max(...xs) - Math.min(...xs),
y: Math.min(...ys),
height: Math.max(...ys) - Math.min(...ys),
};
}
this.changeDetector.markForCheck();
break;
}
});
fromEvent<WheelEvent>(this.dotsContainer.nativeElement, 'wheel', {
passive: false,
})
.pipe(
takeUntil(this.ngUnsubscribe),
switchMap((event: WheelEvent) => {
const shouldZoom = !event.ctrlKey && !event.shiftKey && event.altKey;
this.showZoomInstruction = !shouldZoom;
this.changeDetector.markForCheck();
if (shouldZoom) {
event.preventDefault();
return of(event);
}
return timer(3000).pipe(
tap(() => {
this.showZoomInstruction = false;
this.changeDetector.markForCheck();
}),
map(() => null)
);
}),
filter((eventOrNull) => Boolean(eventOrNull))
)
.subscribe((eventOrNull) => {
const event = eventOrNull!;
this.onViewExtentChange.emit({
dataExtent: getProposedViewExtentOnZoom(
event,
this.viewExtent,
this.domDim,
SCROLL_ZOOM_SPEED_FACTOR,
this.xScale,
this.yScale
),
});
if (this.state !== InteractionState.SCROLL_ZOOMING) {
this.state = InteractionState.SCROLL_ZOOMING;
this.changeDetector.markForCheck();
}
});
}
ngOnChanges() {
this.updateCursoredDataAndTooltipVisibility();
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
private shouldPan(event: MouseEvent | KeyboardEvent): boolean {
const specialKeyEngaged = event.shiftKey || event.altKey;
if (event instanceof KeyboardEvent) {
return specialKeyEngaged;
}
const leftClicked =
(event.buttons & MouseEventButtons.LEFT) === MouseEventButtons.LEFT;
const middleClicked =
(event.buttons & MouseEventButtons.MIDDLE) === MouseEventButtons.MIDDLE;
// Ignore right/forward/back clicks.
if (!leftClicked && !middleClicked) return false;
// At this point, either left or middle is clicked, but if both are clicked, left
// takes precedence.
return (middleClicked && !leftClicked) || specialKeyEngaged;
}
trackBySeriesName(index: number, datum: TooltipDatum) {
return datum.id;
}
getDomX(uiCoord: number): number {
return this.xScale.forward(
this.viewExtent.x,
getScaleRangeFromDomDim(this.domDim, 'x'),
uiCoord
);
}
private getDataX(uiCoord: number): number {
return this.xScale.reverse(
this.viewExtent.x,
getScaleRangeFromDomDim(this.domDim, 'x'),
uiCoord
);
}
getDomY(uiCoord: number): number {
return this.yScale.forward(
this.viewExtent.y,
getScaleRangeFromDomDim(this.domDim, 'y'),
uiCoord
);
}
private getDataY(uiCoord: number): number {
return this.yScale.reverse(
this.viewExtent.y,
getScaleRangeFromDomDim(this.domDim, 'y'),
uiCoord
);
}
shouldRenderTooltipPoint(point: Point | null): boolean {
return point !== null && !isNaN(point.x) && !isNaN(point.y);
}
private updateTooltip(event: MouseEvent) {
this.cursorLocationInDataCoord = {
x: this.getDataX(event.offsetX),
y: this.getDataY(event.offsetY),
};
this.updateCursoredDataAndTooltipVisibility();
}
onTooltipDisplayDetached() {
this.tooltipDisplayAttached = false;
}
private updateCursoredDataAndTooltipVisibility() {
const cursorLoc = this.cursorLocationInDataCoord;
if (cursorLoc === null) {
this.cursoredData = [];
this.tooltipDisplayAttached = false;
return;
}
this.cursoredData = this.isCursorInside
? (this.seriesData
.map((seriesDatum) => {
return {
seriesDatum: seriesDatum,
metadata: this.seriesMetadataMap[seriesDatum.id],
};
})
.filter(({metadata}) => {
return metadata && metadata.visible && !Boolean(metadata.aux);
})
.map(({seriesDatum, metadata}) => {
const index = findClosestIndex(seriesDatum.points, cursorLoc.x);
return {
id: seriesDatum.id,
closestPointIndex: index,
point: seriesDatum.points[index],
metadata,
};
})
.filter((tooltipDatumOrNull) => tooltipDatumOrNull) as TooltipDatum[])
: [];
this.tooltipDisplayAttached = Boolean(this.cursoredData.length);
}
} | the_stack |
import { LayoutViewer, PageLayoutViewer, DocumentHelper } from '../../src/index';
import { DocumentEditor } from '../../src/document-editor/document-editor';
import { createElement } from '@syncfusion/ej2-base';
import { TestHelper } from '../test-helper.spec';
import { Selection } from '../../src/index';
import { TextPosition } from '../../src/index';
import { Point } from '../../src/document-editor/implementation/editor/editor-helper';
import { Editor } from '../../src/index';
import { EditorHistory } from '../../src/document-editor/implementation/editor-history/editor-history';
import { TableWidget, TableRowWidget, TableCellWidget } from '../../src/index';
describe('Nested Table Row Resizing validation and After merge cell resize cell at middle validation', () => {
let editor: DocumentEditor = undefined;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', {
id: 'container',
styles: 'width:1000px;height:500px'
});
document.body.appendChild(ele);
editor = new DocumentEditor({ enableEditor: true, enableSelection: true, isReadOnly: false });
DocumentEditor.Inject(Editor, Selection, EditorHistory); editor.enableEditorHistory = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
});
afterAll((done): void => {
editor.destroy();
editor = undefined;
document.body.removeChild(document.getElementById('container'));
document.body.innerHTML = '';
setTimeout(function () {
done();
}, 1000);
});
it('Nested Table Row Resizing validation', () => {
console.log('Nested Table Row Resizing validation');
documentHelper = editor.documentHelper;
editor.editor.insertTable(2, 2);
editor.editor.insertTable(2, 2);
editor.editorModule.tableResize.currentResizingTable = documentHelper.pages[0].bodyWidgets[0].childWidgets[0] as TableWidget;
editor.editorModule.tableResize.resizeNode = 1;
documentHelper.isRowOrCellResizing = true;
editor.editorModule.tableResize.resizerPosition = 0;
editor.editorModule.tableResize.startingPoint = new Point(227.5, 114);
editor.editorModule.tableResize.resizeTableRow(2);
expect(editor.editorModule.tableResize.resizerPosition).toBe(0);
});
it('After merge cell resize cell at middle validation', () => {
console.log('After merge cell resize cell at middle validation');
documentHelper = editor.documentHelper;
editor.openBlank();
editor.editor.insertTable(2, 2);
editor.selection.handleShiftDownKey();
editor.editor.mergeCells();
editor.selection.handleUpKey();
editor.selection.handleShiftRightKey();
editor.editorModule.tableResize.currentResizingTable = documentHelper.pages[0].bodyWidgets[0].childWidgets[0] as TableWidget
editor.editorModule.tableResize.resizeNode = 0;
documentHelper.isRowOrCellResizing = true;
editor.editorModule.tableResize.resizerPosition = 1;
editor.editorModule.tableResize.startingPoint = new Point(408.5, 104);
documentHelper.currentPage = documentHelper.pages[0];
editor.editorModule.tableResize.resizeTableCellColumn(-1);
expect(editor.editorModule.tableResize.resizerPosition).toBe(1);
});
});
describe('After resize cell validation without selection', () => {
let editor: DocumentEditor = undefined;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', {
id: 'container',
styles: 'width:100%;height:100%'
});
document.body.appendChild(ele);
editor = new DocumentEditor({ enableEditor: true, enableSelection: true, isReadOnly: false });
DocumentEditor.Inject(Editor, Selection, EditorHistory); editor.enableEditorHistory = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
});
afterAll((done): void => {
editor.destroy();
editor = undefined;
document.body.removeChild(document.getElementById('container'));
document.body.innerHTML = '';
setTimeout(function () {
done();
}, 1000);
});
it('Resize without selection', () => {
console.log('Resize without selection');
documentHelper = editor.documentHelper;
editor.openBlank();
editor.editor.insertTable(2, 2);
editor.selection.handleShiftDownKey();
editor.editor.mergeCells();
editor.selection.handleUpKey();
editor.editorModule.tableResize.currentResizingTable = documentHelper.pages[0].bodyWidgets[0].childWidgets[0] as TableWidget
editor.editorModule.tableResize.resizeNode = 0;
documentHelper.isRowOrCellResizing = true;
editor.editorModule.tableResize.resizerPosition = 1;
editor.editorModule.tableResize.startingPoint = new Point(1075, 124);
editor.editorModule.tableResize.resizeTableCellColumn(500.5);
expect(((editor.selection.tableFormat.table.childWidgets[0] as TableRowWidget).childWidgets[0] as TableCellWidget).cellFormat.cellWidth).toBe(468);
});
it('Resize without selection and merge cell in first column', () => {
console.log('Resize without selection and merge cell in first column');
documentHelper = editor.documentHelper;
editor.openBlank();
editor.editor.insertTable(2, 2);
editor.selection.handleRightKey();
editor.selection.handleShiftDownKey();
editor.editor.mergeCells();
editor.selection.handleUpKey();
editor.editorModule.tableResize.currentResizingTable = documentHelper.pages[0].bodyWidgets[0].childWidgets[0] as TableWidget
editor.editorModule.tableResize.resizeNode = 0;
documentHelper.isRowOrCellResizing = true;
editor.editorModule.tableResize.resizerPosition = 1;
editor.editorModule.tableResize.startingPoint = new Point(407.5, 127);
documentHelper.currentPage = documentHelper.pages[0];
editor.editorModule.tableResize.resizeTableCellColumn(1);
expect(editor.editorModule.tableResize.resizerPosition).toBe(1);
});
});
describe('After resize cell validation with selection', () => {
let editor: DocumentEditor = undefined;
let documentHelper: DocumentHelper;
beforeAll((): void => {
let ele: HTMLElement = createElement('div', {
id: 'container',
styles: 'width:100%;height:100%'
});
document.body.appendChild(ele);
editor = new DocumentEditor({ enableEditor: true, enableSelection: true, isReadOnly: false });
DocumentEditor.Inject(Editor, Selection, EditorHistory); editor.enableEditorHistory = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
});
afterAll((done): void => {
editor.destroy();
editor = undefined;
document.body.removeChild(document.getElementById('container'));
document.body.innerHTML = '';
setTimeout(function () {
done();
}, 1000);
});
it('Resize with selection', () => {
console.log('Resize with selection');
documentHelper = editor.documentHelper;
editor.openBlank();
editor.editor.insertTable(2, 2);
editor.selection.handleShiftDownKey();
editor.editor.mergeCells();
editor.editorModule.tableResize.currentResizingTable = documentHelper.pages[0].bodyWidgets[0].childWidgets[0] as TableWidget
editor.editorModule.tableResize.resizeNode = 0;
documentHelper.isRowOrCellResizing = true;
editor.editorModule.tableResize.resizerPosition = 1;
editor.editorModule.tableResize.startingPoint = new Point(407, 122);
editor.editorModule.tableResize.resizeTableCellColumn(-80);
expect(editor.editorModule.tableResize.resizerPosition).toBe(1);
});
});
describe('Table Column resizing validation with selection', () => {
let editor: DocumentEditor = undefined;
beforeEach((): void => {
let ele: HTMLElement = createElement('div', {
id: 'container'
});
document.body.appendChild(ele);
editor = new DocumentEditor({ enableEditor: true, enableSelection: true, isReadOnly: false });
DocumentEditor.Inject(Editor, Selection, EditorHistory); editor.enableEditorHistory = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
});
afterEach((done): void => {
editor.destroy();
editor = undefined;
document.body.removeChild(document.getElementById('container'));
setTimeout(function () {
done();
}, 1000);
});
it('Resize Table Row', () => {
console.log('Resize Table Row');
editor.editor.insertTable(2, 2);
let event: any = { offsetX: 557, offsetY: 134, preventDefault: function () { }, ctrlKey: false, which: 1 };
editor.documentHelper.onMouseDownInternal(event);
editor.editorModule.tableResize.resizerPosition = 1;
editor.editorModule.tableResize.resizeNode = 1;
editor.editorModule.tableResize.startingPoint.x = 305.5;
editor.editorModule.tableResize.startingPoint.y = 114;
let point: Point = new Point(305.5, 115);
editor.editorModule.tableResize.handleResizing(point);
event = { offsetX: 557, offsetY: 135, preventDefault: function () { }, ctrlKey: false, which: 0 };
editor.documentHelper.onMouseMoveInternal(event);
event = { offsetX: 561, offsetY: 193, preventDefault: function () { }, ctrlKey: false, which: 0 };
editor.documentHelper.onMouseMoveInternal(event);
editor.documentHelper.onMouseUpInternal(event);
editor.editorHistory.undo();
editor.editorHistory.redo();
});
});
describe('Table Column resizing validation with selection', () => {
let editor: DocumentEditor = undefined;
let documentHelper: DocumentHelper = undefined;
beforeEach((): void => {
let ele: HTMLElement = createElement('div', {
id: 'container',
styles: 'width:1000px;height:500px'
});
document.body.appendChild(ele);
editor = new DocumentEditor({ enableEditor: true, enableSelection: true, isReadOnly: false });
DocumentEditor.Inject(Editor, Selection, EditorHistory); editor.enableEditorHistory = true;
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
documentHelper = editor.documentHelper;
});
afterEach((done): void => {
editor.destroy();
editor = undefined;
document.body.removeChild(document.getElementById('container'));
setTimeout(function () {
done();
}, 1000);
});
it('Resize Table column with left column selection ', () => {
console.log('Resize Table column with left column selection ');
editor.editor.insertTable(2, 2);
editor.selection.handleShiftDownKey();
let event: any = { offsetX: 631, offsetY: 142, preventDefault: function () { }, ctrlKey: false, which: 1 };
editor.documentHelper.onMouseDownInternal(event);
// event = { offsetX: 632, offsetY: 143, preventDefault: function () { }, ctrlKey: false, which: 0 };
// editor.documentHelper.onMouseMoveInternal(event);
// editor.documentHelper.onMouseUpInternal(event);
editor.editorModule.tableResize.resizerPosition = 1;
editor.editorModule.tableResize.resizeNode = 0;
editor.editorModule.tableResize.startingPoint.x = 408.5;
editor.editorModule.tableResize.startingPoint.y = 103;
documentHelper.isRowOrCellResizing = true;
let point: Point = new Point(409.5, 103);
editor.editorModule.tableResize.handleResizing(point);
event = { offsetX: 632, offsetY: 150, preventDefault: function () { }, ctrlKey: false, which: 0 };
editor.documentHelper.onMouseMoveInternal(event);
editor.documentHelper.onMouseUpInternal(event);
expect(((editor.selection.tableFormat.table.childWidgets[0] as TableRowWidget).childWidgets[0] as TableCellWidget).cellFormat.cellWidth).toBeGreaterThan(234);
});
it('Resize Table column with right column selection ', () => {
console.log('Resize Table column with right column selection ');
editor.editor.insertTable(2, 2);
editor.selection.handleRightKey();
editor.selection.handleShiftDownKey();
let event: any = { offsetX: 631, offsetY: 142, preventDefault: function () { }, ctrlKey: false, which: 1 };
editor.documentHelper.onMouseDownInternal(event);
editor.editorModule.tableResize.resizerPosition = 1;
editor.editorModule.tableResize.resizeNode = 0;
editor.editorModule.tableResize.startingPoint.x = 408.5;
editor.editorModule.tableResize.startingPoint.y = 103;
let point: Point = new Point(409.5, 103);
documentHelper.isRowOrCellResizing = true;
editor.editorModule.tableResize.resizeTableCellColumn(2);
event = { offsetX: 632, offsetY: 145, preventDefault: function () { }, ctrlKey: false, which: 0 };
editor.documentHelper.onMouseMoveInternal(event);
editor.documentHelper.onMouseUpInternal(event);
expect(((editor.selection.tableFormat.table.childWidgets[0] as TableRowWidget).childWidgets[0] as TableCellWidget).cellFormat.cellWidth).toBeGreaterThan(234);
});
}); | the_stack |
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { SimpleChanges } from '@angular/core';
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { AppConstants } from 'app.constants';
import { ImagePreloaderService } from 'pages/exploration-player-page/services/image-preloader.service';
import { AssetsBackendApiService } from 'services/assets-backend-api.service';
import { ContextService } from 'services/context.service';
import { HtmlEscaperService } from 'services/html-escaper.service';
import { ImageLocalStorageService } from 'services/image-local-storage.service';
import { SvgSanitizerService } from 'services/svg-sanitizer.service';
import { NoninteractiveMath } from './oppia-noninteractive-math.component';
describe('NoninteractiveMath', () => {
let assetsBackendApiService: AssetsBackendApiService;
let htmlEscaperService: HtmlEscaperService;
let component: NoninteractiveMath;
let svgSanitizerService: SvgSanitizerService;
let fixture: ComponentFixture<NoninteractiveMath>;
let imagePreloaderService: ImagePreloaderService;
let imageLocalStorageService: ImageLocalStorageService;
let contextService: ContextService;
let serverImageUrl = '/exploration/expId/assets/image/' +
'mathImg_20210721_224145_dyim6a131p_height_3d205_width' +
'_1d784_vertical_1d306.svg';
let explorationPlayerImageUrl =
'/assetsdevhandler/exploration/expId/assets/image/' +
'mathImg_20210721_224145_dyim6a131p_height_3d205_width' +
'_1d784_vertical_1d306.svg';
let rawImagedata =
'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC' +
'9zdmciIHdpZHRoPSIxLjc4NGV4IiBoZWlnaHQ9IjMuMjA1ZXgiIHZpZXdCb3g9IjAgLTgxNy' +
'4zIDc2OCAxMzc5LjciIGZvY3VzYWJsZT0iZmFsc2UiIHN0eWxlPSJ2ZXJ0aWNhbC1hbGlnbj' +
'ogLTEuMzA2ZXg7Ij48ZyBzdHJva2U9ImN1cnJlbnRDb2xvciIgZmlsbD0iY3VycmVudENvbG' +
'9yIiBzdHJva2Utd2lkdGg9IjAiIHRyYW5zZm9ybT0ibWF0cml4KDEgMCAwIC0xIDAgMCkiPj' +
'xnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEyMCwwKSI+PHJlY3Qgc3Ryb2tlPSJub25lIiB3aW' +
'R0aD0iNTI4IiBoZWlnaHQ9IjYwIiB4PSIwIiB5PSIyMjAiLz48ZyB0cmFuc2Zvcm09InRyYW' +
'5zbGF0ZSg1OSw0MjApIj48cGF0aCBzdHJva2Utd2lkdGg9IjEwIiB0cmFuc2Zvcm09InNjYW' +
'xlKDAuNzA3KSIgZD0iTTUyIDI4OVE1OSAzMzEgMTA2IDM4NlQyMjIgNDQyUTI1NyA0NDIgMj' +
'g2IDQyNFQzMjkgMzc5UTM3MSA0NDIgNDMwIDQ0MlE0NjcgNDQyIDQ5NCA0MjBUNTIyIDM2MV' +
'E1MjIgMzMyIDUwOCAzMTRUNDgxIDI5MlQ0NTggMjg4UTQzOSAyODggNDI3IDI5OVQ0MTUgMz' +
'I4UTQxNSAzNzQgNDY1IDM5MVE0NTQgNDA0IDQyNSA0MDRRNDEyIDQwNCA0MDYgNDAyUTM2OC' +
'AzODYgMzUwIDMzNlEyOTAgMTE1IDI5MCA3OFEyOTAgNTAgMzA2IDM4VDM0MSAyNlEzNzggMj' +
'YgNDE0IDU5VDQ2MyAxNDBRNDY2IDE1MCA0NjkgMTUxVDQ4NSAxNTNINDg5UTUwNCAxNTMgNT' +
'A0IDE0NVE1MDQgMTQ0IDUwMiAxMzRRNDg2IDc3IDQ0MCAzM1QzMzMgLTExUTI2MyAtMTEgMj' +
'I3IDUyUTE4NiAtMTAgMTMzIC0xMEgxMjdRNzggLTEwIDU3IDE2VDM1IDcxUTM1IDEwMyA1NC' +
'AxMjNUOTkgMTQzUTE0MiAxNDMgMTQyIDEwMVExNDIgODEgMTMwIDY2VDEwNyA0NlQ5NCA0MU' +
'w5MSA0MFE5MSAzOSA5NyAzNlQxMTMgMjlUMTMyIDI2UTE2OCAyNiAxOTQgNzFRMjAzIDg3ID' +
'IxNyAxMzlUMjQ1IDI0N1QyNjEgMzEzUTI2NiAzNDAgMjY2IDM1MlEyNjYgMzgwIDI1MSAzOT' +
'JUMjE3IDQwNFExNzcgNDA0IDE0MiAzNzJUOTMgMjkwUTkxIDI4MSA4OCAyODBUNzIgMjc4SD' +
'U4UTUyIDI4NCA1MiAyODlaIi8+PC9nPjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDg2LC0zND' +
'UpIj48cGF0aCBzdHJva2Utd2lkdGg9IjEwIiB0cmFuc2Zvcm09InNjYWxlKDAuNzA3KSIgZD' +
'0iTTIxIDI4N1EyMSAzMDEgMzYgMzM1VDg0IDQwNlQxNTggNDQyUTE5OSA0NDIgMjI0IDQxOV' +
'QyNTAgMzU1UTI0OCAzMzYgMjQ3IDMzNFEyNDcgMzMxIDIzMSAyODhUMTk4IDE5MVQxODIgMT' +
'A1UTE4MiA2MiAxOTYgNDVUMjM4IDI3UTI2MSAyNyAyODEgMzhUMzEyIDYxVDMzOSA5NFEzMz' +
'kgOTUgMzQ0IDExNFQzNTggMTczVDM3NyAyNDdRNDE1IDM5NyA0MTkgNDA0UTQzMiA0MzEgND' +
'YyIDQzMVE0NzUgNDMxIDQ4MyA0MjRUNDk0IDQxMlQ0OTYgNDAzUTQ5NiAzOTAgNDQ3IDE5M1' +
'QzOTEgLTIzUTM2MyAtMTA2IDI5NCAtMTU1VDE1NiAtMjA1UTExMSAtMjA1IDc3IC0xODNUND' +
'MgLTExN1E0MyAtOTUgNTAgLTgwVDY5IC01OFQ4OSAtNDhUMTA2IC00NVExNTAgLTQ1IDE1MC' +
'AtODdRMTUwIC0xMDcgMTM4IC0xMjJUMTE1IC0xNDJUMTAyIC0xNDdMOTkgLTE0OFExMDEgLT' +
'E1MyAxMTggLTE2MFQxNTIgLTE2N0gxNjBRMTc3IC0xNjcgMTg2IC0xNjVRMjE5IC0xNTYgMj' +
'Q3IC0xMjdUMjkwIC02NVQzMTMgLTlUMzIxIDIxTDMxNSAxN1EzMDkgMTMgMjk2IDZUMjcwIC' +
'02UTI1MCAtMTEgMjMxIC0xMVExODUgLTExIDE1MCAxMVQxMDQgODJRMTAzIDg5IDEwMyAxMT' +
'NRMTAzIDE3MCAxMzggMjYyVDE3MyAzNzlRMTczIDM4MCAxNzMgMzgxUTE3MyAzOTAgMTczID' +
'M5M1QxNjkgNDAwVDE1OCA0MDRIMTU0UTEzMSA0MDQgMTEyIDM4NVQ4MiAzNDRUNjUgMzAyVD' +
'U3IDI4MFE1NSAyNzggNDEgMjc4SDI3UTIxIDI4NCAyMSAyODdaIi8+PC9nPjwvZz48L2c+PC' +
'9zdmc+';
class mockHtmlEscaperService {
escapedJsonToObj(answer: string): string {
return answer;
}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [NoninteractiveMath],
providers: [
{
provide: HtmlEscaperService,
useClass: mockHtmlEscaperService
},
]
}).compileComponents();
}));
beforeEach(() => {
htmlEscaperService = TestBed.inject(HtmlEscaperService);
assetsBackendApiService = TestBed.inject(AssetsBackendApiService);
imageLocalStorageService = TestBed.inject(ImageLocalStorageService);
contextService = TestBed.inject(ContextService);
imagePreloaderService = TestBed.get(ImagePreloaderService);
svgSanitizerService = TestBed.inject(SvgSanitizerService);
fixture = TestBed.createComponent(NoninteractiveMath);
component = fixture.componentInstance;
component.mathContentWithValue = {
raw_latex: '\\frac{x}{y}',
svg_filename: 'mathImg_20210721_224145_dyim6a131p_height_3d205_width' +
'_1d784_vertical_1d306.svg'
} as unknown as string;
});
it('should initialise component when user inserts a math equation', () => {
spyOn(imagePreloaderService, 'inExplorationPlayer').and.returnValue(false);
spyOn(contextService, 'getEntityType').and.returnValue(
AppConstants.ENTITY_TYPE.EXPLORATION);
spyOn(contextService, 'getImageSaveDestination').and.returnValue(
AppConstants.IMAGE_SAVE_DESTINATION_SERVER);
spyOn(imageLocalStorageService, 'isInStorage').and.returnValue(false);
spyOn(assetsBackendApiService, 'getImageUrlForPreview').and
.returnValue(explorationPlayerImageUrl);
component.ngOnInit();
expect(component.imageContainerStyle.height).toBe('3.205ex');
expect(component.imageContainerStyle.width).toBe('1.784ex');
expect(component.imageContainerStyle['vertical-align']).toBe('-1.306ex');
expect(component.imageUrl).toBe(explorationPlayerImageUrl);
});
it('should retrieve image from local storage if present', () => {
spyOn(imagePreloaderService, 'inExplorationPlayer').and.returnValue(false);
spyOn(contextService, 'getEntityType').and.returnValue(
AppConstants.ENTITY_TYPE.EXPLORATION);
spyOn(contextService, 'getImageSaveDestination').and.returnValue(
AppConstants.IMAGE_SAVE_DESTINATION_LOCAL_STORAGE);
spyOn(imageLocalStorageService, 'isInStorage').and.returnValue(true);
spyOn(svgSanitizerService, 'getTrustedSvgResourceUrl').and
.callFake((data) => {
return data;
});
spyOn(imageLocalStorageService, 'getRawImageData').and
.returnValue(rawImagedata);
component.ngOnInit();
expect(component.imageContainerStyle.height).toBe('3.205ex');
expect(component.imageContainerStyle.width).toBe('1.784ex');
expect(component.imageContainerStyle['vertical-align']).toBe('-1.306ex');
expect(component.imageUrl).toBe(rawImagedata);
});
it('should display equation when user is viewing a concept card in the' +
' exploration player', fakeAsync(() => {
spyOn(imagePreloaderService, 'inExplorationPlayer').and.returnValue(true);
spyOn(contextService, 'getEntityType').and.returnValue(
AppConstants.ENTITY_TYPE.EXPLORATION);
spyOn(imagePreloaderService, 'getImageUrlAsync').and
.returnValue(Promise.resolve(serverImageUrl));
component.ngOnInit();
tick();
expect(component.imageContainerStyle.height).toBe('3.205ex');
expect(component.imageContainerStyle.width).toBe('1.784ex');
expect(component.imageContainerStyle['vertical-align']).toBe('-1.306ex');
expect(component.imageUrl).toBe(serverImageUrl);
}));
it('should throw error when retrieving from local storage fails', () => {
spyOn(imagePreloaderService, 'inExplorationPlayer').and.returnValue(false);
spyOn(contextService, 'getEntityType').and.returnValue(
AppConstants.ENTITY_TYPE.EXPLORATION);
spyOn(contextService, 'getEntityId').and.returnValue('expId');
spyOn(contextService, 'getImageSaveDestination').and.returnValue(
AppConstants.IMAGE_SAVE_DESTINATION_LOCAL_STORAGE);
spyOn(imageLocalStorageService, 'isInStorage').and.returnValue(true);
spyOn(imageLocalStorageService, 'getRawImageData').and
.returnValue(rawImagedata);
spyOn(svgSanitizerService, 'getTrustedSvgResourceUrl').and
.callFake((data) => {
throw new Error('Error');
});
expect(() => {
component.ngOnInit();
}).toThrowError(
'Error\n' +
'Entity type: exploration\n' +
'Entity ID: expId\n' +
'Filepath: mathImg_20210721_224145_dyim6a131p_height_3d205_width_1d784' +
'_vertical_1d306.svg'
);
});
it('should throw error when retrieving from server fails', () => {
spyOn(imagePreloaderService, 'inExplorationPlayer').and.returnValue(false);
spyOn(contextService, 'getEntityType').and.returnValue(
AppConstants.ENTITY_TYPE.EXPLORATION);
spyOn(contextService, 'getEntityId').and.returnValue('expId');
spyOn(contextService, 'getImageSaveDestination').and.returnValue(
AppConstants.IMAGE_SAVE_DESTINATION_SERVER);
spyOn(imageLocalStorageService, 'isInStorage').and.returnValue(false);
spyOn(assetsBackendApiService, 'getImageUrlForPreview').and
.callFake((data) => {
throw new Error('Error');
});
expect(() => {
component.ngOnInit();
}).toThrowError(
'Error\n' +
'Entity type: exploration\n' +
'Entity ID: expId\n' +
'Filepath: mathImg_20210721_224145_dyim6a131p_height_3d205_width_1d784' +
'_vertical_1d306.svg'
);
});
it('should not update image when \'mathContentWithValue\' is not defined ' +
'or empty', () => {
spyOn(htmlEscaperService, 'escapedJsonToObj');
spyOn(imagePreloaderService, 'getDimensionsOfMathSvg');
spyOn(imagePreloaderService, 'inExplorationPlayer');
component.mathContentWithValue = '';
component.ngOnInit();
expect(htmlEscaperService.escapedJsonToObj).not.toHaveBeenCalled();
expect(imagePreloaderService.getDimensionsOfMathSvg).not.toHaveBeenCalled();
expect(imagePreloaderService.inExplorationPlayer).not.toHaveBeenCalled();
});
it('should not update image when \'mathExpressionContent\' is empty', () => {
spyOn(htmlEscaperService, 'escapedJsonToObj').and.returnValue('');
spyOn(imagePreloaderService, 'getDimensionsOfMathSvg');
spyOn(imagePreloaderService, 'inExplorationPlayer');
component.ngOnInit();
expect(htmlEscaperService.escapedJsonToObj).toHaveBeenCalled();
expect(imagePreloaderService.getDimensionsOfMathSvg).not.toHaveBeenCalled();
expect(imagePreloaderService.inExplorationPlayer).not.toHaveBeenCalled();
});
it('should update image when usre makes changes to the equation', () => {
const changes: SimpleChanges = {
mathContentWithValue: {
currentValue: {
raw_latex: '\\frac{a}{b}',
svg_filename:
'mathImg_20210721_224145_dyim6a131p_height_3d205_width' +
'_1d784_vertical_1d306.svg'
} as unknown as string,
previousValue: {
raw_latex: '\\frac{x}{y}',
svg_filename:
'mathImg_20210721_224145_dyim6a131p_height_3d205_width' +
'_1d784_vertical_1d306.svg'
} as unknown as string,
firstChange: false,
isFirstChange: () => false
}
};
component.mathContentWithValue = {
raw_latex: '\\frac{a}{b}',
svg_filename: 'mathImg_20210721_224145_dyim6a131p_height_3d205_width' +
'_1d784_vertical_1d306.svg'
} as unknown as string;
spyOn(imagePreloaderService, 'inExplorationPlayer').and.returnValue(false);
spyOn(contextService, 'getEntityType').and.returnValue(
AppConstants.ENTITY_TYPE.EXPLORATION);
spyOn(contextService, 'getImageSaveDestination').and.returnValue(
AppConstants.IMAGE_SAVE_DESTINATION_SERVER);
spyOn(imageLocalStorageService, 'isInStorage').and.returnValue(false);
spyOn(assetsBackendApiService, 'getImageUrlForPreview').and
.returnValue(explorationPlayerImageUrl);
component.ngOnChanges(changes);
expect(component.imageContainerStyle.height).toBe('3.205ex');
expect(component.imageContainerStyle.width).toBe('1.784ex');
expect(component.imageContainerStyle['vertical-align']).toBe('-1.306ex');
expect(component.imageUrl).toBe(explorationPlayerImageUrl);
});
}); | the_stack |
import 'mocha';
import { expect } from 'chai';
import { DefaultWalletConfigs } from '../config/StaticConfig';
import { WalletCreateOptions, WalletCreator } from '../service/WalletCreator';
import { StorageService } from './StorageService';
import { Session } from '../models/Session';
import { SettingsDataUpdate, Wallet } from '../models/Wallet';
import { getRandomId } from '../crypto/RandomGen';
import { AssetMarketPrice, UserAsset } from '../models/UserAsset';
jest.setTimeout(20_000);
function buildTestWallet(name?: string) {
const testNetConfig = DefaultWalletConfigs.TestNetConfig;
const createOptions: WalletCreateOptions = {
walletType: 'normal',
config: testNetConfig,
walletName: name || 'My-TestNet-Wallet',
addressIndex: 0,
};
return new WalletCreator(createOptions).create().wallet;
}
function buildMainnetWallet(name?: string) {
const mainNetConfig = DefaultWalletConfigs.MainNetConfig;
const createOptions: WalletCreateOptions = {
walletType: 'normal',
config: mainNetConfig,
walletName: name || 'My-Mainnet-Wallet',
addressIndex: 0,
};
return new WalletCreator(createOptions).create().wallet;
}
describe('Testing Full Storage Service', () => {
it('Test creating and storing a new wallet', async () => {
const wallet = buildTestWallet();
const newWalletAddress = wallet.address;
const walletIdentifier = wallet.identifier;
const mockWalletStore = new StorageService(`test-wallet-storage-${getRandomId()}`);
// Persist wallet in the db
await mockWalletStore.saveWallet(wallet);
const loadedWallet = await mockWalletStore.findWalletByIdentifier(walletIdentifier);
expect(loadedWallet.name).to.eq('My-TestNet-Wallet');
expect(loadedWallet.address).to.eq(newWalletAddress);
expect(loadedWallet.config.network.chainId).to.eq('testnet-croeseid-2');
});
it('Test session storage ', async () => {
const wallet = buildTestWallet();
const walletIdentifier = wallet.identifier;
const session = new Session(wallet);
const mockWalletStore = new StorageService(`test-session-storage-${getRandomId()}`);
// Persist session in the db
await mockWalletStore.setSession(session);
const currentSession = await mockWalletStore.retrieveCurrentSession();
expect(currentSession.wallet.name).to.eq('My-TestNet-Wallet');
expect(currentSession.currency).to.eq('USD');
expect(currentSession.wallet.identifier).to.eq(walletIdentifier);
// eslint-disable-next-line no-underscore-dangle
expect(currentSession._id).to.eq(Session.SESSION_ID);
});
it('Test loading all persisted wallets', async () => {
const mockWalletStore = new StorageService(`test-load-all-${getRandomId()}`);
for (let i = 0; i < 10; i++) {
const wallet: Wallet = buildTestWallet();
mockWalletStore.saveWallet(wallet);
}
const fetchedWallets = await mockWalletStore.retrieveAllWallets();
expect(fetchedWallets.length).to.eq(10);
});
it('Test updating wallet fees settings', async () => {
const mockWalletStore = new StorageService(`test-update-wallet-fees-settings-${getRandomId()}`);
const wallet: Wallet = buildTestWallet();
const walletId = wallet.identifier;
await mockWalletStore.saveWallet(wallet);
const newFee = {
networkFee: '33000',
gasLimit: '400000',
};
const nodeData: SettingsDataUpdate = {
walletId,
gasLimit: newFee.gasLimit,
networkFee: newFee.networkFee,
};
await mockWalletStore.updateWalletSettings(nodeData);
const updatedWalletConfig = await mockWalletStore.findWalletByIdentifier(walletId);
expect(updatedWalletConfig.config.fee.networkFee).to.eq(newFee.networkFee);
expect(updatedWalletConfig.config.fee.gasLimit).to.eq(newFee.gasLimit);
const newFee2 = {
networkFee: '38000',
gasLimit: '480000',
};
const nodeData2: SettingsDataUpdate = {
walletId,
gasLimit: newFee2.gasLimit,
networkFee: newFee2.networkFee,
};
await mockWalletStore.updateWalletSettings(nodeData2);
const updatedWalletConfig2 = await mockWalletStore.findWalletByIdentifier(walletId);
expect(updatedWalletConfig2.config.fee.networkFee).to.eq(newFee2.networkFee);
expect(updatedWalletConfig2.config.fee.gasLimit).to.eq(newFee2.gasLimit);
});
it('Test updating wallet settings data', async () => {
const mockWalletStore = new StorageService(`test-update-wallet-settings-${getRandomId()}`);
const wallet: Wallet = buildTestWallet();
const walletId = wallet.identifier;
await mockWalletStore.saveWallet(wallet);
const newChainId = 'new-testnet-id-xv';
const nodeData: SettingsDataUpdate = { walletId, chainId: newChainId };
await mockWalletStore.updateWalletSettings(nodeData);
const updatedWalletConfig = await mockWalletStore.findWalletByIdentifier(walletId);
expect(updatedWalletConfig.config.network.chainId).to.eq(newChainId);
expect(updatedWalletConfig.config.indexingUrl).to.eq(
DefaultWalletConfigs.TestNetConfig.indexingUrl,
);
const newNodeUrl = 'https://testnet-new-croeseid.crypto-4.org';
const newIndexingUrl = 'https://crossfire.crypto.org/api/v1/';
const nodeData2: SettingsDataUpdate = {
walletId,
nodeUrl: newNodeUrl,
indexingUrl: newIndexingUrl,
};
await mockWalletStore.updateWalletSettings(nodeData2);
const updatedWalletConfig2 = await mockWalletStore.findWalletByIdentifier(walletId);
expect(updatedWalletConfig2.config.nodeUrl).to.eq(newNodeUrl);
expect(updatedWalletConfig2.config.network.defaultNodeUrl).to.eq(newNodeUrl);
expect(updatedWalletConfig2.config.indexingUrl).to.eq(newIndexingUrl);
const nodeData3: SettingsDataUpdate = {
walletId,
nodeUrl: 'https://another-new-node-url-test-1.com',
chainId: 'another-new-chainId-test',
};
await mockWalletStore.updateWalletSettings(nodeData3);
const updatedWalletConfig3 = await mockWalletStore.findWalletByIdentifier(walletId);
expect(updatedWalletConfig3.config.nodeUrl).to.eq(nodeData3.nodeUrl);
expect(updatedWalletConfig3.config.network.defaultNodeUrl).to.eq(nodeData3.nodeUrl);
expect(updatedWalletConfig3.config.network.chainId).to.eq(nodeData3.chainId);
});
it('Test wallet config : Enable and Disable default memo', async () => {
const mockWalletStore = new StorageService(`test-update-wallet-memo-settings-${getRandomId()}`);
const wallet: Wallet = buildTestWallet();
const walletId = wallet.identifier;
await mockWalletStore.saveWallet(wallet);
await mockWalletStore.updateDisabledDefaultMemo({
walletId,
disableDefaultMemoAppend: true,
});
const updatedWalletConfig = await mockWalletStore.findWalletByIdentifier(walletId);
expect(updatedWalletConfig.config.disableDefaultClientMemo).to.eq(true);
await mockWalletStore.updateDisabledDefaultMemo({
walletId,
disableDefaultMemoAppend: false,
});
const updatedWalletConfig2 = await mockWalletStore.findWalletByIdentifier(walletId);
expect(updatedWalletConfig2.config.disableDefaultClientMemo).to.eq(false);
});
it('Test assets storage', async () => {
const mockWalletStore = new StorageService(`test-assets-storage-${getRandomId()}`);
const WALLET_ID = '12dc3b3b90bc';
const asset: UserAsset = {
decimals: 8,
mainnetSymbol: '',
balance: '0',
description: 'The best asset',
icon_url: 'some url',
identifier: 'cbd4bab2cbfd2b3',
name: 'Best Asset',
symbol: 'BEST',
walletId: WALLET_ID,
stakedBalance: '0',
unbondingBalance: '0',
rewardsBalance: '0',
};
await mockWalletStore.saveAsset(asset);
const assets = await mockWalletStore.retrieveAssetsByWallet(WALLET_ID);
expect(assets[0].balance).to.eq('0');
expect(assets[0].identifier).to.eq('cbd4bab2cbfd2b3');
expect(assets[0].symbol).to.eq('BEST');
expect(assets.length).to.eq(1);
/// Testing updating assets
asset.balance = '250000'; // New balance
await mockWalletStore.saveAsset(asset);
const updatedAssets = await mockWalletStore.retrieveAssetsByWallet(WALLET_ID);
expect(updatedAssets[0].balance).to.eq('250000');
expect(updatedAssets[0].identifier).to.eq('cbd4bab2cbfd2b3');
expect(updatedAssets[0].symbol).to.eq('BEST');
expect(updatedAssets.length).to.eq(1);
});
it('Test asset market price storage', async () => {
const mockWalletStore = new StorageService(`test-market-storage-${getRandomId()}`);
const assetMarketPrice: AssetMarketPrice = {
assetSymbol: 'CRO',
currency: 'USD',
dailyChange: '-2.48',
price: '0.071',
};
await mockWalletStore.saveAssetMarketPrice(assetMarketPrice);
const fetchedAsset = await mockWalletStore.retrieveAssetPrice('CRO', 'USD');
expect(fetchedAsset.assetSymbol).to.eq('CRO');
expect(fetchedAsset.currency).to.eq('USD');
expect(fetchedAsset.price).to.eq('0.071');
expect(fetchedAsset.dailyChange).to.eq('-2.48');
fetchedAsset.price = '0.0981';
fetchedAsset.dailyChange = '+10.85';
await mockWalletStore.saveAssetMarketPrice(fetchedAsset);
const updatedAsset = await mockWalletStore.retrieveAssetPrice('CRO', 'USD');
expect(updatedAsset.assetSymbol).to.eq('CRO');
expect(updatedAsset.currency).to.eq('USD');
expect(updatedAsset.price).to.eq('0.0981');
expect(updatedAsset.dailyChange).to.eq('+10.85');
});
it('Testing transactions store', async () => {
// const mockWalletStore = new StorageService(`test-transactions-storage-${getRandomId()}`);
// const walletId = 'cbd4bab2cbfd2b3';
// const transactionData: TransferTransactionData = {
// amount: '250400',
// assetSymbol: 'TCRO',
// date: 'Tue Dec 15 2020 11:27:54 GMT+0300 (East Africa Time)',
// hash: 'AFEBA2DE9891AF22040359C8AACEF2836E8BF1276D66505DE36559F3E912EFF8',
// memo: 'Hello ZX',
// receiverAddress: 'tcro172vcpddyavr3mpjrwx4p44h4vlncyj7g0mh06e',
// senderAddress: 'tcrocncl1nrztwwgrgjg4gtctgul80menh7p04n4vzy5dk3',
// status: TransactionStatus.PENDING,
// };
//
// await walletService.saveTransfers({transactions: [], walletId: ""});
//
// const fetchedTxs = await mockWalletStore.retrieveAllTransferTransactions(walletId);
//
// expect(fetchedTxs.transactions[0].memo).to.eq('Hello ZX');
// expect(fetchedTxs.transactions[0].date).to.eq(
// 'Tue Dec 15 2020 11:27:54 GMT+0300 (East Africa Time)',
// );
// expect(fetchedTxs.transactions[0].senderAddress).to.eq(
// 'tcrocncl1nrztwwgrgjg4gtctgul80menh7p04n4vzy5dk3',
// );
// expect(fetchedTxs.transactions[0].receiverAddress).to.eq(
// 'tcro172vcpddyavr3mpjrwx4p44h4vlncyj7g0mh06e',
// );
});
it('Test wallet deletion', async () => {
const wallet = buildTestWallet();
const newWalletAddress = wallet.address;
const walletIdentifier = wallet.identifier;
const mockWalletStore = new StorageService(`test-wallet-deletion-${getRandomId()}`);
// Persist wallet in the db
await mockWalletStore.saveWallet(wallet);
const loadedWallet = await mockWalletStore.findWalletByIdentifier(walletIdentifier);
const allWallets = await mockWalletStore.retrieveAllWallets();
expect(allWallets.length).to.gt(0);
expect(allWallets.length).to.eq(1);
expect(loadedWallet).to.not.eq(null);
expect(loadedWallet.name).to.eq('My-TestNet-Wallet');
expect(loadedWallet.address).to.eq(newWalletAddress);
expect(loadedWallet.config.network.chainId).to.eq('testnet-croeseid-2');
await mockWalletStore.deleteWallet(walletIdentifier);
const loadedWalletAfterDeletion = await mockWalletStore.findWalletByIdentifier(
walletIdentifier,
);
const allWalletsAfterDeletion = await mockWalletStore.retrieveAllWallets();
expect(loadedWalletAfterDeletion).to.eq(null);
expect(allWalletsAfterDeletion.length).to.lt(1);
expect(allWalletsAfterDeletion.length).to.eq(0);
});
it('Test general settings enable/disable ', async () => {
const walletTestnet1 = buildTestWallet('My-TEST-WalletZZ');
const walletTestnet1ID = walletTestnet1.identifier;
const walletTestnet2 = buildTestWallet('TheBestTestnetWalletZ');
const walletTestnet3 = buildTestWallet('TheTestnetWalletZ');
const walletMainnet1 = buildMainnetWallet('MainNetWalletX');
const walletMainnet1ID = walletMainnet1.identifier;
const walletMainnet2 = buildMainnetWallet('MainNetWalletX22');
const mockWalletStore = new StorageService(
`test-general-settings-propagation-${getRandomId()}`,
);
await Promise.all([
await mockWalletStore.saveWallet(walletTestnet1),
await mockWalletStore.saveWallet(walletTestnet2),
await mockWalletStore.saveWallet(walletTestnet3),
await mockWalletStore.saveWallet(walletMainnet1),
await mockWalletStore.saveWallet(walletMainnet2),
]);
const allWalletsBefore = await mockWalletStore.retrieveAllWallets();
// eslint-disable-next-line no-restricted-syntax
for (const wallet of allWalletsBefore) {
expect(wallet.config.enableGeneralSettings).to.eq(false);
}
// GeneralSettingsPropagation updated for TESTNET wallets
await mockWalletStore.updateGeneralSettingsPropagation('TESTNET', true);
const dataSettings: SettingsDataUpdate = {
chainId: 'testnet-xxx-2',
gasLimit: '330000',
indexingUrl: 'https://crypto.org/explorer/croeseid/api/v1/',
networkFee: '12020',
nodeUrl: 'https://www.new-node-url-croeseid.crypto.org',
walletId: walletTestnet1ID,
};
await mockWalletStore.updateWalletSettings(dataSettings);
const allWallets = await mockWalletStore.retrieveAllWallets();
// eslint-disable-next-line no-restricted-syntax
for (const wallet of allWallets) {
if (wallet.config.name === 'TESTNET') {
expect(wallet.config.enableGeneralSettings).to.eq(true);
expect(wallet.config.network.chainId).to.eq('testnet-xxx-2');
expect(wallet.config.fee.gasLimit).to.eq('330000');
expect(wallet.config.fee.networkFee).to.eq('12020');
expect(wallet.config.nodeUrl).to.eq('https://www.new-node-url-croeseid.crypto.org');
expect(wallet.config.network.defaultNodeUrl).to.eq(
'https://www.new-node-url-croeseid.crypto.org',
);
} else {
expect(wallet.config.enableGeneralSettings).to.eq(false);
expect(wallet.config).to.eqls(DefaultWalletConfigs.MainNetConfig);
}
}
// GeneralSettingsPropagation now updated for MAINNET wallets
await mockWalletStore.updateGeneralSettingsPropagation('MAINNET', true);
const dataSettingsMainnet: SettingsDataUpdate = {
chainId: 'MainnetZZ-ChainID',
gasLimit: '3300022',
indexingUrl: 'https://crypto.org/explorer/mainnet/api/v1/',
networkFee: '12022',
nodeUrl: 'https://www.new-node-url-mainnet.crypto.org',
walletId: walletMainnet1ID,
};
await mockWalletStore.updateWalletSettings(dataSettingsMainnet);
const allWalletsAfterMainnetEnabledPropagation = await mockWalletStore.retrieveAllWallets();
// eslint-disable-next-line no-restricted-syntax
for (const wallet of allWalletsAfterMainnetEnabledPropagation) {
expect(wallet.config.enableGeneralSettings).to.eq(true);
if (wallet.config.name === 'MAINNET') {
expect(wallet.config.network.chainId).to.eq('MainnetZZ-ChainID');
expect(wallet.config.fee.gasLimit).to.eq('3300022');
expect(wallet.config.fee.networkFee).to.eq('12022');
expect(wallet.config.nodeUrl).to.eq('https://www.new-node-url-mainnet.crypto.org');
expect(wallet.config.network.defaultNodeUrl).to.eq(
'https://www.new-node-url-mainnet.crypto.org',
);
}
if (wallet.config.name === 'TESTNET') {
expect(wallet.config.enableGeneralSettings).to.eq(true);
expect(wallet.config.network.chainId).to.eq('testnet-xxx-2');
expect(wallet.config.fee.gasLimit).to.eq('330000');
expect(wallet.config.fee.networkFee).to.eq('12020');
expect(wallet.config.nodeUrl).to.eq('https://www.new-node-url-croeseid.crypto.org');
expect(wallet.config.network.defaultNodeUrl).to.eq(
'https://www.new-node-url-croeseid.crypto.org',
);
}
}
});
}); | the_stack |
import { AbstractClassType, asyncOperation, ClassType, empty } from '@deepkit/core';
import {
DatabaseAdapter,
DatabaseError,
DatabaseLogger,
DatabasePersistenceChangeSet,
DatabaseSession,
DatabaseTransaction,
DeleteResult,
OrmEntity,
PatchResult,
UniqueConstraintFailure
} from '@deepkit/orm';
import {
DefaultPlatform,
SqlBuilder,
SQLConnection,
SQLConnectionPool,
SQLDatabaseAdapter,
SQLDatabaseQuery,
SQLDatabaseQueryFactory,
SQLPersistence,
SQLQueryModel,
SQLQueryResolver,
SQLStatement
} from '@deepkit/sql';
import { Changes, getPartialSerializeFunction, getSerializeFunction, ReceiveType, ReflectionClass, resolvePath } from '@deepkit/type';
import sqlite3 from 'better-sqlite3';
import { SQLitePlatform } from './sqlite-platform';
import { FrameCategory, Stopwatch } from '@deepkit/stopwatch';
export class SQLiteStatement extends SQLStatement {
constructor(protected logger: DatabaseLogger, protected sql: string, protected stmt: sqlite3.Statement, protected stopwatch?: Stopwatch) {
super();
}
async get(params: any[] = []): Promise<any> {
const frame = this.stopwatch ? this.stopwatch.start('Query', FrameCategory.databaseQuery) : undefined;
try {
if (frame) frame.data({ sql: this.sql, sqlParams: params });
const res = this.stmt.get(...params);
this.logger.logQuery(this.sql, params);
return res;
} catch (error) {
this.logger.failedQuery(error, this.sql, params);
throw error;
} finally {
if (frame) frame.end();
}
}
async all(params: any[] = []): Promise<any[]> {
const frame = this.stopwatch ? this.stopwatch.start('Query', FrameCategory.databaseQuery) : undefined;
try {
if (frame) frame.data({ sql: this.sql, sqlParams: params });
const res = this.stmt.all(...params);
this.logger.logQuery(this.sql, params);
return res;
} catch (error) {
this.logger.failedQuery(error, this.sql, params);
throw error;
} finally {
if (frame) frame.end();
}
}
release() {
}
}
export class SQLiteDatabaseTransaction extends DatabaseTransaction {
connection?: SQLiteConnection;
async begin() {
if (!this.connection) return;
await this.connection.run('BEGIN');
}
async commit() {
if (!this.connection) return;
if (this.ended) throw new Error('Transaction ended already');
await this.connection.run('COMMIT');
this.ended = true;
this.connection.release();
}
async rollback() {
if (!this.connection) return;
if (this.ended) throw new Error('Transaction ended already');
await this.connection.run('ROLLBACK');
this.ended = true;
this.connection.release();
}
}
export class SQLiteConnection extends SQLConnection {
public platform = new SQLitePlatform();
protected changes: number = 0;
public db: sqlite3.Database;
static DatabaseConstructor: any = sqlite3;
constructor(
connectionPool: SQLConnectionPool,
protected dbPath: string,
logger?: DatabaseLogger,
transaction?: DatabaseTransaction,
stopwatch?: Stopwatch,
) {
super(connectionPool, logger, transaction, stopwatch);
this.db = new SQLiteConnection.DatabaseConstructor(this.dbPath);
this.db.exec('PRAGMA foreign_keys=ON');
}
async prepare(sql: string) {
return new SQLiteStatement(this.logger, sql, this.db.prepare(sql), this.stopwatch);
}
protected handleError(error: Error | string): void {
const message = 'string' === typeof error ? error : error.message;
if (message.includes('UNIQUE constraint failed')) {
//todo: extract table name, column name, and find ClassSchema
throw new UniqueConstraintFailure();
}
}
async run(sql: string, params: any[] = []) {
const frame = this.stopwatch ? this.stopwatch.start('Query', FrameCategory.databaseQuery) : undefined;
try {
if (frame) frame.data({ sql, sqlParams: params });
const stmt = this.db.prepare(sql);
this.logger.logQuery(sql, params);
const result = stmt.run(...params);
this.changes = result.changes;
} catch (error: any) {
this.handleError(error);
this.logger.failedQuery(error, sql, params);
throw error;
} finally {
if (frame) frame.end();
}
}
async exec(sql: string) {
const frame = this.stopwatch ? this.stopwatch.start('Query', FrameCategory.databaseQuery) : undefined;
try {
if (frame) frame.data({ sql });
this.db.exec(sql);
this.logger.logQuery(sql, []);
} catch (error: any) {
this.handleError(error);
this.logger.failedQuery(error, sql, []);
throw error;
} finally {
if (frame) frame.end();
}
}
async getChanges(): Promise<number> {
return this.changes;
}
}
export class SQLiteConnectionPool extends SQLConnectionPool {
public maxConnections: number = 10;
protected queue: ((connection: SQLiteConnection) => void)[] = [];
//we keep the first connection alive
protected firstConnection?: SQLiteConnection;
constructor(protected dbPath: string) {
super();
}
close() {
if (this.firstConnection) this.firstConnection.db.close();
}
protected createConnection(logger?: DatabaseLogger, transaction?: SQLiteDatabaseTransaction, stopwatch?: Stopwatch): SQLiteConnection {
return new SQLiteConnection(this, this.dbPath, logger, transaction, stopwatch);
}
async getConnection(logger?: DatabaseLogger, transaction?: SQLiteDatabaseTransaction, stopwatch?: Stopwatch): Promise<SQLiteConnection> {
//when a transaction object is given, it means we make the connection sticky exclusively to that transaction
//and only release the connection when the transaction is commit/rollback is executed.
if (transaction && transaction.connection) {
transaction.connection.stopwatch = stopwatch;
return transaction.connection;
}
const connection = this.firstConnection && this.firstConnection.released ? this.firstConnection :
this.activeConnections > this.maxConnections
//we wait for the next query to be released and reuse it
? await asyncOperation<SQLiteConnection>((resolve) => {
this.queue.push(resolve);
})
: this.createConnection(logger, transaction, stopwatch);
if (!this.firstConnection) this.firstConnection = connection;
connection.released = false;
connection.stopwatch = stopwatch;
//first connection is always reused, so we update the logger
if (logger) connection.logger = logger;
this.activeConnections++;
if (transaction) {
transaction.connection = connection;
connection.transaction = transaction;
try {
await transaction.begin();
} catch (error) {
transaction.ended = true;
connection.release();
throw new Error('Could not start transaction: ' + error);
}
}
return connection;
}
release(connection: SQLiteConnection) {
//connections attached to a transaction are not automatically released.
//only with commit/rollback actions
if (connection.transaction && !connection.transaction.ended) return;
super.release(connection);
const resolve = this.queue.shift();
if (resolve) {
resolve(connection);
} else if (this.firstConnection !== connection) {
connection.db.close();
}
}
}
export class SQLitePersistence extends SQLPersistence {
constructor(
protected platform: DefaultPlatform,
public connectionPool: SQLiteConnectionPool,
database: DatabaseSession<any>,
) {
super(platform, connectionPool, database);
}
protected getInsertSQL(classSchema: ReflectionClass<any>, fields: string[], values: string[]): string {
if (fields.length === 0) {
const pkName = this.platform.quoteIdentifier(classSchema.getPrimary().name);
fields.push(pkName);
values.fill('NULL');
}
return super.getInsertSQL(classSchema, fields, values);
}
async batchUpdate<T extends OrmEntity>(classSchema: ReflectionClass<T>, changeSets: DatabasePersistenceChangeSet<T>[]): Promise<void> {
const partialSerialize = getPartialSerializeFunction(classSchema.type, this.platform.serializer.serializeRegistry);
const tableName = this.platform.getTableIdentifier(classSchema);
const pkName = classSchema.getPrimary().name;
const pkField = this.platform.quoteIdentifier(pkName);
const values: { [name: string]: any[] } = {};
const setNames: string[] = [];
const aggregateSelects: { [name: string]: { id: any, sql: string }[] } = {};
const requiredFields: { [name: string]: 1 } = {};
const assignReturning: { [name: string]: { item: any, names: string[] } } = {};
const setReturning: { [name: string]: 1 } = {};
for (const changeSet of changeSets) {
const where: string[] = [];
const pk = partialSerialize(changeSet.primaryKey);
for (const i in pk) {
if (!pk.hasOwnProperty(i)) continue;
where.push(`${this.platform.quoteIdentifier(i)} = ${this.platform.quoteValue(pk[i])}`);
requiredFields[i] = 1;
}
if (!values[pkName]) values[pkName] = [];
values[pkName].push(this.platform.quoteValue(changeSet.primaryKey[pkName]));
const fieldAddedToValues: { [name: string]: 1 } = {};
const id = changeSet.primaryKey[pkName];
//todo: handle changes.$unset
if (changeSet.changes.$set) {
const value = partialSerialize(changeSet.changes.$set);
for (const i in value) {
if (!value.hasOwnProperty(i)) continue;
if (!values[i]) {
values[i] = [];
setNames.push(`${this.platform.quoteIdentifier(i)} = _b.${this.platform.quoteIdentifier(i)}`);
}
requiredFields[i] = 1;
fieldAddedToValues[i] = 1;
values[i].push(this.platform.quoteValue(value[i]));
}
}
if (changeSet.changes.$inc) {
for (const i in changeSet.changes.$inc) {
if (!changeSet.changes.$inc.hasOwnProperty(i)) continue;
const value = changeSet.changes.$inc[i];
if (!aggregateSelects[i]) aggregateSelects[i] = [];
if (!values[i]) {
values[i] = [];
setNames.push(`${this.platform.quoteIdentifier(i)} = _b.${this.platform.quoteIdentifier(i)}`);
}
if (!assignReturning[id]) {
assignReturning[id] = { item: changeSet.item, names: [] };
}
assignReturning[id].names.push(i);
setReturning[i] = 1;
aggregateSelects[i].push({
id: changeSet.primaryKey[pkName],
sql: `_origin.${this.platform.quoteIdentifier(i)} + ${this.platform.quoteValue(value)}`
});
requiredFields[i] = 1;
if (!fieldAddedToValues[i]) {
fieldAddedToValues[i] = 1;
values[i].push(this.platform.quoteValue(null));
}
}
}
}
const selects: string[] = [];
const valuesValues: string[] = [];
const valuesNames: string[] = [];
const _rename: string[] = [];
let j = 1;
for (const i in values) {
valuesNames.push(i);
_rename.push(`column${j++} as ${i}`);
}
for (let i = 0; i < values[pkName].length; i++) {
valuesValues.push('(' + valuesNames.map(name => values[name][i]).join(',') + ')');
}
for (const i in requiredFields) {
if (aggregateSelects[i]) {
const select: string[] = [];
select.push('CASE');
for (const item of aggregateSelects[i]) {
select.push(`WHEN _.${pkField} = ${item.id} THEN ${item.sql}`);
}
select.push(`ELSE _.${this.platform.quoteIdentifier(i)} END as ${this.platform.quoteIdentifier(i)}`);
selects.push(select.join(' '));
} else {
selects.push('_.' + i);
}
}
const sql = `
DROP TABLE IF EXISTS _b;
CREATE TEMPORARY TABLE _b AS
SELECT ${selects.join(', ')}
FROM (SELECT ${_rename.join(', ')} FROM (VALUES ${valuesValues.join(', ')})) as _
INNER JOIN ${tableName} as _origin ON (_origin.${pkField} = _.${pkField});
UPDATE
${tableName}
SET ${setNames.join(', ')}
FROM
_b
WHERE ${tableName}.${pkField} = _b.${pkField};
`;
const connection = await this.getConnection(); //will automatically be released in SQLPersistence
await connection.exec(sql);
if (!empty(setReturning)) {
const returnings = await connection.execAndReturnAll('SELECT * FROM _b');
for (const returning of returnings) {
const r = assignReturning[returning[pkName]];
for (const name of r.names) {
r.item[name] = returning[name];
}
}
}
}
protected async populateAutoIncrementFields<T>(classSchema: ReflectionClass<T>, items: T[]) {
const autoIncrement = classSchema.getAutoIncrement();
if (!autoIncrement) return;
//SQLite returns the _last_ auto-incremented value for a batch insert as last_insert_rowid().
//Since we know how many items were inserted, we can simply calculate for each item the auto-incremented value.
const connection = await this.getConnection(); //will automatically be released in SQLPersistence
const row = await connection.execAndReturnSingle(`SELECT last_insert_rowid() as rowid`);
const lastInserted = row.rowid;
let start = lastInserted - items.length + 1;
for (const item of items) {
item[autoIncrement.name] = start++;
}
}
}
export class SQLiteQueryResolver<T extends OrmEntity> extends SQLQueryResolver<T> {
constructor(
protected connectionPool: SQLiteConnectionPool,
protected platform: DefaultPlatform,
classSchema: ReflectionClass<T>,
session: DatabaseSession<DatabaseAdapter>) {
super(connectionPool, platform, classSchema, session);
}
async delete(model: SQLQueryModel<T>, deleteResult: DeleteResult<T>): Promise<void> {
// if (model.hasJoins()) throw new Error('Delete with joins not supported. Fetch first the ids then delete.');
const sqlBuilderFrame = this.session.stopwatch ? this.session.stopwatch.start('SQL Builder') : undefined;
const primaryKey = this.classSchema.getPrimary();
const pkName = primaryKey.name;
const pkField = this.platform.quoteIdentifier(primaryKey.name);
const sqlBuilder = new SqlBuilder(this.platform);
const tableName = this.platform.getTableIdentifier(this.classSchema);
const select = sqlBuilder.select(this.classSchema, model, { select: [pkField] });
const primaryKeyConverted = getSerializeFunction(primaryKey.property, this.platform.serializer.deserializeRegistry);
if (sqlBuilderFrame) sqlBuilderFrame.end();
const connectionFrame = this.session.stopwatch ? this.session.stopwatch.start('Connection acquisition') : undefined;
const connection = await this.connectionPool.getConnection(this.session.logger, this.session.assignedTransaction, this.session.stopwatch);
if (connectionFrame) connectionFrame.end();
try {
await connection.exec(`DROP TABLE IF EXISTS _tmp_d`);
await connection.run(`CREATE TEMPORARY TABLE _tmp_d as ${select.sql};`, select.params);
const sql = `DELETE FROM ${tableName} WHERE ${tableName}.${pkField} IN (SELECT * FROM _tmp_d)`;
await connection.run(sql);
const rows = await connection.execAndReturnAll('SELECT * FROM _tmp_d');
deleteResult.modified = await connection.getChanges();
for (const row of rows) {
deleteResult.primaryKeys.push(primaryKeyConverted(row[pkName]));
}
} finally {
connection.release();
}
}
async patch(model: SQLQueryModel<T>, changes: Changes<T>, patchResult: PatchResult<T>): Promise<void> {
const sqlBuilderFrame = this.session.stopwatch ? this.session.stopwatch.start('SQL Builder') : undefined;
const select: string[] = [];
const selectParams: any[] = [];
const tableName = this.platform.getTableIdentifier(this.classSchema);
const primaryKey = this.classSchema.getPrimary();
const primaryKeyConverted = getSerializeFunction(primaryKey.property, this.platform.serializer.deserializeRegistry);
const fieldsSet: { [name: string]: 1 } = {};
const aggregateFields: { [name: string]: { converted: (v: any) => any } } = {};
const partialSerialize = getPartialSerializeFunction(this.classSchema.type, this.platform.serializer.serializeRegistry);
const $set = changes.$set ? partialSerialize(changes.$set) : undefined;
if ($set) for (const i in $set) {
if (!$set.hasOwnProperty(i)) continue;
fieldsSet[i] = 1;
select.push(`? as ${this.platform.quoteIdentifier(i)}`);
selectParams.push($set[i]);
}
if (changes.$unset) for (const i in changes.$unset) {
if (!changes.$unset.hasOwnProperty(i)) continue;
fieldsSet[i] = 1;
select.push(`NULL as ${this.platform.quoteIdentifier(i)}`);
}
for (const i of model.returning) {
aggregateFields[i] = { converted: getSerializeFunction(resolvePath(i, this.classSchema.type), this.platform.serializer.deserializeRegistry) };
select.push(`(${this.platform.quoteIdentifier(i)} ) as ${this.platform.quoteIdentifier(i)}`);
}
if (changes.$inc) for (const i in changes.$inc) {
if (!changes.$inc.hasOwnProperty(i)) continue;
fieldsSet[i] = 1;
aggregateFields[i] = { converted: getSerializeFunction(resolvePath(i, this.classSchema.type), this.platform.serializer.serializeRegistry) };
select.push(`(${this.platform.quoteIdentifier(i)} + ${this.platform.quoteValue(changes.$inc[i])}) as ${this.platform.quoteIdentifier(i)}`);
}
const set: string[] = [];
for (const i in fieldsSet) {
set.push(`${this.platform.quoteIdentifier(i)} = _b.${this.platform.quoteIdentifier(i)}`);
}
let bPrimaryKey = primaryKey.name;
//we need a different name because primaryKeys could be updated as well
if (fieldsSet[primaryKey.name]) {
select.unshift(this.platform.quoteIdentifier(primaryKey.name) + ' as __' + primaryKey.name);
bPrimaryKey = '__' + primaryKey.name;
} else {
select.unshift(this.platform.quoteIdentifier(primaryKey.name));
}
const sqlBuilder = new SqlBuilder(this.platform, selectParams);
const selectSQL = sqlBuilder.select(this.classSchema, model, { select });
if (!set.length) {
throw new DatabaseError('SET is empty');
}
const sql = `
UPDATE
${tableName}
SET
${set.join(', ')}
FROM
_b
WHERE ${tableName}.${this.platform.quoteIdentifier(primaryKey.name)} = _b.${this.platform.quoteIdentifier(bPrimaryKey)};
`;
if (sqlBuilderFrame) sqlBuilderFrame.end();
const connection = await this.connectionPool.getConnection(this.session.logger, this.session.assignedTransaction, this.session.stopwatch);
try {
await connection.exec(`DROP TABLE IF EXISTS _b;`);
const createBSQL = `CREATE TEMPORARY TABLE _b AS ${selectSQL.sql};`;
await connection.run(createBSQL, selectSQL.params);
await connection.run(sql);
patchResult.modified = await connection.getChanges();
const returnings = await connection.execAndReturnAll('SELECT * FROM _b');
for (const i in aggregateFields) {
patchResult.returning[i] = [];
}
for (const returning of returnings) {
patchResult.primaryKeys.push(primaryKeyConverted(returning[primaryKey.name]));
for (const i in aggregateFields) {
patchResult.returning[i].push(aggregateFields[i].converted(returning[i]));
}
}
} finally {
connection.release();
}
}
}
export class SQLiteDatabaseQuery<T> extends SQLDatabaseQuery<T> {
}
export class SQLiteDatabaseQueryFactory extends SQLDatabaseQueryFactory {
constructor(protected connectionPool: SQLiteConnectionPool, platform: DefaultPlatform, databaseSession: DatabaseSession<any>) {
super(connectionPool, platform, databaseSession);
}
createQuery<T extends OrmEntity>(type?: ReceiveType<T> | ClassType<T> | AbstractClassType<T> | ReflectionClass<T>): SQLiteDatabaseQuery<T> {
return new SQLiteDatabaseQuery<T>(ReflectionClass.from(type), this.databaseSession,
new SQLiteQueryResolver<T>(this.connectionPool, this.platform, ReflectionClass.from(type), this.databaseSession)
);
}
}
export class SQLiteDatabaseAdapter extends SQLDatabaseAdapter {
public readonly connectionPool: SQLiteConnectionPool;
public readonly platform = new SQLitePlatform();
constructor(protected sqlitePath: string = ':memory:') {
super();
this.connectionPool = new SQLiteConnectionPool(this.sqlitePath);
}
async getInsertBatchSize(schema: ReflectionClass<any>): Promise<number> {
return Math.floor(32000 / schema.getProperties().length);
}
getName(): string {
return 'sqlite';
}
getSchemaName(): string {
return '';
}
createTransaction(session: DatabaseSession<this>): SQLiteDatabaseTransaction {
return new SQLiteDatabaseTransaction();
}
createPersistence(session: DatabaseSession<any>): SQLPersistence {
return new SQLitePersistence(this.platform, this.connectionPool, session);
}
queryFactory(databaseSession: DatabaseSession<any>): SQLiteDatabaseQueryFactory {
return new SQLiteDatabaseQueryFactory(this.connectionPool, this.platform, databaseSession);
}
disconnect(force?: boolean): void {
if (!force && this.connectionPool.getActiveConnections() > 0) {
throw new Error(`There are still active connections. Please release() any fetched connection first.`);
}
this.connectionPool.close();
}
} | the_stack |
import React from "react";
import BaseWidget, { WidgetProps, WidgetState } from "widgets/BaseWidget";
import { Alignment } from "@blueprintjs/core";
import { IconName } from "@blueprintjs/icons";
import { WidgetType, RenderModes, TextSize } from "constants/WidgetConstants";
import InputComponent, { InputComponentProps } from "../component";
import {
EventType,
ExecutionResult,
} from "constants/AppsmithActionConstants/ActionConstants";
import {
ValidationTypes,
ValidationResponse,
} from "constants/WidgetValidation";
import {
createMessage,
FIELD_REQUIRED_ERROR,
INPUT_DEFAULT_TEXT_MAX_CHAR_ERROR,
} from "constants/messages";
import { DerivedPropertiesMap } from "utils/WidgetFactory";
import { InputType, InputTypes } from "../constants";
import { GRID_DENSITY_MIGRATION_V1 } from "widgets/constants";
import { ISDCodeDropdownOptions } from "../component/ISDCodeDropdown";
import { CurrencyDropdownOptions } from "../component/CurrencyCodeDropdown";
import { AutocompleteDataType } from "utils/autocomplete/TernServer";
export function defaultValueValidation(
value: any,
props: InputWidgetProps,
_?: any,
): ValidationResponse {
const { inputType } = props;
if (
inputType === "INTEGER" ||
inputType === "NUMBER" ||
inputType === "CURRENCY" ||
inputType === "PHONE_NUMBER"
) {
const parsed = Number(value);
if (typeof value === "string") {
if (value.trim() === "") {
return {
isValid: true,
parsed: undefined,
messages: [""],
};
}
if (!Number.isFinite(parsed)) {
return {
isValid: false,
parsed: undefined,
messages: ["This value must be a number"],
};
}
}
return {
isValid: true,
parsed,
messages: [""],
};
}
if (_.isObject(value)) {
return {
isValid: false,
parsed: JSON.stringify(value, null, 2),
messages: ["This value must be string"],
};
}
let parsed = value;
const isValid = _.isString(parsed);
if (!isValid) {
try {
parsed = _.toString(parsed);
} catch (e) {
return {
isValid: false,
parsed: "",
messages: ["This value must be string"],
};
}
}
return {
isValid,
parsed: parsed,
messages: [""],
};
}
class InputWidget extends BaseWidget<InputWidgetProps, WidgetState> {
constructor(props: InputWidgetProps) {
super(props);
this.state = {
text: props.text,
};
}
static getPropertyPaneConfig() {
return [
{
sectionName: "General",
children: [
{
helpText: "Changes the type of data captured in the input",
propertyName: "inputType",
label: "Data Type",
controlType: "DROP_DOWN",
options: [
{
label: "Text",
value: "TEXT",
},
{
label: "Number",
value: "NUMBER",
},
{
label: "Password",
value: "PASSWORD",
},
{
label: "Email",
value: "EMAIL",
},
{
label: "Currency",
value: "CURRENCY",
},
{
label: "Phone Number",
value: "PHONE_NUMBER",
},
],
isBindProperty: false,
isTriggerProperty: false,
},
{
propertyName: "allowCurrencyChange",
label: "Allow currency change",
helpText: "Search by currency or country",
controlType: "SWITCH",
isJSConvertible: false,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
hidden: (props: InputWidgetProps) => {
return props.inputType !== InputTypes.CURRENCY;
},
dependencies: ["inputType"],
},
{
helpText: "Changes the country code",
propertyName: "phoneNumberCountryCode",
label: "Default Country Code",
enableSearch: true,
dropdownHeight: "195px",
controlType: "DROP_DOWN",
placeholderText: "Search by code or country name",
options: ISDCodeDropdownOptions,
hidden: (props: InputWidgetProps) => {
return props.inputType !== InputTypes.PHONE_NUMBER;
},
dependencies: ["inputType"],
isBindProperty: false,
isTriggerProperty: false,
},
{
helpText: "Changes the type of currency",
propertyName: "currencyCountryCode",
label: "Currency",
enableSearch: true,
dropdownHeight: "195px",
controlType: "DROP_DOWN",
placeholderText: "Search by code or name",
options: CurrencyDropdownOptions,
hidden: (props: InputWidgetProps) => {
return props.inputType !== InputTypes.CURRENCY;
},
dependencies: ["inputType"],
isBindProperty: false,
isTriggerProperty: false,
},
{
helpText: "No. of decimals in currency input",
propertyName: "decimalsInCurrency",
label: "Decimals",
controlType: "DROP_DOWN",
options: [
{
label: "1",
value: 1,
},
{
label: "2",
value: 2,
},
],
hidden: (props: InputWidgetProps) => {
return props.inputType !== InputTypes.CURRENCY;
},
dependencies: ["inputType"],
isBindProperty: false,
isTriggerProperty: false,
},
{
helpText: "Sets maximum allowed text length",
propertyName: "maxChars",
label: "Max Chars",
controlType: "INPUT_TEXT",
placeholderText: "255",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.NUMBER },
hidden: (props: InputWidgetProps) => {
return props.inputType !== InputTypes.TEXT;
},
dependencies: ["inputType"],
},
{
helpText:
"Sets the default text of the widget. The text is updated if the default text changes",
propertyName: "defaultText",
label: "Default Text",
controlType: "INPUT_TEXT",
placeholderText: "John Doe",
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.FUNCTION,
params: {
fn: defaultValueValidation,
expected: {
type: "string or number",
example: `John | 123`,
autocompleteDataType: AutocompleteDataType.STRING,
},
},
},
dependencies: ["inputType"],
},
{
helpText:
"Adds a validation to the input which displays an error on failure",
propertyName: "regex",
label: "Regex",
controlType: "INPUT_TEXT",
placeholderText: "^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$",
inputType: "TEXT",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.REGEX },
},
{
helpText: "Sets the input validity based on a JS expression",
propertyName: "validation",
label: "Valid",
controlType: "INPUT_TEXT",
placeholderText: "{{ Input1.text.length > 0 }}",
inputType: "TEXT",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
helpText:
"The error message to display if the regex or valid property check fails",
propertyName: "errorMessage",
label: "Error Message",
controlType: "INPUT_TEXT",
placeholderText: "Not a valid email!",
inputType: "TEXT",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
helpText: "Sets a placeholder text for the input",
propertyName: "placeholderText",
label: "Placeholder",
controlType: "INPUT_TEXT",
placeholderText: "Placeholder",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
helpText: "Sets the label text of the widget",
propertyName: "label",
label: "Label",
controlType: "INPUT_TEXT",
placeholderText: "Name:",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
helpText: "Show help text or details about current input",
propertyName: "tooltip",
label: "Tooltip",
controlType: "INPUT_TEXT",
placeholderText: "Passwords must be atleast 6 chars",
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
propertyName: "isRequired",
label: "Required",
helpText: "Makes input to the widget mandatory",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
helpText: "Controls the visibility of the widget",
propertyName: "isVisible",
label: "Visible",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
helpText: "Disables input to this widget",
propertyName: "isDisabled",
label: "Disabled",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
helpText: "Clears the input value after submit",
propertyName: "resetOnSubmit",
label: "Reset on submit",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
{
helpText: "Focus input automatically on load",
propertyName: "autoFocus",
label: "Auto Focus",
controlType: "SWITCH",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.BOOLEAN },
},
],
},
{
sectionName: "Actions",
children: [
{
helpText: "Triggers an action when the text is changed",
propertyName: "onTextChanged",
label: "onTextChanged",
controlType: "ACTION_SELECTOR",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: true,
},
{
helpText:
"Triggers an action on submit (when the enter key is pressed)",
propertyName: "onSubmit",
label: "onSubmit",
controlType: "ACTION_SELECTOR",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: true,
},
],
},
{
sectionName: "Label Styles",
children: [
{
propertyName: "labelTextColor",
label: "Text Color",
controlType: "COLOR_PICKER",
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: {
type: ValidationTypes.TEXT,
params: {
regex: /^(?![<|{{]).+/,
},
},
},
{
propertyName: "labelTextSize",
label: "Text Size",
controlType: "DROP_DOWN",
options: [
{
label: "Heading 1",
value: "HEADING1",
subText: "24px",
icon: "HEADING_ONE",
},
{
label: "Heading 2",
value: "HEADING2",
subText: "18px",
icon: "HEADING_TWO",
},
{
label: "Heading 3",
value: "HEADING3",
subText: "16px",
icon: "HEADING_THREE",
},
{
label: "Paragraph",
value: "PARAGRAPH",
subText: "14px",
icon: "PARAGRAPH",
},
{
label: "Paragraph 2",
value: "PARAGRAPH2",
subText: "12px",
icon: "PARAGRAPH_TWO",
},
],
isBindProperty: false,
isTriggerProperty: false,
},
{
propertyName: "labelStyle",
label: "Label Font Style",
controlType: "BUTTON_TABS",
options: [
{
icon: "BOLD_FONT",
value: "BOLD",
},
{
icon: "ITALICS_FONT",
value: "ITALIC",
},
],
isJSConvertible: true,
isBindProperty: true,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
],
},
{
sectionName: "Icon Options",
hidden: (props: InputWidgetProps) => {
const { inputType } = props;
return inputType === "CURRENCY" || inputType === "PHONE_NUMBER";
},
dependencies: ["inputType"],
children: [
{
propertyName: "iconName",
label: "Icon",
helpText: "Sets the icon to be used in input field",
controlType: "ICON_SELECT",
isBindProperty: false,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
},
{
propertyName: "iconAlign",
label: "Icon alignment",
helpText: "Sets the icon alignment of input field",
controlType: "ICON_ALIGN",
isBindProperty: false,
isTriggerProperty: false,
validation: { type: ValidationTypes.TEXT },
hidden: (props: InputWidgetProps) => !props.iconName,
dependencies: ["iconName"],
},
],
},
];
}
static getDerivedPropertiesMap(): DerivedPropertiesMap {
return {
isValid: `{{
function(){
if (!this.isRequired && !this.text) {
return true
}
if(this.isRequired && !this.text){
return false
}
if (typeof this.validation === "boolean" && !this.validation) {
return false;
}
let parsedRegex = null;
if (this.regex) {
/*
* break up the regexp pattern into 4 parts: given regex, regex prefix , regex pattern, regex flags
* Example /test/i will be split into ["/test/gi", "/", "test", "gi"]
*/
const regexParts = this.regex.match(/(\\/?)(.+)\\1([a-z]*)/i);
if (!regexParts) {
parsedRegex = new RegExp(this.regex);
} else {
/*
* if we don't have a regex flags (gmisuy), convert provided string into regexp directly
/*
if (regexParts[3] && !/^(?!.*?(.).*?\\1)[gmisuy]+$/.test(regexParts[3])) {
parsedRegex = RegExp(this.regex);
}
/*
* if we have a regex flags, use it to form regexp
*/
parsedRegex = new RegExp(regexParts[2], regexParts[3]);
}
}
if (this.inputType === "EMAIL") {
const emailRegex = new RegExp(/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/);
return emailRegex.test(this.text);
}
else if (
this.inputType === "NUMBER" ||
this.inputType === "INTEGER" ||
this.inputType === "CURRENCY" ||
this.inputType === "PHONE_NUMBER"
) {
let value = this.text.split(",").join("");
if (parsedRegex) {
return parsedRegex.test(value);
}
if (this.isRequired) {
return !(value === '' || isNaN(value));
}
return (value === '' || !isNaN(value || ''));
}
else if (this.isRequired) {
if(this.text && this.text.length) {
if (parsedRegex) {
return parsedRegex.test(this.text)
} else {
return true;
}
} else {
return false;
}
}
if (parsedRegex) {
return parsedRegex.test(this.text)
} else {
return true;
}
}()
}}`,
value: `{{this.text}}`,
};
}
static getDefaultPropertiesMap(): Record<string, string> {
return {
text: "defaultText",
};
}
static getMetaPropertiesMap(): Record<string, any> {
return {
text: undefined,
isFocused: false,
isDirty: false,
selectedCurrencyType: undefined,
selectedCountryCode: undefined,
};
}
onValueChange = (value: string) => {
this.props.updateWidgetMetaProperty("text", value, {
triggerPropertyName: "onTextChanged",
dynamicString: this.props.onTextChanged,
event: {
type: EventType.ON_TEXT_CHANGE,
},
});
if (!this.props.isDirty) {
this.props.updateWidgetMetaProperty("isDirty", true);
}
};
onCurrencyTypeChange = (code?: string) => {
const currencyCountryCode = code;
if (this.props.renderMode === RenderModes.CANVAS) {
super.updateWidgetProperty("currencyCountryCode", currencyCountryCode);
} else {
this.props.updateWidgetMetaProperty(
"selectedCurrencyCountryCode",
currencyCountryCode,
);
}
};
onISDCodeChange = (code?: string) => {
const countryCode = code;
if (this.props.renderMode === RenderModes.CANVAS) {
super.updateWidgetProperty("phoneNumberCountryCode", countryCode);
} else {
this.props.updateWidgetMetaProperty(
"selectedPhoneNumberCountryCode",
countryCode,
);
}
};
handleFocusChange = (focusState: boolean) => {
/**
* Reason for disabling drag on focusState: true:
* 1. In Firefox, draggable="true" property on the parent element
* or <input /> itself, interferes with some <input /> element's events
* Bug Ref - https://bugzilla.mozilla.org/show_bug.cgi?id=800050
* https://bugzilla.mozilla.org/show_bug.cgi?id=1189486
*
* Eg - input with draggable="true", double clicking the text; won't highlight the text
*
* 2. Dragging across the text (for text selection) in input won't cause the widget to drag.
*/
this.props.updateWidgetMetaProperty("dragDisabled", focusState);
this.props.updateWidgetMetaProperty("isFocused", focusState);
};
onSubmitSuccess = (result: ExecutionResult) => {
if (result.success && this.props.resetOnSubmit) {
this.props.updateWidgetMetaProperty("text", "", {
triggerPropertyName: "onSubmit",
dynamicString: this.props.onTextChanged,
event: {
type: EventType.ON_TEXT_CHANGE,
},
});
}
};
handleKeyDown = (
e:
| React.KeyboardEvent<HTMLTextAreaElement>
| React.KeyboardEvent<HTMLInputElement>,
) => {
const { isValid, onSubmit } = this.props;
const isEnterKey = e.key === "Enter" || e.keyCode === 13;
if (isEnterKey && onSubmit && isValid) {
super.executeAction({
triggerPropertyName: "onSubmit",
dynamicString: onSubmit,
event: {
type: EventType.ON_SUBMIT,
callback: this.onSubmitSuccess,
},
});
}
};
getPageView() {
const value = this.props.text ?? "";
let isInvalid =
"isValid" in this.props && !this.props.isValid && !!this.props.isDirty;
const currencyCountryCode = this.props.selectedCurrencyCountryCode
? this.props.selectedCurrencyCountryCode
: this.props.currencyCountryCode;
const phoneNumberCountryCode = this.props.selectedPhoneNumberCountryCode
? this.props.selectedPhoneNumberCountryCode
: this.props.phoneNumberCountryCode;
const conditionalProps: Partial<InputComponentProps> = {};
conditionalProps.errorMessage = this.props.errorMessage;
if (this.props.isRequired && value.length === 0) {
conditionalProps.errorMessage = createMessage(FIELD_REQUIRED_ERROR);
}
if (this.props.inputType === "TEXT" && this.props.maxChars) {
// pass maxChars only for Text type inputs, undefined for other types
conditionalProps.maxChars = this.props.maxChars;
if (
this.props.defaultText &&
this.props.defaultText.toString().length > this.props.maxChars
) {
isInvalid = true;
conditionalProps.errorMessage = createMessage(
INPUT_DEFAULT_TEXT_MAX_CHAR_ERROR,
);
}
}
if (this.props.maxNum) conditionalProps.maxNum = this.props.maxNum;
if (this.props.minNum) conditionalProps.minNum = this.props.minNum;
const minInputSingleLineHeight =
this.props.label || this.props.tooltip
? // adjust height for label | tooltip extra div
GRID_DENSITY_MIGRATION_V1 + 2
: // GRID_DENSITY_MIGRATION_V1 used to adjust code as per new scaled canvas.
GRID_DENSITY_MIGRATION_V1;
return (
<InputComponent
allowCurrencyChange={this.props.allowCurrencyChange}
autoFocus={this.props.autoFocus}
// show label and Input side by side if true
compactMode={
!(
(this.props.bottomRow - this.props.topRow) /
GRID_DENSITY_MIGRATION_V1 >
1 && this.props.inputType === "TEXT"
)
}
currencyCountryCode={currencyCountryCode}
decimalsInCurrency={this.props.decimalsInCurrency}
defaultValue={this.props.defaultText}
disableNewLineOnPressEnterKey={!!this.props.onSubmit}
disabled={this.props.isDisabled}
iconAlign={this.props.iconAlign}
iconName={this.props.iconName}
inputType={this.props.inputType}
isInvalid={isInvalid}
isLoading={this.props.isLoading}
label={this.props.label}
labelStyle={this.props.labelStyle}
labelTextColor={this.props.labelTextColor}
labelTextSize={this.props.labelTextSize}
multiline={
(this.props.bottomRow - this.props.topRow) /
minInputSingleLineHeight >
1 && this.props.inputType === "TEXT"
}
onCurrencyTypeChange={this.onCurrencyTypeChange}
onFocusChange={this.handleFocusChange}
onISDCodeChange={this.onISDCodeChange}
onKeyDown={this.handleKeyDown}
onValueChange={this.onValueChange}
phoneNumberCountryCode={phoneNumberCountryCode}
placeholder={this.props.placeholderText}
showError={!!this.props.isFocused}
stepSize={1}
tooltip={this.props.tooltip}
value={value}
widgetId={this.props.widgetId}
{...conditionalProps}
/>
);
}
static getWidgetType(): WidgetType {
return "INPUT_WIDGET";
}
}
export interface InputValidator {
validationRegex: string;
errorMessage: string;
}
export interface InputWidgetProps extends WidgetProps {
inputType: InputType;
currencyCountryCode?: string;
noOfDecimals?: number;
allowCurrencyChange?: boolean;
phoneNumberCountryCode?: string;
decimalsInCurrency?: number;
defaultText?: string | number;
tooltip?: string;
isDisabled?: boolean;
validation: boolean;
text: string;
regex?: string;
errorMessage?: string;
placeholderText?: string;
maxChars?: number;
minNum?: number;
maxNum?: number;
onTextChanged?: string;
label: string;
labelTextColor?: string;
labelTextSize?: TextSize;
labelStyle?: string;
inputValidators: InputValidator[];
isValid: boolean;
focusIndex?: number;
isAutoFocusEnabled?: boolean;
isRequired?: boolean;
isFocused?: boolean;
isDirty?: boolean;
autoFocus?: boolean;
iconName?: IconName;
iconAlign?: Omit<Alignment, "center">;
onSubmit?: string;
}
export default InputWidget; | the_stack |
import { define } from 'elements-sk/define';
import { html, TemplateResult } from 'lit-html';
import { toParamSet } from 'common-sk/modules/query';
import { jsonOrThrow } from 'common-sk/modules/jsonOrThrow';
import { stateReflector } from 'common-sk/modules/stateReflector';
import { HintableObject } from 'common-sk/modules/hintable';
import { TabSelectedSkEventDetail } from 'elements-sk/tabs-sk/tabs-sk';
import { SpinnerSk } from 'elements-sk/spinner-sk/spinner-sk';
import { errorMessage } from '../errorMessage';
import { byParams, AveForParam } from '../trybot/calcs';
import { ElementSk } from '../../../infra-sk/modules/ElementSk';
import {
QuerySk,
QuerySkQueryChangeEventDetail,
} from '../../../infra-sk/modules/query-sk/query-sk';
import { QueryCountSk } from '../query-count-sk/query-count-sk';
import {
ParamSet,
Commit,
TryBotRequest,
TryBotResponse,
Params,
} from '../json';
import { CommitDetailPanelSkCommitSelectedDetails } from '../commit-detail-panel-sk/commit-detail-panel-sk';
import '../../../infra-sk/modules/query-sk';
import '../../../infra-sk/modules/paramset-sk';
import '../query-count-sk';
import '../commit-detail-picker-sk';
import '../day-range-sk';
import '../plot-simple-sk';
import '../window/window';
import 'elements-sk/spinner-sk';
import 'elements-sk/tabs-sk';
import 'elements-sk/tabs-panel-sk';
import 'elements-sk/icon/timeline-icon-sk';
import { PlotSimpleSk, PlotSimpleSkTraceEventDetails } from '../plot-simple-sk/plot-simple-sk';
import { addParamsToParamSet, fromKey, makeKey } from '../paramtools';
import { ParamSetSk } from '../../../infra-sk/modules/paramset-sk/paramset-sk';
import { messagesToErrorString, startRequest } from '../progress/progress';
// Number of elements of a long lists head and tail to display.
const numHeadTail = 10;
// The maximum number of traces to plot in the By Params results.
const maxByParamsPlot = 10;
export class TrybotPageSk extends ElementSk {
private queryCount: QueryCountSk | null = null;
private query: QuerySk | null = null;
private spinner: SpinnerSk | null = null;
private results: TryBotResponse | null = null;
private individualPlot: PlotSimpleSk | null = null
private byParamsPlot: PlotSimpleSk | null = null
private byParams: AveForParam[] = [];
private byParamsTraceID: HTMLParagraphElement | null = null;
private byParamsParamSet: ParamSetSk | null = null;
private state: TryBotRequest = {
kind: 'commit',
cl: '',
patch_number: -1,
commit_number: -1,
query: '',
};
private displayedTrace: boolean = false;
private displayedByParamsTrace: boolean = false;
constructor() {
super(TrybotPageSk.template);
}
private static template = (ele: TrybotPageSk) => html`
<tabs-sk
@tab-selected-sk=${ele.tabSelected}
selected=${ele.state.kind === 'commit' ? 0 : 1}
>
<button>Commit</button>
<button>TryBot</button>
</tabs-sk>
<tabs-panel-sk>
<div>
<h2>Choose which commit to analyze:</h2>
<commit-detail-picker-sk
@commit-selected=${ele.commitSelected}
.selection=${ele.state.commit_number}
id="commit"
></commit-detail-picker-sk>
<h2
?hidden=${ele.state.commit_number === -1}
>Choose the traces to analyze:</h2>
<div
?hidden=${ele.state.commit_number === -1}
class=query
>
<query-sk
id=query
@query-change=${ele.queryChange}
@query-change-delayed=${ele.queryChangeDelayed}
.current_query=${ele.state.query}
></query-sk>
<div class=query-summary>
<paramset-sk
.paramsets=${[toParamSet(ele.state.query)]}
id=summary>
</paramset-sk>
<div class=query-counts>
Matches:
<query-count-sk
id=query-count
url='/_/count/'
@paramset-changed=${ele.paramsetChanged}>
</query-count-sk>
</div>
</div>
</div>
<div class=run>
<button
?hidden=${ele.state.commit_number === -1 || ele.state.query === ''}
@click=${ele.run}
id=run
class=action
>Run</button>
<spinner-sk id=run-spinner></spinner-sk>
</div>
</div>
<div>
TryBot Stuff Goes Here
</div>
</tabs-panel-sk>
<div
class=results
?hidden=${ele.results === null}
>
<h2>Results</h2>
<tabs-sk>
<button>Individual</button>
<button>By Params</button>
</tabs-sk>
<tabs-panel-sk>
<div>
<table>
<tr>
<th>Index</th>
<th title="How many standard deviations this value is from the median.">StdDevs</th>
<th>Plot</th>
${TrybotPageSk.paramKeysAsHeaders(ele)}
</tr>
${TrybotPageSk.individualResults(ele)}
</table>
<p class=tiny>Hold CTRL to add multiple traces to the graph.</p>
<p class=tiny>〃- The value is the same as the trace above it.</p>
<p class=tiny>∅ - The key doesn't appear on this trace.</p>
<plot-simple-sk
id=individual-plot
?hidden=${!ele.displayedTrace}
width="800"
height="250"
></plot-simple-sk>
</div>
<div>
<table>
<tr>
<th>Index</th>
<th>Plot</th>
<th>Param</th>
<th title="How many standard deviations this value is from the median.">StdDevs</th>
<th>N</th>
<th>High</th>
<th>Low</th>
</tr>
${TrybotPageSk.byParamsResults(ele)}
</table>
<p class=tiny>Hold CTRL to add multiple groups of traces to the graph.</p>
<plot-simple-sk
id=by-params-plot
?hidden=${!ele.displayedByParamsTrace}
width="800"
height="250"
@trace_focused=${ele.byParamsTraceFocused}
></plot-simple-sk>
<div
?hidden=${!ele.displayedByParamsTrace}
>
<div
id=by-params-traceid-container
></p><b>TraceID:</b><span id=by-params-traceid></span></div>
<paramset-sk
id=by-params-paramset>
</paramset-sk>
</div>
</div>
</tabs-panel-sk>
</div>
`;
private static paramKeysAsHeaders = (ele: TrybotPageSk): TemplateResult[] | null => {
if (!ele.results) {
return null;
}
const keys = Object.keys(ele.results.paramset);
keys.sort();
return keys.map((key) => html`<th>${key}</th>`);
}
private static individualResults = (ele: TrybotPageSk): TemplateResult[] | null => {
if (!ele.results) {
return null;
}
const keys = Object.keys(ele.results.paramset);
// TODO(jcgregorio) Deduplicate this from here and paramKeysAsHeaders.
keys.sort();
let lastParams: Params = {};
const ret: TemplateResult[] = [];
ele.results.results!.forEach((r, i) => {
// Only display the head and tail of the Individual results.
if (i > numHeadTail && i < ele.results!.results!.length - numHeadTail) {
return;
}
const keyValueDelta: TemplateResult[] = [];
keys.forEach((key) => {
const value = r.params[key];
if (value) {
if (value !== lastParams[key] || i === 0) {
// Highlight values that have changed, but not the first row.
keyValueDelta.push(html`<td>${value}</td>`);
} else {
keyValueDelta.push(html`<td>〃</td>`);
}
} else {
keyValueDelta.push(html`<td title="Does not exists on this trace.">∅</td>`);
}
});
ret.push(html`<tr><td>${i + 1}</td> <td>${r.stddevRatio}</td> <td class=link @click=${(e: MouseEvent) => ele.plotIndividualTrace(e, i)}><timeline-icon-sk></timeline-icon-sk></td> ${keyValueDelta}</tr>`);
lastParams = r.params;
});
return ret;
}
private static byParamsResults = (ele: TrybotPageSk): TemplateResult[] | null => {
if (!ele.byParams) {
return null;
}
const ret: TemplateResult[] = [];
ele.byParams.forEach((b, i) => {
// Only display the head and tail of the byParams results.
if (i > numHeadTail && i < ele.byParams.length - numHeadTail) {
return;
}
ret.push(html`<tr>
<td>${i + 1}</td>
<td class=link @click=${(e: MouseEvent) => ele.plotByParamsTraces(e, i)}><timeline-icon-sk></timeline-icon-sk></td>
<td>${b.keyValue}</td>
<td>${b.aveStdDevRatio}</td>
<td>${b.n}</td>
<td>${b.high}</td>
<td>${b.low}</td>
</tr>`);
});
return ret;
}
async connectedCallback(): Promise<void> {
super.connectedCallback();
this._render();
this.query = this.querySelector('#query');
this.query!.key_order = window.sk.perf.key_order || [];
this.queryCount = this.querySelector('#query-count');
this.spinner = this.querySelector('#run-spinner');
this.individualPlot = this.querySelector('#individual-plot');
this.byParamsPlot = this.querySelector('#by-params-plot');
this.byParamsTraceID = this.querySelector('#by-params-traceid');
this.byParamsParamSet = this.querySelector('#by-params-paramset');
// Populate the query element.
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
try {
const resp = await fetch(`/_/initpage/?tz=${tz}`, {
method: 'GET',
});
const json = await jsonOrThrow(resp);
this.query!.paramset = json.dataframe.paramset;
// From this point on reflect the state to the URL.
this.startStateReflector();
} catch (error) {
errorMessage(error);
}
}
private async run() {
this.displayedTrace = false;
this.displayedByParamsTrace = false;
this.byParamsTraceID!.innerText = '';
this._render();
try {
const prog = await startRequest('/_/trybot/load/', this.state, 200, this.spinner!, null);
if (prog.status === 'Finished') {
this.results = prog.results! as TryBotResponse;
this.byParams = byParams(this.results!);
this._render();
} else {
throw new Error(messagesToErrorString(prog.messages));
}
} catch (error) {
errorMessage(error, 0);
}
}
private getLabels() {
return this.results!.header!.map((colHeader) => new Date(colHeader!.timestamp * 1000));
}
private addZero(lines: {[key: string]: number[]|null}, n: number) {
lines.special_zero = new Array(n).fill(0);
}
private plotIndividualTrace(e: MouseEvent, i: number) {
const result = this.results!.results![i];
const params = result.params;
const lines: {[key: string]: number[]|null} = {};
lines[makeKey(params)] = result.values;
this.addZero(lines, result.values!.length);
if (!e.ctrlKey) {
this.individualPlot!.removeAll();
}
this.individualPlot!.addLines(lines, this.getLabels());
this.displayedTrace = true;
this._render();
}
private plotByParamsTraces(e: MouseEvent, i: number) {
// Pick out the array of traces that match the selected key=value.
const result = this.byParams[i];
const keyValue = result.keyValue;
const [key, value] = keyValue.split('=');
const aveStdDevRatio = result.aveStdDevRatio;
let matches = this.results!.results!.filter((r) => r.params[key] === value);
if (aveStdDevRatio >= 0) {
matches = matches.filter((r) => r.stddevRatio >= 0);
matches.sort((a, b) => b.stddevRatio - a.stddevRatio);
} else {
matches = matches.filter((r) => r.stddevRatio < 0);
matches.sort((a, b) => a.stddevRatio - b.stddevRatio);
}
// Truncate the list.
matches = matches.slice(0, maxByParamsPlot);
const lines: {[key: string]: number[]|null} = {};
matches.forEach((r) => {
lines[makeKey(r.params)] = r.values;
});
if (matches) {
this.addZero(lines, matches[0].values!.length);
}
if (!e.ctrlKey) {
this.byParamsPlot!.removeAll();
}
this.byParamsPlot!.addLines(lines, this.getLabels());
const ps: ParamSet = {};
this.byParamsPlot!.getLineNames().forEach((traceName) => {
addParamsToParamSet(ps, fromKey(traceName));
});
this.byParamsParamSet!.paramsets = [ps];
this.displayedByParamsTrace = true;
this._render();
}
private byParamsTraceFocused(e: CustomEvent<PlotSimpleSkTraceEventDetails>) {
this.byParamsTraceID!.innerText = e.detail.name;
this.byParamsParamSet!.highlight = fromKey(e.detail.name);
}
private tabSelected(e: CustomEvent<TabSelectedSkEventDetail>) {
this.state.kind = e.detail.index === 0 ? 'commit' : 'trybot';
this.stateHasChanged();
}
// Call this anytime something in private state is changed. Will be replaced
// with the real function once stateReflector has been setup.
// eslint-disable-next-line @typescript-eslint/no-empty-function
private stateHasChanged = () => {};
private startStateReflector() {
this.stateHasChanged = stateReflector(
() => (this.state as unknown) as HintableObject,
(state) => {
this.state = (state as unknown) as TryBotRequest;
this._render();
},
);
}
private commitSelected(
e: CustomEvent<CommitDetailPanelSkCommitSelectedDetails>,
) {
this.state.commit_number = ((e.detail.commit as unknown) as Commit).offset;
this.stateHasChanged();
this._render();
}
private paramsetChanged(e: CustomEvent<ParamSet>) {
// The query-count-sk element returned a new paramset for the given query.
this.query!.paramset = e.detail;
}
private queryChangeDelayed(
e: CustomEvent<QuerySkQueryChangeEventDetail>,
) {
// Pass to queryCount so it can update the number of traces that match the
// query.
this.queryCount!.current_query = e.detail.q;
}
private queryChange(e: CustomEvent<QuerySkQueryChangeEventDetail>) {
this.state.query = e.detail.q;
this.stateHasChanged();
this._render();
}
}
define('trybot-page-sk', TrybotPageSk); | the_stack |
import { ReactNode } from 'react';
import {
customProperties as vars,
designTokens,
} from '@commercetools-uikit/design-system';
import { Theme } from '@emotion/react';
type TProps = {
isDisabled?: boolean;
hasError?: boolean;
hasWarning?: boolean;
isReadOnly?: boolean;
showOptionGroupDivider?: boolean;
menuPortalZIndex?: number;
iconLeft?: ReactNode;
isMulti?: boolean;
hasValue?: boolean;
};
type TBase = {
fontColorForInput?: string;
borderColorForInput?: string;
color?: string;
backgroundColor?: string;
borderTop?: string;
borderColor?: string;
boxShadow?: string;
pointerEvents?: string;
};
type TState = {
isFocused?: boolean;
isDisabled?: boolean;
isSelected?: boolean;
};
const controlStyles =
(props: TProps, theme: Theme) => (base: TBase, state: TState) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
fontSize: overwrittenVars[designTokens.fontSizeForInput],
backgroundColor: props.isDisabled
? overwrittenVars[designTokens.backgroundColorForInputWhenDisabled]
: overwrittenVars[designTokens.backgroundColorForInput],
borderColor: (() => {
if (props.isDisabled)
return overwrittenVars[designTokens.borderColorForInputWhenDisabled];
if (state.isFocused)
return overwrittenVars[designTokens.borderColorForInputWhenFocused];
if (props.hasError)
return overwrittenVars[designTokens.borderColorForInputWhenError];
if (props.hasWarning)
return overwrittenVars[designTokens.borderColorForInputWhenWarning];
if (props.isReadOnly)
return overwrittenVars[designTokens.borderColorForInputWhenReadonly];
return overwrittenVars[designTokens.borderColorForInput];
})(),
borderRadius: overwrittenVars[designTokens.borderRadiusForInput],
minHeight: overwrittenVars.sizeHeightInput,
cursor: (() => {
if (props.isDisabled) return 'not-allowed';
if (props.isReadOnly) return 'default';
return 'pointer';
})(),
padding: `0 ${overwrittenVars.spacingS}`,
transition: `border-color ${overwrittenVars.transitionStandard},
box-shadow ${overwrittenVars.transitionStandard}`,
outline: 0,
boxShadow: 'none',
'&:focus-within': {
boxShadow: (() => {
if (!props.isDisabled)
return `inset 0 0 0 2px ${
overwrittenVars[designTokens.borderColorForInputWhenFocused]
}`;
return null;
})(),
borderColor: (() => {
if (!props.isDisabled)
return overwrittenVars[designTokens.borderColorForInputWhenFocused];
return null;
})(),
},
'&:hover': {
borderColor: (() => {
if (!props.isDisabled && !props.isReadOnly)
return overwrittenVars[designTokens.borderColorForInputWhenFocused];
return null;
})(),
},
pointerEvents: 'auto',
color:
props.isDisabled || props.isReadOnly
? overwrittenVars[designTokens.fontColorForInputWhenDisabled]
: base.fontColorForInput,
};
};
const menuStyles = (props: TProps, theme: Theme) => (base: TBase) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
border: `1px ${
overwrittenVars[designTokens.borderColorForInputWhenFocused]
} solid`,
borderRadius: overwrittenVars[designTokens.borderRadiusForInput],
backgroundColor: overwrittenVars[designTokens.backgroundColorForInput],
boxShadow: overwrittenVars.shadow7,
fontSize: overwrittenVars[designTokens.fontSizeForInput],
fontFamily: 'inherit',
margin: `${overwrittenVars.spacingXs} 0 0 0`,
borderColor: (() => {
if (props.hasError)
return overwrittenVars[designTokens.borderColorForInputWhenError];
if (props.hasWarning)
return overwrittenVars[designTokens.borderColorForInputWhenWarning];
return base.borderColorForInput;
})(),
};
};
const indicatorSeparatorStyles = (theme: Theme) => (base: TBase) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
display: 'none',
margin: '0',
padding: '0',
marginLeft: overwrittenVars.spacingXs,
};
};
const dropdownIndicatorStyles =
(props: TProps, theme: Theme) => (base: TBase) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
color: overwrittenVars[designTokens.fontColorForInput],
margin: '0',
padding: '0',
marginLeft: overwrittenVars.spacingXs,
fill:
props.isDisabled || props.isReadOnly
? overwrittenVars[designTokens.fontColorForInputWhenDisabled]
: base.fontColorForInput,
};
};
const clearIndicatorStyles = () => (base: TBase) => ({
...base,
display: 'flex',
padding: 0,
});
const menuListStyles = (theme: Theme) => (base: TBase) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
padding: '0',
borderRadius: overwrittenVars[designTokens.borderRadiusForInput],
backgroundColor: overwrittenVars[designTokens.backgroundColorForInput],
};
};
const optionStyles = (theme: Theme) => (base: TBase, state: TState) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
transition: `border-color ${overwrittenVars.transitionStandard},
background-color ${overwrittenVars.transitionStandard},
color ${overwrittenVars.transitionStandard}`,
paddingLeft: overwrittenVars.spacingS,
paddingRight: overwrittenVars.spacingS,
color: (() => {
if (!state.isDisabled)
return overwrittenVars[designTokens.fontColorForInput];
if (state.isSelected)
return overwrittenVars[designTokens.fontColorForInput];
return base.color;
})(),
backgroundColor: (() => {
if (state.isSelected)
return overwrittenVars[
designTokens.backgroundColorForInputWhenSelected
];
if (state.isFocused)
return overwrittenVars[designTokens.backgroundColorForInputWhenHovered];
return base.backgroundColor;
})(),
'&:active': {
color: (() => {
if (!state.isDisabled)
return overwrittenVars[designTokens.fontColorForInput];
return base.color;
})(),
backgroundColor:
overwrittenVars[designTokens.backgroundColorForInputWhenSelected],
},
};
};
const placeholderStyles = (props: TProps, theme: Theme) => (base: TBase) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
color: overwrittenVars[designTokens.placeholderFontColorForInput],
width: '100%',
overflow: 'hidden',
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
fill:
props.isDisabled || props.isReadOnly
? overwrittenVars[designTokens.fontColorForInputWhenDisabled]
: base.fontColorForInput,
};
};
const valueContainerStyles = (props: TProps, theme: Theme) => (base: TBase) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
padding: '0',
backgroundColor: 'none',
overflow: 'hidden',
// Display property should be grid when isMulti and has no value so the Placeholder component is positioned correctly with the Input
// Display property should be Flex when there is an iconLeft, also when the input has some values when isMulti.
// See PR from react select for more insight https://github.com/JedWatson/react-select/pull/4833
display:
(props.iconLeft && !props.isMulti) || (props.isMulti && props.hasValue)
? 'flex'
: 'grid',
fill:
props.isDisabled || props.isReadOnly
? overwrittenVars[designTokens.fontColorForInputWhenDisabled]
: base.fontColorForInput,
};
};
const singleValueStyles = (props: TProps, theme: Theme) => (base: TBase) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
color: (() => {
if (props.isDisabled) {
return overwrittenVars[designTokens.fontColorForInputWhenDisabled];
}
if (props.isReadOnly) {
return overwrittenVars[designTokens.fontColorForInputWhenReadonly];
}
return overwrittenVars[designTokens.fontColorForInput];
})(),
};
};
const groupStyles = (props: TProps, theme: Theme) => (base: TBase) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
padding: 0,
'&:not(:first-of-type)': {
borderTop: props.showOptionGroupDivider
? `1px solid ${overwrittenVars.colorNeutral}`
: base.borderTop,
},
};
};
const groupHeadingStyles = (theme: Theme) => (base: TBase) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
color: overwrittenVars[designTokens.fontColorForInputWhenReadonly],
fontSize: overwrittenVars.fontSizeSmall,
textTransform: 'none',
fontWeight: 'bold',
margin: `0 ${overwrittenVars.spacingXs}`,
padding: `${overwrittenVars.spacingS} ${overwrittenVars.spacingXs}`,
'&:empty': {
padding: 0,
},
};
};
const containerStyles = (theme: Theme) => (base: TBase, state: TState) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
fontFamily: 'inherit',
minHeight: overwrittenVars.sizeHeightInput,
borderRadius: overwrittenVars[designTokens.borderRadiusForInput],
borderColor: state.isFocused
? overwrittenVars[designTokens.borderColorForInputWhenFocused]
: base.borderColor,
boxShadow: state.isFocused ? 'none' : base.boxShadow,
};
};
const indicatorsContainerStyles = () => () => ({
background: 'none',
display: 'flex',
alignItems: 'center',
});
const menuPortalStyles = (props: TProps) => (base: TBase) => ({
...base,
zIndex: props.menuPortalZIndex,
});
const multiValueStyles = (theme: Theme) => (base: TBase) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
height: vars.sizeHeightTag,
backgroundColor: overwrittenVars[designTokens.backgroundColorForTag],
padding: '0',
};
};
const multiValueLabelStyles =
(props: TProps, theme: Theme) => (base: TBase) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
fontSize: vars.fontSizeSmall,
color: (() => {
if (props.isDisabled)
return overwrittenVars[designTokens.fontColorForInputWhenDisabled];
if (props.isReadOnly)
return overwrittenVars[designTokens.fontColorForInputWhenReadonly];
return base.color;
})(),
padding: `${overwrittenVars.spacingXs} ${overwrittenVars.spacingS}`,
borderRadius: `${overwrittenVars.borderRadiusForTag} 0 0 ${overwrittenVars.borderRadiusForTag}`,
border: `1px ${overwrittenVars[designTokens.borderColorForTag]} solid`,
borderWidth: '1px 0 1px 1px',
'&:last-child': {
borderRadius: overwrittenVars.borderRadiusForTag,
borderWidth: '1px',
},
};
};
const multiValueRemoveStyles =
(props: TProps, theme: Theme) => (base: TBase, state: TState) => {
const overwrittenVars = {
...vars,
...theme,
};
return {
...base,
borderColor: overwrittenVars[designTokens.borderColorForTag],
padding: `0 ${overwrittenVars.spacingXs}`,
borderRadius: `0 ${overwrittenVars[designTokens.borderRadiusForTag]} ${
overwrittenVars[designTokens.borderRadiusForTag]
} 0`,
borderStyle: 'solid',
borderWidth: '1px',
pointerEvents:
state.isDisabled || props.isReadOnly ? 'none' : base.pointerEvents,
backgroundColor: overwrittenVars[designTokens.backgroundColorForTag],
'svg *': {
fill: props.isReadOnly
? overwrittenVars[designTokens.fontColorForInputWhenReadonly]
: '',
},
'&:hover, &:focus': {
borderColor: overwrittenVars.borderColorForTagWarning,
backgroundColor: overwrittenVars[designTokens.backgroundColorForTag],
'svg *': {
fill: overwrittenVars[designTokens.borderColorForTagWarning],
},
},
};
};
export default function createSelectStyles(props: TProps, theme: Theme) {
return {
control: controlStyles(props, theme),
menu: menuStyles(props, theme),
indicatorSeparator: indicatorSeparatorStyles(theme),
dropdownIndicator: dropdownIndicatorStyles(props, theme),
clearIndicator: clearIndicatorStyles(),
menuList: menuListStyles(theme),
menuPortal: menuPortalStyles(props),
multiValue: multiValueStyles(theme),
multiValueLabel: multiValueLabelStyles(props, theme),
multiValueRemove: multiValueRemoveStyles(props, theme),
indicatorsContainer: indicatorsContainerStyles(),
option: optionStyles(theme),
placeholder: placeholderStyles(props, theme),
valueContainer: valueContainerStyles(props, theme),
singleValue: singleValueStyles(props, theme),
group: groupStyles(props, theme),
groupHeading: groupHeadingStyles(theme),
container: containerStyles(theme),
};
} | the_stack |
import { LazyJsonString as __LazyJsonString } from "@aws-sdk/smithy-client";
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types";
/**
* <p>The request could not be completed because you do not have access to the resource.
* </p>
*/
export interface AccessDeniedException extends __SmithyException, $MetadataBearer {
name: "AccessDeniedException";
$fault: "client";
Message: string | undefined;
}
export namespace AccessDeniedException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AccessDeniedException): any => ({
...obj,
});
}
/**
* <p> The request could not be completed due to a conflict with the current state of the
* target resource. </p>
*/
export interface ConflictException extends __SmithyException, $MetadataBearer {
name: "ConflictException";
$fault: "client";
Message: string | undefined;
}
export namespace ConflictException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ConflictException): any => ({
...obj,
});
}
/**
* <p>Provides information about the data schema used with the given dataset. </p>
*/
export interface DatasetSchema {
/**
* <p>
* </p>
*/
InlineDataSchema?: __LazyJsonString | string;
}
export namespace DatasetSchema {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DatasetSchema): any => ({
...obj,
});
}
/**
* <p>A tag is a key-value pair that can be added to a resource as metadata. </p>
*/
export interface Tag {
/**
* <p>The key for the specified tag. </p>
*/
Key: string | undefined;
/**
* <p>The value for the specified tag. </p>
*/
Value: string | undefined;
}
export namespace Tag {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Tag): any => ({
...obj,
});
}
export interface CreateDatasetRequest {
/**
* <p>The name of the dataset being created. </p>
*/
DatasetName: string | undefined;
/**
* <p>A JSON description of the data that is in each time series dataset, including names,
* column names, and data types. </p>
*/
DatasetSchema: DatasetSchema | undefined;
/**
* <p>Provides the identifier of the KMS key used to encrypt dataset data by Amazon Lookout for Equipment. </p>
*/
ServerSideKmsKeyId?: string;
/**
* <p> A unique identifier for the request. If you do not set the client request token, Amazon
* Lookout for Equipment generates one. </p>
*/
ClientToken?: string;
/**
* <p>Any tags associated with the ingested data described in the dataset. </p>
*/
Tags?: Tag[];
}
export namespace CreateDatasetRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateDatasetRequest): any => ({
...obj,
});
}
export enum DatasetStatus {
ACTIVE = "ACTIVE",
CREATED = "CREATED",
INGESTION_IN_PROGRESS = "INGESTION_IN_PROGRESS",
}
export interface CreateDatasetResponse {
/**
* <p>The name of the dataset being created. </p>
*/
DatasetName?: string;
/**
* <p> The Amazon Resource Name (ARN) of the dataset being created. </p>
*/
DatasetArn?: string;
/**
* <p>Indicates the status of the <code>CreateDataset</code> operation. </p>
*/
Status?: DatasetStatus | string;
}
export namespace CreateDatasetResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateDatasetResponse): any => ({
...obj,
});
}
/**
* <p> Processing of the request has failed because of an unknown error, exception or failure.
* </p>
*/
export interface InternalServerException extends __SmithyException, $MetadataBearer {
name: "InternalServerException";
$fault: "server";
Message: string | undefined;
}
export namespace InternalServerException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InternalServerException): any => ({
...obj,
});
}
/**
* <p> Resource limitations have been exceeded. </p>
*/
export interface ServiceQuotaExceededException extends __SmithyException, $MetadataBearer {
name: "ServiceQuotaExceededException";
$fault: "client";
Message: string | undefined;
}
export namespace ServiceQuotaExceededException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ServiceQuotaExceededException): any => ({
...obj,
});
}
/**
* <p>The request was denied due to request throttling.</p>
*/
export interface ThrottlingException extends __SmithyException, $MetadataBearer {
name: "ThrottlingException";
$fault: "client";
Message: string | undefined;
}
export namespace ThrottlingException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ThrottlingException): any => ({
...obj,
});
}
/**
* <p> The input fails to satisfy constraints specified by Amazon Lookout for Equipment or a related AWS
* service that's being utilized. </p>
*/
export interface ValidationException extends __SmithyException, $MetadataBearer {
name: "ValidationException";
$fault: "client";
Message: string | undefined;
}
export namespace ValidationException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ValidationException): any => ({
...obj,
});
}
/**
* <p>Specifies configuration information for the input data for the inference, including
* timestamp format and delimiter. </p>
*/
export interface InferenceInputNameConfiguration {
/**
* <p>The format of the timestamp, whether Epoch time, or standard, with or without hyphens
* (-). </p>
*/
TimestampFormat?: string;
/**
* <p>Indicates the delimiter character used between items in the data. </p>
*/
ComponentTimestampDelimiter?: string;
}
export namespace InferenceInputNameConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InferenceInputNameConfiguration): any => ({
...obj,
});
}
/**
* <p> Specifies configuration information for the input data for the inference, including
* input data S3 location. </p>
*/
export interface InferenceS3InputConfiguration {
/**
* <p>The bucket containing the input dataset for the inference. </p>
*/
Bucket: string | undefined;
/**
* <p>The prefix for the S3 bucket used for the input data for the inference. </p>
*/
Prefix?: string;
}
export namespace InferenceS3InputConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InferenceS3InputConfiguration): any => ({
...obj,
});
}
/**
* <p>Specifies configuration information for the input data for the inference, including S3
* location of input data.. </p>
*/
export interface InferenceInputConfiguration {
/**
* <p> Specifies configuration information for the input data for the inference, including S3
* location of input data.. </p>
*/
S3InputConfiguration?: InferenceS3InputConfiguration;
/**
* <p>Indicates the difference between your time zone and Greenwich Mean Time (GMT). </p>
*/
InputTimeZoneOffset?: string;
/**
* <p>Specifies configuration information for the input data for the inference, including
* timestamp format and delimiter. </p>
*/
InferenceInputNameConfiguration?: InferenceInputNameConfiguration;
}
export namespace InferenceInputConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InferenceInputConfiguration): any => ({
...obj,
});
}
/**
* <p> Specifies configuration information for the output results from the inference,
* including output S3 location. </p>
*/
export interface InferenceS3OutputConfiguration {
/**
* <p> The bucket containing the output results from the inference </p>
*/
Bucket: string | undefined;
/**
* <p> The prefix for the S3 bucket used for the output results from the inference. </p>
*/
Prefix?: string;
}
export namespace InferenceS3OutputConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InferenceS3OutputConfiguration): any => ({
...obj,
});
}
/**
* <p> Specifies configuration information for the output results from for the inference,
* including KMS key ID and output S3 location. </p>
*/
export interface InferenceOutputConfiguration {
/**
* <p> Specifies configuration information for the output results from for the inference,
* output S3 location. </p>
*/
S3OutputConfiguration: InferenceS3OutputConfiguration | undefined;
/**
* <p>The ID number for the AWS KMS key used to encrypt the inference output. </p>
*/
KmsKeyId?: string;
}
export namespace InferenceOutputConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InferenceOutputConfiguration): any => ({
...obj,
});
}
export enum DataUploadFrequency {
PT10M = "PT10M",
PT15M = "PT15M",
PT1H = "PT1H",
PT30M = "PT30M",
PT5M = "PT5M",
}
export interface CreateInferenceSchedulerRequest {
/**
* <p>The name of the previously trained ML model being used to create the inference
* scheduler. </p>
*/
ModelName: string | undefined;
/**
* <p>The name of the inference scheduler being created. </p>
*/
InferenceSchedulerName: string | undefined;
/**
* <p>A period of time (in minutes) by which inference on the data is delayed after the data
* starts. For instance, if you select an offset delay time of five minutes, inference will
* not begin on the data until the first data measurement after the five minute mark. For example, if
* five minutes is selected, the inference scheduler will wake up at the configured frequency with the
* additional five minute delay time to check the customer S3 bucket. The customer can upload data at
* the same frequency and they don't need to stop and restart the scheduler when uploading new data. </p>
*/
DataDelayOffsetInMinutes?: number;
/**
* <p> How often data is uploaded to the source S3 bucket for the input data. The value chosen
* is the length of time between data uploads. For instance, if you select 5 minutes, Amazon
* Lookout for Equipment will upload the real-time data to the source bucket once every 5 minutes. This frequency
* also determines how often Amazon Lookout for Equipment starts a scheduled inference on your data. In this
* example, it starts once every 5 minutes. </p>
*/
DataUploadFrequency: DataUploadFrequency | string | undefined;
/**
* <p>Specifies configuration information for the input data for the inference scheduler,
* including delimiter, format, and dataset location. </p>
*/
DataInputConfiguration: InferenceInputConfiguration | undefined;
/**
* <p>Specifies configuration information for the output results for the inference scheduler,
* including the S3 location for the output. </p>
*/
DataOutputConfiguration: InferenceOutputConfiguration | undefined;
/**
* <p>The Amazon Resource Name (ARN) of a role with permission to access the data source being
* used for the inference. </p>
*/
RoleArn: string | undefined;
/**
* <p>Provides the identifier of the KMS key used to encrypt inference scheduler data by Amazon Lookout for Equipment. </p>
*/
ServerSideKmsKeyId?: string;
/**
* <p> A unique identifier for the request. If you do not set the client request token, Amazon
* Lookout for Equipment generates one. </p>
*/
ClientToken?: string;
/**
* <p>Any tags associated with the inference scheduler. </p>
*/
Tags?: Tag[];
}
export namespace CreateInferenceSchedulerRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateInferenceSchedulerRequest): any => ({
...obj,
});
}
export enum InferenceSchedulerStatus {
PENDING = "PENDING",
RUNNING = "RUNNING",
STOPPED = "STOPPED",
STOPPING = "STOPPING",
}
export interface CreateInferenceSchedulerResponse {
/**
* <p>The Amazon Resource Name (ARN) of the inference scheduler being created. </p>
*/
InferenceSchedulerArn?: string;
/**
* <p>The name of inference scheduler being created. </p>
*/
InferenceSchedulerName?: string;
/**
* <p>Indicates the status of the <code>CreateInferenceScheduler</code> operation. </p>
*/
Status?: InferenceSchedulerStatus | string;
}
export namespace CreateInferenceSchedulerResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateInferenceSchedulerResponse): any => ({
...obj,
});
}
/**
* <p> The resource requested could not be found. Verify the resource ID and retry your
* request. </p>
*/
export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer {
name: "ResourceNotFoundException";
$fault: "client";
Message: string | undefined;
}
export namespace ResourceNotFoundException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({
...obj,
});
}
export enum TargetSamplingRate {
PT10M = "PT10M",
PT10S = "PT10S",
PT15M = "PT15M",
PT15S = "PT15S",
PT1H = "PT1H",
PT1M = "PT1M",
PT1S = "PT1S",
PT30M = "PT30M",
PT30S = "PT30S",
PT5M = "PT5M",
PT5S = "PT5S",
}
/**
* <p>The configuration is the <code>TargetSamplingRate</code>, which is the sampling rate of
* the data after post processing by
* Amazon Lookout for Equipment. For example, if you provide data that
* has been collected at a 1 second level and you want the system to resample
* the data at a 1 minute rate before training, the <code>TargetSamplingRate</code> is 1 minute.</p>
* <p>When providing a value for the <code>TargetSamplingRate</code>, you must
* attach the prefix "PT" to the rate you want. The value for a 1 second rate
* is therefore <i>PT1S</i>, the value for a 15 minute rate
* is <i>PT15M</i>, and the value for a 1 hour rate
* is <i>PT1H</i>
* </p>
*/
export interface DataPreProcessingConfiguration {
/**
* <p>The sampling rate of the data after post processing by Amazon Lookout for Equipment.
* For example, if you provide data that has been collected at a 1 second level and
* you want the system to resample the data at a 1 minute rate before training,
* the <code>TargetSamplingRate</code> is 1 minute.</p>
* <p>When providing a value for the <code>TargetSamplingRate</code>, you must attach
* the prefix "PT" to the rate you want. The value for a 1 second rate is
* therefore <i>PT1S</i>, the value for a 15 minute
* rate is <i>PT15M</i>, and the value for a 1 hour rate
* is <i>PT1H</i>
* </p>
*/
TargetSamplingRate?: TargetSamplingRate | string;
}
export namespace DataPreProcessingConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DataPreProcessingConfiguration): any => ({
...obj,
});
}
/**
* <p>The location information (prefix and bucket name) for the s3 location being used for
* label data. </p>
*/
export interface LabelsS3InputConfiguration {
/**
* <p>The name of the S3 bucket holding the label data. </p>
*/
Bucket: string | undefined;
/**
* <p> The prefix for the S3 bucket used for the label data. </p>
*/
Prefix?: string;
}
export namespace LabelsS3InputConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: LabelsS3InputConfiguration): any => ({
...obj,
});
}
/**
* <p>Contains the configuration information for the S3 location being used to hold label
* data. </p>
*/
export interface LabelsInputConfiguration {
/**
* <p>Contains location information for the S3 location being used for label data. </p>
*/
S3InputConfiguration: LabelsS3InputConfiguration | undefined;
}
export namespace LabelsInputConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: LabelsInputConfiguration): any => ({
...obj,
});
}
export interface CreateModelRequest {
/**
* <p>The name for the ML model to be created.</p>
*/
ModelName: string | undefined;
/**
* <p>The name of the dataset for the ML model being created. </p>
*/
DatasetName: string | undefined;
/**
* <p>The data schema for the ML model being created. </p>
*/
DatasetSchema?: DatasetSchema;
/**
* <p>The input configuration for the labels being used for the ML model that's being created.
* </p>
*/
LabelsInputConfiguration?: LabelsInputConfiguration;
/**
* <p>A unique identifier for the request. If you do not set the client request token, Amazon
* Lookout for Equipment generates one. </p>
*/
ClientToken?: string;
/**
* <p>Indicates the time reference in the dataset that should be used to begin the subset of
* training data for the ML model. </p>
*/
TrainingDataStartTime?: Date;
/**
* <p>Indicates the time reference in the dataset that should be used to end the subset of
* training data for the ML model. </p>
*/
TrainingDataEndTime?: Date;
/**
* <p>Indicates the time reference in the dataset that should be used to begin the subset of
* evaluation data for the ML model. </p>
*/
EvaluationDataStartTime?: Date;
/**
* <p> Indicates the time reference in the dataset that should be used to end the subset of
* evaluation data for the ML model. </p>
*/
EvaluationDataEndTime?: Date;
/**
* <p> The Amazon Resource Name (ARN) of a role with permission to access the data source
* being used to create the ML model. </p>
*/
RoleArn?: string;
/**
* <p>The configuration is the <code>TargetSamplingRate</code>, which is the sampling rate of
* the data after post processing by
* Amazon Lookout for Equipment. For example, if you provide data that
* has been collected at a 1 second level and you want the system to resample
* the data at a 1 minute rate before training, the <code>TargetSamplingRate</code> is 1 minute.</p>
* <p>When providing a value for the <code>TargetSamplingRate</code>, you must
* attach the prefix "PT" to the rate you want. The value for a 1 second rate
* is therefore <i>PT1S</i>, the value for a 15 minute rate
* is <i>PT15M</i>, and the value for a 1 hour rate
* is <i>PT1H</i>
* </p>
*/
DataPreProcessingConfiguration?: DataPreProcessingConfiguration;
/**
* <p>Provides the identifier of the KMS key used to encrypt model data by Amazon Lookout for Equipment. </p>
*/
ServerSideKmsKeyId?: string;
/**
* <p> Any tags associated with the ML model being created. </p>
*/
Tags?: Tag[];
/**
* <p>Indicates that the asset associated with this sensor has been shut off. As long as this condition is met, Lookout for Equipment will not use data from this asset for training, evaluation, or inference.</p>
*/
OffCondition?: string;
}
export namespace CreateModelRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateModelRequest): any => ({
...obj,
});
}
export enum ModelStatus {
FAILED = "FAILED",
IN_PROGRESS = "IN_PROGRESS",
SUCCESS = "SUCCESS",
}
export interface CreateModelResponse {
/**
* <p>The Amazon Resource Name (ARN) of the model being created. </p>
*/
ModelArn?: string;
/**
* <p>Indicates the status of the <code>CreateModel</code> operation. </p>
*/
Status?: ModelStatus | string;
}
export namespace CreateModelResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateModelResponse): any => ({
...obj,
});
}
export interface DeleteDatasetRequest {
/**
* <p>The name of the dataset to be deleted. </p>
*/
DatasetName: string | undefined;
}
export namespace DeleteDatasetRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteDatasetRequest): any => ({
...obj,
});
}
export interface DeleteInferenceSchedulerRequest {
/**
* <p>The name of the inference scheduler to be deleted. </p>
*/
InferenceSchedulerName: string | undefined;
}
export namespace DeleteInferenceSchedulerRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteInferenceSchedulerRequest): any => ({
...obj,
});
}
export interface DeleteModelRequest {
/**
* <p>The name of the ML model to be deleted. </p>
*/
ModelName: string | undefined;
}
export namespace DeleteModelRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteModelRequest): any => ({
...obj,
});
}
export interface DescribeDataIngestionJobRequest {
/**
* <p>The job ID of the data ingestion job. </p>
*/
JobId: string | undefined;
}
export namespace DescribeDataIngestionJobRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDataIngestionJobRequest): any => ({
...obj,
});
}
/**
* <p> Specifies S3 configuration information for the input data for the data ingestion job.
* </p>
*/
export interface IngestionS3InputConfiguration {
/**
* <p>The name of the S3 bucket used for the input data for the data ingestion. </p>
*/
Bucket: string | undefined;
/**
* <p>The prefix for the S3 location being used for the input data for the data ingestion.
* </p>
*/
Prefix?: string;
}
export namespace IngestionS3InputConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: IngestionS3InputConfiguration): any => ({
...obj,
});
}
/**
* <p> Specifies configuration information for the input data for the data ingestion job,
* including input data S3 location. </p>
*/
export interface IngestionInputConfiguration {
/**
* <p>The location information for the S3 bucket used for input data for the data ingestion.
* </p>
*/
S3InputConfiguration: IngestionS3InputConfiguration | undefined;
}
export namespace IngestionInputConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: IngestionInputConfiguration): any => ({
...obj,
});
}
export enum IngestionJobStatus {
FAILED = "FAILED",
IN_PROGRESS = "IN_PROGRESS",
SUCCESS = "SUCCESS",
}
export interface DescribeDataIngestionJobResponse {
/**
* <p>Indicates the job ID of the data ingestion job. </p>
*/
JobId?: string;
/**
* <p>The Amazon Resource Name (ARN) of the dataset being used in the data ingestion job.
* </p>
*/
DatasetArn?: string;
/**
* <p>Specifies the S3 location configuration for the data input for the data ingestion job.
* </p>
*/
IngestionInputConfiguration?: IngestionInputConfiguration;
/**
* <p>The Amazon Resource Name (ARN) of an IAM role with permission to access the data source
* being ingested. </p>
*/
RoleArn?: string;
/**
* <p>The time at which the data ingestion job was created. </p>
*/
CreatedAt?: Date;
/**
* <p>Indicates the status of the <code>DataIngestionJob</code> operation. </p>
*/
Status?: IngestionJobStatus | string;
/**
* <p>Specifies the reason for failure when a data ingestion job has failed. </p>
*/
FailedReason?: string;
}
export namespace DescribeDataIngestionJobResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDataIngestionJobResponse): any => ({
...obj,
});
}
export interface DescribeDatasetRequest {
/**
* <p>The name of the dataset to be described. </p>
*/
DatasetName: string | undefined;
}
export namespace DescribeDatasetRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDatasetRequest): any => ({
...obj,
});
}
export interface DescribeDatasetResponse {
/**
* <p>The name of the dataset being described. </p>
*/
DatasetName?: string;
/**
* <p>The Amazon Resource Name (ARN) of the dataset being described. </p>
*/
DatasetArn?: string;
/**
* <p>Specifies the time the dataset was created in Amazon Lookout for Equipment. </p>
*/
CreatedAt?: Date;
/**
* <p>Specifies the time the dataset was last updated, if it was. </p>
*/
LastUpdatedAt?: Date;
/**
* <p>Indicates the status of the dataset. </p>
*/
Status?: DatasetStatus | string;
/**
* <p>A JSON description of the data that is in each time series dataset, including names,
* column names, and data types. </p>
*/
Schema?: __LazyJsonString | string;
/**
* <p>Provides the identifier of the KMS key used to encrypt dataset data by Amazon Lookout for Equipment. </p>
*/
ServerSideKmsKeyId?: string;
/**
* <p>Specifies the S3 location configuration for the data input for the data ingestion job. </p>
*/
IngestionInputConfiguration?: IngestionInputConfiguration;
}
export namespace DescribeDatasetResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDatasetResponse): any => ({
...obj,
});
}
export interface DescribeInferenceSchedulerRequest {
/**
* <p>The name of the inference scheduler being described. </p>
*/
InferenceSchedulerName: string | undefined;
}
export namespace DescribeInferenceSchedulerRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeInferenceSchedulerRequest): any => ({
...obj,
});
}
export interface DescribeInferenceSchedulerResponse {
/**
* <p>The Amazon Resource Name (ARN) of the ML model of the inference scheduler being
* described. </p>
*/
ModelArn?: string;
/**
* <p>The name of the ML model of the inference scheduler being described. </p>
*/
ModelName?: string;
/**
* <p>The name of the inference scheduler being described. </p>
*/
InferenceSchedulerName?: string;
/**
* <p>The Amazon Resource Name (ARN) of the inference scheduler being described. </p>
*/
InferenceSchedulerArn?: string;
/**
* <p>Indicates the status of the inference scheduler. </p>
*/
Status?: InferenceSchedulerStatus | string;
/**
* <p> A period of time (in minutes) by which inference on the data is delayed after the data
* starts. For instance, if you select an offset delay time of five minutes, inference will
* not begin on the data until the first data measurement after the five minute mark. For example, if
* five minutes is selected, the inference scheduler will wake up at the configured frequency with the
* additional five minute delay time to check the customer S3 bucket. The customer can upload data at
* the same frequency and they don't need to stop and restart the scheduler when uploading new data.</p>
*/
DataDelayOffsetInMinutes?: number;
/**
* <p>Specifies how often data is uploaded to the source S3 bucket for the input data. This
* value is the length of time between data uploads. For instance, if you select 5 minutes,
* Amazon Lookout for Equipment will upload the real-time data to the source bucket once every 5 minutes. This
* frequency also determines how often Amazon Lookout for Equipment starts a scheduled inference on your data.
* In this example, it starts once every 5 minutes. </p>
*/
DataUploadFrequency?: DataUploadFrequency | string;
/**
* <p>Specifies the time at which the inference scheduler was created. </p>
*/
CreatedAt?: Date;
/**
* <p>Specifies the time at which the inference scheduler was last updated, if it was. </p>
*/
UpdatedAt?: Date;
/**
* <p> Specifies configuration information for the input data for the inference scheduler,
* including delimiter, format, and dataset location. </p>
*/
DataInputConfiguration?: InferenceInputConfiguration;
/**
* <p> Specifies information for the output results for the inference scheduler,
* including the output S3 location. </p>
*/
DataOutputConfiguration?: InferenceOutputConfiguration;
/**
* <p> The Amazon Resource Name (ARN) of a role with permission to access the data source for
* the inference scheduler being described. </p>
*/
RoleArn?: string;
/**
* <p>Provides the identifier of the KMS key used to encrypt inference scheduler data by Amazon Lookout for Equipment. </p>
*/
ServerSideKmsKeyId?: string;
}
export namespace DescribeInferenceSchedulerResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeInferenceSchedulerResponse): any => ({
...obj,
});
}
export interface DescribeModelRequest {
/**
* <p>The name of the ML model to be described. </p>
*/
ModelName: string | undefined;
}
export namespace DescribeModelRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeModelRequest): any => ({
...obj,
});
}
export interface DescribeModelResponse {
/**
* <p>The name of the ML model being described. </p>
*/
ModelName?: string;
/**
* <p>The Amazon Resource Name (ARN) of the ML model being described. </p>
*/
ModelArn?: string;
/**
* <p>The name of the dataset being used by the ML being described. </p>
*/
DatasetName?: string;
/**
* <p>The Amazon Resouce Name (ARN) of the dataset used to create the ML model being
* described. </p>
*/
DatasetArn?: string;
/**
* <p>A JSON description of the data that is in each time series dataset, including names,
* column names, and data types. </p>
*/
Schema?: __LazyJsonString | string;
/**
* <p>Specifies configuration information about the labels input, including its S3 location.
* </p>
*/
LabelsInputConfiguration?: LabelsInputConfiguration;
/**
* <p> Indicates the time reference in the dataset that was used to begin the subset of
* training data for the ML model. </p>
*/
TrainingDataStartTime?: Date;
/**
* <p> Indicates the time reference in the dataset that was used to end the subset of training
* data for the ML model. </p>
*/
TrainingDataEndTime?: Date;
/**
* <p> Indicates the time reference in the dataset that was used to begin the subset of
* evaluation data for the ML model. </p>
*/
EvaluationDataStartTime?: Date;
/**
* <p> Indicates the time reference in the dataset that was used to end the subset of
* evaluation data for the ML model. </p>
*/
EvaluationDataEndTime?: Date;
/**
* <p> The Amazon Resource Name (ARN) of a role with permission to access the data source for
* the ML model being described. </p>
*/
RoleArn?: string;
/**
* <p>The configuration is the <code>TargetSamplingRate</code>, which is the sampling rate of
* the data after post processing by
* Amazon Lookout for Equipment. For example, if you provide data that
* has been collected at a 1 second level and you want the system to resample
* the data at a 1 minute rate before training, the <code>TargetSamplingRate</code> is 1 minute.</p>
* <p>When providing a value for the <code>TargetSamplingRate</code>, you must
* attach the prefix "PT" to the rate you want. The value for a 1 second rate
* is therefore <i>PT1S</i>, the value for a 15 minute rate
* is <i>PT15M</i>, and the value for a 1 hour rate
* is <i>PT1H</i>
* </p>
*/
DataPreProcessingConfiguration?: DataPreProcessingConfiguration;
/**
* <p>Specifies the current status of the model being described. Status describes the status
* of the most recent action of the model. </p>
*/
Status?: ModelStatus | string;
/**
* <p>Indicates the time at which the training of the ML model began. </p>
*/
TrainingExecutionStartTime?: Date;
/**
* <p>Indicates the time at which the training of the ML model was completed. </p>
*/
TrainingExecutionEndTime?: Date;
/**
* <p>If the training of the ML model failed, this indicates the reason for that failure.
* </p>
*/
FailedReason?: string;
/**
* <p>The Model Metrics show an aggregated summary of the model's performance within the evaluation time
* range. This is the JSON content of the metrics created when evaluating the model. </p>
*/
ModelMetrics?: __LazyJsonString | string;
/**
* <p>Indicates the last time the ML model was updated. The type of update is not specified.
* </p>
*/
LastUpdatedTime?: Date;
/**
* <p>Indicates the time and date at which the ML model was created. </p>
*/
CreatedAt?: Date;
/**
* <p>Provides the identifier of the KMS key used to encrypt model data by Amazon Lookout for Equipment. </p>
*/
ServerSideKmsKeyId?: string;
/**
* <p>Indicates that the asset associated with this sensor has been shut off. As long as this condition is met, Lookout for Equipment will not use data from this asset for training, evaluation, or inference.</p>
*/
OffCondition?: string;
}
export namespace DescribeModelResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeModelResponse): any => ({
...obj,
});
}
export interface ListDataIngestionJobsRequest {
/**
* <p>The name of the dataset being used for the data ingestion job. </p>
*/
DatasetName?: string;
/**
* <p> An opaque pagination token indicating where to continue the listing of data ingestion
* jobs. </p>
*/
NextToken?: string;
/**
* <p> Specifies the maximum number of data ingestion jobs to list. </p>
*/
MaxResults?: number;
/**
* <p>Indicates the status of the data ingestion job. </p>
*/
Status?: IngestionJobStatus | string;
}
export namespace ListDataIngestionJobsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDataIngestionJobsRequest): any => ({
...obj,
});
}
/**
* <p>Provides information about a specified data ingestion job, including dataset
* information, data ingestion configuration, and status. </p>
*/
export interface DataIngestionJobSummary {
/**
* <p>Indicates the job ID of the data ingestion job. </p>
*/
JobId?: string;
/**
* <p>The name of the dataset used for the data ingestion job. </p>
*/
DatasetName?: string;
/**
* <p>The Amazon Resource Name (ARN) of the dataset used in the data ingestion job. </p>
*/
DatasetArn?: string;
/**
* <p> Specifies information for the input data for the data inference job, including data S3
* location parameters. </p>
*/
IngestionInputConfiguration?: IngestionInputConfiguration;
/**
* <p>Indicates the status of the data ingestion job. </p>
*/
Status?: IngestionJobStatus | string;
}
export namespace DataIngestionJobSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DataIngestionJobSummary): any => ({
...obj,
});
}
export interface ListDataIngestionJobsResponse {
/**
* <p> An opaque pagination token indicating where to continue the listing of data ingestion
* jobs. </p>
*/
NextToken?: string;
/**
* <p>Specifies information about the specific data ingestion job, including dataset name and
* status. </p>
*/
DataIngestionJobSummaries?: DataIngestionJobSummary[];
}
export namespace ListDataIngestionJobsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDataIngestionJobsResponse): any => ({
...obj,
});
}
export interface ListDatasetsRequest {
/**
* <p> An opaque pagination token indicating where to continue the listing of datasets.
* </p>
*/
NextToken?: string;
/**
* <p> Specifies the maximum number of datasets to list. </p>
*/
MaxResults?: number;
/**
* <p>The beginning of the name of the datasets to be listed. </p>
*/
DatasetNameBeginsWith?: string;
}
export namespace ListDatasetsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDatasetsRequest): any => ({
...obj,
});
}
/**
* <p>Contains information about the specific data set, including name, ARN, and status.
* </p>
*/
export interface DatasetSummary {
/**
* <p>The name of the dataset. </p>
*/
DatasetName?: string;
/**
* <p>The Amazon Resource Name (ARN) of the specified dataset. </p>
*/
DatasetArn?: string;
/**
* <p>Indicates the status of the dataset. </p>
*/
Status?: DatasetStatus | string;
/**
* <p>The time at which the dataset was created in Amazon Lookout for Equipment. </p>
*/
CreatedAt?: Date;
}
export namespace DatasetSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DatasetSummary): any => ({
...obj,
});
}
export interface ListDatasetsResponse {
/**
* <p> An opaque pagination token indicating where to continue the listing of datasets.
* </p>
*/
NextToken?: string;
/**
* <p>Provides information about the specified dataset, including creation time, dataset ARN,
* and status. </p>
*/
DatasetSummaries?: DatasetSummary[];
}
export namespace ListDatasetsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDatasetsResponse): any => ({
...obj,
});
}
export enum InferenceExecutionStatus {
FAILED = "FAILED",
IN_PROGRESS = "IN_PROGRESS",
SUCCESS = "SUCCESS",
}
export interface ListInferenceExecutionsRequest {
/**
* <p>An opaque pagination token indicating where to continue the listing of inference
* executions.</p>
*/
NextToken?: string;
/**
* <p>Specifies the maximum number of inference executions to list. </p>
*/
MaxResults?: number;
/**
* <p>The name of the inference scheduler for the inference execution listed. </p>
*/
InferenceSchedulerName: string | undefined;
/**
* <p>The time reference in the inferenced dataset after which Amazon Lookout for Equipment started the
* inference execution. </p>
*/
DataStartTimeAfter?: Date;
/**
* <p>The time reference in the inferenced dataset before which Amazon Lookout for Equipment stopped the
* inference execution. </p>
*/
DataEndTimeBefore?: Date;
/**
* <p>The status of the inference execution. </p>
*/
Status?: InferenceExecutionStatus | string;
}
export namespace ListInferenceExecutionsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListInferenceExecutionsRequest): any => ({
...obj,
});
}
/**
* <p>Contains information about an S3 bucket. </p>
*/
export interface S3Object {
/**
* <p>The name of the specific S3 bucket. </p>
*/
Bucket: string | undefined;
/**
* <p>The AWS Key Management Service (AWS KMS) key being used to encrypt the S3 object.
* Without this key, data in the bucket is not accessible. </p>
*/
Key: string | undefined;
}
export namespace S3Object {
/**
* @internal
*/
export const filterSensitiveLog = (obj: S3Object): any => ({
...obj,
});
}
/**
* <p>Contains information about the specific inference execution, including input and output
* data configuration, inference scheduling information, status, and so on. </p>
*/
export interface InferenceExecutionSummary {
/**
* <p>The name of the ML model being used for the inference execution. </p>
*/
ModelName?: string;
/**
* <p>The Amazon Resource Name (ARN) of the ML model used for the inference execution. </p>
*/
ModelArn?: string;
/**
* <p>The name of the inference scheduler being used for the inference execution. </p>
*/
InferenceSchedulerName?: string;
/**
* <p> The Amazon Resource Name (ARN) of the inference scheduler being used for the inference
* execution. </p>
*/
InferenceSchedulerArn?: string;
/**
* <p>Indicates the start time at which the inference scheduler began the specific inference
* execution. </p>
*/
ScheduledStartTime?: Date;
/**
* <p>Indicates the time reference in the dataset at which the inference execution began.
* </p>
*/
DataStartTime?: Date;
/**
* <p>Indicates the time reference in the dataset at which the inference execution stopped.
* </p>
*/
DataEndTime?: Date;
/**
* <p> Specifies configuration information for the input data for the inference scheduler,
* including delimiter, format, and dataset location. </p>
*/
DataInputConfiguration?: InferenceInputConfiguration;
/**
* <p> Specifies configuration information for the output results from for the inference
* execution, including the output S3 location. </p>
*/
DataOutputConfiguration?: InferenceOutputConfiguration;
/**
* <p>
* </p>
*/
CustomerResultObject?: S3Object;
/**
* <p>Indicates the status of the inference execution. </p>
*/
Status?: InferenceExecutionStatus | string;
/**
* <p> Specifies the reason for failure when an inference execution has failed. </p>
*/
FailedReason?: string;
}
export namespace InferenceExecutionSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InferenceExecutionSummary): any => ({
...obj,
});
}
export interface ListInferenceExecutionsResponse {
/**
* <p> An opaque pagination token indicating where to continue the listing of inference
* executions. </p>
*/
NextToken?: string;
/**
* <p>Provides an array of information about the individual inference executions returned from
* the <code>ListInferenceExecutions</code> operation, including model used, inference
* scheduler, data configuration, and so on. </p>
*/
InferenceExecutionSummaries?: InferenceExecutionSummary[];
}
export namespace ListInferenceExecutionsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListInferenceExecutionsResponse): any => ({
...obj,
});
}
export interface ListInferenceSchedulersRequest {
/**
* <p> An opaque pagination token indicating where to continue the listing of inference
* schedulers. </p>
*/
NextToken?: string;
/**
* <p> Specifies the maximum number of inference schedulers to list. </p>
*/
MaxResults?: number;
/**
* <p>The beginning of the name of the inference schedulers to be listed. </p>
*/
InferenceSchedulerNameBeginsWith?: string;
/**
* <p>The name of the ML model used by the inference scheduler to be listed. </p>
*/
ModelName?: string;
}
export namespace ListInferenceSchedulersRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListInferenceSchedulersRequest): any => ({
...obj,
});
}
/**
* <p>Contains information about the specific inference scheduler, including data delay
* offset, model name and ARN, status, and so on. </p>
*/
export interface InferenceSchedulerSummary {
/**
* <p>The name of the ML model used for the inference scheduler. </p>
*/
ModelName?: string;
/**
* <p> The Amazon Resource Name (ARN) of the ML model used by the inference scheduler. </p>
*/
ModelArn?: string;
/**
* <p>The name of the inference scheduler. </p>
*/
InferenceSchedulerName?: string;
/**
* <p> The Amazon Resource Name (ARN) of the inference scheduler. </p>
*/
InferenceSchedulerArn?: string;
/**
* <p>Indicates the status of the inference scheduler. </p>
*/
Status?: InferenceSchedulerStatus | string;
/**
* <p>A period of time (in minutes) by which inference on the data is delayed after the data
* starts. For instance, if an offset delay time of five minutes was selected, inference will
* not begin on the data until the first data measurement after the five minute mark. For example, if
* five minutes is selected, the inference scheduler will wake up at the configured frequency with the
* additional five minute delay time to check the customer S3 bucket. The customer can upload data at
* the same frequency and they don't need to stop and restart the scheduler when uploading new data.
* </p>
*/
DataDelayOffsetInMinutes?: number;
/**
* <p>How often data is uploaded to the source S3 bucket for the input data. This value is the
* length of time between data uploads. For instance, if you select 5 minutes, Amazon Lookout for Equipment
* will upload the real-time data to the source bucket once every 5 minutes. This frequency also
* determines how often Amazon Lookout for Equipment starts a scheduled inference on your data. In this
* example, it starts once every 5 minutes. </p>
*/
DataUploadFrequency?: DataUploadFrequency | string;
}
export namespace InferenceSchedulerSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InferenceSchedulerSummary): any => ({
...obj,
});
}
export interface ListInferenceSchedulersResponse {
/**
* <p> An opaque pagination token indicating where to continue the listing of inference
* schedulers. </p>
*/
NextToken?: string;
/**
* <p>Provides information about the specified inference scheduler, including data upload
* frequency, model name and ARN, and status. </p>
*/
InferenceSchedulerSummaries?: InferenceSchedulerSummary[];
}
export namespace ListInferenceSchedulersResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListInferenceSchedulersResponse): any => ({
...obj,
});
}
export interface ListModelsRequest {
/**
* <p> An opaque pagination token indicating where to continue the listing of ML models.
* </p>
*/
NextToken?: string;
/**
* <p> Specifies the maximum number of ML models to list. </p>
*/
MaxResults?: number;
/**
* <p>The status of the ML model. </p>
*/
Status?: ModelStatus | string;
/**
* <p>The beginning of the name of the ML models being listed. </p>
*/
ModelNameBeginsWith?: string;
/**
* <p>The beginning of the name of the dataset of the ML models to be listed. </p>
*/
DatasetNameBeginsWith?: string;
}
export namespace ListModelsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListModelsRequest): any => ({
...obj,
});
}
/**
* <p>Provides information about the specified ML model, including dataset and model names and
* ARNs, as well as status. </p>
*/
export interface ModelSummary {
/**
* <p>The name of the ML model. </p>
*/
ModelName?: string;
/**
* <p> The Amazon Resource Name (ARN) of the ML model. </p>
*/
ModelArn?: string;
/**
* <p>The name of the dataset being used for the ML model. </p>
*/
DatasetName?: string;
/**
* <p> The Amazon Resource Name (ARN) of the dataset used to create the model. </p>
*/
DatasetArn?: string;
/**
* <p>Indicates the status of the ML model. </p>
*/
Status?: ModelStatus | string;
/**
* <p>The time at which the specific model was created. </p>
*/
CreatedAt?: Date;
}
export namespace ModelSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ModelSummary): any => ({
...obj,
});
}
export interface ListModelsResponse {
/**
* <p> An opaque pagination token indicating where to continue the listing of ML models.
* </p>
*/
NextToken?: string;
/**
* <p>Provides information on the specified model, including created time, model and dataset
* ARNs, and status. </p>
*/
ModelSummaries?: ModelSummary[];
}
export namespace ListModelsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListModelsResponse): any => ({
...obj,
});
}
export interface ListTagsForResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) of the resource (such as the dataset or model) that is
* the focus of the <code>ListTagsForResource</code> operation. </p>
*/
ResourceArn: string | undefined;
}
export namespace ListTagsForResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({
...obj,
});
}
export interface ListTagsForResourceResponse {
/**
* <p> Any tags associated with the resource. </p>
*/
Tags?: Tag[];
}
export namespace ListTagsForResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({
...obj,
});
}
export interface StartDataIngestionJobRequest {
/**
* <p>The name of the dataset being used by the data ingestion job. </p>
*/
DatasetName: string | undefined;
/**
* <p> Specifies information for the input data for the data ingestion job, including dataset
* S3 location. </p>
*/
IngestionInputConfiguration: IngestionInputConfiguration | undefined;
/**
* <p> The Amazon Resource Name (ARN) of a role with permission to access the data source for
* the data ingestion job. </p>
*/
RoleArn: string | undefined;
/**
* <p> A unique identifier for the request. If you do not set the client request token, Amazon
* Lookout for Equipment generates one. </p>
*/
ClientToken?: string;
}
export namespace StartDataIngestionJobRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StartDataIngestionJobRequest): any => ({
...obj,
});
}
export interface StartDataIngestionJobResponse {
/**
* <p>Indicates the job ID of the data ingestion job. </p>
*/
JobId?: string;
/**
* <p>Indicates the status of the <code>StartDataIngestionJob</code> operation. </p>
*/
Status?: IngestionJobStatus | string;
}
export namespace StartDataIngestionJobResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StartDataIngestionJobResponse): any => ({
...obj,
});
}
export interface StartInferenceSchedulerRequest {
/**
* <p>The name of the inference scheduler to be started. </p>
*/
InferenceSchedulerName: string | undefined;
}
export namespace StartInferenceSchedulerRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StartInferenceSchedulerRequest): any => ({
...obj,
});
}
export interface StartInferenceSchedulerResponse {
/**
* <p>The Amazon Resource Name (ARN) of the ML model being used by the inference scheduler.
* </p>
*/
ModelArn?: string;
/**
* <p>The name of the ML model being used by the inference scheduler. </p>
*/
ModelName?: string;
/**
* <p>The name of the inference scheduler being started. </p>
*/
InferenceSchedulerName?: string;
/**
* <p>The Amazon Resource Name (ARN) of the inference scheduler being started. </p>
*/
InferenceSchedulerArn?: string;
/**
* <p>Indicates the status of the inference scheduler. </p>
*/
Status?: InferenceSchedulerStatus | string;
}
export namespace StartInferenceSchedulerResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StartInferenceSchedulerResponse): any => ({
...obj,
});
}
export interface StopInferenceSchedulerRequest {
/**
* <p>The name of the inference scheduler to be stopped. </p>
*/
InferenceSchedulerName: string | undefined;
}
export namespace StopInferenceSchedulerRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StopInferenceSchedulerRequest): any => ({
...obj,
});
}
export interface StopInferenceSchedulerResponse {
/**
* <p>The Amazon Resource Name (ARN) of the ML model used by the inference scheduler being
* stopped. </p>
*/
ModelArn?: string;
/**
* <p>The name of the ML model used by the inference scheduler being stopped. </p>
*/
ModelName?: string;
/**
* <p>The name of the inference scheduler being stopped. </p>
*/
InferenceSchedulerName?: string;
/**
* <p>The Amazon Resource Name (ARN) of the inference schedule being stopped. </p>
*/
InferenceSchedulerArn?: string;
/**
* <p>Indicates the status of the inference scheduler. </p>
*/
Status?: InferenceSchedulerStatus | string;
}
export namespace StopInferenceSchedulerResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StopInferenceSchedulerResponse): any => ({
...obj,
});
}
export interface TagResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) of the specific resource to which the tag should be
* associated. </p>
*/
ResourceArn: string | undefined;
/**
* <p>The tag or tags to be associated with a specific resource. Both the tag key and value
* are specified. </p>
*/
Tags: Tag[] | undefined;
}
export namespace TagResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TagResourceRequest): any => ({
...obj,
});
}
export interface TagResourceResponse {}
export namespace TagResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TagResourceResponse): any => ({
...obj,
});
}
export interface UntagResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) of the resource to which the tag is currently associated.
* </p>
*/
ResourceArn: string | undefined;
/**
* <p>Specifies the key of the tag to be removed from a specified resource. </p>
*/
TagKeys: string[] | undefined;
}
export namespace UntagResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({
...obj,
});
}
export interface UntagResourceResponse {}
export namespace UntagResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UntagResourceResponse): any => ({
...obj,
});
}
export interface UpdateInferenceSchedulerRequest {
/**
* <p>The name of the inference scheduler to be updated. </p>
*/
InferenceSchedulerName: string | undefined;
/**
* <p> A period of time (in minutes) by which inference on the data is delayed after the data
* starts. For instance, if you select an offset delay time of five minutes, inference will
* not begin on the data until the first data measurement after the five minute mark. For example, if
* five minutes is selected, the inference scheduler will wake up at the configured frequency with the
* additional five minute delay time to check the customer S3 bucket. The customer can upload data at
* the same frequency and they don't need to stop and restart the scheduler when uploading new data.</p>
*/
DataDelayOffsetInMinutes?: number;
/**
* <p>How often data is uploaded to the source S3 bucket for the input data. The value chosen
* is the length of time between data uploads. For instance, if you select 5 minutes, Amazon
* Lookout for Equipment will upload the real-time data to the source bucket once every 5 minutes. This frequency
* also determines how often Amazon Lookout for Equipment starts a scheduled inference on your data. In this
* example, it starts once every 5 minutes. </p>
*/
DataUploadFrequency?: DataUploadFrequency | string;
/**
* <p> Specifies information for the input data for the inference scheduler, including
* delimiter, format, and dataset location. </p>
*/
DataInputConfiguration?: InferenceInputConfiguration;
/**
* <p> Specifies information for the output results from the inference scheduler, including the output S3 location. </p>
*/
DataOutputConfiguration?: InferenceOutputConfiguration;
/**
* <p> The Amazon Resource Name (ARN) of a role with permission to access the data source for
* the inference scheduler. </p>
*/
RoleArn?: string;
}
export namespace UpdateInferenceSchedulerRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateInferenceSchedulerRequest): any => ({
...obj,
});
} | the_stack |
'use strict';
import nls = require('vs/nls');
import { TPromise } from 'vs/base/common/winjs.base';
import Strings = require('vs/base/common/strings');
import Collections = require('vs/base/common/collections');
import { CommandOptions, resolveCommandOptions, Source, ErrorData } from 'vs/base/common/processes';
import { LineProcess } from 'vs/base/node/processes';
import { IFileService } from 'vs/platform/files/common/files';
import { SystemVariables } from 'vs/workbench/parts/lib/node/systemVariables';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import * as FileConfig from './processRunnerConfiguration';
let build: string = 'build';
let test: string = 'test';
let defaultValue: string = 'default';
interface TaskInfo {
index: number;
exact: number;
}
interface TaskInfos {
build: TaskInfo;
test: TaskInfo;
}
interface TaskDetectorMatcher {
init();
match(tasks: string[], line:string);
}
interface DetectorConfig {
matcher: TaskDetectorMatcher;
arg: string;
}
class RegexpTaskMatcher implements TaskDetectorMatcher {
private regexp: RegExp;
constructor(regExp:RegExp) {
this.regexp = regExp;
}
init() {
}
match(tasks: string[], line: string) {
let matches = this.regexp.exec(line);
if (matches && matches.length > 0) {
tasks.push(matches[1]);
}
}
}
class GruntTaskMatcher implements TaskDetectorMatcher {
private tasksStart: boolean;
private tasksEnd: boolean;
private descriptionOffset: number;
init() {
this.tasksStart = false;
this.tasksEnd = false;
this.descriptionOffset = null;
}
match(tasks: string[], line: string) {
// grunt lists tasks as follows (description is wrapped into a new line if too long):
// ...
// Available tasks
// uglify Minify files with UglifyJS. *
// jshint Validate files with JSHint. *
// test Alias for "jshint", "qunit" tasks.
// default Alias for "jshint", "qunit", "concat", "uglify" tasks.
// long Alias for "eslint", "qunit", "browserify", "sass",
// "autoprefixer", "uglify", tasks.
//
// Tasks run in the order specified
if (!this.tasksStart && !this.tasksEnd) {
if (line.indexOf('Available tasks') === 0) {
this.tasksStart = true;
}
}
else if (this.tasksStart && !this.tasksEnd) {
if (line.indexOf('Tasks run in the order specified') === 0) {
this.tasksEnd = true;
} else {
if (this.descriptionOffset === null) {
this.descriptionOffset = line.match(/\S \S/).index + 1;
}
let taskName = line.substr(0,this.descriptionOffset).trim();
if (taskName.length > 0) {
tasks.push(taskName);
}
}
}
}
}
export interface DetectorResult {
config: FileConfig.ExternalTaskRunnerConfiguration;
stdout: string[];
stderr: string[];
}
export class ProcessRunnerDetector {
private static Version: string = '0.1.0';
private static SupportedRunners: Collections.IStringDictionary<boolean> = {
'gulp': true,
'jake': true,
'grunt': true
};
private static TaskMatchers: Collections.IStringDictionary<DetectorConfig> = {
'gulp': { matcher: new RegexpTaskMatcher(/^(.*)$/), arg: '--tasks-simple' },
'jake': { matcher: new RegexpTaskMatcher(/^jake\s+([^\s]+)\s/), arg: '--tasks' },
'grunt': { matcher: new GruntTaskMatcher(), arg: '--help' },
};
public static supports(runner: string): boolean {
return ProcessRunnerDetector.SupportedRunners[runner];
}
private static detectorConfig(runner:string): DetectorConfig {
return ProcessRunnerDetector.TaskMatchers[runner];
}
private static DefaultProblemMatchers: string[] = ['$lessCompile', '$tsc', '$jshint'];
private fileService: IFileService;
private contextService: IWorkspaceContextService;
private variables: SystemVariables;
private taskConfiguration: FileConfig.ExternalTaskRunnerConfiguration;
private _stderr: string[];
private _stdout: string[];
constructor(fileService: IFileService, contextService: IWorkspaceContextService, variables:SystemVariables, config: FileConfig.ExternalTaskRunnerConfiguration = null) {
this.fileService = fileService;
this.contextService = contextService;
this.variables = variables;
this.taskConfiguration = config;
this._stderr = [];
this._stdout = [];
}
public get stderr(): string[] {
return this._stderr;
}
public get stdout(): string[] {
return this._stdout;
}
public detect(list: boolean = false, detectSpecific?: string): TPromise<DetectorResult> {
if (this.taskConfiguration && this.taskConfiguration.command && ProcessRunnerDetector.supports(this.taskConfiguration.command)) {
let config = ProcessRunnerDetector.detectorConfig(this.taskConfiguration.command);
let args = (this.taskConfiguration.args || []).concat(config.arg);
let options: CommandOptions = this.taskConfiguration.options ? resolveCommandOptions(this.taskConfiguration.options, this.variables) : { cwd: this.variables.workspaceRoot };
let isShellCommand = !!this.taskConfiguration.isShellCommand;
return this.runDetection(
new LineProcess(this.taskConfiguration.command, this.variables.resolve(args), isShellCommand, options),
this.taskConfiguration.command, isShellCommand, config.matcher, ProcessRunnerDetector.DefaultProblemMatchers, list);
} else {
if (detectSpecific) {
let detectorPromise: TPromise<DetectorResult>;
if ('gulp' === detectSpecific) {
detectorPromise = this.tryDetectGulp(list);
} else if ('jake' === detectSpecific) {
detectorPromise = this.tryDetectJake(list);
} else if ('grunt' === detectSpecific) {
detectorPromise = this.tryDetectGrunt(list);
}
return detectorPromise.then((value) => {
if (value) {
return value;
} else {
return { config: null, stdout: this.stdout, stderr: this.stderr };
}
});
} else {
return this.tryDetectGulp(list).then((value) => {
if (value) {
return value;
}
return this.tryDetectJake(list).then((value) => {
if (value) {
return value;
}
return this.tryDetectGrunt(list).then((value) => {
if (value) {
return value;
}
return { config: null, stdout: this.stdout, stderr: this.stderr };
});
});
});
}
}
}
private tryDetectGulp(list:boolean): TPromise<{ config: FileConfig.ExternalTaskRunnerConfiguration; stderr: string[]; }> {
return this.fileService.resolveFile(this.contextService.toResource('gulpfile.js')).then((stat) => {
let config = ProcessRunnerDetector.detectorConfig('gulp');
let process = new LineProcess('gulp', [config.arg, '--no-color'], true, {cwd: this.variables.workspaceRoot});
return this.runDetection(process, 'gulp', true, config.matcher, ProcessRunnerDetector.DefaultProblemMatchers, list);
}, (err: any): FileConfig.ExternalTaskRunnerConfiguration => {
return null;
});
}
private tryDetectGrunt(list:boolean): TPromise<{ config: FileConfig.ExternalTaskRunnerConfiguration; stderr: string[]; }> {
return this.fileService.resolveFile(this.contextService.toResource('Gruntfile.js')).then((stat) => {
let config = ProcessRunnerDetector.detectorConfig('grunt');
let process = new LineProcess('grunt', [config.arg, '--no-color'], true, {cwd: this.variables.workspaceRoot});
return this.runDetection(process, 'grunt', true, config.matcher, ProcessRunnerDetector.DefaultProblemMatchers, list);
}, (err: any): FileConfig.ExternalTaskRunnerConfiguration => {
return null;
});
}
private tryDetectJake(list:boolean): TPromise<{ config: FileConfig.ExternalTaskRunnerConfiguration; stderr: string[]; }> {
let run = () => {
let config = ProcessRunnerDetector.detectorConfig('jake');
let process = new LineProcess('jake', [config.arg], true, {cwd: this.variables.workspaceRoot});
return this.runDetection(process, 'jake', true, config.matcher, ProcessRunnerDetector.DefaultProblemMatchers, list);
};
return this.fileService.resolveFile(this.contextService.toResource('Jakefile')).then((stat) => {
return run();
}, (err: any) => {
return this.fileService.resolveFile(this.contextService.toResource('Jakefile.js')).then((stat) => {
return run();
}, (err: any): FileConfig.ExternalTaskRunnerConfiguration => {
return null;
});
});
}
private runDetection(process: LineProcess, command: string, isShellCommand: boolean, matcher: TaskDetectorMatcher, problemMatchers: string[], list: boolean): TPromise<DetectorResult> {
let tasks:string[] = [];
matcher.init();
return process.start().then((success) => {
if (tasks.length === 0) {
if (success.cmdCode !== 0) {
if (command === 'gulp') {
this._stderr.push(nls.localize('TaskSystemDetector.noGulpTasks', 'Running gulp --tasks-simple didn\'t list any tasks. Did you run npm install?'));
} else if (command === 'jake') {
this._stderr.push(nls.localize('TaskSystemDetector.noJakeTasks', 'Running jake --tasks didn\'t list any tasks. Did you run npm install?'));
}
}
return { config: null, stdout: this._stdout, stderr: this._stderr };
}
let result: FileConfig.ExternalTaskRunnerConfiguration = {
version: ProcessRunnerDetector.Version,
command: command,
isShellCommand: isShellCommand
};
// Hack. We need to remove this.
if (command === 'gulp') {
result.args = ['--no-color'];
}
result.tasks = this.createTaskDescriptions(tasks, problemMatchers, list);
return { config: result, stdout: this._stdout, stderr: this._stderr };
}, (err: ErrorData) => {
let error = err.error;
if ((<any>error).code === 'ENOENT') {
if (command === 'gulp') {
this._stderr.push(nls.localize('TaskSystemDetector.noGulpProgram', 'Gulp is not installed on your system. Run npm install -g gulp to install it.'));
} else if (command === 'jake') {
this._stderr.push(nls.localize('TaskSystemDetector.noJakeProgram', 'Jake is not installed on your system. Run npm install -g jake to install it.'));
} else if (command === 'grunt') {
this._stderr.push(nls.localize('TaskSystemDetector.noGruntProgram', 'Grunt is not installed on your system. Run npm install -g grunt to install it.'));
}
} else {
this._stderr.push(nls.localize('TaskSystemDetector.noProgram', 'Program {0} was not found. Message is {1}', command, error.message));
}
return { config: null, stdout: this._stdout, stderr: this._stderr };
}, (progress) => {
if (progress.source === Source.stderr) {
this._stderr.push(progress.line);
return;
}
let line = Strings.removeAnsiEscapeCodes(progress.line);
let matches = matcher.match(tasks, line);
if (matches && matches.length > 0) {
tasks.push(matches[1]);
}
});
}
private createTaskDescriptions(tasks: string[], problemMatchers: string[], list: boolean):FileConfig.TaskDescription[] {
let taskConfigs: FileConfig.TaskDescription[] = [];
if (list) {
tasks.forEach((task) => {
taskConfigs.push({
taskName: task,
args: [],
isWatching: false
});
});
} else {
let taskInfos: TaskInfos = {
build: { index: -1, exact: -1 },
test: { index: -1, exact: -1 }
};
tasks.forEach((task, index) => {
this.testBuild(taskInfos.build, task, index);
this.testTest(taskInfos.test, task, index);
});
if (taskInfos.build.index !== -1) {
let name = tasks[taskInfos.build.index];
this._stdout.push(nls.localize('TaskSystemDetector.buildTaskDetected','Build task named \'{0}\' detected.', name));
taskConfigs.push({
taskName: name,
args: [],
isBuildCommand: true,
isWatching: false,
problemMatcher: problemMatchers
});
}
if (taskInfos.test.index !== -1) {
let name = tasks[taskInfos.test.index];
this._stdout.push(nls.localize('TaskSystemDetector.testTaskDetected','Test task named \'{0}\' detected.', name));
taskConfigs.push({
taskName: name,
args: [],
isTestCommand: true
});
}
}
return taskConfigs;
}
private testBuild(taskInfo: TaskInfo, taskName: string, index: number):void {
if (taskName === build) {
taskInfo.index = index;
taskInfo.exact = 4;
} else if ((Strings.startsWith(taskName, build) || Strings.endsWith(taskName, build)) && taskInfo.exact < 4) {
taskInfo.index = index;
taskInfo.exact = 3;
} else if (taskName.indexOf(build) !== -1 && taskInfo.exact < 3) {
taskInfo.index = index;
taskInfo.exact = 2;
} else if (taskName === defaultValue && taskInfo.exact < 2) {
taskInfo.index = index;
taskInfo.exact = 1;
}
}
private testTest(taskInfo: TaskInfo, taskName: string, index: number):void {
if (taskName === test) {
taskInfo.index = index;
taskInfo.exact = 3;
} else if ((Strings.startsWith(taskName, test) || Strings.endsWith(taskName, test)) && taskInfo.exact < 3) {
taskInfo.index = index;
taskInfo.exact = 2;
} else if (taskName.indexOf(test) !== -1 && taskInfo.exact < 2) {
taskInfo.index = index;
taskInfo.exact = 1;
}
}
} | the_stack |
import moment from "moment"
import { pageable } from "relay-cursor-paging"
import {
connectionFromArraySlice,
connectionFromArray,
connectionDefinitions,
} from "graphql-relay"
import {
isExisty,
exclude,
existyValue,
convertConnectionArgsToGravityArgs,
} from "lib/helpers"
import { HTTPError } from "lib/HTTPError"
import numeral from "./fields/numeral"
import { dateRange, exhibitionStatus } from "lib/date"
import cached from "./fields/cached"
import date from "./fields/date"
import { markdown } from "./fields/markdown"
import Artist from "./artist"
import { PartnerType } from "./partner"
import { ExternalPartnerType } from "./external_partner"
import Fair from "./fair"
import Artwork, { artworkConnection } from "./artwork"
import Location from "./location"
import Image, { getDefault, normalizeImageData } from "./image"
import PartnerShowEventType from "./partner_show_event"
import { connectionWithCursorInfo } from "schema/v1/fields/pagination"
import { filterArtworksWithParams } from "schema/v1/filter_artworks"
import { NodeInterface, SlugAndInternalIDFields } from "./object_identification"
import {
GraphQLObjectType,
GraphQLString,
GraphQLNonNull,
GraphQLList,
GraphQLInt,
GraphQLBoolean,
GraphQLUnionType,
GraphQLFieldConfig,
GraphQLFieldConfigArgumentMap,
} from "graphql"
import { allViaLoader } from "lib/all"
import { totalViaLoader } from "lib/total"
import { find, flatten } from "lodash"
import PartnerShowSorts from "./sorts/partner_show_sorts"
import EventStatus from "./input_fields/event_status"
import { LOCAL_DISCOVERY_RADIUS_KM } from "./city/constants"
import { ResolverContext } from "types/graphql"
import followArtistsResolver from "lib/shared_resolvers/followedArtistsResolver"
import { deprecate } from "lib/deprecation"
import { decodeUnverifiedJWT } from "lib/decodeUnverifiedJWT"
const FollowArtistType = new GraphQLObjectType<any, ResolverContext>({
name: "ShowFollowArtist",
fields: () => ({
artist: {
type: Artist.type,
},
}),
})
const kind = ({ artists, fair, artists_without_artworks, group }) => {
if (isExisty(fair)) return "fair"
if (
group ||
artists.length > 1 ||
(artists_without_artworks && artists_without_artworks.length > 1)
) {
return "group"
}
if (
artists.length === 1 ||
(artists_without_artworks && artists_without_artworks.length === 1)
) {
return "solo"
}
}
const artworksArgs: GraphQLFieldConfigArgumentMap = {
exclude: {
type: new GraphQLList(GraphQLString),
description:
"List of artwork IDs to exclude from the response (irrespective of size)",
},
for_sale: {
type: GraphQLBoolean,
defaultValue: false,
},
published: {
type: GraphQLBoolean,
defaultValue: true,
},
}
export const ShowType = new GraphQLObjectType<any, ResolverContext>({
name: "Show",
interfaces: [NodeInterface],
fields: () => ({
...SlugAndInternalIDFields,
cached,
artists: {
description: "The Artists presenting in this show",
type: new GraphQLList(Artist.type),
resolve: ({ artists }) => {
return artists
},
},
artworks: {
description: "The artworks featured in this show",
deprecationReason: deprecate({
inVersion: 2,
preferUsageOf: "artworks_connection",
}),
type: new GraphQLList(Artwork.type),
args: {
...artworksArgs,
all: {
type: GraphQLBoolean,
default: false,
},
page: {
type: GraphQLInt,
defaultValue: 1,
},
size: {
type: GraphQLInt,
description: "Number of artworks to return",
defaultValue: 25,
},
},
resolve: (show, options, { partnerShowArtworksLoader }) => {
let fetch: Promise<any>
if (options.all) {
fetch = allViaLoader(partnerShowArtworksLoader, {
path: {
partner_id: show.partner.id,
show_id: show.id,
},
params: options,
})
} else {
fetch = partnerShowArtworksLoader(
{
partner_id: show.partner.id,
show_id: show.id,
},
options
).then(({ body }) => body)
}
return fetch.then(exclude(options.exclude, "id"))
},
},
artworks_connection: {
description: "The artworks featured in the show",
type: artworkConnection,
args: pageable(artworksArgs),
resolve: (show, options, { partnerShowArtworksLoader }) => {
const loaderOptions = {
partner_id: show.partner.id,
show_id: show.id,
}
const { page, size, offset } = convertConnectionArgsToGravityArgs(
options
)
interface GravityArgs {
exclude_ids?: string[]
page: number
size: number
total_count: boolean
}
const gravityArgs: GravityArgs = {
page,
size,
total_count: true,
}
if (options.exclude) {
gravityArgs.exclude_ids = flatten([options.exclude])
}
return partnerShowArtworksLoader(loaderOptions, gravityArgs).then(
({ body, headers }) => {
return connectionFromArraySlice(body, options, {
arrayLength: parseInt(headers["x-total-count"] || "0", 10),
sliceStart: offset,
})
}
)
},
},
artists_without_artworks: {
description: "Artists inside the show who do not have artworks present",
type: new GraphQLList(Artist.type),
resolve: ({ artists_without_artworks }) => artists_without_artworks,
},
artists_grouped_by_name: {
description: "Artists in the show grouped by last name",
type: new GraphQLList(
new GraphQLObjectType<any, ResolverContext>({
name: "ArtistGroup",
fields: {
letter: {
type: GraphQLString,
description: "Letter artists group belongs to",
},
items: {
type: new GraphQLList(Artist.type),
description: "Artists sorted by last name",
},
},
})
),
resolve: ({ artists }) => {
const groups: {
[letter: string]: { letter: string; items: [string] }
} = {}
const sortedArtists = artists.sort((a, b) => {
const aNames = a.name.split(" ")
const bNames = b.name.split(" ")
const aLastName = aNames[aNames.length - 1]
const bLastName = bNames[bNames.length - 1]
if (aLastName < bLastName) return -1
if (aLastName > bLastName) return 1
return 0
})
for (const artist of sortedArtists) {
const names = artist.name.split(" ")
const lastName = names[names.length - 1]
const letter = lastName.substring(0, 1).toUpperCase()
if (groups[letter] !== undefined) {
groups[letter].items.push(artist)
} else {
groups[letter] = {
letter,
items: [artist],
}
}
}
return Object.values(groups)
},
},
city: {
description:
"The general city, derived from a fair location, a show location or a potential city",
type: GraphQLString,
resolve: ({ fair, location, partner_city }) => {
if (fair && fair.location && fair.location.city) {
return fair.location.city
}
if (location && isExisty(location.city)) {
return location.city
}
return existyValue(partner_city)
},
},
cover_image: {
description: "The image you should use to represent this show",
type: Image.type,
resolve: (
{ id, partner, image_versions, image_url },
_options,
{ partnerShowArtworksLoader }
) => {
if (image_versions && image_versions.length && image_url) {
return normalizeImageData({
image_versions,
image_url,
})
}
if (partner) {
return partnerShowArtworksLoader(
{
partner_id: partner.id,
show_id: id,
},
{
size: 1,
published: true,
}
)
.then(({ body }) => {
const artwork = body[0]
return artwork && normalizeImageData(getDefault(artwork.images))
})
.catch(() => null)
}
return null
},
},
counts: {
description:
"An object that represents some of the numbers you might want to highlight",
type: new GraphQLObjectType<any, ResolverContext>({
name: "ShowCounts",
fields: {
artworks: {
type: GraphQLInt,
args: {
artist_id: {
type: GraphQLString,
description: "The slug or ID of an artist in the show.",
},
},
resolve: (
{ id, partner },
options,
{ partnerShowArtworksLoader }
) => {
return totalViaLoader(
partnerShowArtworksLoader,
{
partner_id: partner.id,
show_id: id,
},
options
)
},
},
eligible_artworks: numeral(
({ eligible_artworks_count }) => eligible_artworks_count
),
artists: {
type: GraphQLInt,
resolve: (
{ id, partner },
options,
{ partnerShowArtistsLoader }
) => {
return totalViaLoader(
partnerShowArtistsLoader,
{
partner_id: partner.id,
show_id: id,
},
options
)
},
},
},
}),
resolve: (partner_show) => partner_show,
},
description: {
description: "A description of the show",
type: GraphQLString,
},
displayable: {
type: GraphQLBoolean,
deprecationReason: deprecate({
inVersion: 2,
preferUsageOf: "is_displayable",
}),
},
end_at: date,
events: {
description: "Events from the partner that runs this show",
type: new GraphQLList(PartnerShowEventType),
resolve: ({ partner, id }, _options, { partnerShowLoader }) =>
partnerShowLoader({
partner_id: partner.id,
show_id: id,
}).then(({ events }) => events),
},
exhibition_period: {
type: GraphQLString,
description: "A formatted description of the start to end dates",
resolve: ({ start_at, end_at }) => dateRange(start_at, end_at, "UTC"),
},
fair: {
description: "If the show is in a Fair, then that fair",
type: Fair.type,
resolve: ({ fair }) => fair,
},
filteredArtworks: filterArtworksWithParams(({ _id, partner }) => ({
partner_show_id: _id,
partner_id: partner.id,
})),
href: {
description: "A path to the show on Artsy",
type: GraphQLString,
resolve: ({ id, is_reference, displayable }) => {
if (is_reference || !displayable) return null
return `/show/${id}`
},
},
images: {
description:
"Images that represent the show, you may be interested in meta_image or cover_image for a definitive thumbnail",
type: new GraphQLList(Image.type),
args: {
size: {
type: GraphQLInt,
description: "Number of images to return",
},
default: {
type: GraphQLBoolean,
description: "Pass true/false to include cover or not",
},
page: {
type: GraphQLInt,
},
},
resolve: ({ id }, options, { partnerShowImagesLoader }) => {
return partnerShowImagesLoader(id, options).then(normalizeImageData)
},
},
has_location: {
type: GraphQLBoolean,
description: "Flag showing if show has any location.",
resolve: ({ location, fair, partner_city }) => {
return isExisty(location || fair || partner_city)
},
},
is_active: {
type: GraphQLBoolean,
description:
"Gravity doesn’t expose the `active` flag. Temporarily re-state its logic.",
resolve: ({ start_at, end_at }) => {
const start = moment.utc(start_at).subtract(7, "days")
const end = moment.utc(end_at).add(7, "days")
return moment.utc().isBetween(start, end)
},
},
is_displayable: {
description: "Is this something we can display to the front-end?",
type: GraphQLBoolean,
resolve: ({ displayable }) => displayable,
},
is_fair_booth: {
description: "Does the show exist as a fair booth?",
type: GraphQLBoolean,
resolve: ({ fair }) => isExisty(fair),
},
is_reference: {
description: "Is it a show provided for historical reference?",
type: GraphQLBoolean,
resolve: ({ is_reference }) => is_reference,
},
is_local_discovery: {
deprecationReason: deprecate({
inVersion: 2,
preferUsageOf: "isStubShow",
}),
type: GraphQLBoolean,
},
isStubShow: {
description: "Is it an outsourced local discovery stub show?",
type: GraphQLBoolean,
resolve: ({ is_local_discovery }) => is_local_discovery,
},
kind: {
description: "Whether the show is in a fair, group or solo",
type: GraphQLString,
resolve: (show, _options, { partnerShowLoader }) => {
if (show.artists || show.artists_without_artworks) return kind(show)
return partnerShowLoader({
partner_id: show.partner.id,
show_id: show.id,
}).then(kind)
},
},
location: {
description: "Where the show is located (Could also be a fair location)",
type: Location.type,
resolve: ({ location, fair_location }) => location || fair_location,
},
meta_image: {
description:
"An image representing the show, or a sharable image from an artwork in the show",
type: Image.type,
resolve: (
{ id, partner, image_versions, image_url },
_options,
{ partnerShowArtworksLoader }
) => {
if (image_versions && image_versions.length && image_url) {
return normalizeImageData({
image_versions,
image_url,
})
}
return partnerShowArtworksLoader(
{
partner_id: partner.id,
show_id: id,
},
{
published: true,
}
).then(({ body }) => {
return normalizeImageData(
getDefault(
find(body, {
can_share_image: true,
})
)
)
})
},
},
is_followed: {
type: GraphQLBoolean,
description: "Is the user following this show",
resolve: async ({ _id }, _args, { followedShowLoader }) => {
if (!followedShowLoader) return null
return followedShowLoader(_id).then(({ is_followed }) => is_followed)
},
},
name: {
type: GraphQLString,
description: "The exhibition title",
resolve: ({ name }) => (isExisty(name) ? name.trim() : name),
},
nearbyShows: {
description: "Shows that are near (~75km) from this show",
type: showConnection,
args: pageable({
sort: PartnerShowSorts,
status: {
type: EventStatus.type,
defaultValue: "CURRENT",
description: "By default show only current shows",
},
discoverable: {
type: GraphQLBoolean,
description:
"Whether to include local discovery stubs as well as displayable shows",
},
}),
resolve: async (show, args, { showsWithHeadersLoader }) => {
// Bail with an empty array if we can't get the lat/long for this show
if (!show.location || !show.location.coordinates) {
return connectionFromArray([], args)
}
// Manually toLowerCase to handle issue with resolving Enum default value
args.status = args.status.toLowerCase()
const coordinates = show.location.coordinates
const gravityOptions = {
...convertConnectionArgsToGravityArgs(args),
displayable: true,
near: `${coordinates.lat},${coordinates.lng}`,
max_distance: LOCAL_DISCOVERY_RADIUS_KM,
has_location: true,
total_count: true,
}
// @ts-expect-error FIXME: Make `page` an optional param of gravityOptions
delete gravityOptions.page
if (args.discoverable) {
// @ts-expect-error FIXME: Make `displayable` an optional param of gravityOptions
delete gravityOptions.displayable
}
const response = await showsWithHeadersLoader(gravityOptions)
const { headers, body: cities } = response
const results = connectionFromArraySlice(cities, args, {
arrayLength: parseInt(headers["x-total-count"] || "0", 10),
sliceStart: gravityOptions.offset,
})
// This is in our schema, so might as well fill it
// @ts-ignore
results.totalCount = parseInt(headers["x-total-count"] || "0", 10)
return results
},
},
openingReceptionText: {
type: GraphQLString,
description:
"Alternate Markdown-supporting free text representation of the opening reception event’s date/time",
resolve: ({ opening_reception_text }) => opening_reception_text,
},
partner: {
description:
"The partner that represents this show, could be a non-Artsy partner",
type: new GraphQLUnionType({
name: "PartnerTypes",
types: [PartnerType, ExternalPartnerType],
resolveType: (value) => {
if (value._links) {
return ExternalPartnerType
}
return PartnerType
},
}),
resolve: (
{ partner, galaxy_partner_id },
_options,
{ galaxyGalleriesLoader }
) => {
if (partner) {
return partner
}
if (galaxy_partner_id) {
return galaxyGalleriesLoader(galaxy_partner_id)
}
},
},
press_release: {
description: "The press release for this show",
...markdown(),
},
pressReleaseUrl: {
type: GraphQLString,
description: "Link to the press release for this show",
resolve: ({ press_release_url }) => press_release_url,
},
start_at: {
description: "When this show starts",
...date,
},
status: {
description: "Is this show running, upcoming or closed?",
type: GraphQLString,
},
status_update: {
type: GraphQLString,
description: "A formatted update on upcoming status changes",
args: {
max_days: {
type: GraphQLInt,
description: "Before this many days no update will be generated",
},
},
resolve: ({ start_at, end_at }, options) =>
exhibitionStatus(start_at, end_at, options.max_days),
},
type: {
description: "Is it a fair booth or a show?",
type: GraphQLString,
resolve: ({ fair }) => (isExisty(fair) ? "Fair Booth" : "Show"),
},
followedArtists: {
type: connectionDefinitions({ nodeType: FollowArtistType })
.connectionType,
args: pageable({}),
description:
"A Connection of followed artists by current user for this show",
resolve: (show, args, context) =>
followArtistsResolver({ show_id: show.id }, args, context),
},
}),
})
const Show: GraphQLFieldConfig<void, ResolverContext> = {
type: ShowType,
description: "A Show",
args: {
id: {
type: new GraphQLNonNull(GraphQLString),
description: "The slug or ID of the Show",
},
},
resolve: (_root, { id }, { showLoader, accessToken }) => {
const decodeUnverifiedJwt = decodeUnverifiedJWT(accessToken as string)
const partnerIds: Array<string> = decodeUnverifiedJwt
? decodeUnverifiedJwt.partner_ids
: []
const isAdmin: boolean =
decodeUnverifiedJwt &&
decodeUnverifiedJwt.roles.split(",").includes("admin")
const isDisplayable = (show) =>
show.displayable || isAdmin || partnerIds.includes(show.partner._id)
return showLoader(id)
.then((show) => {
if (
!isDisplayable(show) &&
!show.is_local_discovery &&
!show.is_reference &&
!isExisty(show.fair)
) {
return new HTTPError("Show Not Found", 404)
}
return show
})
.catch(() => null)
},
}
export default Show
export const showConnection = connectionWithCursorInfo(ShowType) | the_stack |
import {
CallExpr,
EqualityOp,
Expr,
HasAttributeExpr,
LiteralExpr,
NumberLiteralExpr,
RelationalOp,
StringLiteralExpr,
VarExpr
} from "./Expr";
/**
* Character value
*/
enum Character {
Tab = 9,
Lf = 10,
Cr = 13,
Space = 32,
LParen = 40,
RParen = 41,
Comma = 44,
Dot = 46,
LBracket = 91,
Backslash = 92,
RBracket = 93,
_0 = 48,
_9 = 57,
_ = 95,
A = 64,
Z = 90,
a = 97,
z = 122,
DoubleQuote = 34,
SingleQuote = 39,
Exclaim = 33,
Equal = 61,
Caret = 94,
Tilde = 126,
Dollar = 36,
Less = 60,
Greater = 62,
Bar = 124,
Amp = 38
}
/**
* Check if a codepoint is a whitespace character.
*/
function isSpace(codepoint: number): boolean {
switch (codepoint) {
case Character.Tab:
case Character.Lf:
case Character.Cr:
case Character.Space:
return true;
default:
return false;
} // switch
}
/**
* Check if codepoint is a digit character.
*/
function isNumber(codepoint: number): boolean {
return codepoint >= Character._0 && codepoint <= Character._9;
}
/**
* Check if codepoint is a letter character.
*/
function isLetter(codepoint: number): boolean {
return (
(codepoint >= Character.a && codepoint <= Character.z) ||
(codepoint >= Character.A && codepoint <= Character.Z)
);
}
/**
* Check if codepoint is either a digit or a letter character.
*/
function isLetterOrNumber(codepoint: number): boolean {
return isLetter(codepoint) || isNumber(codepoint);
}
/**
* Check if codepoint is an identification character: underscore, dollar sign, dot or bracket.
*/
function isIdentChar(codepoint: number): boolean {
return (
isLetterOrNumber(codepoint) ||
codepoint === Character._ ||
codepoint === Character.Dollar ||
codepoint === Character.Dot ||
codepoint === Character.LBracket ||
codepoint === Character.RBracket
);
}
/**
* Tokens used in theme grammar.
*/
enum Token {
Eof = 0,
Error,
Identifier,
Number,
String,
Comma,
LParen,
RParen,
LBracket,
RBracket,
Exclaim,
TildeEqual,
CaretEqual,
DollarEqual,
EqualEqual,
ExclaimEqual,
Less,
Greater,
LessEqual,
GreaterEqual,
BarBar,
AmpAmp
}
/**
* Maps a token to its string name.
*/
function tokenSpell(token: Token): string {
switch (token) {
case Token.Eof:
return "eof";
case Token.Error:
return "error";
case Token.Identifier:
return "identifier";
case Token.Number:
return "number";
case Token.String:
return "string";
case Token.Comma:
return ",";
case Token.LParen:
return "(";
case Token.RParen:
return ")";
case Token.LBracket:
return "[";
case Token.RBracket:
return "]";
case Token.Exclaim:
return "!";
case Token.TildeEqual:
return "~=";
case Token.CaretEqual:
return "^=";
case Token.DollarEqual:
return "$=";
case Token.EqualEqual:
return "==";
case Token.ExclaimEqual:
return "!=";
case Token.Less:
return "<";
case Token.Greater:
return ">";
case Token.LessEqual:
return "<=";
case Token.GreaterEqual:
return ">=";
case Token.BarBar:
return "||";
case Token.AmpAmp:
return "&&";
default:
throw new Error(`invalid token ${token}`);
}
}
/**
* Lexer class implementation.
*/
class Lexer {
private m_token: Token = Token.Error;
private m_index = 0;
private m_char: number = Character.Lf;
private m_text?: string;
constructor(readonly code: string) {}
/**
* Single lexer token.
*/
token(): Token {
return this.m_token;
}
/**
* Parsed text.
*/
text(): string {
return this.m_text ?? "";
}
/**
* Go to the next token.
*/
next(): Token {
this.m_token = this.yylex();
if (this.m_token === Token.Error) {
throw new Error(`unexpected character ${this.m_char}`);
}
return this.m_token;
}
private yyinp(): void {
this.m_char = this.code.codePointAt(this.m_index++) ?? 0;
}
private yylex(): Token {
this.m_text = undefined;
while (isSpace(this.m_char)) {
this.yyinp();
}
if (this.m_char === 0) {
return Token.Eof;
}
const ch = this.m_char;
this.yyinp();
switch (ch) {
case Character.LParen:
return Token.LParen;
case Character.RParen:
return Token.RParen;
case Character.LBracket:
return Token.LBracket;
case Character.RBracket:
return Token.RBracket;
case Character.Comma:
return Token.Comma;
case Character.SingleQuote:
case Character.DoubleQuote: {
const start = this.m_index - 1;
while (this.m_char && this.m_char !== ch) {
// ### TODO handle escape sequences
this.yyinp();
}
if (this.m_char !== ch) {
throw new Error("Unfinished string literal");
}
this.yyinp();
this.m_text = this.code.substring(start, this.m_index - 2);
return Token.String;
}
case Character.Exclaim:
if (this.m_char === Character.Equal) {
this.yyinp();
return Token.ExclaimEqual;
}
return Token.Exclaim;
case Character.Caret:
if (this.m_char === Character.Equal) {
this.yyinp();
return Token.CaretEqual;
}
return Token.Error;
case Character.Tilde:
if (this.m_char === Character.Equal) {
this.yyinp();
return Token.TildeEqual;
}
return Token.Error;
case Character.Equal:
if (this.m_char === Character.Equal) {
this.yyinp();
return Token.EqualEqual;
}
return Token.Error;
case Character.Less:
if (this.m_char === Character.Equal) {
this.yyinp();
return Token.LessEqual;
}
return Token.Less;
case Character.Greater:
if (this.m_char === Character.Equal) {
this.yyinp();
return Token.GreaterEqual;
}
return Token.Greater;
case Character.Bar:
if (this.m_char === Character.Bar) {
this.yyinp();
return Token.BarBar;
}
return Token.Error;
case Character.Amp:
if (this.m_char === Character.Amp) {
this.yyinp();
return Token.AmpAmp;
}
return Token.Error;
default: {
const start = this.m_index - 2;
if (
isLetter(ch) ||
ch === Character._ ||
(ch === Character.Dollar && isIdentChar(this.m_char))
) {
while (isIdentChar(this.m_char)) {
this.yyinp();
}
this.m_text = this.code.substring(start, this.m_index - 1);
return Token.Identifier;
} else if (isNumber(ch)) {
while (isNumber(this.m_char)) {
this.yyinp();
}
if (this.m_char === Character.Dot) {
this.yyinp();
while (isNumber(this.m_char)) {
this.yyinp();
}
}
this.m_text = this.code.substring(start, this.m_index - 1);
return Token.Number;
} else if (ch === Character.Dollar) {
if (this.m_char === Character.Equal) {
this.yyinp();
return Token.DollarEqual;
}
return Token.Error;
}
}
}
return Token.Error;
}
}
function getEqualityOp(token: Token): EqualityOp | undefined {
switch (token) {
case Token.TildeEqual:
return "~=";
case Token.CaretEqual:
return "^=";
case Token.DollarEqual:
return "$=";
case Token.EqualEqual:
return "==";
case Token.ExclaimEqual:
return "!=";
default:
return undefined;
} // switch
}
function getRelationalOp(token: Token): RelationalOp | undefined {
switch (token) {
case Token.Less:
return "<";
case Token.Greater:
return ">";
case Token.LessEqual:
return "<=";
case Token.GreaterEqual:
return ">=";
default:
return undefined;
} // switch
}
export class ExprParser {
private readonly lex: Lexer;
constructor(code: string) {
this.lex = new Lexer(code);
this.lex.next();
}
parse(): Expr | never {
return this.parseLogicalOr();
}
private yyexpect(token: Token): void | never {
if (this.lex.token() !== token) {
throw new Error(
`Syntax error: Expected token '${tokenSpell(token)}' but ` +
`found '${tokenSpell(this.lex.token())}'`
);
}
this.lex.next();
}
private parsePrimary(): Expr | never {
switch (this.lex.token()) {
case Token.Identifier: {
const text = this.lex.text();
switch (text) {
case "has":
this.lex.next(); // skip has keyword
this.yyexpect(Token.LParen);
const hasAttribute = this.lex.text();
this.yyexpect(Token.Identifier);
this.yyexpect(Token.RParen);
return new HasAttributeExpr(hasAttribute);
case "length":
this.lex.next(); // skip length keyword
this.yyexpect(Token.LParen);
const value = this.parseLogicalOr();
this.yyexpect(Token.RParen);
return new CallExpr("length", [value]);
default:
const expr = new VarExpr(text);
this.lex.next();
return expr;
}
}
case Token.LParen: {
this.lex.next();
const expr = this.parseLogicalOr();
this.yyexpect(Token.RParen);
return expr;
}
default:
return this.parseLiteral();
} // switch
}
private parseLiteral(): NumberLiteralExpr | StringLiteralExpr | never {
switch (this.lex.token()) {
case Token.Number: {
const expr = new NumberLiteralExpr(parseFloat(this.lex.text()));
this.lex.next();
return expr;
}
case Token.String: {
const expr = new StringLiteralExpr(this.lex.text());
this.lex.next();
return expr;
}
default:
throw new Error("Syntax error");
} // switch
}
private parseUnary(): Expr | never {
if (this.lex.token() === Token.Exclaim) {
this.lex.next();
return new CallExpr("!", [this.parseUnary()]);
}
return this.parsePrimary();
}
private parseRelational(): Expr | never {
let expr = this.parseUnary();
while (true) {
if (this.lex.token() === Token.Identifier && this.lex.text() === "in") {
this.lex.next();
this.yyexpect(Token.LBracket);
const elements = [this.parseLiteral()];
while (this.lex.token() === Token.Comma) {
this.lex.next();
elements.push(this.parseLiteral());
}
this.yyexpect(Token.RBracket);
expr = new CallExpr("in", [
expr,
LiteralExpr.fromValue(elements.map(({ value }) => value))
]);
} else {
const op = getRelationalOp(this.lex.token());
if (op === undefined) {
break;
}
this.lex.next();
const right = this.parseUnary();
expr = new CallExpr(op, [expr, right]);
}
}
return expr;
}
private parseEquality(): Expr | never {
let expr = this.parseRelational();
while (true) {
let op: string | undefined = getEqualityOp(this.lex.token());
if (op === undefined) {
break;
}
if (op === "~=") {
op = "in";
}
this.lex.next();
const right = this.parseRelational();
expr = new CallExpr(op, [expr, right]);
}
return expr;
}
private parseLogicalAnd(): Expr | never {
const expr = this.parseEquality();
if (this.lex.token() !== Token.AmpAmp) {
return expr;
}
const expressions: Expr[] = [expr];
do {
this.lex.next();
expressions.push(this.parseEquality());
} while (this.lex.token() === Token.AmpAmp);
return new CallExpr("all", expressions);
}
private parseLogicalOr(): Expr | never {
const expr = this.parseLogicalAnd();
if (this.lex.token() !== Token.BarBar) {
return expr;
}
const expressions: Expr[] = [expr];
do {
this.lex.next();
expressions.push(this.parseLogicalAnd());
} while (this.lex.token() === Token.BarBar);
return new CallExpr("any", expressions);
}
} | the_stack |
import {
TypeSummaryReducer,
TypeComputedColumnsMap,
TypeComputedColumn,
TypeGroupDataItem,
TypeShowGroupSummaryRow,
TypePivotSummaryShape,
TypePivotItem,
TypePivotColumnSummaryReducer,
TypePivotUniqueValuesDescriptor,
} from '../../../types';
const get = (item: any, field: string) => item[field];
const defaultStringify = (obj: any): string => {
const type = typeof obj;
return type == 'string' || type === 'number' || type === 'boolean'
? `${obj}`
: JSON.stringify(obj);
};
type TypeGroupBucket = {
key: string | null;
keyPath: string[];
field: string | null;
fieldPath: string[];
groupSummary: any | null;
groupColumnSummary: { [colName: string]: any } | null;
pivotSummary: TypePivotSummaryShape | null;
pivotColumnSummary?: TypePivotSummaryShape | null;
data: { [key: string]: TypeGroupBucket } | null;
array: any[];
depth: number;
order: string[];
};
const getShowSummaryRow = (
showGroupSummaryRow: TypeShowGroupSummaryRow | null,
groupData: TypeGroupDataItem | null,
pivot: TypePivotItem[] | null
): 'start' | 'end' | false => {
if (!showGroupSummaryRow || !groupData || pivot) {
return false;
}
if (typeof showGroupSummaryRow === 'function') {
showGroupSummaryRow = showGroupSummaryRow(groupData);
}
if (showGroupSummaryRow === true) {
showGroupSummaryRow = 'end';
}
if (!showGroupSummaryRow) {
showGroupSummaryRow = false;
}
return showGroupSummaryRow;
};
const completeBucketSummaries = (
bucket: TypeGroupBucket,
{
groupSummaryReducer,
groupColumnSummaryReducers,
pivotColumnSummaryReducers,
}: {
groupSummaryReducer: TypeSummaryReducer | null;
groupColumnSummaryReducers: { [key: string]: TypeSummaryReducer } | null;
pivotColumnSummaryReducers?: {
[key: string]: TypePivotColumnSummaryReducer;
} | null;
}
): TypeGroupBucket => {
if (groupSummaryReducer && groupSummaryReducer.complete) {
bucket.groupSummary = groupSummaryReducer.complete(
bucket.groupSummary,
bucket.array
);
}
if (groupColumnSummaryReducers) {
bucket.groupColumnSummary = Object.keys(groupColumnSummaryReducers).reduce(
(acc: { [key: string]: any }, key: string) => {
const value = acc[key];
const reducer = groupColumnSummaryReducers[key];
if (reducer.complete) {
acc[key] = reducer.complete(value, bucket.array);
}
return acc;
},
bucket.groupColumnSummary as { [key: string]: any }
);
if (bucket.pivotSummary !== null) {
completePivotBucketSummaries(bucket, {
groupColumnSummaryReducers,
pivotColumnSummaryReducers,
});
}
}
return bucket;
};
const completeGroupColumnSummaryReducers = (
target: { [colId: string]: any } | null,
array: any[],
groupColumnSummaryReducers: { [key: string]: TypeSummaryReducer } | null
) => {
if (!target || !groupColumnSummaryReducers) {
return null;
}
return Object.keys(groupColumnSummaryReducers).reduce(
(acc, colId: string) => {
const reducer = groupColumnSummaryReducers[colId];
if (reducer.complete) {
acc[colId] = reducer.complete(acc[colId], array);
}
return acc;
},
target
);
};
const completePivotBucketSummaries = (
pivotSummaryBucket: { pivotSummary: TypePivotSummaryShape | null },
{
groupColumnSummaryReducers,
pivotColumnSummaryReducers,
}: {
groupColumnSummaryReducers: { [key: string]: TypeSummaryReducer } | null;
pivotColumnSummaryReducers?: {
[key: string]: TypePivotColumnSummaryReducer;
} | null;
}
) => {
if (!pivotSummaryBucket.pivotSummary) {
return;
}
Object.keys(pivotSummaryBucket.pivotSummary).forEach((groupName: string) => {
const pivotBucket = pivotSummaryBucket.pivotSummary![groupName];
pivotBucket.values = completeGroupColumnSummaryReducers(
pivotBucket.values,
pivotBucket.array,
groupColumnSummaryReducers
)!;
completePivotBucketSummaries(pivotBucket, {
groupColumnSummaryReducers,
pivotColumnSummaryReducers,
});
if (
pivotBucket.pivotColumnSummary &&
pivotColumnSummaryReducers &&
pivotColumnSummaryReducers[pivotBucket.field]
) {
const pivotColumnSummaryReducer =
pivotColumnSummaryReducers[pivotBucket.field];
if (pivotColumnSummaryReducer.complete) {
pivotBucket.pivotColumnSummary[
pivotBucket.field
] = pivotColumnSummaryReducer.complete(
pivotBucket.pivotColumnSummary[pivotBucket.field],
pivotBucket.array
);
}
}
});
};
const createGroupItem = (
key: string,
bucket: TypeGroupBucket
): TypeGroupDataItem => {
return {
__group: true,
leaf: !bucket.data,
value: key,
depth: bucket.depth,
groupSummary: bucket.groupSummary,
groupColumnSummary: bucket.groupColumnSummary,
pivotSummary: bucket.pivotSummary,
keyPath: bucket.keyPath,
fieldPath: bucket.fieldPath,
};
};
export const flatten = (
bucket: TypeGroupBucket,
{
pivot,
groupSummaryReducer,
groupColumnSummaryReducers,
pivotColumnSummaryReducers,
isCollapsed,
showGroupSummaryRow,
}: {
isCollapsed?: (group: TypeGroupDataItem) => boolean;
pivot: TypePivotItem[] | null;
showGroupSummaryRow: TypeShowGroupSummaryRow | null;
groupSummaryReducer: TypeSummaryReducer | null;
groupColumnSummaryReducers: { [key: string]: TypeSummaryReducer } | null;
pivotColumnSummaryReducers?: {
[key: string]: TypePivotColumnSummaryReducer;
} | null;
}
): {
data: any[];
bucket: TypeGroupBucket;
indexesInGroups: number[];
groupCounts: number[];
} => {
let data: any[] = [];
let indexesInGroups: number[] = [];
let groupCounts: number[] = [];
// we need to complete the summary calculation
// before going down and flattening more,
// since createGroupItem sends the summary info to the created data item
completeBucketSummaries(bucket, {
groupSummaryReducer,
groupColumnSummaryReducers,
pivotColumnSummaryReducers,
});
let shouldInclude = true;
let showSummaryRow;
let summaryGroupItem;
if (!bucket.data) {
const groupItem = createGroupItem(bucket.key!, bucket);
data = [groupItem];
indexesInGroups = [-1];
groupCounts = [-1];
shouldInclude = !pivot;
if (isCollapsed && isCollapsed(groupItem)) {
shouldInclude = false;
}
if (shouldInclude) {
showSummaryRow = getShowSummaryRow(showGroupSummaryRow, groupItem, pivot);
summaryGroupItem = showSummaryRow
? {
...groupItem.groupColumnSummary,
__parentGroup: groupItem,
__summary: showSummaryRow,
}
: null;
let indexesInGroupsOffset = 0;
if (showSummaryRow === 'start') {
data.push(summaryGroupItem);
groupCounts.push(-1);
indexesInGroups.push(-1);
}
data = data.concat(bucket.array);
indexesInGroups = indexesInGroups.concat(
bucket.array.map((_, index) => index + indexesInGroupsOffset)
);
groupCounts = groupCounts.concat(
bucket.array.map(_ => bucket.array.length)
);
if (showSummaryRow === 'end') {
data.push(summaryGroupItem);
indexesInGroups.push(-1);
groupCounts.push(-1);
}
}
} else {
const groupItem =
bucket.key != null ? createGroupItem(bucket.key, bucket) : null;
data = groupItem ? [groupItem] : [];
indexesInGroups = groupItem ? [-1] : [];
groupCounts = groupItem ? [-1] : [];
if (groupItem && isCollapsed && isCollapsed(groupItem)) {
shouldInclude = false;
}
if (shouldInclude) {
showSummaryRow = getShowSummaryRow(showGroupSummaryRow, groupItem, pivot);
summaryGroupItem = showSummaryRow
? {
...groupItem!.groupColumnSummary,
__parentGroup: groupItem,
__summary: showSummaryRow,
}
: null;
if (showSummaryRow === 'start') {
data.push(summaryGroupItem);
indexesInGroups.push(-1);
groupCounts.push(-1);
}
data = bucket.order.reduce((data: any[], key: string) => {
const childBucket: TypeGroupBucket = bucket.data![key];
const result = flatten(childBucket, {
pivot,
isCollapsed,
showGroupSummaryRow,
groupColumnSummaryReducers,
groupSummaryReducer,
pivotColumnSummaryReducers,
});
indexesInGroups = indexesInGroups.concat(result.indexesInGroups);
groupCounts = groupCounts.concat(result.groupCounts);
return data.concat(result.data);
}, data);
if (showSummaryRow === 'end') {
data.push(summaryGroupItem);
indexesInGroups.push(-1);
groupCounts.push(-1);
}
}
}
return {
indexesInGroups,
groupCounts,
bucket,
data,
};
};
const buildDataBucket = ({
field,
key,
parent,
groupSummaryReducer,
groupColumnSummaryReducers,
pivotColumnSummaryReducers,
}: {
field: string | null;
key: string | null;
parent: TypeGroupBucket | null;
groupSummaryReducer?: TypeSummaryReducer;
groupColumnSummaryReducers?: { [key: string]: TypeSummaryReducer };
pivotColumnSummaryReducers?: { [key: string]: TypePivotColumnSummaryReducer };
}): TypeGroupBucket => {
return {
key,
field,
fieldPath: parent && field ? [...parent.fieldPath, field] : [],
keyPath: parent && key ? [...parent.keyPath, key] : [],
order: [],
array: [],
data: null,
depth: parent ? parent.depth + 1 : 0,
groupSummary: groupSummaryReducer ? groupSummaryReducer.initialValue : null,
groupColumnSummary: getDefaultGroupSummaryValue(groupColumnSummaryReducers),
pivotColumnSummary: getDefaultGroupSummaryValue(pivotColumnSummaryReducers),
pivotSummary: null,
};
};
type TypeMasterGroupBucket = TypeGroupBucket & {
pivotUniqueValuesPerColumn?: TypePivotUniqueValuesDescriptor;
};
const groupAndPivot = (
data: any[],
{
groupBy,
pivot,
columnsMap,
stringify = defaultStringify,
groupSummaryReducer,
groupColumnSummaryReducers,
pivotColumnSummaryReducers,
}: {
groupBy: string[];
pivot?: TypePivotItem[];
columnsMap: TypeComputedColumnsMap;
groupSummaryReducer?: TypeSummaryReducer;
groupColumnSummaryReducers?: { [key: string]: TypeSummaryReducer };
pivotColumnSummaryReducers?: {
[key: string]: TypePivotColumnSummaryReducer;
};
stringify?: (v: any, ...args: any[]) => string;
}
): TypeMasterGroupBucket => {
const masterBucket: TypeMasterGroupBucket = buildDataBucket({
field: null,
parent: null,
key: null,
groupSummaryReducer,
groupColumnSummaryReducers,
pivotColumnSummaryReducers,
});
if (pivot && pivot.length) {
masterBucket.pivotUniqueValuesPerColumn = {
field: null,
values: null,
};
}
const onItem = (item: any) => {
let rootBucket: TypeGroupBucket = masterBucket;
updateBucketSummaries(rootBucket, item, {
groupSummaryReducer,
groupColumnSummaryReducers,
columnsMap,
});
groupBy.forEach((field: string) => {
const fieldValue = get(item, field);
const toString = columnsMap[field]
? columnsMap[field].groupToString || stringify
: stringify;
const stringKey = toString(fieldValue, { data: item, field });
if (!rootBucket.data) {
rootBucket.data = {};
}
let currentBucket = rootBucket.data[stringKey];
if (!currentBucket) {
currentBucket = rootBucket.data[stringKey] = buildDataBucket({
field,
key: stringKey,
parent: rootBucket,
groupSummaryReducer,
groupColumnSummaryReducers,
});
rootBucket.order.push(stringKey);
}
currentBucket.array.push(item);
updateBucketSummaries(currentBucket, item, {
groupSummaryReducer,
groupColumnSummaryReducers,
columnsMap,
});
if (pivot && pivot.length) {
let pivotBucketOwner: {
pivotSummary: TypePivotSummaryShape | null;
pivotColumnSummary?: TypePivotSummaryShape | null;
} = currentBucket;
let uniqueValuesRoot: TypePivotUniqueValuesDescriptor = masterBucket.pivotUniqueValuesPerColumn!;
pivot.forEach((field: TypePivotItem) => {
field = typeof field === 'string' ? field : field.name;
const fieldValue = get(item, field);
const col = columnsMap[field];
const toString = col
? col.pivotToString || col.groupToString || stringify
: stringify;
const stringKey = toString(fieldValue, { data: item, field });
if (!pivotBucketOwner.pivotSummary) {
pivotBucketOwner.pivotSummary = {};
}
if (!pivotBucketOwner.pivotColumnSummary) {
pivotBucketOwner.pivotColumnSummary = {};
}
let currentPivotSummaryBucket: TypePivotSummaryShape =
pivotBucketOwner.pivotSummary;
pivotBucketOwner = updateBucketPivotSummary(
currentPivotSummaryBucket,
item,
{
field,
groupName: stringKey,
groupColumnSummaryReducers,
pivotColumnSummaryReducers: pivotColumnSummaryReducers
? {
[field]: pivotColumnSummaryReducers[field],
}
: undefined,
columnsMap,
}
);
if (!uniqueValuesRoot.field) {
uniqueValuesRoot.field = field;
uniqueValuesRoot.values = {};
}
if (!uniqueValuesRoot.values![stringKey]) {
uniqueValuesRoot.values![stringKey] = { field: null, values: null };
}
uniqueValuesRoot = uniqueValuesRoot.values![stringKey];
});
}
rootBucket = currentBucket;
});
};
data.forEach(onItem);
return masterBucket;
};
export const updateBucketSummaries = (
currentBucket: {
groupSummary: any | null;
groupColumnSummary: { [colName: string]: any } | null;
},
item: any,
{
groupSummaryReducer,
groupColumnSummaryReducers,
columnsMap,
}: {
groupSummaryReducer?: TypeSummaryReducer;
groupColumnSummaryReducers?: { [key: string]: TypeSummaryReducer };
columnsMap: TypeComputedColumnsMap;
}
) => {
if (groupSummaryReducer) {
currentBucket.groupSummary = groupSummaryReducer.reducer(
currentBucket.groupSummary,
item,
item
);
}
if (groupColumnSummaryReducers) {
currentBucket.groupColumnSummary = Object.keys(
groupColumnSummaryReducers
).reduce((columnSummaries, colId) => {
const col: TypeComputedColumn = columnsMap[colId];
const value = col.name ? item[col.name] : item[colId];
columnSummaries[colId] = groupColumnSummaryReducers[colId].reducer(
columnSummaries[colId],
value,
item
);
return columnSummaries;
}, currentBucket.groupColumnSummary as { [key: string]: any });
}
};
const updateBucketPivotSummary = (
currentBucket: TypePivotSummaryShape,
item: any,
{
groupColumnSummaryReducers,
pivotColumnSummaryReducers,
groupName,
field,
columnsMap,
}: {
field: string;
groupName: string;
pivotColumnSummaryReducers?: {
[key: string]: TypePivotColumnSummaryReducer;
};
groupColumnSummaryReducers?: { [key: string]: TypeSummaryReducer };
columnsMap: TypeComputedColumnsMap;
}
): { pivotSummary: TypePivotSummaryShape | null } => {
groupColumnSummaryReducers = groupColumnSummaryReducers || {};
pivotColumnSummaryReducers = pivotColumnSummaryReducers || {};
if (!currentBucket[groupName]) {
currentBucket[groupName] = {
array: [],
field,
values: getDefaultGroupSummaryValue(groupColumnSummaryReducers)!,
pivotColumnSummary: getDefaultGroupSummaryValue(
pivotColumnSummaryReducers
)!,
pivotSummary: null,
};
}
currentBucket[groupName].array.push(item);
currentBucket[groupName].values = Object.keys(
groupColumnSummaryReducers
).reduce((columnSummaries, colId) => {
const col: TypeComputedColumn = columnsMap[colId];
const value = col.name ? item[col.name] : item[colId];
columnSummaries[colId] = groupColumnSummaryReducers![colId].reducer(
columnSummaries[colId],
value,
item
);
return columnSummaries;
}, currentBucket[groupName].values as TypePivotSummaryShape);
currentBucket[groupName].pivotColumnSummary = Object.keys(
pivotColumnSummaryReducers
).reduce((pivotColumnSummaries, colId) => {
// const value = item[colId];
if (pivotColumnSummaryReducers![colId]) {
pivotColumnSummaries[colId] = pivotColumnSummaryReducers![colId].reducer(
pivotColumnSummaries[colId],
groupName,
item
);
}
return pivotColumnSummaries;
}, currentBucket[groupName].pivotColumnSummary);
return currentBucket[groupName];
};
export const getDefaultGroupSummaryValue = (groupColumnSummaryReducers?: {
[key: string]: TypeSummaryReducer | TypePivotColumnSummaryReducer;
}) => {
return groupColumnSummaryReducers
? Object.keys(groupColumnSummaryReducers).reduce((acc, key) => {
if (groupColumnSummaryReducers[key]) {
acc[key] = groupColumnSummaryReducers[key].initialValue;
}
return acc;
}, {} as { [key: string]: any })
: null;
};
export default groupAndPivot; | the_stack |
import React, { PureComponent } from 'react';
import {
FlatList,
Image,
ImageSourcePropType,
ImageStyle,
ListRenderItemInfo,
StyleProp,
StyleSheet,
Text,
TextStyle,
TouchableOpacity,
View,
ViewStyle
} from 'react-native';
import { SelectableRow, SelectableRowProps } from '../SelectableRow';
import { FilterItem } from './FilterItem';
import { FilterItemValue } from './FilterItemValue';
import FSI18n, { translationKeys } from '@brandingbrand/fsi18n';
const componentTranslationKeys = translationKeys.flagship.filterListDefaults;
const defaultSingleFilterIds = [`cgid`];
const closeIcon = require('../../../assets/images/clear.png');
export interface FilterListDrilldownProps {
items: FilterItem[];
onApply: (selectedItems: Record<string, string[]>, info?: { isButtonPress: boolean }) => void;
onReset: (info?: { isButtonPress: boolean }) => void;
onClose?: () => void;
selectedItems?: Record<string, string[]>;
style?: StyleProp<ViewStyle>;
closeButtonStyle?: StyleProp<ViewStyle>;
resetButtonStyle?: StyleProp<ViewStyle>;
applyButtonStyle?: StyleProp<ViewStyle>;
closeButtonImageStyle?: StyleProp<ImageStyle>;
resetButtonTextStyle?: StyleProp<TextStyle>;
applyButtonTextStyle?: StyleProp<TextStyle>;
closeIcon?: ImageSourcePropType;
applyText?: string;
resetText?: string;
floatingReset?: boolean;
itemStyle?: StyleProp<ViewStyle>;
itemTextStyle?: StyleProp<TextStyle>;
itemTextSelectedStyle?: StyleProp<TextStyle>;
selectedValueStyle?: StyleProp<TextStyle>;
selectableRowProps?: Partial<SelectableRowProps>;
singleFilterIds?: string[]; // Filter IDs for which only one value can be selected at a time
ignoreActiveStyleIds?: string[]; // Filter IDs for which active styling won't be applied
applyOnSelect?: boolean;
renderFilterItem?: (
item: FilterItem,
i: number,
selectedValues: string[],
handlePress: () => void,
renderFilterItem: (
info: Omit<ListRenderItemInfo<FilterItem>, 'separators'>,
skipCustomRender: boolean
) => JSX.Element
) => JSX.Element;
renderFilterItemValue?: (
item: FilterItem,
i: number,
value: FilterItemValue,
handleSelect: () => void,
selected: boolean,
renderFilterItemValue: (
item: FilterItem,
skipCustomRender?: boolean
) => (info: Omit<ListRenderItemInfo<FilterItemValue>, 'separators'>) => JSX.Element
) => JSX.Element;
renderSecondLevel?: (
item: FilterItem,
goBack: () => void,
renderSecondLevel: (
item: FilterItem,
skipCustomRender?: boolean
) => JSX.Element
) => JSX.Element;
showUnselected?: boolean;
showSelectedCount?: boolean;
refineText?: string;
filterHeader?: StyleProp<ViewStyle>;
filterTitleStyle?: StyleProp<TextStyle>;
secondLevelTitle?: string;
secondLevelHeaderStyle?: StyleProp<ViewStyle>;
secondLevelTitleStyle?: StyleProp<TextStyle>;
secondLevelShowApply?: boolean;
secondLevelShowClose?: boolean;
optionsFooterStyles?: StyleProp<ViewStyle>;
}
const S = StyleSheet.create({
title: {
fontWeight: 'bold',
fontSize: 15
},
titleSelected: {
fontWeight: '800'
},
valueButton: {
height: 40
},
container: {
flex: 1
},
buttonsContainer: {
flexDirection: 'row',
marginRight: 10
},
firstLevelItem: {},
firstLevelItemContainer: {
padding: 15,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
borderBottomColor: '#ccc',
borderBottomWidth: StyleSheet.hairlineWidth
},
selectedValueStyle: {
color: '#999',
fontSize: 13,
marginTop: 3,
maxWidth: 300
},
arrow: {
width: 14,
height: 14,
borderColor: '#555',
borderBottomWidth: 1,
borderLeftWidth: 1
},
arrowBack: {
transform: [{ rotate: '45deg' }]
},
arrowNext: {
transform: [{ rotate: '-135deg' }]
},
arrowContainer: {
position: 'absolute',
left: 15
},
secondLevelHeader: {
height: 50,
paddingHorizontal: 10,
borderBottomColor: '#aaa',
borderBottomWidth: 1,
justifyContent: 'center',
alignItems: 'center'
},
secondLevelTitle: {
fontWeight: 'bold'
},
resetButton: {
position: 'absolute',
left: 15,
top: 0,
height: 50,
justifyContent: 'center',
alignItems: 'center'
},
floatApplyButton: {
position: 'absolute',
left: 20,
right: 20,
bottom: 15,
paddingVertical: 17,
backgroundColor: '#333132',
justifyContent: 'center',
alignItems: 'center'
},
floatApplyButtonText: {
color: 'white'
},
floatResetButton: {
position: 'absolute',
left: 20,
right: 20,
bottom: 80,
paddingVertical: 16,
borderWidth: 1,
borderColor: '#565555',
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center'
},
floatResetButtonText: {
color: '#333132'
},
rightButton: {
position: 'absolute',
right: 15,
height: 50,
justifyContent: 'center',
alignItems: 'center'
},
filterHeader: {
height: 50,
justifyContent: 'center',
alignItems: 'center',
borderBottomColor: '#aaa',
borderBottomWidth: 1
},
filterTitle: {
fontSize: 20
},
applyButton: {
flex: 1
},
emptyCell: {
height: 100
},
closeButtonImage: {
height: 16,
width: 16
}
});
export interface FilterListDrilldownState {
selectedItems: Record<string, string[]>;
secondLevelItem?: FilterItem;
}
export class FilterListDrilldown extends PureComponent<
FilterListDrilldownProps,
FilterListDrilldownState
> {
constructor(props: FilterListDrilldownProps) {
super(props);
this.state = {
selectedItems: props.selectedItems || {},
secondLevelItem: undefined
};
}
componentDidUpdate(
prevProps: FilterListDrilldownProps
): void {
const stateChanges: Partial<FilterListDrilldownState> = {};
if (this.props.items !== prevProps.items && this.state.secondLevelItem) {
stateChanges.secondLevelItem = this.props.items.find(item => (
item.id === this.state.secondLevelItem?.id
));
}
if (this.props.selectedItems !== prevProps.selectedItems) {
stateChanges.selectedItems = this.props.selectedItems;
}
if (Object.keys(stateChanges).length) {
this.setState(stateChanges as FilterListDrilldownState);
}
}
handleSelect = (id: string, value: string) => () => {
const { selectedItems } = this.state;
const singleFilterIds =
this.props.singleFilterIds || defaultSingleFilterIds;
let nextSelectedItems = null;
// if already selected, and it's not in the list of single filter
if (selectedItems[id] && singleFilterIds.indexOf(id) === -1) {
const findIndex = selectedItems[id].indexOf(value);
if (findIndex > -1) {
selectedItems[id].splice(findIndex, 1);
} else {
selectedItems[id].push(value);
}
nextSelectedItems = {
...selectedItems
};
} else {
nextSelectedItems = {
...selectedItems,
[id]: [value]
};
}
this.setState({ selectedItems: nextSelectedItems });
if (this.props.applyOnSelect) {
this.props.onApply(nextSelectedItems);
}
}
renderFilterItemValue = (filterItem: FilterItem, skipCustomRender?: boolean) => ({
item,
index
}: Omit<ListRenderItemInfo<FilterItemValue>, 'separators'>): JSX.Element => {
const selected =
this.state.selectedItems[filterItem.id] &&
this.state.selectedItems[filterItem.id].indexOf(item.value) > -1;
if (this.props.renderFilterItemValue && !skipCustomRender) {
return this.props.renderFilterItemValue(
filterItem,
index || 0,
item,
this.handleSelect(filterItem.id, item.value),
selected,
this.renderFilterItemValue
);
}
return (
<SelectableRow
key={index}
title={item.title}
selected={selected}
onPress={this.handleSelect(filterItem.id, item.value)}
{...this.props.selectableRowProps}
/>
);
}
// tslint:disable cyclomatic-complexity
renderFilterItem = (
{ item, index }: Omit<ListRenderItemInfo<FilterItem>, 'separators'>,
skipCustomRender: boolean = false
): JSX.Element => {
const selectedValues = this.state.selectedItems[item.id] || [];
const selectedValueTitles = (item.values || [])
.filter((v: FilterItemValue) => selectedValues.indexOf(v.value) > -1)
.map((v: FilterItemValue) => v.title);
if (this.props.renderFilterItem && !skipCustomRender) {
return this.props.renderFilterItem(
item,
index || 0,
selectedValues,
this.drilldown(item),
this.renderFilterItem // this can be used to render the original item
);
}
return (
<TouchableOpacity
style={[S.firstLevelItemContainer, this.props.itemStyle]}
onPress={this.drilldown(item)}
accessibilityRole={'button'}
accessibilityHint={FSI18n.string(componentTranslationKeys.hintToggle)}
accessibilityLabel={item.title}
>
<View style={S.firstLevelItem}>
<Text
style={[
S.title,
selectedValueTitles.length ? S.titleSelected : false,
this.props.itemTextStyle,
(this.props.ignoreActiveStyleIds || []).indexOf(item.id) === -1 &&
selectedValueTitles.length ? this.props.itemTextSelectedStyle : false
]}
>
{item.title}
{(selectedValueTitles.length && this.props.showSelectedCount !== false)
? ` (${selectedValueTitles.length})`
: ''}
</Text>
{(selectedValueTitles.length || this.props.showUnselected !== false) ? (
<Text
style={[
S.selectedValueStyle,
(this.props.ignoreActiveStyleIds || []).indexOf(item.id) === -1 &&
this.props.selectedValueStyle
]}
numberOfLines={1}
ellipsizeMode='tail'
>
{selectedValueTitles.join(', ') || FSI18n.string(componentTranslationKeys.all)}
</Text>
) : null}
</View>
<View style={[S.arrow, S.arrowNext]} />
</TouchableOpacity>
);
}
handleApply = () => {
this.props.onApply(this.state.selectedItems, { isButtonPress: true });
}
handleReset = () => {
this.setState({ selectedItems: {} });
this.props.onReset({ isButtonPress: true });
}
handleClose = () => {
if (this.props.onClose) {
this.props.onClose();
}
}
drilldown = (item: FilterItem) => () => {
this.setState({
secondLevelItem: item
});
}
backToFirstLevel = () => {
this.setState({
secondLevelItem: undefined
});
}
getKey = (item: any, index: number) => {
return index.toString();
}
renderEmptyCell = () => {
return (
<View style={[S.emptyCell, this.props.optionsFooterStyles]}/>
);
}
renderSecondLevel = (item: FilterItem, skipCustomRender?: boolean): JSX.Element => {
if (this.props.renderSecondLevel && !skipCustomRender) {
return this.props.renderSecondLevel(
item,
this.backToFirstLevel,
this.renderSecondLevel
);
}
return (
<View style={S.applyButton}>
<TouchableOpacity
style={[S.secondLevelHeader, this.props.secondLevelHeaderStyle]}
onPress={this.backToFirstLevel}
accessibilityRole={'button'}
accessibilityHint={FSI18n.string(componentTranslationKeys.hintBack)}
accessibilityLabel={item.title}
>
<View style={S.arrowContainer}>
<View style={[S.arrow, S.arrowBack]} />
</View>
<Text
style={[S.secondLevelTitle, this.props.secondLevelTitleStyle]}
>
{this.props.secondLevelTitle || item.title}
</Text>
{this.props.onClose && this.props.secondLevelShowClose ? (
<TouchableOpacity
style={[S.rightButton, this.props.closeButtonStyle]}
onPress={this.handleClose}
accessibilityRole={'button'}
accessibilityLabel={FSI18n.string(componentTranslationKeys.done)}
>
<Image
source={this.props.closeIcon || closeIcon}
style={[S.closeButtonImage, this.props.closeButtonImageStyle]}
/>
</TouchableOpacity>
) : null}
</TouchableOpacity>
<FlatList
keyExtractor={this.getKey}
data={item.values || []}
renderItem={this.renderFilterItemValue(item)}
extraData={this.state}
ListFooterComponent={this.props.secondLevelShowApply ? this.renderEmptyCell : undefined}
/>
{this.props.secondLevelShowApply ? (
<TouchableOpacity
style={[S.floatApplyButton, this.props.applyButtonStyle]}
onPress={this.handleApply}
accessibilityRole={'button'}
accessibilityLabel={FSI18n.string(componentTranslationKeys.apply)}
>
<Text style={[S.floatApplyButtonText, this.props.applyButtonTextStyle]}>
{this.props.applyText || FSI18n.string(componentTranslationKeys.apply)}
</Text>
</TouchableOpacity>
) : null}
</View>
);
}
renderDrilldownHeader = () => {
return (
<View style={[S.filterHeader, this.props.filterHeader]}>
{!this.props.floatingReset && Object.keys(this.state.selectedItems).length ? (
<TouchableOpacity
style={[S.resetButton, this.props.resetButtonStyle]}
onPress={this.handleReset}
accessibilityRole={'button'}
accessibilityLabel={FSI18n.string(componentTranslationKeys.clearAll)}
>
<Text style={this.props.resetButtonTextStyle}>
{this.props.resetText || FSI18n.string(componentTranslationKeys.clearAll)}
</Text>
</TouchableOpacity>
) : null}
{this.props.onClose ? (
<TouchableOpacity
style={[S.rightButton, this.props.closeButtonStyle]}
onPress={this.handleClose}
accessibilityRole={'button'}
accessibilityLabel={FSI18n.string(componentTranslationKeys.done)}
>
<Image
source={this.props.closeIcon || closeIcon}
style={[S.closeButtonImage, this.props.closeButtonImageStyle]}
/>
</TouchableOpacity>
) : (
<TouchableOpacity
style={[S.rightButton, this.props.applyButtonStyle]}
onPress={this.handleApply}
accessibilityRole={'button'}
accessibilityLabel={FSI18n.string(componentTranslationKeys.done)}
>
<Text style={this.props.applyButtonTextStyle}>
{this.props.applyText || FSI18n.string(componentTranslationKeys.done)}
</Text>
</TouchableOpacity>
)}
<Text style={[S.filterTitle, this.props.filterTitleStyle]}>
{this.props.refineText ||
FSI18n.string(translationKeys.flagship.sort.actions.refine.actionBtn)}
</Text>
</View>
);
}
render(): React.ReactNode {
return (
<View style={[S.container, this.props.style]}>
<View
style={{
flex: 1,
display: this.state.secondLevelItem ? 'none' : 'flex'
}}
>
{this.renderDrilldownHeader()}
<FlatList
data={this.props.items}
renderItem={this.renderFilterItem}
extraData={this.state.selectedItems}
ListFooterComponent={this.props.onClose ? this.renderEmptyCell : undefined}
/>
{this.props.onClose ? (
<TouchableOpacity
style={[S.floatApplyButton, this.props.applyButtonStyle]}
onPress={this.handleApply}
accessibilityRole={'button'}
accessibilityLabel={FSI18n.string(componentTranslationKeys.apply)}
>
<Text style={[S.floatApplyButtonText, this.props.applyButtonTextStyle]}>
{this.props.applyText || FSI18n.string(componentTranslationKeys.apply)}
</Text>
</TouchableOpacity>
) : null}
{this.props.floatingReset && Object.keys(this.state.selectedItems).length ? (
<TouchableOpacity
style={[S.floatResetButton, this.props.onClose ? undefined : {
bottom: 15
}, this.props.resetButtonStyle]}
onPress={this.handleReset}
accessibilityRole={'button'}
accessibilityLabel={FSI18n.string(componentTranslationKeys.clearAll)}
>
<Text style={[S.floatResetButtonText, this.props.resetButtonTextStyle]}>
{this.props.resetText || FSI18n.string(componentTranslationKeys.clearAll)}
</Text>
</TouchableOpacity>
) : null}
</View>
{this.state.secondLevelItem &&
this.renderSecondLevel(this.state.secondLevelItem)}
</View>
);
}
} | the_stack |
import type {
CallData,
CapacitorInstance,
ErrorCallData,
MessageCallData,
PluginResult,
WindowCapacitor,
} from './src/definitions-internal';
// For removing exports for iOS/Android, keep let for reassignment
// eslint-disable-next-line
let dummy = {};
const initBridge = (w: any): void => {
const getPlatformId = (win: WindowCapacitor): 'android' | 'ios' | 'web' => {
if (win?.androidBridge) {
return 'android';
} else if (win?.webkit?.messageHandlers?.bridge) {
return 'ios';
} else {
return 'web';
}
};
const convertFileSrcServerUrl = (
webviewServerUrl: string,
filePath: string,
): string => {
if (typeof filePath === 'string') {
if (filePath.startsWith('/')) {
return webviewServerUrl + '/_capacitor_file_' + filePath;
} else if (filePath.startsWith('file://')) {
return (
webviewServerUrl + filePath.replace('file://', '/_capacitor_file_')
);
} else if (filePath.startsWith('content://')) {
return (
webviewServerUrl +
filePath.replace('content:/', '/_capacitor_content_')
);
}
}
return filePath;
};
const initEvents = (win: WindowCapacitor, cap: CapacitorInstance) => {
cap.addListener = (pluginName, eventName, callback) => {
const callbackId = cap.nativeCallback(
pluginName,
'addListener',
{
eventName: eventName,
},
callback,
);
return {
remove: async () => {
win?.console?.debug('Removing listener', pluginName, eventName);
cap.removeListener(pluginName, callbackId, eventName, callback);
},
};
};
cap.removeListener = (pluginName, callbackId, eventName, callback) => {
cap.nativeCallback(
pluginName,
'removeListener',
{
callbackId: callbackId,
eventName: eventName,
},
callback,
);
};
cap.createEvent = (eventName, eventData) => {
const doc = win.document;
if (doc) {
const ev = doc.createEvent('Events');
ev.initEvent(eventName, false, false);
if (eventData && typeof eventData === 'object') {
for (const i in eventData) {
// eslint-disable-next-line no-prototype-builtins
if (eventData.hasOwnProperty(i)) {
ev[i] = eventData[i];
}
}
}
return ev;
}
return null;
};
cap.triggerEvent = (eventName, target, eventData) => {
const doc = win.document;
const cordova = win.cordova;
eventData = eventData || {};
const ev = cap.createEvent(eventName, eventData);
if (ev) {
if (target === 'document') {
if (cordova?.fireDocumentEvent) {
cordova.fireDocumentEvent(eventName, eventData);
return true;
} else if (doc?.dispatchEvent) {
return doc.dispatchEvent(ev);
}
} else if (target === 'window' && win.dispatchEvent) {
return win.dispatchEvent(ev);
} else if (doc?.querySelector) {
const targetEl = doc.querySelector(target);
if (targetEl) {
return targetEl.dispatchEvent(ev);
}
}
}
return false;
};
win.Capacitor = cap;
};
const initLegacyHandlers = (win: WindowCapacitor, cap: CapacitorInstance) => {
// define cordova if it's not there already
win.cordova = win.cordova || {};
const doc = win.document;
const nav = win.navigator;
if (nav) {
nav.app = nav.app || {};
nav.app.exitApp = () => {
if (!cap.Plugins || !cap.Plugins.App) {
win.console.warn('App plugin not installed');
} else {
cap.nativeCallback('App', 'exitApp', {});
}
};
}
if (doc) {
const docAddEventListener = doc.addEventListener;
doc.addEventListener = (...args: any[]) => {
const eventName = args[0];
const handler = args[1];
if (eventName === 'deviceready' && handler) {
Promise.resolve().then(handler);
} else if (eventName === 'backbutton' && cap.Plugins.App) {
// Add a dummy listener so Capacitor doesn't do the default
// back button action
if (!cap.Plugins || !cap.Plugins.App) {
win.console.warn('App plugin not installed');
} else {
cap.Plugins.App.addListener('backButton', () => {
// ignore
});
}
}
return docAddEventListener.apply(doc, args);
};
}
// deprecated in v3, remove from v4
cap.platform = cap.getPlatform();
cap.isNative = cap.isNativePlatform();
win.Capacitor = cap;
};
const initVendor = (win: WindowCapacitor, cap: CapacitorInstance) => {
const Ionic = (win.Ionic = win.Ionic || {});
const IonicWebView = (Ionic.WebView = Ionic.WebView || {});
const Plugins = cap.Plugins;
IonicWebView.getServerBasePath = (callback: (path: string) => void) => {
Plugins?.WebView?.getServerBasePath().then((result: any) => {
callback(result.path);
});
};
IonicWebView.setServerBasePath = (path: any) => {
Plugins?.WebView?.setServerBasePath({ path });
};
IonicWebView.persistServerBasePath = () => {
Plugins?.WebView?.persistServerBasePath();
};
IonicWebView.convertFileSrc = (url: string) => cap.convertFileSrc(url);
win.Capacitor = cap;
win.Ionic.WebView = IonicWebView;
};
const safeStringify = (value: any): string => {
const seen = new Set();
return JSON.stringify(value, (_k, v) => {
if (seen.has(v)) {
if (v === null) return null;
else return '...';
}
if (typeof v === 'object') {
seen.add(v);
}
return v;
});
};
const initLogger = (win: WindowCapacitor, cap: CapacitorInstance) => {
const BRIDGED_CONSOLE_METHODS: (keyof Console)[] = [
'debug',
'error',
'info',
'log',
'trace',
'warn',
];
const createLogFromNative =
(c: Partial<Console>) => (result: PluginResult) => {
if (isFullConsole(c)) {
const success = result.success === true;
const tagStyles = success
? 'font-style: italic; font-weight: lighter; color: gray'
: 'font-style: italic; font-weight: lighter; color: red';
c.groupCollapsed(
'%cresult %c' +
result.pluginId +
'.' +
result.methodName +
' (#' +
result.callbackId +
')',
tagStyles,
'font-style: italic; font-weight: bold; color: #444',
);
if (result.success === false) {
c.error(result.error);
} else {
c.dir(result.data);
}
c.groupEnd();
} else {
if (result.success === false) {
c.error('LOG FROM NATIVE', result.error);
} else {
c.log('LOG FROM NATIVE', result.data);
}
}
};
const createLogToNative =
(c: Partial<Console>) => (call: MessageCallData) => {
if (isFullConsole(c)) {
c.groupCollapsed(
'%cnative %c' +
call.pluginId +
'.' +
call.methodName +
' (#' +
call.callbackId +
')',
'font-weight: lighter; color: gray',
'font-weight: bold; color: #000',
);
c.dir(call);
c.groupEnd();
} else {
c.log('LOG TO NATIVE: ', call);
}
};
const isFullConsole = (c: Partial<Console>): c is Console => {
if (!c) {
return false;
}
return (
typeof c.groupCollapsed === 'function' ||
typeof c.groupEnd === 'function' ||
typeof c.dir === 'function'
);
};
const serializeConsoleMessage = (msg: any): string => {
if (typeof msg === 'object') {
try {
msg = safeStringify(msg);
} catch (e) {
// ignore
}
}
return String(msg);
};
// patch window.console on iOS and store original console fns
const isIos = getPlatformId(win) === 'ios';
if (win.console && isIos) {
Object.defineProperties(
win.console,
BRIDGED_CONSOLE_METHODS.reduce((props: any, method) => {
const consoleMethod = win.console[method].bind(win.console);
props[method] = {
value: (...args: any[]) => {
const msgs = [...args];
cap.toNative('Console', 'log', {
level: method,
message: msgs.map(serializeConsoleMessage).join(' '),
});
return consoleMethod(...args);
},
};
return props;
}, {}),
);
}
cap.logJs = (msg, level) => {
switch (level) {
case 'error':
win.console.error(msg);
break;
case 'warn':
win.console.warn(msg);
break;
case 'info':
win.console.info(msg);
break;
default:
win.console.log(msg);
}
};
cap.logToNative = createLogToNative(win.console);
cap.logFromNative = createLogFromNative(win.console);
cap.handleError = err => win.console.error(err);
win.Capacitor = cap;
};
function initNativeBridge(win: WindowCapacitor) {
const cap = win.Capacitor || ({} as CapacitorInstance);
// keep a collection of callbacks for native response data
const callbacks = new Map();
const webviewServerUrl =
typeof win.WEBVIEW_SERVER_URL === 'string' ? win.WEBVIEW_SERVER_URL : '';
cap.getServerUrl = () => webviewServerUrl;
cap.convertFileSrc = filePath =>
convertFileSrcServerUrl(webviewServerUrl, filePath);
// Counter of callback ids, randomized to avoid
// any issues during reloads if a call comes back with
// an existing callback id from an old session
let callbackIdCount = Math.floor(Math.random() * 134217728);
let postToNative: (data: CallData) => void | null = null;
const isNativePlatform = () => true;
const getPlatform = () => getPlatformId(win);
cap.getPlatform = getPlatform;
cap.isPluginAvailable = name =>
Object.prototype.hasOwnProperty.call(cap.Plugins, name);
cap.isNativePlatform = isNativePlatform;
// create the postToNative() fn if needed
if (getPlatformId(win) === 'android') {
// android platform
postToNative = data => {
try {
win.androidBridge.postMessage(safeStringify(data));
} catch (e) {
win?.console?.error(e);
}
};
} else if (getPlatformId(win) === 'ios') {
// ios platform
postToNative = data => {
try {
data.type = data.type ? data.type : 'message';
win.webkit.messageHandlers.bridge.postMessage(data);
} catch (e) {
win?.console?.error(e);
}
};
}
cap.handleWindowError = (msg, url, lineNo, columnNo, err) => {
const str = (msg as string).toLowerCase();
if (str.indexOf('script error') > -1) {
// Some IE issue?
} else {
const errObj: ErrorCallData = {
type: 'js.error',
error: {
message: msg as string,
url: url,
line: lineNo,
col: columnNo,
errorObject: safeStringify(err),
},
};
if (err !== null) {
cap.handleError(err);
}
postToNative(errObj);
}
return false;
};
if (cap.DEBUG) {
window.onerror = cap.handleWindowError;
}
initLogger(win, cap);
/**
* Send a plugin method call to the native layer
*/
cap.toNative = (pluginName, methodName, options, storedCallback) => {
try {
if (typeof postToNative === 'function') {
let callbackId = '-1';
if (
storedCallback &&
(typeof storedCallback.callback === 'function' ||
typeof storedCallback.resolve === 'function')
) {
// store the call for later lookup
callbackId = String(++callbackIdCount);
callbacks.set(callbackId, storedCallback);
}
const callData = {
callbackId: callbackId,
pluginId: pluginName,
methodName: methodName,
options: options || {},
};
if (cap.isLoggingEnabled && pluginName !== 'Console') {
cap.logToNative(callData);
}
// post the call data to native
postToNative(callData);
return callbackId;
} else {
win?.console?.warn(`implementation unavailable for: ${pluginName}`);
}
} catch (e) {
win?.console?.error(e);
}
return null;
};
/**
* Process a response from the native layer.
*/
cap.fromNative = result => {
if (cap.isLoggingEnabled && result.pluginId !== 'Console') {
cap.logFromNative(result);
}
// get the stored call, if it exists
try {
const storedCall = callbacks.get(result.callbackId);
if (storedCall) {
// looks like we've got a stored call
if (result.error) {
// ensure stacktraces by copying error properties to an Error
result.error = Object.keys(result.error).reduce((err, key) => {
// use any type to avoid importing util and compiling most of .ts files
(err as any)[key] = (result as any).error[key];
return err;
}, new cap.Exception(''));
}
if (typeof storedCall.callback === 'function') {
// callback
if (result.success) {
storedCall.callback(result.data);
} else {
storedCall.callback(null, result.error);
}
} else if (typeof storedCall.resolve === 'function') {
// promise
if (result.success) {
storedCall.resolve(result.data);
} else {
storedCall.reject(result.error);
}
// no need to keep this stored callback
// around for a one time resolve promise
callbacks.delete(result.callbackId);
}
} else if (!result.success && result.error) {
// no stored callback, but if there was an error let's log it
win?.console?.warn(result.error);
}
if (result.save === false) {
callbacks.delete(result.callbackId);
}
} catch (e) {
win?.console?.error(e);
}
// always delete to prevent memory leaks
// overkill but we're not sure what apps will do with this data
delete result.data;
delete result.error;
};
cap.nativeCallback = (pluginName, methodName, options, callback) => {
if (typeof options === 'function') {
console.warn(
`Using a callback as the 'options' parameter of 'nativeCallback()' is deprecated.`,
);
callback = options as any;
options = null;
}
return cap.toNative(pluginName, methodName, options, { callback });
};
cap.nativePromise = (pluginName, methodName, options) => {
return new Promise((resolve, reject) => {
cap.toNative(pluginName, methodName, options, {
resolve: resolve,
reject: reject,
});
});
};
cap.withPlugin = (_pluginId, _fn) => dummy;
initEvents(win, cap);
initLegacyHandlers(win, cap);
initVendor(win, cap);
win.Capacitor = cap;
}
initNativeBridge(w);
};
initBridge(
typeof globalThis !== 'undefined'
? (globalThis as WindowCapacitor)
: typeof self !== 'undefined'
? (self as WindowCapacitor)
: typeof window !== 'undefined'
? (window as WindowCapacitor)
: typeof global !== 'undefined'
? (global as WindowCapacitor)
: ({} as WindowCapacitor),
);
// Export only for tests
export { initBridge }; | the_stack |
import { NodeAPI } from 'node-red'
import HAPService2ConfigType from './types/HAPService2ConfigType'
import HAPService2NodeType from './types/HAPService2NodeType'
import HAPHostNodeType from './types/HAPHostNodeType'
import HostType from './types/HostType'
import { uuid } from 'hap-nodejs'
import { logger } from '@nrchkb/logger'
import { FlowTypeType } from './types/FlowType'
import NRCHKBError from './NRCHKBError'
module.exports = (RED: NodeAPI) => {
/**
* Config override when user created services in old NRCHKB version
*/
const nrchkbConfigCompatibilityOverride = function (
this: HAPService2NodeType
) {
const self = this
const log = logger('NRCHKB', 'HAPServiceNode2', self.config.name, self)
if (self.config.isParent === undefined) {
log.trace(
`nrchkbConfigCompatibilityOverride => self.config.isParent=${self.config.isParent} value changed to true`
)
// Services created in pre linked services era where working in 1.2 but due to more typescript in 1.3+ it started to cause some errors
self.config.isParent = true
}
if (self.config.hostType === undefined) {
// When moving from 1.2 to 1.3 hostType is not defined on homekit-service
log.trace(
`nrchkbConfigCompatibilityOverride => self.config.hostType=${self.config.hostType} value changed to HostType.BRIDGE`
)
self.config.hostType = HostType.BRIDGE
}
}
const preInit = function (
this: HAPService2NodeType,
config: HAPService2ConfigType
) {
const self = this
self.lastStatusId = 0
self.setStatus = (status) => {
self.status(status)
self.lastStatusId = new Date().getTime()
return self.lastStatusId
}
self.clearStatus = (statusId) => {
if (statusId === self.lastStatusId) {
self.setStatus({})
}
}
self.config = config
self.name = self.config.name
const log = logger('NRCHKB', 'HAPServiceNode2', self.config.name, self)
self.RED = RED
self.publishTimers = {}
nrchkbConfigCompatibilityOverride.call(self)
RED.nodes.createNode(self, self.config)
const ServiceUtils = require('./utils/ServiceUtils2')(self)
new Promise<HAPService2ConfigType>((resolve) => {
if (self.config.waitForSetupMsg) {
log.debug(
'Waiting for Setup message. It should be of format {"payload":{"nrchkb":{"setup":{}}}}'
)
self.setupDone = false
self.setStatus({
fill: 'blue',
shape: 'dot',
text: 'Waiting for Setup',
})
self.handleWaitForSetup = (msg: Record<string, unknown>) =>
ServiceUtils.handleWaitForSetup(self.config, msg, resolve)
self.on('input', self.handleWaitForSetup)
} else {
resolve(self.config)
}
})
.then((newConfig) => {
init.call(self, newConfig)
})
.catch((error: any) => {
log.error(`Error while starting Service due to ${error}`)
})
}
const init = function (
this: HAPService2NodeType,
config: HAPService2ConfigType
) {
const self = this
self.config = config
const log = logger('NRCHKB', 'HAPServiceNode2', self.config.name, self)
const ServiceUtils = require('./utils/ServiceUtils2')(self)
if (self.config.isParent) {
log.debug('Starting Parent Service')
configure.call(self)
self.configured = true
} else {
const serviceType =
config.serviceName === 'CameraControl' ? 'Camera' : 'Linked'
ServiceUtils.waitForParent()
.then(() => {
log.debug(`Starting ${serviceType} Service`)
configure.call(self)
self.configured = true
})
.catch((error: any) => {
log.error(
`Error while starting ${serviceType} Service due to ${error}`
)
})
}
}
const configure = function (this: HAPService2NodeType) {
const self = this
const log = logger('NRCHKB', 'HAPServiceNode2', self.config.name, self)
const Utils = require('./utils')(self)
const AccessoryUtils = Utils.AccessoryUtils
const BridgeUtils = Utils.BridgeUtils
const CharacteristicUtils = require('./utils/CharacteristicUtils2')(
self
)
const ServiceUtils = require('./utils/ServiceUtils2')(self)
let parentNode: HAPService2NodeType
if (self.config.isParent) {
const hostId =
self.config.hostType == HostType.BRIDGE
? self.config.bridge
: self.config.accessoryId
self.hostNode = RED.nodes.getNode(hostId) as HAPHostNodeType
if (!self.hostNode) {
log.error('Host Node not found', false)
throw new NRCHKBError('Host Node not found')
}
self.childNodes = []
self.childNodes.push(self)
} else {
// Retrieve parent service node
parentNode = RED.nodes.getNode(
self.config.parentService
) as HAPService2NodeType
if (!parentNode) {
log.error('Parent Node not assigned', false)
throw new NRCHKBError('Parent Node not assigned')
}
self.parentService = parentNode.service
if (!self.parentService) {
log.error('Parent Service not assigned', false)
throw new NRCHKBError('Parent Service not assigned')
}
self.hostNode = parentNode.hostNode
parentNode.childNodes.push(self)
self.accessory = parentNode.accessory
}
// Service node properties
self.name = self.config.name
// Find a unique identifier for the current service
if (
self.hasOwnProperty('_flow') &&
self.hasOwnProperty('_alias') &&
self._flow.hasOwnProperty('TYPE') &&
FlowTypeType.Subflow == self._flow.TYPE
) {
// For subflows, use the service node identifier from the subflow template
// plus the full path from the subflow node identifier to the subflow.
self.uniqueIdentifier = self._alias + '/' + self._flow.path
} else {
// For top level flows, use the node identifier
self.uniqueIdentifier = self.id
}
// Generate UUID from unique identifier
const subtypeUUID = uuid.generate(self.uniqueIdentifier)
// Look for existing Accessory or create a new one
if (self.config.hostType == HostType.BRIDGE) {
if (self.config.isParent) {
// According to the HomeKit Accessory Protocol Specification the value
// of the fields Name, Manufacturer, Serial Number and Model must not
// change throughout the lifetime of an accessory. Because of that the
// accessory UUID will be generated based on that data to ensure that
// a new accessory will be created if any of those configuration values
// changes.
const accessoryUUID = uuid.generate(
'A' +
self.uniqueIdentifier +
self.name +
self.config.manufacturer +
self.config.serialNo +
self.config.model
)
self.accessory = AccessoryUtils.getOrCreate(
self.hostNode.host,
{
name: self.name,
UUID: accessoryUUID,
manufacturer: self.config.manufacturer,
serialNo: self.config.serialNo,
model: self.config.model,
firmwareRev: self.config.firmwareRev,
hardwareRev: self.config.hardwareRev,
softwareRev: self.config.softwareRev,
},
subtypeUUID // subtype of the primary service for identification
)
//Respond to identify
self.onIdentify = AccessoryUtils.onIdentify
self.accessory.on('identify', self.onIdentify)
}
} else {
// We are using Standalone Accessory mode so no need to create new Accessory as we have "host" already
log.debug('Binding Service accessory as Standalone Accessory')
self.accessory = self.hostNode.host
}
// Look for existing Service or create a new one
self.service = ServiceUtils.getOrCreate(
self.accessory,
{
name: self.name,
UUID: subtypeUUID,
serviceName: self.config.serviceName,
config: self.config,
},
self.parentService
)
self.characteristicProperties = CharacteristicUtils.load(
self.service,
self.config
)
if (self.config.isParent) {
BridgeUtils.delayedPublish(self)
}
// The pinCode should be shown to the user until interaction with iOS
// client starts
self.setStatus({
fill: 'yellow',
shape: 'ring',
text: self.hostNode.config.pinCode,
})
// Emit message when value changes
// service.on("characteristic-change", ServiceUtils.onCharacteristicChange);
// Subscribe to set and get on characteristics for that service and get
// list of all supported
self.supported = CharacteristicUtils.subscribeAndGetSupported(
self.service
)
// Respond to inputs
self.on('input', ServiceUtils.onInput)
self.on('close', ServiceUtils.onClose)
}
return {
preInit,
init,
}
} | the_stack |
import type * as vscode from 'vscode';
import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import { IEditorTabDto, IEditorTabGroupDto, IExtHostEditorTabsShape, MainContext, MainThreadEditorTabsShape, TabInputKind, TabModelOperationKind, TabOperation } from 'vs/workbench/api/common/extHost.protocol';
import { URI } from 'vs/base/common/uri';
import { Emitter } from 'vs/base/common/event';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { CustomEditorTabInput, NotebookDiffEditorTabInput, NotebookEditorTabInput, TerminalEditorTabInput, TextDiffTabInput, TextTabInput, WebviewEditorTabInput } from 'vs/workbench/api/common/extHostTypes';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { assertIsDefined } from 'vs/base/common/types';
import { diffSets } from 'vs/base/common/collections';
export interface IExtHostEditorTabs extends IExtHostEditorTabsShape {
readonly _serviceBrand: undefined;
tabGroups: vscode.TabGroups;
}
export const IExtHostEditorTabs = createDecorator<IExtHostEditorTabs>('IExtHostEditorTabs');
type AnyTabInput = TextTabInput | TextDiffTabInput | CustomEditorTabInput | NotebookEditorTabInput | NotebookDiffEditorTabInput | WebviewEditorTabInput | TerminalEditorTabInput;
class ExtHostEditorTab {
private _apiObject: vscode.Tab | undefined;
private _dto!: IEditorTabDto;
private _input: AnyTabInput | undefined;
private _parentGroup: ExtHostEditorTabGroup;
private readonly _activeTabIdGetter: () => string;
constructor(dto: IEditorTabDto, parentGroup: ExtHostEditorTabGroup, activeTabIdGetter: () => string) {
this._activeTabIdGetter = activeTabIdGetter;
this._parentGroup = parentGroup;
this.acceptDtoUpdate(dto);
}
get apiObject(): vscode.Tab {
if (!this._apiObject) {
// Don't want to lose reference to parent `this` in the getters
const that = this;
const obj: vscode.Tab = {
get isActive() {
// We use a getter function here to always ensure at most 1 active tab per group and prevent iteration for being required
return that._dto.id === that._activeTabIdGetter();
},
get label() {
return that._dto.label;
},
get input() {
return that._input;
},
get isDirty() {
return that._dto.isDirty;
},
get isPinned() {
return that._dto.isPinned;
},
get isPreview() {
return that._dto.isPreview;
},
get group() {
return that._parentGroup.apiObject;
}
};
this._apiObject = Object.freeze<vscode.Tab>(obj);
}
return this._apiObject;
}
get tabId(): string {
return this._dto.id;
}
acceptDtoUpdate(dto: IEditorTabDto) {
this._dto = dto;
this._input = this._initInput();
}
private _initInput() {
switch (this._dto.input.kind) {
case TabInputKind.TextInput:
return new TextTabInput(URI.revive(this._dto.input.uri));
case TabInputKind.TextDiffInput:
return new TextDiffTabInput(URI.revive(this._dto.input.original), URI.revive(this._dto.input.modified));
case TabInputKind.CustomEditorInput:
return new CustomEditorTabInput(URI.revive(this._dto.input.uri), this._dto.input.viewType);
case TabInputKind.WebviewEditorInput:
return new WebviewEditorTabInput(this._dto.input.viewType);
case TabInputKind.NotebookInput:
return new NotebookEditorTabInput(URI.revive(this._dto.input.uri), this._dto.input.notebookType);
case TabInputKind.NotebookDiffInput:
return new NotebookDiffEditorTabInput(URI.revive(this._dto.input.original), URI.revive(this._dto.input.modified), this._dto.input.notebookType);
case TabInputKind.TerminalEditorInput:
return new TerminalEditorTabInput();
default:
return undefined;
}
}
}
class ExtHostEditorTabGroup {
private _apiObject: vscode.TabGroup | undefined;
private _dto: IEditorTabGroupDto;
private _tabs: ExtHostEditorTab[] = [];
private _activeTabId: string = '';
private _activeGroupIdGetter: () => number | undefined;
constructor(dto: IEditorTabGroupDto, proxy: MainThreadEditorTabsShape, activeGroupIdGetter: () => number | undefined) {
this._dto = dto;
this._activeGroupIdGetter = activeGroupIdGetter;
// Construct all tabs from the given dto
for (const tabDto of dto.tabs) {
if (tabDto.isActive) {
this._activeTabId = tabDto.id;
}
this._tabs.push(new ExtHostEditorTab(tabDto, this, () => this.activeTabId()));
}
}
get apiObject(): vscode.TabGroup {
if (!this._apiObject) {
// Don't want to lose reference to parent `this` in the getters
const that = this;
const obj: vscode.TabGroup = {
get isActive() {
// We use a getter function here to always ensure at most 1 active group and prevent iteration for being required
return that._dto.groupId === that._activeGroupIdGetter();
},
get viewColumn() {
return typeConverters.ViewColumn.to(that._dto.viewColumn);
},
get activeTab() {
return that._tabs.find(tab => tab.tabId === that._activeTabId)?.apiObject;
},
get tabs() {
return Object.freeze(that._tabs.map(tab => tab.apiObject));
}
};
this._apiObject = Object.freeze<vscode.TabGroup>(obj);
}
return this._apiObject;
}
get groupId(): number {
return this._dto.groupId;
}
get tabs(): ExtHostEditorTab[] {
return this._tabs;
}
acceptGroupDtoUpdate(dto: IEditorTabGroupDto) {
this._dto = dto;
}
acceptTabOperation(operation: TabOperation): ExtHostEditorTab {
// In the open case we add the tab to the group
if (operation.kind === TabModelOperationKind.TAB_OPEN) {
const tab = new ExtHostEditorTab(operation.tabDto, this, () => this.activeTabId());
// Insert tab at editor index
this._tabs.splice(operation.index, 0, tab);
if (operation.tabDto.isActive) {
this._activeTabId = tab.tabId;
}
return tab;
} else if (operation.kind === TabModelOperationKind.TAB_CLOSE) {
const tab = this._tabs.splice(operation.index, 1)[0];
if (!tab) {
throw new Error(`Tab close updated received for index ${operation.index} which does not exist`);
}
if (tab.tabId === this._activeTabId) {
this._activeTabId = '';
}
return tab;
} else if (operation.kind === TabModelOperationKind.TAB_MOVE) {
if (operation.oldIndex === undefined) {
throw new Error('Invalid old index on move IPC');
}
// Splice to remove at old index and insert at new index === moving the tab
const tab = this._tabs.splice(operation.oldIndex, 1)[0];
if (!tab) {
throw new Error(`Tab move updated received for index ${operation.oldIndex} which does not exist`);
}
this._tabs.splice(operation.index, 0, tab);
return tab;
}
const tab = this._tabs.find(extHostTab => extHostTab.tabId === operation.tabDto.id);
if (!tab) {
throw new Error('INVALID tab');
}
if (operation.tabDto.isActive) {
this._activeTabId = operation.tabDto.id;
} else if (this._activeTabId === operation.tabDto.id && !operation.tabDto.isActive) {
// Events aren't guaranteed to be in order so if we receive a dto that matches the active tab id
// but isn't active we mark the active tab id as empty. This prevent onDidActiveTabChange frorm
// firing incorrectly
this._activeTabId = '';
}
tab.acceptDtoUpdate(operation.tabDto);
return tab;
}
// Not a getter since it must be a function to be used as a callback for the tabs
activeTabId(): string {
return this._activeTabId;
}
}
export class ExtHostEditorTabs implements IExtHostEditorTabs {
readonly _serviceBrand: undefined;
private readonly _proxy: MainThreadEditorTabsShape;
private readonly _onDidChangeTabs = new Emitter<vscode.TabChangeEvent>();
private readonly _onDidChangeTabGroups = new Emitter<vscode.TabGroupChangeEvent>();
// Have to use ! because this gets initialized via an RPC proxy
private _activeGroupId!: number;
private _extHostTabGroups: ExtHostEditorTabGroup[] = [];
private _apiObject: vscode.TabGroups | undefined;
constructor(@IExtHostRpcService extHostRpc: IExtHostRpcService) {
this._proxy = extHostRpc.getProxy(MainContext.MainThreadEditorTabs);
}
get tabGroups(): vscode.TabGroups {
if (!this._apiObject) {
const that = this;
const obj: vscode.TabGroups = {
// never changes -> simple value
onDidChangeTabGroups: that._onDidChangeTabGroups.event,
onDidChangeTabs: that._onDidChangeTabs.event,
// dynamic -> getters
get all() {
return Object.freeze(that._extHostTabGroups.map(group => group.apiObject));
},
get activeTabGroup() {
const activeTabGroupId = that._activeGroupId;
const activeTabGroup = assertIsDefined(that._extHostTabGroups.find(candidate => candidate.groupId === activeTabGroupId)?.apiObject);
return activeTabGroup;
},
close: async (tabOrTabGroup: vscode.Tab | readonly vscode.Tab[] | vscode.TabGroup | readonly vscode.TabGroup[], preserveFocus?: boolean) => {
const tabsOrTabGroups = Array.isArray(tabOrTabGroup) ? tabOrTabGroup : [tabOrTabGroup];
if (!tabsOrTabGroups.length) {
return true;
}
// Check which type was passed in and call the appropriate close
// Casting is needed as typescript doesn't seem to infer enough from this
if (isTabGroup(tabsOrTabGroups[0])) {
return this._closeGroups(tabsOrTabGroups as vscode.TabGroup[], preserveFocus);
} else {
return this._closeTabs(tabsOrTabGroups as vscode.Tab[], preserveFocus);
}
},
// move: async (tab: vscode.Tab, viewColumn: ViewColumn, index: number, preservceFocus?: boolean) => {
// const extHostTab = this._findExtHostTabFromApi(tab);
// if (!extHostTab) {
// throw new Error('Invalid tab');
// }
// this._proxy.$moveTab(extHostTab.tabId, index, typeConverters.ViewColumn.from(viewColumn), preservceFocus);
// return;
// }
};
this._apiObject = Object.freeze(obj);
}
return this._apiObject;
}
$acceptEditorTabModel(tabGroups: IEditorTabGroupDto[]): void {
const groupIdsBefore = new Set(this._extHostTabGroups.map(group => group.groupId));
const groupIdsAfter = new Set(tabGroups.map(dto => dto.groupId));
const diff = diffSets(groupIdsBefore, groupIdsAfter);
const closed: vscode.TabGroup[] = this._extHostTabGroups.filter(group => diff.removed.includes(group.groupId)).map(group => group.apiObject);
const opened: vscode.TabGroup[] = [];
const changed: vscode.TabGroup[] = [];
this._extHostTabGroups = tabGroups.map(tabGroup => {
const group = new ExtHostEditorTabGroup(tabGroup, this._proxy, () => this._activeGroupId);
if (diff.added.includes(group.groupId)) {
opened.push(group.apiObject);
} else {
changed.push(group.apiObject);
}
return group;
});
// Set the active tab group id
const activeTabGroupId = assertIsDefined(tabGroups.find(group => group.isActive === true)?.groupId);
if (activeTabGroupId !== undefined && this._activeGroupId !== activeTabGroupId) {
this._activeGroupId = activeTabGroupId;
}
this._onDidChangeTabGroups.fire(Object.freeze({ opened, closed, changed }));
}
$acceptTabGroupUpdate(groupDto: IEditorTabGroupDto) {
const group = this._extHostTabGroups.find(group => group.groupId === groupDto.groupId);
if (!group) {
throw new Error('Update Group IPC call received before group creation.');
}
group.acceptGroupDtoUpdate(groupDto);
if (groupDto.isActive) {
this._activeGroupId = groupDto.groupId;
}
this._onDidChangeTabGroups.fire(Object.freeze({ changed: [group.apiObject], opened: [], closed: [] }));
}
$acceptTabOperation(operation: TabOperation) {
const group = this._extHostTabGroups.find(group => group.groupId === operation.groupId);
if (!group) {
throw new Error('Update Tabs IPC call received before group creation.');
}
const tab = group.acceptTabOperation(operation);
// Construct the tab change event based on the operation
switch (operation.kind) {
case TabModelOperationKind.TAB_OPEN:
this._onDidChangeTabs.fire(Object.freeze({
opened: [tab.apiObject],
closed: [],
changed: []
}));
return;
case TabModelOperationKind.TAB_CLOSE:
this._onDidChangeTabs.fire(Object.freeze({
opened: [],
closed: [tab.apiObject],
changed: []
}));
return;
case TabModelOperationKind.TAB_MOVE:
case TabModelOperationKind.TAB_UPDATE:
this._onDidChangeTabs.fire(Object.freeze({
opened: [],
closed: [],
changed: [tab.apiObject]
}));
return;
}
}
private _findExtHostTabFromApi(apiTab: vscode.Tab): ExtHostEditorTab | undefined {
for (const group of this._extHostTabGroups) {
for (const tab of group.tabs) {
if (tab.apiObject === apiTab) {
return tab;
}
}
}
return;
}
private _findExtHostTabGroupFromApi(apiTabGroup: vscode.TabGroup): ExtHostEditorTabGroup | undefined {
return this._extHostTabGroups.find(candidate => candidate.apiObject === apiTabGroup);
}
private async _closeTabs(tabs: vscode.Tab[], preserveFocus?: boolean): Promise<boolean> {
const extHostTabIds: string[] = [];
for (const tab of tabs) {
const extHostTab = this._findExtHostTabFromApi(tab);
if (!extHostTab) {
throw new Error('Tab close: Invalid tab not found!');
}
extHostTabIds.push(extHostTab.tabId);
}
return this._proxy.$closeTab(extHostTabIds, preserveFocus);
}
private async _closeGroups(groups: vscode.TabGroup[], preserverFoucs?: boolean): Promise<boolean> {
const extHostGroupIds: number[] = [];
for (const group of groups) {
const extHostGroup = this._findExtHostTabGroupFromApi(group);
if (!extHostGroup) {
throw new Error('Group close: Invalid group not found!');
}
extHostGroupIds.push(extHostGroup.groupId);
}
return this._proxy.$closeGroup(extHostGroupIds, preserverFoucs);
}
}
//#region Utils
function isTabGroup(obj: unknown): obj is vscode.TabGroup {
const tabGroup = obj as vscode.TabGroup;
if (tabGroup.tabs !== undefined) {
return true;
}
return false;
}
//#endregion | the_stack |
// TypeScript Version: 2.1
/**
* The animator class is useful for creating an animation loop. We supply pre and post events for apply animation changes between frames.
*/
export class Animator {
dispatch: Events.Dispatcher;
timestamp: number;
frameDelay: number | null;
constructor();
animateFrame(): this;
frame(t?: boolean): this;
onAfter(handler: FrameHandler): this;
onBefore(handler: FrameHandler): this;
onFrame(handler: FrameHandler): this;
start(): this;
stop(): this;
}
export interface FrameHandler {
(timestamp: number, deltaTimestamp: number): void;
}
/**
* The Bounds object contains an axis-aligned bounding box.
*/
export class Bounds {
constructor();
add(p: Point): this;
center(): Point;
contains(p: Point): boolean;
copy(): this;
depth(): number;
height(): number;
intersect(box: Bounds): this;
maxX(): number;
maxY(): number;
maxZ(): number;
minX(): number;
minY(): number;
minZ(): number;
pad(x: number, y: number, z: number): this;
reset(): this;
valid(): boolean;
width(): number;
static points(points: Point[]): Bounds;
static xywh(x: number, y: number, w: number, h: number): Bounds;
static xyzwhd(x: number, y: number, z: number, w: number, h: number, d: number): Bounds;
}
/**
* The Camera model contains all three major components of the 3D to 2D tranformation.
*
* First, we transform object from world-space (the same space that the coordinates of surface points are in after all their transforms are applied) to camera space. Typically, this will place all
* viewable objects into a cube with coordinates: x = -1 to 1, y = -1 to 1, z = 1 to 2
*
* Second, we apply the projection trasform to create perspective parallax and what not.
*
* Finally, we rescale to the viewport size.
*
* These three steps allow us to easily create shapes whose coordinates match up to screen coordinates in the z = 0 plane.
*/
export class Camera extends Transformable {
projection: Matrix;
defaults: { projection: Matrix };
constructor(transform?: Matrix);
}
export class CanvasCirclePainter extends CanvasStyler {
circle(center: { x: number, y: number }, radius: number): CanvasCirclePainter;
}
export class CanvasLayerRenderContext extends RenderLayerContext {
constructor(ctx: CanvasRenderingContext2D);
circle(): CanvasCirclePainter;
path(): CanvasPathPainter;
rect(): CanvasRectPainter;
text(): CanvasTextPainter;
}
export class CanvasPathPainter extends CanvasStyler {
path(points: Point[]): this;
}
export class CanvasRectPainter extends CanvasStyler {
rect(width: number, height: number): this;
}
export class CanvasRenderContext extends RenderContext {
el: HTMLCanvasElement;
ctx: CanvasRenderingContext2D;
constructor(elementOrId: string | HTMLElement);
layer(layer: RenderLayerContext): this;
reset(): void;
}
export class CanvasStyler {
constructor(ctx: CanvasRenderingContext2D);
draw(style?: { stroke?: string | undefined, 'stroke-width'?: number | undefined, 'text-anchor'?: string | undefined }): this;
fill(style?: { fill?: string | undefined, 'fill-opacity'?: number | undefined, 'text-anchor'?: string | undefined }): this;
}
export class CanvasTextPainter {
constructor(ctx: CanvasRenderingContext2D);
fillText(m: Matrix, text: string, style?: { font: string, fill?: string | undefined, 'text-anchor'?: string | undefined }): this;
}
/**
* Color objects store RGB and Alpha values from 0 to 255.
*/
export class Color {
r: number;
g: number;
b: number;
a: number;
constructor(r?: number, g?: number, b?: number, a?: number);
addChannels(c: Color): this;
clamp(min?: number, max?: number): this;
copy(): this;
hex(): string;
minChannels(c: Color): this;
multiplyChannels(c: Color): this;
offset(n: number): this;
scale(n: number): this;
style(): string;
}
/**
* Adds simple mouse drag eventing to a DOM element. A ‘drag’ event is emitted as the user is dragging their mouse. This is the easiest way to add mouse- look or mouse-rotate to a scene.
*/
export class Drag {
el: HTMLElement;
inertia: boolean;
dispatch: Events.Dispatcher;
defaults: { inertia: boolean };
constructor(elementOrId: string | HTMLElement, options?: { inertia?: boolean | undefined });
on(type: string, listener: (e: { offset: number[], offsetRelative: number[] }) => void): Events.Dispatcher;
}
export class FillLayer extends RenderLayer {
constructor(width: number, height: number, fill: string);
render(context: RenderLayerContext): void;
}
export class Grad {
x: number;
y: number;
z: number;
constructor(x: number, y: number, z: number);
dot(x: number, y: number, z: number): number;
}
/**
* A class for computing mouse interia for interial scrolling
*/
export class InertialMouse {
xy: number[];
constructor();
damp(): this;
get(): [number, number];
reset(): this;
update(xy: [number, number]): this;
static inertiaExtinction: number;
static inertiaMsecDelay: number;
static smoothingTimeout: number;
}
export interface LightOptions {
point?: Point | undefined;
color?: Color | undefined;
intensity?: number | undefined;
normal?: Point | undefined;
enabled?: boolean | undefined;
}
/**
* This model object holds the attributes and transformation of a light source.
*/
export class Light extends Transformable {
type: string;
point: Point;
color: Color;
intensity: number;
normal: Point;
enabled: boolean;
id: string;
defaults: LightOptions;
constructor(type: 'point' | 'directional' | 'ambient', options?: LightOptions);
render(): void;
}
/**
* The LightRenderModel stores pre-computed values necessary for shading surfaces with the supplied Light.
*/
export class LightRenderModel {
colorIntensity: Color;
type: string;
intensity: number;
point: Point;
origin: Point;
normal: Point;
constructor(light: Light, transform: Matrix);
}
export interface MaterialOptions {
color?: Color | undefined;
metallic?: boolean | undefined;
specularColor?: Color | undefined;
specularExponent?: number | undefined;
shader?: Shader | undefined;
}
/**
* Material objects hold the attributes that desribe the color and finish of a surface.
*/
export class Material {
color: Color;
metallic: boolean;
specularColor: Color;
specularExponent: number;
shader: Shader;
defaults: MaterialOptions;
constructor(color?: Color, options?: MaterialOptions);
render(lights?: Light[], shader?: Shader, renderData?: RenderModel): Color;
static create(value?: Material | Color | string): Material;
}
/**
* The Matrix class stores transformations in the scene. These include: (1) Camera Projection and Viewport transformations. (2) Transformations of any Transformable type object, such as Shapes or
* Models
*
* Most of the methods on Matrix are destructive, so be sure to use .copy() when you want to preserve an object’s value.
*/
export class Matrix {
m: number[];
baked: number[];
constructor(m?: number[]);
bake(m?: number[]): this;
copy(): this;
matrix(m: number[]): this;
multiply(b: Matrix): this;
reset(): this;
rotx(theta: number): this;
roty(theta: number): this;
rotz(theta: number): this;
scale(x?: number, y?: number, z?: number): this;
translate(x?: number, y?: number, z?: number): this;
transpose(): this;
}
export class Mocap {
bvh: any;
constructor(bvh?: any);
createMocapModel(shapeFactory?: () => Shape): MocapModel;
static DEFAULT_SHAPE_FACTORY(joint?: any, endpoint?: Point): Shape;
static parse(source: string): Mocap;
}
export class MocapAnimator extends Animator {
constructor(mocap: MocapModel);
renderFrame(): void;
}
export class MocapModel {
constructor(model: Model, frames: any[], frameDelay?: number);
applyFrameTransforms(frameIndex: number): number;
}
/**
* The object model class. It stores Shapes, Lights, and other Models as well as a transformation matrix.
*
* Notably, models are hierarchical, like a tree. This means you can isolate the transformation of groups of shapes in the scene, as well as create chains of transformations for creating, for
* example, articulated skeletons.
*/
export class Model extends Transformable {
constructor();
add(...args: Array<Shape | Model | Light>): this;
append(): this;
eachRenderable(lightFn: (light: Light, matrix?: Matrix) => Model, shapeFn: (item: Shape | Model, lightModels?: Model[], matrix?: Matrix) => any): void;
eachShape(f: (shape: Shape) => any): void;
remove(...args: Array<Shape | Model | Light>): void;
}
export interface MouseEventOptions {
dragStart?: EventListener | undefined;
drag?: EventListener | undefined;
dragEnd?: EventListener | undefined;
mouseMove?: EventListener | undefined;
mouseDown?: EventListener | undefined;
mouseUp?: EventListener | undefined;
mouseWheel?: EventListener | undefined;
}
/**
* An event dispatcher for mouse and drag events on a single dom element. The available events are 'dragStart', 'drag', 'dragEnd', 'mouseMove', 'mouseDown', 'mouseUp', 'mouseWheel'
*/
export class MouseEvents {
el: HTMLElement;
dispatch: Events.Dispatcher;
constructor(elementOrId: string | HTMLElement, options?: MouseEventOptions);
attach(): void;
detach(): void;
}
/**
* Parser for Wavefront .obj files
*
* Note: Wavefront .obj array indicies are 1-based.
*/
export class ObjParser {
vertices: number[][];
faces: number[][];
commands: { v: (v: any) => any, f: (f: any) => any };
constructor();
mapFacePoints(faceMap: (points: Point[]) => any): void;
parse(contents: string): void;
}
/**
* Each Painter overrides the paint method. It uses the supplied RenderLayerContext‘s builders to create and style the geometry on screen.
*/
export class Painter {
constructor();
paint(renderModel: RenderModel, context: RenderLayerContext): void;
}
export class PathPainter extends Painter { }
/**
* The Point object contains x,y,z, and w coordinates. Points support various arithmetic operations with other Points, scalars, or Matrices.
*
* Most of the methods on Point are destructive, so be sure to use .copy() when you want to preserve an object’s value.
*/
export class Point {
x: number;
y: number;
z: number;
w: number;
constructor(x?: number, y?: number, z?: number, w?: number);
add(q: Point): this;
copy(): this;
cross(q: Point): this;
divide(n: number): this;
dot(q: Point): number;
magnitude(): number;
magnitudeSquared(): number;
multiply(n: number): this;
normalize(): this;
perpendicular(): this;
round(): this;
set(p: Point): this;
subtract(q: Point): this;
transform(matrix: Matrix): this;
translate(x: number, y: number, z: number): this;
}
/**
* A Quaterionion class for computing quaterion multiplications. This creates more natural mouse rotations.
*/
export class Quaternion {
q: Point;
constructor();
multiply(q: Point): this;
toMatrix(): Matrix;
static axisAngle(x: number, y: number, z: number, angleRads: number): Quaternion;
static pixelsPerRadian: number;
static pointAngle(p: Point, angleRads: number): Quaternion;
static xyToTransform(x: number, y: number): Matrix;
}
export class RenderAnimator extends Animator { }
/**
* The RenderContext uses RenderModels produced by the scene’s render method to paint the shapes into an HTML element. Since we support both SVG and Canvas painters, the RenderContext and
* RenderLayerContext define a common interface.
*/
export class RenderContext {
layers: RenderLayerContext[];
constructor();
animate(): RenderAnimator;
cleanup(): void;
layer(layer: RenderLayerContext): this;
render(): this;
reset(): void;
sceneLayer(scene: Scene): this;
}
export class RenderLayer {
constructor();
render(context: RenderLayerContext): void;
}
/**
* The RenderLayerContext defines the interface for producing painters that can paint various things into the current layer.
*/
export class RenderLayerContext {
constructor();
circle(): any;
cleanup(): void;
path(): any;
rect(): any;
reset(): void;
text(): any;
}
/**
* The RenderModel object contains the transformed and projected points as well as various data needed to shade and paint a Surface.
*
* Once initialized, the object will have a constant memory footprint down to Number primitives. Also, we compare each transform and projection to prevent unnecessary re-computation.
*
* If you need to force a re-computation, mark the surface as ‘dirty’.
*/
export class RenderModel {
constructor(surface: Surface, transform: Matrix, projection: Matrix, viewport: Matrix);
update(transform: Matrix, projection: Matrix, viewport: Matrix): void;
}
/**
* A Scene is the main object for a view of a scene.
*/
export class Scene {
constructor(options?: SceneOptions);
defaults(): SceneOptions;
flushCache(): void;
render(): Transformable[];
}
export interface SceneOptions {
model?: Model | undefined;
camera?: Camera | undefined;
viewport?: Viewport | undefined;
shader?: Shader | undefined;
cullBackfaces?: boolean | undefined;
fractionalPoints?: boolean | undefined;
cache?: boolean | undefined;
}
export class SceneLayer extends RenderLayer {
model: Model;
camera: Camera;
viewport: Viewport;
shader: Shader;
cullBackfaces: boolean;
fractionalPoints: boolean;
cache: boolean;
constructor(scene: Scene);
render(context: RenderLayerContext): void;
}
/**
* The Shader class is the base class for all shader objects.
*/
export class Shader {
constructor();
shade(lights: Light[], renderModel: RenderModel, material: Material): void;
}
/**
* The Phong shader implements the Phong shading model with a diffuse, specular, and ambient term.
*
* See https://en.wikipedia.org/wiki/Phong_reflection_model for more information
*/
export class Phong extends Shader { }
/**
* The DiffusePhong shader implements the Phong shading model with a diffuse and ambient term (no specular).
*/
export class DiffusePhong extends Shader { }
/**
* The Ambient shader colors surfaces from ambient light only.
*/
export class Ambient extends Shader { }
/**
* The Flat shader colors surfaces with the material color, disregarding all light sources.
*/
export class Flat extends Shader { }
/**
* A Shape contains a collection of surface. They may create a closed 3D shape, but not necessarily. For example, a cube is a closed shape, but a patch is not.
*/
export class Shape extends Transformable {
type: string;
surfaces: Surface[];
constructor(type: string, surfaces: Surface[]);
eachSurface(f: (s: Surface) => void): this;
fill(fill: string | Color): this;
stroke(stroke: string | Color): this;
}
export class Simplex3D {
perm: number[];
gradP: Grad[];
constructor(seed?: number);
noise(x: number, y: number, z: number): number;
seed(seed: number): void;
}
/**
* A Surface is a defined as a planar object in 3D space. These paths don’t necessarily need to be convex, but they should be non-degenerate. This library does not support shapes with holes.
*/
export class Surface {
points: Point[];
painter: Painter;
id: string;
cullBackfaces: boolean;
dirty: boolean | null;
fillMaterial: Material;
strokeMaterial: Material;
constructor(points: Point[], painter?: Painter);
fill(fill: string | Color): this;
stroke(stroke: string | Color): this;
}
export class SvgCirclePainter extends SvgStyler {
circle(center: Point, radius: number): this;
}
export class SvgLayerRenderContext extends RenderLayerContext {
constructor(group: SVGGElement);
circle(): SvgCirclePainter;
path(): SvgPathPainter;
rect(): SvgRectPainter;
text(): SvgTextPainter;
}
export class SvgPathPainter extends SvgStyler {
path(points: Point[]): this;
}
export class SvgRectPainter extends SvgStyler {
rect(width: number, height: number): this;
}
export class SvgRenderContext extends RenderContext {
svg: SVGSVGElement;
layers: SvgLayerRenderContext[];
constructor(svgElementOrId: string | HTMLElement);
}
export class SvgStyler {
constructor(elementFactory: (name: string) => HTMLElement);
clear(): this;
draw(style?: Partial<CSSStyleDeclaration>): this;
fill(style?: Partial<CSSStyleDeclaration>): this;
}
export class SvgTextPainter {
constructor(elementFactory: (name: string) => HTMLElement);
fillText(m: number[], text: string, style?: Partial<CSSStyleDeclaration>): void;
}
export class TextPainter extends Painter { }
/**
* Transformable base class extended by Shape and Model.
*
* The advantages of keeping transforms in Matrix form are (1) lazy computation of point position (2) ability combine hierarchical transformations easily (3) ability to reset transformations to an
* original state.
*
* Resetting transformations is especially useful when you want to animate interpolated values. Instead of computing the difference at each animation step, you can compute the global interpolated
* value for that time step and apply that value directly to a matrix (once it is reset).
*/
export class Transformable {
baked: number[];
m: Matrix;
constructor();
transform(m: Matrix): this;
bake(m?: number[]): this;
matrix(m: number[]): this;
reset(): this;
rotx(theta: number): this;
roty(theta: number): this;
rotz(theta: number): this;
scale(x?: number, y?: number, z?: number): this;
translate(x?: number, y?: number, z?: number): this;
}
/**
* A transition object to manage to animation of shapes
*/
export class Transition {
duration: number;
defaults: { duration: number };
constructor(options?: { duration?: number | undefined });
firstFrame(): void;
frame(): void;
lastFrame(): void;
update(t?: number): boolean;
}
/**
* A seen.Animator for updating seen.Transtions. We include keyframing to make sure we wait for one transition to finish before starting the next one.
*/
export class TransitionAnimator extends Animator {
dispatch: Events.Dispatcher;
timestamp: number;
frameDelay: number | null;
queue: Transition[][];
transitions: Transition[];
add(txn: Transition): void;
keyframe(): void;
update(t?: number): void;
}
/**
* Adds simple mouse wheel eventing to a DOM element. A ‘zoom’ event is emitted as the user is scrolls their mouse wheel.
*/
export class Zoom {
el: HTMLElement;
speed: number;
dispatch: Events.Dispatcher;
defaults: { smooth: boolean };
constructor(elementOrId: string | HTMLElement, options?: { smooth?: boolean | undefined });
}
export const Painters: {
path: PathPainter,
text: TextPainter
};
export function C(r?: number, g?: number, b?: number, a?: number): Color;
export function CanvasContext(elementOrId: string | HTMLElement, scene?: Scene): CanvasRenderContext;
/**
* Create a render context for the element with the specified elementId. elementId should correspond to either an SVG or Canvas element.
*/
export function Context(elementOrId: string | HTMLElement, scene?: Scene): RenderContext;
export function M(m?: number[]): Matrix;
export function P(x?: number, y?: number, z?: number, w?: number): Point;
export function SvgContext(elementOrId: string | HTMLElement, scene?: Scene): SvgRenderContext;
/**
* It is not possible exactly render text in a scene with a perspective projection because Canvas and SVG support only affine transformations. So, in order to fake it, we create an affine transform
* that approximates the linear effects of a perspective projection on an unrendered planar surface that represents the text’s shape. We can use this transform directly in the text painter to warp
* the text.
*
* This fake projection will produce unrealistic results with large strings of text that are not broken into their own shapes.
*/
export const Affine: {
INITIAL_STATE_MATRIX: number[][],
ORTHONORMAL_BASIS(): Point[],
solveForAffineTransform(points: Point[]): number[]
};
export const BvhParser: {
SyntaxError(message: string, expected: string, found: string, location: any): void,
parse(input: string): any
};
export const Colors: {
CSS_RGBA_STRING_REGEX: RegExp,
black(): Color,
gray(): Color,
hex(hex: string): Color,
hsl(h: number, s: number, l: number, a?: number): Color,
parse(str: string): Color,
randomShape(shape: Shape, sat?: number, lit?: number): void,
randomSurfaces(shape: Shape, sat?: number, lit?: number): void,
randomSurfaces2(shape: Shape, drift?: number, sat?: number, lit?: number): void,
rgb(r: number, g: number, b: number, a?: number): Color,
white(): Color
};
export namespace Events {
/**
* The Dispatcher class. These objects have methods that can be invoked like dispatch.eventName(). Listeners can be registered with dispatch.on('eventName.uniqueId', callback). Listeners can be
* removed with dispatch.on('eventName.uniqueId', null). Listeners can also be registered and removed with dispatch.eventName.on('name', callback).
*
* Note that only one listener with the name event name and id can be registered at once. If you to generate unique ids, you can use the seen.Util.uniqueId() method.
*/
class Dispatcher {
constructor();
on(type: string, listener: EventListener): Dispatcher;
}
/**
* Return a new dispatcher that creates event types using the supplied string argument list. The returned Dispatcher will have methods with the names of the event types.
*/
function dispatch(): Dispatcher;
function Event(): void;
}
export const Lights: {
ambient(opts?: LightOptions): Light,
directional(opts?: LightOptions): Light,
point(opts?: LightOptions): Light
};
/**
* A few useful Matrix objects.
*/
export const Matrices: {
flipX(): Matrix,
flipY(): Matrix,
flipZ(): Matrix,
identity(): Matrix
};
export const Models: {
default(): Model
};
/**
* A few useful Point objects. Be sure that you don’t invoke destructive methods on these objects.
*/
export const Points: {
X(): Point,
Y(): Point,
Z(): Point,
ZERO(): Point
};
/**
* These projection methods return a 3D to 2D Matrix transformation. Each projection assumes the camera is located at (0,0,0).
*/
export const Projections: {
ortho(left?: number, right?: number, bottom?: number, top?: number, near?: number, far?: number): Matrix,
perspective(left?: number, right?: number, bottom?: number, top?: number, near?: number, far?: number): Matrix,
perspectiveFov(fovyInDegrees?: number, front?: number): Matrix
};
/**
* These shading functions compute the shading for a surface. To reduce code duplication, we aggregate them in a utils object.
*/
export const ShaderUtils: {
applyAmbient(c: Color, light: Light): void,
applyDiffuse(c: Color, light: Light, lightNormal: Point, surfaceNormal: Point, material?: Material): void,
applyDiffuseAndSpecular(c: Color, light: Light, lightNormal: Point, surfaceNormal: Point, material: Material): void
};
export const Shaders: {
ambient(): Ambient,
diffuse(): DiffusePhong,
flat(): Flat,
phong(): Phong
};
/**
* Shape primitives and shape-making methods
*/
export const Shapes: {
arrow(thickness?: number, tailLength?: number, tailWidth?: number, headLength?: number, headPointiness?: number): Shape,
cube(): Shape,
custom(s: Shape): Shape,
extrude(points: Point[], offset: Point): Shape,
icosahedron(): Shape,
mapPointsToSurfaces(points: Point[], coordinateMap: number[][]): Surface[],
obj(objContents: string, cullBackfaces?: boolean): Shape,
patch(nx?: number, ny?: number): Shape,
path(points: Point[]): Shape,
pipe(point1: Point, point2: Point, radius?: number, segments?: number): Shape,
pyramid(): Shape,
rectangle(point1: Point, point2: Point): Shape,
sphere(subdivisions?: number): Shape,
tetrahedron(): Shape,
text(text: string, surfaceOptions?: Partial<Surface>): Shape,
unitcube(): Shape
};
/**
* Utility methods
*/
export const Util: {
arraysEqual<T>(a: T[], b: T[]): boolean,
defaults<T>(obj: T, opts: Partial<T>, defaults: Partial<T>): void,
element(elementOrId: string | HTMLElement): HTMLElement,
uniqueId(prefix?: string): string
};
export interface Viewport {
prescale: Matrix;
postscale: Matrix;
}
export const Viewports: {
center(width?: number, height?: number, x?: number, y?: number): Viewport,
origin(width?: number, height?: number, x?: number, y?: number): Viewport
};
/**
* A global window event dispatcher. Attaches listeners only if window is defined.
*/
export const WindowEvents: {
on(type: string, listener: EventListener): Events.Dispatcher;
}; | the_stack |
import {
encodeOutpoints,
encodeOutput,
encodeOutputsForSigning,
encodeSequenceNumbersForSigning,
} from '../../../transaction/transaction-serialization';
import { TransactionContextCommon } from '../../../transaction/transaction-types';
import { Operation } from '../../virtual-machine';
import {
AuthenticationProgramStateAlternateStack,
AuthenticationProgramStateCommon,
AuthenticationProgramStateError,
AuthenticationProgramStateExecutionStack,
AuthenticationProgramStateInternalCommon,
AuthenticationProgramStateStack,
AuthenticationProgramTransactionContextCommon,
} from '../../vm-types';
import { AuthenticationInstruction } from '../instruction-sets-types';
import { arithmeticOperations } from './arithmetic';
import { bitwiseOperations } from './bitwise';
import {
conditionallyEvaluate,
incrementOperationCount,
mapOverOperations,
} from './combinators';
import { cryptoOperations, Ripemd160, Secp256k1, Sha1, Sha256 } from './crypto';
import { applyError, AuthenticationErrorCommon } from './errors';
import {
conditionalFlowControlOperations,
reservedOperation,
unconditionalFlowControlOperations,
} from './flow-control';
import { disabledOperations, nonOperations } from './nop';
import { OpcodesCommon } from './opcodes';
import { pushNumberOperations, pushOperations } from './push';
import { spliceOperations } from './splice';
import { stackOperations } from './stack';
import { timeOperations } from './time';
export * from './arithmetic';
export * from './bitwise';
export * from './combinators';
export * from './crypto';
export * from './descriptions';
export * from './encoding';
export * from './errors';
export * from './flow-control';
export * from './nop';
export * from './opcodes';
export * from './push';
export * from './signing-serialization';
export * from './splice';
export * from './stack';
export * from './time';
export * from './types';
export enum ConsensusCommon {
/**
* A.K.A. `MAX_SCRIPT_ELEMENT_SIZE`
*/
maximumStackItemLength = 520,
maximumScriptNumberLength = 4,
/**
* A.K.A. `MAX_OPS_PER_SCRIPT`
*/
maximumOperationCount = 201,
/**
* A.K.A. `MAX_SCRIPT_SIZE`
*/
maximumBytecodeLength = 10000,
/**
* A.K.A. `MAX_STACK_SIZE`
*/
maximumStackDepth = 1000,
}
export const undefinedOperation = <
State extends AuthenticationProgramStateExecutionStack &
AuthenticationProgramStateError<Errors>,
Errors
>() => ({
undefined: conditionallyEvaluate((state: State) =>
applyError<State, Errors>(AuthenticationErrorCommon.unknownOpcode, state)
),
});
export const checkLimitsCommon = <
State extends AuthenticationProgramStateError<Errors> &
AuthenticationProgramStateStack &
AuthenticationProgramStateAlternateStack & { operationCount: number },
Errors
>(
operation: Operation<State>
): Operation<State> => (state: State) => {
const nextState = operation(state);
return nextState.stack.length + nextState.alternateStack.length >
ConsensusCommon.maximumStackDepth
? applyError<State, Errors>(
AuthenticationErrorCommon.exceededMaximumStackDepth,
nextState
)
: nextState.operationCount > ConsensusCommon.maximumOperationCount
? applyError<State, Errors>(
AuthenticationErrorCommon.exceededMaximumOperationCount,
nextState
)
: nextState;
};
export const commonOperations = <
Opcodes,
State extends AuthenticationProgramStateCommon<Opcodes, Errors>,
Errors
>({
flags,
ripemd160,
secp256k1,
sha1,
sha256,
}: {
sha1: { hash: Sha1['hash'] };
sha256: { hash: Sha256['hash'] };
ripemd160: { hash: Ripemd160['hash'] };
secp256k1: {
verifySignatureSchnorr: Secp256k1['verifySignatureSchnorr'];
verifySignatureDERLowS: Secp256k1['verifySignatureDERLowS'];
};
flags: {
disallowUpgradableNops: boolean;
requireBugValueZero: boolean;
requireMinimalEncoding: boolean;
requireNullSignatureFailures: boolean;
};
}): { readonly [opcodes: number]: Operation<State> } => {
const unconditionalOperations = {
...disabledOperations<State, Errors>(),
...pushOperations<Opcodes, State, Errors>(flags),
...mapOverOperations<State>(
unconditionalFlowControlOperations<Opcodes, State, Errors>(flags),
incrementOperationCount
),
};
const conditionalOperations = mapOverOperations<State>(
{
...pushNumberOperations<Opcodes, State>(),
[OpcodesCommon.OP_RESERVED]: reservedOperation<State, Errors>(),
},
conditionallyEvaluate
);
const incrementingOperations = mapOverOperations<State>(
{
...arithmeticOperations<Opcodes, State, Errors>(flags),
...bitwiseOperations<Opcodes, State, Errors>(),
...cryptoOperations<Opcodes, State, Errors>({
flags,
ripemd160,
secp256k1,
sha1,
sha256,
}),
...conditionalFlowControlOperations<Opcodes, State, Errors>(),
...stackOperations<State, Errors>(flags),
...spliceOperations<State, Errors>(),
...timeOperations<Opcodes, State, Errors>(flags),
...nonOperations<State>(flags),
},
conditionallyEvaluate,
incrementOperationCount
);
return mapOverOperations<State>(
{
...unconditionalOperations,
...incrementingOperations,
...conditionalOperations,
},
checkLimitsCommon
);
};
export const cloneStack = (stack: readonly Readonly<Uint8Array>[]) =>
stack.reduce<Uint8Array[]>((newStack, element) => {
// eslint-disable-next-line functional/no-expression-statement, functional/immutable-data
newStack.push(element.slice());
return newStack;
}, []);
export const createAuthenticationProgramInternalStateCommon = <
Opcodes,
Errors
>({
instructions,
stack = [],
}: {
instructions: readonly AuthenticationInstruction<Opcodes>[];
stack?: Uint8Array[];
}): AuthenticationProgramStateInternalCommon<Opcodes, Errors> => ({
alternateStack: [],
executionStack: [],
instructions,
ip: 0,
lastCodeSeparator: -1,
operationCount: 0,
signatureOperationsCount: 0,
signedMessages: [],
stack,
});
export const createTransactionContextCommon = (
program: AuthenticationProgramTransactionContextCommon
): TransactionContextCommon => ({
correspondingOutput:
program.inputIndex < program.spendingTransaction.outputs.length
? encodeOutput(program.spendingTransaction.outputs[program.inputIndex])
: undefined,
locktime: program.spendingTransaction.locktime,
outpointIndex:
program.spendingTransaction.inputs[program.inputIndex].outpointIndex,
outpointTransactionHash:
program.spendingTransaction.inputs[program.inputIndex]
.outpointTransactionHash,
outputValue: program.sourceOutput.satoshis,
sequenceNumber:
program.spendingTransaction.inputs[program.inputIndex].sequenceNumber,
transactionOutpoints: encodeOutpoints(program.spendingTransaction.inputs),
transactionOutputs: encodeOutputsForSigning(
program.spendingTransaction.outputs
),
transactionSequenceNumbers: encodeSequenceNumbersForSigning(
program.spendingTransaction.inputs
),
version: program.spendingTransaction.version,
});
export const createAuthenticationProgramStateCommon = <Opcodes, Errors>({
transactionContext,
instructions,
stack,
}: {
transactionContext: TransactionContextCommon;
instructions: readonly AuthenticationInstruction<Opcodes>[];
stack: Uint8Array[];
}): AuthenticationProgramStateCommon<Opcodes, Errors> => ({
...createAuthenticationProgramInternalStateCommon<Opcodes, Errors>({
instructions,
stack,
}),
...transactionContext,
});
/**
* Note: this implementation does not safely clone elements within array
* properties. Mutating values within arrays will mutate those values in cloned
* program states.
*/
export const cloneAuthenticationProgramStateCommon = <
Opcodes,
State extends AuthenticationProgramStateCommon<Opcodes, Errors>,
Errors
>(
state: State
) => ({
...(state.error === undefined ? {} : { error: state.error }),
alternateStack: state.alternateStack.slice(),
correspondingOutput: state.correspondingOutput,
executionStack: state.executionStack.slice(),
instructions: state.instructions.slice(),
ip: state.ip,
lastCodeSeparator: state.lastCodeSeparator,
locktime: state.locktime,
operationCount: state.operationCount,
outpointIndex: state.outpointIndex,
outpointTransactionHash: state.outpointTransactionHash.slice(),
outputValue: state.outputValue,
sequenceNumber: state.sequenceNumber,
signatureOperationsCount: state.signatureOperationsCount,
signedMessages: state.signedMessages.slice(),
stack: state.stack.slice(),
transactionOutpoints: state.transactionOutpoints,
transactionOutputs: state.transactionOutputs,
transactionSequenceNumbers: state.transactionSequenceNumbers,
version: state.version,
});
const sha256HashLength = 32;
const outputValueLength = 8;
/**
* This is a meaningless but complete `TransactionContextCommon` which uses `0`
* values for each property.
*/
export const createTransactionContextCommonEmpty = () => ({
correspondingOutput: Uint8Array.of(0),
locktime: 0,
outpointIndex: 0,
outpointTransactionHash: new Uint8Array(sha256HashLength),
outputValue: new Uint8Array(outputValueLength),
sequenceNumber: 0,
transactionOutpoints: Uint8Array.of(0),
transactionOutputs: Uint8Array.of(0),
transactionSequenceNumbers: Uint8Array.of(0),
version: 0,
});
const correspondingOutput = 1;
const transactionOutpoints = 2;
const transactionOutputs = 3;
const transactionSequenceNumbers = 4;
const outpointTransactionHashFill = 5;
/**
* This is a meaningless but complete `TransactionContextCommon` which uses a
* different value for each property. This is useful for testing and debugging.
*/
export const createTransactionContextCommonTesting = () => ({
correspondingOutput: Uint8Array.of(correspondingOutput),
locktime: 0,
outpointIndex: 0,
outpointTransactionHash: new Uint8Array(sha256HashLength).fill(
outpointTransactionHashFill
),
outputValue: new Uint8Array(outputValueLength),
sequenceNumber: 0,
transactionOutpoints: Uint8Array.of(transactionOutpoints),
transactionOutputs: Uint8Array.of(transactionOutputs),
transactionSequenceNumbers: Uint8Array.of(transactionSequenceNumbers),
version: 0,
});
/**
* Create an "empty" common authentication program state, suitable for testing a
* VM/compiler.
*/
export const createAuthenticationProgramStateCommonEmpty = <Opcodes, Errors>({
instructions,
stack = [],
}: {
instructions: readonly AuthenticationInstruction<Opcodes>[];
stack?: Uint8Array[];
}): AuthenticationProgramStateCommon<Opcodes, Errors> => ({
...createAuthenticationProgramInternalStateCommon({ instructions, stack }),
...createTransactionContextCommonEmpty(),
}); | the_stack |
import { axios } from '../axios-instance';
import {
ForwardingRule,
HealthCheck,
LoadBalancer
} from '../models/load-balancer';
export class LoadBalancerService {
constructor() {}
/**
* Create a new Load Balancer
*
* ### Example
* ```js
* import { DigitalOcean } from 'digitalocean-js';
*
* const client = new DigitalOcean('your-api-key');
*
* const lb = {
* "name": "example-lb-01",
* "region": "nyc3",
* "forwarding_rules": [
* {
* "entry_protocol": "http",
* "entry_port": 80,
* "target_protocol": "http",
* "target_port": 80,
* "certificate_id": "",
* "tls_passthrough": false
* },
* {
* "entry_protocol": "https",
* "entry_port": 444,
* "target_protocol": "https",
* "target_port": 443,
* "tls_passthrough": true
* }
* ],
* "health_check": {
* "protocol": "http",
* "port": 80,
* "path": "/",
* "check_interval_seconds": 10,
* "response_timeout_seconds": 5,
* "healthy_threshold": 5,
* "unhealthy_threshold": 3
* },
* "sticky_sessions": {
* "type": "none"
* },
* "droplet_ids": [
* 3164444,
* 3164445
* ]
* };
*
* const loadBalancer = await client.loadBalancers.createLoadBalancer(lb);
* ```
*/
public createLoadBalancer(loadBalancer: LoadBalancer): Promise<LoadBalancer> {
return new Promise((resolve, reject) => {
if (!this.loadBalancerIsValid(loadBalancer)) {
throw new Error('Required fields missing from Load Balancer Object');
}
loadBalancer.forwarding_rules.forEach(rule => {
if (!this.forwardingRuleIsValid(rule)) {
throw new Error(
'Required fields missing from Forwarding Rule Object'
);
}
});
if (loadBalancer.health_check) {
if (!this.healthCheckIsValid(loadBalancer.health_check)) {
throw new Error('Required fields missing from Health Check Object');
}
}
axios
.post(`/load_balancers`, loadBalancer)
.then(response => {
// Return actual load_balancer instead of wrapped load_balancer
resolve(response.data.load_balancer);
})
.catch(error => {
reject(error);
});
});
}
/**
* Get an existing Load Balancer
*
* ### Example
* ```js
* import { DigitalOcean } from 'digitalocean-js';
*
* const client = new DigitalOcean('your-api-key');
* const loadBalancer = await client.loadBalancers.getExistingLoadBalancer('load-balancer-id');
* ```
*/
public getExistingLoadBalancer(id: string): Promise<LoadBalancer> {
return new Promise((resolve, reject) => {
axios
.get(`/load_balancers/${id}`)
.then(response => {
// Return actual load_balancer instead of wrapped load_balancer
resolve(response.data.load_balancer);
})
.catch(error => {
reject(error);
});
});
}
/**
* Get all existing Load Balancers
*
* ### Example
* ```js
* import { DigitalOcean } from 'digitalocean-js';
*
* const client = new DigitalOcean('your-api-key');
* const loadBalancers = await client.loadBalancers.getAllLoadBalancers();
* ```
*/
public getAllLoadBalancers(): Promise<LoadBalancer[]> {
return new Promise((resolve, reject) => {
axios
.get(`/load_balancers`)
.then(response => {
// Return actual load_balancers instead of wrapped load_balancers
resolve(response.data.load_balancers);
})
.catch(error => {
reject(error);
});
});
}
/**
* Update an existing Load Balancer
*
* ### Example
* ```js
* import { DigitalOcean } from 'digitalocean-js';
*
* const client = new DigitalOcean('your-api-key');
*
* const lb = {
* "name": "example-lb-01",
* "region": "nyc3",
* "algorithm": "least_connections",
* "forwarding_rules": [
* {
* "entry_protocol": "http",
* "entry_port": 80,
* "target_protocol": "http",
* "target_port": 80
* },
* {
* "entry_protocol": "https",
* "entry_port": 444,
* "target_protocol": "https",
* "target_port": 443,
* "tls_passthrough": true
* }
* ],
* "health_check": {
* "protocol": "http",
* "port": 80,
* "path": "/",
* "check_interval_seconds": 10,
* "response_timeout_seconds": 5,
* "healthy_threshold": 5,
* "unhealthy_threshold": 3
* },
* "sticky_sessions": {
* "type": "cookies",
* "cookie_name": "DO_LB",
* "cookie_ttl_seconds": 300
* },
* "droplet_ids": [
* 3164444,
* 3164445
* ]
* };
*
* const loadBalancer = await client.loadBalancers.updateLoadBalancer(lb);
* ```
*/
public updateLoadBalancer(loadBalancer: LoadBalancer): Promise<LoadBalancer> {
return new Promise((resolve, reject) => {
if (!this.loadBalancerIsValid(loadBalancer)) {
throw new Error('Required fields missing from Load Balancer Object');
}
loadBalancer.forwarding_rules.forEach(rule => {
if (!this.forwardingRuleIsValid(rule)) {
throw new Error(
'Required fields missing from Forwarding Rule Object'
);
}
});
if (loadBalancer.health_check) {
if (!this.healthCheckIsValid(loadBalancer.health_check)) {
throw new Error('Required fields missing from Health Check Object');
}
}
axios
.put(`/load_balancers/${loadBalancer.id}`, loadBalancer)
.then(response => {
// Return actual load_balancer instead of wrapped load_balancer
resolve(response.data.load_balancer);
})
.catch(error => {
reject(error);
});
});
}
/**
* Delete an existing Load Balancer
*
* ### Example
* ```js
* import { DigitalOcean } from 'digitalocean-js';
*
* const client = new DigitalOcean('your-api-key');
* await client.loadBalancers.deleteLoadBalancer('load-balancer-id');
* ```
*/
public deleteLoadBalancer(id: string): Promise<void> {
return new Promise((resolve, reject) => {
axios
.delete(`/load_balancers/${id}`)
.then(() => {
resolve();
})
.catch(error => {
reject(error);
});
});
}
/**
* Add droplets to a Load Balancer
*
* ### Example
* ```js
* import { DigitalOcean } from 'digitalocean-js';
*
* const client = new DigitalOcean('your-api-key');
* const dropletIds = [
* 'droplet-id-1',
* 'droplet-id-2',
* 'droplet-id-3',
* ];
* await client.loadBalancers.addDropletsToLoadBalancer(dropletIds);
* ```
*/
public addDropletsToLoadBalancer(
id: string,
dropletIds: number[]
): Promise<void> {
return new Promise((resolve, reject) => {
axios
.post(`/load_balancers/${id}`, {
droplet_ids: dropletIds
})
.then(() => {
resolve();
})
.catch(error => {
reject(error);
});
});
}
/**
* Remove droplets from a Load Balancer
*
* ### Example
* ```js
* import { DigitalOcean } from 'digitalocean-js';
*
* const client = new DigitalOcean('your-api-key');
* const dropletIds = [
* 'droplet-id-1',
* 'droplet-id-2',
* 'droplet-id-3',
* ];
* await client.loadBalancers.removeDropletsFromLoadBalancer('load-balancer-id', dropletIds);
* ```
*/
public removeDropletsFromLoadBalancer(
id: string,
dropletIds: number[]
): Promise<void> {
return new Promise((resolve, reject) => {
axios
.delete(`/load_balancers/${id}`, {
data: { droplet_ids: dropletIds }
})
.then(() => {
resolve();
})
.catch(error => {
reject(error);
});
});
}
/**
* Add forwarding rules to an existing Load Balancer
*
* ### Example
* ```js
* import { DigitalOcean } from 'digitalocean-js';
*
* const client = new DigitalOcean('your-api-key');
* const rules = [
* {
* "entry_protocol": "tcp",
* "entry_port": 3306,
* "target_protocol": "tcp",
* "target_port": 3306
* }
* ];
* await client.loadBalancers
* .addForwardingRulesToLoadBalancer('load-balancer-id', rules);
* ```
*/
public addForwardingRulesToLoadBalancer(
id: string,
rules: ForwardingRule[]
): Promise<void> {
return new Promise((resolve, reject) => {
rules.forEach(rule => {
if (!this.forwardingRuleIsValid(rule)) {
throw new Error(
'Required fields missing from Forwarding Rule Object'
);
}
});
axios
.post(`/load_balancers/${id}/forwarding_rules`, {
forwarding_rules: rules
})
.then(() => {
resolve();
})
.catch(error => {
reject(error);
});
});
}
/**
* Remove forwarding rules from an existing Load Balancer
*
* ### Example
* ```js
* import { DigitalOcean } from 'digitalocean-js';
*
* const client = new DigitalOcean('your-api-key');
* const rules = [
* {
* "entry_protocol": "tcp",
* "entry_port": 3306,
* "target_protocol": "tcp",
* "target_port": 3306
* }
* ];
* await client.loadBalancers
* .removeForwardingRulesFromLoadBalancer('load-balancer-id', rules);
* ```
*/
public removeForwardingRulesFromLoadBalancer(
id: string,
rules: ForwardingRule[]
): Promise<void> {
return new Promise((resolve, reject) => {
rules.forEach(rule => {
if (!this.forwardingRuleIsValid(rule)) {
throw new Error(
'Required fields missing from Forwarding Rule Object'
);
}
});
axios
.delete(`/load_balancers/${id}/forwarding_rules`, {
data: { forwarding_rules: rules }
})
.then(() => {
resolve();
})
.catch(error => {
reject(error);
});
});
}
////////// Validation Methods //////////
private loadBalancerIsValid(lb: LoadBalancer): boolean {
if (
!lb.name ||
!lb.region ||
!lb.forwarding_rules ||
lb.forwarding_rules.length === 0
) {
return false;
}
return true;
}
private forwardingRuleIsValid(rule: ForwardingRule): boolean {
if (
!rule.entry_protocol ||
!rule.entry_port ||
!rule.target_protocol ||
!rule.target_port
) {
return false;
}
return true;
}
private healthCheckIsValid(check: HealthCheck): boolean {
if (!check.protocol || !check.port) {
return false;
}
return true;
}
} | the_stack |
/* eslint-disable */
/**
* Polyaxon SDKs and REST API specification.
* Polyaxon SDKs and REST API specification.
*
* The version of the OpenAPI document: 1.11.3
* Contact: contact@polyaxon.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import * as runtime from '../runtime';
import {
RuntimeError,
RuntimeErrorFromJSON,
RuntimeErrorToJSON,
V1ListTeamMembersResponse,
V1ListTeamMembersResponseFromJSON,
V1ListTeamMembersResponseToJSON,
V1ListTeamsResponse,
V1ListTeamsResponseFromJSON,
V1ListTeamsResponseToJSON,
V1Team,
V1TeamFromJSON,
V1TeamToJSON,
V1TeamMember,
V1TeamMemberFromJSON,
V1TeamMemberToJSON,
} from '../models';
export interface CreateTeamRequest {
owner: string;
body: V1Team;
}
export interface CreateTeamMemberRequest {
owner: string;
team: string;
body: V1TeamMember;
}
export interface DeleteTeamRequest {
owner: string;
name: string;
}
export interface DeleteTeamMemberRequest {
owner: string;
team: string;
user: string;
}
export interface GetTeamRequest {
owner: string;
name: string;
}
export interface GetTeamMemberRequest {
owner: string;
team: string;
user: string;
}
export interface ListTeamMembersRequest {
owner: string;
name: string;
offset?: number;
limit?: number;
sort?: string;
query?: string;
bookmarks?: boolean;
pins?: string;
mode?: string;
noPage?: boolean;
}
export interface ListTeamNamesRequest {
owner: string;
offset?: number;
limit?: number;
sort?: string;
query?: string;
bookmarks?: boolean;
pins?: string;
mode?: string;
noPage?: boolean;
}
export interface ListTeamsRequest {
owner: string;
offset?: number;
limit?: number;
sort?: string;
query?: string;
bookmarks?: boolean;
pins?: string;
mode?: string;
noPage?: boolean;
}
export interface PatchTeamRequest {
owner: string;
teamName: string;
body: V1Team;
}
export interface PatchTeamMemberRequest {
owner: string;
team: string;
memberUser: string;
body: V1TeamMember;
}
export interface UpdateTeamRequest {
owner: string;
teamName: string;
body: V1Team;
}
export interface UpdateTeamMemberRequest {
owner: string;
team: string;
memberUser: string;
body: V1TeamMember;
}
/**
*
*/
export class TeamsV1Api extends runtime.BaseAPI {
/**
* Create team
*/
async createTeamRaw(requestParameters: CreateTeamRequest): Promise<runtime.ApiResponse<V1Team>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling createTeam.');
}
if (requestParameters.body === null || requestParameters.body === undefined) {
throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createTeam.');
}
const queryParameters: runtime.HTTPQuery = {};
const headerParameters: runtime.HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/json';
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))),
method: 'POST',
headers: headerParameters,
query: queryParameters,
body: V1TeamToJSON(requestParameters.body),
});
return new runtime.JSONApiResponse(response, (jsonValue) => V1TeamFromJSON(jsonValue));
}
/**
* Create team
*/
async createTeam(requestParameters: CreateTeamRequest): Promise<V1Team> {
const response = await this.createTeamRaw(requestParameters);
return await response.value();
}
/**
* Create team member
*/
async createTeamMemberRaw(requestParameters: CreateTeamMemberRequest): Promise<runtime.ApiResponse<V1TeamMember>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling createTeamMember.');
}
if (requestParameters.team === null || requestParameters.team === undefined) {
throw new runtime.RequiredError('team','Required parameter requestParameters.team was null or undefined when calling createTeamMember.');
}
if (requestParameters.body === null || requestParameters.body === undefined) {
throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createTeamMember.');
}
const queryParameters: runtime.HTTPQuery = {};
const headerParameters: runtime.HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/json';
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams/{team}/members`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"team"}}`, encodeURIComponent(String(requestParameters.team))),
method: 'POST',
headers: headerParameters,
query: queryParameters,
body: V1TeamMemberToJSON(requestParameters.body),
});
return new runtime.JSONApiResponse(response, (jsonValue) => V1TeamMemberFromJSON(jsonValue));
}
/**
* Create team member
*/
async createTeamMember(requestParameters: CreateTeamMemberRequest): Promise<V1TeamMember> {
const response = await this.createTeamMemberRaw(requestParameters);
return await response.value();
}
/**
* Delete team
*/
async deleteTeamRaw(requestParameters: DeleteTeamRequest): Promise<runtime.ApiResponse<void>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling deleteTeam.');
}
if (requestParameters.name === null || requestParameters.name === undefined) {
throw new runtime.RequiredError('name','Required parameter requestParameters.name was null or undefined when calling deleteTeam.');
}
const queryParameters: runtime.HTTPQuery = {};
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams/{name}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"name"}}`, encodeURIComponent(String(requestParameters.name))),
method: 'DELETE',
headers: headerParameters,
query: queryParameters,
});
return new runtime.VoidApiResponse(response);
}
/**
* Delete team
*/
async deleteTeam(requestParameters: DeleteTeamRequest): Promise<void> {
await this.deleteTeamRaw(requestParameters);
}
/**
* Delete team member details
*/
async deleteTeamMemberRaw(requestParameters: DeleteTeamMemberRequest): Promise<runtime.ApiResponse<void>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling deleteTeamMember.');
}
if (requestParameters.team === null || requestParameters.team === undefined) {
throw new runtime.RequiredError('team','Required parameter requestParameters.team was null or undefined when calling deleteTeamMember.');
}
if (requestParameters.user === null || requestParameters.user === undefined) {
throw new runtime.RequiredError('user','Required parameter requestParameters.user was null or undefined when calling deleteTeamMember.');
}
const queryParameters: runtime.HTTPQuery = {};
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams/{team}/members/{user}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"team"}}`, encodeURIComponent(String(requestParameters.team))).replace(`{${"user"}}`, encodeURIComponent(String(requestParameters.user))),
method: 'DELETE',
headers: headerParameters,
query: queryParameters,
});
return new runtime.VoidApiResponse(response);
}
/**
* Delete team member details
*/
async deleteTeamMember(requestParameters: DeleteTeamMemberRequest): Promise<void> {
await this.deleteTeamMemberRaw(requestParameters);
}
/**
* Get team
*/
async getTeamRaw(requestParameters: GetTeamRequest): Promise<runtime.ApiResponse<V1Team>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling getTeam.');
}
if (requestParameters.name === null || requestParameters.name === undefined) {
throw new runtime.RequiredError('name','Required parameter requestParameters.name was null or undefined when calling getTeam.');
}
const queryParameters: runtime.HTTPQuery = {};
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams/{name}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"name"}}`, encodeURIComponent(String(requestParameters.name))),
method: 'GET',
headers: headerParameters,
query: queryParameters,
});
return new runtime.JSONApiResponse(response, (jsonValue) => V1TeamFromJSON(jsonValue));
}
/**
* Get team
*/
async getTeam(requestParameters: GetTeamRequest): Promise<V1Team> {
const response = await this.getTeamRaw(requestParameters);
return await response.value();
}
/**
* Get team member details
*/
async getTeamMemberRaw(requestParameters: GetTeamMemberRequest): Promise<runtime.ApiResponse<V1TeamMember>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling getTeamMember.');
}
if (requestParameters.team === null || requestParameters.team === undefined) {
throw new runtime.RequiredError('team','Required parameter requestParameters.team was null or undefined when calling getTeamMember.');
}
if (requestParameters.user === null || requestParameters.user === undefined) {
throw new runtime.RequiredError('user','Required parameter requestParameters.user was null or undefined when calling getTeamMember.');
}
const queryParameters: runtime.HTTPQuery = {};
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams/{team}/members/{user}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"team"}}`, encodeURIComponent(String(requestParameters.team))).replace(`{${"user"}}`, encodeURIComponent(String(requestParameters.user))),
method: 'GET',
headers: headerParameters,
query: queryParameters,
});
return new runtime.JSONApiResponse(response, (jsonValue) => V1TeamMemberFromJSON(jsonValue));
}
/**
* Get team member details
*/
async getTeamMember(requestParameters: GetTeamMemberRequest): Promise<V1TeamMember> {
const response = await this.getTeamMemberRaw(requestParameters);
return await response.value();
}
/**
* Get team members
*/
async listTeamMembersRaw(requestParameters: ListTeamMembersRequest): Promise<runtime.ApiResponse<V1ListTeamMembersResponse>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling listTeamMembers.');
}
if (requestParameters.name === null || requestParameters.name === undefined) {
throw new runtime.RequiredError('name','Required parameter requestParameters.name was null or undefined when calling listTeamMembers.');
}
const queryParameters: runtime.HTTPQuery = {};
if (requestParameters.offset !== undefined) {
queryParameters['offset'] = requestParameters.offset;
}
if (requestParameters.limit !== undefined) {
queryParameters['limit'] = requestParameters.limit;
}
if (requestParameters.sort !== undefined) {
queryParameters['sort'] = requestParameters.sort;
}
if (requestParameters.query !== undefined) {
queryParameters['query'] = requestParameters.query;
}
if (requestParameters.bookmarks !== undefined) {
queryParameters['bookmarks'] = requestParameters.bookmarks;
}
if (requestParameters.pins !== undefined) {
queryParameters['pins'] = requestParameters.pins;
}
if (requestParameters.mode !== undefined) {
queryParameters['mode'] = requestParameters.mode;
}
if (requestParameters.noPage !== undefined) {
queryParameters['no_page'] = requestParameters.noPage;
}
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams/{name}/members`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"name"}}`, encodeURIComponent(String(requestParameters.name))),
method: 'GET',
headers: headerParameters,
query: queryParameters,
});
return new runtime.JSONApiResponse(response, (jsonValue) => V1ListTeamMembersResponseFromJSON(jsonValue));
}
/**
* Get team members
*/
async listTeamMembers(requestParameters: ListTeamMembersRequest): Promise<V1ListTeamMembersResponse> {
const response = await this.listTeamMembersRaw(requestParameters);
return await response.value();
}
/**
* List teams names
*/
async listTeamNamesRaw(requestParameters: ListTeamNamesRequest): Promise<runtime.ApiResponse<V1ListTeamsResponse>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling listTeamNames.');
}
const queryParameters: runtime.HTTPQuery = {};
if (requestParameters.offset !== undefined) {
queryParameters['offset'] = requestParameters.offset;
}
if (requestParameters.limit !== undefined) {
queryParameters['limit'] = requestParameters.limit;
}
if (requestParameters.sort !== undefined) {
queryParameters['sort'] = requestParameters.sort;
}
if (requestParameters.query !== undefined) {
queryParameters['query'] = requestParameters.query;
}
if (requestParameters.bookmarks !== undefined) {
queryParameters['bookmarks'] = requestParameters.bookmarks;
}
if (requestParameters.pins !== undefined) {
queryParameters['pins'] = requestParameters.pins;
}
if (requestParameters.mode !== undefined) {
queryParameters['mode'] = requestParameters.mode;
}
if (requestParameters.noPage !== undefined) {
queryParameters['no_page'] = requestParameters.noPage;
}
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams/names`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))),
method: 'GET',
headers: headerParameters,
query: queryParameters,
});
return new runtime.JSONApiResponse(response, (jsonValue) => V1ListTeamsResponseFromJSON(jsonValue));
}
/**
* List teams names
*/
async listTeamNames(requestParameters: ListTeamNamesRequest): Promise<V1ListTeamsResponse> {
const response = await this.listTeamNamesRaw(requestParameters);
return await response.value();
}
/**
* List teams
*/
async listTeamsRaw(requestParameters: ListTeamsRequest): Promise<runtime.ApiResponse<V1ListTeamsResponse>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling listTeams.');
}
const queryParameters: runtime.HTTPQuery = {};
if (requestParameters.offset !== undefined) {
queryParameters['offset'] = requestParameters.offset;
}
if (requestParameters.limit !== undefined) {
queryParameters['limit'] = requestParameters.limit;
}
if (requestParameters.sort !== undefined) {
queryParameters['sort'] = requestParameters.sort;
}
if (requestParameters.query !== undefined) {
queryParameters['query'] = requestParameters.query;
}
if (requestParameters.bookmarks !== undefined) {
queryParameters['bookmarks'] = requestParameters.bookmarks;
}
if (requestParameters.pins !== undefined) {
queryParameters['pins'] = requestParameters.pins;
}
if (requestParameters.mode !== undefined) {
queryParameters['mode'] = requestParameters.mode;
}
if (requestParameters.noPage !== undefined) {
queryParameters['no_page'] = requestParameters.noPage;
}
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))),
method: 'GET',
headers: headerParameters,
query: queryParameters,
});
return new runtime.JSONApiResponse(response, (jsonValue) => V1ListTeamsResponseFromJSON(jsonValue));
}
/**
* List teams
*/
async listTeams(requestParameters: ListTeamsRequest): Promise<V1ListTeamsResponse> {
const response = await this.listTeamsRaw(requestParameters);
return await response.value();
}
/**
* Patch team
*/
async patchTeamRaw(requestParameters: PatchTeamRequest): Promise<runtime.ApiResponse<V1Team>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling patchTeam.');
}
if (requestParameters.teamName === null || requestParameters.teamName === undefined) {
throw new runtime.RequiredError('teamName','Required parameter requestParameters.teamName was null or undefined when calling patchTeam.');
}
if (requestParameters.body === null || requestParameters.body === undefined) {
throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling patchTeam.');
}
const queryParameters: runtime.HTTPQuery = {};
const headerParameters: runtime.HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/json';
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams/{team.name}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"team.name"}}`, encodeURIComponent(String(requestParameters.teamName))),
method: 'PATCH',
headers: headerParameters,
query: queryParameters,
body: V1TeamToJSON(requestParameters.body),
});
return new runtime.JSONApiResponse(response, (jsonValue) => V1TeamFromJSON(jsonValue));
}
/**
* Patch team
*/
async patchTeam(requestParameters: PatchTeamRequest): Promise<V1Team> {
const response = await this.patchTeamRaw(requestParameters);
return await response.value();
}
/**
* Patch team member
*/
async patchTeamMemberRaw(requestParameters: PatchTeamMemberRequest): Promise<runtime.ApiResponse<V1TeamMember>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling patchTeamMember.');
}
if (requestParameters.team === null || requestParameters.team === undefined) {
throw new runtime.RequiredError('team','Required parameter requestParameters.team was null or undefined when calling patchTeamMember.');
}
if (requestParameters.memberUser === null || requestParameters.memberUser === undefined) {
throw new runtime.RequiredError('memberUser','Required parameter requestParameters.memberUser was null or undefined when calling patchTeamMember.');
}
if (requestParameters.body === null || requestParameters.body === undefined) {
throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling patchTeamMember.');
}
const queryParameters: runtime.HTTPQuery = {};
const headerParameters: runtime.HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/json';
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams/{team}/members/{member.user}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"team"}}`, encodeURIComponent(String(requestParameters.team))).replace(`{${"member.user"}}`, encodeURIComponent(String(requestParameters.memberUser))),
method: 'PATCH',
headers: headerParameters,
query: queryParameters,
body: V1TeamMemberToJSON(requestParameters.body),
});
return new runtime.JSONApiResponse(response, (jsonValue) => V1TeamMemberFromJSON(jsonValue));
}
/**
* Patch team member
*/
async patchTeamMember(requestParameters: PatchTeamMemberRequest): Promise<V1TeamMember> {
const response = await this.patchTeamMemberRaw(requestParameters);
return await response.value();
}
/**
* Update team
*/
async updateTeamRaw(requestParameters: UpdateTeamRequest): Promise<runtime.ApiResponse<V1Team>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling updateTeam.');
}
if (requestParameters.teamName === null || requestParameters.teamName === undefined) {
throw new runtime.RequiredError('teamName','Required parameter requestParameters.teamName was null or undefined when calling updateTeam.');
}
if (requestParameters.body === null || requestParameters.body === undefined) {
throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updateTeam.');
}
const queryParameters: runtime.HTTPQuery = {};
const headerParameters: runtime.HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/json';
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams/{team.name}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"team.name"}}`, encodeURIComponent(String(requestParameters.teamName))),
method: 'PUT',
headers: headerParameters,
query: queryParameters,
body: V1TeamToJSON(requestParameters.body),
});
return new runtime.JSONApiResponse(response, (jsonValue) => V1TeamFromJSON(jsonValue));
}
/**
* Update team
*/
async updateTeam(requestParameters: UpdateTeamRequest): Promise<V1Team> {
const response = await this.updateTeamRaw(requestParameters);
return await response.value();
}
/**
* Update team member
*/
async updateTeamMemberRaw(requestParameters: UpdateTeamMemberRequest): Promise<runtime.ApiResponse<V1TeamMember>> {
if (requestParameters.owner === null || requestParameters.owner === undefined) {
throw new runtime.RequiredError('owner','Required parameter requestParameters.owner was null or undefined when calling updateTeamMember.');
}
if (requestParameters.team === null || requestParameters.team === undefined) {
throw new runtime.RequiredError('team','Required parameter requestParameters.team was null or undefined when calling updateTeamMember.');
}
if (requestParameters.memberUser === null || requestParameters.memberUser === undefined) {
throw new runtime.RequiredError('memberUser','Required parameter requestParameters.memberUser was null or undefined when calling updateTeamMember.');
}
if (requestParameters.body === null || requestParameters.body === undefined) {
throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updateTeamMember.');
}
const queryParameters: runtime.HTTPQuery = {};
const headerParameters: runtime.HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/json';
if (this.configuration && this.configuration.apiKey) {
headerParameters["Authorization"] = this.configuration.apiKey("Authorization"); // ApiKey authentication
}
const response = await this.request({
path: `/api/v1/orgs/{owner}/teams/{team}/members/{member.user}`.replace(`{${"owner"}}`, encodeURIComponent(String(requestParameters.owner))).replace(`{${"team"}}`, encodeURIComponent(String(requestParameters.team))).replace(`{${"member.user"}}`, encodeURIComponent(String(requestParameters.memberUser))),
method: 'PUT',
headers: headerParameters,
query: queryParameters,
body: V1TeamMemberToJSON(requestParameters.body),
});
return new runtime.JSONApiResponse(response, (jsonValue) => V1TeamMemberFromJSON(jsonValue));
}
/**
* Update team member
*/
async updateTeamMember(requestParameters: UpdateTeamMemberRequest): Promise<V1TeamMember> {
const response = await this.updateTeamMemberRaw(requestParameters);
return await response.value();
}
} | the_stack |
import * as vscode from 'vscode';
import * as fs from 'fs';
import { RTTConsoleDecoderOpts, TerminalInputMode, TextEncoding, BinaryEncoding, HrTimer } from '../common';
import { IPtyTerminalOptions, magentaWrite, PtyTerminal, RESET } from './pty';
import { decoders as DECODER_MAP } from './swo/decoders/utils';
import { SocketRTTSource } from './swo/sources/socket';
export class RTTTerminal {
protected ptyTerm: PtyTerminal;
protected ptyOptions: IPtyTerminalOptions;
protected binaryFormatter: BinaryFormatter;
private source: SocketRTTSource;
public inUse = true;
protected logFd: number;
protected hrTimer: HrTimer = new HrTimer();
public get terminal(): vscode.Terminal {
return this.ptyTerm ? this.ptyTerm.terminal : null;
}
constructor(
protected context: vscode.ExtensionContext,
public options: RTTConsoleDecoderOpts,
src: SocketRTTSource) {
this.ptyOptions = this.createTermOptions(null);
this.createTerminal();
this.sanitizeEncodings(this.options);
this.connectToSource(src);
this.openLogFile();
}
private connectToSource(src: SocketRTTSource) {
this.hrTimer = new HrTimer();
this.binaryFormatter = new BinaryFormatter(this.ptyTerm, this.options.encoding, this.options.scale);
src.once('disconnected', () => { this.onClose(); });
src.on('error', (e) => {
const code: string = (e as any).code;
if (code === 'ECONNRESET') {
// Server closed the connection. We are done with this session
this.source = null;
} else if (code === 'ECONNREFUSED') {
// We expect 'ECONNREFUSED' if the server has not yet started.
magentaWrite(`${e.message}\nPlease report this problem.`, this.ptyTerm);
this.source = null;
} else {
magentaWrite(`${e.message}\nPlease report this problem.`, this.ptyTerm);
}
});
src.on('data', (data) => { this.onData(data); });
if (src.connError) {
this.source = src;
magentaWrite(`${src.connError.message}\nPlease report this problem.`, this.ptyTerm);
} else if (src.connected) {
this.source = src;
}
else {
src.once('connected', () => {
this.source = src;
});
}
}
private onClose() {
this.source = null;
this.inUse = false;
if (!this.options.noclear && (this.logFd >= 0)) {
try { fs.closeSync(this.logFd); } catch { }
}
this.logFd = -1;
this.ptyTerm.write(RESET + '\n');
magentaWrite(`RTT connection on TCP port ${this.options.tcpPort} ended. Waiting for next connection...`, this.ptyTerm);
}
private onData(data: Buffer) {
try {
if (this.logFd >= 0) {
fs.writeSync(this.logFd, data);
}
if (this.options.type === 'binary') {
this.binaryFormatter.writeBinary(data);
} else {
this.writeNonBinary(data);
}
}
catch (e) {
magentaWrite(`Error writing data: ${e}\n`, this.ptyTerm);
}
}
private openLogFile() {
this.logFd = -1;
if (this.options.logfile) {
try {
this.logFd = fs.openSync(this.options.logfile, 'w');
}
catch (e) {
const msg = `Could not open file ${this.options.logfile} for writing. ${e.toString()}`;
console.error(msg);
magentaWrite(msg, this.ptyTerm);
}
}
}
private writeNonBinary(buf: Buffer) {
let start = 0;
let time = '';
if (this.options.timestamp) {
time = this.hrTimer.createDateTimestamp() + ' ';
}
for (let ix = 1; ix < buf.length; ix++ ) {
if (buf[ix - 1] !== 0xff) { continue; }
const chr = buf[ix];
if (((chr >= 48) && (chr <= 57)) || ((chr >= 65) && (chr <= 90))) {
if (ix >= 1) {
this.ptyTerm.writeWithHeader(buf.slice(start, ix - 1), time);
}
this.ptyTerm.write(`<switch to vTerm#${String.fromCharCode(chr)}>\n`);
buf = buf.slice(ix + 1);
ix = 0;
start = 0;
}
}
if (buf.length > 0) {
this.ptyTerm.writeWithHeader(buf, time);
}
}
protected createTermOptions(existing: string | null): IPtyTerminalOptions {
const ret: IPtyTerminalOptions = {
name: RTTTerminal.createTermName(this.options, existing),
prompt: this.createPrompt(),
inputMode: this.options.inputmode || TerminalInputMode.COOKED
};
return ret;
}
protected createTerminal() {
this.ptyTerm = new PtyTerminal(this.createTermOptions(null));
this.ptyTerm.on('data', this.sendData.bind(this));
this.ptyTerm.on('close', this.terminalClosed.bind(this));
}
protected createPrompt(): string {
return this.options.noprompt ? '' : this.options.prompt || `RTT:${this.options.port}> `;
}
protected static createTermName(options: RTTConsoleDecoderOpts, existing: string | null): string {
const suffix = options.type === 'binary' ? `enc:${getBinaryEncoding(options.encoding)}` : options.type;
const orig = options.label || `RTT Ch:${options.port} ${suffix}`;
let ret = orig;
let count = 1;
while (vscode.window.terminals.findIndex((t) => t.name === ret) >= 0) {
if (existing === ret) {
return existing;
}
ret = `${orig}-${count}`;
count++;
}
return ret;
}
protected terminalClosed() {
this.dispose();
}
public sendData(str: string | Buffer) {
if (this.source) {
try {
if (((typeof str === 'string') || (str instanceof String)) &&
(this.options.inputmode === TerminalInputMode.COOKED)) {
str = Buffer.from(str as string, this.options.iencoding);
}
this.source.write(str);
}
catch (e) {
console.error(`RTTTerminal:sendData failed ${e}`);
}
}
}
private sanitizeEncodings(obj: RTTConsoleDecoderOpts) {
obj.encoding = getBinaryEncoding(obj.encoding);
obj.iencoding = getTextEncoding(obj.iencoding);
}
// If all goes well, this will reset the terminal options. Label for the VSCode terminal has to match
// since there no way to rename it. If successful, tt will reset the Terminal options and mark it as
// used (inUse = true) as well
public tryReuse(options: RTTConsoleDecoderOpts, src: SocketRTTSource): boolean {
if (!this.ptyTerm || !this.ptyTerm.terminal) { return false; }
this.sanitizeEncodings(this.options);
const newTermName = RTTTerminal.createTermName(options, this.ptyOptions.name);
if (newTermName === this.ptyOptions.name) {
this.inUse = true;
if (!this.options.noclear || (this.options.type !== options.type)) {
this.ptyTerm.clearTerminalBuffer();
try {
if (this.logFd >= 0) {
fs.closeSync(this.logFd);
this.logFd = -1;
}
this.openLogFile();
}
catch (e) {
magentaWrite(`Error: closing fille ${e}\n`, this.ptyTerm);
}
}
this.options = options;
this.ptyOptions = this.createTermOptions(newTermName);
this.ptyTerm.resetOptions(this.ptyOptions);
this.connectToSource(src);
return true;
}
return false;
}
public dispose() {
this.ptyTerm.dispose();
if (this.logFd >= 0) {
try { fs.closeSync(this.logFd); } catch {}
this.logFd = -1;
}
}
}
function parseEncoded(buffer: Buffer, encoding: string) {
return DECODER_MAP[encoding] ? DECODER_MAP[encoding](buffer) : DECODER_MAP.unsigned(buffer);
}
function padLeft(str: string, len: number, chr = ' '): string {
if (str.length >= len) {
return str;
}
str = chr.repeat(len - str.length) + str;
return str;
}
function getBinaryEncoding(enc: string): BinaryEncoding {
enc = enc ? enc.toLowerCase() : '';
if (!(enc in BinaryEncoding)) {
enc = BinaryEncoding.UNSIGNED;
}
return enc as BinaryEncoding;
}
function getTextEncoding(enc: string): TextEncoding {
enc = enc ? enc.toLowerCase() : '';
if (!(enc in TextEncoding)) {
return TextEncoding.UTF8;
}
return enc as TextEncoding;
}
class BinaryFormatter {
private readonly bytesNeeded = 4;
private buffer = Buffer.alloc(4);
private bytesRead = 0;
private hrTimer = new HrTimer();
constructor(
protected ptyTerm: PtyTerminal,
protected encoding: string,
protected scale: number) {
this.bytesRead = 0;
this.encoding = getBinaryEncoding(encoding);
this.scale = scale || 1;
}
public writeBinary(input: string | Buffer) {
const data: Buffer = Buffer.from(input);
const timestamp = this.hrTimer.createDateTimestamp();
for (const chr of data) {
this.buffer[this.bytesRead] = chr;
this.bytesRead = this.bytesRead + 1;
if (this.bytesRead === this.bytesNeeded) {
let chars = '';
for (const byte of this.buffer) {
if (byte <= 32 || (byte >= 127 && byte <= 159)) {
chars += '.';
} else {
chars += String.fromCharCode(byte);
}
}
const blah = this.buffer.toString();
const hexvalue = padLeft(this.buffer.toString('hex'), 8, '0');
const decodedValue = parseEncoded(this.buffer, this.encoding);
const decodedStr = padLeft(`${decodedValue}`, 12);
const scaledValue = padLeft(`${decodedValue * this.scale}`, 12);
this.ptyTerm.write(`${timestamp} ${chars} 0x${hexvalue} - ${decodedStr} - ${scaledValue}\n`);
this.bytesRead = 0;
}
}
}
} | the_stack |
import React, {
useEffect,
KeyboardEvent,
FocusEvent,
useState,
ChangeEvent,
} from 'react';
import styles from './styles.module.css';
import {
cancelOnConflictMessage,
dataAttributes,
classnames,
defaultValidationMessage,
getCanEdit,
} from './utils';
export type EdiTextType =
| 'text'
| 'textarea'
| 'email'
| 'number'
| 'date'
| 'datetime-local'
| 'time'
| 'month'
| 'url'
| 'week'
| 'tel';
export type ButtonsAlignment = 'after' | 'before';
export type InputProps =
| React.DetailedHTMLProps<
React.InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>
| React.DetailedHTMLProps<
React.TextareaHTMLAttributes<HTMLTextAreaElement>,
HTMLTextAreaElement
>;
export interface EdiTextProps {
/**
* Props to be passed to input element.
* Any kind of valid DOM attributes are welcome
*/
inputProps?: InputProps;
/**
* Props to be passed to div element that shows the text.
* You can specify your own `styles` or `className`
*/
viewProps?: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLDivElement>,
HTMLDivElement
>;
/**
* Props to be passed to edit button.
* You can set `styles`, `className or disabled state.
*/
editButtonProps?: React.DetailedHTMLProps<
React.ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement
>;
/**
* Class name for the root container of the EdiText.
*/
className?: string;
/**
* Props to be passed to div element that is container for all elements.
* You can use this if you want to style or select the whole container.
*/
containerProps?: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLDivElement>,
HTMLDivElement
>;
/**
* Value of the content [in view mode] and input [in edit mode]
*/
value: string;
/**
* A simple hint message appears at the bottom of input element.
* Any valid element is allowed.
*/
hint?: React.ReactNode;
/**
* If validation fails this message will appear
*/
validationMessage?: any;
/** Pass your own validation function.
* takes one param -> `value`.
* It must return `true` or `false`
*/
validation?: (...args: string[]) => boolean;
/**
* will be called when validation fails.
* takes one param <value> which is the current value of input
*/
onValidationFail?: (...args: string[]) => any;
/**
* Input type. Possible options are:
* `text`, `number`, `email`, `textarea`, `date`,
* `datetime-local`, `time`, `month`, `url`, `week`, `tel`
* @default "text"
*/
type?: EdiTextType;
/**
* will be called when user clicked cancel button
* @param value the current value of input when cancelled.
* @param inputProps inputProps that passed to the element.
*/
onCancel?: (value: any, inputProps?: InputProps) => any;
/**
* will be called when user clicked save button.
* @param value the current value of input
* @param inputProps inputProps that passed to the element.
*/
onSave: (value: any, inputProps?: InputProps) => any;
/**
* Custom class name for SAVE button.
* */
saveButtonClassName?: string;
/**
* Custom class name for EDIT button.
* */
editButtonClassName?: string;
/**
* Custom class name for CANCEL button. */
cancelButtonClassName?: string;
/**
* Content for CANCEL button. Any valid element and node are allowed. */
cancelButtonContent?: any;
/**
* Content for SAVE button. Any valid element and node are allowed. */
saveButtonContent?: any;
/**
* Content for EDIT button. Any valid element and node are allowed. */
editButtonContent?: any;
/**
* Set it to `true` if you don't want to see default icons
* on action buttons.See Examples page for more details.
* @default "false"
*/
hideIcons?: boolean;
/**
* Decides whether buttons will be located _BEFORE_ or _AFTER_
* the input element.
* @default "after"
*/
buttonsAlign?: ButtonsAlignment;
/**
* Custom class name for the container in view mode.
*/
viewContainerClassName?: string;
/**
* Custom class name for the container in edit mode.
* Will be set to viewContainerClassName if you set it and omit this.
*/
editContainerClassName?: string;
/**
* Custom class name for the top-level main container.
* @deprecated please use `containerProps` instead of this
*/
mainContainerClassName?: string;
/**
* Set it to `true` if you want clicking on the view to activate the editor.
* @default false
*/
editOnViewClick?: boolean;
/**
* Set it to `true` if you want the view state to be edit mode
* @default false
*/
editing?: boolean;
/**
* control function that will be called when user clicks on the edit button.
* return false to prevent editing or return true to allow editing.
*/
canEdit?: boolean | (() => boolean);
/**
* Will be called when the editing mode is active.
*
* @param value the value of the input at the time when editing started.
* @param inputProps inputProps that passed to the element.
*/
onEditingStart?: (value: any, inputProps?: InputProps) => any;
/**
* Set it to `true` if you want to display action buttons **only**
* when the text hovered by the user.
* @default false
*/
showButtonsOnHover?: boolean;
/**
* Set it to `true` if you want to submit the form when `Enter`
* is pressed.
* @default false
*/
submitOnEnter?: boolean;
/**
* Set it to `true` if you want to cancel the form when `Escape`
* is pressed.
* @default false
*/
cancelOnEscape?: boolean;
/**
* Set it to `true` if you want to cancel the form when the input
* is unfocused.
* @default false
*/
cancelOnUnfocus?: boolean;
/**
* Set it to `true` if you want to save the form when the input
* is unfocused.
* @default false
*/
submitOnUnfocus?: boolean;
/**
* An helper shortcut in case you want to pass the same tabIndex to both
* `viewProps` and `inputProps`.
*
* NOTE: This will be overriden if you pass the tabIndex in `viewProps`
* or `inputProps`.
*/
tabIndex?: number;
/**
* Activates the edit mode when the view container is in focus.
*/
startEditingOnFocus?: boolean;
/**
* Activates the edit mode when the `Enter` key is pressed if the view
* container is focused.
*
* NOTE: This requires the element to be in focus.
*/
startEditingOnEnter?: boolean;
/**
* Custom render method for the content in the view mode.
* Use this prop to customize the displayed value in view mode.
* The return value from this function will be rendered in view mode.
* You can return string or JSX. Both are allowed.
*/
renderValue?: (value: any) => any;
}
function EdiText(props: EdiTextProps) {
// state
const [editingInternal, setEditingInternal] = useState(props.editing);
const [valid, setValid] = useState<boolean>(true);
const [valueInternal, setValueInternal] = useState<string>(props.value || '');
const [savedValue, setSavedValue] = useState<string | undefined>(undefined);
const [viewFocused, setViewFocused] = useState<boolean>(false);
// refs
const saveButton = React.createRef<HTMLButtonElement>();
const editingContainer = React.createRef<HTMLDivElement>();
const editingButtons = React.createRef<any>();
useEffect(() => {
if (props.cancelOnUnfocus && props.submitOnUnfocus) {
console.warn(cancelOnConflictMessage);
}
}, [props.cancelOnUnfocus, props.submitOnUnfocus]);
useEffect(() => {
if (props.value !== undefined) {
setValueInternal(props.value);
setSavedValue(props.value);
}
if (props.editing !== undefined) {
setEditingInternal(props.editing);
}
}, [props.editing, props.value]);
function handleKeyDown(e: KeyboardEvent<any>): void {
const isEnter = [13, 'Enter'].some((c) => e.key === c || e.code === c);
const isEscape = [27, 'Escape', 'Esc'].some(
(c) => e.code === c || e.key === c
);
if (isEnter) {
props.submitOnEnter && handleSave();
e?.preventDefault();
}
if (isEscape) {
props.cancelOnEscape && handleCancel();
e.preventDefault();
}
props.inputProps?.onKeyDown && props.inputProps.onKeyDown(e);
}
function handleOnBlur(e: FocusEvent<any>): void {
const isEditingButton = editingButtons.current?.contains(e?.relatedTarget);
props.cancelOnUnfocus && !isEditingButton && handleCancel();
props.submitOnUnfocus &&
!isEditingButton &&
!props.cancelOnUnfocus &&
handleSave();
props.inputProps?.onBlur && props.inputProps.onBlur(e);
}
function handleViewFocus(e: FocusEvent<HTMLDivElement>): void {
setViewFocused(true);
props.startEditingOnFocus && setEditingInternal(true);
props.viewProps?.onFocus && props.viewProps.onFocus(e);
}
function handleKeyDownForView(e: KeyboardEvent<any>): void {
const isEnter = [13, 'Enter'].some((c) => e.key === c || e.code === c);
const startEditing = isEnter && viewFocused && props.startEditingOnEnter;
startEditing && e.preventDefault();
startEditing && setEditingInternal(true);
props.viewProps?.onKeyDown && props.viewProps.onKeyDown(e);
}
function handleInputChange(
e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
): void {
setValid(true);
setValueInternal(e.target.value);
props.inputProps?.onChange?.(e as any);
}
function handleCancel(): void {
const val = savedValue ?? props.value;
setValid(true);
setEditingInternal(false);
setValueInternal(val);
props.onCancel?.(val, props.inputProps);
}
function handleActivateEditMode(): void {
if (getCanEdit(props.canEdit)) {
setEditingInternal(true);
props.onEditingStart?.(valueInternal, props.inputProps);
}
}
function handleSave(): void {
if (typeof props.validation === 'function') {
const isValid = props.validation(valueInternal);
if (!isValid) {
setValid(false);
props.onValidationFail && props.onValidationFail(valueInternal);
return;
}
}
setEditingInternal(false);
setSavedValue(valueInternal);
props.onSave(valueInternal, props.inputProps);
}
function _renderInput() {
if (props.type === 'textarea') {
return (
<textarea
className={styles.Editext__input}
// @ts-ignore
editext={dataAttributes.input}
// this is here because,
// we still allow people to pass the tabIndex via inputProps
// also backward compatibility.
tabIndex={props.tabIndex}
{...(props.inputProps as React.DetailedHTMLProps<
React.TextareaHTMLAttributes<HTMLTextAreaElement>,
HTMLTextAreaElement
>)}
onBlur={handleOnBlur}
value={valueInternal}
onChange={handleInputChange}
autoFocus={editingInternal}
/>
);
} else {
return (
<input
className={styles.Editext__input}
// @ts-ignore
editext={dataAttributes.input}
// this is here because,
// we still allow people to pass the tabIndex via inputProps
// also backward compatibility.
tabIndex={props.tabIndex}
{...props.inputProps}
onKeyDown={handleKeyDown}
onBlur={handleOnBlur}
value={valueInternal}
type={props.type || 'text'}
onChange={handleInputChange}
autoFocus={editingInternal}
/>
);
}
}
function _renderEditingMode() {
const inputElem = _renderInput();
// calculate save button classes
const saveButtonDefaultClasses = classnames(
`${styles.Editext__button}`,
`${styles.Editext__save_button}`,
props.hideIcons && `${styles.Editext__hide_default_icons}`
);
const saveButtonClass =
props.saveButtonClassName || saveButtonDefaultClasses;
// calculate cancel button classes
const cancelButtonDefaultClasses = classnames(
`${styles.Editext__button}`,
`${styles.Editext__cancel_button}`,
props.hideIcons && `${styles.Editext__hide_default_icons}`
);
const cancelButtonClass =
props.cancelButtonClassName || cancelButtonDefaultClasses;
let editContainerClass = styles.Editext__editing_container;
if (props.editContainerClassName)
editContainerClass = props.editContainerClassName;
if (props.viewContainerClassName)
editContainerClass = props.viewContainerClassName;
const alignment = props.buttonsAlign || 'after';
const buttonsContainerClass = classnames(
styles.Editext__buttons_container,
alignment === 'before' && `${styles.Editext__buttons_before_aligned}`,
alignment === 'after' && `${styles.Editext__buttons_after_aligned}`
);
return (
<div>
<div
ref={editingContainer}
className={editContainerClass}
// @ts-ignore
editext={dataAttributes.editContainer}
>
{alignment === 'after' && inputElem}
<div className={buttonsContainerClass} ref={editingButtons}>
<button
ref={saveButton}
// @ts-ignore
editext={dataAttributes.saveButton}
type="button"
className={saveButtonClass}
onClick={handleSave}
>
{props.saveButtonContent}
</button>
<button
type="button"
// @ts-ignore
editext={dataAttributes.cancelButton}
className={cancelButtonClass}
onClick={handleCancel}
>
{props.cancelButtonContent}
</button>
</div>
{alignment === 'before' && inputElem}
</div>
{!valid && !props.onValidationFail && (
<div className={styles.Editext__validation_message}>
{props.validationMessage || defaultValidationMessage}
</div>
)}
{props.hint && (
<div
className={styles.Editext__hint}
// @ts-ignore
editext={dataAttributes.hint}
>
{props.hint}
</div>
)}
</div>
);
}
function _renderViewMode() {
// calculate edit button classes
const editButtonDefaultClasses = classnames(
`${styles.Editext__button}`,
`${styles.Editext__edit_button}`,
props.hideIcons && `${styles.Editext__hide_default_icons}`
);
const editButtonClass =
props.editButtonClassName || editButtonDefaultClasses;
const viewContainerClass = classnames(
props.viewContainerClassName || styles.Editext__view_container,
props.showButtonsOnHover &&
`${styles.Editext__buttons_showButtonsOnHover}`
);
const alignment = props.buttonsAlign || 'after';
const buttonsContainerClass = classnames(
styles.Editext__buttons_container,
alignment === 'before' && `${styles.Editext__buttons_before_aligned}`,
alignment === 'after' && `${styles.Editext__buttons_after_aligned}`
);
const viewClickHandler = props.editOnViewClick
? handleActivateEditMode
: undefined;
const _value =
typeof props.renderValue === 'function'
? props.renderValue(valueInternal)
: valueInternal;
return (
<div
className={viewContainerClass}
// @ts-ignore
editext={dataAttributes.viewContainer}
>
{alignment === 'after' && (
<div
// this is here because,
// we still allow people to pass the tabIndex via inputProps
// also backward compatibility.
tabIndex={props.tabIndex}
{...props.viewProps}
onKeyDown={handleKeyDownForView}
onFocus={handleViewFocus}
onClick={viewClickHandler}
// @ts-ignore
editext="view"
>
{_value}
</div>
)}
<div className={buttonsContainerClass}>
<button
type="button"
className={editButtonClass}
{...props.editButtonProps}
// @ts-ignore
editext={dataAttributes.editButton}
onClick={handleActivateEditMode}
>
{props.editButtonContent}
</button>
</div>
{alignment === 'before' && (
<div
// this is here because,
// we still allow people to pass the tabIndex via inputProps
// also backward compatibility.
tabIndex={props.tabIndex}
{...props.viewProps}
onKeyDown={handleKeyDownForView}
onFocus={handleViewFocus}
onClick={viewClickHandler}
// @ts-ignore
editext={dataAttributes.viewContainer}
>
{_value}
</div>
)}
</div>
);
}
const mode = editingInternal ? _renderEditingMode() : _renderViewMode();
const clsName = classnames(
props.containerProps?.className ||
props.mainContainerClassName ||
styles.Editext__main_container,
props.className
);
return (
<div
{...props.containerProps}
className={clsName}
// @ts-ignore
editext={dataAttributes.mainContainer}
>
{mode}
</div>
);
}
export default EdiText; | the_stack |
import {
AttributeContextParameters,
CdmAttributeContext,
cdmAttributeContextType,
CdmConstantEntityDefinition,
CdmCorpusContext,
CdmCorpusDefinition,
CdmDocumentDefinition,
CdmEntityAttributeDefinition,
CdmEntityDefinition,
CdmEntityReference,
cdmLogCode,
CdmObject,
CdmObjectBase,
cdmObjectType,
Logger,
ProjectionAttributeState,
ProjectionAttributeStateSet,
ProjectionContext,
ProjectionDirective,
ResolvedAttribute,
ResolvedAttributeSet,
SearchResult,
SearchStructure
} from '../../internal';
/**
* A utility class to handle name based functionality for projections and operations
* @internal
*/
export class ProjectionResolutionCommonUtil {
private static TAG: string = ProjectionResolutionCommonUtil.name;
/**
* Function to initialize the input projection attribute state Set for a projection
* @internal
*/
public static initializeProjectionAttributeStateSet(
projDir: ProjectionDirective,
ctx: CdmCorpusContext,
orgSrcRAS: ResolvedAttributeSet,
isSourcePolymorphic: boolean = false,
polymorphicSet: Map<string, ProjectionAttributeState[]> = null
): ProjectionAttributeStateSet {
const set: ProjectionAttributeStateSet = new ProjectionAttributeStateSet(ctx);
for (const resAttr of orgSrcRAS.set) {
let prevSet: ProjectionAttributeState[];
if (isSourcePolymorphic && polymorphicSet) {
const polyList: ProjectionAttributeState[] = polymorphicSet.get(resAttr.resolvedName);
prevSet = polyList;
}
const projAttrState: ProjectionAttributeState = new ProjectionAttributeState(ctx);
projAttrState.currentResolvedAttribute = resAttr;
projAttrState.previousStateList = prevSet;
set.add(projAttrState);
}
return set;
}
/**
* If a source is tagged as polymorphic source, get the list of original source
* @internal
*/
public static getPolymorphicSourceSet(
projDir: ProjectionDirective,
ctx: CdmCorpusContext,
source: CdmEntityReference,
rasSource: ResolvedAttributeSet
): Map<string, ProjectionAttributeState[]> {
const polySources: Map<string, ProjectionAttributeState[]> = new Map<string, ProjectionAttributeState[]>();
// TODO (sukanyas): when projection based polymorphic source is made available - the following line will have to be changed
// for now assuming non-projections based polymorphic source
const sourceDef: CdmEntityDefinition = source.fetchObjectDefinition(projDir.resOpt);
for (const attr of sourceDef.attributes) {
if (attr.objectType === cdmObjectType.entityAttributeDef) {
// the attribute context for this entity typed attribute was already created by the `FetchResolvedAttributes` that happens before this function call.
// we are only interested in linking the attributes to the entity that they came from and the attribute context nodes should not be taken into account.
// create this dummy attribute context so the resolution code works properly and discard it after.
const attrCtxParam: AttributeContextParameters = {
regarding: attr,
type: cdmAttributeContextType.passThrough,
under: new CdmAttributeContext(ctx, 'discard')
};
const raSet: ResolvedAttributeSet = (attr as CdmEntityAttributeDefinition).fetchResolvedAttributes(projDir.resOpt, attrCtxParam);
for (const resAttr of raSet.set) {
// we got a null ctx because null was passed in to fetch, but the nodes are in the parent's tree
// so steal them based on name
var resAttSrc = rasSource.get(resAttr.resolvedName);
if (resAttSrc != null) {
resAttr.attCtx = resAttSrc.attCtx;
}
const projAttrState: ProjectionAttributeState = new ProjectionAttributeState(ctx);
projAttrState.currentResolvedAttribute = resAttr;
projAttrState.previousStateList = undefined;
// the key doesn't exist, initialize with an empty list first
if (!polySources.has(resAttr.resolvedName)) {
polySources.set(resAttr.resolvedName, []);
}
polySources.get(resAttr.resolvedName).push(projAttrState);
}
}
}
return polySources;
}
/**
* Get leaf nodes of the projection state tree for polymorphic scenarios
* @internal
*/
public static getLeafList(projCtx: ProjectionContext, attrName: string): ProjectionAttributeState[] {
let result: SearchResult;
for (const top of projCtx.currentAttributeStateSet.states) {
let st: SearchStructure = new SearchStructure();
st = SearchStructure.buildStructure(top, top, attrName, st, false, 0);
if (st?.result.foundFlag === true && st.result.leaf.length > 0) {
result = st.result;
}
}
return result?.leaf;
}
/**
* Gets the names of the top-level nodes in the projection state tree (for non-polymorphic scenarios) that match a set of attribute names
* @internal
*/
public static getTopList(projCtx: ProjectionContext, attrNames: string[]): Map<string, string> {
// This dictionary contains a mapping from the top-level (most recent) name of an attribute
// to the attribute name the top-level name was derived from (the name contained in the given list)
const topLevelAttributeNames: Map<string, string> = new Map<string, string>();
// Iterate through each attribute name in the list and search for their top-level names
for (const attrName of attrNames) {
// Iterate through each projection attribute state in the current set and check if its
// current resolved attribute's name is the top-level name of the current attrName
for (const top of projCtx.currentAttributeStateSet.states) {
let st: SearchStructure = new SearchStructure();
st = SearchStructure.buildStructure(top, top, attrName, st, false, 0);
// Found the top-level name
if (st?.result.foundFlag === true) {
// Create a mapping from the top-level name of the attribute to the name it has in the given list
topLevelAttributeNames.set(top.currentResolvedAttribute.resolvedName, attrName);
}
}
}
return topLevelAttributeNames;
}
/**
* Convert a single value to a list
* @internal
*/
public static convertToList(top: ProjectionAttributeState): ProjectionAttributeState[] {
let topList: ProjectionAttributeState[];
if (top) {
topList = [];
topList.push(top);
}
return topList;
}
/**
* Create a constant entity that contains the source mapping to a foreign key.
* e.g.
* an fk created to entity "Customer" based on the "customerName", would add a parameter to the "is.linkedEntity.identifier" trait as follows:
* [
* "/Customer.cdm.json/Customer",
* "customerName"
* ]
* In the case of polymorphic source, there will be a collection of such entries.
* @internal
*/
public static createForeignKeyLinkedEntityIdentifierTraitParameter(projDir: ProjectionDirective, corpus: CdmCorpusDefinition, refFoundList: ProjectionAttributeState[]): CdmEntityReference {
let traitParamEntRef: CdmEntityReference;
const entRefAndAttrNameList: [string, string][] = [];
for (const refFound of refFoundList) {
const resAttr: ResolvedAttribute = refFound.currentResolvedAttribute;
if (!resAttr.owner) {
const atCorpusPath: string = resAttr.target instanceof CdmObjectBase ? resAttr.target.atCorpusPath: resAttr.resolvedName;
Logger.warning(corpus.ctx, this.TAG, this.createForeignKeyLinkedEntityIdentifierTraitParameter.name, atCorpusPath, cdmLogCode.WarnProjCreateForeignKeyTraits, resAttr.resolvedName);
} else if ((resAttr.target as CdmObject).objectType === cdmObjectType.typeAttributeDef || (resAttr.target as CdmObject).objectType === cdmObjectType.entityAttributeDef) {
// find the linked entity
const owner: CdmObject = resAttr.owner;
// find where the projection is defined
const projectionDoc: CdmDocumentDefinition = projDir.owner !== undefined ? projDir.owner.inDocument : undefined;
if (owner && owner.objectType === cdmObjectType.entityDef && projectionDoc) {
const entDef: CdmEntityDefinition = owner.fetchObjectDefinition(projDir.resOpt);
if (entDef) {
// should contain relative path without the namespace
const relativeEntPath: string =
entDef.ctx.corpus.storage.createRelativeCorpusPath(entDef.atCorpusPath, projectionDoc);
entRefAndAttrNameList.push([relativeEntPath, resAttr.resolvedName]);
}
}
}
}
if (entRefAndAttrNameList.length > 0) {
const constantEntity: CdmConstantEntityDefinition = corpus.MakeObject(cdmObjectType.constantEntityDef);
constantEntity.entityShape = corpus.MakeRef(cdmObjectType.entityRef, 'entitySet', true);
const constantValues: string[][] = [];
for (const entRefAndAttrName of entRefAndAttrNameList) {
const originalSourceEntityAttributeName = projDir.originalSourceAttributeName || '';
constantValues.push([entRefAndAttrName[0], entRefAndAttrName[1], `${originalSourceEntityAttributeName}_${entRefAndAttrName[0].substring(entRefAndAttrName[0].lastIndexOf('/') + 1)}`]);
}
constantEntity.constantValues = constantValues;
traitParamEntRef = corpus.MakeRef(cdmObjectType.entityRef, constantEntity, false);
}
return traitParamEntRef;
}
} | the_stack |
import Ambrosia = require("ambrosia-node");
import Utils = Ambrosia.Utils;
import Meta = Ambrosia.Meta;
import IC = Ambrosia.IC;
import Configuration = Ambrosia.Configuration;
import StringEncoding = Ambrosia.StringEncoding;
import Process = require("process");
import * as PTI from "./PTI";
import * as Framework from "./PublisherFramework.g"; // This is a generated file
import * as PublishedAPI from "./ConsumerInterface.g"; // This is a generated file
main();
// codeGen();
// A "bootstrap" program that code-gen's the publisher/consumer TypeScript files.
async function codeGen()
{
try
{
await Ambrosia.initializeAsync(Ambrosia.LBInitMode.CodeGen);
const sourceFile: string = "./src/PTI.ts";
const fileKind: Meta.GeneratedFileKind = Meta.GeneratedFileKind.All;
const mergeType: Meta.FileMergeType = Meta.FileMergeType.None;
Meta.emitTypeScriptFileFromSource(sourceFile, { apiName: "PTI", fileKind: fileKind, mergeType: mergeType, outputPath: "./src" });
}
catch (error: unknown)
{
Utils.tryLog(Utils.makeError(error));
}
}
let _config: Configuration.AmbrosiaConfig | null = null;
// Note: For optimal performance, run this outside the debugger in a PowerShell (not CMD) window.
// TODO: Performance is worse if main() is not async: but why? It almost seems like additional thread(s) get spun up by node.exe, which then allows CPU usage to exceed 50%.
async function main()
{
const ONE_KB: number = 1024;
const ONE_MB: number = ONE_KB * ONE_KB;
const CLIENT_ROLE_NAME = PTI.InstanceRoles[PTI.InstanceRoles.Client];
const SERVER_ROLE_NAME = PTI.InstanceRoles[PTI.InstanceRoles.Server];
const COMBINED_ROLE_NAME = PTI.InstanceRoles[PTI.InstanceRoles.Combined];
const CLIENT_PARAMS: string[] = ["-sin", "--serverInstanceName", "-bpr", "--bytesPerRound", "-bsc", "--batchSizeCutoff", "-mms", "--maxMessageSize", "-n", "--numOfRounds", "-nds", "--noDescendingSize", "-fms", "--fixedMessageSize", "-eeb", "--expectedEchoedBytes", "-ipm", "--includePostMethod"];
const SERVER_PARAMS: string[] = ["-nhc", "--noHealthCheck", "-bd", "--bidirectional", "-efb", "--expectedFinalBytes"];
let instanceRole: string;
let serverInstanceName: string;
let bytesPerRound: number = 1024 * ONE_MB; // 1 GB
let batchSizeCutoff: number = 10 * ONE_MB; // 10 MB
let maxMessageSize: number = 64 * ONE_KB; // 64 KB
let numberOfRounds: number = 1;
let useDescendingSize: boolean;
let useFixedMessageSize: boolean;
let checkpointPadding: number = 0; // In bytes
let noHealthCheck: boolean;
let expectedFinalBytes: number = 0;
let expectedEchoedBytes: number = 0;
// Note: 'autoContinue' defaults to false in C# PTI. However, if we did the same we'd want to set --autoContinue in runClient.ps1/runServer.ps1 so that the user
// wouldn't have to explicitly add it as a parameter each time. But if we did that then the user would have no way to way to turn off --autoContinue.
// So instead we default it to true, and consume it as "=true|false" parameter. An alternative would be to rename it to --waitAtStart and default it to false.
let autoContinue: boolean = true;
let bidirectional: boolean = false;
let verifyPayload: boolean = false;
let includePostMethod: boolean = false;
/** [Local function] Returns the first command-line arg (if any) found in the supplied 'paramList', otherwise returns null. */
function getCommandLineArgIn(paramList: string[]): string | null
{
const args: string[] = Process.argv;
for (let i = 2; i < args.length; i++)
{
const paramName: string = args[i].split("=")[0];
if (paramList.indexOf(paramName) !== -1)
{
return (paramName);
}
}
return (null);
}
try
{
// Parse command-line parameters
try
{
if (Utils.hasCommandLineArg("-h|help"))
{
throw new Error("ShowHelp");
}
instanceRole = Utils.getCommandLineArg("-ir|instanceRole", COMBINED_ROLE_NAME); // JS-only
serverInstanceName = Utils.getCommandLineArg("-sin|serverInstanceName", ""); // JS-only
bytesPerRound = parseInt(Utils.getCommandLineArg("-bpr|bytesPerRound", bytesPerRound.toString())); // JS-only
batchSizeCutoff = parseInt(Utils.getCommandLineArg("-bsc|batchSizeCutoff", batchSizeCutoff.toString())); // JS-only
maxMessageSize = parseInt(Utils.getCommandLineArg("-mms|maxMessageSize", maxMessageSize.toString()));
numberOfRounds = parseInt(Utils.getCommandLineArg("-n|numOfRounds", numberOfRounds.toString()));
useFixedMessageSize = Utils.hasCommandLineArg("-fms|fixedMessageSize"); // JS-only
useDescendingSize = !Utils.hasCommandLineArg("-nds|noDescendingSize") && !useFixedMessageSize;
checkpointPadding = parseInt(Utils.getCommandLineArg("-m|memoryUsed", checkpointPadding.toString()));
noHealthCheck = Utils.hasCommandLineArg("-nhc|noHealthCheck"); // JS-only
expectedFinalBytes = parseInt(Utils.getCommandLineArg("-efb|expectedFinalBytes", expectedFinalBytes.toString())); // JS-only
autoContinue = Utils.equalIgnoringCase(Utils.getCommandLineArg("-c|autoContinue", autoContinue.toString()), "true");
bidirectional = Utils.hasCommandLineArg("-bd|bidirectional");
expectedEchoedBytes = parseInt(Utils.getCommandLineArg("-eeb|expectedEchoedBytes", expectedEchoedBytes.toString())); // JS-only
verifyPayload = Utils.hasCommandLineArg("-vp|verifyPayload"); // JS-only
includePostMethod = Utils.hasCommandLineArg("-ipm|includePostMethod"); // JS-only
const unknownArgName: string | null = Utils.getUnknownCommandLineArg();
if (unknownArgName)
{
throw new Error(`Invalid parameter: The supplied '${unknownArgName}' parameter is unknown; specify '--help' to see all possible parameters`);
}
// Validate parameters
const availableRoles: string[] = Utils.getEnumKeys("InstanceRoles", PTI.InstanceRoles);
if (availableRoles.indexOf(instanceRole) === -1)
{
throw new Error(`Invalid parameter: The supplied --instanceRole ('${instanceRole}') must be '${availableRoles.join("' or '")}'`);
}
// Check that all the supplied parameters are valid for the role
if ((instanceRole === CLIENT_ROLE_NAME) && getCommandLineArgIn(SERVER_PARAMS))
{
throw new Error(`Invalid parameter: The ${getCommandLineArgIn(SERVER_PARAMS)} parameter is only valid when --instanceRole is '${SERVER_ROLE_NAME}' (or '${COMBINED_ROLE_NAME}')`);
}
if ((instanceRole === SERVER_ROLE_NAME) && getCommandLineArgIn(CLIENT_PARAMS))
{
throw new Error(`Invalid parameter: The ${getCommandLineArgIn(CLIENT_PARAMS)} parameter is only valid when --instanceRole is '${CLIENT_ROLE_NAME}' (or '${COMBINED_ROLE_NAME}')`);
}
if ((instanceRole === CLIENT_ROLE_NAME) && !serverInstanceName)
{
throw new Error(`Missing parameter: The --serverInstanceName is required when --instanceRole is '${CLIENT_ROLE_NAME}'`);
}
const bytesPerRoundPower2: number = Math.log2(bytesPerRound);
if (!Number.isInteger(bytesPerRoundPower2) || (bytesPerRoundPower2 <= 6))
{
throw new Error(`Invalid parameter: The supplied --bytesPerRound (${bytesPerRound}) must be an exact power of 2 greater than 6 (128+)`);
}
const maxMessageSizePower2 = Math.log2(maxMessageSize);
if (!Number.isInteger(maxMessageSizePower2) || (maxMessageSizePower2 < 6) || (maxMessageSizePower2 > bytesPerRoundPower2))
{
throw new Error(`Invalid parameter: --maxMessageSize (${maxMessageSize}) must be set to an exact power of 2 between 6 (64) and ${bytesPerRoundPower2} (${Math.pow(2, bytesPerRoundPower2)}) [the --bytesPerRound value]`);
}
if (batchSizeCutoff > bytesPerRound)
{
throw new Error(`Invalid parameter: --batchSizeCutoff (${batchSizeCutoff}) must be less than or equal to --bytesPerRound (${bytesPerRound})`);
}
if (useDescendingSize && (numberOfRounds > 1) && ((numberOfRounds - 1) > (maxMessageSizePower2 - 6)))
{
// This is not an error condition, but the result may not be what the user expected so we emit a warning
console.log(`WARNING: The supplied --numOfRounds (${numberOfRounds}) is larger than needed to reach the 64 byte minimum message size when using "descending size"; the final ${numberOfRounds - (maxMessageSizePower2 - 6) - 1} rounds will use a message size of 64`);
}
const MAX_UINT32: number = Math.pow(2, 32) - 1; // The message ID is sent as a Uint32, so we can only send MAX_UINT32 messages in total (in all rounds)
const maxMessagesPerRound: number = (bytesPerRound / 64); // For simplicity, we assume the "worst" case (ie. all messages being 64 bytes)
const maxRounds: number = Math.floor(MAX_UINT32 / maxMessagesPerRound);
if ((numberOfRounds < 1) || (numberOfRounds > maxRounds))
{
// For example, if bytesPerRound is 1GB then maxRounds will be 255
throw new Error(`Invalid parameter: The supplied --numOfRounds (${numberOfRounds}) must be between 1 and ${maxRounds}`);
}
if (expectedFinalBytes > 0)
{
if ((instanceRole === COMBINED_ROLE_NAME) && (expectedFinalBytes != numberOfRounds * bytesPerRound))
{
throw new Error(`Invalid parameter: The supplied --expectedFinalBytes (${expectedFinalBytes}) should either be 0 or ${numberOfRounds * bytesPerRound}`);
}
// Validate that expectedFinalBytes is a multiple of some number that's a power of 2
// (eg. 256MB [Client #1] + 128MB [Client #2] = 384MB, which is a multiple of a 128MB so it's valid).
const expectedFinalBytesPower2: number = Math.log2(expectedFinalBytes);
if (!Number.isInteger(expectedFinalBytesPower2))
{
let isMultipleOfPowerOf2: boolean = false;
for (let powerOf2 = Math.floor(expectedFinalBytesPower2) - 1; powerOf2 > 0; powerOf2--)
{
if (expectedFinalBytes % Math.pow(2, powerOf2) === 0)
{
isMultipleOfPowerOf2 = true;
break;
}
}
if (!isMultipleOfPowerOf2)
{
throw new Error(`Invalid parameter: The supplied --expectedFinalBytes (${expectedFinalBytes}) must be a multiple of a number that is an exact power of 2`);
}
}
}
else
{
// If possible, set a default for expectedFinalBytes. Note that for the explicit 'Server' role there can be
// multiple clients, each with its own bytesPerRound and numberOfRounds, so we can't compute a default value.
if (instanceRole === COMBINED_ROLE_NAME)
{
expectedFinalBytes = numberOfRounds * bytesPerRound; // This will always be multiple of some number that's a power of 2
}
}
if ((instanceRole === CLIENT_ROLE_NAME) && (expectedEchoedBytes > 0) && (expectedEchoedBytes !== (numberOfRounds * bytesPerRound)))
{
throw new Error(`Invalid parameter: The supplied --expectedEchoedBytes (${expectedEchoedBytes}) should either be 0 or ${numberOfRounds * bytesPerRound}`);
}
if ((instanceRole === COMBINED_ROLE_NAME) && bidirectional)
{
if (expectedEchoedBytes === 0)
{
expectedEchoedBytes = expectedFinalBytes;
}
else
{
if (expectedEchoedBytes !== expectedFinalBytes)
{
throw new Error(`Invalid parameter: The supplied --expectedEchoedBytes (${expectedEchoedBytes}) must be the same as --expectedFinalBytes (${expectedFinalBytes}) when --bidirectional is specified in the '${COMBINED_ROLE_NAME}' role`);
}
}
}
const nodeMaxOldGenerationSize: number = Utils.getNodeLongTermHeapSizeInBytes(); // _appState will end up in the long-term ("old") GC heap
const maxCheckpointPadding: number = Math.floor((nodeMaxOldGenerationSize * 0.8) / ONE_MB) * ONE_MB; // Largest whole MB <= 80% of nodeMaxOldGenerationSize
if ((checkpointPadding < 0) || (checkpointPadding > maxCheckpointPadding))
{
throw new Error(`Invalid parameter: The supplied memoryUsed (${checkpointPadding}) must be between 0 and ${maxCheckpointPadding} (${maxCheckpointPadding / ONE_MB} MB); set the node.js V8 parameter '--max-old-space-size' to raise the upper limit (see https://nodejs.org/api/cli.html)`);
}
}
catch (e: unknown)
{
const error: Error = Utils.makeError(e);
console.log("");
if (error.message === "ShowHelp")
{
console.log(" PTI Parameters:");
console.log(" ===============");
console.log(" -h|--help : [Common] Displays this help message");
console.log(" -ir|--instanceRole= : [Common] The role of this instance in the test ('Server', 'Client', or 'Combined'); defaults to 'Combined'");
console.log(" -m|--memoryUsed= : [Common] Optional \"padding\" (in bytes) used to simulate large checkpoints by being included in app state; defaults to 0");
console.log(" -c|--autoContinue= : [Common] Whether to continue automatically at startup (if true), or wait for the 'Enter' key (if false); defaults to true");
console.log(" -vp|--verifyPayload : [Common] Enables verifying the message payload bytes (for 'doWork' on the server, and 'doWorkEcho' on the client); enabling this will decrease performance");
console.log(" -sin|--serverInstanceName= : [Client] The name of the instance that's acting in the 'Server' role for the test; only required when --role is 'Client'");
console.log(" -bpr|--bytesPerRound= : [Client] The total number of message payload bytes that will be sent in a single round; defaults to 1 GB");
console.log(" -bsc|--batchSizeCutoff= : [Client] Once the total number of message payload bytes queued reaches (or exceeds) this limit, then the batch will be sent; defaults to 10 MB");
console.log(" -mms|--maxMessageSize= : [Client] The maximum size (in bytes) of the message payload; must be a power of 2 (eg. 65536), and be at least 64; defaults to 64KB");
console.log(" -n|--numOfRounds= : [Client] The number of rounds (of size bytesPerRound) to work through; each round will use a [potentially] different message size; defaults to 1");
console.log(" -nds|--noDescendingSize : [Client] Disables descending (halving) the message size after each round; instead, a random size [power of 2] between 64 and --maxMessageSize will be used");
console.log(" -fms|--fixedMessageSize : [Client] All messages (in all rounds) will be of size --maxMessageSize; --noDescendingSize (if also supplied) will be ignored");
console.log(" -eeb|--expectedEchoedBytes= : [Client] The total number of \"echoed\" bytes expected to be received from the server when --bidirectional is specified; the client will report a \"success\" message when this number of bytes have been received");
console.log(" -ipm|--includePostMethod : [Client] Includes a 'post' method call in the test");
console.log(" -nhc|--noHealthCheck : [Server] Disables the periodic server health check (requested via an Impulse message)");
console.log(" -bd|--bidirectional : [Server] Enables echoing the 'doWork' method call back to the client(s)");
console.log(" -efb|--expectedFinalBytes= : [Server] The total number of bytes expected to be received from all clients; the server will report a \"success\" message when this number of bytes have been received");
}
else
{
console.log(error.message);
}
console.log("");
return;
}
// Run the app
await Ambrosia.initializeAsync();
const outputLoggingLevel: Utils.LoggingLevel = Configuration.loadedConfig().lbOptions.outputLoggingLevel;
if (outputLoggingLevel !== Utils.LoggingLevel.Minimal)
{
PTI.log(`Warning: Set the 'outputLoggingLevel' in ${Configuration.loadedConfigFileName()} to 'Minimal' (not '${Utils.LoggingLevel[outputLoggingLevel]}') for optimal performance`);
}
// Check if the effective batch size exceeds 50% of the "maxMessageQueueSizeInMB" config setting.
// Note: We use 50% (not 100%) because we only know the message payload size (maxMessageSize), not the actual on-the-wire message size, but at 50% we are guaranteed to be able to queue 1 batch.
const effectiveBatchSize: number = (maxMessageSize >= batchSizeCutoff) ? maxMessageSize : (Math.ceil(batchSizeCutoff / maxMessageSize) * maxMessageSize);
const maxMessageQueueSizeInBytes: number = Configuration.loadedConfig().lbOptions.maxMessageQueueSizeInMB * ONE_MB;
const maxEffectiveBatchSize: number = maxMessageQueueSizeInBytes / 2;
if (effectiveBatchSize > maxEffectiveBatchSize)
{
let maxBatchSizeCutoff: number = 0;
if (batchSizeCutoff > maxMessageSize)
{
if (maxEffectiveBatchSize % maxMessageSize === 0)
{
maxBatchSizeCutoff = maxEffectiveBatchSize;
}
else
{
maxBatchSizeCutoff = Math.floor(maxEffectiveBatchSize / maxMessageSize) * maxMessageSize;
}
}
console.log(`\nInvalid parameter: The effective batch size (${effectiveBatchSize}) cannot be larger than ${maxEffectiveBatchSize}; ` +
`reduce ${(maxMessageSize > batchSizeCutoff) ? `--maxMessageSize (to ${maxEffectiveBatchSize}` : `--batchSizeCutoff (to ${maxBatchSizeCutoff}`} or less) to resolve this\n`);
return;
}
// For the 'Server' or 'Combined' role, set serverInstanceName to the local instance name (for the 'Client' role, we've already checked that a --serverInstanceName was supplied)
if (!serverInstanceName)
{
serverInstanceName = IC.instanceName();
}
// Prevent a client instance from targeting itself as the server
if ((instanceRole === CLIENT_ROLE_NAME) && Utils.equalIgnoringCase(serverInstanceName, IC.instanceName()))
{
console.log(`\nInvalid parameter: When --instanceRole is '${CLIENT_ROLE_NAME}' the --serverInstanceName cannot reference the local instance ('${IC.instanceName()}'); instead, set --instanceRole to '${COMBINED_ROLE_NAME}'\n`);
return;
}
// The client sends its name in the message payload, which can be as small as 64 bytes, so the client name is limited to 59 bytes (+1 byte for name length, +4 bytes for call number = 64 bytes)
if (((instanceRole === CLIENT_ROLE_NAME) || (instanceRole === COMBINED_ROLE_NAME)) && (StringEncoding.toUTF8Bytes(IC.instanceName()).length > 59))
{
console.log(`\nThe client instance name ('${IC.instanceName()}') is too long; the maximum allowed length is 59 bytes`);
return;
}
PTI.log(`Local instance is running in the '${instanceRole}' PTI role`);
if (!autoContinue)
{
// For debugging we don't want to auto-continue, but for test automation we do
PTI.log(`Pausing execution of '${IC.instanceName()}'. Press 'Enter' to continue...`);
await Utils.consoleReadKeyAsync([Utils.ENTER_KEY]);
}
_config = new Configuration.AmbrosiaConfig(Framework.messageDispatcher, Framework.checkpointProducer, Framework.checkpointConsumer, PublishedAPI.postResultDispatcher);
PTI.State._appState = IC.start(_config, PTI.State.AppState);
// Preserve command-line parameters in app-state [so that they're available upon re-start, in which case these
// command-line parameter values will be ignored since they'll be overwritten when the checkpoint is restored]
// Note: 'autoContinue' is not included in app-state because it's used for debugging.
PTI.State._appState.instanceRole = PTI.InstanceRoles[instanceRole as keyof typeof PTI.InstanceRoles];
PTI.State._appState.serverInstanceName = serverInstanceName;
PTI.State._appState.bytesPerRound = bytesPerRound;
PTI.State._appState.batchSizeCutoff = batchSizeCutoff;
PTI.State._appState.maxMessageSize = maxMessageSize;
PTI.State._appState.numRounds = numberOfRounds;
PTI.State._appState.numRoundsLeft = numberOfRounds;
PTI.State._appState.useDescendingSize = useDescendingSize;
PTI.State._appState.useFixedMessageSize = useFixedMessageSize;
PTI.State._appState.noHealthCheck = noHealthCheck;
PTI.State._appState.bidirectional = bidirectional;
PTI.State._appState.expectedFinalBytesTotal = expectedFinalBytes;
PTI.State._appState.expectedEchoedBytesTotal = expectedEchoedBytes;
if (checkpointPadding > 0)
{
const ONE_HUNDRED_MB: number = 100 * ONE_MB;
PTI.State._appState.checkpointPadding = new Array<Uint8Array>();
let padding: Uint8Array = new Uint8Array(checkpointPadding % ONE_HUNDRED_MB);
PTI.State._appState.checkpointPadding.push(padding);
for (let i = 0; i < Math.floor(checkpointPadding / ONE_HUNDRED_MB); i++)
{
padding = new Uint8Array(ONE_HUNDRED_MB).fill(i + 1);
PTI.State._appState.checkpointPadding.push(padding);
}
}
PTI.State._appState.verifyPayload = verifyPayload;
PTI.State._appState.includePostMethod = includePostMethod;
}
catch (error: unknown)
{
Utils.tryLog(Utils.makeError(error));
}
} | the_stack |
import fs = require('fs');
import ts = require('typescript');
import path = require('path');
const tsfmt = require('../../tsfmt.json');
var util = require('gulp-util');
function log(message: any, ...rest: any[]): void {
util.log(util.colors.cyan('[monaco.d.ts]'), message, ...rest);
}
const SRC = path.join(__dirname, '../../src');
const OUT_ROOT = path.join(__dirname, '../../');
const RECIPE_PATH = path.join(__dirname, './monaco.d.ts.recipe');
const DECLARATION_PATH = path.join(__dirname, '../../src/vs/monaco.d.ts');
var CURRENT_PROCESSING_RULE = '';
function logErr(message: any, ...rest: any[]): void {
util.log(util.colors.red('[monaco.d.ts]'), 'WHILE HANDLING RULE: ', CURRENT_PROCESSING_RULE);
util.log(util.colors.red('[monaco.d.ts]'), message, ...rest);
}
function moduleIdToPath(out:string, moduleId:string): string {
if (/\.d\.ts/.test(moduleId)) {
return path.join(SRC, moduleId);
}
return path.join(OUT_ROOT, out, moduleId) + '.d.ts';
}
let SOURCE_FILE_MAP: {[moduleId:string]:ts.SourceFile;} = {};
function getSourceFile(out:string, inputFiles: { [file: string]: string; }, moduleId:string): ts.SourceFile {
if (!SOURCE_FILE_MAP[moduleId]) {
let filePath = path.normalize(moduleIdToPath(out, moduleId));
if (!inputFiles.hasOwnProperty(filePath)) {
logErr('CANNOT FIND FILE ' + filePath + '. YOU MIGHT NEED TO RESTART gulp');
return null;
}
let fileContents = inputFiles[filePath];
let sourceFile = ts.createSourceFile(filePath, fileContents, ts.ScriptTarget.ES5);
SOURCE_FILE_MAP[moduleId] = sourceFile;
}
return SOURCE_FILE_MAP[moduleId];
}
type TSTopLevelDeclaration = ts.InterfaceDeclaration | ts.EnumDeclaration | ts.ClassDeclaration | ts.TypeAliasDeclaration | ts.FunctionDeclaration | ts.ModuleDeclaration;
type TSTopLevelDeclare = TSTopLevelDeclaration | ts.VariableStatement;
function isDeclaration(a:TSTopLevelDeclare): a is TSTopLevelDeclaration {
return (
a.kind === ts.SyntaxKind.InterfaceDeclaration
|| a.kind === ts.SyntaxKind.EnumDeclaration
|| a.kind === ts.SyntaxKind.ClassDeclaration
|| a.kind === ts.SyntaxKind.TypeAliasDeclaration
|| a.kind === ts.SyntaxKind.FunctionDeclaration
|| a.kind === ts.SyntaxKind.ModuleDeclaration
);
}
function visitTopLevelDeclarations(sourceFile:ts.SourceFile, visitor:(node:TSTopLevelDeclare)=>boolean): void {
let stop = false;
let visit = (node: ts.Node): void => {
if (stop) {
return;
}
switch (node.kind) {
case ts.SyntaxKind.InterfaceDeclaration:
case ts.SyntaxKind.EnumDeclaration:
case ts.SyntaxKind.ClassDeclaration:
case ts.SyntaxKind.VariableStatement:
case ts.SyntaxKind.TypeAliasDeclaration:
case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.ModuleDeclaration:
stop = visitor(<TSTopLevelDeclare>node);
}
// if (node.kind !== ts.SyntaxKind.SourceFile) {
// if (getNodeText(sourceFile, node).indexOf('SymbolKind') >= 0) {
// console.log('FOUND TEXT IN NODE: ' + ts.SyntaxKind[node.kind]);
// console.log(getNodeText(sourceFile, node));
// }
// }
if (stop) {
return;
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
}
function getAllTopLevelDeclarations(sourceFile:ts.SourceFile): TSTopLevelDeclare[] {
let all:TSTopLevelDeclare[] = [];
visitTopLevelDeclarations(sourceFile, (node) => {
if (node.kind === ts.SyntaxKind.InterfaceDeclaration || node.kind === ts.SyntaxKind.ClassDeclaration || node.kind === ts.SyntaxKind.ModuleDeclaration) {
let interfaceDeclaration = <ts.InterfaceDeclaration>node;
let triviaStart = interfaceDeclaration.pos;
let triviaEnd = interfaceDeclaration.name.pos;
let triviaText = getNodeText(sourceFile, { pos: triviaStart, end: triviaEnd });
// // let nodeText = getNodeText(sourceFile, node);
// if (getNodeText(sourceFile, node).indexOf('SymbolKind') >= 0) {
// console.log('TRIVIA: ', triviaText);
// }
if (triviaText.indexOf('@internal') === -1) {
all.push(node);
}
} else {
let nodeText = getNodeText(sourceFile, node);
if (nodeText.indexOf('@internal') === -1) {
all.push(node);
}
}
return false /*continue*/;
});
return all;
}
function getTopLevelDeclaration(sourceFile:ts.SourceFile, typeName:string): TSTopLevelDeclare {
let result:TSTopLevelDeclare = null;
visitTopLevelDeclarations(sourceFile, (node) => {
if (isDeclaration(node)) {
if (node.name.text === typeName) {
result = node;
return true /*stop*/;
}
return false /*continue*/;
}
// node is ts.VariableStatement
if (getNodeText(sourceFile, node).indexOf(typeName) >= 0) {
result = node;
return true /*stop*/;
}
return false /*continue*/;
});
return result;
}
function getNodeText(sourceFile:ts.SourceFile, node:{pos:number; end:number;}): string {
return sourceFile.getFullText().substring(node.pos, node.end);
}
function getMassagedTopLevelDeclarationText(sourceFile:ts.SourceFile, declaration: TSTopLevelDeclare): string {
let result = getNodeText(sourceFile, declaration);
// if (result.indexOf('MonacoWorker') >= 0) {
// console.log('here!');
// // console.log(ts.SyntaxKind[declaration.kind]);
// }
if (declaration.kind === ts.SyntaxKind.InterfaceDeclaration || declaration.kind === ts.SyntaxKind.ClassDeclaration) {
let interfaceDeclaration = <ts.InterfaceDeclaration | ts.ClassDeclaration>declaration;
let members:ts.NodeArray<ts.Node> = interfaceDeclaration.members;
members.forEach((member) => {
try {
let memberText = getNodeText(sourceFile, member);
if (memberText.indexOf('@internal') >= 0 || memberText.indexOf('private') >= 0) {
// console.log('BEFORE: ', result);
result = result.replace(memberText, '');
// console.log('AFTER: ', result);
}
} catch (err) {
// life..
}
});
}
result = result.replace(/export default/g, 'export');
result = result.replace(/export declare/g, 'export');
return result;
}
function format(text:string): string {
// Parse the source text
let sourceFile = ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest, /*setParentPointers*/ true);
// Get the formatting edits on the input sources
let edits = (<any>ts).formatting.formatDocument(sourceFile, getRuleProvider(tsfmt), tsfmt);
// Apply the edits on the input code
return applyEdits(text, edits);
function getRuleProvider(options: ts.FormatCodeSettings) {
// Share this between multiple formatters using the same options.
// This represents the bulk of the space the formatter uses.
let ruleProvider = new (<any>ts).formatting.RulesProvider();
ruleProvider.ensureUpToDate(options);
return ruleProvider;
}
function applyEdits(text: string, edits: ts.TextChange[]): string {
// Apply edits in reverse on the existing text
let result = text;
for (let i = edits.length - 1; i >= 0; i--) {
let change = edits[i];
let head = result.slice(0, change.span.start);
let tail = result.slice(change.span.start + change.span.length);
result = head + change.newText + tail;
}
return result;
}
}
function createReplacer(data:string): (str:string)=>string {
data = data || '';
let rawDirectives = data.split(';');
let directives: [RegExp,string][] = [];
rawDirectives.forEach((rawDirective) => {
if (rawDirective.length === 0) {
return;
}
let pieces = rawDirective.split('=>');
let findStr = pieces[0];
let replaceStr = pieces[1];
findStr = findStr.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
findStr = '\\b' + findStr + '\\b';
directives.push([new RegExp(findStr, 'g'), replaceStr]);
});
return (str:string)=> {
for (let i = 0; i < directives.length; i++) {
str = str.replace(directives[i][0], directives[i][1]);
}
return str;
};
}
function generateDeclarationFile(out: string, inputFiles: { [file: string]: string; }, recipe:string): string {
let lines = recipe.split(/\r\n|\n|\r/);
let result = [];
lines.forEach(line => {
let m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m1) {
CURRENT_PROCESSING_RULE = line;
let moduleId = m1[1];
let sourceFile = getSourceFile(out, inputFiles, moduleId);
if (!sourceFile) {
return;
}
let replacer = createReplacer(m1[2]);
let typeNames = m1[3].split(/,/);
typeNames.forEach((typeName) => {
typeName = typeName.trim();
if (typeName.length === 0) {
return;
}
let declaration = getTopLevelDeclaration(sourceFile, typeName);
if (!declaration) {
logErr('Cannot find type ' + typeName);
return;
}
result.push(replacer(getMassagedTopLevelDeclarationText(sourceFile, declaration)));
});
return;
}
let m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m2) {
CURRENT_PROCESSING_RULE = line;
let moduleId = m2[1];
let sourceFile = getSourceFile(out, inputFiles, moduleId);
if (!sourceFile) {
return;
}
let replacer = createReplacer(m2[2]);
let typeNames = m2[3].split(/,/);
let typesToExcludeMap: {[typeName:string]:boolean;} = {};
let typesToExcludeArr: string[] = [];
typeNames.forEach((typeName) => {
typeName = typeName.trim();
if (typeName.length === 0) {
return;
}
typesToExcludeMap[typeName] = true;
typesToExcludeArr.push(typeName);
});
getAllTopLevelDeclarations(sourceFile).forEach((declaration) => {
if (isDeclaration(declaration)) {
if (typesToExcludeMap[declaration.name.text]) {
return;
}
} else {
// node is ts.VariableStatement
let nodeText = getNodeText(sourceFile, declaration);
for (let i = 0; i < typesToExcludeArr.length; i++) {
if (nodeText.indexOf(typesToExcludeArr[i]) >= 0) {
return;
}
}
}
result.push(replacer(getMassagedTopLevelDeclarationText(sourceFile, declaration)));
});
return;
}
result.push(line);
});
let resultTxt = result.join('\n');
resultTxt = resultTxt.replace(/\bURI\b/g, 'Uri');
resultTxt = resultTxt.replace(/\bEvent</g, 'IEvent<');
resultTxt = resultTxt.replace(/\bTPromise</g, 'Promise<');
resultTxt = format(resultTxt);
resultTxt = resultTxt.replace(/\r\n/g, '\n');
return resultTxt;
}
export function getFilesToWatch(out:string): string[] {
let recipe = fs.readFileSync(RECIPE_PATH).toString();
let lines = recipe.split(/\r\n|\n|\r/);
let result = [];
lines.forEach(line => {
let m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m1) {
let moduleId = m1[1];
result.push(moduleIdToPath(out, moduleId));
return;
}
let m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m2) {
let moduleId = m2[1];
result.push(moduleIdToPath(out, moduleId));
return;
}
});
return result;
}
export interface IMonacoDeclarationResult {
content: string;
filePath: string;
isTheSame: boolean;
}
export function run(out: string, inputFiles: { [file: string]: string; }): IMonacoDeclarationResult {
log('Starting monaco.d.ts generation');
SOURCE_FILE_MAP = {};
let recipe = fs.readFileSync(RECIPE_PATH).toString();
let result = generateDeclarationFile(out, inputFiles, recipe);
let currentContent = fs.readFileSync(DECLARATION_PATH).toString();
log('Finished monaco.d.ts generation');
return {
content: result,
filePath: DECLARATION_PATH,
isTheSame: currentContent === result
};
}
export function complainErrors() {
logErr('Not running monaco.d.ts generation due to compile errors');
} | the_stack |
import IbaxAPI, { IRequestTransport, TRequestMethod } from '.';
import { IContentRequest } from 'ibax/api';
class FormDataMock implements FormData {
private _values: { [key: string]: any } = {};
public append(name: string, value: string | Blob, fileName?: string) {
this.set(name, value, fileName);
}
delete(name: string) {
delete this._values[name];
}
get(name: string) {
return this._values[name];
}
getAll(name: string) {
return this._values[name];
}
has(name: string) {
return !!this._values[name];
}
set(name: string, value: string | Blob, fileName?: string) {
if (value instanceof Blob) {
this._values[name] = {
type: 'file',
value,
fileName
};
}
else {
this._values[name] = String(value);
}
}
}
(window as any).FormData = FormDataMock;
interface IMockTransportResponse {
__requestUrl: string;
method: TRequestMethod;
url: string;
body: { [key: string]: any };
query: { [key: string]: any };
headers: { [key: string]: any };
}
const apiPassthroughTransportMock: IRequestTransport = request => {
return new Promise<any>((resolve, reject) => {
setTimeout(() => {
resolve({
json: request
});
}, 0);
});
};
const paramsTransportMock: IRequestTransport = request => {
return new Promise<any>((resolve, reject) => {
setTimeout(() => {
resolve({
json: {
__requestUrl: request.url,
body: request.body
}
});
}, 0);
});
};
const mockFormData = (values: { [key: string]: any }) => {
const value = new FormData();
for (let itr in values) {
if (values.hasOwnProperty(itr)) {
value.append(itr, values[itr]);
}
}
return value;
};
const paramTestingAPIHost = 'http://test_Url.com';
const paramTestingAPIEndpoint = 'api/v2';
const paramTestingAPIMock = () => new IbaxAPI({
apiHost: paramTestingAPIHost,
apiEndpoint: paramTestingAPIEndpoint,
transport: paramsTransportMock
});
test('Url slug parsing', () => {
const TEST_URL = '://test_url.com';
const TEST_ENDPOINT = 'api/v2';
const TEST_ROUTE = 'test_route';
class MockAPI extends IbaxAPI {
public slugEndpoint = this.setEndpoint<{ slug: string }, IMockTransportResponse>('get', `${TEST_ROUTE}/{slug}`);
public complexSlugEndpoint = this.setEndpoint<{ a: string, b: string }, IMockTransportResponse>('get', `${TEST_ROUTE}/{a}/${TEST_ROUTE}/{b}/test`);
public postSlugEndpoint = this.setEndpoint<{ slug: string, some: 1, more: true, params: 'hello' }, IMockTransportResponse>('post', `${TEST_ROUTE}/{slug}`);
}
const api = new MockAPI({
apiHost: TEST_URL,
apiEndpoint: TEST_ENDPOINT,
transport: apiPassthroughTransportMock
});
return Promise.all([
api.slugEndpoint({ slug: 'test0123456789' }).then(l =>
expect(l.url).toEqual(`${TEST_URL}/${TEST_ENDPOINT}/${TEST_ROUTE}/test0123456789?slug=test0123456789`)
),
api.complexSlugEndpoint({ a: '../../test', b: '-12345-' }).then(l =>
expect(l.url).toEqual(`${TEST_URL}/${TEST_ENDPOINT}/${TEST_ROUTE}/${encodeURIComponent('../../test')}/${TEST_ROUTE}/-12345-/test?a=..%2F..%2Ftest&b=-12345-`)
),
api.postSlugEndpoint({ slug: 'test0123456789', some: 1, more: true, params: 'hello' }).then(l =>
expect(l.url).toEqual(`${TEST_URL}/${TEST_ENDPOINT}/${TEST_ROUTE}/test0123456789`)
)
]);
});
test('Request transformer', () => {
const testData = {
first: 1,
second: 2,
third: 3
};
class MockAPI extends IbaxAPI {
public transformEndpoint = this.setEndpoint<typeof testData, IMockTransportResponse>('get', 'test', {
requestTransformer: request => ({
first: request.third,
third: request.first
})
});
}
const api = new MockAPI({
apiHost: '://test_url.com',
apiEndpoint: 'api/v2',
transport: apiPassthroughTransportMock
});
return api.transformEndpoint(testData).then(l => {
expect(l.url).toEqual('://test_url.com/api/v2/test?first=3&third=1');
});
});
test('Response transformer', () => {
const testData = {
first: 1,
second: 2,
third: 3
};
class MockAPI extends IbaxAPI {
public transformEndpoint = this.setEndpoint<typeof testData, Partial<typeof testData>>('post', 'test', {
responseTransformer: response => ({
first: response.body.get('third'),
third: response.body.get('first')
})
});
}
const api = new MockAPI({
apiHost: '://test_url.com',
apiEndpoint: 'api/v2',
transport: apiPassthroughTransportMock
});
return api.transformEndpoint(testData).then(l =>
expect(l).toEqual({
first: '3',
third: '1'
})
);
});
test('Login', () => {
const testRequest = {
ecosystem: '1',
expire: 4815162342,
publicKey: '04123456789',
signature: 'test',
role: 123
};
return paramTestingAPIMock().login(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/login`,
body: mockFormData({
ecosystem: '1',
expire: 4815162342,
pubkey: '04123456789',
signature: 'test',
role_id: 123,
}),
roles: []
});
});
});
test('GetConfig', () => {
const testRequest = 'centrifugo';
return paramTestingAPIMock().getConfig({ name: 'centrifugo' }).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/config/${testRequest}`,
body: null
});
});
});
test('GetContract', () => {
const testRequest = {
name: 'TEST_CONTRACT',
};
return paramTestingAPIMock().getContract(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/contract/TEST_CONTRACT`,
body: null
});
});
});
test('GetContracts', () => {
const testRequest = {
offset: 4,
limit: 8
};
return paramTestingAPIMock().getContracts(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/contracts?limit=8&offset=4`,
body: null
});
});
});
test('GetParam', () => {
const testRequest = {
name: 'TEST_PARAM'
};
return paramTestingAPIMock().getParam(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/ecosystemparam/TEST_PARAM`,
body: null
});
});
});
test('GetParams', () => {
const testRequest = {
names: ['TEST_PARAM', 'MOCK_PARAM', ',#PARAM']
};
return paramTestingAPIMock().getParams(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/ecosystemparams?names=TEST_PARAM%2CMOCK_PARAM%2C%2C%23PARAM`,
body: null
});
});
});
test('GetPage', () => {
const testRequest = {
name: 'TEST_PAGE'
};
return paramTestingAPIMock().getPage(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/interface/page/TEST_PAGE`,
body: null
});
});
});
test('GetMenu', () => {
const testRequest = {
name: 'TEST_MENU'
};
return paramTestingAPIMock().getMenu(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/interface/menu/TEST_MENU`,
body: null
});
});
});
test('GetBlock', () => {
const testRequest = {
name: 'TEST_BLOCK'
};
return paramTestingAPIMock().getBlock(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/interface/block/TEST_BLOCK`,
body: null
});
});
});
test('GetTable', () => {
const testRequest = {
name: 'TEST_TABLE'
};
return paramTestingAPIMock().getTable(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/table/TEST_TABLE`,
body: null
});
});
});
test('GetTables', () => {
const testRequest = {
offset: 4,
limit: 8
};
return paramTestingAPIMock().getTables(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/tables?limit=8&offset=4`,
body: null
});
});
});
test('GetHistory', () => {
const testRequest = {
id: '4815162342',
table: 'TEST_TABLE'
};
return paramTestingAPIMock().getHistory(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/history/TEST_TABLE/4815162342`,
body: null
});
});
});
test('GetRow', () => {
const testRequest = {
id: '4815162342',
table: 'TEST_TABLE',
columns: ['COL_1', 'COL2', '@COL"3']
};
return paramTestingAPIMock().getRow(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/row/TEST_TABLE/4815162342?columns=COL_1%2CCOL2%2C%40COL%223`,
body: null
});
});
});
test('GetData', () => {
const testRequest = {
name: 'TEST_TABLE',
columns: ['COL_1', 'COL2', '@COL"3']
};
return paramTestingAPIMock().getData(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/list/TEST_TABLE?columns=COL_1%2CCOL2%2C%40COL%223`,
body: null
});
});
});
test('Content', () => {
const testRequest = {
type: 'page',
name: 'TEST_PAGE',
locale: 'en-US',
params: {
strParam: 'hello?',
numParam: 4815162342,
boolParam: true
}
} as IContentRequest;
return paramTestingAPIMock().content(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/content/page/TEST_PAGE`,
body: mockFormData({
lang: 'en-US',
strParam: 'hello?',
numParam: 4815162342,
boolParam: true
})
});
});
});
test('ContentTest', () => {
const testRequest = {
template: 'TEST_DATA',
locale: 'en-US',
params: {
strParam: 'hello?',
numParam: 4815162342,
boolParam: true
}
};
return paramTestingAPIMock().contentTest(testRequest).then((response: any) => {
expect(response).toEqual({
__requestUrl: `${paramTestingAPIHost}/${paramTestingAPIEndpoint}/content`,
body: mockFormData({
lang: 'en-US',
template: 'TEST_DATA',
strParam: 'hello?',
numParam: 4815162342,
boolParam: true
})
});
});
}); | the_stack |
import { LayoutController } from "./layout/controller";
import { WindowSummary, Workspace, WorkspaceOptionsWithTitle, WorkspaceOptionsWithLayoutName, ComponentFactory, LoadingStrategy, WorkspaceLayout, Bounds, Constraints } from "./types/internal";
import { LayoutEventEmitter } from "./layout/eventEmitter";
import { IFrameController } from "./iframeController";
import store from "./state/store";
import registryFactory, { UnsubscribeFunction } from "callback-registry";
import GoldenLayout from "@glue42/golden-layout";
import { LayoutsManager } from "./layouts";
import { LayoutStateResolver } from "./state/resolver";
import scReader from "./config/startupReader";
import { idAsString, getAllWindowsFromConfig, getElementBounds, getWorkspaceContextName } from "./utils";
import { WorkspacesConfigurationFactory } from "./config/factory";
import { WorkspacesEventEmitter } from "./eventEmitter";
import { Glue42Web } from "@glue42/web";
import { LockColumnArguments, LockContainerArguments, LockGroupArguments, LockRowArguments, LockWindowArguments, LockWorkspaceArguments, ResizeItemArguments, RestoreWorkspaceConfig } from "./interop/types";
import { TitleGenerator } from "./config/titleGenerator";
import startupReader from "./config/startupReader";
import componentStateMonitor from "./componentStateMonitor";
import { ConfigConverter } from "./config/converter";
import { PopupManagerComposer } from "./popups/composer";
import { PopupManager } from "./popups/external";
import { ComponentPopupManager } from "./popups/component";
import { GlueFacade } from "./interop/facade";
import { ApplicationFactory } from "./app/factory";
import { DelayedExecutor } from "./utils/delayedExecutor";
import systemSettings from "./config/system";
import { ConstraintsValidator } from "./config/constraintsValidator";
import { WorkspaceWrapper } from "./state/workspaceWrapper";
export class WorkspacesManager {
private _controller: LayoutController;
private _frameController: IFrameController;
private _frameId: string;
private _popupManager: PopupManagerComposer
private _layoutsManager: LayoutsManager;
private _stateResolver: LayoutStateResolver;
private _isLayoutInitialized = false;
private _initPromise = Promise.resolve();
private _workspacesEventEmitter = new WorkspacesEventEmitter();
private _titleGenerator = new TitleGenerator();
private _initialized: boolean;
private _glue: Glue42Web.API;
private _configFactory: WorkspacesConfigurationFactory;
private _applicationFactory: ApplicationFactory;
private _facade: GlueFacade;
private _isDisposing: boolean;
public get stateResolver(): LayoutStateResolver {
return this._stateResolver;
}
public get workspacesEventEmitter(): WorkspacesEventEmitter {
return this._workspacesEventEmitter;
}
public get initPromise(): Promise<void> {
return this._initPromise;
}
public get initialized(): boolean {
return this._initialized;
}
public get frameId(): string {
return this._frameId;
}
public init(glue: Glue42Web.API, frameId: string, facade: GlueFacade, componentFactory?: ComponentFactory): { cleanUp: () => void } {
this._glue = glue;
this._facade = facade;
const startupConfig = scReader.loadConfig();
if (this._initialized) {
componentStateMonitor.reInitialize(componentFactory);
return;
}
this._initialized = true;
this._frameId = frameId;
this._configFactory = new WorkspacesConfigurationFactory(glue);
const converter = new ConfigConverter(this._configFactory);
componentStateMonitor.init(this._frameId, componentFactory);
this._frameController = new IFrameController(glue);
const eventEmitter = new LayoutEventEmitter(registryFactory());
this._stateResolver = new LayoutStateResolver(this._frameId, eventEmitter, this._frameController, converter);
this._controller = new LayoutController(eventEmitter, this._stateResolver, startupConfig, this._configFactory);
this._applicationFactory = new ApplicationFactory(glue, this.stateResolver, this._frameController, this, new DelayedExecutor());
this._layoutsManager = new LayoutsManager(this.stateResolver, glue, this._configFactory, converter, new ConstraintsValidator());
this._popupManager = new PopupManagerComposer(new PopupManager(glue), new ComponentPopupManager(componentFactory, frameId), componentFactory);
if (!startupConfig.emptyFrame) {
this.initLayout();
}
return { cleanUp: this.cleanUp };
}
public getComponentBounds = (): Bounds => {
return this._controller.bounds;
}
public subscribeForWindowClicked = (cb: () => void): UnsubscribeFunction => {
if (!this._frameController) {
// tslint:disable-next-line: no-console
console.warn("Your subscription to window clicked wasn't successful, because the Workspaces library isn't initialized yet");
return (): void => { };
}
return this._frameController.onFrameContentClicked(cb);
}
public async saveWorkspace(name: string, id?: string, saveContext?: boolean, metadata?: object): Promise<WorkspaceLayout> {
const workspace = store.getById(id) || store.getActiveWorkspace();
const result = await this._layoutsManager.save({
name,
workspace,
title: store.getWorkspaceTitle(workspace.id),
saveContext,
metadata
});
const config = workspace.layout?.config || workspace.hibernateConfig;
(config.workspacesOptions as WorkspaceOptionsWithLayoutName).layoutName = name;
if (config.workspacesOptions.noTabHeader) {
delete config.workspacesOptions.noTabHeader;
}
return result;
}
public async openWorkspace(name: string, options?: RestoreWorkspaceConfig): Promise<string> {
const savedConfigWithData = await this._layoutsManager.getWorkspaceByName(name);
const savedConfig = savedConfigWithData.config;
savedConfig.workspacesOptions.context = savedConfigWithData.layoutData.context;
if (options?.context && savedConfig.workspacesOptions.context) {
savedConfig.workspacesOptions.context = Object.assign(savedConfigWithData.layoutData.context, options?.context);
} else if (options?.context) {
savedConfig.workspacesOptions.context = options?.context;
}
(savedConfig.workspacesOptions as WorkspaceOptionsWithTitle).title = options?.title || name;
if (savedConfig && savedConfig.workspacesOptions && !savedConfig.workspacesOptions.name) {
savedConfig.workspacesOptions.name = name;
}
if (savedConfig) {
savedConfig.workspacesOptions = savedConfig.workspacesOptions || {};
(savedConfig.workspacesOptions as WorkspaceOptionsWithLayoutName).layoutName = savedConfigWithData.layoutData.name;
}
if (savedConfig && options) {
(savedConfig.workspacesOptions as any).loadingStrategy = options.loadingStrategy;
}
if (savedConfig && options?.noTabHeader !== undefined) {
savedConfig.workspacesOptions = savedConfig.workspacesOptions || {};
savedConfig.workspacesOptions.noTabHeader = options?.noTabHeader;
}
if (!this._isLayoutInitialized) {
this._layoutsManager.setInitialWorkspaceConfig(savedConfig);
this._initPromise = this.initLayout();
await this._initPromise;
return idAsString(savedConfig.id);
} else if (name) {
savedConfig.id = options?.reuseWorkspaceId || this._configFactory.getId();
if (options?.reuseWorkspaceId) {
const workspace = store.getById(savedConfig.id);
workspace.windows.map((w) => store.getWindowContentItem(w.id))
.filter((w) => w)
.map((w) => this.closeTab(w, false));
await this.reinitializeWorkspace(savedConfig.id, savedConfig);
if (savedConfig.workspacesOptions?.context) {
await this._glue.contexts.set(getWorkspaceContextName(savedConfig.id), savedConfig.workspacesOptions.context);
}
} else {
await this.addWorkspace(idAsString(savedConfig.id), savedConfig);
}
return idAsString(savedConfig.id);
}
}
public exportAllLayouts() {
return this._layoutsManager.export();
}
public deleteLayout(name: string): void {
this._layoutsManager.delete(name);
}
public maximizeItem(itemId: string): void {
const container = store.getContainer(itemId);
if (container) {
this._controller.maximizeContainer(itemId);
return;
}
const workspaceByWindowId = store.getByWindowId(itemId);
if (workspaceByWindowId) {
this._controller.maximizeWindow(itemId);
return;
}
throw new Error(`Could not find a window or a container with id ${itemId} in frame ${this.frameId} to maximize`);
}
public restoreItem(itemId: string): void {
const container = store.getContainer(itemId);
if (container) {
this._controller.restoreContainer(itemId);
return;
}
const workspaceByWindowId = store.getByWindowId(itemId);
if (workspaceByWindowId) {
this._controller.restoreWindow(itemId);
return;
}
throw new Error(`Could not find a window or a container with id ${itemId} in frame ${this.frameId} to restore`);
}
public closeItem(itemId: string): void {
const win = store.getWindow(itemId);
const container = store.getContainer(itemId);
if (this._frameId === itemId) {
store.workspaceIds.forEach((wid) => this.closeWorkspace(store.getById(wid)));
} else if (win) {
const windowContentItem = store.getWindowContentItem(itemId);
if (!windowContentItem) {
throw new Error(`Could not find item ${itemId} to close`);
}
this.closeTab(windowContentItem);
} else if (container) {
this._controller.closeContainer(itemId);
} else {
const workspace = store.getById(itemId);
this.closeWorkspace(workspace);
}
}
public async addContainer(config: GoldenLayout.RowConfig | GoldenLayout.StackConfig | GoldenLayout.ColumnConfig, parentId: string): Promise<string> {
const configWithoutIsPinned = this.cleanIsPinned(config) as GoldenLayout.RowConfig | GoldenLayout.StackConfig | GoldenLayout.ColumnConfig;
const workspace = store.getByContainerId(parentId) || store.getById(parentId);
const workspaceContentItem = store.getWorkspaceContentItem(workspace.id);
const workspaceWrapper = new WorkspaceWrapper(this.stateResolver, workspace, workspaceContentItem, this.frameId);
if (workspaceWrapper.hasMaximizedItems) {
throw new Error(`Cannot add a new container to workspace ${workspaceWrapper.id}, because it contains maximized items`);
}
const result = await this._controller.addContainer(configWithoutIsPinned, parentId);
const itemConfig = store.getContainer(result);
if (itemConfig) {
this.applyIsPinned(config, itemConfig);
}
const windowConfigs = getAllWindowsFromConfig(config.content);
Promise.all(windowConfigs.map(async (itemConfig) => {
const component = store.getWindowContentItem(idAsString(itemConfig.id));
await this._applicationFactory.start(component, workspace.id);
}));
return result;
}
public async addWindow(itemConfig: GoldenLayout.ItemConfig, parentId: string): Promise<void> {
const parent = store.getContainer(parentId);
if ((!parent || parent.type !== "stack") && itemConfig.type === "component") {
itemConfig = this._configFactory.wrapInGroup([itemConfig]);
}
const workspace = store.getById(parentId) || store.getByContainerId(parentId);
const workspaceContentItem = store.getWorkspaceContentItem(workspace.id);
const workspaceWrapper = new WorkspaceWrapper(this.stateResolver, workspace, workspaceContentItem, this.frameId);
if (workspaceWrapper.hasMaximizedItems) {
throw new Error(`Cannot add a new window to workspace ${workspaceWrapper.id}, because it contains maximized items`);
}
await this._controller.addWindow(itemConfig, parentId);
const allWindowsInConfig = getAllWindowsFromConfig([itemConfig]);
const component = store.getWindowContentItem(idAsString(allWindowsInConfig[0].id));
this._applicationFactory.start(component, workspace.id);
}
public setItemTitle(itemId: string, title: string): void {
if (store.getById(itemId)) {
this._controller.setWorkspaceTitle(itemId, title);
} else {
this._controller.setWindowTitle(itemId, title);
}
}
public async eject(item: GoldenLayout.Component): Promise<{ windowId: string }> {
const { appName, url, windowId } = item.config.componentState;
const workspaceContext = store.getWorkspaceContext(store.getByWindowId(item.config.id).id);
const webWindow = this._glue.windows.findById(windowId);
const context = webWindow ? await webWindow.getContext() : workspaceContext;
this.closeItem(idAsString(item.config.id));
// If an appName is available it should be used instead of just opening the window with glue.windows.open
// in order to be as close as possible to a real eject
if (appName) {
const options = (windowId ? { reuseId: windowId } : undefined) as any; // making sure that the invokation is robust and can't fail easily due to corrupted state
const ejectedInstance = await this._glue.appManager.application(appName).start(context, options);
return { windowId: ejectedInstance.id };
}
const ejectedWindowUrl = this._applicationFactory.getUrlByAppName(appName) || url;
const ejectedWindow = await this._glue.windows.open(`${appName}_${windowId}`, ejectedWindowUrl, { context, windowId } as Glue42Web.Windows.Settings);
return { windowId: ejectedWindow.id };
}
public async createWorkspace(config: GoldenLayout.Config): Promise<string> {
if (!this._isLayoutInitialized) {
config.id = this._configFactory.getId();
this._layoutsManager.setInitialWorkspaceConfig(config);
this._initPromise = this.initLayout();
await this._initPromise;
return idAsString(config.id);
}
const id = config.workspacesOptions?.reuseWorkspaceId || this._configFactory.getId();
if (config.workspacesOptions?.reuseWorkspaceId) {
const workspace = store.getById(id);
if (!workspace) {
throw new Error(`Could not find workspace ${config.workspacesOptions?.reuseWorkspaceId} to reuse`);
}
workspace.windows
.map((w) => store.getWindowContentItem(w.id))
.filter((w) => w)
.map((w) => this.closeTab(w, false));
await this.reinitializeWorkspace(id, config);
await this._glue.contexts.set(getWorkspaceContextName(id), config.workspacesOptions.context ?? {});
} else {
await this.addWorkspace(id, config);
}
return id;
}
public async loadWindow(itemId: string): Promise<{ windowId: string }> {
let contentItem = store.getWindowContentItem(itemId);
if (!contentItem) {
throw new Error(`Could not find window ${itemId} to load`);
}
let { windowId } = contentItem.config.componentState;
const workspace = store.getByWindowId(itemId);
if (!this.stateResolver.isWindowLoaded(itemId) && contentItem.type === "component") {
this._applicationFactory.start(contentItem, workspace.id);
await this.waitForFrameLoaded(itemId);
contentItem = store.getWindowContentItem(itemId);
windowId = contentItem.config.componentState.windowId;
}
return new Promise<{ windowId: string }>((res, rej) => {
if (!windowId) {
rej(`The window id of ${itemId} is missing`);
}
let unsub = () => {
// safety
};
const timeout = setTimeout(() => {
rej(`Could not load window ${windowId} for 5000ms`);
unsub();
}, 5000);
unsub = this._glue.windows.onWindowAdded((w) => {
if (w.id === windowId) {
res({ windowId });
unsub();
clearTimeout(timeout);
}
});
const win = this._glue.windows.list().find((w) => w.id === windowId);
if (win) {
res({ windowId });
unsub();
clearTimeout(timeout);
}
});
}
public async focusItem(itemId: string): Promise<void> {
const workspace = store.getById(itemId);
if (this._frameId === itemId) {
// do nothing
} else if (workspace) {
if (workspace.hibernateConfig) {
await this.resumeWorkspace(workspace.id);
}
this._controller.focusWorkspace(workspace.id);
} else {
this._controller.focusWindow(itemId);
}
}
public bundleWorkspace(workspaceId: string, type: "row" | "column"): void {
if (this._stateResolver.isWorkspaceHibernated(workspaceId)) {
throw new Error(`Could not bundle workspace ${workspaceId} because its hibernated`);
}
this._controller.bundleWorkspace(workspaceId, type);
}
public move(location: { x: number; y: number }) {
return this._glue.windows.my().moveTo(location.y, location.x);
}
public getFrameSummary(itemId: string): { id: string } {
const workspace = store.getByContainerId(itemId) || store.getByWindowId(itemId) || store.getById(itemId);
const isFrameId = this._frameId === itemId;
return {
id: (workspace || isFrameId) ? this._frameId : "none"
};
}
public async moveWindowTo(itemId: string, containerId: string): Promise<void> {
const sourceWorkspace = store.getByWindowId(itemId);
const targetWorkspace = store.getByContainerId(containerId) || store.getById(containerId);
if (!targetWorkspace) {
throw new Error(`Could not find container ${containerId} in frame ${this._frameId}`);
}
if (!sourceWorkspace) {
throw new Error(`Could not find window ${itemId} in frame ${this._frameId}`);
}
if (this._stateResolver.isWorkspaceHibernated(targetWorkspace.id)) {
throw new Error(`Could not move window ${itemId} to workspace ${targetWorkspace.id} because its hibernated`);
}
if (this._stateResolver.isWorkspaceHibernated(sourceWorkspace.id)) {
throw new Error(`Could not move window ${itemId} from workspace ${sourceWorkspace.id} because its hibernated`);
}
const targetWindow = store.getWindowContentItem(itemId);
if (!targetWindow) {
throw new Error(`Could not find window ${itemId} in frame ${this._frameId}`);
}
const movedWindow = sourceWorkspace.windows.find(w => w.id === itemId || w.windowId === itemId);
const windowSummaryBeforeMove = this.stateResolver.getWindowSummarySync(movedWindow.id);
this._controller.removeLayoutElement(itemId);
store.removeWindow(movedWindow, sourceWorkspace.id);
store.addWindow(movedWindow, targetWorkspace.id);
// this.closeTab(targetWindow);
await this._controller.addWindow(targetWindow.config, containerId);
const windowSummary = this.stateResolver.getWindowSummarySync(movedWindow.id);
this.workspacesEventEmitter.raiseWindowEvent({
action: "removed",
payload: {
windowSummary: windowSummaryBeforeMove
}
});
this.workspacesEventEmitter.raiseWindowEvent({
action: "added",
payload: {
windowSummary
}
});
}
public generateWorkspaceLayout(name: string, itemId: string) {
const workspace = store.getById(itemId);
if (!workspace) {
throw new Error(`Could not find workspace with id ${itemId}`);
}
return this._layoutsManager.generateLayout(name, workspace);
}
public async resumeWorkspace(workspaceId: string): Promise<void> {
const workspace = store.getById(workspaceId);
if (!workspace) {
throw new Error(`Could not find workspace ${workspaceId} in any of the frames`);
}
const hibernatedConfig = workspace.hibernateConfig;
if (!hibernatedConfig.workspacesOptions) {
hibernatedConfig.workspacesOptions = {};
}
hibernatedConfig.workspacesOptions.reuseWorkspaceId = workspaceId;
// the start mode should always be eager
await this.createWorkspace(hibernatedConfig);
workspace.hibernateConfig = undefined;
this._controller.showSaveIcon(workspaceId);
}
public lockWorkspace(lockConfig: LockWorkspaceArguments): void {
if (!lockConfig.config) {
lockConfig.config = {
allowDrop: false,
allowDropLeft: false,
allowDropTop: false,
allowDropRight: false,
allowDropBottom: false,
allowExtract: false,
allowSplitters: false,
showCloseButton: false,
showSaveButton: false,
showWindowCloseButtons: false,
showEjectButtons: false,
showAddWindowButtons: false
};
}
Object.keys(lockConfig.config).forEach((key) => {
const config = lockConfig.config as any;
if (config[key] === undefined) {
config[key] = true;
}
});
if (typeof lockConfig.config.allowDrop === "boolean") {
lockConfig.config.allowDropLeft = lockConfig.config.allowDropLeft ?? lockConfig.config.allowDrop;
lockConfig.config.allowDropTop = lockConfig.config.allowDropTop ?? lockConfig.config.allowDrop;
lockConfig.config.allowDropRight = lockConfig.config.allowDropRight ?? lockConfig.config.allowDrop;
lockConfig.config.allowDropBottom = lockConfig.config.allowDropBottom ?? lockConfig.config.allowDrop;
}
const { allowDrop, allowExtract, allowSplitters, showCloseButton, showSaveButton, showAddWindowButtons, showWindowCloseButtons, showEjectButtons } = lockConfig.config;
const { workspaceId } = lockConfig;
if (allowDrop === false) {
this._controller.disableWorkspaceDrop(workspaceId, lockConfig.config);
} else {
this._controller.enableWorkspaceDrop(workspaceId, lockConfig.config);
}
if (allowExtract === false) {
this._controller.disableWorkspaceExtract(workspaceId);
} else {
this._controller.enableWorkspaceExtract(workspaceId);
}
if (allowSplitters === false) {
this._controller.disableSplitters(workspaceId);
} else {
this._controller.enableSplitters(workspaceId);
}
if (showCloseButton === false) {
this._controller.disableWorkspaceCloseButton(workspaceId);
} else {
this._controller.enableWorkspaceCloseButton(workspaceId);
}
if (showSaveButton === false) {
this._controller.disableWorkspaceSaveButton(workspaceId);
} else {
this._controller.enableWorkspaceSaveButton(workspaceId);
}
if (showAddWindowButtons === false) {
this._controller.disableWorkspaceAddWindowButtons(workspaceId);
} else {
this._controller.enableWorkspaceAddWindowButtons(workspaceId);
}
if (showEjectButtons === false) {
this._controller.disableWorkspaceEjectButtons(workspaceId);
} else {
this._controller.enableWorkspaceEjectButtons(workspaceId);
}
if (showWindowCloseButtons === false) {
this._controller.disableWorkspaceWindowCloseButtons(workspaceId);
} else {
this._controller.enableWorkspaceWindowCloseButtons(workspaceId);
}
}
public lockContainer(lockConfig: LockContainerArguments): void {
if (!lockConfig.config && lockConfig.type === "column") {
lockConfig.config = {
allowDrop: false,
allowSplitters: false
};
} else if (!lockConfig.config && lockConfig.type === "row") {
lockConfig.config = {
allowDrop: false,
allowSplitters: false
};
} else if (!lockConfig.config && lockConfig.type === "group") {
lockConfig.config = {
allowDrop: false,
allowDropHeader: false,
allowDropLeft: false,
allowDropRight: false,
allowDropTop: false,
allowDropBottom: false,
allowExtract: false,
showAddWindowButton: false,
showEjectButton: false,
showMaximizeButton: false
};
}
if (typeof lockConfig.config.allowDrop !== "undefined" && lockConfig.type === "group") {
lockConfig.config.allowDropHeader = lockConfig.config.allowDropHeader ?? lockConfig.config.allowDrop;
lockConfig.config.allowDropLeft = lockConfig.config.allowDropLeft ?? lockConfig.config.allowDrop;
lockConfig.config.allowDropTop = lockConfig.config.allowDropTop ?? lockConfig.config.allowDrop;
lockConfig.config.allowDropRight = lockConfig.config.allowDropRight ?? lockConfig.config.allowDrop;
lockConfig.config.allowDropBottom = lockConfig.config.allowDropBottom ?? lockConfig.config.allowDrop;
}
Object.keys(lockConfig.config).forEach((key) => {
const config = lockConfig.config as any;
if (config[key] === undefined) {
config[key] = true;
}
});
switch (lockConfig.type) {
case "column":
this.handleColumnLockRequested(lockConfig);
break;
case "row":
this.handleRowLockRequested(lockConfig);
break;
case "group":
this.handleGroupLockRequested(lockConfig);
break;
}
}
public lockWindow(lockConfig: LockWindowArguments): void {
if (!lockConfig.config) {
lockConfig.config = {
allowExtract: false,
showCloseButton: false,
};
}
Object.keys(lockConfig.config).forEach((key) => {
const config = lockConfig.config as any;
if (config[key] === undefined) {
config[key] = true;
}
});
const { allowExtract, showCloseButton } = lockConfig.config;
const { windowPlacementId } = lockConfig;
if (allowExtract === false) {
this._controller.disableWindowExtract(windowPlacementId);
} else {
this._controller.enableWindowExtract(windowPlacementId, allowExtract);
}
if (showCloseButton === false) {
this._controller.disableWindowCloseButton(windowPlacementId);
} else {
this._controller.enableWindowCloseButton(windowPlacementId, showCloseButton);
}
const workspace = store.getByWindowId(windowPlacementId);
if (workspace?.layout) {
workspace.layout.updateSize();
}
}
public async hibernateWorkspace(workspaceId: string): Promise<GoldenLayout.Config> {
const workspace = store.getById(workspaceId);
if (store.getActiveWorkspace().id === workspace.id) {
throw new Error(`Cannot hibernate workspace ${workspace.id} because its active`);
}
if (this.stateResolver.isWorkspaceHibernated(workspaceId)) {
throw new Error(`Cannot hibernate workspace ${workspaceId} because it has already been hibernated`);
}
if (!workspace.layout) {
throw new Error(`Cannot hibernate workspace ${workspace.id} because its empty`);
}
const snapshot = await this.stateResolver.getWorkspaceConfig(workspace.id);
workspace.hibernatedWindows = workspace.windows;
(snapshot.workspacesOptions as any).isHibernated = true;
workspace.hibernateConfig = snapshot;
workspace.windows.map((w) => store.getWindowContentItem(w.id)).forEach((w) => this.closeTab(w, false));
store.removeLayout(workspace.id);
this._controller.showHibernationIcon(workspaceId);
return snapshot;
}
public closeTab(item: GoldenLayout.ContentItem, emptyWorkspaceCheck = true): void {
const itemId = idAsString(item.config.id);
const workspace = store.getByWindowId(itemId);
const windowSummary = this.stateResolver.getWindowSummarySync(itemId);
this._controller.removeLayoutElement(itemId);
this._frameController.remove(itemId);
this._applicationFactory.notifyFrameWillClose(windowSummary.config.windowId, windowSummary.config.appName).catch((e) => {
// Log the error
});
if (!workspace.hibernatedWindows.some((hw) => windowSummary.itemId === hw.id)) {
this.workspacesEventEmitter.raiseWindowEvent({
action: "removed",
payload: {
windowSummary
}
});
}
if (!workspace.windows.length && emptyWorkspaceCheck) {
this._controller.resetWorkspace(workspace.id);
}
}
public resizeItem(args: ResizeItemArguments): void {
if (args.itemId === this.frameId) {
throw new Error(`Cannot resize frame ${args.itemId}`);
} else {
return this.resizeWorkspaceItem(args);
}
}
public unmount(): void {
try {
this._popupManager.hidePopup();
} catch (error) {
// tslint:disable-next-line: no-console
console.warn(error);
}
}
private resizeWorkspaceItem(args: ResizeItemArguments): void {
const item = store.getContainer(args.itemId) || store.getWindowContentItem(args.itemId);
if (!item) {
throw new Error(`Could not find container ${args.itemId} in frame ${this.frameId}`);
}
if (item.type === "column" && args.height) {
throw new Error(`Requested resize for ${item.type} ${args.itemId}, however an unsupported argument (height) was passed`);
}
if (item.type === "row" && args.width) {
throw new Error(`Requested resize for ${item.type} ${args.itemId}, however an unsupported argument (width) was passed`);
}
const workspace = store.getByContainerId(item.config.id) || store.getByWindowId(idAsString(item.config.id));
let maximizedWindow;
let maximizedContainer;
if (this.stateResolver.isWorkspaceHibernated(workspace.id)) {
throw new Error(`Requested resize for ${item.type} ${args.itemId}, however the workspace ${workspace.id} is hibernated`);
}
if (workspace) {
maximizedWindow = workspace.windows.find((w) => {
return this.stateResolver.isWindowMaximized(w.id);
});
maximizedContainer = workspace.layout?.root?.getItemsByFilter((layoutItem) => {
return layoutItem.hasId("__glMaximised") && layoutItem.type !== "component";
})[0];
}
if (maximizedWindow) {
this._controller.restoreWindow(maximizedWindow.id);
}
if (maximizedContainer) {
this._controller.restoreContainer(idAsString(maximizedContainer.config.id));
}
if (item.type === "row") {
this._controller.resizeRow(item, args.height);
} else if (item.type === "column") {
this._controller.resizeColumn(item, args.width);
} else if (item.type === "stack") {
this._controller.resizeStack(item, args.width, args.height);
} else {
this._controller.resizeComponent(item, args.width, args.height);
}
if (maximizedWindow) {
this._controller.maximizeWindow(maximizedWindow.id);
}
if (maximizedContainer) {
this._controller.maximizeContainer(idAsString(maximizedContainer.config.id));
}
}
private async initLayout(): Promise<void> {
const workspacesSystemSettings = await systemSettings.getSettings(this._glue);
const config = await this._layoutsManager.getInitialConfig();
this.subscribeForPopups();
this.subscribeForLayout();
this._isLayoutInitialized = true;
await Promise.all(config.workspaceConfigs.map(c => {
return this._glue.contexts.set(getWorkspaceContextName(c.id), c.config?.workspacesOptions?.context || {});
}));
await this._controller.init({
frameId: this._frameId,
workspaceLayout: config.workspaceLayout,
workspaceConfigs: config.workspaceConfigs,
showLoadingIndicator: workspacesSystemSettings?.loadingStrategy?.showDelayedIndicator || false
});
Promise.all(store.workspaceIds.map((wid) => {
const loadingStrategy = this._applicationFactory.getLoadingStrategy(workspacesSystemSettings, config.workspaceConfigs[0].config);
return this.handleWindows(wid, loadingStrategy);
}));
store.layouts.map((l) => l.layout).filter((l) => l).forEach((l) => this.reportLayoutStructure(l));
if (startupReader.config.emptyFrame) {
this._workspacesEventEmitter.raiseFrameEvent({
action: "opened", payload: {
frameSummary: {
id: this._frameId
}
}
});
}
}
private async reinitializeWorkspace(id: string, config: GoldenLayout.Config): Promise<void> {
await this._controller.reinitializeWorkspace(id, config);
const workspacesSystemSettings = await systemSettings.getSettings(this._glue);
const loadingStrategy = this._applicationFactory.getLoadingStrategy(workspacesSystemSettings, config);
this.handleWindows(id, loadingStrategy);
}
private subscribeForLayout(): void {
this._controller.emitter.onContentItemResized((target, id) => {
this._frameController.moveFrame(id, getElementBounds(target));
});
this._controller.emitter.onTabCloseRequested(async (item) => {
const workspace = store.getByWindowId(idAsString(item.config.id));
// const windowSummary = await this.stateResolver.getWindowSummary(item.config.id);
this.closeTab(item);
this._controller.removeLayoutElement(idAsString(item.config.id));
this._frameController.remove(idAsString(item.config.id));
});
this._controller.emitter.onWorkspaceTabCloseRequested((workspace) => {
this.closeWorkspace(workspace);
});
this._controller.emitter.onTabElementMouseDown((tab) => {
const tabContentSize = getElementBounds(tab.contentItem.element);
const contentWidth = Math.min(tabContentSize.width, 800);
const contentHeight = Math.min(tabContentSize.height, 600);
this._controller.setDragElementSize(contentWidth, contentHeight);
});
this._controller.emitter.onTabDragStart((tab) => {
const dragElement = this._controller.getDragElement();
const mutationObserver = new MutationObserver((mutations) => {
Array.from(mutations).forEach((m) => {
if (m.type === "attributes") {
const proxyContent = $(this._controller.getDragElement())
.children(".lm_content")
.children(".lm_item_container");
const proxyContentBounds = getElementBounds(proxyContent[0]);
const id = idAsString(tab.contentItem.config.id);
this._frameController.moveFrame(id, proxyContentBounds);
this._frameController.bringToFront(id);
}
});
});
if (!dragElement) {
return;
}
mutationObserver.observe(dragElement, {
attributes: true
});
const windowSummary = this.stateResolver.getWindowSummarySync(tab.contentItem.config.id, tab.contentItem as GoldenLayout.Component);
this.workspacesEventEmitter.raiseWindowEvent({
action: "removed", payload: {
windowSummary
}
});
});
this._controller.emitter.onItemDropped((item) => {
const windowSummary = this.stateResolver.getWindowSummarySync(item.config.id, item as GoldenLayout.Component);
this.workspacesEventEmitter.raiseWindowEvent({
action: "added", payload: {
windowSummary
}
});
});
this._controller.emitter.onSelectionChanged(async (toBack, toFront) => {
this._popupManager.hidePopup();
this._frameController.selectionChanged(toFront.map((tf) => tf.id), toBack.map((t) => t.id));
});
this._controller.emitter.onWorkspaceAdded((workspace) => {
this.handleOnWorkspaceAdded(workspace);
});
this._controller.emitter.onWorkspaceSelectionChanged((workspace, toBack) => {
this._popupManager.hidePopup();
if (!workspace.layout) {
this._frameController.selectionChangedDeep([], toBack.map((w) => w.id));
this._workspacesEventEmitter.raiseWorkspaceEvent({
action: "selected", payload: {
frameSummary: { id: this._frameId },
workspaceSummary: this.stateResolver.getWorkspaceSummary(workspace.id)
}
});
if (workspace.hibernateConfig) {
this.resumeWorkspace(workspace.id);
}
return;
}
const allWinsInLayout = getAllWindowsFromConfig(workspace.layout.toConfig().content)
.filter((w) => this._controller.isWindowVisible(w.id));
this._frameController.selectionChangedDeep(allWinsInLayout.map((w) => idAsString(w.id)), toBack.map((w) => w.id));
this._workspacesEventEmitter.raiseWorkspaceEvent({
action: "selected", payload: {
frameSummary: { id: this._frameId },
workspaceSummary: this.stateResolver.getWorkspaceSummary(workspace.id)
}
});
});
this._controller.emitter.onAddButtonClicked(async ({ laneId, workspaceId, bounds, parentType }) => {
const payload: any = {
boxId: laneId,
workspaceId,
parentType,
frameId: this._frameId,
peerId: this._glue.agm.instance.peerId,
domNode: undefined,
resizePopup: undefined,
hidePopup: undefined
};
await this._popupManager.showAddWindowPopup(bounds, payload);
});
this._controller.emitter.onContentLayoutInit((layout: Workspace["layout"]) => {
this.reportLayoutStructure(layout);
});
this._controller.emitter.onWorkspaceAddButtonClicked(async () => {
const payload = {
frameId: this._frameId,
peerId: this._glue.agm.instance.windowId
};
const addButton = store
.workspaceLayoutHeader
.element
.find(".lm_workspace_controls")
.find(".lm_add_button");
const addButtonBounds = getElementBounds(addButton);
await this._popupManager.showOpenWorkspacePopup(addButtonBounds, payload);
});
this._controller.emitter.onWorkspaceSaveRequested(async (workspaceId) => {
const payload: any = {
frameId: this._frameId,
workspaceId,
peerId: this._glue.agm.instance.peerId,
buildMode: scReader.config.build,
domNode: undefined,
resizePopup: undefined,
hidePopup: undefined
};
const saveButton = (store
.getWorkspaceLayoutItemById(workspaceId) as GoldenLayout.Component)
.tab
.element
.find(".lm_saveButton");
const targetBounds = getElementBounds(saveButton);
await this._popupManager.showSaveWorkspacePopup(targetBounds, payload);
});
this._controller.emitter.onContainerMaximized((contentItem: GoldenLayout.ContentItem) => {
if (contentItem.config.type === "component") {
return;
}
const components = contentItem.getItemsByFilter((ci) => ci.type === "component");
components.forEach((c) => {
this._frameController.maximizeTab(idAsString(c.config.id));
});
const stacks = contentItem.getItemsByFilter((ci) => ci.type === "stack");
if (contentItem.type === "stack") {
stacks.push(contentItem);
}
const [toFront, toBack] = stacks.reduce((acc, stack: GoldenLayout.Stack) => {
const activeItem = stack.getActiveContentItem();
const toBack = stack.contentItems.map((ci) => idAsString(ci.config.id));
acc[0].push(idAsString(activeItem.config.id));
acc[1] = [...acc[1], ...toBack];
return acc;
}, [[], []]);
this._frameController.selectionChanged(toFront, toBack);
});
this._controller.emitter.onContainerRestored((contentItem: GoldenLayout.ContentItem) => {
if (contentItem.config.type === "component") {
return;
}
const components = contentItem.getItemsByFilter((ci) => ci.type === "component");
components.forEach((c) => {
this._frameController.restoreTab(idAsString(c.config.id));
});
const stacks = contentItem.getItemsByFilter((ci) => ci.type === "stack");
if (contentItem.type === "stack") {
stacks.push(contentItem);
}
const [toFront, toBack] = stacks.reduce((acc, stack: GoldenLayout.Stack) => {
const activeItem = stack.getActiveContentItem();
const toBack = stack.contentItems.map((ci) => idAsString(ci.config.id));
acc[0].push(idAsString(activeItem.config.id));
acc[1] = [...acc[1], ...toBack];
return acc;
}, [[], []]);
this._frameController.selectionChanged(toFront, toBack);
});
this._controller.emitter.onEjectRequested((item) => {
if (!item.isComponent) {
throw new Error(`Can't eject item of type ${item.type}`);
}
return this.eject(item);
});
this._controller.emitter.onComponentSelectedInWorkspace((component, workspaceId) => {
this._applicationFactory.start(component, workspaceId);
});
const resizedTimeouts: { [id: string]: NodeJS.Timeout } = {};
this._controller.emitter.onWorkspaceContainerResized((workspaceId) => {
const id = idAsString(workspaceId);
if (resizedTimeouts[id]) {
clearTimeout(resizedTimeouts[id]);
}
resizedTimeouts[id] = setTimeout(() => {
this._controller.refreshWorkspaceSize(id);
}, 16); // 60 FPS
});
// debouncing because there is potential for 1ms spam
let shownTimeout: NodeJS.Timeout = undefined;
componentStateMonitor.onWorkspaceContentsShown((workspaceId: string) => {
const workspace = store.getActiveWorkspace();
if (!workspace?.layout || workspaceId !== workspace.id) {
return;
}
if (shownTimeout) {
clearTimeout(shownTimeout);
}
shownTimeout = setTimeout(() => {
const containerElement = $(`#nestHere${workspace.id}`);
const bounds = getElementBounds(containerElement[0]);
workspace.layout.updateSize(bounds.width, bounds.height);
}, 50);
const stacks = workspace.layout.root.getItemsByFilter((e) => e.type === "stack");
this._frameController.selectionChangedDeep(stacks.map(s => idAsString(s.getActiveContentItem().config.id)), []);
});
componentStateMonitor.onWorkspaceContentsHidden((workspaceId: string) => {
const workspace = store.getById(workspaceId);
if (!workspace?.layout || workspaceId !== workspace.id) {
return;
}
this._frameController.selectionChangedDeep([], workspace.windows.map(w => w.id));
});
this.workspacesEventEmitter.onWorkspaceEvent((action, payload) => {
const workspace = store.getById(payload.workspaceSummary.id);
if (!workspace) {
return;
}
workspace.lastActive = Date.now();
});
}
private subscribeForPopups(): void {
this._frameController.onFrameContentClicked(() => {
this._popupManager.hidePopup();
});
this._frameController.onWindowTitleChanged((id, title) => {
this.setItemTitle(id, title);
});
this._frameController.onFrameLoaded((id) => {
this._controller.hideLoadingIndicator(id);
});
}
private cleanUp = (): void => {
this._isDisposing = true;
if (scReader.config?.build) {
return;
}
const windowSummaries: WindowSummary[] = [];
const workspaceSummaries = store.workspaceIds.map((wid) => {
const workspace = store.getById(wid);
windowSummaries.push(...workspace.windows.map(w => this.stateResolver.getWindowSummarySync(w.id)));
const snapshot = this.stateResolver.getWorkspaceConfig(wid);
const hibernatedSummaries = this.stateResolver.extractWindowSummariesFromSnapshot(snapshot);
windowSummaries.push(...hibernatedSummaries);
return this.stateResolver.getWorkspaceSummary(wid);
});
windowSummaries.forEach((ws) => {
this._applicationFactory.notifyFrameWillClose(ws.config.windowId, ws.config.appName).catch((e) => {
// Log the error
});
this.workspacesEventEmitter.raiseWindowEvent({ action: "removed", payload: { windowSummary: ws } });
});
workspaceSummaries.forEach((ws) => {
this.workspacesEventEmitter.raiseWorkspaceEvent({ action: "closed", payload: { frameSummary: { id: this._frameId }, workspaceSummary: ws } });
});
const currentWorkspaces = store.layouts.filter(l => !l.layout?.config?.workspacesOptions?.noTabHeader);
this._layoutsManager.saveWorkspacesFrame(currentWorkspaces);
this.workspacesEventEmitter.raiseFrameEvent({ action: "closed", payload: { frameSummary: { id: this._frameId } } });
};
private reportLayoutStructure(layout: Workspace["layout"]): void {
const allWinsInLayout = getAllWindowsFromConfig(layout.toConfig().content);
allWinsInLayout.forEach((w) => {
const win = layout.root.getItemsById(w.id)[0];
this._frameController.moveFrame(idAsString(win.config.id), getElementBounds(win.element));
});
}
private closeWorkspace(workspace: Workspace): void {
if (!workspace) {
throw new Error("Could not find a workspace to close");
}
if (workspace.hibernateConfig) {
this.closeHibernatedWorkspaceCore(workspace);
} else {
this.closeWorkspaceCore(workspace);
}
}
private closeWorkspaceCore(workspace: Workspace): void {
const workspaceSummary = this.stateResolver.getWorkspaceSummary(workspace.id);
const windowSummaries = workspace.windows.map((w) => {
if (store.getWindowContentItem(w.id)) {
return this.stateResolver.getWindowSummarySync(w.id);
}
}).filter(ws => ws);
workspace.windows.forEach((w) => this._frameController.remove(w.id));
const isFrameEmpty = this.checkForEmptyWorkspace(workspace);
windowSummaries.forEach((ws) => {
this._applicationFactory.notifyFrameWillClose(ws.config.windowId, ws.config.appName).catch((e) => {
// Log the error
});
this.workspacesEventEmitter.raiseWindowEvent({
action: "removed",
payload: {
windowSummary: ws
}
});
});
if (isFrameEmpty) {
return;
}
this.workspacesEventEmitter.raiseWorkspaceEvent({
action: "closed",
payload: {
workspaceSummary,
frameSummary: { id: this._frameId }
}
});
}
private closeHibernatedWorkspaceCore(workspace: Workspace): void {
const workspaceSummary = this.stateResolver.getWorkspaceSummary(workspace.id);
const snapshot = this.stateResolver.getSnapshot(workspace.id) as GoldenLayout.Config;
const windowSummaries = this.stateResolver.extractWindowSummariesFromSnapshot(snapshot);
workspace.windows.forEach((w) => this._frameController.remove(w.id));
const isFrameEmpty = this.checkForEmptyWorkspace(workspace);
windowSummaries.forEach((ws) => {
this._applicationFactory.notifyFrameWillClose(ws.config.windowId, ws.config.appName).catch((e) => {
// Log the error
});
this.workspacesEventEmitter.raiseWindowEvent({
action: "removed",
payload: {
windowSummary: ws
}
});
});
if (isFrameEmpty) {
return;
}
this.workspacesEventEmitter.raiseWorkspaceEvent({
action: "closed",
payload: {
workspaceSummary,
frameSummary: { id: this._frameId }
}
});
}
private async addWorkspace(id: string, config: GoldenLayout.Config): Promise<void> {
await this._glue.contexts.set(getWorkspaceContextName(id), config?.workspacesOptions?.context || {});
await this._controller.addWorkspace(id, config);
this._controller.emitter.raiseEvent("workspace-added", { workspace: store.getById(id) });
const workspacesSystemSettings = await systemSettings.getSettings(this._glue);
const loadingStrategy = this._applicationFactory.getLoadingStrategy(workspacesSystemSettings, config);
this.handleWindows(id, loadingStrategy).catch((e) => {
// If it fails do nothing
console.log(e);
});
}
private async handleWindows(workspaceId: string, loadingStrategy: LoadingStrategy): Promise<void> {
switch (loadingStrategy) {
case "delayed":
await this._applicationFactory.startDelayed(workspaceId);
break;
case "direct":
await this._applicationFactory.startDirect(workspaceId);
break;
case "lazy":
await this._applicationFactory.startLazy(workspaceId);
break;
}
}
private checkForEmptyWorkspace(workspace: Workspace): boolean {
// Closing all workspaces except the last one
if (store.layouts.length === 1) {
if (this._isLayoutInitialized && (window as any).glue42core.isPlatformFrame) {
const newId = this._configFactory.getId();
this._controller.addWorkspace(newId, undefined).then(() => {
this.handleOnWorkspaceAddedWithSnapshot(store.getById(newId));
this.checkForEmptyWorkspace(workspace);
}).catch(() => {
// Can happen if the workspace has already been closed
// e.g the closing of the last window in a workspace could potentially trigger this behavior
});
return false;
} else if (this._isLayoutInitialized) {
try {
this._facade.executeAfterControlIsDone(() => {
window.close();
});
} catch (error) {
// Try to close my window if it fails fallback to frame with one empty workspace
}
return true;
}
} else {
this._controller.removeWorkspace(workspace.id);
}
return false;
}
private waitForFrameLoaded(itemId: string): Promise<void> {
return new Promise<void>((res, rej) => {
let unsub = (): void => {
// safety
};
const timeout = setTimeout(() => {
unsub();
rej(`Did not hear frame loaded for ${itemId} in 5000ms`);
}, 5000);
unsub = this.workspacesEventEmitter.onWindowEvent((action, payload) => {
if (action === "loaded" && payload.windowSummary.itemId === itemId) {
res();
clearTimeout(timeout);
unsub();
}
});
if (this.stateResolver.isWindowLoaded(itemId)) {
res();
clearTimeout(timeout);
unsub();
}
});
}
private handleGroupLockRequested(data: LockGroupArguments): void {
const { allowExtract, showAddWindowButton, showEjectButton, showMaximizeButton, allowDrop } = data.config;
if (allowExtract === false) {
this._controller.disableGroupExtract(data.itemId);
} else {
this._controller.enableGroupExtract(data.itemId, allowExtract);
}
if (showAddWindowButton === false) {
this._controller.disableGroupAddWindowButton(data.itemId);
} else {
this._controller.enableGroupAddWindowButton(data.itemId, showAddWindowButton);
}
if (showEjectButton === false) {
this._controller.disableGroupEjectButton(data.itemId);
} else {
this._controller.enableGroupEjectButton(data.itemId, showEjectButton);
}
if (showMaximizeButton === false) {
this._controller.disableGroupMaximizeButton(data.itemId);
} else {
this._controller.enableGroupMaximizeButton(data.itemId, showMaximizeButton);
}
if (allowDrop === false) {
this._controller.disableGroupDrop(data.itemId, data.config);
} else {
this._controller.enableGroupDrop(data.itemId, data.config);
}
const workspace = store.getByContainerId(data.itemId);
if (workspace?.layout) {
workspace.layout.updateSize();
}
}
private handleRowLockRequested(data: LockRowArguments): void {
const { allowDrop, allowSplitters } = data.config;
if (allowDrop === false) {
this._controller.disableRowDrop(data.itemId);
} else {
this._controller.enableRowDrop(data.itemId, allowDrop);
}
if (allowSplitters === false) {
this._controller.disableRowSplitters(data.itemId);
} else {
this._controller.enableRowSplitters(data.itemId, allowSplitters);
}
}
private handleColumnLockRequested(data: LockColumnArguments): void {
const { allowDrop, allowSplitters } = data.config;
if (allowDrop === false) {
this._controller.disableColumnDrop(data.itemId);
} else {
this._controller.enableColumnDrop(data.itemId, allowDrop);
}
if (allowSplitters === false) {
this._controller.disableColumnSplitters(data.itemId);
} else {
this._controller.enableColumnSplitters(data.itemId, allowSplitters);
}
}
private cleanIsPinned(data: GoldenLayout.Config | GoldenLayout.ItemConfig): GoldenLayout.ItemConfig | GoldenLayout.Config {
if (data.type !== "row" && data.type !== "column") {
return data;
}
let hasFoundIsPinned = false;
const clone = JSON.parse(JSON.stringify(data));
const traverseAndClean = (item: GoldenLayout.ItemConfig): void => {
if (item.workspacesConfig.isPinned) {
hasFoundIsPinned = true;
item.workspacesConfig.isPinned = false;
}
if (item.type === "component") {
return;
}
item.content.forEach((c) => traverseAndClean(c));
};
traverseAndClean(clone);
if (hasFoundIsPinned) {
return clone;
}
return data;
}
private applyIsPinned(initialConfig: GoldenLayout.Config | GoldenLayout.ItemConfig, currentConfig: GoldenLayout | GoldenLayout.ContentItem): void {
if (initialConfig.type !== "row" && initialConfig.type !== "column") {
return;
}
if (currentConfig.config.type !== "row" && currentConfig.config.type !== "column") {
return;
}
let hasFoundIsPinned = false;
const traverseAndApply = (initialItem: GoldenLayout.ItemConfig, currentItem: GoldenLayout.ContentItem): void => {
if (initialItem.workspacesConfig.isPinned) {
hasFoundIsPinned = true;
currentItem.config.workspacesConfig.isPinned = true;
}
if (initialItem.type === "component" || currentItem.type === "component") {
return;
}
initialItem.content.forEach((c, i) => traverseAndApply(c, currentItem.contentItems[i]));
};
traverseAndApply(initialConfig, currentConfig as GoldenLayout.ContentItem);
}
private handleOnWorkspaceAdded(workspace: Workspace): void {
const allOtherWindows = store.workspaceIds.filter((wId) => wId !== workspace.id).reduce((acc, w) => {
return [...acc, ...store.getById(w).windows];
}, []);
this._workspacesEventEmitter.raiseWorkspaceEvent({
action: "opened",
payload: {
frameSummary: { id: this._frameId },
workspaceSummary: this.stateResolver.getWorkspaceSummary(workspace.id)
}
});
if (store.getActiveWorkspace().id === workspace.id) {
this._workspacesEventEmitter.raiseWorkspaceEvent({
action: "selected",
payload: {
frameSummary: { id: this._frameId },
workspaceSummary: this.stateResolver.getWorkspaceSummary(workspace.id)
}
});
if (!workspace.layout) {
this._frameController.selectionChangedDeep([], allOtherWindows.map((w) => w.id));
return;
}
const allWinsInLayout = getAllWindowsFromConfig(workspace.layout.toConfig().content);
this._frameController.selectionChangedDeep(allWinsInLayout.map((w) => idAsString(w.id)), allOtherWindows.map((w) => w.id));
}
if (!workspace.layout) {
return;
}
const workspaceOptions = workspace.layout.config.workspacesOptions as { title: string; name: string };
const title = workspaceOptions.title || workspaceOptions.name;
if (title) {
store.getWorkspaceLayoutItemById(workspace.id)?.setTitle(title);
}
}
private handleOnWorkspaceAddedWithSnapshot(workspace: Workspace): void {
const allOtherWindows = store.workspaceIds.filter((wId) => wId !== workspace.id).reduce((acc, w) => {
return [...acc, ...store.getById(w).windows];
}, []);
const snapshot = this._stateResolver.getWorkspaceSnapshot(workspace.id);
this._workspacesEventEmitter.raiseWorkspaceEvent({
action: "opened",
payload: {
frameSummary: { id: this._frameId },
workspaceSnapshot: snapshot,
workspaceSummary: this.stateResolver.getWorkspaceSummary(workspace.id)
}
});
if (store.getActiveWorkspace().id === workspace.id) {
this._workspacesEventEmitter.raiseWorkspaceEvent({
action: "selected",
payload: {
frameSummary: { id: this._frameId },
workspaceSummary: this.stateResolver.getWorkspaceSummary(workspace.id)
}
});
if (!workspace.layout) {
this._frameController.selectionChangedDeep([], allOtherWindows.map((w) => w.id));
return;
}
const allWinsInLayout = getAllWindowsFromConfig(workspace.layout.toConfig().content);
this._frameController.selectionChangedDeep(allWinsInLayout.map((w) => idAsString(w.id)), allOtherWindows.map((w) => w.id));
}
if (!workspace.layout) {
return;
}
const workspaceOptions = workspace.layout.config.workspacesOptions as { title: string; name: string };
const title = workspaceOptions.title || workspaceOptions.name;
if (title) {
store.getWorkspaceLayoutItemById(workspace.id)?.setTitle(title);
}
}
}
export default new WorkspacesManager(); | the_stack |
import * as jsStyles from './EditTaskStyles';
import * as moment from 'moment';
import * as React from 'react';
import styles from './EditTask.module.scss';
import { Assigns } from './../Assigns/Assigns';
import * as strings from 'MyTasksWebPartStrings';
import { CommunicationColors } from '@uifabric/fluent-theme/lib/fluent/FluentColors';
import { DefaultPalette, FontSizes, FontWeights } from 'office-ui-fabric-react/lib/Styling';
import { getGUID } from '@pnp/pnpjs';
import { IAssignments } from '../../../../services/IAssignments';
import { ICheckListItem } from '../../../../services/ICheckListItem';
import { IEditTaskProps } from './IEditTaskProps';
import { IEditTaskState } from './IEditTaskState';
import { IMember } from '../../../../services/IGroupMembers';
import { IPlannerBucket } from '../../../../services/IPlannerBucket';
import { registerChangeSettingsHandler } from '@microsoft/teams-js';
import { CheckList } from './../CheckList';
import {
ActionButton,
Checkbox,
DatePicker,
DayOfWeek,
DialogType,
Dropdown,
Icon,
IContextualMenuItem,
IDatePickerStrings,
IDropdownOption,
IDropdownProps,
IIconProps,
ITextFieldProps,
Label,
MessageBar,
MessageBarType,
Spinner,
SpinnerType,
Stack,
TextField,
Facepile,
OverflowButtonType,
PersonaSize,
IFacepilePersona,
Dialog,
StackItem,
Callout,
} from 'office-ui-fabric-react';
import {Attachments} from './../Attachments';
import { labelProperties } from '@uifabric/utilities';
import { IPlannerAssignment } from '../../../../services/IPlannerAssignment';
import { getTheme } from '@uifabric/styling';
import { EditCategories} from './../../../../Controls/EditCategories/EditCategories';
import { refreshOptions} from '../TaskCard/ERefreshOptions';
import { ITask } from '../../../../services/ITask';
const DayPickerStrings: IDatePickerStrings = {
months: [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
],
shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
shortDays: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
goToToday: 'Go to today',
prevMonthAriaLabel: 'Go to previous month',
nextMonthAriaLabel: 'Go to next month',
prevYearAriaLabel: 'Go to previous year',
nextYearAriaLabel: 'Go to next year',
closeButtonAriaLabel: 'Close date picker'
};
const addFriendIcon: IIconProps = { iconName: 'AddFriend', style: { marginLeft: 0, paddingLeft: 0 } };
/**
* New task
*/
export class EditTask extends React.Component<IEditTaskProps, IEditTaskState> {
private _assigns: IMember[] = [];
private _checkListItems: ICheckListItem[] = [];
constructor(props: IEditTaskProps) {
super(props);
this.state = {
hideDialog: !this.props.displayDialog,
hasError: false,
errorMessage: '',
progressSelectedKey: this.props.task.percentComplete === 0 ? 0 : this.props.task.percentComplete === 50 ? 50 : 100,
disableSave: true,
selectedBucket: undefined,
buckets: undefined,
isLoading: true,
addAssigns: false,
dueDate: '',
calloutTarget: undefined,
displayAssigns: false,
renderAssigns: [],
task: this.props.task,
taskDetails: this.props.taskDetails,
newCheckListItemTitle: '',
displayAttachments:false,
taskChanged: false,
isCallOut: false,
};
}
/**
* Get assignments of edit task
*/
private _getAssignments = async (assignments: IAssignments): Promise<void> => {
let assignmentsKeys: string[] = [];
assignmentsKeys = Object.keys(assignments);
for (const userId of assignmentsKeys) {
try {
const user = await this.props.spservice.getUser(userId);
this._assigns.push(user);
} catch (error) {
throw new Error(error);
}
}
}
/**
* Render assignments of edit task
*/
private _renderAssignments = async (assignments: IMember[]): Promise<IFacepilePersona[]> => {
let personas: IFacepilePersona[] = [];
for (const user of assignments) {
try {
// const userInfo = await this.props.spservice.getUser(user.id);
const userPhoto = await this.props.spservice.getUserPhoto(user.userPrincipalName);
personas.push({
style: { paddingRight: 5 },
personaName: user.displayName,
imageUrl: userPhoto
});
} catch (error) {
throw new Error(error);
}
}
return personas;
}
/**
* Components did mount
*/
public async componentWillMount(): Promise<void> {
const buckets = await this._getPlannerBuckets(this.state.task.planId);
await this._getAssignments(this.state.task.assignments);
const renderAssigns = await this._renderAssignments(this._assigns);
// await this._getCheckListItems(this.state.taskDetails.checklist);
// const renderCheckListItems = await this._renderCheckListItems(this._checkListItems);
this.setState({
buckets: buckets,
isLoading: false,
selectedBucket: this.state.task.bucketId,
renderAssigns: renderAssigns
});
}
/**
* Components did update
* @param prevProps
* @param prevState
*/
public componentDidUpdate(prevProps: IEditTaskProps, prevState: IEditTaskState): void {
if (this.props.displayDialog !== prevProps.displayDialog) {
this.setState({ hideDialog: !this.props.displayDialog });
}
if (this.props.taskDetails !== prevProps.taskDetails) {
this.setState({ taskDetails: this.props.taskDetails });
}
}
private _displayAttachemnts = (ev?: React.MouseEvent<HTMLElement, MouseEvent> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => {
this.setState({displayAttachments: true});
}
/**
* Closes dialog
* @param [ev]
*/
private _closeDialog = (ev?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
this.setState({ hideDialog: true });
this.props.onDismiss(refreshOptions.card); // Refresh card = 0 Refresh List os Cards = 1
};
/**
* Get planner buckets of new task
*/
private _getPlannerBuckets = async (planId: string): Promise<IDropdownOption[]> => {
try {
const plannerBuckets: IPlannerBucket[] = await this.props.spservice.getPlanBuckets(String(planId));
let bucketsMenu: IDropdownOption[] = [];
for (const bucket of plannerBuckets) {
bucketsMenu.push({
key: bucket.id,
text: bucket.name
});
}
return bucketsMenu;
} catch (error) {
Promise.reject(error);
}
}
/**
* Gets user plans
*/
/**
* Determines whether render option on
*/
private _onRenderOption = (option: IDropdownOption): JSX.Element => {
return (
<div className={styles.selectPlanContainer}>
{option.data && option.data.icon && (
<Icon style={{ marginRight: '8px', color: DefaultPalette.green }} iconName={option.data.icon} aria-hidden='true' />
)}
<span>{option.text}</span>
</div>
);
}
private _onRenderTitleBucket = (options: IDropdownOption[]): JSX.Element => {
const option = options[0];
return (
<div className={styles.selectPlanContainer}>
{option.data && option.data.icon && (
<Icon style={{ marginRight: '8px' }} iconName={option.data.icon} aria-hidden='true' />
)}
<span>{option.text}</span>
</div>
);
}
/**
* Determines whether render title on
*/
private _onRenderTitleProgress = (options: IDropdownOption[]): JSX.Element => {
const option = options[0];
return (
<div className={styles.selectPlanContainer}>
{option.data && option.data.icon && (
<Icon style={{ marginRight: '8px', color: DefaultPalette.green }} iconName={option.data.icon} aria-hidden='true' />
)}
<span>{option.text}</span>
</div>
);
}
/**
* Determines whether render placeholder on
*/
private _onRenderPlaceholder = (props: IDropdownProps): JSX.Element => {
return (
<div className={styles.selectPlanContainer}>
<Icon styles={{ root: { marginRight: '8px', fontSize: 20 } }} iconName={'plannerLogo'} aria-hidden='true' />
<span>{props.placeholder}</span>
</div>
);
}
/**
* Determines whether change bucket on
*/
private _onChangeBucket = async (event: React.FormEvent<HTMLDivElement>, bucket: IDropdownOption) => {
// selected Bucket
try {
const updatedTask:ITask = await this.props.spservice.updateTaskProperty(this.state.task.id, 'bucketId', bucket.key, this.state.task["@odata.etag"]);
this.setState({hasError:false, errorMessage:'', selectedBucket: bucket.key ,task: updatedTask });
} catch (error) {
this.setState({hasError: true, errorMessage: error.message});
}
}
/**
* Determines whether change progress on
*/
private _onChangeProgress = async (event: React.FormEvent<HTMLDivElement>, progress: IDropdownOption) => {
// selected Bucket
try {
const updatedTask = await this.props.spservice.updateTaskProperty(this.state.task.id, 'percentComplete', progress.key, this.state.task["@odata.etag"]);
this.setState({hasError:false, errorMessage:'', progressSelectedKey: progress.key , task:updatedTask });
} catch (error) {
this.setState({hasError: true, errorMessage: error.message});
}
}
/**
* Validate task name of new task
*/
private _validateTaskName = async (value: string): Promise<string> => {
if (value.trim().length > 0) {
return '';
} else {
return 'Plase enter task name';
}
}
/**
* Determines whether change task name on
*/
private _onChangeTaskName = (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue: string) => {
event.preventDefault();
this.setState({ task: { ...this.state.task, title: newValue}, taskChanged: true});
}
/**
* Determines whether blur task name on
*/
private _onBlurTaskName = async (event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>): Promise<void> => {
event.preventDefault();
try {
if (this.state.taskChanged){
const updatedTask = await this.props.spservice.updateTaskProperty(this.state.task.id,'title', this.state.task.title, this.state.task["@odata.etag"]);
this.setState({task:updatedTask , taskChanged: false,hasError:false, errorMessage:''});
}
} catch (error) {
this.setState({hasError: true, errorMessage: error.message});
}
}
/**
* Determines whether change description on
*/
private _onChangeDescription = async (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string) => {
event.preventDefault();
this.setState({ taskDetails: { ...this.state.taskDetails, description: newValue }, taskChanged:true, hasError:false, errorMessage:'' ,});
}
/**
* Determines whether blur description on
*/
private _onBlurDescription = async (event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
event.preventDefault();
try {
if (this.state.taskChanged){
const updatedTaskDetails = await this.props.spservice.updateTaskDetailsProperty(this.state.task.id,'description', this.state.taskDetails.description, this.state.taskDetails["@odata.etag"]);
this.setState({taskDetails:updatedTaskDetails ,taskChanged: false, hasError:false, errorMessage:''});
}
} catch (error) {
this.setState({hasError: true, errorMessage: error.message});
}
}
/**
* Determines whether select due date on
*/
private _onSelectDueDate = async (date: Date) => {
try {
const updatedTask = await this.props.spservice.updateTaskProperty(this.state.task.id,'dueDateTime', moment(date).toISOString(), this.state.task["@odata.etag"]);
this.setState({ hasError:false, errorMessage:'', task: updatedTask });
} catch (error) {
this.setState({hasError: true, errorMessage: error.message});
}
}
/**
* Determines whether select start date on
*/
private _onSelectStartDate = async (date: Date) => {
try {
const updatedTask = await this.props.spservice.updateTaskProperty(this.state.task.id,'startDateTime', moment(date).toISOString(), this.state.task["@odata.etag"]);
this.setState({ hasError:false, errorMessage:'',task: updatedTask });
} catch (error) {
this.setState({hasError: true, errorMessage: error.message});
}
};
private _onRenderTextField = (props: ITextFieldProps) => {
return <Checkbox styles={{ checkbox: { height: 17, width: 17 } }}></Checkbox>;
}
private _onRenderTextFieldSufix = (props: ITextFieldProps) => {
return <Icon iconName='delete' />;
}
/**
* Determines whether dismiss assigns on
*/
private _onDismissAssigns = async (assigns: IMember[]): Promise<void> => {
try {
this._assigns = assigns;
const personas = await this._renderAssignments(assigns);
let assignments: {[key:string]:IPlannerAssignment} = {} ;
for (const user of assigns){
assignments[user.id] = {"@odata.type": "#microsoft.graph.plannerAssignment", "orderHint": " !"};
}
const updatedTask = await this.props.spservice.updateTaskProperty(this.state.task.id,'assignments', assignments, this.state.task["@odata.etag"]);
this.setState({hasError:false, errorMessage:'',displayAssigns: !this.state.displayAssigns, renderAssigns: personas, task:updatedTask });
} catch (error) {
this.setState({hasError: true, errorMessage: error.message});
}
};
/**
* Determines whether callout on
*/
private _onAssigns = (ev?: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement | HTMLDivElement>) => {
this.setState({ displayAssigns: !this.state.displayAssigns, calloutTarget: ev.currentTarget });
}
/**
* Determines whether check list changed on
*/
private _onCheckListChanged = (checkListItems: ICheckListItem[]) => {
console.log(checkListItems);
this._checkListItems = checkListItems;
};
private _onClickDeleteTask = async (ev?: React.MouseEvent<HTMLElement, MouseEvent> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => {
try {
await this.props.spservice.deleteTask(this.state.task.id, this.state.task["@odata.etag"]);
this.setState({ hideDialog: true });
this.props.onDismiss(refreshOptions.list); // Refresh card = 0 Refresh List os Cards = 1
} catch (error) {
this.setState({hasError: true, errorMessage: error.message});
}
};
/**
* Renders new task
* @returns render
*/
public render(): React.ReactElement<IEditTaskProps> {
const hideDialog: boolean = this.state.hideDialog;
return (
<div>
<Dialog
hidden={hideDialog}
onDismiss={this._closeDialog}
minWidth={650}
maxWidth={650}
dialogContentProps={{
topButtonsProps:[{
iconProps: {
iconName: 'More'
},
style:{backgroundColor: '#1fe0' },
menuIconProps: { iconName: '' },
menuProps:{
items: [
{
key: '1',
text: strings.RemoveLabel,
iconProps: { iconName: 'Delete' },
onClick: this._onClickDeleteTask.bind(this)
}
]
},
checked: true
}],
type: DialogType.normal,
title: !this.state.isLoading ? <EditCategories task={this.props.task} spservice={this.props.spservice} plannerPlan={this.props.plannerPlan}/> : ''
}}
modalProps={{
isBlocking: false,
styles: jsStyles.modalStyles
// topOffsetFixed: true
}}>
{this.state.isLoading ? (
<Spinner type={SpinnerType.normal} label={strings.LoadingTaskLabel} />
) : (
<>
<Stack horizontal horizontalAlign='start' gap='5' style={{marginBottom:2}} disableShrink>
</Stack>
<Stack gap='10'>
{this.state.hasError ? (
<MessageBar messageBarType={MessageBarType.error}>{this.state.errorMessage}</MessageBar>
) : (
<>
<TextField
title={strings.TaskNameLabel}
styles={jsStyles.textFieldStylesTaskName}
borderless={true}
placeholder={strings.EnterTaskNameLabel}
required
onGetErrorMessage={this._validateTaskName}
onChange={this._onChangeTaskName}
onBlur={this._onBlurTaskName}
validateOnLoad={false}
value={this.state.task.title}
/>
<Stack horizontal horizontalAlign='start' styles={jsStyles.stackStyles}>
<ActionButton
iconProps={addFriendIcon}
checked={true}
styles={jsStyles.addMemberButton}
text={this.state.renderAssigns && this.state.renderAssigns.length > 0 ? '' : strings.AssignLabel}
title={strings.AssignTaskLabel}
onClick={this._onAssigns}
/>
{
<div onClick={this._onAssigns} style={{ cursor: 'pointer', width: '100%' }}>
<Facepile
personaSize={PersonaSize.size32}
personas={this.state.renderAssigns}
maxDisplayablePersonas={10}
overflowButtonType={OverflowButtonType.descriptive}
overflowButtonProps={{
ariaLabel: 'More users',
styles: { root: { cursor: 'default' } }
}}
showAddButton={false}
/>
</div>
}
</Stack>
<Stack
tokens={jsStyles.stackTokens}
horizontal
wrap
disableShrink
horizontalAlign='space-between'
gap={25}
style={{ marginTop: 30 }}>
<div style={{ width: 172 }}>
<Dropdown
placeholder={strings.SelectBucketPlaceHolder}
styles={jsStyles.dropDownBucketStyles}
dropdownWidth={172}
title={strings.SelectBucketLabel}
label={strings.SelectBucketLabel}
ariaLabel={strings.SelectBucketPlaceHolder}
options={this.state.buckets}
selectedKey={this.state.selectedBucket}
onChange={this._onChangeBucket}
/>
</div>
<div style={{ width: 172 }}>
<Dropdown
placeholder={strings.ProgressPlaceHolder}
title={strings.ProgressLabel}
label={strings.ProgressLabel}
styles={jsStyles.dropDownProgressStyles}
dropdownWidth={172}
ariaLabel={strings.ProgressLabel}
onRenderPlaceholder={this._onRenderPlaceholder}
onRenderTitle={this._onRenderTitleProgress}
onRenderOption={this._onRenderOption}
options={[
{
key: 0,
text: strings.notStarted,
data: { icon: 'StatusCircleRing' }
},
{
key: 50,
text: strings.started,
data: { icon: 'CircleHalfFull' }
},
{
key: 100,
text: strings.completed,
data: { icon: 'CompletedSolid' }
}
]}
selectedKey={this.state.progressSelectedKey}
onChange={this._onChangeProgress}
//onChange={this._onChangePlan}
/>
</div>
<div style={{ width: 172 }}>
<DatePicker
textField={jsStyles.textFielStartDateDatePickerStyles}
title={strings.StartDateLabel}
label={strings.StartDateLabel}
firstDayOfWeek={DayOfWeek.Sunday}
strings={DayPickerStrings}
showWeekNumbers={true}
firstWeekOfYear={1}
showGoToToday={true}
showMonthPickerAsOverlay={true}
borderless={true}
placeholder={strings.StartDateLabel}
ariaLabel={strings.StartDateLabel}
onSelectDate={this._onSelectStartDate}
value={
this.state.task.startDateTime ? moment(this.state.task.startDateTime).toDate() : undefined
}
/>
</div>
<div style={{ width: 172 }}>
<DatePicker
title={strings.DueDateLabel}
style={{ margin: 0 }}
label={strings.DueDateLabel}
firstDayOfWeek={DayOfWeek.Sunday}
textField={jsStyles.textFielDueDateDatePickerStyles}
// style={{ width: 172, marginTop: 0, marginLeft: 0, marginRight: 'auto' }}
strings={DayPickerStrings}
showWeekNumbers={true}
firstWeekOfYear={1}
showGoToToday={true}
showMonthPickerAsOverlay={true}
borderless={true}
placeholder={strings.DueDateLabel}
ariaLabel={strings.DueDateLabel}
onSelectDate={this._onSelectDueDate}
value={this.state.task.dueDateTime ? moment(this.state.task.dueDateTime).toDate() : undefined}
/>
</div>
</Stack>
<TextField
borderless={true}
label={strings.DescriptionLabel}
onChange={this._onChangeDescription}
onBlur={this._onBlurDescription}
multiline
value={this.state.taskDetails ? this.state.taskDetails.description : ''}
styles={jsStyles.textFieldDescriptionStyles}>
</TextField>
<Label>{strings.CheckListLabel}</Label>
<CheckList taskDetails={this.state.taskDetails} spservice={this.props.spservice} onCheckListChanged={this._onCheckListChanged}/>
<Label style={{marginTop:20}}>{strings.AttachmentsLabel}</Label>
<Attachments groupId={this.props.plannerPlan.owner} spservice={this.props.spservice} taskDetails={this.state.taskDetails}/>
</>
)}
</Stack>
</>
)}
</Dialog>
{this.state.displayAssigns && (
<>
<Assigns
target={this.state.calloutTarget}
onDismiss={this._onDismissAssigns}
task={this.props.task}
plannerPlan={this.props.plannerPlan}
spservice={this.props.spservice}
assigns={this._assigns}
AssignMode={1}
/>
</>
)}
</div>
);
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/reviewsMappers";
import * as Parameters from "../models/parameters";
import { ContentModeratorClientContext } from "../contentModeratorClientContext";
/** Class representing a Reviews. */
export class Reviews {
private readonly client: ContentModeratorClientContext;
/**
* Create a Reviews.
* @param {ContentModeratorClientContext} client Reference to the service client.
*/
constructor(client: ContentModeratorClientContext) {
this.client = client;
}
/**
* Returns review details for the review Id passed.
* @param teamName Your Team Name.
* @param reviewId Id of the review.
* @param [options] The optional parameters
* @returns Promise<Models.ReviewsGetReviewResponse>
*/
getReview(teamName: string, reviewId: string, options?: msRest.RequestOptionsBase): Promise<Models.ReviewsGetReviewResponse>;
/**
* @param teamName Your Team Name.
* @param reviewId Id of the review.
* @param callback The callback
*/
getReview(teamName: string, reviewId: string, callback: msRest.ServiceCallback<Models.Review>): void;
/**
* @param teamName Your Team Name.
* @param reviewId Id of the review.
* @param options The optional parameters
* @param callback The callback
*/
getReview(teamName: string, reviewId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Review>): void;
getReview(teamName: string, reviewId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Review>, callback?: msRest.ServiceCallback<Models.Review>): Promise<Models.ReviewsGetReviewResponse> {
return this.client.sendOperationRequest(
{
teamName,
reviewId,
options
},
getReviewOperationSpec,
callback) as Promise<Models.ReviewsGetReviewResponse>;
}
/**
* Get the Job Details for a Job Id.
* @param teamName Your Team Name.
* @param jobId Id of the job.
* @param [options] The optional parameters
* @returns Promise<Models.ReviewsGetJobDetailsResponse>
*/
getJobDetails(teamName: string, jobId: string, options?: msRest.RequestOptionsBase): Promise<Models.ReviewsGetJobDetailsResponse>;
/**
* @param teamName Your Team Name.
* @param jobId Id of the job.
* @param callback The callback
*/
getJobDetails(teamName: string, jobId: string, callback: msRest.ServiceCallback<Models.Job>): void;
/**
* @param teamName Your Team Name.
* @param jobId Id of the job.
* @param options The optional parameters
* @param callback The callback
*/
getJobDetails(teamName: string, jobId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Job>): void;
getJobDetails(teamName: string, jobId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Job>, callback?: msRest.ServiceCallback<Models.Job>): Promise<Models.ReviewsGetJobDetailsResponse> {
return this.client.sendOperationRequest(
{
teamName,
jobId,
options
},
getJobDetailsOperationSpec,
callback) as Promise<Models.ReviewsGetJobDetailsResponse>;
}
/**
* The reviews created would show up for Reviewers on your team. As Reviewers complete reviewing,
* results of the Review would be POSTED (i.e. HTTP POST) on the specified CallBackEndpoint.
*
* <h3>CallBack Schemas </h3>
* <h4>Review Completion CallBack Sample</h4>
* <p>
* {<br/>
* "ReviewId": "<Review Id>",<br/>
* "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/>
* "ModifiedBy": "<Name of the Reviewer>",<br/>
* "CallBackType": "Review",<br/>
* "ContentId": "<The ContentId that was specified input>",<br/>
* "Metadata": {<br/>
* "adultscore": "0.xxx",<br/>
* "a": "False",<br/>
* "racyscore": "0.xxx",<br/>
* "r": "True"<br/>
* },<br/>
* "ReviewerResultTags": {<br/>
* "a": "False",<br/>
* "r": "True"<br/>
* }<br/>
* }<br/>
*
* </p>.
* @param urlContentType The content type.
* @param teamName Your team name.
* @param createReviewBody Body for create reviews API
* @param [options] The optional parameters
* @returns Promise<Models.ReviewsCreateReviewsResponse>
*/
createReviews(urlContentType: string, teamName: string, createReviewBody: Models.CreateReviewBodyItem[], options?: Models.ReviewsCreateReviewsOptionalParams): Promise<Models.ReviewsCreateReviewsResponse>;
/**
* @param urlContentType The content type.
* @param teamName Your team name.
* @param createReviewBody Body for create reviews API
* @param callback The callback
*/
createReviews(urlContentType: string, teamName: string, createReviewBody: Models.CreateReviewBodyItem[], callback: msRest.ServiceCallback<string[]>): void;
/**
* @param urlContentType The content type.
* @param teamName Your team name.
* @param createReviewBody Body for create reviews API
* @param options The optional parameters
* @param callback The callback
*/
createReviews(urlContentType: string, teamName: string, createReviewBody: Models.CreateReviewBodyItem[], options: Models.ReviewsCreateReviewsOptionalParams, callback: msRest.ServiceCallback<string[]>): void;
createReviews(urlContentType: string, teamName: string, createReviewBody: Models.CreateReviewBodyItem[], options?: Models.ReviewsCreateReviewsOptionalParams | msRest.ServiceCallback<string[]>, callback?: msRest.ServiceCallback<string[]>): Promise<Models.ReviewsCreateReviewsResponse> {
return this.client.sendOperationRequest(
{
urlContentType,
teamName,
createReviewBody,
options
},
createReviewsOperationSpec,
callback) as Promise<Models.ReviewsCreateReviewsResponse>;
}
/**
* A job Id will be returned for the content posted on this endpoint.
*
* Once the content is evaluated against the Workflow provided the review will be created or
* ignored based on the workflow expression.
*
* <h3>CallBack Schemas </h3>
*
* <p>
* <h4>Job Completion CallBack Sample</h4><br/>
*
* {<br/>
* "JobId": "<Job Id>,<br/>
* "ReviewId": "<Review Id, if the Job resulted in a Review to be created>",<br/>
* "WorkFlowId": "default",<br/>
* "Status": "<This will be one of Complete, InProgress, Error>",<br/>
* "ContentType": "Image",<br/>
* "ContentId": "<This is the ContentId that was specified on input>",<br/>
* "CallBackType": "Job",<br/>
* "Metadata": {<br/>
* "adultscore": "0.xxx",<br/>
* "a": "False",<br/>
* "racyscore": "0.xxx",<br/>
* "r": "True"<br/>
* }<br/>
* }<br/>
*
* </p>
* <p>
* <h4>Review Completion CallBack Sample</h4><br/>
*
* {
* "ReviewId": "<Review Id>",<br/>
* "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/>
* "ModifiedBy": "<Name of the Reviewer>",<br/>
* "CallBackType": "Review",<br/>
* "ContentId": "<The ContentId that was specified input>",<br/>
* "Metadata": {<br/>
* "adultscore": "0.xxx",
* "a": "False",<br/>
* "racyscore": "0.xxx",<br/>
* "r": "True"<br/>
* },<br/>
* "ReviewerResultTags": {<br/>
* "a": "False",<br/>
* "r": "True"<br/>
* }<br/>
* }<br/>
*
* </p>.
* @param teamName Your team name.
* @param contentType Image, Text or Video. Possible values include: 'Image', 'Text', 'Video'
* @param contentId Id/Name to identify the content submitted.
* @param workflowName Workflow Name that you want to invoke.
* @param jobContentType The content type. Possible values include: 'application/json',
* 'image/jpeg'
* @param content Content to evaluate.
* @param [options] The optional parameters
* @returns Promise<Models.ReviewsCreateJobResponse>
*/
createJob(teamName: string, contentType: Models.ContentType, contentId: string, workflowName: string, jobContentType: Models.JobContentType, content: Models.Content, options?: Models.ReviewsCreateJobOptionalParams): Promise<Models.ReviewsCreateJobResponse>;
/**
* @param teamName Your team name.
* @param contentType Image, Text or Video. Possible values include: 'Image', 'Text', 'Video'
* @param contentId Id/Name to identify the content submitted.
* @param workflowName Workflow Name that you want to invoke.
* @param jobContentType The content type. Possible values include: 'application/json',
* 'image/jpeg'
* @param content Content to evaluate.
* @param callback The callback
*/
createJob(teamName: string, contentType: Models.ContentType, contentId: string, workflowName: string, jobContentType: Models.JobContentType, content: Models.Content, callback: msRest.ServiceCallback<Models.JobId>): void;
/**
* @param teamName Your team name.
* @param contentType Image, Text or Video. Possible values include: 'Image', 'Text', 'Video'
* @param contentId Id/Name to identify the content submitted.
* @param workflowName Workflow Name that you want to invoke.
* @param jobContentType The content type. Possible values include: 'application/json',
* 'image/jpeg'
* @param content Content to evaluate.
* @param options The optional parameters
* @param callback The callback
*/
createJob(teamName: string, contentType: Models.ContentType, contentId: string, workflowName: string, jobContentType: Models.JobContentType, content: Models.Content, options: Models.ReviewsCreateJobOptionalParams, callback: msRest.ServiceCallback<Models.JobId>): void;
createJob(teamName: string, contentType: Models.ContentType, contentId: string, workflowName: string, jobContentType: Models.JobContentType, content: Models.Content, options?: Models.ReviewsCreateJobOptionalParams | msRest.ServiceCallback<Models.JobId>, callback?: msRest.ServiceCallback<Models.JobId>): Promise<Models.ReviewsCreateJobResponse> {
return this.client.sendOperationRequest(
{
teamName,
contentType,
contentId,
workflowName,
jobContentType,
content,
options
},
createJobOperationSpec,
callback) as Promise<Models.ReviewsCreateJobResponse>;
}
/**
* The reviews created would show up for Reviewers on your team. As Reviewers complete reviewing,
* results of the Review would be POSTED (i.e. HTTP POST) on the specified CallBackEndpoint.
*
* <h3>CallBack Schemas </h3>
* <h4>Review Completion CallBack Sample</h4>
* <p>
* {<br/>
* "ReviewId": "<Review Id>",<br/>
* "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/>
* "ModifiedBy": "<Name of the Reviewer>",<br/>
* "CallBackType": "Review",<br/>
* "ContentId": "<The ContentId that was specified input>",<br/>
* "Metadata": {<br/>
* "adultscore": "0.xxx",<br/>
* "a": "False",<br/>
* "racyscore": "0.xxx",<br/>
* "r": "True"<br/>
* },<br/>
* "ReviewerResultTags": {<br/>
* "a": "False",<br/>
* "r": "True"<br/>
* }<br/>
* }<br/>
*
* </p>.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
addVideoFrame(teamName: string, reviewId: string, options?: Models.ReviewsAddVideoFrameOptionalParams): Promise<msRest.RestResponse>;
/**
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param callback The callback
*/
addVideoFrame(teamName: string, reviewId: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param options The optional parameters
* @param callback The callback
*/
addVideoFrame(teamName: string, reviewId: string, options: Models.ReviewsAddVideoFrameOptionalParams, callback: msRest.ServiceCallback<void>): void;
addVideoFrame(teamName: string, reviewId: string, options?: Models.ReviewsAddVideoFrameOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
teamName,
reviewId,
options
},
addVideoFrameOperationSpec,
callback);
}
/**
* The reviews created would show up for Reviewers on your team. As Reviewers complete reviewing,
* results of the Review would be POSTED (i.e. HTTP POST) on the specified CallBackEndpoint.
*
* <h3>CallBack Schemas </h3>
* <h4>Review Completion CallBack Sample</h4>
* <p>
* {<br/>
* "ReviewId": "<Review Id>",<br/>
* "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/>
* "ModifiedBy": "<Name of the Reviewer>",<br/>
* "CallBackType": "Review",<br/>
* "ContentId": "<The ContentId that was specified input>",<br/>
* "Metadata": {<br/>
* "adultscore": "0.xxx",<br/>
* "a": "False",<br/>
* "racyscore": "0.xxx",<br/>
* "r": "True"<br/>
* },<br/>
* "ReviewerResultTags": {<br/>
* "a": "False",<br/>
* "r": "True"<br/>
* }<br/>
* }<br/>
*
* </p>.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param [options] The optional parameters
* @returns Promise<Models.ReviewsGetVideoFramesResponse>
*/
getVideoFrames(teamName: string, reviewId: string, options?: Models.ReviewsGetVideoFramesOptionalParams): Promise<Models.ReviewsGetVideoFramesResponse>;
/**
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param callback The callback
*/
getVideoFrames(teamName: string, reviewId: string, callback: msRest.ServiceCallback<Models.Frames>): void;
/**
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param options The optional parameters
* @param callback The callback
*/
getVideoFrames(teamName: string, reviewId: string, options: Models.ReviewsGetVideoFramesOptionalParams, callback: msRest.ServiceCallback<Models.Frames>): void;
getVideoFrames(teamName: string, reviewId: string, options?: Models.ReviewsGetVideoFramesOptionalParams | msRest.ServiceCallback<Models.Frames>, callback?: msRest.ServiceCallback<Models.Frames>): Promise<Models.ReviewsGetVideoFramesResponse> {
return this.client.sendOperationRequest(
{
teamName,
reviewId,
options
},
getVideoFramesOperationSpec,
callback) as Promise<Models.ReviewsGetVideoFramesResponse>;
}
/**
* Publish video review to make it available for review.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
publishVideoReview(teamName: string, reviewId: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param callback The callback
*/
publishVideoReview(teamName: string, reviewId: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param options The optional parameters
* @param callback The callback
*/
publishVideoReview(teamName: string, reviewId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
publishVideoReview(teamName: string, reviewId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
teamName,
reviewId,
options
},
publishVideoReviewOperationSpec,
callback);
}
/**
* This API adds a transcript screen text result file for a video review. Transcript screen text
* result file is a result of Screen Text API . In order to generate transcript screen text result
* file , a transcript file has to be screened for profanity using Screen Text API.
* @param contentType The content type.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param transcriptModerationBody Body for add video transcript moderation result API
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
addVideoTranscriptModerationResult(contentType: string, teamName: string, reviewId: string, transcriptModerationBody: Models.TranscriptModerationBodyItem[], options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param contentType The content type.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param transcriptModerationBody Body for add video transcript moderation result API
* @param callback The callback
*/
addVideoTranscriptModerationResult(contentType: string, teamName: string, reviewId: string, transcriptModerationBody: Models.TranscriptModerationBodyItem[], callback: msRest.ServiceCallback<void>): void;
/**
* @param contentType The content type.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param transcriptModerationBody Body for add video transcript moderation result API
* @param options The optional parameters
* @param callback The callback
*/
addVideoTranscriptModerationResult(contentType: string, teamName: string, reviewId: string, transcriptModerationBody: Models.TranscriptModerationBodyItem[], options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
addVideoTranscriptModerationResult(contentType: string, teamName: string, reviewId: string, transcriptModerationBody: Models.TranscriptModerationBodyItem[], options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
contentType,
teamName,
reviewId,
transcriptModerationBody,
options
},
addVideoTranscriptModerationResultOperationSpec,
callback);
}
/**
* This API adds a transcript file (text version of all the words spoken in a video) to a video
* review. The file should be a valid WebVTT format.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param vTTfile Transcript file of the video.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
addVideoTranscript(teamName: string, reviewId: string, vTTfile: msRest.HttpRequestBody, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param vTTfile Transcript file of the video.
* @param callback The callback
*/
addVideoTranscript(teamName: string, reviewId: string, vTTfile: msRest.HttpRequestBody, callback: msRest.ServiceCallback<void>): void;
/**
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param vTTfile Transcript file of the video.
* @param options The optional parameters
* @param callback The callback
*/
addVideoTranscript(teamName: string, reviewId: string, vTTfile: msRest.HttpRequestBody, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
addVideoTranscript(teamName: string, reviewId: string, vTTfile: msRest.HttpRequestBody, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
teamName,
reviewId,
vTTfile,
options
},
addVideoTranscriptOperationSpec,
callback);
}
/**
* The reviews created would show up for Reviewers on your team. As Reviewers complete reviewing,
* results of the Review would be POSTED (i.e. HTTP POST) on the specified CallBackEndpoint.
*
* <h3>CallBack Schemas </h3>
* <h4>Review Completion CallBack Sample</h4>
* <p>
* {<br/>
* "ReviewId": "<Review Id>",<br/>
* "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/>
* "ModifiedBy": "<Name of the Reviewer>",<br/>
* "CallBackType": "Review",<br/>
* "ContentId": "<The ContentId that was specified input>",<br/>
* "Metadata": {<br/>
* "adultscore": "0.xxx",<br/>
* "a": "False",<br/>
* "racyscore": "0.xxx",<br/>
* "r": "True"<br/>
* },<br/>
* "ReviewerResultTags": {<br/>
* "a": "False",<br/>
* "r": "True"<br/>
* }<br/>
* }<br/>
*
* </p>.
* @param contentType The content type.
* @param teamName Your team name.
* @param createVideoReviewsBody Body for create reviews API
* @param [options] The optional parameters
* @returns Promise<Models.ReviewsCreateVideoReviewsResponse>
*/
createVideoReviews(contentType: string, teamName: string, createVideoReviewsBody: Models.CreateVideoReviewsBodyItem[], options?: Models.ReviewsCreateVideoReviewsOptionalParams): Promise<Models.ReviewsCreateVideoReviewsResponse>;
/**
* @param contentType The content type.
* @param teamName Your team name.
* @param createVideoReviewsBody Body for create reviews API
* @param callback The callback
*/
createVideoReviews(contentType: string, teamName: string, createVideoReviewsBody: Models.CreateVideoReviewsBodyItem[], callback: msRest.ServiceCallback<string[]>): void;
/**
* @param contentType The content type.
* @param teamName Your team name.
* @param createVideoReviewsBody Body for create reviews API
* @param options The optional parameters
* @param callback The callback
*/
createVideoReviews(contentType: string, teamName: string, createVideoReviewsBody: Models.CreateVideoReviewsBodyItem[], options: Models.ReviewsCreateVideoReviewsOptionalParams, callback: msRest.ServiceCallback<string[]>): void;
createVideoReviews(contentType: string, teamName: string, createVideoReviewsBody: Models.CreateVideoReviewsBodyItem[], options?: Models.ReviewsCreateVideoReviewsOptionalParams | msRest.ServiceCallback<string[]>, callback?: msRest.ServiceCallback<string[]>): Promise<Models.ReviewsCreateVideoReviewsResponse> {
return this.client.sendOperationRequest(
{
contentType,
teamName,
createVideoReviewsBody,
options
},
createVideoReviewsOperationSpec,
callback) as Promise<Models.ReviewsCreateVideoReviewsResponse>;
}
/**
* Use this method to add frames for a video review.Timescale: This parameter is a factor which is
* used to convert the timestamp on a frame into milliseconds. Timescale is provided in the output
* of the Content Moderator video media processor on the Azure Media Services platform.Timescale in
* the Video Moderation output is Ticks/Second.
* @param contentType The content type.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param videoFrameBody Body for add video frames API
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
addVideoFrameUrl(contentType: string, teamName: string, reviewId: string, videoFrameBody: Models.VideoFrameBodyItem[], options?: Models.ReviewsAddVideoFrameUrlOptionalParams): Promise<msRest.RestResponse>;
/**
* @param contentType The content type.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param videoFrameBody Body for add video frames API
* @param callback The callback
*/
addVideoFrameUrl(contentType: string, teamName: string, reviewId: string, videoFrameBody: Models.VideoFrameBodyItem[], callback: msRest.ServiceCallback<void>): void;
/**
* @param contentType The content type.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param videoFrameBody Body for add video frames API
* @param options The optional parameters
* @param callback The callback
*/
addVideoFrameUrl(contentType: string, teamName: string, reviewId: string, videoFrameBody: Models.VideoFrameBodyItem[], options: Models.ReviewsAddVideoFrameUrlOptionalParams, callback: msRest.ServiceCallback<void>): void;
addVideoFrameUrl(contentType: string, teamName: string, reviewId: string, videoFrameBody: Models.VideoFrameBodyItem[], options?: Models.ReviewsAddVideoFrameUrlOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
contentType,
teamName,
reviewId,
videoFrameBody,
options
},
addVideoFrameUrlOperationSpec,
callback);
}
/**
* Use this method to add frames for a video review.Timescale: This parameter is a factor which is
* used to convert the timestamp on a frame into milliseconds. Timescale is provided in the output
* of the Content Moderator video media processor on the Azure Media Services platform.Timescale in
* the Video Moderation output is Ticks/Second.
* @param contentType The content type.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param frameImageZip Zip file containing frame images.
* @param frameMetadata Metadata of the frame.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
addVideoFrameStream(contentType: string, teamName: string, reviewId: string, frameImageZip: msRest.HttpRequestBody, frameMetadata: string, options?: Models.ReviewsAddVideoFrameStreamOptionalParams): Promise<msRest.RestResponse>;
/**
* @param contentType The content type.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param frameImageZip Zip file containing frame images.
* @param frameMetadata Metadata of the frame.
* @param callback The callback
*/
addVideoFrameStream(contentType: string, teamName: string, reviewId: string, frameImageZip: msRest.HttpRequestBody, frameMetadata: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param contentType The content type.
* @param teamName Your team name.
* @param reviewId Id of the review.
* @param frameImageZip Zip file containing frame images.
* @param frameMetadata Metadata of the frame.
* @param options The optional parameters
* @param callback The callback
*/
addVideoFrameStream(contentType: string, teamName: string, reviewId: string, frameImageZip: msRest.HttpRequestBody, frameMetadata: string, options: Models.ReviewsAddVideoFrameStreamOptionalParams, callback: msRest.ServiceCallback<void>): void;
addVideoFrameStream(contentType: string, teamName: string, reviewId: string, frameImageZip: msRest.HttpRequestBody, frameMetadata: string, options?: Models.ReviewsAddVideoFrameStreamOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
contentType,
teamName,
reviewId,
frameImageZip,
frameMetadata,
options
},
addVideoFrameStreamOperationSpec,
callback);
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const getReviewOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "contentmoderator/review/v1.0/teams/{teamName}/reviews/{reviewId}",
urlParameters: [
Parameters.endpoint,
Parameters.teamName,
Parameters.reviewId
],
responses: {
200: {
bodyMapper: Mappers.Review
},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const getJobDetailsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "contentmoderator/review/v1.0/teams/{teamName}/jobs/{JobId}",
urlParameters: [
Parameters.endpoint,
Parameters.teamName,
Parameters.jobId
],
responses: {
200: {
bodyMapper: Mappers.Job
},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const createReviewsOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "contentmoderator/review/v1.0/teams/{teamName}/reviews",
urlParameters: [
Parameters.endpoint,
Parameters.teamName
],
queryParameters: [
Parameters.subTeam
],
headerParameters: [
Parameters.urlContentType
],
requestBody: {
parameterPath: "createReviewBody",
mapper: {
required: true,
serializedName: "createReviewBody",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "CreateReviewBodyItem"
}
}
}
}
},
responses: {
200: {
bodyMapper: {
serializedName: "parsedResponse",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const createJobOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "contentmoderator/review/v1.0/teams/{teamName}/jobs",
urlParameters: [
Parameters.endpoint,
Parameters.teamName
],
queryParameters: [
Parameters.contentType1,
Parameters.contentId,
Parameters.workflowName,
Parameters.callBackEndpoint
],
headerParameters: [
Parameters.jobContentType
],
requestBody: {
parameterPath: "content",
mapper: {
...Mappers.Content,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.JobId
},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const addVideoFrameOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "contentmoderator/review/v1.0/teams/{teamName}/reviews/{reviewId}/frames",
urlParameters: [
Parameters.endpoint,
Parameters.teamName,
Parameters.reviewId
],
queryParameters: [
Parameters.timescale
],
responses: {
200: {},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const getVideoFramesOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "contentmoderator/review/v1.0/teams/{teamName}/reviews/{reviewId}/frames",
urlParameters: [
Parameters.endpoint,
Parameters.teamName,
Parameters.reviewId
],
queryParameters: [
Parameters.startSeed,
Parameters.noOfRecords,
Parameters.filter
],
responses: {
200: {
bodyMapper: Mappers.Frames
},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const publishVideoReviewOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "contentmoderator/review/v1.0/teams/{teamName}/reviews/{reviewId}/publish",
urlParameters: [
Parameters.endpoint,
Parameters.teamName,
Parameters.reviewId
],
responses: {
204: {},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const addVideoTranscriptModerationResultOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "contentmoderator/review/v1.0/teams/{teamName}/reviews/{reviewId}/transcriptmoderationresult",
urlParameters: [
Parameters.endpoint,
Parameters.teamName,
Parameters.reviewId
],
headerParameters: [
Parameters.contentType0
],
requestBody: {
parameterPath: "transcriptModerationBody",
mapper: {
required: true,
serializedName: "transcriptModerationBody",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "TranscriptModerationBodyItem"
}
}
}
}
},
responses: {
204: {},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const addVideoTranscriptOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "contentmoderator/review/v1.0/teams/{teamName}/reviews/{reviewId}/transcript",
urlParameters: [
Parameters.endpoint,
Parameters.teamName,
Parameters.reviewId
],
headerParameters: [
Parameters.contentType2
],
requestBody: {
parameterPath: "vTTfile",
mapper: {
required: true,
serializedName: "VTT file",
type: {
name: "Stream"
}
}
},
contentType: "text/plain",
responses: {
204: {},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const createVideoReviewsOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "contentmoderator/review/v1.0/teams/{teamName}/reviews",
urlParameters: [
Parameters.endpoint,
Parameters.teamName
],
queryParameters: [
Parameters.subTeam
],
headerParameters: [
Parameters.contentType0
],
requestBody: {
parameterPath: "createVideoReviewsBody",
mapper: {
required: true,
serializedName: "CreateVideoReviewsBody",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "CreateVideoReviewsBodyItem"
}
}
}
}
},
responses: {
200: {
bodyMapper: {
serializedName: "parsedResponse",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const addVideoFrameUrlOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "contentmoderator/review/v1.0/teams/{teamName}/reviews/{reviewId}/frames",
urlParameters: [
Parameters.endpoint,
Parameters.teamName,
Parameters.reviewId
],
queryParameters: [
Parameters.timescale
],
headerParameters: [
Parameters.contentType0
],
requestBody: {
parameterPath: "videoFrameBody",
mapper: {
required: true,
serializedName: "videoFrameBody",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "VideoFrameBodyItem"
}
}
}
}
},
responses: {
204: {},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const addVideoFrameStreamOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "contentmoderator/review/v1.0/teams/{teamName}/reviews/{reviewId}/frames",
urlParameters: [
Parameters.endpoint,
Parameters.teamName,
Parameters.reviewId
],
queryParameters: [
Parameters.timescale
],
headerParameters: [
Parameters.contentType0
],
formDataParameters: [
Parameters.frameImageZip,
Parameters.frameMetadata
],
contentType: "multipart/form-data",
responses: {
204: {},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
}; | the_stack |
import assert from "assert";
import range from "lodash-es/range";
import { PLAYER } from "../../../common";
import testHelpers from "../../../test/helpers";
import { player } from "..";
import { makeBrother, makeSon } from "./addRelatives";
import { idb } from "../../db";
import type { Relative } from "../../../common/types";
const season = 2017;
const genFathers = () => {
return range(season - 40, season - 20).map(season2 =>
player.generate(PLAYER.RETIRED, 50, season2, true, 15.5),
);
};
const genBrothers = () => {
return range(season - 5, season + 1).map(season2 =>
player.generate(0, 50, season2, true, 15.5),
);
};
const getPlayer = async (pid: number) => {
const p = await idb.cache.players.get(pid);
if (p === undefined) {
throw new Error("Invalid pid");
}
return p;
};
describe("worker/core/player/addRelatives", () => {
beforeAll(() => {
testHelpers.resetG();
idb.league = testHelpers.mockIDBLeague();
});
afterAll(() => {
// @ts-expect-error
idb.league = undefined;
});
describe("makeBrother", () => {
test("make player the brother of another player", async () => {
await testHelpers.resetCache({
players: [
player.generate(PLAYER.UNDRAFTED, 20, season, true, 15.5),
...genBrothers(),
],
});
const p = await getPlayer(0);
p.born.loc = "Fake Country";
await makeBrother(p);
const brothers = await idb.cache.players.indexGetAll("playersByTid", 0);
const brother = brothers.find(b => b.relatives.length > 0);
if (!brother) {
throw new Error("No brother found");
}
assert.strictEqual(p.relatives.length, 1);
assert.strictEqual(p.relatives[0].type, "brother");
assert.strictEqual(p.relatives[0].pid, brother.pid);
assert.strictEqual(brother.relatives.length, 1);
assert.strictEqual(brother.relatives[0].type, "brother");
assert.strictEqual(brother.relatives[0].pid, p.pid);
assert.strictEqual(p.lastName, brother.lastName);
assert.strictEqual(p.born.loc, brother.born.loc);
});
test("skip player if no possible brother exists", async () => {
await testHelpers.resetCache({
players: [player.generate(PLAYER.UNDRAFTED, 20, season, true, 15.5)],
});
const p = await getPlayer(0);
await makeBrother(p);
assert.strictEqual(p.relatives.length, 0);
});
test("handle case where target has a father", async () => {
const initialBrothers = genBrothers();
for (const p of initialBrothers) {
p.relatives.push({
type: "father",
pid: 1,
name: "Foo Bar",
});
}
await testHelpers.resetCache({
players: [
player.generate(PLAYER.UNDRAFTED, 20, season, true, 15.5),
player.generate(PLAYER.RETIRED, 50, season - 30, true, 15.5), // Father
...initialBrothers,
],
});
const p = await getPlayer(0);
await makeBrother(p);
const brothers = await idb.cache.players.indexGetAll("playersByTid", 0);
const brother = brothers.find(b => b.relatives.length > 1);
if (!brother) {
throw new Error("No brother found");
}
assert.strictEqual(p.relatives.length, 2);
assert.strictEqual(p.relatives[0].type, "father");
assert.strictEqual(p.relatives[0].pid, 1);
assert.strictEqual(p.relatives[1].type, "brother");
assert.strictEqual(p.relatives[1].pid, brother.pid);
assert.strictEqual(brother.relatives.length, 2);
assert.strictEqual(brother.relatives[0].type, "father");
assert.strictEqual(brother.relatives[0].pid, 1);
assert.strictEqual(brother.relatives[1].type, "brother");
assert.strictEqual(brother.relatives[1].pid, p.pid);
});
test("handle case where source has a father", async () => {
const initialPlayer = player.generate(
PLAYER.UNDRAFTED,
20,
season,
true,
15.5,
);
initialPlayer.firstName = "Foo";
initialPlayer.lastName = "HasFather Jr.";
initialPlayer.relatives.push({
type: "father",
pid: 1,
name: "Foo HasFather",
});
await testHelpers.resetCache({
players: [
initialPlayer,
player.generate(PLAYER.RETIRED, 50, season - 30, true, 15.5), // Father
...genBrothers(),
],
});
const father = await idb.cache.players.get(1);
if (!father) {
throw new Error("Missing father");
}
father.firstName = "Foo";
father.lastName = "HasFather";
const p = await getPlayer(0);
await makeBrother(p);
const brothers = await idb.cache.players.indexGetAll("playersByTid", 0);
const brother = brothers.find(b => b.relatives.length > 1);
if (!brother) {
throw new Error("No brother found");
}
assert.strictEqual(p.relatives.length, 2);
assert.strictEqual(p.relatives[0].type, "father");
assert.strictEqual(p.relatives[0].pid, 1);
assert.strictEqual(p.relatives[1].type, "brother");
assert.strictEqual(p.relatives[1].pid, brother.pid);
assert.strictEqual(brother.relatives.length, 2);
assert.strictEqual(brother.relatives[0].type, "father");
assert.strictEqual(brother.relatives[0].pid, 1);
assert.strictEqual(brother.relatives[1].type, "brother");
assert.strictEqual(brother.relatives[1].pid, p.pid);
assert.strictEqual(p.lastName, "HasFather Jr.");
assert.strictEqual(brother.lastName, "HasFather");
});
test("handle case where both have fathers", async () => {
const players = [
player.generate(PLAYER.UNDRAFTED, 20, season, true, 15.5),
...genBrothers(),
];
for (const p of players) {
p.relatives.push({
type: "father",
pid: 666,
name: "Foo Bar",
});
}
await testHelpers.resetCache({
players,
});
const p = await getPlayer(0);
await makeBrother(p);
const brothers = await idb.cache.players.indexGetAll("playersByTid", 0);
const brother = brothers.find(b => b.relatives.length > 1);
assert.strictEqual(brother, undefined);
});
test("handle case where target has a brother", async () => {
const initialP = player.generate(
PLAYER.UNDRAFTED,
20,
season,
true,
15.5,
);
const initialBrothers = genBrothers();
for (const p of initialBrothers) {
p.relatives.push({
type: "brother",
pid: 1,
name: "Foo Bar",
});
}
await testHelpers.resetCache({
players: [
initialP,
player.generate(PLAYER.RETIRED, 25, season - 6, true, 15.5), // Extra brother - 6 years ago means never picked by makeBrother
...initialBrothers,
],
});
const p = await getPlayer(0);
await makeBrother(p);
const brothers = await idb.cache.players.indexGetAll("playersByTid", 0);
const brother = brothers.find(b => b.relatives.length > 1);
if (!brother) {
throw new Error("No brother found");
}
assert.strictEqual(p.relatives.length, 2);
assert.strictEqual(p.relatives[0].type, "brother");
assert.strictEqual(p.relatives[0].pid, 1);
assert.strictEqual(p.relatives[1].type, "brother");
assert.strictEqual(p.relatives[1].pid, brother.pid);
assert.strictEqual(brother.relatives.length, 2);
assert.strictEqual(brother.relatives[0].type, "brother");
assert.strictEqual(brother.relatives[0].pid, 1);
assert.strictEqual(brother.relatives[1].type, "brother");
assert.strictEqual(brother.relatives[1].pid, p.pid);
});
test("handle case where source has a brother", async () => {
const initialPlayer = player.generate(
PLAYER.UNDRAFTED,
20,
season,
true,
15.5,
);
initialPlayer.relatives.push({
type: "brother",
pid: 1,
name: "Foo Bar",
});
await testHelpers.resetCache({
players: [
initialPlayer,
player.generate(PLAYER.RETIRED, 25, season - 5, true, 15.5), // Extra brother
...genBrothers(),
],
});
const p = await getPlayer(0);
await makeBrother(p);
const brothers = await idb.cache.players.indexGetAll("playersByTid", 0);
const brother = brothers.find(b => b.relatives.length > 1);
assert.strictEqual(brother, undefined);
assert.strictEqual(p.relatives.length, 1);
});
});
describe("makeSon", () => {
test("make player the son of another player", async () => {
await testHelpers.resetCache({
players: [
// Son
player.generate(PLAYER.UNDRAFTED, 20, season, true, 15.5), // Fathers
...genFathers(),
],
});
const son = await getPlayer(0);
son.born.loc = "Fake Country";
await makeSon(son);
const fathers = await idb.cache.players.indexGetAll(
"playersByTid",
PLAYER.RETIRED,
);
const father = fathers.find(p => p.relatives.length > 0);
if (!father) {
throw new Error("No father found");
}
assert.strictEqual(son.relatives.length, 1);
assert.strictEqual(son.relatives[0].type, "father");
assert.strictEqual(son.relatives[0].pid, father.pid);
assert.strictEqual(father.relatives.length, 1);
assert.strictEqual(father.relatives[0].type, "son");
assert.strictEqual(father.relatives[0].pid, son.pid);
assert.strictEqual(son.born.loc, father.born.loc);
});
test("skip player if no possible father exists", async () => {
await testHelpers.resetCache({
players: [player.generate(PLAYER.UNDRAFTED, 20, season, true, 15.5)],
});
const son = await getPlayer(0);
await makeSon(son);
assert.strictEqual(son.relatives.length, 0);
});
test("skip player if he already has a father", async () => {
await testHelpers.resetCache({
players: [
// Son
player.generate(PLAYER.UNDRAFTED, 20, season, true, 15.5), // Fathers
...genFathers(),
],
});
const relFather: Relative = {
type: "father",
pid: 1,
name: "Foo Bar",
};
const son = await getPlayer(0);
son.relatives = [relFather];
await makeSon(son);
const fathers = await idb.cache.players.indexGetAll(
"playersByTid",
PLAYER.RETIRED,
);
const father = fathers.find(p => p.relatives.length > 0);
assert(!father);
assert.strictEqual(son.relatives.length, 1);
assert.deepStrictEqual(son.relatives[0], relFather);
});
test("handle case where player already has a brother", async () => {
await testHelpers.resetCache({
players: [
// Son
player.generate(PLAYER.UNDRAFTED, 20, season, true, 15.5), // Brother
player.generate(PLAYER.UNDRAFTED, 20, season, true, 15.5), // Fathers
...genFathers(),
],
});
const son = await getPlayer(0);
son.relatives = [
{
type: "brother",
pid: 1,
name: "Foo Bar",
},
];
await idb.cache.players.put(son);
const brother = await getPlayer(1);
brother.born.loc = "Fake Country";
brother.relatives = [
{
type: "brother",
pid: 0,
name: "Foo Bar",
},
];
await idb.cache.players.put(brother);
await makeSon(son);
const fathers = await idb.cache.players.indexGetAll(
"playersByTid",
PLAYER.RETIRED,
);
const father = fathers.find(p => p.relatives.length > 0);
if (!father) {
throw new Error("No father found");
}
const son2 = await getPlayer(0);
const brother2 = await getPlayer(1);
assert.strictEqual(son2.relatives.length, 2);
assert.strictEqual(son2.relatives[0].type, "father");
assert.strictEqual(son2.relatives[0].pid, father.pid);
assert.strictEqual(son2.relatives[1].type, "brother");
assert.strictEqual(son2.relatives[1].pid, brother2.pid);
assert.strictEqual(brother2.relatives.length, 2);
assert.strictEqual(brother2.relatives[0].type, "father");
assert.strictEqual(brother2.relatives[0].pid, father.pid);
assert.strictEqual(brother2.relatives[1].type, "brother");
assert.strictEqual(brother2.relatives[1].pid, son2.pid);
assert.strictEqual(father.relatives.length, 2);
assert.strictEqual(father.relatives[0].type, "son");
assert.strictEqual(father.relatives[1].type, "son");
assert.deepStrictEqual(
father.relatives.map(relative => relative.pid).sort(),
[0, 1],
);
assert.strictEqual(brother2.born.loc, father.born.loc);
});
test("handle case where father already has a son", async () => {
const initialFathers = genFathers();
const initialOtherSons = initialFathers.map(() =>
player.generate(0, 25, season, true, 15.5),
);
await testHelpers.resetCache({
players: [
// Son
player.generate(PLAYER.UNDRAFTED, 20, season, true, 15.5), // Other sons (one for each potential father)
...initialOtherSons, // Fathers
...initialFathers,
],
});
const fathers = await idb.cache.players.indexGetAll(
"playersByTid",
PLAYER.RETIRED,
);
const otherSons = await idb.cache.players.indexGetAll("playersByTid", 0);
assert.strictEqual(fathers.length, otherSons.length);
for (let i = 0; i < fathers.length; i++) {
const father = fathers[i];
const otherSon = otherSons[i];
father.relatives.push({
type: "son",
pid: otherSon.pid,
name: `${otherSon.firstName} ${otherSon.lastName}`,
});
otherSon.relatives.push({
type: "father",
pid: father.pid,
name: `${father.firstName} ${father.lastName}`,
});
await idb.cache.players.put(father);
await idb.cache.players.put(otherSon);
}
const son = await getPlayer(0);
await makeSon(son);
const fathers2 = await idb.cache.players.indexGetAll(
"playersByTid",
PLAYER.RETIRED,
);
const father = fathers2.find(p => p.relatives.length > 1);
if (!father) {
throw new Error("No father found");
}
const otherSons2 = await idb.cache.players.indexGetAll("playersByTid", 0);
const otherSon = otherSons2.find(p => p.relatives.length > 1);
if (!otherSon) {
throw new Error("No other son found");
}
const son2 = await getPlayer(0);
assert.strictEqual(son2.relatives.length, 2);
assert.strictEqual(son2.relatives[0].type, "father");
assert.strictEqual(son2.relatives[0].pid, father.pid);
assert.strictEqual(son2.relatives[1].type, "brother");
assert.strictEqual(son2.relatives[1].pid, otherSon.pid);
assert.strictEqual(otherSon.relatives.length, 2);
assert.strictEqual(otherSon.relatives[0].type, "father");
assert.strictEqual(otherSon.relatives[0].pid, father.pid);
assert.strictEqual(otherSon.relatives[1].type, "brother");
assert.strictEqual(otherSon.relatives[1].pid, son2.pid);
assert.strictEqual(father.relatives.length, 2);
assert.strictEqual(father.relatives[0].type, "son");
assert.strictEqual(father.relatives[1].type, "son");
assert.deepStrictEqual(
father.relatives.map(relative => relative.pid).sort(),
[son2.pid, otherSon.pid],
);
});
});
}); | the_stack |
import CodeMirror from "codemirror";
import {Asm, AssembledLine, FileInfo, SymbolInfo, SymbolReference} from "../assembler/Asm";
import mnemonicData from "../assembler/Opcodes";
import {toHexByte, toHexWord} from "z80-base";
import tippy from 'tippy.js';
import 'tippy.js/dist/tippy.css';
import "codemirror/lib/codemirror.css";
import "codemirror/theme/mbo.css";
import "codemirror/addon/dialog/dialog.css";
import "codemirror/addon/hint/show-hint.css";
import "codemirror/addon/fold/foldgutter.css";
import "./main.css";
// Load these for their side-effects (they register themselves).
import "codemirror/addon/dialog/dialog";
import "codemirror/addon/search/search";
import "codemirror/addon/search/jump-to-line";
import "codemirror/addon/edit/closebrackets";
import "codemirror/addon/hint/show-hint";
import "codemirror/addon/scroll/annotatescrollbar";
import "codemirror/addon/selection/active-line";
import "codemirror/addon/selection/mark-selection";
import "codemirror/addon/fold/foldcode";
import "codemirror/addon/fold/foldgutter";
import "codemirror/mode/z80/z80";
import * as fs from "fs";
import Store from "electron-store";
import {ClrInstruction, OpcodeTemplate, Variant} from "../assembler/OpcodesTypes";
// Max number of sub-lines per line. These are lines where we display the
// opcodes for a single source line.
const MAX_SUBLINES = 100;
// Max number of opcode bytes we display per subline. Sync this with the CSS
// that lays out the gutter.
const BYTES_PER_SUBLINE = 3;
const CURRENT_PATHNAME_KEY = "current-pathname";
// Convenience for the result of a range finder function (for folding).
type RangeFinderResult = {from: CodeMirror.Position, to: CodeMirror.Position} | undefined;
// Result of looking up what symbol we're on.
class SymbolHit {
public readonly symbol: SymbolInfo;
public readonly isDefinition: boolean;
public readonly referenceNumber: number;
constructor(symbol: SymbolInfo, isDefinition: boolean, reference: number) {
this.symbol = symbol;
this.isDefinition = isDefinition;
this.referenceNumber = reference;
}
}
// In-memory cache of the disk file.
class SourceFile {
public readonly pathname: string;
public readonly lines: string[];
public modified = false;
constructor(pathname: string, lines: string[]) {
this.pathname = pathname;
this.lines = lines;
}
public setLines(lines: string[]): void {
console.log("Pushing " + lines.length + " lines to " + this.pathname);
// See if they've changed.
let changed = this.lines.length !== lines.length;
if (!changed) {
const length = lines.length;
for (let i = 0; i < length; i++) {
if (this.lines[i] !== lines[i]) {
changed = true;
break;
}
}
}
if (changed) {
console.log("Was modified");
this.lines.splice(0, this.lines.length, ...lines);
this.modified = true;
}
}
}
// Read a file raw text, or undefined if the file can't be opened.
function readFile(pathname: string): string | undefined {
try {
return fs.readFileSync(pathname, "utf-8");
} catch (e) {
console.log("readFile(" + pathname + "): " + e);
return undefined;
}
}
// Read a file as an array of lines, or undefined if the file can't be opened.
function readFileLines(pathname: string): string[] | undefined {
let text = readFile(pathname);
if (text === undefined) {
return undefined;
}
// Remove trailing newline, since we treat newlines as separators, not terminators.
// This means that a partial line at the end of a file is treated like a full line.
// TODO handle CR/NL too.
if (text.endsWith("\n")) {
text = text.substr(0, text.length - 1);
}
return text.split(/\r?\n/);
}
/**
* Whether "prefix" is a prefix of "opcode". I.e., the opcode array starts with prefix.
*/
function isPrefix(prefix: OpcodeTemplate[], opcode: OpcodeTemplate[]): boolean {
if (prefix.length > opcode.length) {
return false;
}
for (let i = 0; i < prefix.length; i++) {
if (prefix[i] !== opcode[i]) {
return false;
}
}
return true;
}
class Ide {
private store: Store;
private readonly cm: CodeMirror.Editor;
// The index of this array is the line number in the file (zero-based).
private assembledLines: AssembledLine[] = [];
private pathname: string = "";
private ipcRenderer: any;
private scrollbarAnnotator: any;
private sourceFiles = new Map<string,SourceFile>();
private readonly symbolMarks: CodeMirror.TextMarker[] = [];
private readonly lineWidgets: CodeMirror.LineWidget[] = [];
private fileInfo: FileInfo | undefined;
constructor(parent: HTMLElement) {
this.store = new Store({
name: "z80-ide",
});
const config = {
value: "",
lineNumbers: true,
tabSize: 8,
theme: 'mbo',
gutters: ["CodeMirror-linenumbers", "gutter-assembled", "CodeMirror-foldgutter"],
autoCloseBrackets: true,
mode: "text/x-z80",
// Doesn't work, I call focus() explicitly later.
autoFocus: true,
extraKeys: (CodeMirror as any).normalizeKeyMap({
// "Ctrl-Space": "autocomplete"
"Cmd-B": () => this.jumpToDefinition(false),
"Shift-Cmd-B": () => this.jumpToDefinition(true),
}),
hintOptions: {
hint: () => this.hint(),
},
styleActiveLine: true,
styleSelectedText: true,
cursorScrollMargin: 200,
foldGutter: true,
foldOptions: {
rangeFinder: (cm: CodeMirror.Editor, start: CodeMirror.Position) => this.rangeFinder(start),
widget: (from: CodeMirror.Position, to: CodeMirror.Position) => {
const count = to.line - from.line;
return `\u21A4 ${count} \u21A6`;
},
},
};
this.cm = CodeMirror(parent, config);
// Create CSS classes for our line heights. We do this dynamically since
// we don't know the line height at compile time.
const cssRules = [];
for (let lineCount = 1; lineCount < MAX_SUBLINES; lineCount++) {
cssRules.push(".line-height-" + lineCount + " { height: " + lineCount * this.cm.defaultTextHeight() + "px; }");
}
const style = document.createElement("style");
style.appendChild(document.createTextNode(cssRules.join("\n")));
document.head.appendChild(style);
this.cm.on("change", (instance, changeObj) => {
// It's important to call this in "change", and not in "changes" or
// after a timeout, because we want to be part of this operation.
// This way a large re-assemble takes 40ms instead of 300ms.
// We should be entirely within a file (otherwise we would have gotten
// canceled in the "beforeChange" event). Find which file we're in
// and update it all.
if (changeObj.origin !== "setValue") {
console.log(changeObj);
const removed = changeObj.removed ?? [];
const linesAdded = changeObj.text.length - removed.length;
this.editorToCache(changeObj.from.line, linesAdded);
this.assembleAll();
}
});
this.cm.on("beforeChange", (instance, changeObj) => {
if (changeObj.origin === "setValue") {
// Always allow setValue().
return;
}
console.log("beforeChange \"" + changeObj.origin + "\"");
const beginLine = changeObj.from.line;
const endLine = changeObj.to.ch === 0 ? changeObj.to.line : changeObj.to.line + 1;
if (this.fileInfo !== undefined) {
const spansFileInfo = (fileInfo: FileInfo): boolean => {
if ((beginLine < fileInfo.beginLineNumber && endLine > fileInfo.beginLineNumber) ||
(beginLine < fileInfo.endLineNumber && endLine > fileInfo.endLineNumber)) {
return true;
}
for (const fi of fileInfo.childFiles) {
if (spansFileInfo(fi)) {
return true;
}
}
return false;
};
const spanFile = spansFileInfo(this.fileInfo);
if (spanFile) {
console.log("Canceling update");
changeObj.cancel();
}
}
});
this.cm.on("cursorActivity", (instance) => {
this.updateHighlight();
});
this.cm.on("blur", () => this.saveSilently());
// The type definition doesn't include this extension.
this.scrollbarAnnotator = (this.cm as any).annotateScrollbar("scrollbar-error");
// Configure IPC with the main process of Electron.
this.ipcRenderer = (window as any).ipcRenderer;
this.ipcRenderer.on("set-pathname", (event: any, pathname: string) => this.setPathnameAndLoad(pathname));
this.ipcRenderer.on("next-error", () => this.nextError());
this.ipcRenderer.on("declaration-or-usages", () => this.jumpToDefinition(false));
this.ipcRenderer.on("next-usage", () => this.jumpToDefinition(true));
this.ipcRenderer.on("save", () => this.saveOrAskPathname());
this.ipcRenderer.on("asked-for-filename", (event: any, pathname: string | undefined) => this.userSpecifiedPathname(pathname));
this.ipcRenderer.on("fold-all", () => this.cm.execCommand("foldAll"));
this.ipcRenderer.on("unfold-all", () => this.cm.execCommand("unfoldAll"));
this.cm.focus();
// Read file from last time.
const pathname = this.store.get(CURRENT_PATHNAME_KEY);
if (pathname !== undefined) {
this.pathname = pathname;
this.ipcRenderer.send("set-window-title", pathname);
this.assembleAll();
this.cm.execCommand("foldAll")
}
}
// Set pathname when we want to load that existing file from disk.
private setPathnameAndLoad(pathname: string): void {
this.setPathname(pathname);
this.assembleAll();
this.cm.execCommand("foldAll")
this.cm.clearHistory();
}
// Set the pathname of a previously-new document.
private setPathname(pathname: string) {
this.pathname = pathname;
this.ipcRenderer.send("set-window-title", pathname === "" ? "New File" : pathname);
if (pathname !== "") {
this.store.set(CURRENT_PATHNAME_KEY, pathname);
}
}
// Save if possible, else do nothing. This is for implicit saving like when the editor
// loses focus.
private saveSilently(): void {
if (this.pathname !== "") {
this.saveFile();
}
}
// User-initiated save.
private saveOrAskPathname(): void {
if (this.pathname === "") {
this.ipcRenderer.send("ask-for-filename");
// Continues in "asked-for-filename".
} else {
this.saveFile();
}
}
private userSpecifiedPathname(pathname: string | undefined): void {
if (pathname === undefined) {
// Ignore.
} else {
this.setPathname(pathname);
this.saveFile();
}
}
// Save the file to disk.
private saveFile(): void {
/*
fs.writeFile(this.pathname, this.cm.getValue(), () => {
// TODO mark file clean.
});
*/
}
// Given a starting line, see if it starts a section that could be folded.
private rangeFinder(start: CodeMirror.Position): RangeFinderResult {
const checkFileInfo = (fi: FileInfo | undefined, depth: number): RangeFinderResult => {
if (fi !== undefined) {
// Prefer children, do those first.
for (const child of fi.childFiles) {
const range = checkFileInfo(child, depth + 1);
if (range !== undefined) {
return range;
}
}
// Assume that whatever is being folded, it's the result of an #include statement
// on the previous line. Don't need to fold entire top-level file.
if (fi.beginLineNumber - 1 === start.line && depth > 0) {
const firstLineNumber = start.line;
const firstLine = this.cm.getLine(firstLineNumber);
const lastLineNumber = fi.endLineNumber - 1;
const lastLine = this.cm.getLine(lastLineNumber);
if (firstLine !== undefined && lastLine !== undefined) {
return {
from: CodeMirror.Pos(firstLineNumber, firstLine.length),
to: CodeMirror.Pos(lastLineNumber, lastLine.length),
};
}
}
}
return undefined;
};
return checkFileInfo(this.fileInfo, 0);
}
private nextError(): void {
if (this.assembledLines.length === 0) {
return;
}
const currentLineNumber = this.cm.getCursor().line;
let nextErrorLineNumber = currentLineNumber;
do {
nextErrorLineNumber = (nextErrorLineNumber + 1) % this.assembledLines.length;
} while (nextErrorLineNumber !== currentLineNumber && this.assembledLines[nextErrorLineNumber].error === undefined);
if (nextErrorLineNumber !== currentLineNumber) {
// TODO error might not be in this file:
this.setCursor(nextErrorLineNumber, 0);
}
}
private setCursorToReference(ref: SymbolReference): void {
this.setCursor(ref.lineNumber, ref.column);
}
// Set the editor's cursor if it's for this file.
private setCursor(lineNumber: number, column: number): void {
this.cm.setCursor(lineNumber, column);
}
// Find symbol usage at a location, or undefined if we're not on a symbol.
private findSymbolAt(lineNumber: number, column: number): SymbolHit | undefined {
const assembledLine = this.assembledLines[lineNumber];
for (const symbol of assembledLine.symbols) {
// See if we're at a definition.
for (let i = 0; i < symbol.definitions.length; i++) {
if (symbol.matches(symbol.definitions[i], lineNumber, column)) {
return new SymbolHit(symbol, true, i);
}
}
// See if we're at a use.
for (let i = 0; i < symbol.references.length; i++) {
if (symbol.matches(symbol.references[i], lineNumber, column)) {
return new SymbolHit(symbol, false, i);
}
}
}
return undefined;
}
// Jump from a use to its definition and vice versa.
//
// @param nextUse whether to cycle uses/definitions (true) or switch between use and definition (false).
private jumpToDefinition(nextUse: boolean) {
const pos = this.cm.getCursor();
const symbolHit = this.findSymbolAt(pos.line, pos.ch);
if (symbolHit !== undefined) {
const symbol = symbolHit.symbol;
if (symbolHit.isDefinition) {
if (nextUse) {
const reference = symbol.definitions[(symbolHit.referenceNumber + 1) % symbol.definitions.length];
this.setCursorToReference(reference);
} else if (symbol.references.length > 0) {
this.setCursorToReference(symbol.references[0]);
} else {
// TODO: Display error.
}
} else {
if (nextUse) {
const reference = symbol.references[(symbolHit.referenceNumber + 1) % symbol.references.length];
this.setCursorToReference(reference);
} else if (symbol.definitions.length > 0) {
this.setCursorToReference(symbol.definitions[0]);
} else {
// TODO: Display error.
}
}
}
}
// Delete all line widgets.
private clearLineWidgets(): void {
let lineWidget;
while ((lineWidget = this.lineWidgets.pop()) !== undefined) {
lineWidget.clear();
}
}
private clearSymbolMarks(): void {
let mark;
while ((mark = this.symbolMarks.pop()) !== undefined) {
mark.clear();
}
}
private updateHighlight() {
this.clearSymbolMarks();
const pos = this.cm.getCursor();
const symbolHit = this.findSymbolAt(pos.line, pos.ch);
if (symbolHit !== undefined) {
const symbol = symbolHit.symbol;
// Highlight definitions.
for (const reference of symbol.definitions) {
const mark = this.cm.markText({line: reference.lineNumber, ch: reference.column},
{line: reference.lineNumber, ch: reference.column + symbol.name.length},
{
className: "current-symbol",
});
this.symbolMarks.push(mark);
}
// Highlight references.
for (const reference of symbol.references) {
const mark = this.cm.markText({line: reference.lineNumber, ch: reference.column},
{line: reference.lineNumber, ch: reference.column + symbol.name.length},
{
className: "current-symbol",
});
this.symbolMarks.push(mark);
}
}
}
// Push the lines in the editor back to the file cache.
private editorToCache(beginLineNumber: number, linesAdded: number): void {
if (this.fileInfo === undefined) {
// Haven't assembled yet.
return;
}
// The line we're on.
const assembledLine = this.assembledLines[beginLineNumber];
// Find the file we're in.
const fileInfo = assembledLine.fileInfo;
const sourceFile = this.sourceFiles.get(fileInfo.pathname);
if (sourceFile === undefined) {
throw new Error("Can't find source file for " + fileInfo.pathname);
}
let lineNumbers = Array.from(fileInfo.lineNumbers);
if (linesAdded > 0) {
const index = lineNumbers.indexOf(beginLineNumber);
if (index === -1) {
throw new Error("Can't find line number " + beginLineNumber + " in array of lines");
}
for (let i = 0; i < linesAdded; i++) {
lineNumbers.splice(index + 1 + i, 0, beginLineNumber + i + 1);
}
console.log(lineNumbers);
for (let i = index + linesAdded + 1; i < lineNumbers.length; i++) {
lineNumbers[i] += linesAdded;
}
console.log(lineNumbers);
} else if (linesAdded < 0) {
const linesRemoved = -linesAdded;
console.log(lineNumbers);
const index = lineNumbers.indexOf(beginLineNumber);
if (index === -1) {
throw new Error("Can't find line number " + beginLineNumber + " in array of lines");
}
lineNumbers.splice(index + 1, linesRemoved);
console.log(lineNumbers);
for (let i = index + 1; i < lineNumbers.length; i++) {
lineNumbers[i] -= linesRemoved;
}
console.log(lineNumbers);
}
const newLines: string[] = [];
for (const lineNumber of lineNumbers) {
// Skip synthetic lines.
const lineInfo = this.cm.lineInfo(lineNumber);
const isSynthetic = lineInfo.textClass === undefined
? false
: lineInfo.textClass.split(" ").indexOf("synthetic-line") >= 0;
if (!isSynthetic) {
const text = this.cm.getLine(lineNumber);
newLines.push(text);
}
}
sourceFile.setLines(newLines);
}
// Get the lines from the file cache, reading from disk if necessary.
private getFileLines(pathname: string): string[] | undefined {
// Check the cache.
let sourceFile = this.sourceFiles.get(pathname);
if (sourceFile === undefined) {
const lines = pathname === "" ? [""] : readFileLines(pathname);
if (lines === undefined) {
// Don't cache the failure, just try again next time.
return undefined;
}
sourceFile = new SourceFile(pathname, lines);
this.sourceFiles.set(pathname, sourceFile);
}
return sourceFile.lines;
}
private assembleAll() {
this.clearLineWidgets();
const before = Date.now();
const asm = new Asm((pathname) => this.getFileLines(pathname));
const sourceFile = asm.assembleFile(this.pathname);
if (sourceFile === undefined) {
// TODO deal with file not existing.
return;
}
this.assembledLines = sourceFile.assembledLines;
this.fileInfo = sourceFile.fileInfo;
// Compute new text for editor.
const lines: string[] = [];
for (const assembledLine of this.assembledLines) {
lines.push(assembledLine.line);
}
let newValue = lines.join("\n");
if (newValue !== this.cm.getValue()) {
const cursor = this.cm.getCursor();
this.cm.setValue(newValue);
this.cm.setCursor(cursor);
}
const before1 = Date.now();
// Update text markers.
for (let lineNumber = 0; lineNumber < this.assembledLines.length; lineNumber++) {
const assembledLine = this.assembledLines[lineNumber];
const depth = assembledLine.fileInfo.depth;
if (depth > 0) {
this.cm.addLineClass(lineNumber, "background", "include-" + depth);
}
}
console.log("Updating include line markers: " + (Date.now() - before1));
// Update UI.
const before2 = Date.now();
const annotationMarks: any[] = [];
for (let lineNumber = 0; lineNumber < this.assembledLines.length; lineNumber++) {
const assembledLine = this.assembledLines[lineNumber];
// Update gutter.
let addressElement: HTMLElement | null;
if (assembledLine.binary.length > 0) {
addressElement = document.createElement("div");
// Break opcodes over multiple lines if necessary.
let numLines = 0;
for (let offset = 0;
offset < assembledLine.binary.length && numLines < MAX_SUBLINES;
offset += BYTES_PER_SUBLINE, numLines++) {
const addressString = toHexWord(assembledLine.address + offset) +
" " + assembledLine.binary.slice(offset, offset + BYTES_PER_SUBLINE).map(toHexByte).join(" ");
const addressTextElement = document.createTextNode(addressString);
if (offset > 0) {
addressElement.appendChild(document.createElement("br"));
}
addressElement.appendChild(addressTextElement);
}
addressElement.classList.add("gutter-style");
// For the line height using CSS.
this.cm.removeLineClass(lineNumber, "wrap", undefined);
if (numLines !== 1) {
this.cm.addLineClass(lineNumber, "wrap", "line-height-" + numLines);
}
if (assembledLine.variant !== undefined) {
let popup = assembledLine.variant.clr !== null
? this.getPopupForClr(assembledLine.variant.clr)
: this.getPopupForPseudoInstruction(assembledLine.variant);
if (popup !== undefined) {
addressElement.addEventListener("mouseenter", () => {
if (addressElement !== null && (addressElement as any)._tippy === undefined) {
const instance = tippy(addressElement, {
content: popup,
allowHTML: true,
});
instance.show();
}
});
}
}
} else {
addressElement = null;
}
this.cm.setGutterMarker(lineNumber, "gutter-assembled", addressElement);
// Update errors.
if (assembledLine.error === undefined) {
this.cm.removeLineClass(lineNumber, "background", "error-line");
} else {
this.cm.addLineClass(lineNumber, "background", "error-line");
// Highlight error in scrollbar.
annotationMarks.push({
from: { line: lineNumber, ch: 0 },
to: { line: lineNumber + 1, ch: 0 },
});
// Write error below line.
const node = document.createElement("span");
node.appendChild(document.createTextNode(assembledLine.error));
this.lineWidgets.push(this.cm.addLineWidget(lineNumber, node, {
className: "error-line",
}));
}
// Handle synthetic lines.
if (assembledLine.lineNumber === undefined) {
this.cm.addLineClass(lineNumber, "text", "synthetic-line");
// I don't know if we need to remember these marks and delete them ourselves, or
// if the setValue() call will do it.
this.cm.markText({line: lineNumber, ch: 0}, {line: lineNumber + 1, ch: 0}, {
inclusiveLeft: false,
inclusiveRight: false,
// These are not in the type definition. Not sure if we need them.
// selectLeft: false,
// selectRight: true,
atomic: true,
collapsed: false,
clearOnEnter: false,
css: "color: #666",
});
}
}
console.log("Updating gutters and line widgets: " + (Date.now() - before2));
const before3 = Date.now();
this.scrollbarAnnotator.update(annotationMarks);
console.log("Updating scrollbar annotations: " + (Date.now() - before3));
console.log("Total assembly time: " + (Date.now() - before));
}
private hint(): any {
// TODO remove.
const cursor = this.cm.getCursor();
const line = this.cm.getLine(cursor.line);
const start = cursor.ch;
const end = cursor.ch;
return {
list: ["aaaaa", "bbbbb", "ccccc"],
from: CodeMirror.Pos(cursor.line, start - 3),
to: CodeMirror.Pos(cursor.line, start),
};
}
/**
* Generate a popup for an instruction that has clr info.
*/
private getPopupForClr(clr: ClrInstruction): string {
let popup = "<b>" + clr.instruction.toUpperCase() + "</b><br><br>";
if (clr.description) {
popup += clr.description + "<br><br>";
}
popup += clr.byte_count + " bytes, ";
if (clr.with_jump_clock_count === clr.without_jump_clock_count) {
popup += clr.with_jump_clock_count + " clocks.<br><br>";
} else {
popup += clr.with_jump_clock_count + "/" + clr.without_jump_clock_count + " clocks.<br><br>";
}
if (clr.flags === "------") {
popup += "Flags are unaffected.</br>";
} else {
const flagLabels = ['C', 'N', 'P/V', 'H', 'Z', 'S'];
for (let i = 0; i < 6; i++) {
popup += "<b>" + flagLabels[i] + ":</b> ";
switch (clr.flags.charAt(i)) {
case '-':
popup += 'unaffected';
break;
case '+':
popup += 'affected as defined';
break;
case 'P':
popup += 'detects parity';
break;
case 'V':
popup += 'detects overflow';
break;
case '1':
popup += 'set';
break;
case '0':
popup += 'reset';
break;
case '*':
popup += 'exceptional';
break;
default:
popup += 'unknown';
break;
}
popup += "<br>";
}
}
if (clr.undocumented) {
popup += "<br>Undocumented instructions.<br>";
}
return popup;
}
/**
* Generate popup for a pseudo instruction (composite of multiple instructions),
* or undefined if we can't find which instructions it's made of.
*/
private getPopupForPseudoInstruction(variant: Variant): string | undefined {
if (variant.opcode.length === 0) {
return undefined;
}
let popup = "<b>Pseudo Instruction</b><br><br>";
// If this happens a lot we should make a reverse map.
let start = 0;
while (start < variant.opcode.length) {
const subVariant = this.getVariantForOpcode(variant.opcode.slice(start));
if (subVariant === undefined) {
return undefined;
}
if (subVariant.clr === null) {
popup += "Unknown instruction<br>";
} else {
popup += subVariant.clr.instruction.toUpperCase() + "<br>";
}
start += subVariant.opcode.length;
}
return popup;
}
/**
* Find the variant for whatever instruction is at the head of the sequence of opcodes,
* or undefined if it can't be found. Never returns pseudo-instructions.
*/
private getVariantForOpcode(opcode: OpcodeTemplate[]): Variant | undefined {
for (const mnemonic of Object.keys(mnemonicData.mnemonics)) {
for (const variant of mnemonicData.mnemonics[mnemonic].variants) {
if (variant.clr !== null && isPrefix(variant.opcode, opcode)) {
return variant;
}
}
}
return undefined;
}
}
function main() {
const element = document.getElementById("editor") as HTMLElement;
new Ide(element);
}
main(); | the_stack |
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
import {
IIterable, IIterator, IRetroable, IterableOrArrayLike, each
} from '@lumino/algorithm';
/**
* A generic doubly-linked list.
*/
export
class LinkedList<T> implements IIterable<T>, IRetroable<T> {
/**
* Construct a new linked list.
*/
constructor() { }
/**
* Whether the list is empty.
*
* #### Complexity
* Constant.
*/
get isEmpty(): boolean {
return this._size === 0;
}
/**
* The size of the list.
*
* #### Complexity
* `O(1)`
*
* #### Notes
* This is equivalent to `length`.
*/
get size(): number {
return this._size;
}
/**
* The length of the list.
*
* #### Complexity
* Constant.
*
* #### Notes
* This is equivalent to `size`.
*
* This property is deprecated.
*/
get length(): number {
return this._size;
}
/**
* The first value in the list.
*
* This is `undefined` if the list is empty.
*
* #### Complexity
* Constant.
*/
get first(): T | undefined {
return this._first ? this._first.value : undefined;
}
/**
* The last value in the list.
*
* This is `undefined` if the list is empty.
*
* #### Complexity
* Constant.
*/
get last(): T | undefined {
return this._last ? this._last.value : undefined;
}
/**
* The first node in the list.
*
* This is `null` if the list is empty.
*
* #### Complexity
* Constant.
*/
get firstNode(): LinkedList.INode<T> | null {
return this._first;
}
/**
* The last node in the list.
*
* This is `null` if the list is empty.
*
* #### Complexity
* Constant.
*/
get lastNode(): LinkedList.INode<T> | null {
return this._last;
}
/**
* Create an iterator over the values in the list.
*
* @returns A new iterator starting with the first value.
*
* #### Complexity
* Constant.
*/
iter(): IIterator<T> {
return new LinkedList.ForwardValueIterator<T>(this._first);
}
/**
* Create a reverse iterator over the values in the list.
*
* @returns A new iterator starting with the last value.
*
* #### Complexity
* Constant.
*/
retro(): IIterator<T> {
return new LinkedList.RetroValueIterator<T>(this._last);
}
/**
* Create an iterator over the nodes in the list.
*
* @returns A new iterator starting with the first node.
*
* #### Complexity
* Constant.
*/
nodes(): IIterator<LinkedList.INode<T>> {
return new LinkedList.ForwardNodeIterator<T>(this._first);
}
/**
* Create a reverse iterator over the nodes in the list.
*
* @returns A new iterator starting with the last node.
*
* #### Complexity
* Constant.
*/
retroNodes(): IIterator<LinkedList.INode<T>> {
return new LinkedList.RetroNodeIterator<T>(this._last);
}
/**
* Assign new values to the list, replacing all current values.
*
* @param values - The values to assign to the list.
*
* #### Complexity
* Linear.
*/
assign(values: IterableOrArrayLike<T>): void {
this.clear();
each(values, value => { this.addLast(value); });
}
/**
* Add a value to the end of the list.
*
* @param value - The value to add to the end of the list.
*
* #### Complexity
* Constant.
*
* #### Notes
* This is equivalent to `addLast`.
*/
push(value: T): void {
this.addLast(value);
}
/**
* Remove and return the value at the end of the list.
*
* @returns The removed value, or `undefined` if the list is empty.
*
* #### Complexity
* Constant.
*
* #### Notes
* This is equivalent to `removeLast`.
*/
pop(): T | undefined {
return this.removeLast();
}
/**
* Add a value to the beginning of the list.
*
* @param value - The value to add to the beginning of the list.
*
* #### Complexity
* Constant.
*
* #### Notes
* This is equivalent to `addFirst`.
*/
shift(value: T): void {
this.addFirst(value);
}
/**
* Remove and return the value at the beginning of the list.
*
* @returns The removed value, or `undefined` if the list is empty.
*
* #### Complexity
* Constant.
*
* #### Notes
* This is equivalent to `removeFirst`.
*/
unshift(): T | undefined {
return this.removeFirst();
}
/**
* Add a value to the beginning of the list.
*
* @param value - The value to add to the beginning of the list.
*
* @returns The list node which holds the value.
*
* #### Complexity
* Constant.
*/
addFirst(value: T): LinkedList.INode<T> {
let node = new Private.LinkedListNode<T>(this, value);
if (!this._first) {
this._first = node;
this._last = node;
} else {
node.next = this._first;
this._first.prev = node;
this._first = node;
}
this._size++;
return node;
}
/**
* Add a value to the end of the list.
*
* @param value - The value to add to the end of the list.
*
* @returns The list node which holds the value.
*
* #### Complexity
* Constant.
*/
addLast(value: T): LinkedList.INode<T> {
let node = new Private.LinkedListNode<T>(this, value);
if (!this._last) {
this._first = node;
this._last = node;
} else {
node.prev = this._last;
this._last.next = node;
this._last = node;
}
this._size++;
return node;
}
/**
* Insert a value before a specific node in the list.
*
* @param value - The value to insert before the reference node.
*
* @param ref - The reference node of interest. If this is `null`,
* the value will be added to the beginning of the list.
*
* @returns The list node which holds the value.
*
* #### Notes
* The reference node must be owned by the list.
*
* #### Complexity
* Constant.
*/
insertBefore(value: T, ref: LinkedList.INode<T> | null): LinkedList.INode<T> {
if (!ref || ref === this._first) {
return this.addFirst(value);
}
if (!(ref instanceof Private.LinkedListNode) || ref.list !== this) {
throw new Error('Reference node is not owned by the list.');
}
let node = new Private.LinkedListNode<T>(this, value);
let _ref = ref as Private.LinkedListNode<T>;
let prev = _ref.prev!;
node.next = _ref;
node.prev = prev;
_ref.prev = node;
prev.next = node;
this._size++;
return node;
}
/**
* Insert a value after a specific node in the list.
*
* @param value - The value to insert after the reference node.
*
* @param ref - The reference node of interest. If this is `null`,
* the value will be added to the end of the list.
*
* @returns The list node which holds the value.
*
* #### Notes
* The reference node must be owned by the list.
*
* #### Complexity
* Constant.
*/
insertAfter(value: T, ref: LinkedList.INode<T> | null): LinkedList.INode<T> {
if (!ref || ref === this._last) {
return this.addLast(value);
}
if (!(ref instanceof Private.LinkedListNode) || ref.list !== this) {
throw new Error('Reference node is not owned by the list.');
}
let node = new Private.LinkedListNode<T>(this, value);
let _ref = ref as Private.LinkedListNode<T>;
let next = _ref.next!;
node.next = next;
node.prev = _ref;
_ref.next = node;
next.prev = node;
this._size++;
return node;
}
/**
* Remove and return the value at the beginning of the list.
*
* @returns The removed value, or `undefined` if the list is empty.
*
* #### Complexity
* Constant.
*/
removeFirst(): T | undefined {
let node = this._first;
if (!node) {
return undefined;
}
if (node === this._last) {
this._first = null;
this._last = null;
} else {
this._first = node.next;
this._first!.prev = null;
}
node.list = null;
node.next = null;
node.prev = null;
this._size--;
return node.value;
}
/**
* Remove and return the value at the end of the list.
*
* @returns The removed value, or `undefined` if the list is empty.
*
* #### Complexity
* Constant.
*/
removeLast(): T | undefined {
let node = this._last;
if (!node) {
return undefined;
}
if (node === this._first) {
this._first = null;
this._last = null;
} else {
this._last = node.prev;
this._last!.next = null;
}
node.list = null;
node.next = null;
node.prev = null;
this._size--;
return node.value;
}
/**
* Remove a specific node from the list.
*
* @param node - The node to remove from the list.
*
* #### Complexity
* Constant.
*
* #### Notes
* The node must be owned by the list.
*/
removeNode(node: LinkedList.INode<T>): void {
if (!(node instanceof Private.LinkedListNode) || node.list !== this) {
throw new Error('Node is not owned by the list.');
}
let _node = node as Private.LinkedListNode<T>;
if (_node === this._first && _node === this._last) {
this._first = null;
this._last = null;
} else if (_node === this._first) {
this._first = _node.next;
this._first!.prev = null;
} else if (_node === this._last) {
this._last = _node.prev;
this._last!.next = null;
} else {
_node.next!.prev = _node.prev;
_node.prev!.next = _node.next;
}
_node.list = null;
_node.next = null;
_node.prev = null;
this._size--;
}
/**
* Remove all values from the list.
*
* #### Complexity
* Linear.
*/
clear(): void {
let node = this._first;
while (node) {
let next = node.next;
node.list = null;
node.prev = null;
node.next = null;
node = next;
}
this._first = null;
this._last = null;
this._size = 0;
}
private _first: Private.LinkedListNode<T> | null = null;
private _last: Private.LinkedListNode<T> | null = null;
private _size = 0;
}
/**
* The namespace for the `LinkedList` class statics.
*/
export
namespace LinkedList {
/**
* An object which represents a node in a linked list.
*
* #### Notes
* User code will not create linked list nodes directly. Nodes
* are created automatically when values are added to a list.
*/
export
interface INode<T> {
/**
* The linked list which created and owns the node.
*
* This will be `null` when the node is removed from the list.
*/
readonly list: LinkedList<T> | null;
/**
* The next node in the list.
*
* This will be `null` when the node is the last node in the list
* or when the node is removed from the list.
*/
readonly next: INode<T> | null;
/**
* The previous node in the list.
*
* This will be `null` when the node is the first node in the list
* or when the node is removed from the list.
*/
readonly prev: INode<T> | null;
/**
* The user value stored in the node.
*/
readonly value: T;
}
/**
* Create a linked list from an iterable of values.
*
* @param values - The iterable or array-like object of interest.
*
* @returns A new linked list initialized with the given values.
*
* #### Complexity
* Linear.
*/
export
function from<T>(values: IterableOrArrayLike<T>): LinkedList<T> {
let list = new LinkedList<T>();
list.assign(values);
return list;
}
/**
* A forward iterator for values in a linked list.
*/
export
class ForwardValueIterator<T> implements IIterator<T> {
/**
* Construct a forward value iterator.
*
* @param node - The first node in the list.
*/
constructor(node: INode<T> | null) {
this._node = node;
}
/**
* Get an iterator over the object's values.
*
* @returns An iterator which yields the object's values.
*/
iter(): IIterator<T> {
return this;
}
/**
* Create an independent clone of the iterator.
*
* @returns A new independent clone of the iterator.
*/
clone(): IIterator<T> {
return new ForwardValueIterator<T>(this._node);
}
/**
* Get the next value from the iterator.
*
* @returns The next value from the iterator, or `undefined`.
*/
next(): T | undefined {
if (!this._node) {
return undefined;
}
let node = this._node;
this._node = node.next;
return node.value;
}
private _node: INode<T> | null;
}
/**
* A reverse iterator for values in a linked list.
*/
export
class RetroValueIterator<T> implements IIterator<T> {
/**
* Construct a retro value iterator.
*
* @param node - The last node in the list.
*/
constructor(node: INode<T> | null) {
this._node = node;
}
/**
* Get an iterator over the object's values.
*
* @returns An iterator which yields the object's values.
*/
iter(): IIterator<T> {
return this;
}
/**
* Create an independent clone of the iterator.
*
* @returns A new independent clone of the iterator.
*/
clone(): IIterator<T> {
return new RetroValueIterator<T>(this._node);
}
/**
* Get the next value from the iterator.
*
* @returns The next value from the iterator, or `undefined`.
*/
next(): T | undefined {
if (!this._node) {
return undefined;
}
let node = this._node;
this._node = node.prev;
return node.value;
}
private _node: INode<T> | null;
}
/**
* A forward iterator for nodes in a linked list.
*/
export
class ForwardNodeIterator<T> implements IIterator<INode<T>> {
/**
* Construct a forward node iterator.
*
* @param node - The first node in the list.
*/
constructor(node: INode<T> | null) {
this._node = node;
}
/**
* Get an iterator over the object's values.
*
* @returns An iterator which yields the object's values.
*/
iter(): IIterator<INode<T>> {
return this;
}
/**
* Create an independent clone of the iterator.
*
* @returns A new independent clone of the iterator.
*/
clone(): IIterator<INode<T>> {
return new ForwardNodeIterator<T>(this._node);
}
/**
* Get the next value from the iterator.
*
* @returns The next value from the iterator, or `undefined`.
*/
next(): INode<T> | undefined {
if (!this._node) {
return undefined;
}
let node = this._node;
this._node = node.next;
return node;
}
private _node: INode<T> | null;
}
/**
* A reverse iterator for nodes in a linked list.
*/
export
class RetroNodeIterator<T> implements IIterator<INode<T>> {
/**
* Construct a retro node iterator.
*
* @param node - The last node in the list.
*/
constructor(node: INode<T> | null) {
this._node = node;
}
/**
* Get an iterator over the object's values.
*
* @returns An iterator which yields the object's values.
*/
iter(): IIterator<INode<T>> {
return this;
}
/**
* Create an independent clone of the iterator.
*
* @returns A new independent clone of the iterator.
*/
clone(): IIterator<INode<T>> {
return new RetroNodeIterator<T>(this._node);
}
/**
* Get the next value from the iterator.
*
* @returns The next value from the iterator, or `undefined`.
*/
next(): INode<T> | undefined {
if (!this._node) {
return undefined;
}
let node = this._node;
this._node = node.prev;
return node;
}
private _node: INode<T> | null;
}
}
/**
* The namespace for the module implementation details.
*/
namespace Private {
/**
* The internal linked list node implementation.
*/
export
class LinkedListNode<T> {
/**
* The linked list which created and owns the node.
*/
list: LinkedList<T> | null = null;
/**
* The next node in the list.
*/
next: LinkedListNode<T> | null = null;
/**
* The previous node in the list.
*/
prev: LinkedListNode<T> | null = null;
/**
* The user value stored in the node.
*/
readonly value: T;
/**
* Construct a new linked list node.
*
* @param list - The list which owns the node.
*
* @param value - The value for the link.
*/
constructor(list: LinkedList<T>, value: T) {
this.list = list;
this.value = value;
}
}
} | the_stack |
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
HostListener,
Input,
OnChanges, OnDestroy,
OnInit,
Output,
QueryList,
SimpleChange,
SimpleChanges,
ViewChildren
} from '@angular/core';
import {LocMeta, LogService, MetaUi, WebSocketService, ZoomUtils} from 'org_onosproject_onos/web/gui2-fw-lib/public_api';
import {
Badge,
Device, DeviceHighlight,
DeviceProps,
ForceDirectedGraph,
Host, HostHighlight,
HostLabelToggle,
LabelToggle,
LayerType,
Link,
LinkHighlight,
Location,
ModelEventMemo,
ModelEventType,
Node,
Options,
Region,
RegionLink,
SubRegion,
UiElement
} from './models';
import {LocationType} from '../backgroundsvg/backgroundsvg.component';
import {DeviceNodeSvgComponent} from './visuals/devicenodesvg/devicenodesvg.component';
import {HostNodeSvgComponent} from './visuals/hostnodesvg/hostnodesvg.component';
import {LinkSvgComponent} from './visuals/linksvg/linksvg.component';
import {SelectedEvent} from './visuals/nodevisual';
interface UpdateMeta {
id: string;
class: string;
memento: MetaUi;
}
const SVGCANVAS = <Options>{
width: 1000,
height: 1000
};
interface ChangeSummary {
numChanges: number;
locationChanged: boolean;
}
/**
* ONOS GUI -- Topology Forces Graph Layer View.
*
* The regionData is set by Topology Service on WebSocket topo2CurrentRegion callback
* This drives the whole Force graph
*/
@Component({
selector: '[onos-forcesvg]',
templateUrl: './forcesvg.component.html',
styleUrls: ['./forcesvg.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ForceSvgComponent implements OnInit, OnDestroy, OnChanges {
@Input() deviceLabelToggle: LabelToggle.Enum = LabelToggle.Enum.NONE;
@Input() hostLabelToggle: HostLabelToggle.Enum = HostLabelToggle.Enum.NONE;
@Input() showHosts: boolean = false;
@Input() showAlarms: boolean = false;
@Input() highlightPorts: boolean = true;
@Input() onosInstMastership: string = '';
@Input() visibleLayer: LayerType = LayerType.LAYER_DEFAULT;
@Input() selectedLink: RegionLink = null;
@Input() scale: number = 1;
@Input() regionData: Region = <Region>{devices: [ [], [], [] ], hosts: [ [], [], [] ], links: []};
@Output() linkSelected = new EventEmitter<RegionLink>();
@Output() selectedNodeEvent = new EventEmitter<UiElement[]>();
public graph: ForceDirectedGraph;
private selectedNodes: UiElement[] = [];
viewInitialized: boolean = false;
linksHighlighted: Map<string, LinkHighlight>;
// References to the children of this component - these are created in the
// template view with the *ngFor and we get them by a query here
@ViewChildren(DeviceNodeSvgComponent) devices: QueryList<DeviceNodeSvgComponent>;
@ViewChildren(HostNodeSvgComponent) hosts: QueryList<HostNodeSvgComponent>;
@ViewChildren(LinkSvgComponent) links: QueryList<LinkSvgComponent>;
constructor(
protected log: LogService,
private ref: ChangeDetectorRef,
protected wss: WebSocketService
) {
this.selectedLink = null;
this.log.debug('ForceSvgComponent constructed');
this.linksHighlighted = new Map<string, LinkHighlight>();
}
/**
* Utility for extracting a node name from an endpoint string
* In some cases - have to remove the port number from the end of a device
* name
* @param endPtStr The end point name
* @param portStr The port name
*/
static extractNodeName(endPtStr: string, portStr: string): string {
if (portStr === undefined || endPtStr === undefined) {
return endPtStr;
} else if (endPtStr.includes('/')) {
return endPtStr.substr(0, endPtStr.length - portStr.length - 1);
}
return endPtStr;
}
/**
* Recursive method to compare 2 objects attribute by attribute and update
* the first where a change is detected
* @param existingNode 1st object
* @param updatedNode 2nd object
*/
private static updateObject(existingNode: Object, updatedNode: Object): ChangeSummary {
const changed = <ChangeSummary>{numChanges: 0, locationChanged: false};
for (const key of Object.keys(updatedNode)) {
const o = updatedNode[key];
if (['id', 'x', 'y', 'fx', 'fy', 'vx', 'vy', 'index'].some(k => k === key)) {
continue;
} else if (o && typeof o === 'object' && o.constructor === Object) {
const subChanged = ForceSvgComponent.updateObject(existingNode[key], updatedNode[key]);
changed.numChanges += subChanged.numChanges;
changed.locationChanged = subChanged.locationChanged ? true : changed.locationChanged;
} else if (existingNode === undefined) {
// Copy the whole object
existingNode = updatedNode;
changed.locationChanged = true;
changed.numChanges++;
} else if (existingNode[key] !== updatedNode[key]) {
if (['locType', 'latOrY', 'longOrX', 'latitude', 'longitude', 'gridX', 'gridY'].some(k => k === key)) {
changed.locationChanged = true;
}
changed.numChanges++;
existingNode[key] = updatedNode[key];
}
}
return changed;
}
@HostListener('window:resize', ['$event'])
onResize(event) {
this.graph.restartSimulation();
this.log.debug('Simulation restart after resize', event);
}
/**
* After the component is initialized create the Force simulation
* The list of devices, hosts and links will not have been receieved back
* from the WebSocket yet as this time - they will be updated later through
* ngOnChanges()
*/
ngOnInit() {
// Receiving an initialized simulated graph from our custom d3 service
this.graph = new ForceDirectedGraph(SVGCANVAS, this.log);
/** Binding change detection check on each tick
* This along with an onPush change detection strategy should enforce
* checking only when relevant! This improves scripting computation
* duration in a couple of tests I've made, consistently. Also, it makes
* sense to avoid unnecessary checks when we are dealing only with
* simulations data binding.
*/
this.graph.ticker.subscribe((simulation) => {
// this.log.debug("Force simulation has ticked. Alpha",
// Math.round(simulation.alpha() * 1000) / 1000);
this.ref.markForCheck();
});
this.log.debug('ForceSvgComponent initialized - waiting for nodes and links');
}
/**
* When any one of the inputs get changed by a containing component, this
* gets called automatically. In addition this is called manually by
* topology.service when a response is received from the WebSocket from the
* server
*
* The Devices, Hosts and SubRegions are all added to the Node list for the simulation
* The Links are added to the Link list of the simulation.
* Before they are added the Links are associated with Nodes based on their endPt
*
* @param changes - a list of changed @Input(s)
*/
ngOnChanges(changes: SimpleChanges) {
if (changes['regionData']) {
const devices: Device[] =
changes['regionData'].currentValue.devices[this.visibleLayerIdx()];
const hosts: Host[] =
changes['regionData'].currentValue.hosts[this.visibleLayerIdx()];
const subRegions: SubRegion[] = changes['regionData'].currentValue.subRegion;
this.graph.nodes = [];
if (devices) {
this.graph.nodes = devices;
}
if (hosts) {
this.graph.nodes = this.graph.nodes.concat(hosts);
}
if (subRegions) {
this.graph.nodes = this.graph.nodes.concat(subRegions);
}
this.graph.nodes.forEach((n) => this.fixPosition(n));
// Associate the endpoints of each link with a real node
this.graph.links = [];
for (const linkIdx of Object.keys(this.regionData.links)) {
const link = this.regionData.links[linkIdx];
const epA = ForceSvgComponent.extractNodeName(link.epA, link.portA);
if (!this.graph.nodes.find((node) => node.id === epA)) {
this.log.error('ngOnChange Could not find endpoint A', epA, 'for', link);
continue;
}
const epB = ForceSvgComponent.extractNodeName(
link.epB, link.portB);
if (!this.graph.nodes.find((node) => node.id === epB)) {
this.log.error('ngOnChange Could not find endpoint B', epB, 'for', link);
continue;
}
this.regionData.links[linkIdx].source =
this.graph.nodes.find((node) =>
node.id === epA);
this.regionData.links[linkIdx].target =
this.graph.nodes.find((node) =>
node.id === epB);
this.regionData.links[linkIdx].index = Number(linkIdx);
}
this.graph.links = this.regionData.links;
if (this.graph.nodes.length > 0) {
this.graph.reinitSimulation();
}
this.log.debug('ForceSvgComponent input changed',
this.graph.nodes.length, 'nodes,', this.graph.links.length, 'links');
if (!this.viewInitialized) {
this.viewInitialized = true;
if (this.showAlarms) {
this.wss.sendEvent('alarmTopovDisplayStart', {});
}
}
}
if (changes['showAlarms'] && this.viewInitialized) {
if (this.showAlarms) {
this.wss.sendEvent('alarmTopovDisplayStart', {});
} else {
this.wss.sendEvent('alarmTopovDisplayStop', {});
this.cancelAllDeviceHighlightsNow();
}
}
}
ngOnDestroy(): void {
if (this.showAlarms) {
this.wss.sendEvent('alarmTopovDisplayStop', {});
this.cancelAllDeviceHighlightsNow();
}
this.viewInitialized = false;
}
/**
* If instance has a value then mute colors of devices not connected to it
* Otherwise if instance does not have a value unmute all
* @param instanceName name of the selected instance
*/
changeInstSelection(instanceName: string) {
this.log.debug('Mastership changed', instanceName);
this.devices.filter((d) => d.device.master !== instanceName)
.forEach((d) => {
const isMuted = Boolean(instanceName);
d.ngOnChanges({'colorMuted': new SimpleChange(!isMuted, isMuted, true)});
}
);
}
/**
* If a node has a fixed location then assign it to fx and fy so
* that it doesn't get affected by forces
* @param graphNode The node whose location should be processed
*/
private fixPosition(graphNode: Node): void {
const loc: Location = <Location>graphNode['location'];
const props: DeviceProps = <DeviceProps>graphNode['props'];
const metaUi = <MetaUi>graphNode['metaUi'];
if (loc && loc.locType === LocationType.GEO) {
const position: MetaUi =
ZoomUtils.convertGeoToCanvas(
<LocMeta>{lng: loc.longOrX, lat: loc.latOrY});
graphNode.fx = position.x;
graphNode.fy = position.y;
this.log.debug('Found node', graphNode.id, 'with', loc.locType);
} else if (loc && loc.locType === LocationType.GRID) {
graphNode.fx = loc.longOrX;
graphNode.fy = loc.latOrY;
this.log.debug('Found node', graphNode.id, 'with', loc.locType);
} else if (props && props.locType === LocationType.NONE && metaUi) {
graphNode.fx = metaUi.x;
graphNode.fy = metaUi.y;
this.log.debug('Found node', graphNode.id, 'with locType=none and metaUi');
} else {
graphNode.fx = null;
graphNode.fy = null;
}
}
/**
* Get the index of LayerType so it can drive the visibility of nodes and
* hosts on layers
*/
visibleLayerIdx(): number {
const layerKeys: string[] = Object.keys(LayerType);
for (const idx in layerKeys) {
if (LayerType[layerKeys[idx]] === this.visibleLayer) {
return Number(idx);
}
}
return -1;
}
selectLink(link: RegionLink): void {
this.selectedLink = link;
this.linkSelected.emit(link);
}
/**
* Iterate through all hosts and devices and links to deselect the previously selected
* node. The emit an event to the parent that lets it know the selection has
* changed.
*
* This function collates all of the nodes that have been selected and passes
* a collection of nodes up to the topology component
*
* @param selectedNode the newly selected node
*/
updateSelected(selectedNode: SelectedEvent): void {
this.log.debug('Node or link ',
selectedNode.uiElement ? selectedNode.uiElement.id : '--',
selectedNode.deselecting ? 'deselected' : 'selected',
selectedNode.isShift ? 'Multiple' : '');
if (selectedNode.isShift && selectedNode.deselecting) {
const idx = this.selectedNodes.findIndex((n) =>
n.id === selectedNode.uiElement.id
);
this.selectedNodes.splice(idx, 1);
this.log.debug('Removed node', idx);
} else if (selectedNode.isShift) {
this.selectedNodes.push(selectedNode.uiElement);
} else if (selectedNode.deselecting) {
this.devices
.forEach((d) => d.deselect());
this.hosts
.forEach((h) => h.deselect());
this.links
.forEach((l) => l.deselect());
this.selectedNodes = [];
} else {
const selNodeId = selectedNode.uiElement.id;
// Otherwise if shift was not pressed deselect previous
this.devices
.filter((d) => d.device.id !== selNodeId)
.forEach((d) => d.deselect());
this.hosts
.filter((h) => h.host.id !== selNodeId)
.forEach((h) => h.deselect());
this.links
.filter((l) => l.link.id !== selNodeId)
.forEach((l) => l.deselect());
this.selectedNodes = [selectedNode.uiElement];
}
// Push the changes back up to parent (Topology Component)
this.selectedNodeEvent.emit(this.selectedNodes);
}
/**
* We want to filter links to show only those not related to hosts if the
* 'showHosts' flag has been switched off. If 'showHosts' is true, then
* display all links.
*/
filteredLinks(): Link[] {
return this.regionData.links.filter((h) =>
this.showHosts ||
((<Host>h.source).nodeType !== 'host' &&
(<Host>h.target).nodeType !== 'host'));
}
/**
* When changes happen in the model, then model events are sent up through the
* Web Socket
* @param type - the type of the change
* @param memo - a qualifier on the type
* @param subject - the item that the update is for
* @param data - the new definition of the item
*/
handleModelEvent(type: ModelEventType, memo: ModelEventMemo, subject: string, data: UiElement): void {
switch (type) {
case ModelEventType.DEVICE_ADDED_OR_UPDATED:
if (memo === ModelEventMemo.ADDED) {
this.fixPosition(<Device>data);
this.graph.nodes.push(<Device>data);
this.regionData.devices[this.visibleLayerIdx()].push(<Device>data);
this.log.debug('Device added', (<Device>data).id);
} else if (memo === ModelEventMemo.UPDATED) {
const oldDevice: Device =
this.regionData.devices[this.visibleLayerIdx()]
.find((d) => d.id === subject);
const changes = ForceSvgComponent.updateObject(oldDevice, <Device>data);
if (changes.numChanges > 0) {
this.log.debug('Device ', oldDevice.id, memo, ' - ', changes, 'changes');
if (changes.locationChanged) {
this.fixPosition(oldDevice);
}
const svgDevice: DeviceNodeSvgComponent =
this.devices.find((svgdevice) => svgdevice.device.id === subject);
svgDevice.ngOnChanges({'device':
new SimpleChange(<Device>{}, oldDevice, true)
});
}
} else {
this.log.warn('Device ', memo, ' - not yet implemented', data);
}
break;
case ModelEventType.HOST_ADDED_OR_UPDATED:
if (memo === ModelEventMemo.ADDED) {
this.fixPosition(<Host>data);
this.graph.nodes.push(<Host>data);
this.regionData.hosts[this.visibleLayerIdx()].push(<Host>data);
this.log.debug('Host added', (<Host>data).id);
} else if (memo === ModelEventMemo.UPDATED) {
const oldHost: Host = this.regionData.hosts[this.visibleLayerIdx()]
.find((h) => h.id === subject);
const changes = ForceSvgComponent.updateObject(oldHost, <Host>data);
if (changes.numChanges > 0) {
this.log.debug('Host ', oldHost.id, memo, ' - ', changes, 'changes');
if (changes.locationChanged) {
this.fixPosition(oldHost);
}
}
} else {
this.log.warn('Host change', memo, ' - unexpected');
}
break;
case ModelEventType.DEVICE_REMOVED:
if (memo === ModelEventMemo.REMOVED || memo === undefined) {
const removeIdx: number =
this.regionData.devices[this.visibleLayerIdx()]
.findIndex((d) => d.id === subject);
this.regionData.devices[this.visibleLayerIdx()].splice(removeIdx, 1);
this.removeRelatedLinks(subject);
this.log.debug('Device ', subject, 'removed. Links', this.regionData.links);
} else {
this.log.warn('Device removed - unexpected memo', memo);
}
break;
case ModelEventType.HOST_REMOVED:
if (memo === ModelEventMemo.REMOVED || memo === undefined) {
const removeIdx: number =
this.regionData.hosts[this.visibleLayerIdx()]
.findIndex((h) => h.id === subject);
this.regionData.hosts[this.visibleLayerIdx()].splice(removeIdx, 1);
this.removeRelatedLinks(subject);
this.log.debug('Host ', subject, 'removed');
} else {
this.log.warn('Host removed - unexpected memo', memo);
}
break;
case ModelEventType.LINK_ADDED_OR_UPDATED:
if (memo === ModelEventMemo.ADDED &&
this.regionData.links.findIndex((l) => l.id === subject) === -1) {
const newLink = <RegionLink>data;
const epA = ForceSvgComponent.extractNodeName(
newLink.epA, newLink.portA);
if (!this.graph.nodes.find((node) => node.id === epA)) {
this.log.error('Could not find endpoint A', epA, 'of', newLink);
break;
}
const epB = ForceSvgComponent.extractNodeName(
newLink.epB, newLink.portB);
if (!this.graph.nodes.find((node) => node.id === epB)) {
this.log.error('Could not find endpoint B', epB, 'of link', newLink);
break;
}
const listLen = this.regionData.links.push(<RegionLink>data);
this.regionData.links[listLen - 1].source =
this.graph.nodes.find((node) => node.id === epA);
this.regionData.links[listLen - 1].target =
this.graph.nodes.find((node) => node.id === epB);
this.log.debug('Link added', subject);
} else if (memo === ModelEventMemo.UPDATED) {
const oldLink = this.regionData.links.find((l) => l.id === subject);
const changes = ForceSvgComponent.updateObject(oldLink, <RegionLink>data);
this.log.debug('Link ', subject, '. Updated', changes, 'items');
} else {
this.log.warn('Link event ignored', subject, data);
}
break;
case ModelEventType.LINK_REMOVED:
if (memo === ModelEventMemo.REMOVED) {
const removeIdx = this.regionData.links.findIndex((l) => l.id === subject);
this.regionData.links.splice(removeIdx, 1);
this.log.debug('Link ', subject, 'removed');
}
break;
default:
this.log.error('Unexpected model event', type, 'for', subject, 'Data', data);
}
this.graph.links = this.regionData.links;
this.graph.reinitSimulation();
}
private removeRelatedLinks(subject: string) {
const len = this.regionData.links.length;
for (let i = 0; i < len; i++) {
const linkIdx = this.regionData.links.findIndex((l) =>
(ForceSvgComponent.extractNodeName(l.epA, l.portA) === subject ||
ForceSvgComponent.extractNodeName(l.epB, l.portB) === subject));
if (linkIdx >= 0) {
this.regionData.links.splice(linkIdx, 1);
this.log.debug('Link ', linkIdx, 'removed on attempt', i);
}
}
}
/**
* When traffic monitoring is turned on (A key) highlights will be sent back
* from the WebSocket through the Traffic Service
* Also handles Intent highlights in case one is selected
* @param devices - an array of device highlights
* @param hosts - an array of host highlights
* @param links - an array of link highlights
*/
handleHighlights(devices: DeviceHighlight[], hosts: HostHighlight[], links: LinkHighlight[], fadeMs: number = 0): void {
if (devices.length > 0) {
this.log.debug(devices.length, 'Devices highlighted');
devices.forEach((dh: DeviceHighlight) => {
this.devices.forEach((d: DeviceNodeSvgComponent) => {
if (d.device.id === dh.id) {
d.badge = dh.badge;
this.ref.markForCheck(); // Forces ngOnChange in the DeviceSvgComponent
this.log.debug('Highlighting device', dh.id);
}
});
});
}
if (hosts.length > 0) {
this.log.debug(hosts.length, 'Hosts highlighted');
hosts.forEach((hh: HostHighlight) => {
this.hosts.forEach((h) => {
if (h.host.id === hh.id) {
h.badge = hh.badge;
this.ref.markForCheck(); // Forces ngOnChange in the HostSvgComponent
this.log.debug('Highlighting host', hh.id);
}
});
});
}
if (links.length > 0) {
this.log.debug(links.length, 'Links highlighted');
links.forEach((lh: LinkHighlight) => {
if (fadeMs > 0) {
lh.fadems = fadeMs;
}
this.linksHighlighted.set(Link.linkIdFromShowHighlights(lh.id), lh);
});
this.ref.detectChanges(); // Forces ngOnChange in the LinkSvgComponent
}
}
cancelAllHostHighlightsNow() {
this.hosts.forEach((host: HostNodeSvgComponent) => {
host.badge = undefined;
this.ref.markForCheck(); // Forces ngOnChange in the HostSvgComponent
});
}
cancelAllDeviceHighlightsNow() {
this.devices.forEach((device: DeviceNodeSvgComponent) => {
device.badge = undefined;
this.ref.markForCheck(); // Forces ngOnChange in the DeviceSvgComponent
});
}
cancelAllLinkHighlightsNow() {
this.links.forEach((link: LinkSvgComponent) => {
link.linkHighlight = <LinkHighlight>{};
this.ref.markForCheck(); // Forces ngOnChange in the LinkSvgComponent
});
}
/**
* As nodes are dragged around the graph, their new location should be sent
* back to server
* @param klass The class of node e.g. 'host' or 'device'
* @param id - the ID of the node
* @param newLocation - the new Location of the node
*/
nodeMoved(klass: string, id: string, newLocation: MetaUi) {
this.wss.sendEvent('updateMeta2', <UpdateMeta>{
id: id,
class: klass,
memento: newLocation
});
this.log.debug(klass, id, 'has been moved to', newLocation);
}
/**
* If any nodes with fixed positions had been dragged out of place
* then put back where they belong
* If there are some devices selected reset only these
*/
resetNodeLocations(): number {
let numbernodes = 0;
if (this.selectedNodes.length > 0) {
this.devices
.filter((d) => this.selectedNodes.some((s) => s.id === d.device.id))
.forEach((dev) => {
Node.resetNodeLocation(<Node>dev.device);
numbernodes++;
});
this.hosts
.filter((h) => this.selectedNodes.some((s) => s.id === h.host.id))
.forEach((h) => {
Host.resetNodeLocation(<Host>h.host);
numbernodes++;
});
} else {
this.devices.forEach((dev) => {
Node.resetNodeLocation(<Node>dev.device);
numbernodes++;
});
this.hosts.forEach((h) => {
Host.resetNodeLocation(<Host>h.host);
numbernodes++;
});
}
this.graph.reinitSimulation();
return numbernodes;
}
/**
* Toggle floating nodes between unpinned and frozen
* There may be frozen and unpinned in the selection
*
* If there are nodes selected toggle only these
*/
unpinOrFreezeNodes(freeze: boolean): number {
let numbernodes = 0;
if (this.selectedNodes.length > 0) {
this.devices
.filter((d) => this.selectedNodes.some((s) => s.id === d.device.id))
.forEach((d) => {
Node.unpinOrFreezeNode(<Node>d.device, freeze);
numbernodes++;
});
this.hosts
.filter((h) => this.selectedNodes.some((s) => s.id === h.host.id))
.forEach((h) => {
Node.unpinOrFreezeNode(<Node>h.host, freeze);
numbernodes++;
});
} else {
this.devices.forEach((d) => {
Node.unpinOrFreezeNode(<Node>d.device, freeze);
numbernodes++;
});
this.hosts.forEach((h) => {
Node.unpinOrFreezeNode(<Node>h.host, freeze);
numbernodes++;
});
}
this.graph.reinitSimulation();
return numbernodes;
}
} | 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::ECR::PublicRepository`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-publicrepository.html
* @external
*/
export interface CfnPublicRepositoryProps {
/**
* `AWS::ECR::PublicRepository.RepositoryCatalogData`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-publicrepository.html#cfn-ecr-publicrepository-repositorycatalogdata
* @external
*/
readonly repositoryCatalogData?: any | cdk.IResolvable;
/**
* `AWS::ECR::PublicRepository.RepositoryName`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-publicrepository.html#cfn-ecr-publicrepository-repositoryname
* @external
*/
readonly repositoryName?: string;
/**
* `AWS::ECR::PublicRepository.RepositoryPolicyText`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-publicrepository.html#cfn-ecr-publicrepository-repositorypolicytext
* @external
*/
readonly repositoryPolicyText?: any | cdk.IResolvable;
}
/**
* A CloudFormation `AWS::ECR::PublicRepository`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-publicrepository.html
* @external
* @cloudformationResource AWS::ECR::PublicRepository
*/
export declare class CfnPublicRepository extends cdk.CfnResource implements cdk.IInspectable {
/**
* The CloudFormation resource type name for this resource class.
*
* @external
*/
static readonly CFN_RESOURCE_TYPE_NAME = "AWS::ECR::PublicRepository";
/**
* 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): CfnPublicRepository;
/**
* @external
* @cloudformationAttribute Arn
*/
readonly attrArn: string;
/**
* `AWS::ECR::PublicRepository.RepositoryCatalogData`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-publicrepository.html#cfn-ecr-publicrepository-repositorycatalogdata
* @external
*/
repositoryCatalogData: any | cdk.IResolvable | undefined;
/**
* `AWS::ECR::PublicRepository.RepositoryName`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-publicrepository.html#cfn-ecr-publicrepository-repositoryname
* @external
*/
repositoryName: string | undefined;
/**
* `AWS::ECR::PublicRepository.RepositoryPolicyText`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-publicrepository.html#cfn-ecr-publicrepository-repositorypolicytext
* @external
*/
repositoryPolicyText: any | cdk.IResolvable | undefined;
/**
* Create a new `AWS::ECR::PublicRepository`.
*
* @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?: CfnPublicRepositoryProps);
/**
* (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;
};
}
/**
* Properties for defining a `AWS::ECR::Repository`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html
* @external
*/
export interface CfnRepositoryProps {
/**
* `AWS::ECR::Repository.ImageScanningConfiguration`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-imagescanningconfiguration
* @external
*/
readonly imageScanningConfiguration?: any | cdk.IResolvable;
/**
* `AWS::ECR::Repository.ImageTagMutability`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-imagetagmutability
* @external
*/
readonly imageTagMutability?: string;
/**
* `AWS::ECR::Repository.LifecyclePolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-lifecyclepolicy
* @external
*/
readonly lifecyclePolicy?: CfnRepository.LifecyclePolicyProperty | cdk.IResolvable;
/**
* `AWS::ECR::Repository.RepositoryName`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-repositoryname
* @external
*/
readonly repositoryName?: string;
/**
* `AWS::ECR::Repository.RepositoryPolicyText`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-repositorypolicytext
* @external
*/
readonly repositoryPolicyText?: any | cdk.IResolvable;
/**
* `AWS::ECR::Repository.Tags`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-tags
* @external
*/
readonly tags?: cdk.CfnTag[];
}
/**
* A CloudFormation `AWS::ECR::Repository`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html
* @external
* @cloudformationResource AWS::ECR::Repository
*/
export declare class CfnRepository extends cdk.CfnResource implements cdk.IInspectable {
/**
* The CloudFormation resource type name for this resource class.
*
* @external
*/
static readonly CFN_RESOURCE_TYPE_NAME = "AWS::ECR::Repository";
/**
* 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): CfnRepository;
/**
* @external
* @cloudformationAttribute Arn
*/
readonly attrArn: string;
/**
* `AWS::ECR::Repository.ImageScanningConfiguration`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-imagescanningconfiguration
* @external
*/
imageScanningConfiguration: any | cdk.IResolvable | undefined;
/**
* `AWS::ECR::Repository.ImageTagMutability`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-imagetagmutability
* @external
*/
imageTagMutability: string | undefined;
/**
* `AWS::ECR::Repository.LifecyclePolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-lifecyclepolicy
* @external
*/
lifecyclePolicy: CfnRepository.LifecyclePolicyProperty | cdk.IResolvable | undefined;
/**
* `AWS::ECR::Repository.RepositoryName`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-repositoryname
* @external
*/
repositoryName: string | undefined;
/**
* `AWS::ECR::Repository.RepositoryPolicyText`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-repositorypolicytext
* @external
*/
repositoryPolicyText: any | cdk.IResolvable | undefined;
/**
* `AWS::ECR::Repository.Tags`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-tags
* @external
*/
readonly tags: cdk.TagManager;
/**
* Create a new `AWS::ECR::Repository`.
*
* @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?: CfnRepositoryProps);
/**
* (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::ECR::Repository`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html
* @external
* @cloudformationResource AWS::ECR::Repository
*/
export declare namespace CfnRepository {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecr-repository-lifecyclepolicy.html
* @external
*/
interface LifecyclePolicyProperty {
/**
* `CfnRepository.LifecyclePolicyProperty.LifecyclePolicyText`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecr-repository-lifecyclepolicy.html#cfn-ecr-repository-lifecyclepolicy-lifecyclepolicytext
* @external
*/
readonly lifecyclePolicyText?: string;
/**
* `CfnRepository.LifecyclePolicyProperty.RegistryId`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecr-repository-lifecyclepolicy.html#cfn-ecr-repository-lifecyclepolicy-registryid
* @external
*/
readonly registryId?: string;
}
} | the_stack |
import { truncate, truncateSync } from "fs";
import * as jsesc from "jsesc";
import { spawn } from "process-promises";
import {
CancellationToken,
CodeActionContext,
CodeActionProvider,
Command,
commands,
Diagnostic,
DiagnosticCollection,
DiagnosticSeverity,
Disposable,
ExtensionContext,
languages,
OutputChannel,
Position,
Range,
Selection,
TextDocument,
TextEditorRevealType,
Uri,
window,
workspace,
WorkspaceEdit
} from "vscode";
import { Utils, IPredicate } from "../utils/utils";
// import { basename, extname, resolve } from "path";
import * as find from "find";
import * as path from "path";
export enum RunTrigger {
onType,
onSave,
never
}
export default class PrologLinter implements CodeActionProvider {
private commandAddDynamic: Disposable;
private commandAddDynamicId: string;
private commandAddUseModule: Disposable;
private commandAddUseModuleId: string;
private commandExportPredicate: Disposable;
private commandExportPredicateId: string;
private diagnosticCollection: DiagnosticCollection;
private diagnostics: { [docName: string]: Diagnostic[] } = {};
private filePathIds: { [id: string]: string } = {};
private sortedDiagIndex: { [docName: string]: number[] } = {};
private swiRegex = /([^:]+?):\s*(.+?):(\d+):((\d+):)?((\d+):)?\s*([\s\S]*)/;
private executable: string;
private trigger: RunTrigger;
private timer: NodeJS.Timer = null;
private delay: number;
private documentListener: Disposable;
private openDocumentListener: Disposable;
private outputChannel: OutputChannel = null;
private enableOutput: boolean = false;
constructor(private context: ExtensionContext) {
this.executable = null;
this.commandAddDynamicId = "prolog.addDynamicDirective";
this.commandAddDynamic = commands.registerCommand(
this.commandAddDynamicId,
this.addDynamicDirective,
this
);
this.commandAddUseModuleId = "prolog.addUseModule";
this.commandAddUseModule = commands.registerCommand(
this.commandAddUseModuleId,
this.addUseModule,
this
);
this.commandExportPredicateId = "prolog.exportPredicate";
this.commandExportPredicate = commands.registerCommand(
this.commandExportPredicateId,
this.exportPredicateUnderCursor,
this
);
this.enableOutput = workspace.getConfiguration("prolog")
.get<boolean>("linter.enableMsgInOutput");
}
private getDirectiveLines(
doc: TextDocument,
declarativePredicate: string,
range: Range
): number[] {
let textlines: string[] = doc.getText().split("\n");
let re = new RegExp("^\\s*:-\\s+\\(?\\s*" + declarativePredicate + "\\b");
let lines: number[] = [];
let line = 0;
while (line < textlines.length) {
if (re.test(textlines[line])) {
lines = lines.concat(line);
}
line++;
}
if (lines.length > 0) {
return lines;
}
line = -1;
textlines.filter((item, index) => {
if (/^\s*:-/.test(item)) {
line = index;
return true;
}
});
while (line >= 0 && !/.+\.(\s*%.*)*/.test(textlines[line])) {
line++;
}
if (line >= 0 && line < range.start.line) {
return [++line];
}
line = 0;
let inComment = /\s*\/\*/.test(textlines[0]);
while (inComment) {
if (/\*\//.test(textlines[line])) {
inComment = false;
line++;
break;
}
line++;
}
return [line];
}
private addDynamicDirective(
doc: TextDocument,
predicate: string,
uri: Uri,
range: Range
): Thenable<boolean> {
let edit = new WorkspaceEdit();
let line = this.getDirectiveLines(doc, "dynamic", range)[0];
let text = doc.lineAt(line).text;
let pos: Position;
if (/:-\s+\(?dynamic/.test(text)) {
let startChar = text.indexOf("dynamic") + 7;
pos = new Position(line, startChar);
edit.insert(uri, pos, " " + predicate + ",");
} else {
pos = new Position(line, 0);
edit.insert(uri, pos, ":- dynamic " + predicate + ".\n");
}
let result: Thenable<boolean> = null;
try {
result = workspace.applyEdit(edit);
} catch (e) {
console.log("Error in add dynamic declaration: " + e);
}
return result;
}
private addUseModule(
doc: TextDocument,
predicate: string,
module: string,
uri: Uri,
range: Range
): Thenable<boolean> {
let edit = new WorkspaceEdit();
let lines = this.getDirectiveLines(doc, "use_module", range);
let pred: string = predicate.match(/(.+)\/\d+/)[1];
let re = new RegExp("^:-\\s+use_module\\s*\\(\\s*.+\\b" + module + "\\b");
let directiveLine: number = -1;
let pos: Position;
lines.forEach(line => {
if (re.test(doc.lineAt(line).text)) {
directiveLine = line;
}
});
if (directiveLine >= 0) {
let line = directiveLine;
while (doc.lineAt(line).text.indexOf("[") < 0) line++;
let startChar = doc.lineAt(line).text.indexOf("[");
pos = new Position(line, startChar + 1);
edit.insert(uri, pos, predicate + ",");
} else {
pos = new Position(lines[lines.length - 1], 0);
edit.insert(
uri,
pos,
`:- use_module(library(${module}), [${predicate}]).\n`
);
}
let result: Thenable<boolean> = null;
try {
result = workspace.applyEdit(edit);
} catch (e) {
console.log("Error in add dynamic declaration: " + e);
}
return result;
}
provideCodeActions(
document: TextDocument,
range: Range,
context: CodeActionContext,
token: CancellationToken
): Command[] | Thenable<Command[]> {
let codeActions: Command[] = [];
context.diagnostics.forEach(diagnostic => {
let regex = /Predicate (.+) not defined/;
let match = diagnostic.message.match(regex);
if (match[1]) {
let pred = match[1];
let modules = Utils.getPredModules(pred);
if (modules.length > 0) {
modules.forEach(module => {
codeActions.push({
title:
"Add ':- use_module(library(" + module + "), [" + pred + "]).'",
command: this.commandAddUseModuleId,
arguments: [
document,
pred,
module,
document.uri,
diagnostic.range
]
});
});
}
match = document.getText().match(/:-\s*module\((\w+),/);
let module: string = "";
if (match) {
module = match[1];
}
if (pred.indexOf(":") > -1) {
let [mod, pred1] = pred.split(":");
if (mod === module) {
pred = pred1;
}
}
codeActions.push({
title: "Add ':- dynamic " + pred + ".'",
command: this.commandAddDynamicId,
arguments: [document, pred, document.uri, diagnostic.range]
});
}
});
return codeActions;
}
private parseIssue(issue: string) {
let match = issue.match(this.swiRegex);
if (match == null) return null;
let fileName = this.filePathIds[match[2]]
? this.filePathIds[match[2]]
: match[2];
let severity: DiagnosticSeverity;
if (match[1] == "ERROR") severity = DiagnosticSeverity.Error;
else if (match[1] == "Warning") severity = DiagnosticSeverity.Warning;
let line = parseInt(match[3]) - 1;
// move up to above line if the line to mark error is empty
// line = line < 0 ? 0 : line;
let fromCol = match[5] ? parseInt(match[5]) : 0;
fromCol = fromCol < 0 ? 0 : fromCol;
let toCol = match[7] ? parseInt(match[7]) : 200;
let fromPos = new Position(line, fromCol);
let toPos = new Position(line, toCol);
let range = new Range(fromPos, toPos);
let errMsg = match[8];
let diag = new Diagnostic(range, errMsg, severity);
if (diag) {
if (!this.diagnostics[fileName]) {
this.diagnostics[fileName] = [diag];
} else {
this.diagnostics[fileName].push(diag);
}
}
}
private doPlint(textDocument: TextDocument) {
if (textDocument.languageId != "prolog") {
return;
}
this.diagnostics = {};
this.sortedDiagIndex = {};
this.diagnosticCollection.delete(textDocument.uri);
let options = workspace.rootPath
? { cwd: workspace.rootPath }
: undefined;
let args: string[] = [],
goals: string = "";
let lineErr: string = "";
let docTxt = textDocument.getText();
let docTxtEsced = jsesc(docTxt, { quotes: "double" });
let fname = jsesc(path.resolve(textDocument.fileName));
switch (Utils.DIALECT) {
case "swi":
if (this.trigger === RunTrigger.onSave) {
args = ["-g", "halt", fname];
}
if (this.trigger === RunTrigger.onType) {
args = ["-q"];
goals = `
open_string("${docTxtEsced}", S),
load_files('${fname}', [stream(S),if(true)]).
list_undefined.
`;
}
break;
case "ecl":
let dir = jsesc(path.resolve(`${this.context.extensionPath}/out/src/features`));
if (this.trigger === RunTrigger.onSave) {
const fdir = path.dirname(fname);
const file = path.basename(fname);
goals = `(cd("${dir}"),
use_module('load_modules'),
cd("${fdir}"),
load_modules_from_file('${file}'),
compile('${file}', [debug:off]),halt)`;
args = ["-e", goals];
}
if (this.trigger === RunTrigger.onType) {
goals = `(cd("${dir}"),
use_module(load_modules),
load_modules_from_text("${docTxtEsced}"),
open(string("${docTxtEsced}"), read, S),
compile(stream(S), [debug:off]),
close(S),halt)`;
}
default:
break;
}
spawn(this.executable, args, options)
.on("process", process => {
if (process.pid) {
if (this.trigger === RunTrigger.onType) {
process.stdin.write(goals);
process.stdin.end();
}
if (this.enableOutput) {
this.outputChannel.clear();
}
}
})
.on("stdout", out => {
// console.log("lintout:" + out + "\n");
if (Utils.DIALECT === "ecl" && !/checking completed/.test(out)) {
if (/^File\s*/.test(out)) {
if (lineErr) {
this.parseIssue(lineErr + "\n");
lineErr = '';
}
let match = out.match(/File\s*([^,]+),.*line\s*(\d+):\s*(.*)/);
let fullName: string;
if (match[1] === "string") {
fullName = textDocument.fileName;
} else {
fullName = find.fileSync(
new RegExp(match[1]),
workspace.rootPath
)[0];
}
lineErr = "Warning:" + fullName + ":" + match[2] + ":" + match[3];
} else if (/^\|/.test(out)) {
lineErr += out;
} else if (/WARNING/.test(out) && this.enableOutput) {
this.outputMsg(out);
}
}
})
.on("stderr", (errStr: string) => {
// console.log("linterr: " + errStr);
switch (Utils.DIALECT) {
case "swi":
if (/which is referenced by/.test(errStr)) {
let regex = /Warning:\s*(.+),/;
let match = errStr.match(regex);
lineErr = " Predicate " + match[1] + " not defined";
} else if (/clause of /.test(errStr)) {
let regex = /^(Warning:\s*(.+?):)(\d+):(\d+)?/;
let match = errStr.match(regex);
// let fileName = match[2];
let line = parseInt(match[3]);
let char = match[4] ? parseInt(match[4]) : 0;
let rangeStr = line + ":" + char + ":200: ";
let lineMsg = match[1] + rangeStr + lineErr;
this.parseIssue(lineMsg + "\n");
} else if (/:\s*$/.test(errStr)) {
lineErr = errStr;
} else {
if (errStr.startsWith("ERROR") || errStr.startsWith("Warning")) {
lineErr = errStr;
} else {
lineErr = lineErr.concat(errStr);
}
this.parseIssue(lineErr + "\n");
lineErr = '';
}
break;
case "ecl":
if (this.enableOutput) {
this.outputChannel.clear();
}
if (/^[fF]ile|^string stream|^Stream/.test(errStr)) {
if (lineErr !== '') {
this.parseIssue(lineErr + "\n");
if (this.enableOutput) {
this.outputMsg(lineErr);
}
lineErr = '';
}
let fullName: string, line: string, msg: string;
let match = errStr.match(
/[fF]ile\s*([^,]+),\s*line\s*(\d+):\s*(.*)/
);
if (match) {
fullName = find.fileSync(
new RegExp(match[1]),
workspace.rootPath
)[0];
line = match[2];
msg = match[3];
} else {
fullName = textDocument.fileName;
match = errStr.match(/line\s*(\d+):\s*(.*)/);
if (!match) {
match = errStr.match(/:(\d+):\s*(.*)/);
}
line = match[1];
msg = match[2];
}
const msgType = /error:|[sS]tream/.test(lineErr) ? "ERROR:" : "WARNING:";
lineErr = msgType + fullName + ":" + line + ":" + msg;
} else if (!/^\s*$/.test(errStr)) {
lineErr += "\n" + errStr;
}
default:
break;
}
})
.then(result => {
// console.log('exit code:' + result.exitCode);
if (lineErr !== '') {
this.parseIssue(lineErr + "\n");
lineErr = '';
}
for (let doc in this.diagnostics) {
let index = this.diagnostics[doc]
.map((diag, i) => {
return [diag.range.start.line, i];
})
.sort((a, b) => {
return a[0] - b[0];
});
this.sortedDiagIndex[doc] = index.map(item => {
return item[1];
});
this.diagnosticCollection.set(Uri.file(doc), this.diagnostics[doc]);
}
if (this.enableOutput) {
this.outputChannel.clear();
}
for (let doc in this.sortedDiagIndex) {
let si = this.sortedDiagIndex[doc];
for (let i = 0; i < si.length; i++) {
let diag = this.diagnostics[doc][si[i]];
let severity =
diag.severity === DiagnosticSeverity.Error ? "ERROR" : "Warning";
let msg = `${path.basename(doc)}:${diag.range.start.line +
1}:\t${severity}:\t${diag.message}\n`;
if (this.enableOutput) {
this.outputChannel.append(msg);
}
}
if (si.length > 0 && this.enableOutput) {
this.outputChannel.show(true);
}
}
})
.catch(error => {
let message: string = null;
if ((<any>error).code === "ENOENT") {
message =
"Cannot lint the prolog file. The Prolog executable was not found. Use the 'prolog.executablePath' setting to configure";
} else {
message = error.message
? error.message
: `Failed to run prolog executable using path: ${this
.executable}. Reason is unknown.`;
}
this.outputMsg(message);
});
}
private loadConfiguration(): void {
let section = workspace.getConfiguration("prolog");
if (section) {
this.executable = path.resolve(section.get<string>("executablePath", "swipl"));
if (Utils.LINTERTRIGGER === "onSave") {
this.trigger = RunTrigger.onSave;
} else if (Utils.LINTERTRIGGER === "onType") {
this.trigger = RunTrigger.onType;
} else {
this.trigger = RunTrigger.never;
}
if (this.documentListener) {
this.documentListener.dispose();
}
if (this.openDocumentListener) {
this.openDocumentListener.dispose();
}
}
this.openDocumentListener = workspace.onDidOpenTextDocument(e => {
this.triggerLinter(e);
});
if (this.trigger === RunTrigger.onType) {
this.delay = section.get<number>("linter.delay");
this.documentListener = workspace.onDidChangeTextDocument(e => {
this.triggerLinter(e.document);
});
} else {
if (this.timer) {
clearTimeout(this.timer);
}
this.documentListener = workspace.onDidSaveTextDocument(
this.doPlint,
this
);
}
workspace.textDocuments.forEach(this.triggerLinter, this);
}
private triggerLinter(textDocument: TextDocument) {
if (textDocument.languageId !== "prolog") {
return;
}
if (this.trigger === RunTrigger.onType) {
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
this.doPlint(textDocument);
}, this.delay);
} else if (this.trigger !== RunTrigger.never) {
this.doPlint(textDocument);
}
}
public activate(): void {
let subscriptions: Disposable[] = this.context.subscriptions;
this.diagnosticCollection = languages.createDiagnosticCollection();
workspace.onDidChangeConfiguration(
this.loadConfiguration,
this,
subscriptions
);
this.loadConfiguration();
if (this.outputChannel === null) {
this.outputChannel = window.createOutputChannel("PrologLinter");
this.outputChannel.clear();
}
if (this.trigger === RunTrigger.onSave) {
workspace.onDidOpenTextDocument(this.doPlint, this, subscriptions);
}
workspace.onDidCloseTextDocument(
textDocument => {
this.diagnosticCollection.delete(textDocument.uri);
},
null,
subscriptions
);
}
private outputMsg(msg: string) {
this.outputChannel.append(msg + "\n");
this.outputChannel.show(true);
}
private getClauseInfo(
doc: TextDocument,
pred: IPredicate
): [string, number] | null {
let docTxt = jsesc(doc.getText(), { quotes: "double" });
let input = `
clause_location(Pred) :-
open_string("${docTxt}", S),
load_files('${jsesc(doc.fileName)}', [module(user), stream(S), if(true)]),
close(S),
( functor(Pred, :, 2)
-> Pred1 = pred
; context_module(Mod),
Pred1 = Mod:Pred
),
clause(Pred1, _, R),
clause_property(R, file(File)),
clause_property(R, line_count(Line)), !,
format('File=~s;Line=~d~n', [File, Line]).
`;
let clauseInfo = Utils.execPrologSync(
["-q"],
input,
`clause_location(${pred.wholePred.split(":")[1]})`,
"true",
/File=(.+);Line=(\d+)/
);
return clauseInfo ? [clauseInfo[1], parseInt(clauseInfo[2])] : null;
}
public exportPredicateUnderCursor() {
if (Utils.DIALECT === "ecl") {
this.outputMsg("export helper only works for SWI-Prolog now.");
return;
}
let editor = window.activeTextEditor;
let doc = editor.document;
let docTxt = jsesc(doc.getText(), { quotes: "double" });
let pos = editor.selection.active;
let pred = Utils.getPredicateUnderCursor(doc, pos);
if (pred.arity < 0) {
this.outputMsg(`${pred.functor} is not a valid predicate to export.`);
return;
}
let clauseInfo = this.getClauseInfo(doc, pred);
if (clauseInfo == null) {
this.outputMsg(`${pred.wholePred} is not a valid predicate to export.`);
return;
}
if (clauseInfo[0] !== doc.fileName) {
this.outputMsg(`${pred.wholePred} is not defined in active source file.`);
return;
}
let input = `
rewrite_module_declaration(Module, PI) :-
setup_call_cleanup(
open_string("${docTxt}", S),
( read_term(S, Term, [term_position(Pos)]),
stream_position_data(line_count, Pos, Line),
stream_position_data(line_position, Pos, Start),
( Term=(:-module(Module1, Exports))
-> ( memberchk(PI, Exports)
-> ReTerm=none,
Action=none
; NewExp=[PI|Exports],
ReTerm=(:-module(Module1, NewExp)),
Action=replace
)
; ReTerm=(:-module(Module, [PI])),
Action=insert
),
format('Action=~s;Mod=~w;Line=~d;Start=~d;~n',
[Action, ReTerm, Line, Start])
),
close(S)
).
`;
let modname = path.basename(doc.fileName).split(".")[0];
let modDec = Utils.execPrologSync(
["-q"],
input,
`rewrite_module_declaration('${modname}', ${pred.pi.split(":")[1]})`,
"true",
/Action=(\w+);Mod=(.+);Line=(\d+);Start=(\d+)/
);
let action = modDec[1];
let edit = new WorkspaceEdit();
let lines = doc.getText().split("\n");
let newModStr = modDec[2].replace(":-", ":- ") + ".\n\n";
let modStartLine = parseInt(modDec[3]);
let modStartChar = parseInt(modDec[4]);
if (action === "insert") {
edit.insert(
Uri.file(doc.fileName),
new Position(modStartLine - 1, modStartChar),
newModStr
);
workspace.applyEdit(edit);
} else if (action === "replace") {
let modEndLine = parseInt(modDec[3]);
while (!/\.\s*$/.test(lines[modEndLine - 1])) modEndLine++;
let modEndChar = lines[modEndLine - 1].indexOf(".");
let modRange = new Range(
modStartLine - 1,
modStartChar,
modEndLine,
modEndChar + 1
);
edit.replace(Uri.file(doc.fileName), modRange, newModStr);
workspace.applyEdit(edit);
}
window
.showInformationMessage(
`'${pred.pi}' exported. Add structured comments to it?`,
"yes",
"no"
)
.then(answer => {
if (answer !== "yes") {
return;
}
// add comments
let comm = "%!\t" + pred.functor + "\n%\n%\n";
let newClauseInfo = this.getClauseInfo(doc, pred);
edit = new WorkspaceEdit();
edit.insert(
Uri.file(doc.fileName),
new Position(newClauseInfo[1] - 1, 0),
comm
);
workspace.applyEdit(edit);
});
}
public dispose(): void {
this.documentListener.dispose();
this.openDocumentListener.dispose();
this.diagnosticCollection.clear();
this.diagnosticCollection.dispose();
this.commandAddDynamic.dispose();
this.commandAddUseModule.dispose();
this.commandExportPredicate.dispose();
}
public nextErrLine() {
this.gotoErrLine(0);
}
public prevErrLine() {
this.gotoErrLine(1);
}
private gotoErrLine(direction: number) {
//direction: 0: next, 1: previous
const editor = window.activeTextEditor;
let diagnostics = this.diagnosticCollection.get(editor.document.uri);
if (!diagnostics || diagnostics.length == 0) {
this.outputMsg("No errors or warnings :)");
return;
}
this.outputChannel.clear();
const activeLine = editor.selection.active.line;
let position: Position, i: number;
let si = this.sortedDiagIndex[editor.document.uri.fsPath];
if (direction === 0) {
i = 0;
if (activeLine >= diagnostics[si[si.length - 1]].range.start.line) {
position = diagnostics[si[0]].range.start;
} else {
while (diagnostics[si[i]].range.start.line <= activeLine) {
i = i === si.length - 1 ? 0 : i + 1;
}
position = diagnostics[si[i]].range.start;
}
} else {
i = si.length - 1;
if (activeLine <= diagnostics[si[0]].range.start.line) {
position = diagnostics[si[i]].range.start;
} else {
while (diagnostics[si[i]].range.start.line >= activeLine) {
i = i === 0 ? si.length - 1 : i - 1;
}
position = diagnostics[si[i]].range.start;
}
}
editor.revealRange(diagnostics[si[i]].range, TextEditorRevealType.InCenter);
diagnostics.forEach(item => {
if (item.range.start.line === position.line) {
let severity =
item.severity === DiagnosticSeverity.Error
? "ERROR:\t\t"
: "Warning:\t";
this.outputChannel.append(severity + item.message + "\n");
}
});
editor.selection = new Selection(position, position);
this.outputChannel.show(true);
}
} | the_stack |
import { PartnerCard_artwork } from "__generated__/PartnerCard_artwork.graphql"
import { PartnerCardTestsQueryRawResponse } from "__generated__/PartnerCardTestsQuery.graphql"
// @ts-ignore
import { mount } from "enzyme"
import { GlobalStoreProvider } from "lib/store/GlobalStore"
import { flushPromiseQueue } from "lib/tests/flushPromiseQueue"
import { renderRelayTree } from "lib/tests/renderRelayTree"
import { Button, Sans, Theme } from "palette"
import React from "react"
import { Image } from "react-native"
import { graphql, RelayProp } from "react-relay"
import { PartnerCard, PartnerCardFragmentContainer } from "./PartnerCard"
jest.unmock("react-relay")
describe("PartnerCard", () => {
it("renders partner name correctly", () => {
const component = mount(
<GlobalStoreProvider>
<Theme>
<PartnerCard relay={{ environment: {} } as RelayProp} artwork={PartnerCardArtwork} />
</Theme>
</GlobalStoreProvider>
)
expect(component.find(Button).length).toEqual(1)
expect(component.text()).toContain(`Test Gallery`)
})
it("renders partner image", () => {
const component = mount(
<GlobalStoreProvider>
<Theme>
<PartnerCard relay={{ environment: {} } as RelayProp} artwork={PartnerCardArtwork} />
</Theme>
</GlobalStoreProvider>
)
expect(component.find(Image)).toHaveLength(1)
})
it("renders partner type", () => {
const component = mount(
<GlobalStoreProvider>
<Theme>
<PartnerCard relay={{ environment: {} } as RelayProp} artwork={PartnerCardArtwork} />
</Theme>
</GlobalStoreProvider>
)
expect(component.find(Sans).at(0).text()).toMatchInlineSnapshot(`"At gallery"`)
})
it("renders partner type correctly for institutional sellers", () => {
const PartnerCardArtworkInstitutionalSeller = {
...PartnerCardArtwork,
partner: {
...PartnerCardArtwork.partner!,
type: "Institutional Seller",
},
}
const component = mount(
<GlobalStoreProvider>
<Theme>
<PartnerCard relay={{ environment: {} } as RelayProp} artwork={PartnerCardArtworkInstitutionalSeller} />
</Theme>
</GlobalStoreProvider>
)
expect(component.find(Sans).at(0).text()).toMatchInlineSnapshot(`"At institution"`)
})
it("doesn't render partner type for partners that aren't institutions or galleries", () => {
const PartnerCardArtworkOtherType = {
...PartnerCardArtwork,
partner: {
...PartnerCardArtwork.partner!,
type: "Some Other Partner Type",
},
}
const component = mount(
<GlobalStoreProvider>
<Theme>
<PartnerCard relay={{ environment: {} } as RelayProp} artwork={PartnerCardArtworkOtherType} />
</Theme>
</GlobalStoreProvider>
)
expect(component.find(Sans).at(0).text()).not.toEqual("At institution")
expect(component.find(Sans).at(0).text()).not.toEqual("At gallery")
})
it("renders partner initials when no image is present", () => {
const PartnerCardArtworkWithoutImage = {
...PartnerCardArtwork,
partner: {
...PartnerCardArtwork.partner!,
profile: null,
},
}
const component = mount(
<GlobalStoreProvider>
<Theme>
<PartnerCard relay={{ environment: {} } as RelayProp} artwork={PartnerCardArtworkWithoutImage} />
</Theme>
</GlobalStoreProvider>
)
expect(component.find(Image)).toHaveLength(0)
expect(component.text()).toContain(`TG`)
})
it("truncates partner locations correctly", () => {
const component = mount(
<GlobalStoreProvider>
<Theme>
<PartnerCard relay={{ environment: {} } as RelayProp} artwork={PartnerCardArtwork} />
</Theme>
</GlobalStoreProvider>
)
expect(component.find(Button).length).toEqual(1)
expect(component.text()).toContain(`Miami, New York, +3 more`)
})
it("renders button text correctly", () => {
const component = mount(
<GlobalStoreProvider>
<Theme>
<PartnerCard relay={{ environment: {} } as RelayProp} artwork={PartnerCardArtwork} />
</Theme>
</GlobalStoreProvider>
)
expect(component.find(Button)).toHaveLength(1)
expect(component.find(Button).at(0).render().text()).toMatchInlineSnapshot(`"FollowingFollow"`)
})
it("does not render when the partner is an auction house", () => {
const PartnerCardArtworkAuctionHouse: PartnerCard_artwork = {
...PartnerCardArtwork,
partner: {
...PartnerCardArtwork.partner!,
type: "Auction House",
},
}
const component = mount(
<GlobalStoreProvider>
<Theme>
<PartnerCard relay={{ environment: {} } as RelayProp} artwork={PartnerCardArtworkAuctionHouse} />
</Theme>
</GlobalStoreProvider>
)
expect(component.html()).toBe(null)
})
it("does not render when the artwork is in a benefit or gallery auction", () => {
const PartnerCardArtworkAuction = {
...PartnerCardArtwork,
sale: {
isBenefit: true,
isGalleryAuction: true,
},
}
const component = mount(
<GlobalStoreProvider>
<Theme>
<PartnerCard relay={{ environment: {} } as RelayProp} artwork={PartnerCardArtworkAuction} />
</Theme>
</GlobalStoreProvider>
)
expect(component.html()).toBe(null)
})
it("does not render follow button when the partner has no profile info", () => {
const PartnerCardArtworkNoProfile = {
...PartnerCardArtwork,
partner: {
...PartnerCardArtwork.partner!,
profile: null,
},
}
const component = mount(
<GlobalStoreProvider>
<Theme>
<PartnerCard relay={{ environment: {} } as RelayProp} artwork={PartnerCardArtworkNoProfile} />
</Theme>
</GlobalStoreProvider>
)
expect(component.find(Button)).toHaveLength(0)
})
describe("Following a partner", () => {
const getWrapper = async ({ mockArtworkData, mockFollowResults }: any) => {
return await renderRelayTree({
Component: (props: any) => (
<GlobalStoreProvider>
<Theme>
<PartnerCardFragmentContainer {...props} />
</Theme>
</GlobalStoreProvider>
),
query: graphql`
query PartnerCardTestsQuery @raw_response_type {
artwork(id: "artworkID") {
...PartnerCard_artwork
}
}
`,
mockData: { artwork: mockArtworkData } as PartnerCardTestsQueryRawResponse,
mockMutationResults: { followProfile: mockFollowResults },
})
}
it("correctly displays when the artist is already followed, and allows unfollowing", async () => {
const PartnerCardArtworkFollowed = {
...PartnerCardArtwork,
partner: {
...PartnerCardArtwork.partner,
profile: {
...PartnerCardArtwork.partner!.profile,
is_followed: true,
},
},
}
const unfollowResponse = {
profile: {
is_followed: false,
slug: PartnerCardArtwork.partner!.slug,
internalID: PartnerCardArtwork.partner!.profile!.internalID,
},
}
const partnerCard = await getWrapper({
mockArtworkData: PartnerCardArtworkFollowed,
mockFollowResults: unfollowResponse,
})
const followButton = partnerCard.find(Button)
expect(followButton.text()).toMatchInlineSnapshot(`"FollowingFollowing"`)
await partnerCard.find(Button).at(0).props().onPress()
await flushPromiseQueue()
partnerCard.update()
const updatedFollowButton = partnerCard.find(Button).at(0)
expect(updatedFollowButton.text()).toMatchInlineSnapshot(`"FollowingFollow"`)
})
it("correctly displays when the work is not followed, and allows following", async () => {
const followResponse = {
profile: {
is_followed: true,
slug: PartnerCardArtwork.partner!.slug,
internalID: PartnerCardArtwork.partner!.profile!.internalID,
},
}
const partnerCard = await getWrapper({
mockArtworkData: PartnerCardArtwork,
mockFollowResults: followResponse,
})
const followButton = partnerCard.find(Button).at(0)
expect(followButton.text()).toMatchInlineSnapshot(`"FollowingFollow"`)
await partnerCard.find(Button).at(0).props().onPress()
await flushPromiseQueue()
partnerCard.update()
const updatedFollowButton = partnerCard.find(Button).at(0)
expect(updatedFollowButton.text()).toMatchInlineSnapshot(`"FollowingFollowing"`)
})
// TODO Update once we can use relay's new facilities for testing
xit("handles errors in saving gracefully", async () => {
const partnerCard = await renderRelayTree({
Component: PartnerCardFragmentContainer,
query: graphql`
query PartnerCardTestsErrorQuery @raw_response_type {
artwork(id: "artworkID") {
...PartnerCard_artwork
}
}
`,
mockData: { artwork: PartnerCardArtwork }, // Enable/fix this when making large change to these components/fixtures: as PartnerCardTestsErrorQueryRawResponse,
mockMutationResults: {
PartnerCardFragmentContainer: () => {
return Promise.reject(new Error("failed to fetch"))
},
},
})
const followButton = partnerCard.find(Button).at(0)
expect(followButton.text()).toMatchInlineSnapshot(`"Follow"`)
await partnerCard.find(Button).at(0).props().onPress()
await flushPromiseQueue()
partnerCard.update()
const updatedFollowButton = partnerCard.find(Button).at(0)
expect(updatedFollowButton.text()).toMatchInlineSnapshot(`"Follow"`)
})
})
})
const PartnerCardArtwork: PartnerCard_artwork = {
sale: {
isBenefit: false,
isGalleryAuction: false,
},
partner: {
is_default_profile_public: true,
type: "Gallery",
name: "Test Gallery",
slug: "12345",
id: "12345",
href: "",
initials: "TG",
profile: {
id: "12345",
internalID: "56789",
is_followed: false,
icon: {
url: "https://d32dm0rphc51dk.cloudfront.net/YciR5levjrhp2JnFYlPxpw/square140.webp",
},
},
cities: ["Miami", "New York", "Hong Kong", "London", "Boston"],
},
" $refType": null as any,
} | the_stack |
declare module Phaser {
interface Physics {
isoArcade:Phaser.Plugin.Isometric.Arcade;
}
}
declare module Phaser.Plugin {
class Isometric extends Phaser.Plugin {
static CLASSIC: number;
static ISOMETRIC: number;
static MILITARY: number;
static VERSION: string;
static UP: number;
static DOWN: number;
static FORWARDX: number;
static FORWARDY: number;
static BACKWARDX: number;
static BACKWARDY: number;
static ISOSPRITE: number;
static ISOARCADE: number;
projector: Phaser.Plugin.Isometric.Projector;
constructor(game: Phaser.Game, parent?: any);
addIsoSprite(x: number, y: number, z: number, key?: any, frame?: any, group?: Phaser.Group): Phaser.Plugin.Isometric.IsoSprite;
}
module Isometric {
class Projector {
game: Phaser.Game;
anchor: Phaser.Point;
projectionAngle: number;
project(point3: Phaser.Plugin.Isometric.Point3, out?: Phaser.Point): Phaser.Point;
projectXY(point3: Phaser.Plugin.Isometric.Point3, out?: Phaser.Point): Phaser.Point;
unproject(point: Phaser.Point, out?: Phaser.Plugin.Isometric.Point3, z?: number): Phaser.Plugin.Isometric.Point3;
simpleSort(group: Phaser.Group): void;
topologicalSort(group: Phaser.Group, padding?: number, prop?: string): void;
}
class Point3 {
static add(a: Phaser.Plugin.Isometric.Point3, b: Phaser.Plugin.Isometric.Point3, out?: Phaser.Plugin.Isometric.Point3): Phaser.Plugin.Isometric.Point3;
static subtract(a: Phaser.Plugin.Isometric.Point3, b: Phaser.Plugin.Isometric.Point3, out?: Phaser.Plugin.Isometric.Point3): Phaser.Plugin.Isometric.Point3;
static multiply(a: Phaser.Plugin.Isometric.Point3, b: Phaser.Plugin.Isometric.Point3, out?: Phaser.Plugin.Isometric.Point3): Phaser.Plugin.Isometric.Point3;
static divide(a: Phaser.Plugin.Isometric.Point3, b: Phaser.Plugin.Isometric.Point3, out?: Phaser.Plugin.Isometric.Point3): Phaser.Plugin.Isometric.Point3;
static equals(a: Phaser.Plugin.Isometric.Point3, b: Phaser.Plugin.Isometric.Point3): boolean;
x: number;
y: number;
z: number;
constructor(x?: number, y?: number, z?: number);
copyFrom(source: any): Phaser.Plugin.Isometric.Point3;
copyto(dest: any): any;
equals(a: any): boolean;
set(x?: number, y?: number, z?: number): Phaser.Plugin.Isometric.Point3;
setTo(x?: number, y?: number, z?: number): Phaser.Plugin.Isometric.Point3;
add(x?: number, y?: number): Phaser.Plugin.Isometric.Point3;
subtract(x?: number, y?: number, z?: number): Phaser.Plugin.Isometric.Point3;
multiply(x?: number, y?: number, z?: number): Phaser.Plugin.Isometric.Point3;
divide(x?: number, y?: number, z?: number): Phaser.Plugin.Isometric.Point3;
}
class Octree {
maxObjects: number;
maxLevels: number;
level: number;
bounds: any;
objects: any[];
nodes: any[];
constructor(x: number, y: number, z: number, widthX: number, widthY: number, height: number, maxObject?: number, maxLevels?: number, level?: number);
reset(x: number, y: number, z: number, widthX: number, widthY: number, height: number, maxObject?: number, maxLevels?: number, level?: number): void;
populate(group: Phaser.Group): void;
populateHandler(sprite: Phaser.Plugin.Isometric.IsoSprite): void;
populateHandler(sprite: any): void;
split(): void;
insert(body: Phaser.Plugin.Isometric.Body): void;
insert(body: Phaser.Plugin.Isometric.Cube): void;
insert(body: any): void;
getIndex(cube: Phaser.Plugin.Isometric.Cube): number;
getIndex(cube: any): number;
retrieve(source: Phaser.Plugin.Isometric.IsoSprite): any[];
retrieve(source: Phaser.Plugin.Isometric.Cube): any[];
clear(): void;
}
class IsoSprite extends Phaser.Sprite {
snap: number;
isoX: number;
isoY: number;
isoZ: number;
isoPosition: Phaser.Plugin.Isometric.Point3;
isoBounds: Phaser.Plugin.Isometric.Point3;
depth: number;
constructor(game: Phaser.Game, x: number, y: number, z: number, key?: any, frame?: any);
resetIsoBounds(): void;
}
class Cube {
static size(a: Phaser.Plugin.Isometric.Cube, output?: Phaser.Plugin.Isometric.Point3): Phaser.Plugin.Isometric.Point3;
static clone(a: Phaser.Plugin.Isometric.Cube, output?: Phaser.Plugin.Isometric.Cube): Phaser.Plugin.Isometric.Cube;
static contains(a: Phaser.Plugin.Isometric.Cube, x: number, y: number, z: number): boolean;
static containsXY(a: Phaser.Plugin.Isometric.Cube, x: number, y: number): boolean;
static containsPoint3(a: Phaser.Plugin.Isometric.Cube, point3: Phaser.Plugin.Isometric.Point3): boolean;
static containsCube(a: Phaser.Plugin.Isometric.Cube, b: Phaser.Plugin.Isometric.Cube): boolean;
static intersects(a: Phaser.Plugin.Isometric.Cube, b: Phaser.Plugin.Isometric.Cube): boolean;
x: number;
y: number;
z: number;
widthX: number;
widthY: number;
height: number;
halfWidthX: number;
halfWidthY: number;
halfHeight: number;
bottom: number;
top: number;
backX: number;
backY: number;
frontX: number;
frontY: number;
volume: number;
centerX: number;
centerY: number;
centerZ: number;
randomX: number;
randomY: number;
randomZ: number;
empty: boolean;
constructor(x?: number, y?: number, z?: number, widthX?: number, widthY?: number, height?: number);
setTo(x?: number, y?: number, z?: number, widthX?: number, widthY?: number, height?: number): Phaser.Plugin.Isometric.Cube;
copyFrom(source: any): Phaser.Plugin.Isometric.Cube;
copyTo(dest: any): Phaser.Plugin.Isometric.Cube;
size(output?: Phaser.Plugin.Isometric.Point3): Phaser.Plugin.Isometric.Point3;
contains(x: number, y: number, z: number): boolean;
containsXY(x: number, y: number): boolean;
clone(output?: Phaser.Plugin.Isometric.Cube): Phaser.Plugin.Isometric.Cube;
intersects(b: Phaser.Plugin.Isometric.Cube): boolean;
getCorners(): Phaser.Plugin.Isometric.Point3[];
toString(): string;
}
class Body {
static render(context: any, body: Phaser.Plugin.Isometric.Body, color?: string, filled?: boolean): void;
static renderBodyInfo(debug: any, body: Phaser.Plugin.Isometric.Body): void; //togo debug?
sprite: Phaser.Plugin.Isometric.IsoSprite;
game: Phaser.Game;
type: number;
enable: boolean;
offset: Phaser.Plugin.Isometric.Point3;
position: Phaser.Plugin.Isometric.Point3;
prev: Phaser.Plugin.Isometric.Point3;
allowRotation: boolean;
rotation: number;
preRotation: number;
sourceWidthX: number;
sourceWidthY: number;
sourceHeight: number;
widthX: number;
widthY: number;
height: number;
halfWidthX: number;
halfWidthY: number;
halfHeight: number;
center: Phaser.Plugin.Isometric.Point3;
velocity: Phaser.Plugin.Isometric.Point3;
newVelocity: Phaser.Plugin.Isometric.Point3;
deltaMax: Phaser.Plugin.Isometric.Point3;
acceleration: Phaser.Plugin.Isometric.Point3;
drag: Phaser.Plugin.Isometric.Point3;
allowGravity: boolean;
gravity: Phaser.Plugin.Isometric.Point3;
bounce: Phaser.Plugin.Isometric.Point3;
maxVelocity: Phaser.Plugin.Isometric.Point3;
angularVelocity: number;
angularAcceleration: number;
angularDrag: number;
maxAngular: number;
mass: number;
angle: number;
speed: number;
facing: number;
immovable: boolean;
moves: boolean;
customSeparateX: boolean;
customSeparateY: boolean;
customSeparateZ: boolean;
overlapX: number;
overlapY: number;
overlayZ: number;
embedded: boolean;
collideWorldBounds: boolean;
checkCollision: {
none: boolean;
any: boolean;
up: boolean;
down: boolean;
frontX: number;
frontY: number;
backX: number;
backY: number;
};
touching: {
none: boolean;
up: boolean;
down: boolean;
frontX: number;
frontY: number;
backX: number;
backY: number;
};
wasTouching: {
none: boolean;
up: boolean;
down: boolean;
frontX: number;
frontY: number;
backX: number;
backY: number;
};
blocked: {
up: boolean;
down: boolean;
frontX: number;
frontY: number;
backX: number;
backY: number;
};
phase: number;
skipTree: boolean;
top: number;
frontX: number;
right: number;
frontY: number;
bottom: number;
x: number;
y: number;
z: number;
constructor(sprite: Phaser.Plugin.Isometric.IsoSprite);
destroy(): void;
setSize(widthX: number, widthY: number, height: number, offsetX?: number, offsetY?: number, offsetZ?: number): void;
reset(x: number, y: number, z: number): void;
hitText(x: number, y: number, z: number): boolean;
onFloor(): boolean;
onWall(): boolean;
deltaAbsX(): number;
deltaAbsY(): number;
deltaAbsZ(): number;
deltaX(): number;
deltaY(): number;
deltaZ(): number;
deltaR(): number;
getCorners(): Phaser.Plugin.Isometric.Point3[];
}
class Arcade {
game: Phaser.Game;
gravity: Phaser.Plugin.Isometric.Point3;
bounds: Phaser.Plugin.Isometric.Cube;
checkCollision: {
up: boolean;
down: boolean;
frontX: boolean;
frontY: boolean;
backX: boolean;
backY: boolean;
};
maxObjects: number;
maxLevels: number;
OVERLAP_BIAS: number;
forceXY: boolean;
skipTree: boolean;
useQuadTree: boolean;
quadTree: Phaser.QuadTree;
octree: Phaser.Plugin.Isometric.Octree;
constructor(game: Phaser.Game);
setBounds(x: number, y: number, z: number, widthX: number, widthY: number, height: number): void;
setBoundsToWorld(): void;
enable(object: any, children?: boolean): void;
enableBody(object: any): void;
updateMotion(body: Phaser.Plugin.Isometric.Body): void;
computeVelocity(axis: number, body: Phaser.Plugin.Isometric.Body, velocity: number, acceleration: number, drag: number, max?: number): number;
overlap(object1: any, object2: any, overlapCallback?: Function, processCallback?: Function, callbackContext?: any): boolean;
collide(object1: any, object2: any, overlapCallback?: Function, processCallback?: Function, callbackContext?: any): boolean;
intersects(body1: Phaser.Plugin.Isometric.Body): boolean;
distanceBetween(source: any, target: any): number;
distanceToXY(displayObject: any, x: number, y: number): number;
distanceToXYZ(displayObject: any, x: number, y: number, z: number): number;
}
}
} | the_stack |
import { expect } from 'chai'
import { Redis } from 'ioredis'
import sinon from 'sinon'
import LostLockError from '../../src/errors/LostLockError'
import RedlockSemaphore from '../../src/RedlockSemaphore'
import { TimeoutOptions } from '../../src/types'
import { delay } from '../../src/utils/index'
import { allClients, client1, client2, client3 } from '../redisClient'
import { downRedisServer, upRedisServer } from '../shell'
import {
catchUnhandledRejection, throwUnhandledRejection, unhandledRejectionSpy
} from '../unhandledRejection'
const timeoutOptions: TimeoutOptions = {
lockTimeout: 300,
acquireTimeout: 100,
refreshInterval: 80,
retryInterval: 10
}
async function expectZRangeAllEql(key: string, values: string[]) {
const results = await Promise.all([
client1.zrange(key, 0, -1),
client2.zrange(key, 0, -1),
client3.zrange(key, 0, -1)
])
expect(results).to.be.eql([values, values, values])
}
async function expectZRangeAllHaveMembers(key: string, values: string[]) {
const results = await Promise.all([
client1.zrange(key, 0, -1),
client2.zrange(key, 0, -1),
client3.zrange(key, 0, -1)
])
for (const result of results) {
expect(result).to.have.members(values)
}
}
async function expectZCardAllEql(key: string, count: number) {
const results = await Promise.all([
client1.zcard(key),
client2.zcard(key),
client3.zcard(key)
])
expect(results).to.be.eql([count, count, count])
}
describe('RedlockSemaphore', () => {
it('should fail on invalid arguments', () => {
expect(
() => new RedlockSemaphore((null as unknown) as Redis[], 'key', 5)
).to.throw('"clients" array is required')
expect(
() => new RedlockSemaphore(([{}] as unknown) as Redis[], 'key', 5)
).to.throw('"client" must be instance of ioredis client')
expect(() => new RedlockSemaphore(allClients, '', 5)).to.throw(
'"key" is required'
)
expect(
() => new RedlockSemaphore(allClients, (1 as unknown) as string, 5)
).to.throw('"key" must be a string')
expect(() => new RedlockSemaphore(allClients, 'key', 0)).to.throw(
'"limit" is required'
)
expect(
() => new RedlockSemaphore(allClients, 'key', ('10' as unknown) as number)
).to.throw('"limit" must be a number')
})
it('should acquire and release semaphore', async () => {
const semaphore1 = new RedlockSemaphore(allClients, 'key', 2)
const semaphore2 = new RedlockSemaphore(allClients, 'key', 2)
await semaphore1.acquire()
await semaphore2.acquire()
await expectZRangeAllHaveMembers('semaphore:key', [
semaphore1.identifier,
semaphore2.identifier
])
await semaphore1.release()
await expectZRangeAllEql('semaphore:key', [semaphore2.identifier])
await semaphore2.release()
await expectZCardAllEql('semaphore:key', 0)
})
it('should reject after timeout', async () => {
const semaphore1 = new RedlockSemaphore(
allClients,
'key',
1,
timeoutOptions
)
const semaphore2 = new RedlockSemaphore(
allClients,
'key',
1,
timeoutOptions
)
await semaphore1.acquire()
await expect(semaphore2.acquire()).to.be.rejectedWith(
'Acquire redlock-semaphore semaphore:key timeout'
)
await semaphore1.release()
await expectZCardAllEql('semaphore:key', 0)
})
it('should refresh lock every refreshInterval ms until release', async () => {
const semaphore1 = new RedlockSemaphore(
allClients,
'key',
2,
timeoutOptions
)
const semaphore2 = new RedlockSemaphore(
allClients,
'key',
2,
timeoutOptions
)
await semaphore1.acquire()
await semaphore2.acquire()
await delay(100)
await expectZRangeAllHaveMembers('semaphore:key', [
semaphore1.identifier,
semaphore2.identifier
])
await semaphore1.release()
await expectZRangeAllEql('semaphore:key', [semaphore2.identifier])
await semaphore2.release()
await expectZCardAllEql('semaphore:key', 0)
})
it('should acquire maximum LIMIT semaphores', async () => {
const s = () =>
new RedlockSemaphore(allClients, 'key', 3, {
acquireTimeout: 1000,
lockTimeout: 50,
retryInterval: 10,
refreshInterval: 0 // disable refresh
})
const set1 = [s(), s(), s()]
const pr1 = Promise.all(set1.map(sem => sem.acquire()))
await delay(5)
const set2 = [s(), s(), s()]
const pr2 = Promise.all(set2.map(sem => sem.acquire()))
await pr1
await expectZRangeAllHaveMembers('semaphore:key', [
set1[0].identifier,
set1[1].identifier,
set1[2].identifier
])
await expectZCardAllEql('semaphore:key', 3)
await pr2
await expectZRangeAllHaveMembers('semaphore:key', [
set2[0].identifier,
set2[1].identifier,
set2[2].identifier
])
await expectZCardAllEql('semaphore:key', 3)
})
describe('lost lock case', () => {
beforeEach(() => {
catchUnhandledRejection()
})
afterEach(() => {
throwUnhandledRejection()
})
it('should throw unhandled error if lock is lost between refreshes', async () => {
const semaphore = new RedlockSemaphore(
allClients,
'key',
3,
timeoutOptions
)
await semaphore.acquire()
await Promise.all(allClients.map(client => client.del('semaphore:key')))
await Promise.all(
allClients.map(client =>
client.zadd(
'semaphore:key',
Date.now(),
'aaa',
Date.now(),
'bbb',
Date.now(),
'ccc'
)
)
)
await delay(200)
expect(unhandledRejectionSpy).to.be.called
expect(unhandledRejectionSpy.firstCall.firstArg instanceof LostLockError)
.to.be.true
})
it('should call onLockLost callback if provided', async () => {
const onLockLostCallback = sinon.spy(function (this: RedlockSemaphore) {
expect(this.isAcquired).to.be.false
})
const semaphore = new RedlockSemaphore(allClients, 'key', 3, {
...timeoutOptions,
onLockLost: onLockLostCallback
})
await semaphore.acquire()
expect(semaphore.isAcquired).to.be.true
await Promise.all(allClients.map(client => client.del('semaphore:key')))
await Promise.all(
allClients.map(client =>
client.zadd(
'semaphore:key',
Date.now(),
'aaa',
Date.now(),
'bbb',
Date.now(),
'ccc'
)
)
)
await delay(200)
expect(semaphore.isAcquired).to.be.false
expect(unhandledRejectionSpy).to.not.called
expect(onLockLostCallback).to.be.called
expect(onLockLostCallback.firstCall.firstArg instanceof LostLockError).to
.be.true
})
})
describe('reusable', () => {
it('autorefresh enabled', async () => {
const semaphore1 = new RedlockSemaphore(
allClients,
'key',
2,
timeoutOptions
)
const semaphore2 = new RedlockSemaphore(
allClients,
'key',
2,
timeoutOptions
)
await semaphore1.acquire()
await semaphore2.acquire()
await delay(100)
await semaphore1.release()
await semaphore2.release()
await delay(100)
await semaphore1.acquire()
await semaphore2.acquire()
await delay(100)
await semaphore1.release()
await semaphore2.release()
await delay(100)
await semaphore1.acquire()
await semaphore2.acquire()
await delay(100)
await semaphore1.release()
await semaphore2.release()
})
it('autorefresh disabled', async () => {
const noRefreshOptions = {
...timeoutOptions,
refreshInterval: 0,
acquireTimeout: 10
}
const semaphore1 = new RedlockSemaphore(
allClients,
'key',
2,
noRefreshOptions
)
const semaphore2 = new RedlockSemaphore(
allClients,
'key',
2,
noRefreshOptions
)
const semaphore3 = new RedlockSemaphore(
allClients,
'key',
2,
noRefreshOptions
)
await semaphore1.acquire()
await semaphore2.acquire()
await delay(100)
await semaphore1.release()
await semaphore2.release()
await delay(100)
// [0/2]
await semaphore1.acquire()
// [1/2]
await delay(80)
await semaphore2.acquire()
// [2/2]
await expect(semaphore3.acquire()).to.be.rejectedWith(
'Acquire redlock-semaphore semaphore:key timeout'
) // rejectes after 10ms
// since semaphore1.acquire() elapsed 80ms (delay) + 10ms (semaphore3 timeout)
// semaphore1 will expire after 300 - 90 = 210ms
await delay(210)
// [1/2]
await semaphore3.acquire()
})
})
describe('[Node shutdown]', () => {
beforeEach(() => {
catchUnhandledRejection()
})
afterEach(async () => {
throwUnhandledRejection()
await Promise.all([upRedisServer(1), upRedisServer(2), upRedisServer(3)])
})
it('should work again if node become alive', async function () {
this.timeout(60000)
const semaphore11 = new RedlockSemaphore(
allClients,
'key',
3,
timeoutOptions
)
const semaphore12 = new RedlockSemaphore(
allClients,
'key',
3,
timeoutOptions
)
const semaphore13 = new RedlockSemaphore(
allClients,
'key',
3,
timeoutOptions
)
await Promise.all([
semaphore11.acquire(),
semaphore12.acquire(),
semaphore13.acquire()
])
// <Server1Failure>
await downRedisServer(1)
console.log('SHUT DOWN 1')
await delay(1000)
// lock survive in server2 and server3
// semaphore2 will NOT be able to acquire the lock
const semaphore2 = new RedlockSemaphore(
allClients,
'key',
3,
timeoutOptions
)
await expect(semaphore2.acquire()).to.be.rejectedWith(
'Acquire redlock-semaphore semaphore:key timeout'
)
// key in server1 has expired now
await upRedisServer(1)
console.log('ONLINE 1')
// let semaphore1[1-3] to refresh lock on server1
await delay(1000)
expect(await client1.zrange('semaphore:key', 0, -1)).to.have.members([
semaphore11.identifier,
semaphore12.identifier,
semaphore13.identifier
])
// </Server1Failure>
// <Server2Failure>
await downRedisServer(2)
console.log('SHUT DOWN 2')
await delay(1000)
// lock survive in server1 and server3
// semaphore3 will NOT be able to acquire the lock
const semaphore3 = new RedlockSemaphore(
allClients,
'key',
3,
timeoutOptions
)
await expect(semaphore3.acquire()).to.be.rejectedWith(
'Acquire redlock-semaphore semaphore:key timeout'
)
// key in server2 has expired now
await upRedisServer(2)
console.log('ONLINE 2')
// let semaphore1[1-3] to refresh lock on server1
await delay(1000)
expect(await client2.zrange('semaphore:key', 0, -1)).to.have.members([
semaphore11.identifier,
semaphore12.identifier,
semaphore13.identifier
])
// </Server2Failure>
// <Server3Failure>
await downRedisServer(3)
console.log('SHUT DOWN 3')
await delay(1000)
// lock survive in server1 and server2
// semaphore4 will NOT be able to acquire the lock
const semaphore4 = new RedlockSemaphore(
allClients,
'key',
3,
timeoutOptions
)
await expect(semaphore4.acquire()).to.be.rejectedWith(
'Acquire redlock-semaphore semaphore:key timeout'
)
// key in server1 has expired now
await upRedisServer(3)
console.log('ONLINE 3')
// let semaphore1[1-3] to refresh lock on server1
await delay(1000)
expect(await client3.zrange('semaphore:key', 0, -1)).to.have.members([
semaphore11.identifier,
semaphore12.identifier,
semaphore13.identifier
])
// </Server3Failure>
await Promise.all([
semaphore11.release(),
semaphore12.release(),
semaphore13.release()
])
})
})
}) | the_stack |
import { TestBed, fakeAsync, waitForAsync } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { AssetsLoader, AssetsLoadResult } from './assets-loader';
import { hashCode } from './helpers';
import { Subject, of, observable, Observable, BehaviorSubject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
describe('assets-loader', () => {
let assetsLoader: AssetsLoader;
const mockScript: {
onload: () => void;
onerror: (error: string | Event) => void;
} = { onload: () => {}, onerror: null };
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: []
});
assetsLoader = TestBed.inject(AssetsLoader);
});
describe('loadScript', () => {
it('should load script success when not in IE', fakeAsync(() => {
const src = 'assets/main.js';
const createElementSpy: jasmine.Spy = spyOn(document, 'createElement');
const appendChildSpy = spyOn(document.body, 'appendChild');
// 返回 mock script
createElementSpy.and.returnValue(mockScript);
// 没有调用
expect(appendChildSpy).not.toHaveBeenCalled();
expect(createElementSpy).not.toHaveBeenCalled();
const scriptLoaded = jasmine.createSpy('load script');
assetsLoader.loadScript(src).subscribe(scriptLoaded, error => {
console.error(error);
});
// 已经被调用
expect(appendChildSpy).toHaveBeenCalledTimes(1);
expect(createElementSpy).toHaveBeenCalledTimes(1);
// scriptLoaded 没有加载完毕
expect(scriptLoaded).toHaveBeenCalledTimes(0);
// 手动调用使其加载完毕
mockScript.onload();
// // scriptLoaded 加载完毕
expect(scriptLoaded).toHaveBeenCalledTimes(1);
expect(scriptLoaded).toHaveBeenCalledWith({
src: src,
hashCode: hashCode(src),
loaded: true,
status: 'Loaded'
});
}));
it('should load script success when in IE and readyState is loaded', fakeAsync(() => {
const mockScriptInIE: { readyState: string; onreadystatechange: () => void } = {
readyState: 'uninitialized',
onreadystatechange: () => {
console.log('loaded script state change');
}
};
const src = 'assets/main.js';
const createElementSpy: jasmine.Spy = spyOn(document, 'createElement');
const appendChildSpy = spyOn(document.body, 'appendChild');
// 返回 mock script
createElementSpy.and.returnValue(mockScriptInIE);
// 没有调用
expect(appendChildSpy).not.toHaveBeenCalled();
expect(createElementSpy).not.toHaveBeenCalled();
const scriptLoaded = jasmine.createSpy('load script');
assetsLoader.loadScript(src).subscribe(scriptLoaded, error => {
console.error(error);
});
// 已经被调用
expect(appendChildSpy).toHaveBeenCalledTimes(1);
expect(createElementSpy).toHaveBeenCalledTimes(1);
// scriptLoaded 没有加载完毕
expect(scriptLoaded).toHaveBeenCalledTimes(0);
// 手动调用使其加载完毕
mockScriptInIE.readyState = 'loaded';
mockScriptInIE.onreadystatechange();
// // scriptLoaded 加载完毕
expect(scriptLoaded).toHaveBeenCalledTimes(1);
expect(mockScriptInIE.onreadystatechange).toBeNull();
expect(scriptLoaded).toHaveBeenCalledWith({
src: src,
hashCode: hashCode(src),
loaded: true,
status: 'Loaded'
});
}));
it('should load script success when in IE and readyState is complete or loaded', fakeAsync(() => {
const mockScriptInIE: { readyState: string; onreadystatechange: () => void } = {
readyState: 'uninitialized',
onreadystatechange: () => {
console.log('loaded script state change');
}
};
const src = 'assets/main.js';
const createElementSpy: jasmine.Spy = spyOn(document, 'createElement');
const appendChildSpy = spyOn(document.body, 'appendChild');
// 返回 mock script
createElementSpy.and.returnValue(mockScriptInIE);
// 没有调用
expect(appendChildSpy).not.toHaveBeenCalled();
expect(createElementSpy).not.toHaveBeenCalled();
const scriptLoaded = jasmine.createSpy('load script');
assetsLoader.loadScript(src).subscribe(scriptLoaded, error => {
console.error(error);
});
// 已经被调用
expect(appendChildSpy).toHaveBeenCalledTimes(1);
expect(createElementSpy).toHaveBeenCalledTimes(1);
// scriptLoaded 没有加载完毕
expect(scriptLoaded).toHaveBeenCalledTimes(0);
// 手动调用使其加载完毕
mockScriptInIE.readyState = 'complete';
mockScriptInIE.onreadystatechange();
// // scriptLoaded 加载完毕
expect(scriptLoaded).toHaveBeenCalledTimes(1);
expect(mockScriptInIE.onreadystatechange).toBeNull();
expect(scriptLoaded).toHaveBeenCalledWith({
src: src,
hashCode: hashCode(src),
loaded: true,
status: 'Loaded'
});
}));
it('should load script success when in IE and readyState is not complete or loaded', fakeAsync(() => {
const mockScriptInIE: { readyState: string; onreadystatechange: () => void } = {
readyState: 'uninitialized',
onreadystatechange: () => {
console.log('loaded script state change');
}
};
const src = 'assets/main.js';
const createElementSpy: jasmine.Spy = spyOn(document, 'createElement');
const appendChildSpy = spyOn(document.body, 'appendChild');
// 返回 mock script
createElementSpy.and.returnValue(mockScriptInIE);
// 没有调用
expect(appendChildSpy).not.toHaveBeenCalled();
expect(createElementSpy).not.toHaveBeenCalled();
const scriptLoaded = jasmine.createSpy('load script');
assetsLoader.loadScript(src).subscribe(scriptLoaded, error => {
console.error(error);
});
// 已经被调用
expect(appendChildSpy).toHaveBeenCalledTimes(1);
expect(createElementSpy).toHaveBeenCalledTimes(1);
// scriptLoaded 没有加载完毕
expect(scriptLoaded).toHaveBeenCalledTimes(0);
// 手动调用使其加载完毕
mockScriptInIE.readyState = 'any status';
mockScriptInIE.onreadystatechange();
// // scriptLoaded 加载完毕
expect(scriptLoaded).not.toHaveBeenCalled();
expect(mockScriptInIE.onreadystatechange).not.toBeNull();
}));
it('should not load script which has been loaded', fakeAsync(() => {
const src = 'assets/main.js';
const createElementSpy: jasmine.Spy = spyOn(document, 'createElement');
const appendChildSpy = spyOn(document.body, 'appendChild');
createElementSpy.and.returnValue(mockScript);
const scriptLoaded = jasmine.createSpy('load script');
assetsLoader.loadScript(src).subscribe(scriptLoaded, error => {
console.error(error);
});
mockScript.onload();
const scriptLoaded2 = jasmine.createSpy('load script');
assetsLoader.loadScript(src).subscribe(scriptLoaded2, error => {
console.error(error);
});
expect(appendChildSpy).toHaveBeenCalledTimes(1);
expect(createElementSpy).toHaveBeenCalledTimes(1);
expect(scriptLoaded2).toHaveBeenCalledTimes(1);
expect(scriptLoaded2).toHaveBeenCalledWith({
src: src,
hashCode: hashCode(src),
loaded: true,
status: 'Loaded'
});
}));
it('should get error when load script fail', fakeAsync(() => {
const src = 'assets/main.js';
const createElementSpy: jasmine.Spy = spyOn(document, 'createElement');
const appendChildSpy = spyOn(document.body, 'appendChild');
// 返回 mock script
createElementSpy.and.returnValue(mockScript);
// 没有调用
expect(appendChildSpy).not.toHaveBeenCalled();
expect(createElementSpy).not.toHaveBeenCalled();
const scriptLoaded = jasmine.createSpy('load script');
const scriptLoadedError = jasmine.createSpy('load script error');
assetsLoader.loadScript(src).subscribe(scriptLoaded, scriptLoadedError);
// 已经被调用
expect(appendChildSpy).toHaveBeenCalledTimes(1);
expect(createElementSpy).toHaveBeenCalledTimes(1);
// scriptLoaded 没有加载完毕
expect(scriptLoaded).not.toHaveBeenCalled();
// 手动调用使其加载完毕
mockScript.onerror('load js error');
expect(scriptLoaded).not.toHaveBeenCalled();
expect(scriptLoadedError).toHaveBeenCalled();
expect(scriptLoadedError).toHaveBeenCalledWith({
src: src,
hashCode: hashCode(src),
loaded: false,
status: 'Error',
error: 'load js error'
});
}));
});
describe('loadScripts', () => {
it('should return null when sources is []', fakeAsync(() => {
const loadScriptSpy = spyOn(assetsLoader, 'loadScript');
expect(loadScriptSpy).not.toHaveBeenCalled();
const loadedScripts = jasmine.createSpy('loaded scripts success');
const loadedScriptsFail = jasmine.createSpy('loaded scripts fail');
assetsLoader.loadStyles([]).subscribe(loadedScripts, loadedScriptsFail);
expect(loadScriptSpy).not.toHaveBeenCalled();
expect(loadedScripts).toHaveBeenCalledTimes(1);
expect(loadedScripts).toHaveBeenCalledWith(null);
expect(loadedScriptsFail).not.toHaveBeenCalled();
}));
it('should return null when sources is null', fakeAsync(() => {
const loadScriptSpy = spyOn(assetsLoader, 'loadScript');
expect(loadScriptSpy).not.toHaveBeenCalled();
const loadedScripts = jasmine.createSpy('loaded scripts success');
const loadedScriptsFail = jasmine.createSpy('loaded scripts fail');
assetsLoader.loadStyles(null).subscribe(loadedScripts, loadedScriptsFail);
expect(loadScriptSpy).not.toHaveBeenCalled();
expect(loadedScripts).toHaveBeenCalledTimes(1);
expect(loadedScripts).toHaveBeenCalledWith(null);
expect(loadedScriptsFail).not.toHaveBeenCalled();
}));
it('should load scripts success', () => {
const src1 = 'assets/vendor.js';
const src2 = 'assets/main.js';
const loadScriptSpy = spyOn(assetsLoader, 'loadScript');
const loadScriptObservable1 = new Subject<AssetsLoadResult>();
const loadScriptObservable2 = new Subject<AssetsLoadResult>();
loadScriptSpy.and.returnValues(loadScriptObservable1, loadScriptObservable2);
const result1 = {
src: src1,
hashCode: hashCode(src1),
loaded: true,
status: 'Loaded'
};
const result2 = {
src: src2,
hashCode: hashCode(src2),
loaded: true,
status: 'Loaded'
};
const loadScriptsSpy = jasmine.createSpy('load scripts spy');
assetsLoader.loadScripts([src1, src2]).subscribe(loadScriptsSpy);
loadScriptObservable2.next(result2);
loadScriptObservable2.complete();
loadScriptObservable1.next(result1);
loadScriptObservable1.complete();
expect(loadScriptsSpy).toHaveBeenCalled();
expect(loadScriptsSpy).toHaveBeenCalledWith([result1, result2]);
});
it('should load scripts success when serial is true', () => {
const src1 = 'assets/vendor.js';
const src2 = 'assets/main.js';
const loadScriptSpy = spyOn(assetsLoader, 'loadScript');
const loadScriptObservable1 = new Subject<AssetsLoadResult>();
const loadScriptObservable2 = new Subject<AssetsLoadResult>();
loadScriptSpy.and.returnValues(loadScriptObservable1, loadScriptObservable2);
const result1 = {
src: src1,
hashCode: hashCode(src1),
loaded: true,
status: 'Loaded'
};
const result2 = {
src: src2,
hashCode: hashCode(src2),
loaded: true,
status: 'Loaded'
};
const loadScriptsSpy = jasmine.createSpy('load scripts spy');
assetsLoader.loadScripts([src1, src2], { serial: true }).subscribe(loadScriptsSpy);
loadScriptObservable1.next(result1);
loadScriptObservable1.complete();
loadScriptObservable2.next(result2);
loadScriptObservable2.complete();
expect(loadScriptsSpy).toHaveBeenCalled();
expect(loadScriptsSpy.calls.count()).toEqual(2);
expect(loadScriptsSpy.calls.argsFor(0)).toEqual([[result1]]);
expect(loadScriptsSpy.calls.argsFor(1)).toEqual([[result2]]);
});
});
describe('loadManifest', () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => {
httpClient = TestBed.inject(HttpClient);
httpTestingController = TestBed.inject(HttpTestingController);
});
afterEach(() => {
// After every test, assert that there are no more pending requests.
httpTestingController.verify();
});
it(
'should load manifest success',
waitForAsync(() => {
const testData = {
'main.js': 'main1.js'
};
const loadManifestSpy = jasmine.createSpy('load manifest spy');
assetsLoader.loadManifest('/static/assets/manifest.json').subscribe(loadManifestSpy);
const req = httpTestingController.expectOne('/static/assets/manifest.json');
// Assert that the request is a GET.
expect(req.request.method).toEqual('GET');
expect(loadManifestSpy).not.toHaveBeenCalled();
// Respond with mock data, causing Observable to resolve.
// Subscribe callback asserts that correct data was returned.
req.flush(testData);
expect(loadManifestSpy).toHaveBeenCalled();
expect(loadManifestSpy).toHaveBeenCalledWith(testData);
})
);
});
describe('loadAppAssets', () => {
const app1 = {
name: 'app1',
hostParent: '.host-selector',
selector: 'app1-root',
routerPathPrefix: '/app1',
hostClass: 'app1-host',
preload: false,
resourcePathPrefix: '/static/app1/',
styles: ['styles/main.css'],
scripts: ['vendor.js', 'main.js'],
sandbox: false,
loadSerial: false,
manifest: '',
extra: {
appName: '应用1'
}
};
it('load assets success without manifest', () => {
const loadScriptsAndStyles$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>();
const loadScriptsAndStylesSpy = spyOn(assetsLoader, 'loadScriptsAndStyles');
loadScriptsAndStylesSpy.and.returnValue(loadScriptsAndStyles$);
const loadAssetsSpy = jasmine.createSpy('load assets spy');
assetsLoader.loadAppAssets(app1).subscribe(loadAssetsSpy);
expect(loadAssetsSpy).not.toHaveBeenCalled();
expect(loadScriptsAndStylesSpy).toHaveBeenCalled();
expect(loadScriptsAndStylesSpy).toHaveBeenCalledWith(
['/static/app1/vendor.js', '/static/app1/main.js'],
['/static/app1/styles/main.css'],
{
app: 'app1',
sandbox: false,
serial: app1.loadSerial
}
);
loadScriptsAndStyles$.next('load success' as any);
expect(loadAssetsSpy).toHaveBeenCalled();
expect(loadAssetsSpy).toHaveBeenCalledWith('load success');
});
it('load assets success with manifest', () => {
const loadScriptsAndStyles$ = new Subject<[AssetsLoadResult[], AssetsLoadResult[]]>();
const loadScriptsAndStylesSpy = spyOn(assetsLoader, 'loadScriptsAndStyles');
loadScriptsAndStylesSpy.and.returnValue(loadScriptsAndStyles$);
const loadManifestSpy = spyOn(assetsLoader, 'loadManifest');
const manifestResult = {
'main.js': 'main.123455.js',
'vendor.js': 'vendor.23221.js',
'main.css': 'main.s1223.css'
};
loadManifestSpy.and.returnValue(of(manifestResult));
const loadAssetsSpy = jasmine.createSpy('load assets spy');
assetsLoader
.loadAppAssets({
...app1,
manifest: '/app1/manifest.json'
})
.subscribe(loadAssetsSpy);
expect(loadAssetsSpy).not.toHaveBeenCalled();
expect(loadScriptsAndStylesSpy).toHaveBeenCalled();
expect(loadScriptsAndStylesSpy).toHaveBeenCalledWith(
[`/static/app1/${manifestResult['vendor.js']}`, `/static/app1/${manifestResult['main.js']}`],
[`/static/app1/styles/${manifestResult['main.css']}`],
{
app: 'app1',
sandbox: false,
serial: app1.loadSerial
}
);
loadScriptsAndStyles$.next('load success' as any);
expect(loadAssetsSpy).toHaveBeenCalled();
expect(loadAssetsSpy).toHaveBeenCalledWith('load success');
});
});
describe('loadStyle', () => {
let src, createElementSpy, getElementsByTagNameSpy, appendChildSpy, styleLoaded, styleLoadedFail;
const heads: { appendChild: () => void }[] = [{ appendChild: null }];
beforeEach(() => {
src = 'css/style.css';
createElementSpy = spyOn(document, 'createElement');
getElementsByTagNameSpy = spyOn(document, 'getElementsByTagName');
createElementSpy.and.returnValue(mockScript);
getElementsByTagNameSpy.and.returnValue(heads);
expect(createElementSpy).not.toHaveBeenCalled();
expect(getElementsByTagNameSpy).not.toHaveBeenCalled();
appendChildSpy = spyOn(heads[0], 'appendChild');
expect(appendChildSpy).not.toHaveBeenCalled();
styleLoaded = jasmine.createSpy('style loaded');
styleLoadedFail = jasmine.createSpy('load style error');
assetsLoader.loadStyle(src).subscribe(styleLoaded, styleLoadedFail);
expect(createElementSpy).toHaveBeenCalledTimes(1);
expect(getElementsByTagNameSpy).toHaveBeenCalledTimes(1);
expect(appendChildSpy).toHaveBeenCalledTimes(1);
expect(styleLoaded).toHaveBeenCalledTimes(0);
});
it('should load style success', fakeAsync(() => {
mockScript.onload();
expect(styleLoaded).toHaveBeenCalledTimes(1);
expect(styleLoadedFail).toHaveBeenCalledTimes(0);
expect(styleLoaded).toHaveBeenCalledWith({
src: src,
hashCode: hashCode(src),
loaded: true,
status: 'Loaded'
});
}));
it('should not load style when style has been loaded', fakeAsync(() => {
mockScript.onload();
const styleLoaded2 = jasmine.createSpy('load style');
assetsLoader.loadStyle(src).subscribe(styleLoaded2, error => {
console.error(error);
});
expect(createElementSpy).toHaveBeenCalledTimes(1);
expect(getElementsByTagNameSpy).toHaveBeenCalledTimes(1);
expect(styleLoaded2).toHaveBeenCalledWith({
src: src,
hashCode: hashCode(src),
loaded: true,
status: 'Loaded'
});
}));
it('should get error when load style fail', fakeAsync(() => {
mockScript.onerror('load style error');
expect(styleLoaded).toHaveBeenCalledTimes(0);
expect(styleLoadedFail).toHaveBeenCalledTimes(1);
expect(styleLoadedFail).toHaveBeenCalledWith({
src: src,
hashCode: hashCode(src),
loaded: true,
status: 'Loaded',
error: 'load style error'
});
}));
});
describe('loadStyles', () => {
it('should return null when sources is empty', fakeAsync(() => {
const loadStyletSpy = spyOn(assetsLoader, 'loadStyle');
expect(loadStyletSpy).not.toHaveBeenCalled();
const loadedStyles = jasmine.createSpy('loaded styles success');
const loadedStylesFail = jasmine.createSpy('loaded styles fail');
assetsLoader.loadStyles([]).subscribe(loadedStyles, loadedStylesFail);
expect(loadStyletSpy).not.toHaveBeenCalled();
expect(loadedStyles).toHaveBeenCalledTimes(1);
expect(loadedStyles).toHaveBeenCalledWith(null);
}));
it('should return load styles', fakeAsync(() => {
const stylesSrc = ['css/style1.css', 'css/style2.css'];
const loadStyletSpy = spyOn(assetsLoader, 'loadStyle');
expect(loadStyletSpy).not.toHaveBeenCalled();
const loadStyleObservable1: Subject<AssetsLoadResult> = new Subject<AssetsLoadResult>();
const loadStyleObservable2: Subject<AssetsLoadResult> = new Subject<AssetsLoadResult>();
const loadStyleObservable1Value = {
src: stylesSrc[0],
hashCode: hashCode(stylesSrc[0]),
loaded: true,
status: 'Loaded'
};
const loadStyleObservable2Value = {
src: stylesSrc[1],
hashCode: hashCode(stylesSrc[1]),
loaded: true,
status: 'Loaded'
};
loadStyletSpy.and.returnValues(loadStyleObservable1, loadStyleObservable2);
const loadedStyles = jasmine.createSpy('loaded styles success');
const loadedStylesFail = jasmine.createSpy('loaded styles fail');
assetsLoader.loadStyles(stylesSrc).subscribe(loadedStyles, loadedStylesFail);
expect(loadStyletSpy).toHaveBeenCalledTimes(2);
expect(loadedStyles).not.toHaveBeenCalled();
loadStyleObservable1.next(loadStyleObservable1Value);
loadStyleObservable1.complete();
loadStyleObservable2.next(loadStyleObservable2Value);
loadStyleObservable2.complete();
expect(loadedStyles).toHaveBeenCalledTimes(1);
expect(loadedStyles).toHaveBeenCalledWith([loadStyleObservable1Value, loadStyleObservable2Value]);
}));
});
describe('loadScriptsAndStyles', () => {
it('should load scripts and styles success', fakeAsync(() => {
const scripts = ['assert/main.js', 'assert/main1.js'];
const styles = ['css/style.css', 'css/style1.css'];
const loadScriptsSpy = spyOn(assetsLoader, 'loadScripts');
const loadStylesSpy = spyOn(assetsLoader, 'loadStyles');
const loadScriptsObservable = new Subject<AssetsLoadResult[]>();
const loadStylesObservable = new Subject<AssetsLoadResult[]>();
const loadScriptsValues = [
{
src: scripts[0],
hashCode: hashCode(scripts[0]),
loaded: true,
status: 'Loaded'
},
{
src: scripts[1],
hashCode: hashCode(scripts[1]),
loaded: true,
status: 'Loaded'
}
];
const loadStylesValues = [
{
src: styles[0],
hashCode: hashCode(styles[0]),
loaded: true,
status: 'Loaded'
},
{
src: styles[1],
hashCode: hashCode(styles[1]),
loaded: true,
status: 'Loaded'
}
];
loadScriptsSpy.and.returnValue(loadScriptsObservable);
loadStylesSpy.and.returnValue(loadStylesObservable);
expect(loadScriptsSpy).not.toHaveBeenCalled();
expect(loadStylesSpy).not.toHaveBeenCalled();
const loadedSuccess = jasmine.createSpy('loaded scripts and styles success');
const loadedFail = jasmine.createSpy('loaded scripts and styles fail');
assetsLoader.loadScriptsAndStyles(scripts, styles).subscribe(loadedSuccess, loadedFail);
expect(loadScriptsSpy).toHaveBeenCalledTimes(1);
expect(loadStylesSpy).toHaveBeenCalledTimes(1);
expect(loadedSuccess).not.toHaveBeenCalled();
loadScriptsObservable.next(loadScriptsValues);
loadScriptsObservable.complete();
loadStylesObservable.next(loadStylesValues);
loadStylesObservable.complete();
expect(loadedSuccess).toHaveBeenCalledTimes(1);
expect(loadedSuccess).toHaveBeenCalledWith([loadScriptsValues, loadStylesValues]);
}));
it('should return null when scripts and styles is []', fakeAsync(() => {
const scripts = [];
const styles = [];
const loadScriptsSpy = spyOn(assetsLoader, 'loadScripts');
const loadStylesSpy = spyOn(assetsLoader, 'loadStyles');
const loadScriptsObservable = new Subject<AssetsLoadResult[]>();
const loadStylesObservable = new Subject<AssetsLoadResult[]>();
loadScriptsSpy.and.returnValue(loadScriptsObservable);
loadStylesSpy.and.returnValue(loadStylesObservable);
expect(loadScriptsSpy).not.toHaveBeenCalled();
expect(loadStylesSpy).not.toHaveBeenCalled();
const loadedSuccess = jasmine.createSpy('loaded scripts and styles success');
const loadedFail = jasmine.createSpy('loaded scripts and styles fail');
assetsLoader.loadScriptsAndStyles(scripts, styles).subscribe(loadedSuccess, loadedFail);
expect(loadScriptsSpy).toHaveBeenCalledTimes(1);
expect(loadStylesSpy).toHaveBeenCalledTimes(1);
expect(loadedSuccess).not.toHaveBeenCalled();
loadScriptsObservable.next(null);
loadScriptsObservable.complete();
loadStylesObservable.next(null);
loadStylesObservable.complete();
expect(loadedSuccess).toHaveBeenCalledTimes(1);
expect(loadedSuccess).toHaveBeenCalledWith([null, null]);
}));
});
}); | the_stack |
import { IEvent } from "@clarity-types/core";
import { Action } from "@clarity-types/layout";
import { cleanupPage, setupPageAndStartClarity } from "@karma/setup/page";
import { PubSubEvents, waitFor } from "@karma/setup/pubsub";
import { testAsync } from "@karma/setup/testasync";
import { stopWatching, watch } from "@karma/setup/watch";
import { NodeIndex, Tags } from "@src/plugins/layout/states/generic";
import { assert } from "chai";
describe("Layout: Mutation Tests", () => {
beforeEach(setupPageAndStartClarity);
afterEach(cleanupPage);
it("checks that dom additions are captured by clarity", testAsync(async (done: DoneFn) => {
watch();
let div = document.createElement("div");
let span = document.createElement("span");
span.innerHTML = "Clarity";
div.appendChild(span);
document.body.insertBefore(div, document.body.firstChild);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 3);
assert.equal(events[0].state.tag, "DIV");
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[1].state.tag, "SPAN");
assert.equal(events[2].state.tag, "*TXT*");
done();
}));
it("checks that dom removals are captured by clarity", testAsync(async (done: DoneFn) => {
watch();
let dom = document.getElementById("clarity");
dom.parentNode.removeChild(dom);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 1);
assert.equal(events[0].state.tag, "DIV");
assert.equal(events[0].state.action, Action.Remove);
done();
}));
it("checks that dom moves are captured correctly by clarity", testAsync(async (done: DoneFn) => {
watch();
let dom = document.getElementById("clarity");
let backup = document.getElementById("backup");
backup.appendChild(dom);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 1);
assert.equal(events.length, 1);
assert.equal(events[0].state.action, Action.Move);
done();
}));
it("checks that insertBefore works correctly", testAsync(async (done: DoneFn) => {
watch();
// Insert a node before an existing node
let dom = document.getElementById("clarity");
let backup = document.getElementById("backup");
let domIndex = dom[NodeIndex];
let firstChildIndex = dom.firstChild[NodeIndex];
dom.insertBefore(backup, dom.firstChild);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 1);
assert.equal(events.length, 1);
assert.equal(events[0].state.action, Action.Move);
assert.equal(events[0].state.parent, domIndex);
assert.equal(events[0].state.next, firstChildIndex);
done();
}));
it("checks that moving two known nodes to a new location such that they are siblings works correctly",
testAsync(async (done: DoneFn) => {
watch();
// Move multiple nodes from one parent to another
let dom = document.getElementById("clarity");
let backup = document.getElementById("backup");
let span = document.createElement("span");
dom.parentElement.appendChild(span);
span.appendChild(dom);
span.appendChild(backup);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 3);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.tag, "SPAN");
assert.equal(events[1].state.action, Action.Move);
assert.equal(events[1].state.index, dom[NodeIndex]);
assert.equal(events[1].state.next, backup[NodeIndex]);
assert.equal(events[2].state.action, Action.Move);
assert.equal(events[2].state.index, backup[NodeIndex]);
assert.equal(events[2].state.next, null);
done();
})
);
it("checks dom changes are captured accurately when multiple siblings are moved to another parent", testAsync(async (done: DoneFn) => {
watch();
// Move multiple nodes from one parent to another
let dom = document.getElementById("clarity");
let backup = document.getElementById("backup");
let backupIndex = backup[NodeIndex];
let childrenCount = dom.childNodes.length;
while (dom.childNodes.length > 0) {
backup.appendChild(dom.childNodes[0]);
}
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, childrenCount);
assert.equal(events[0].state.action, Action.Move);
assert.equal(events[0].state.parent, backupIndex);
assert.equal(events[4].state.parent, backupIndex);
assert.equal(events[4].state.next, events[5].state.index);
done();
}));
it("checks that insertion of multiple nodes in the same mutation record is handled correctly", testAsync(async (done: DoneFn) => {
watch();
let df = document.createDocumentFragment();
let n1 = document.createElement("div");
let n2 = document.createElement("span");
let n3 = document.createElement("a");
let backup = document.getElementById("backup");
let backupPrevious = backup.previousSibling;
df.appendChild(n1);
df.appendChild(n2);
df.appendChild(n3);
backup.parentElement.insertBefore(df, backup);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 3);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.tag, "DIV");
assert.equal(events[0].state.previous, backupPrevious[NodeIndex]);
assert.equal(events[0].state.next, n2[NodeIndex]);
// Check SPAN insert event
assert.equal(events[1].state.action, Action.Insert);
assert.equal(events[1].state.tag, "SPAN");
assert.equal(events[1].state.next, n3[NodeIndex]);
// Check A insert event
assert.equal(events[2].state.action, Action.Insert);
assert.equal(events[2].state.tag, "A");
assert.equal(events[2].state.next, backup[NodeIndex]);
done();
}));
it("checks that removal of multiple nodes in the same mutation record is handled correctly", testAsync(async (done: DoneFn) => {
watch();
let dom = document.getElementById("clarity");
let children = [];
let childIndices = [];
for (let i = 0; i < dom.childNodes.length; i++) {
let child = dom.childNodes[i];
let index = child[NodeIndex];
children.push(child);
childIndices[index] = true;
}
// Remove all children
dom.innerHTML = "";
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
// Make sure that there is a remove event for every child
for (let i = 0; i < events.length; i++) {
let index = events[i].state.index;
assert.equal(events[i].state.action, Action.Remove);
assert.equal(childIndices[index], true);
delete childIndices[index];
}
// Make sure that clarity index is cleared from all removed nodes
for (let i = 0; i < children.length; i++) {
assert.equal(NodeIndex in children[i], false);
}
done();
}));
// Nodes that are inserted and then removed in the same mutation don't produce any events and their mutations are ignored
// However, it's possible that some other observed node can be appended to the ignored node and then get removed from the
// DOM as a part of the ignored node's subtree. This test makes sure that removing observed node this way is captured correctly.
it("checks that removal of a known node through a subtree of its ignored parent is handled correctly",
testAsync(async (done: DoneFn) => {
watch();
let clarityNode = document.getElementById("clarity");
let backupNode = document.getElementById("backup");
let backupNodeIndex = backupNode[NodeIndex];
let tempNode = document.createElement("div");
clarityNode.appendChild(tempNode);
tempNode.appendChild(backupNode);
clarityNode.removeChild(tempNode);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 1);
assert.equal(events[0].state.action, Action.Remove);
assert.equal(events[0].state.index, backupNodeIndex);
// Make sure that clarity index is cleared from all removed nodes
assert.equal(NodeIndex in tempNode, false);
assert.equal(NodeIndex in backupNode, false);
done();
})
);
it("checks that dom addition with immediate move ignores the 'Move' action", testAsync(async (done: DoneFn) => {
watch();
// Add a node to the document
let clarity = document.getElementById("clarity");
let div = document.createElement("div");
document.body.appendChild(div);
clarity.appendChild(div);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 1);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.tag, "DIV");
assert.equal(events[0].state.parent, clarity[NodeIndex]);
done();
}));
it("checks that dom addition with the follow-up attribute change captures the 'Update' action", testAsync(async (done: DoneFn) => {
watch();
let div = document.createElement("div");
document.body.appendChild(div);
await waitFor(PubSubEvents.MUTATION);
div.setAttribute("data-clarity", "test");
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 2);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.tag, "DIV");
assert.equal(events[1].state.action, Action.Update);
done();
}));
it("checks that dom addition with immediate attribute change ignores the 'Update' action", testAsync(async (done: DoneFn) => {
watch();
let div = document.createElement("div");
document.body.appendChild(div);
div.setAttribute("data-clarity", "test");
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 1);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.tag, "DIV");
done();
}));
it("checks that nodes that are added and removed in the same mutation don't create index gaps in event logs ",
testAsync(async (done: DoneFn) => {
watch();
let div1 = document.createElement("div");
let div2 = document.createElement("div");
let div3 = document.createElement("div");
document.body.appendChild(div1);
document.body.appendChild(div3);
document.body.appendChild(div2);
document.body.removeChild(div3);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 2);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.index, div1[NodeIndex]);
assert.equal(events[1].state.action, Action.Insert);
assert.equal(events[1].state.index, div2[NodeIndex]);
assert.equal(div1[NodeIndex], div2[NodeIndex] - 1);
done();
})
);
it("checks that we do not instrument disconnected dom tree", testAsync(async (done: DoneFn) => {
watch();
let div = document.createElement("div");
document.body.appendChild(div);
document.body.removeChild(div);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
// Prove that we didn't send any extra instrumentation back for no-op mutation
assert.equal(events.length, 0);
// Make sure that clarity index is cleared from all removed nodes
assert.equal(NodeIndex in div, false);
done();
}));
it("checks that we do not instrument child nodes within disconnected dom tree", testAsync(async (done: DoneFn) => {
watch();
let div = document.createElement("div");
let span = document.createElement("span");
document.body.appendChild(div);
div.appendChild(span);
document.body.removeChild(div);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
// Prove that we didn't send any extra instrumentation back for no-op mutation
assert.equal(events.length, 0);
// Make sure that clarity index is cleared from all removed nodes
assert.equal(NodeIndex in div, false);
assert.equal(NodeIndex in span, false);
done();
}));
it("checks that we do not instrument child nodes within a previously observed disconnected dom tree",
testAsync(async (done: DoneFn) => {
watch();
let clarityDiv = document.getElementById("clarity");
let span = document.createElement("span");
let clarityDivIndex = clarityDiv[NodeIndex];
clarityDiv.appendChild(span);
clarityDiv.parentElement.removeChild(clarityDiv);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
// Prove that we didn't send any extra instrumentation back for no-op mutation
assert.equal(events.length, 1);
assert.equal(events[0].state.action, Action.Remove);
assert.equal(events[0].state.index, clarityDivIndex);
// Make sure that clarity index is cleared from all removed nodes
assert.equal(NodeIndex in clarityDiv, false);
assert.equal(NodeIndex in span, false);
done();
})
);
it("checks that we do not instrument inserted nodes twice", testAsync(async (done: DoneFn) => {
watch();
// Edge case scenario for the test:
// 1. Node n1 is added to the page
// 2. Immediately node n2 is appended to n1
// They both show up as insertions in the same batch of mutations
// When we serialize n1, we will discover its children and serialize n2 as well
// Make sure we don't serialize n2 again when we move on to n2 insertion mutation record
let n1 = document.createElement("div");
let n2 = document.createElement("span");
let bodyIndex = document.body[NodeIndex];
document.body.appendChild(n1);
n1.appendChild(n2);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 2);
// Check DIV insert event
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.parent, bodyIndex);
assert.equal(events[0].state.tag, "DIV");
// Check SPAN insert event
assert.equal(events[1].state.action, Action.Insert);
assert.equal(events[1].state.parent, n1[NodeIndex]);
assert.equal(events[1].state.tag, "SPAN");
done();
}));
it("checks that all kinds of mutations within the same batch have the same mutation sequence", testAsync(async (done: DoneFn) => {
watch();
let divOne = document.createElement("div");
let clarityDiv = document.getElementById("clarity");
let backup = document.getElementById("backup");
document.body.appendChild(divOne); // Insert
clarityDiv.firstElementChild.id = "updatedId"; // Update
divOne.appendChild(clarityDiv); // Move
backup.parentElement.removeChild(backup); // Remove
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 4);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[1].state.action, Action.Move);
assert.equal(events[2].state.action, Action.Update);
assert.equal(events[3].state.action, Action.Remove);
// Make sure all events have the same mutation sequence
let mutationSequence = events[0].state.mutationSequence;
assert.isTrue(mutationSequence >= 0);
assert.equal(events[0].state.mutationSequence, mutationSequence);
assert.equal(events[1].state.mutationSequence, mutationSequence);
assert.equal(events[2].state.mutationSequence, mutationSequence);
assert.equal(events[3].state.mutationSequence, mutationSequence);
done();
}));
it("checks that mutation sequence number is incremented between mutation callbacks", testAsync(async (done: DoneFn) => {
watch();
let divOne = document.createElement("div");
let divTwo = document.createElement("div");
document.body.appendChild(divOne);
await waitFor(PubSubEvents.MUTATION);
document.body.appendChild(divTwo);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 2);
assert.equal(events[0].state.mutationSequence, 0);
assert.equal(events[1].state.mutationSequence, 1);
done();
}));
it("checks that script element and its text are ignored", testAsync(async (done: DoneFn) => {
watch();
let script = document.createElement("script");
script.innerText = "/*some javascriptcode*/";
document.body.appendChild(script);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 2);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.tag, Tags.Ignore);
assert.equal(events[0].state.nodeType, Node.ELEMENT_NODE);
assert.equal(events[1].state.action, Action.Insert);
assert.equal(events[1].state.tag, Tags.Ignore);
assert.equal(events[1].state.nodeType, Node.TEXT_NODE);
done();
}));
it("checks that comment node is ignored", testAsync(async (done: DoneFn) => {
watch();
let comment = document.createComment("some explanation");
document.body.appendChild(comment);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 1);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.tag, Tags.Ignore);
assert.equal(events[0].state.nodeType, Node.COMMENT_NODE);
done();
}));
it("checks that meta element is ignored", testAsync(async (done: DoneFn) => {
watch();
let meta = document.createElement("meta");
document.body.appendChild(meta);
await waitFor(PubSubEvents.MUTATION);
const events = stopWatching().coreEvents;
assert.equal(events.length, 1);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.tag, Tags.Ignore);
assert.equal(events[0].state.nodeType, Node.ELEMENT_NODE);
done();
}));
// This test is related to a specific MutationObserver behavior in Internet Explorer for this scenario:
// 1. Append script 'myscript' to the page
// 2. 'myscript' executes and appends 'mydiv' div to the page
// 3. Inspect MutationObserver callback
// In Chrome:
// MutationObserver will invoke a callback and show 2 mutation records:
// (1) script added
// (2) <div> added
// In IE:
// (1) MutationObserver will invoke first callback with 1 mutation record: <div> added
// (2) MutationObserver will invoke second callback with 1 mutation record: script added
// The problem with this behavior in IE is that during the first MutationObserver's callback, script element
// can already be observed in the DOM, even though its mutation is not reported in the callback.
// As a result, after processing (1), DOM and ShadowDOM states are not consistent until (2) is processed.
// This breaks functionality, because after (1) we determine that ShadowDOM arrived to the inconsistent
// state and stop processing mutations.
// Solution:
// Wait for 2 consequtive mutations that bring ShadowDOM to the inconsistent state before disabling mutation processing.
it("checks that inserting script, which inserts an element, works correctly", testAsync(async (done: DoneFn) => {
watch();
let events: IEvent[] = [];
let script = document.createElement("script");
script.type = "text/javascript";
script.innerHTML = `var div=document.createElement("div");div.id="newdiv";document.body.appendChild(div);`;
document.body.appendChild(script);
await waitFor(PubSubEvents.MUTATION);
let newEvents = stopWatching().coreEvents;
events = events.concat(newEvents);
if (events.length === 1) {
watch();
await waitFor(PubSubEvents.MUTATION);
newEvents = stopWatching().coreEvents;
events = events.concat(newEvents);
watch();
// Add another mutation to ensure that we continue processing mutations
document.body.appendChild(document.createElement("span"));
await waitFor(PubSubEvents.MUTATION);
newEvents = stopWatching().coreEvents;
assert.equal(events.length, 4);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.tag, "DIV");
assert.equal(events[1].state.action, Action.Insert);
assert.equal(events[1].state.tag, Tags.Ignore);
assert.equal(events[2].state.action, Action.Insert);
assert.equal(events[2].state.tag, Tags.Ignore);
assert.equal(events[3].state.action, Action.Insert);
assert.equal(events[3].state.tag, "SPAN");
done();
} else {
// Non-IE path: Both div and script are reported in the first callback
assert.equal(events.length, 3);
assert.equal(events[0].state.action, Action.Insert);
assert.equal(events[0].state.tag, Tags.Ignore);
assert.equal(events[1].state.action, Action.Insert);
assert.equal(events[1].state.tag, Tags.Ignore);
assert.equal(events[2].state.action, Action.Insert);
assert.equal(events[2].state.tag, "DIV");
done();
}
}));
}); | the_stack |
import { chimeeLog } from 'chimee-helper-log';
import { off as removeEvent, on as addEvent } from 'dom-helpers/events';
import { clone, isArray, isEmpty, isError, isFunction, isPlainObject, isString } from 'lodash';
import { autobind, before, nonenumerable } from 'toxic-decorators';
import { isPromise } from 'toxic-predicate-functions';
import { camelize } from 'toxic-utils';
import defaultContainerConfig from '../config/container';
import Vessel from '../config/vessel';
import VideoConfig from '../config/video';
import { videoDomAttributes } from '../const/attribute';
import Binder from '../dispatcher/binder';
import Dom from '../dispatcher/dom';
import ChimeeKernel, { getLegalBox, IChimeeKernelConfig } from '../dispatcher/kernel';
import ChimeePlugin, { IChimeePluginConstructor } from '../dispatcher/plugin';
import { isSupportedKernelType, runRejectableQueue, transObjectAttrIntoArray } from '../helper/utils';
import Chimee from '../index';
import { IVideoKernelConstructor } from '../kernels/base';
import { ChimeePictureInPictureOnWindow } from '../plugin/picture-in-picture';
import PictureInPicture from '../plugin/picture-in-picture';
import { PluginConfig, PluginOption, SingleKernelConfig, SupportedKernelType, UserConfig, UserKernelsConfig, UserKernelsConstructorMap } from '../typings/base';
declare global {
// tslint:disable-next-line:interface-name
interface Window {
__chimee_picture_in_picture: ChimeePictureInPictureOnWindow;
}
}
const pluginConfigSet: {
[id: string]: PluginConfig | IChimeePluginConstructor,
} = {};
const kernelsSet: { [key in SupportedKernelType]?: IVideoKernelConstructor } = {};
function convertNameIntoId(name: string): string {
if (!isString(name)) { throw new Error(`Plugin's name must be a string, but not "${name}" in ${typeof name}`); }
return camelize(name);
}
function checkPluginConfig(config: PluginConfig | IChimeePluginConstructor) {
if (isFunction(config)) {
if (!(config.prototype instanceof ChimeePlugin)) {
throw new TypeError(`Your are trying to install plugin ${config.name}, but it's not extends from Chimee.plugin.`);
}
return;
}
if (!isPlainObject(config) || isEmpty(config)) { throw new TypeError(`plugin's config must be an Object, but not "${config}" in ${typeof config}`); }
const { name } = config;
if (!isString(name) || name.length < 1) { throw new TypeError(`plugin must have a legal namea, but not "${name}" in ${typeof name}`); }
}
export interface IFriendlyDispatcher {
getTopLevel: Dispatcher['getTopLevel'];
sortZIndex: Dispatcher['sortZIndex'];
}
/**
* <pre>
* Dispatcher is the hub of plugins, user, and video kernel.
* It take charge of plugins install, use and remove
* It also offer a bridge to let user handle video kernel.
* </pre>
*/
export default class Dispatcher {
/**
* get Plugin config based on plugin's id
* @type {[type]}
*/
@before(convertNameIntoId)
public static getPluginConfig(id: string): PluginConfig | void | IChimeePluginConstructor {
return pluginConfigSet[id];
}
@before(convertNameIntoId)
public static hasInstalled(id: string): boolean {
return !!pluginConfigSet[id];
}
public static hasInstalledKernel(key: SupportedKernelType) {
return isFunction(kernelsSet[key]);
}
@nonenumerable
get inPictureInPictureMode(): boolean {
return 'pictureInPictureEnabled' in document
// @ts-ignore: support new function in document
? this.dom.videoElement === (document as Document).pictureInPictureElement
: Boolean(this.plugins.pictureInPicture && this.plugins.pictureInPicture.isShown);
}
/**
* static method to install plugin
* we will store the plugin config
* @type {string} plugin's id
*/
@before(checkPluginConfig)
public static install(config: PluginConfig | IChimeePluginConstructor): string {
const { name } = config;
const id = camelize(name);
if (pluginConfigSet[id]) {
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
chimeeLog.warn('Dispatcher', 'You have installed ' + name + ' again. And the older one will be replaced');
}
}
const pluginConfig = isFunction(config)
? config
: Object.assign({}, config, { id });
pluginConfigSet[id] = pluginConfig;
return id;
}
public static installKernel(key: SupportedKernelType | { [key in SupportedKernelType]?: IVideoKernelConstructor }, value?: IVideoKernelConstructor) {
const tasks = isPlainObject(key)
? Object.entries(key)
: [[ key, value ]];
(tasks as Array<[ SupportedKernelType, IVideoKernelConstructor ]>).forEach(([ key, value ]) => {
if (!isFunction(value)) {
throw new Error(`The kernel you install on ${key} must be a Function, but not ${typeof value}`);
}
if (isFunction(kernelsSet[key])) {
chimeeLog.warn(`You have alrady install a kernel on ${key}, and now we will replace it`);
}
kernelsSet[key] = value;
});
}
@before(convertNameIntoId)
public static uninstall(id: string) {
delete pluginConfigSet[id];
}
// only use for debug in internal
public static uninstallKernel(key: SupportedKernelType) {
delete kernelsSet[key];
}
public binder: Binder;
public changeWatchable: boolean = true;
public containerConfig: Vessel;
public destroyed: true;
public dom: Dom;
public kernel: ChimeeKernel;
// to save the kernel event handler, so that we can remove it when we destroy the kernel
public kernelEventHandlerList: Array<(...args: any[]) => any> = [];
/**
* plugin's order
* @type {Array<string>}
* @member order
*/
public order: string[] = [];
/**
* all plugins instance set
* @type {Object}
* @member plugins
*/
public plugins: {
[id: string]: ChimeePlugin,
pictureInPicture?: PictureInPicture,
} = {};
public ready: Promise<void>;
/**
* the synchronous ready flag
* @type {boolean}
* @member readySync
*/
public readySync: boolean = false;
public videoConfig: VideoConfig;
public videoConfigReady: boolean;
public vm: Chimee;
/**
* the z-index map of the dom, it contain some important infomation
* @type {Object}
* @member zIndexMap
*/
public zIndexMap: {
inner: string[];
outer: string[];
} = {
inner: [],
outer: [],
};
// 测试用的临时记录
private silentLoadTempKernel: ChimeeKernel | void;
/**
* @param {UserConfig} config UserConfig for whole Chimee player
* @param {Chimee} vm referrence of outer class
* @return {Dispatcher}
*/
constructor(config: UserConfig, vm: Chimee) {
if (!isPlainObject(config)) { throw new TypeError(`UserConfig must be an Object, but not "${config}" in ${typeof config}`); }
/**
* dom Manager
* @type {Dom}
*/
this.dom = new Dom(config, this);
/**
* Chimee's referrence
* @type {[type]}
*/
this.vm = vm;
/**
* tell user have Chimee installed finished
* @type {Promises}
*/
this.videoConfigReady = false;
// create the videoconfig
this.videoConfig = new VideoConfig(this, config);
// support both plugin and plugins here as people often cofuse both
if (isArray(config.plugins) && !isArray(config.plugin)) {
config.plugin = config.plugins;
delete config.plugins;
}
this.binder = new Binder(this);
this.binder.listenOnMouseMoveEvent(this.dom.videoElement);
// use the plugin user want to use
this.initUserPlugin(config.plugin);
// add default config for container
const containerConfig = Object.assign({}, defaultContainerConfig, config.container || {});
// trigger the init life hook of plugin
this.order.forEach((key) => this.plugins[key].runInitHook(this.videoConfig));
this.videoConfigReady = true;
this.videoConfig.init();
this.containerConfig = new Vessel(this, 'container', containerConfig);
/**
* video kernel
* @type {Kernel}
*/
this.kernel = this.createKernel(this.dom.videoElement, this.videoConfig);
this.binder.applyPendingEvents('kernel');
if (config.noDefaultContextMenu) {
const { noDefaultContextMenu } = config;
const target = (noDefaultContextMenu === 'container' || noDefaultContextMenu === 'wrapper')
? noDefaultContextMenu
: 'video-dom';
this.binder.on({
fn: (evt) => evt.preventDefault(),
id: '_vm',
name: 'contextmenu',
stage: 'main',
target,
});
}
// trigger auto load event
const asyncInitedTasks: Array<Promise<ChimeePlugin>> = [];
this.order.forEach((key) => {
const ready = this.plugins[key].runInitedHook();
if (isPromise(ready)) {
asyncInitedTasks.push(ready);
}
});
this.readySync = asyncInitedTasks.length === 0;
// tell them we have inited the whold player
this.ready = this.readySync
? Promise.resolve()
: Promise.all(asyncInitedTasks)
.then(() => {
this.readySync = true;
this.onReady();
});
if (this.readySync) { this.onReady(); }
}
/**
* destroy function called when dispatcher destroyed
*/
public destroy() {
for (const key in this.plugins) {
if (this.plugins.hasOwnProperty(key)) {
this.unuse(key);
}
}
this.binder.destroy();
delete this.binder;
this.dom.destroy();
delete this.dom;
this.kernel.destroy();
delete this.kernel;
delete this.vm;
delete this.plugins;
delete this.order;
this.destroyed = true;
}
public exitPictureInPicture() {
if ('pictureInPictureEnabled' in document) {
// if current video is not in picture-in-picture mode, do nothing
if (this.inPictureInPictureMode) {
window.__chimee_picture_in_picture = undefined;
// @ts-ignore: support new function in document
return (document as Document).exitPictureInPicture();
}
}
return this.plugins.pictureInPicture && this.plugins.pictureInPicture.exitPictureInPicture();
}
public getPluginConfig(id: string): PluginConfig | void | IChimeePluginConstructor {
return Dispatcher.getPluginConfig(id);
}
@before(convertNameIntoId)
public hasUsed(id: string) {
const plugin = this.plugins[id];
return isPlainObject(plugin);
}
public load(
srcOrOption: string | {
box?: string,
isLive?: boolean,
kernels?: UserKernelsConfig,
preset?: UserConfig['preset'],
src: string,
},
option: {
box?: string,
isLive?: boolean,
kernels?: UserKernelsConfig,
preset?: UserConfig['preset'],
} = {}) {
const src: string = isString(srcOrOption)
? srcOrOption
: isPlainObject(srcOrOption) && isString(srcOrOption.src)
? srcOrOption.src
// give a chance for user to clear the src
: '';
if (!isString(srcOrOption)) {
delete srcOrOption.src;
option = srcOrOption;
}
const oldBox = this.kernel.box;
const videoConfig = this.videoConfig;
const {
isLive = videoConfig.isLive,
box = getLegalBox({ src, box: videoConfig.box }),
preset = videoConfig.preset,
kernels = videoConfig.kernels,
} = option;
if (box !== 'native' || box !== oldBox || !isEmpty(option)) {
const video = document.createElement('video');
const config = { isLive, box, preset, src, kernels };
const kernel = this.createKernel(video, config);
this.switchKernel({ video, kernel, config, notifyChange: true });
}
const originAutoLoad = this.videoConfig.autoload;
this.changeUnwatchable(this.videoConfig, 'autoload', false);
this.videoConfig.src = src || this.videoConfig.src;
this.kernel.load(this.videoConfig.src);
this.changeUnwatchable(this.videoConfig, 'autoload', originAutoLoad);
}
public onReady() {
this.binder.trigger({
id: 'dispatcher',
name: 'ready',
target: 'plugin',
});
this.autoloadVideoSrcAtFirst();
}
public async requestPictureInPicture() {
if ('pictureInPictureEnabled' in document) {
// if video is in picture-in-picture mode, do nothing
if (this.inPictureInPictureMode) { return Promise.resolve(window.__chimee_picture_in_picture); }
const pipWindow = await (this.dom.videoElement as any).requestPictureInPicture();
window.__chimee_picture_in_picture = pipWindow;
// if (autoplay) this.play();
return pipWindow;
}
if (!Dispatcher.hasInstalled(PictureInPicture.name)) {
Dispatcher.install(PictureInPicture);
}
if (!this.hasUsed(PictureInPicture.name)) {
this.use(PictureInPicture.name);
}
return this.plugins.pictureInPicture.requestPictureInPicture();
}
public silentLoad(src: string, option: {
abort?: boolean,
bias?: number,
box?: string,
duration?: number,
immediate?: boolean,
increment?: number,
isLive?: boolean,
kernels?: UserKernelsConfig,
preset?: UserConfig['preset'],
repeatTimes?: number,
} = {}): Promise<void | {}> {
const {
duration = 3,
bias = 0,
repeatTimes = 0,
increment = 0,
isLive = this.videoConfig.isLive,
box = this.videoConfig.box,
kernels = this.videoConfig.kernels,
preset = this.videoConfig.preset,
} = option;
// all live stream seem as immediate mode
// it's impossible to seek on live stream
const immediate = option.immediate || isLive;
// form the base config for kernel
// it should be the same as the config now
const config = { isLive, box, src, kernels, preset };
// build tasks accroding repeat times
const tasks = new Array(repeatTimes + 1).fill(1).map((value, index) => {
return () => {
return new Promise((resolve, reject) => {
// if abort, give up and reject
if (option.abort) { reject({ error: true, message: 'user abort the mission' }); }
const video = document.createElement('video');
const idealTime = this.kernel.currentTime + duration + increment * index;
video.muted = true;
const that = this;
let newVideoReady = false;
let kernel: ChimeeKernel;
// bind time update on old video
// when we bump into the switch point and ready
// we switch
function oldVideoTimeupdate() {
const currentTime = that.kernel.currentTime;
if ((bias <= 0 && currentTime >= idealTime) ||
(bias > 0 &&
((Math.abs(idealTime - currentTime) <= bias && newVideoReady) ||
(currentTime - idealTime) > bias))
) {
removeEvent(that.dom.videoElement, 'timeupdate', oldVideoTimeupdate);
removeEvent(video, 'error', videoError, true);
if (!newVideoReady) {
removeEvent(video, 'canplay', videoCanplay, true);
removeEvent(video, 'loadedmetadata', videoLoadedmetadata, true);
kernel.destroy();
return resolve();
}
return reject({
error: false,
kernel,
video,
});
}
}
function videoCanplay() {
newVideoReady = true;
// you can set it immediately run by yourself
if (immediate) {
removeEvent(that.dom.videoElement, 'timeupdate', oldVideoTimeupdate);
removeEvent(video, 'error', videoError, true);
return reject({
error: false,
kernel,
video,
});
}
}
function videoLoadedmetadata() {
if (!isLive) {
kernel.seek(immediate ? this.kernel.currentTime : idealTime);
}
}
function videoError(evt: ErrorEvent) {
removeEvent(video, 'canplay', videoCanplay, true);
removeEvent(video, 'loadedmetadata', videoLoadedmetadata, true);
removeEvent(that.dom.videoElement, 'timeupdate', oldVideoTimeupdate);
kernel.off('error', videoError);
let error;
// TODO: need to add the kernel error declare here
if (evt && (evt as any).errmsg) {
const { errmsg } = (evt as any);
chimeeLog.error('chimee\'s silentload bump into a kernel error', errmsg);
error = new Error(errmsg);
} else {
error = !isEmpty(video.error)
? new Error(video.error.message)
: new Error('unknow video error');
chimeeLog.error('chimee\'s silentload', error.message);
}
kernel.destroy();
that.silentLoadTempKernel = undefined;
return index === repeatTimes
? reject(error)
: resolve(error);
}
addEvent(video, 'canplay', videoCanplay, true);
addEvent(video, 'loadedmetadata', videoLoadedmetadata.bind(this), true);
addEvent(video, 'error', videoError, true);
kernel = this.createKernel(video, config);
this.silentLoadTempKernel = kernel;
kernel.on('error', videoError);
addEvent(this.dom.videoElement, 'timeupdate', oldVideoTimeupdate);
kernel.load();
});
};
});
return runRejectableQueue(tasks)
.then(() => {
const message = `The silentLoad for ${src} timed out. Please set a longer duration or check your network`;
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
chimeeLog.warn('chimee\'s silentLoad', message);
}
return Promise.reject(new Error(message));
}).catch((result: Error | { error: string, message: string } | { kernel: ChimeeKernel, video: HTMLVideoElement }) => {
if (isError(result)) {
return Promise.reject(result);
}
let kernelError: { error: string, message: string } | void;
let data: { kernel: ChimeeKernel, video: HTMLVideoElement };
if ((result as any).error) {
kernelError = (result as { error: string, message: string });
} else {
data = (result as { kernel: ChimeeKernel, video: HTMLVideoElement });
}
if (kernelError && kernelError.error) {
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
chimeeLog.warn('chimee\'s silentLoad', kernelError.message);
}
return Promise.reject(new Error(kernelError.message));
}
const { video, kernel } = data;
if (option.abort) {
kernel.destroy();
return Promise.reject(new Error('user abort the mission'));
}
const paused = this.dom.videoElement.paused;
if (paused) {
this.switchKernel({ video, kernel, config });
return Promise.resolve();
}
return new Promise((resolve) => {
addEvent(video, 'play', () => {
this.switchKernel({ video, kernel, config });
resolve();
}, true);
(video as HTMLVideoElement).play();
});
});
}
public switchKernel({ video, kernel, config, notifyChange }: {
config: {
box: string,
isLive: boolean,
kernels: UserKernelsConfig,
preset: UserConfig['preset'],
src: string,
},
kernel: ChimeeKernel,
notifyChange?: boolean,
video: HTMLVideoElement,
}) {
const oldKernel = this.kernel;
const originVideoConfig = clone(this.videoConfig);
this.dom.migrateVideoRequiredGuardedAttributes(video);
this.dom.removeVideo();
this.dom.installVideo(video);
// as we will reset the currentVideoConfig on the new video
// it will trigger the watch function as they maybe differnet
// because video config will return the real situation
// so we need to stop them
this.videoConfig.changeWatchable = false;
this.videoConfig.autoload = false;
this.videoConfig.src = config.src;
videoDomAttributes.forEach((key) => {
if (key !== 'src') { this.videoConfig[key] = originVideoConfig[key]; }
});
this.videoConfig.changeWatchable = true;
this.binder.migrateKernelEvent(oldKernel, kernel);
this.kernel = kernel;
this.silentLoadTempKernel = undefined;
const { isLive, box, preset, kernels } = config;
Object.assign(this.videoConfig, { isLive, box, preset, kernels });
oldKernel.destroy();
// delay video event binding
// so that people can't feel the default value change
// unless it's caused by autoload
if (notifyChange) {
if (this.binder && this.binder.bindEventOnVideo) {
this.binder.bindEventOnVideo(video);
}
} else {
setTimeout(() => {
if (this.binder && this.binder.bindEventOnVideo) {
this.binder.bindEventOnVideo(video);
}
});
}
// if we are in picutre in picture mode
// we need to exit thie picture in picture mode
if (this.inPictureInPictureMode) {
this.exitPictureInPicture();
}
}
@(autobind as MethodDecorator)
public throwError(error: Error | string) {
this.vm.customThrowError(error);
}
/**
* unuse an plugin, we will destroy the plugin instance and exlude it
* @param {string} name plugin's name
*/
@before(convertNameIntoId)
public unuse(id: string) {
const plugin = this.plugins[id];
if (!plugin) {
delete this.plugins[id];
return;
}
plugin.$destroy();
const orderIndex = this.order.indexOf(id);
if (orderIndex > -1) {
this.order.splice(orderIndex, 1);
}
delete this.plugins[id];
// @ts-ignore: delete the plugin hooks on chimee itself
delete this.vm[id];
}
/**
* use a plugin, which means we will new a plugin instance and include int this Chimee instance
* @param {Object|string} option you can just set a plugin name or plugin config
* @return {Promise}
*/
public use(option: string | PluginOption): Promise<ChimeePlugin> {
if (isString(option)) { option = { name: option, alias: undefined }; }
if (!isPlainObject(option) || (isPlainObject(option) && !isString(option.name))) {
throw new TypeError('pluginConfig do not match requirement');
}
if (!isString(option.alias)) { option.alias = undefined; }
const { name, alias } = option;
option.name = alias || name;
delete option.alias;
const key = camelize(name);
const id = camelize(alias || name);
const pluginOption = option;
const pluginConfig = Dispatcher.getPluginConfig(key);
if (!pluginConfig) {
throw new TypeError('You have not installed plugin ' + key);
}
if (isPlainObject(pluginConfig)) {
(pluginConfig as PluginConfig).id = id;
}
const plugin = isFunction(pluginConfig)
? new (pluginConfig as IChimeePluginConstructor)({id}, this, pluginOption)
: new ChimeePlugin((pluginConfig as PluginConfig), this, pluginOption);
this.plugins[id] = plugin;
Object.defineProperty(this.vm, id, {
configurable: true,
enumerable: false,
value: plugin,
writable: false,
});
this.order.push(id);
this.sortZIndex();
if (this.videoConfigReady) {
plugin.runInitedHook();
}
return plugin.ready;
}
private autoloadVideoSrcAtFirst() {
if (this.videoConfig.autoload) {
if (process.env.NODE_ENV !== 'prodution' && !this.videoConfig.src) {
chimeeLog.warn('You have not set the src, so you better set autoload to be false. Accroding to https://github.com/Chimeejs/chimee/blob/master/doc/zh-cn/chimee-api.md#src.');
return;
}
this.binder.emit({
id: 'dispatcher',
name: 'load',
target: 'plugin',
}, { src: this.videoConfig.src });
}
}
private changeUnwatchable(object: any, property: string, value: any) {
this.changeWatchable = false;
object[property] = value;
this.changeWatchable = true;
}
private createKernel(video: HTMLVideoElement, config: {
box: string;
isLive: boolean;
kernels: UserKernelsConfig;
preset: {
flv?: IVideoKernelConstructor;
hls?: IVideoKernelConstructor;
mp4?: IVideoKernelConstructor;
};
src: string;
}) {
const { kernels, preset } = config;
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production' && isEmpty(kernels) && !isEmpty(preset)) { chimeeLog.warn('preset will be deprecated in next major version, please use kernels instead.'); }
const presetConfig: { [key: string]: SingleKernelConfig } = {};
let newPreset: UserKernelsConstructorMap = {};
if (isArray(kernels)) {
// SKC means SingleKernelConfig
newPreset = (kernels as (Array< SupportedKernelType | SingleKernelConfig >)).reduce((kernels: UserKernelsConstructorMap, keyOrSKC: SupportedKernelType | SingleKernelConfig) => {
// if it is a string key, it means the kernel has been pre installed.
if (isString(keyOrSKC)) {
if (!isSupportedKernelType(keyOrSKC)) {
throw new Error(`We have not support ${keyOrSKC} kernel type`);
}
const kernelFn = kernelsSet[keyOrSKC];
if (!isFunction(kernelFn)) {
chimeeLog.warn(`You have not installed kernel for ${keyOrSKC}.`);
return kernels;
}
kernels[keyOrSKC] = kernelFn;
return kernels;
}
// if it is a SingleKernelConfig, it means user may pass in some config here
// so we need to extract the handler
// get the name of the handler
// and collect the config for the handler
if (isPlainObject(keyOrSKC)) {
const { name, handler } = keyOrSKC;
// if the handler is a pure string, it means the kernel has been pre installed
if (isString(handler)) {
if (!isSupportedKernelType(handler)) {
throw new Error(`We have not support ${handler} kernel type`);
}
const kernelFn = kernelsSet[handler];
if (!isFunction(kernelFn)) {
chimeeLog.warn(`You have not installed kernel for ${handler}.`);
return kernels;
}
kernels[handler] = kernelFn;
presetConfig[handler] = keyOrSKC;
return kernels;
}
// if the handler is a function, it means that the user pass in the kernel directly
// if the provide name, we use it as kernel name
// if they do not provide name, we just use the function's name
if (isFunction(handler)) {
const kernelName = name || handler.name;
if (!isSupportedKernelType(kernelName)) {
throw new Error(`We have not support ${kernelName} kernel type`);
}
kernels[kernelName] = handler;
presetConfig[kernelName] = keyOrSKC;
return kernels;
}
chimeeLog.warn(`When you pass in an SingleKernelConfig in Array, you must clarify it's handler, we only support handler in string or function but not ${typeof handler}`);
return kernels;
}
chimeeLog.warn(`If you pass in kernels as array, you must pass in kernels in string or function, but not ${typeof keyOrSKC}`);
return kernels;
}, {});
} else {
// SKC means SingleKernelConfig
Object.keys(kernels || {}).forEach((key: SupportedKernelType) => {
const fnOrSKC: SupportedKernelType | SingleKernelConfig | IVideoKernelConstructor = kernels[key];
// if it's a function, means we need to do nothing
if (isFunction(fnOrSKC)) {
const fn = (fnOrSKC as IVideoKernelConstructor);
newPreset[key] = fn;
return;
}
if (isPlainObject(fnOrSKC)) {
const SKC = (fnOrSKC as SingleKernelConfig);
const { handler } = SKC;
// if handler is an string, it means user has pre install it
if (isString(handler)) {
if (!isSupportedKernelType(handler)) {
throw new Error(`We have not support ${handler} kernel type`);
}
const kernelFn = kernelsSet[handler];
if (!isFunction(kernelFn)) {
chimeeLog.warn(`You have not installed kernel for ${handler}.`);
return;
}
newPreset[key] = kernelFn;
presetConfig[key] = SKC;
return;
}
if (isFunction(handler)) {
newPreset[key] = handler;
presetConfig[key] = SKC;
return;
}
chimeeLog.warn(`When you pass in an SingleKernelConfig in Object, you must clarify it's handler, we only support handler in string or function but not ${typeof handler}`);
return;
}
chimeeLog.warn(`If you pass in kernels as object, you must pass in kernels in string or function, but not ${typeof fnOrSKC}`);
return kernels;
});
}
config.preset = Object.assign(newPreset, preset);
const legalConfig: IChimeeKernelConfig = Object.assign(config, { presetConfig });
const kernel = new ChimeeKernel(video, legalConfig);
return kernel;
}
/**
* get the top element's level
* @param {boolean} inner get the inner array or the outer array
*/
private getTopLevel(inner: boolean): number {
const arr = this.zIndexMap[inner ? 'inner' : 'outer'];
const plugin = this.plugins[arr[arr.length - 1]];
return isEmpty(plugin) ? 0 : plugin.$level;
}
/**
* use a set of plugin
* @param {Array<UserPluginConfig>} configs a set of plugin config
* @return {Array<Promise>} a set of Promise indicate the plugin install stage
*/
private initUserPlugin(configs: Array<string | PluginOption> = []): Array<Promise<ChimeePlugin>> {
if (!isArray(configs)) {
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') { chimeeLog.warn('Dispatcher', `UserConfig.plugin can only by an Array, but not "${configs}" in ${typeof configs}`); }
configs = [];
}
return configs.map((config) => this.use(config));
}
/**
* sort zIndex of plugins to make plugin display in order
*/
private sortZIndex() {
const { inner, outer } = this.order.reduce((levelSet, key) => {
const plugin = this.plugins[key];
if (isEmpty(plugin)) { return levelSet; }
const set = levelSet[plugin.$inner ? 'inner' : 'outer'];
const level = plugin.$level;
set[level] = set[level] || [];
set[level].push(key);
return levelSet;
}, ({ inner: {}, outer: {} }) as { inner: { [x: number]: string[] }, outer: { [x: number]: string[] }});
inner[0] = inner[0] || [];
inner[0].unshift('videoElement');
outer[0] = outer[0] || [];
outer[0].unshift('container');
const innerOrderArr = transObjectAttrIntoArray(inner);
const outerOrderArr = transObjectAttrIntoArray(outer);
this.dom.setPluginsZIndex(innerOrderArr);
this.dom.setPluginsZIndex(outerOrderArr);
this.zIndexMap.inner = innerOrderArr;
this.zIndexMap.outer = outerOrderArr;
}
} | the_stack |
import * as React from 'react';
import classNames from 'classnames';
import KeyCode from 'rc-util/lib/KeyCode';
import type {
OptionListProps as SelectOptionListProps,
RefOptionListProps,
} from 'rc-select/lib/OptionList';
import { SelectContext } from 'rc-tree-select/lib/Context';
import type { OptionDataNode } from '../interface';
import Column from './Column';
import { isLeaf, restoreCompatibleValue } from '../util';
import CascaderContext from '../context';
import useSearchResult from '../hooks/useSearchResult';
type OptionListProps = SelectOptionListProps<OptionDataNode[]> & { prefixCls: string };
export type FlattenOptions = OptionListProps['flattenOptions'];
const RefOptionList = React.forwardRef<RefOptionListProps, OptionListProps>((props, ref) => {
const {
prefixCls,
options,
onSelect,
multiple,
open,
flattenOptions,
searchValue,
onToggleOpen,
notFoundContent,
direction,
} = props;
const containerRef = React.useRef<HTMLDivElement>();
const rtl = direction === 'rtl';
const { checkedKeys, halfCheckedKeys } = React.useContext(SelectContext);
const { changeOnSelect, expandTrigger, fieldNames, loadData, search, dropdownPrefixCls } =
React.useContext(CascaderContext);
const mergedPrefixCls = dropdownPrefixCls || prefixCls;
// ========================= loadData =========================
const [loadingKeys, setLoadingKeys] = React.useState([]);
const internalLoadData = (pathValue: React.Key) => {
// Do not load when search
if (!loadData || searchValue) {
return;
}
const entity = flattenOptions.find(flattenOption => flattenOption.data.value === pathValue);
if (entity && !isLeaf(entity.data.node as any)) {
const { options: optionList } = restoreCompatibleValue(entity as any, fieldNames);
const rawOptionList = optionList.map(opt => opt.node);
setLoadingKeys(keys => [...keys, optionList[optionList.length - 1].value]);
loadData(rawOptionList);
}
};
// zombieJ: This is bad. We should make this same as `rc-tree` to use Promise instead.
React.useEffect(() => {
if (loadingKeys.length) {
loadingKeys.forEach(loadingKey => {
const option = flattenOptions.find(opt => opt.value === loadingKey);
if (option.data.children) {
setLoadingKeys(keys => keys.filter(key => key !== loadingKey));
}
});
}
}, [flattenOptions, loadingKeys]);
// ========================== Values ==========================
const checkedSet = React.useMemo(() => new Set(checkedKeys), [checkedKeys]);
const halfCheckedSet = React.useMemo(() => new Set(halfCheckedKeys), [halfCheckedKeys]);
// =========================== Open ===========================
const [openFinalValue, setOpenFinalValue] = React.useState<React.Key>(null);
const mergedOpenPath = React.useMemo<React.Key[]>(() => {
if (searchValue) {
return openFinalValue !== undefined && openFinalValue !== null ? [openFinalValue] : [];
}
const entity = flattenOptions.find(
flattenOption => flattenOption.data.value === openFinalValue,
);
if (entity) {
const { path } = restoreCompatibleValue(entity as any, fieldNames);
return path;
}
return [];
}, [openFinalValue, flattenOptions, searchValue]);
React.useEffect(() => {
if (open) {
let nextOpenPath: React.Key = null;
if (!multiple && checkedKeys.length) {
const entity = flattenOptions.find(
flattenOption => flattenOption.data.value === checkedKeys[0],
);
if (entity) {
nextOpenPath = entity.data.value;
}
}
setOpenFinalValue(nextOpenPath);
}
}, [open]);
// =========================== Path ===========================
const onPathOpen = (index: number, pathValue: React.Key) => {
setOpenFinalValue(pathValue);
// Trigger loadData
internalLoadData(pathValue);
};
const onPathSelect = (pathValue: React.Key, leaf: boolean) => {
onSelect(pathValue, { selected: !checkedSet.has(pathValue) });
if (!multiple && (leaf || (changeOnSelect && expandTrigger === 'hover'))) {
onToggleOpen(false);
}
};
const getPathList = (pathList: React.Key[]) => {
let currentOptions = options;
for (let i = 0; i < pathList.length; i += 1) {
currentOptions = (currentOptions || []).find(option => option.value === pathList[i]).children;
}
return currentOptions;
};
// ========================== Search ==========================
const searchOptions = useSearchResult({
...props,
prefixCls: mergedPrefixCls,
fieldNames,
changeOnSelect,
searchConfig: search,
});
// ========================== Column ==========================
const optionColumns = React.useMemo(() => {
if (searchValue) {
return [
{
options: searchOptions,
},
];
}
const rawOptionColumns: {
options: OptionDataNode[];
}[] = [];
for (let i = 0; i <= mergedOpenPath.length; i += 1) {
const subOptions = getPathList(mergedOpenPath.slice(0, i));
if (subOptions) {
rawOptionColumns.push({
options: subOptions,
});
} else {
break;
}
}
return rawOptionColumns;
}, [searchValue, searchOptions, mergedOpenPath]);
// ========================= Keyboard =========================
const getActiveOption = (activeColumnIndex: number, offset: number) => {
const pathActiveValue = mergedOpenPath[activeColumnIndex];
const currentOptions = optionColumns[activeColumnIndex]?.options || [];
let activeOptionIndex = currentOptions.findIndex(opt => opt.value === pathActiveValue);
const len = currentOptions.length;
// Last one is special since -1 may back 2 offset
if (offset === -1 && activeOptionIndex === -1) {
activeOptionIndex = len;
}
for (let i = 1; i <= len; i += 1) {
const current = (activeOptionIndex + i * offset + len) % len;
const option = currentOptions[current];
if (!option.disabled) {
return option;
}
}
return null;
};
const prevColumn = () => {
if (mergedOpenPath.length <= 1) {
onToggleOpen(false);
}
setOpenFinalValue(mergedOpenPath[mergedOpenPath.length - 2]);
};
const nextColumn = () => {
const nextColumnIndex = mergedOpenPath.length;
const nextActiveOption = getActiveOption(nextColumnIndex, 1);
if (nextActiveOption) {
onPathOpen(nextColumnIndex, nextActiveOption.value);
}
};
React.useImperativeHandle(ref, () => ({
// scrollTo: treeRef.current?.scrollTo,
onKeyDown: event => {
const { which } = event;
switch (which) {
// >>> Arrow keys
case KeyCode.UP:
case KeyCode.DOWN: {
let offset = 0;
if (which === KeyCode.UP) {
offset = -1;
} else if (which === KeyCode.DOWN) {
offset = 1;
}
if (offset !== 0) {
const activeColumnIndex = Math.max(mergedOpenPath.length - 1, 0);
const nextActiveOption = getActiveOption(activeColumnIndex, offset);
if (nextActiveOption) {
const ele = containerRef.current?.querySelector(
`li[data-value="${nextActiveOption.value}"]`,
);
ele?.scrollIntoView?.({ block: 'nearest' });
onPathOpen(activeColumnIndex, nextActiveOption.value);
}
}
break;
}
case KeyCode.LEFT: {
if (rtl) {
nextColumn();
} else {
prevColumn();
}
break;
}
case KeyCode.RIGHT: {
if (rtl) {
prevColumn();
} else {
nextColumn();
}
break;
}
case KeyCode.BACKSPACE: {
if (!searchValue) {
prevColumn();
}
break;
}
// >>> Select
case KeyCode.ENTER: {
const lastValue = mergedOpenPath[mergedOpenPath.length - 1];
const option = optionColumns[mergedOpenPath.length - 1]?.options?.find(
opt => opt.value === lastValue,
);
// Skip when no select
if (option) {
const leaf = isLeaf(option);
if (multiple || changeOnSelect || leaf) {
onPathSelect(lastValue, leaf);
}
// Close for changeOnSelect
if (changeOnSelect) {
onToggleOpen(false);
}
}
break;
}
// >>> Close
case KeyCode.ESC: {
onToggleOpen(false);
if (open) {
event.stopPropagation();
}
}
}
},
onKeyUp: () => {},
}));
// ========================== Render ==========================
const columnProps = {
...props,
onOpen: onPathOpen,
onSelect: onPathSelect,
onToggleOpen,
checkedSet,
halfCheckedSet,
loadingKeys,
};
// >>>>> Empty
const isEmpty = !optionColumns[0]?.options?.length;
const emptyList: OptionDataNode[] = [
{
title: notFoundContent,
value: '__EMPTY__',
disabled: true,
node: null,
},
];
// >>>>> Columns
const mergedOptionColumns = isEmpty ? [{ options: emptyList }] : optionColumns;
const columnNodes: React.ReactElement[] = mergedOptionColumns.map((col, index) => (
<Column
key={index}
index={index}
{...columnProps}
prefixCls={mergedPrefixCls}
options={col.options}
openKey={mergedOpenPath[index]}
/>
));
// >>>>> Render
return (
<>
<div
className={classNames(`${mergedPrefixCls}-menus`, {
[`${mergedPrefixCls}-menu-empty`]: isEmpty,
[`${mergedPrefixCls}-rtl`]: rtl,
})}
ref={containerRef}
>
{columnNodes}
</div>
</>
);
});
export default RefOptionList; | the_stack |
import { EventEmitter } from "events";
import { merge, filter, mapValues, uniqueId } from "lodash-es";
import getDefaults from "./defaults";
import { Plugin } from "./plugins";
import {
Storage as YStorage,
drawFontAwesomeIconAsSvg,
drawSvgStringAsElement,
removeClass,
addClass,
hasClass,
} from "@triply/yasgui-utils";
import Parser from "./parsers";
export { default as Parser } from "./parsers";
import { addScript, addCss, sanitize } from "./helpers";
import * as faDownload from "@fortawesome/free-solid-svg-icons/faDownload";
import * as faQuestionCircle from "@fortawesome/free-solid-svg-icons/faQuestionCircle";
require("./main.scss");
export interface PersistentConfig {
selectedPlugin?: string;
pluginsConfig?: { [pluginName: string]: any };
}
export interface Yasr {
on(event: "change", listener: (instance: Yasr) => void): this;
emit(event: "change", instance: Yasr): boolean;
on(event: "draw", listener: (instance: Yasr, plugin: Plugin<any>) => void): this;
emit(event: "draw", instance: Yasr, plugin: Plugin<any>): boolean;
on(event: "drawn", listener: (instance: Yasr, plugin: Plugin<any>) => void): this;
emit(event: "drawn", instance: Yasr, plugin: Plugin<any>): boolean;
on(event: "toggle-help", listener: (instance: Yasr) => void): this;
emit(event: "toggle-help", instance: Yasr): boolean;
}
export class Yasr extends EventEmitter {
public results?: Parser;
public rootEl: HTMLDivElement;
public headerEl: HTMLDivElement;
public fallbackInfoEl: HTMLDivElement;
public resultsEl: HTMLDivElement;
public pluginControls!: HTMLDivElement;
public config: Config;
public storage: YStorage;
public plugins: { [name: string]: Plugin<any> } = {};
// private persistentConfig: PersistentConfig;
public helpDrawn: Boolean = false;
private drawnPlugin: string | undefined;
private selectedPlugin: string | undefined;
// Utils
public utils = { addScript: addScript, addCSS: addCss, sanitize: sanitize };
constructor(parent: HTMLElement, conf: Partial<Config> = {}, data?: any) {
super();
if (!parent) throw new Error("No parent passed as argument. Dont know where to draw YASR");
this.rootEl = document.createElement("div");
this.rootEl.className = "yasr";
parent.appendChild(this.rootEl);
this.config = merge({}, Yasr.defaults, conf);
//Do some post processing
this.storage = new YStorage(Yasr.storageNamespace);
this.getConfigFromStorage();
this.headerEl = document.createElement("div");
this.headerEl.className = "yasr_header";
this.rootEl.appendChild(this.headerEl);
this.fallbackInfoEl = document.createElement("div");
this.fallbackInfoEl.className = "yasr_fallback_info";
this.rootEl.appendChild(this.fallbackInfoEl);
this.resultsEl = document.createElement("div");
this.resultsEl.className = "yasr_results";
this.resultsEl.id = uniqueId("resultsId");
this.rootEl.appendChild(this.resultsEl);
this.initializePlugins();
this.drawHeader();
const resp = data || this.getResponseFromStorage();
if (resp) this.setResponse(resp);
}
private getConfigFromStorage() {
const storageId = this.getStorageId(this.config.persistenceLabelConfig);
if (storageId) {
const persistentConfig: PersistentConfig | undefined = this.storage.get(storageId);
if (persistentConfig) {
this.selectedPlugin = persistentConfig.selectedPlugin;
for (const pluginName in persistentConfig.pluginsConfig) {
const pConf = persistentConfig.pluginsConfig[pluginName];
if (pConf && this.config.plugins[pluginName]) this.config.plugins[pluginName].dynamicConfig = pConf;
}
}
}
}
/**
* Ask the [[ Config.errorRenderers | configured error renderers ]] for a
* custom rendering of [[`error`]].
*
* @param error the error for which to find a custom rendering
* @return the first custom rendering found, or `undefined` if none was found.
*/
public async renderError(error: Parser.ErrorSummary): Promise<HTMLElement | undefined> {
// Chain the errorRenderers to get the first special rendering of the error
// if no special rendering is found, return undefined
let element: HTMLElement | undefined = undefined;
if (this.config.errorRenderers !== undefined) {
for (const renderer of this.config.errorRenderers) {
element = await renderer(error);
if (element !== undefined) break; // we found the first special case, so return that!
}
}
return element;
}
public getStorageId(label: string, getter?: Config["persistenceId"]): string | undefined {
const persistenceId = getter || this.config.persistenceId;
if (!persistenceId) return;
if (typeof persistenceId === "string") return persistenceId + "_" + label;
return persistenceId(this) + "_" + label;
}
public somethingDrawn() {
return !!this.resultsEl.children.length;
}
/**
* Empties fallback element
* CSS will make sure the outline is hidden when empty
*/
public emptyFallbackElement() {
// This is quicker than `<node>.innerHtml = ""`
while (this.fallbackInfoEl.firstChild) this.fallbackInfoEl.removeChild(this.fallbackInfoEl.firstChild);
}
public getSelectedPluginName(): string {
return this.selectedPlugin || this.config.defaultPlugin;
}
public getSelectedPlugin() {
if (this.plugins[this.getSelectedPluginName()]) {
return this.plugins[this.getSelectedPluginName()];
}
console.warn(`Tried using plugin ${this.getSelectedPluginName()}, but seems this plugin isnt registered in yasr.`);
}
/**
* Update selectors, based on whether they can actuall draw something, and which plugin is currently selected
*/
private updatePluginSelectors(enabledPlugins?: string[]) {
if (!this.pluginSelectorsEl) return;
for (const pluginName in this.config.plugins) {
const plugin = this.plugins[pluginName];
if (plugin && !plugin.hideFromSelection) {
if (enabledPlugins) {
if (enabledPlugins.indexOf(pluginName) >= 0) {
//make sure enabled
removeClass(this.pluginSelectorsEl.querySelector(".select_" + pluginName), "disabled");
} else {
//make sure disabled
addClass(this.pluginSelectorsEl.querySelector(".select_" + pluginName), "disabled");
}
}
if (pluginName === this.getSelectedPluginName()) {
addClass(this.pluginSelectorsEl.querySelector(".select_" + pluginName), "selected");
} else {
removeClass(this.pluginSelectorsEl.querySelector(".select_" + pluginName), "selected");
}
}
}
}
private getCompatiblePlugins(): string[] {
if (!this.results)
return Object.keys(
filter(this.config.plugins, (val) => (typeof val === "object" && val.enabled) || val === true)
);
const supportedPlugins: { name: string; priority: number }[] = [];
for (const pluginName in this.plugins) {
if (this.plugins[pluginName].canHandleResults()) {
supportedPlugins.push({ name: pluginName, priority: this.plugins[pluginName].priority });
}
}
return supportedPlugins.sort((p1, p2) => p2.priority - p1.priority).map((p) => p.name);
}
public draw() {
this.updateHelpButton();
this.updateResponseInfo();
if (!this.results) return;
const compatiblePlugins = this.getCompatiblePlugins();
if (this.drawnPlugin && this.getSelectedPluginName() !== this.drawnPlugin) {
while (this.pluginControls.firstChild) {
this.pluginControls.firstChild.remove();
}
this.plugins[this.drawnPlugin].destroy?.();
}
let pluginToDraw: string | undefined;
if (this.getSelectedPlugin() && this.getSelectedPlugin()?.canHandleResults()) {
pluginToDraw = this.getSelectedPluginName();
// When present remove fallback box
this.emptyFallbackElement();
} else if (compatiblePlugins[0]) {
if (this.drawnPlugin) {
this.plugins[this.drawnPlugin].destroy?.();
}
pluginToDraw = compatiblePlugins[0];
// Signal to create the plugin+
this.fillFallbackBox(pluginToDraw);
}
if (pluginToDraw) {
this.drawnPlugin = pluginToDraw;
this.emit("draw", this, this.plugins[pluginToDraw]);
const plugin = this.plugins[pluginToDraw];
const initPromise = plugin.initialize ? plugin.initialize() : Promise.resolve();
initPromise.then(
async () => {
if (pluginToDraw) {
// make sure to clear the object _here_
// otherwise we run into race conditions when draw is executed
// shortly after each other, and the plugin uses an initialize function
// as a result, things can be rendered _twice_
while (this.resultsEl.firstChild) this.resultsEl.firstChild.remove();
await this.plugins[pluginToDraw].draw(this.config.plugins[pluginToDraw].dynamicConfig);
this.emit("drawn", this, this.plugins[pluginToDraw]);
this.updateExportHeaders();
this.updatePluginSelectors(compatiblePlugins);
}
},
(_e) => console.error
);
} else {
this.resultsEl.textContent = "cannot render result";
this.updateExportHeaders();
this.updatePluginSelectors(compatiblePlugins);
}
}
//just an alias for `draw`. That way, we've got a consistent api with yasqe
public refresh() {
this.draw();
}
public destroy() {
if (this.drawnPlugin) this.plugins[this.drawnPlugin]?.destroy?.();
this.removeAllListeners();
this.rootEl.remove();
}
getPrefixes(): Prefixes {
if (this.config.prefixes) {
if (typeof this.config.prefixes === "function") {
return this.config.prefixes(this);
} else {
return this.config.prefixes;
}
}
return {};
}
public selectPlugin(plugin: string) {
if (this.selectedPlugin === plugin) {
// Don't re-render when selecting the same plugin. Also see #1893
return;
}
if (this.config.plugins[plugin]) {
this.selectedPlugin = plugin;
} else {
console.warn(`Plugin ${plugin} does not exist.`);
this.selectedPlugin = this.config.defaultPlugin;
}
this.storeConfig();
this.emit("change", this);
this.updatePluginSelectors();
this.draw();
}
private pluginSelectorsEl!: HTMLUListElement;
drawPluginSelectors() {
this.pluginSelectorsEl = document.createElement("ul");
this.pluginSelectorsEl.className = "yasr_btnGroup";
const pluginOrder = this.config.pluginOrder;
Object.keys(this.config.plugins)
.sort()
.forEach((plugin) => {
if (pluginOrder.indexOf(plugin) === -1) pluginOrder.push(plugin);
});
for (const pluginName of pluginOrder) {
if (!this.config.plugins[pluginName] || !this.config.plugins[pluginName].enabled) {
continue;
}
const plugin = this.plugins[pluginName];
if (!plugin) continue; //plugin not loaded
if (plugin.hideFromSelection) continue;
const name = plugin.label || pluginName;
const button = document.createElement("button");
addClass(button, "yasr_btn", "select_" + pluginName);
button.title = name;
button.type = "button";
button.setAttribute("aria-label", `Shows ${name} view`);
if (plugin.getIcon) {
const icon = plugin.getIcon();
if (icon) {
// icon.className = '';
addClass(icon, "plugin_icon");
button.appendChild(icon);
}
}
const nameEl = document.createElement("span");
nameEl.textContent = name;
button.appendChild(nameEl);
button.addEventListener("click", () => this.selectPlugin(pluginName));
const li = document.createElement("li");
li.appendChild(button);
this.pluginSelectorsEl.appendChild(li);
}
if (this.pluginSelectorsEl.children.length >= 1) this.headerEl.appendChild(this.pluginSelectorsEl);
this.updatePluginSelectors();
}
private fillFallbackBox(fallbackElement?: string) {
this.emptyFallbackElement();
// Do not show fallback render warnings for plugins without a selector.
if (this.plugins[fallbackElement || this.drawnPlugin || ""]?.hideFromSelection) return;
const selectedPlugin = this.getSelectedPlugin();
const fallbackPluginLabel =
this.plugins[fallbackElement || this.drawnPlugin || ""]?.label || fallbackElement || this.drawnPlugin;
const selectedPluginLabel = selectedPlugin?.label || this.getSelectedPluginName();
const textElement = document.createElement("p");
textElement.innerText = `Could not render results with the ${selectedPluginLabel} plugin, the results currently are rendered with the ${fallbackPluginLabel} plugin. ${
this.getSelectedPlugin()?.helpReference ? "See " : ""
}`;
if (selectedPlugin?.helpReference) {
const linkElement = document.createElement("a");
linkElement.innerText = `${selectedPluginLabel} documentation`;
linkElement.href = selectedPlugin.helpReference;
linkElement.rel = "noopener noreferrer";
linkElement.target = "_blank";
textElement.append(linkElement);
textElement.innerHTML += " for more information.";
}
this.fallbackInfoEl.appendChild(textElement);
}
private drawPluginElement() {
const spaceElement = document.createElement("div");
addClass(spaceElement, "space_element");
this.headerEl.appendChild(spaceElement);
this.pluginControls = document.createElement("div");
this.pluginControls.setAttribute("id", "yasr_plugin_control");
addClass(this.pluginControls, "yasr_plugin_control");
this.pluginControls.setAttribute("aria-controls", this.resultsEl.id);
this.headerEl.appendChild(this.pluginControls);
}
private drawHeader() {
this.drawPluginSelectors();
this.drawResponseInfo();
this.drawPluginElement();
this.drawDownloadIcon();
this.drawDocumentationButton();
}
private downloadBtn: HTMLAnchorElement | undefined;
private drawDownloadIcon() {
this.downloadBtn = document.createElement("a");
addClass(this.downloadBtn, "yasr_btn", "yasr_downloadIcon", "btn_icon");
this.downloadBtn.download = ""; // should default to the file name of the blob
this.downloadBtn.setAttribute("aria-label", "Download Results");
this.downloadBtn.setAttribute("tabindex", "0"); // anchor elements with no href are not automatically included in the tabindex
this.downloadBtn.setAttribute("role", "button");
const iconEl = drawSvgStringAsElement(drawFontAwesomeIconAsSvg(faDownload));
iconEl.setAttribute("aria-hidden", "true");
this.downloadBtn.appendChild(iconEl);
this.downloadBtn.addEventListener("click", () => {
if (hasClass(this.downloadBtn, "disabled")) return;
this.download();
});
this.downloadBtn.addEventListener("keydown", (event) => {
// needed for accessibility
if (event.code === "Space" || event.code === "Enter") {
if (hasClass(this.downloadBtn, "disabled")) return;
this.download();
}
});
this.headerEl.appendChild(this.downloadBtn);
}
private dataElement!: HTMLDivElement;
private drawResponseInfo() {
this.dataElement = document.createElement("div");
addClass(this.dataElement, "yasr_response_chip");
this.headerEl.appendChild(this.dataElement);
this.updateResponseInfo();
}
private updateResponseInfo() {
let innerText = "";
if (this.results) {
removeClass(this.dataElement, "empty");
const bindings = this.results.getBindings();
if (bindings) {
innerText += `${bindings.length} result${bindings.length === 1 ? "" : "s"}`; // Set amount of results
}
const responseTime = this.results.getResponseTime();
if (responseTime) {
if (!innerText) innerText = "Response";
const time = responseTime / 1000;
innerText += ` in ${time} second${time === 1 ? "" : "s"}`;
}
} else {
addClass(this.dataElement, "empty");
}
this.dataElement.innerText = innerText;
}
private updateHelpButton() {
const selectedPlugin = this.getSelectedPlugin();
if (selectedPlugin?.helpReference) {
const titleLabel = `View documentation of ${selectedPlugin.label || this.getSelectedPluginName()}`;
this.documentationLink.href = selectedPlugin.helpReference;
this.documentationLink.title = titleLabel;
this.documentationLink.setAttribute("aria-label", titleLabel);
removeClass(this.documentationLink, "disabled");
} else {
addClass(this.documentationLink, "disabled");
this.documentationLink.title =
"This plugin doesn't have a help reference yet. Please contact the maintainer to fix this";
}
}
updateExportHeaders() {
if (this.downloadBtn && this.drawnPlugin) {
this.downloadBtn.title = "";
const plugin = this.plugins[this.drawnPlugin];
if (plugin && plugin.download) {
const downloadInfo = plugin.download(this.config.getDownloadFileName?.());
removeClass(this.downloadBtn, "disabled");
if (downloadInfo) {
if (downloadInfo.title) this.downloadBtn.title = downloadInfo.title;
return;
}
}
this.downloadBtn.title = "Download not supported";
addClass(this.downloadBtn, "disabled");
}
}
private documentationLink!: HTMLAnchorElement;
private drawDocumentationButton() {
this.documentationLink = document.createElement("a");
addClass(this.documentationLink, "yasr_btn", "yasr_external_ref_btn");
this.documentationLink.appendChild(drawSvgStringAsElement(drawFontAwesomeIconAsSvg(faQuestionCircle)));
this.documentationLink.href = "//triply.cc/docs/yasgui";
this.documentationLink.target = "_blank";
this.documentationLink.rel = "noopener noreferrer";
this.headerEl.appendChild(this.documentationLink); // We can do this as long as the help-element is the last item in the row
}
download() {
if (!this.drawnPlugin) return;
const currentPlugin = this.plugins[this.drawnPlugin];
if (currentPlugin && currentPlugin.download) {
const downloadInfo = currentPlugin.download(this.config.getDownloadFileName?.());
if (!downloadInfo) return;
const data = downloadInfo.getData();
let downloadUrl: string;
if (data.startsWith("data:")) {
downloadUrl = data;
} else {
const blob = new Blob([data], { type: downloadInfo.contentType ?? "text/plain" });
downloadUrl = window.URL.createObjectURL(blob);
}
const mockLink = document.createElement("a");
mockLink.href = downloadUrl;
mockLink.download = downloadInfo.filename;
mockLink.click();
}
}
public handleLocalStorageQuotaFull(_e: any) {
console.warn("Localstorage quota exceeded. Clearing all queries");
Yasr.clearStorage();
}
public getResponseFromStorage() {
const storageId = this.getStorageId(this.config.persistenceLabelResponse);
if (storageId) {
return this.storage.get(storageId);
}
}
public getPersistentConfig(): PersistentConfig {
return {
selectedPlugin: this.getSelectedPluginName(),
pluginsConfig: mapValues(this.config.plugins, (plugin) => plugin.dynamicConfig),
};
}
//This doesnt store the plugin complete config. Only those configs we want persisted
public storePluginConfig(pluginName: string, conf: any) {
this.config.plugins[pluginName].dynamicConfig = conf;
this.storeConfig();
this.emit("change", this);
}
private storeConfig() {
const storageId = this.getStorageId(this.config.persistenceLabelConfig);
if (storageId) {
this.storage.set(
storageId,
this.getPersistentConfig(),
this.config.persistencyExpire,
this.handleLocalStorageQuotaFull
);
}
}
private storeResponse() {
const storageId = this.getStorageId(this.config.persistenceLabelResponse);
if (storageId && this.results) {
const storeObj = this.results.getAsStoreObject(this.config.maxPersistentResponseSize);
if (storeObj && !storeObj.error) {
this.storage.set(storageId, storeObj, this.config.persistencyExpire, this.handleLocalStorageQuotaFull);
} else {
//remove old string;
this.storage.remove(storageId);
}
}
}
public setResponse(data: any, duration?: number) {
if (!data) return;
this.results = new Parser(data, duration);
this.draw();
this.storeResponse();
}
private initializePlugins() {
for (const plugin in this.config.plugins) {
if (!this.config.plugins[plugin]) continue; //falsy value, so assuming it should be disabled
if (Yasr.plugins[plugin]) {
this.plugins[plugin] = new (<any>Yasr.plugins[plugin])(this);
} else {
console.warn("Wanted to initialize plugin " + plugin + " but could not find a matching registered plugin");
}
}
}
static defaults: Config = getDefaults();
static plugins: { [key: string]: typeof Plugin & { defaults?: any } } = {};
static registerPlugin(name: string, plugin: typeof Plugin, enable = true) {
Yasr.plugins[name] = plugin;
if (enable) {
Yasr.defaults.plugins[name] = { enabled: true };
} else {
Yasr.defaults.plugins[name] = { enabled: false };
}
}
/**
* Collection of Promises to load external scripts used by Yasr Plugins
* That way, the plugins wont load similar scripts simultaneously
*/
static Dependencies: { [name: string]: Promise<any> } = {};
static storageNamespace = "triply";
static clearStorage() {
const storage = new YStorage(Yasr.storageNamespace);
storage.removeNamespace();
}
}
export type Prefixes = { [prefixLabel: string]: string };
export interface PluginConfig {
dynamicConfig?: any;
staticConfig?: any;
enabled?: boolean;
}
export interface Config {
persistenceId: ((yasr: Yasr) => string) | string | null;
persistenceLabelResponse: string;
persistenceLabelConfig: string;
maxPersistentResponseSize: number;
persistencyExpire: number;
getPlainQueryLinkToEndpoint: (() => string | undefined) | undefined;
getDownloadFileName?: () => string | undefined;
plugins: { [pluginName: string]: PluginConfig };
pluginOrder: string[];
defaultPlugin: string;
prefixes: Prefixes | ((yasr: Yasr) => Prefixes);
/**
* Custom renderers for errors.
* Allow multiple to be able to add new custom renderers without having to
* overwrite or explicitly call previously added or default ones.
*/
errorRenderers?: ((error: Parser.ErrorSummary) => Promise<HTMLElement | undefined>)[];
}
export function registerPlugin(name: string, plugin: typeof Plugin, enable = true) {
Yasr.plugins[name] = plugin;
if (enable) {
Yasr.defaults.plugins[name] = { enabled: true };
} else {
Yasr.defaults.plugins[name] = { enabled: false };
}
}
import * as YasrPluginTable from "./plugins/table";
import * as YasrPluginBoolean from "./plugins/boolean";
import * as YasrPluginResponse from "./plugins/response";
import * as YasrPluginError from "./plugins/error";
Yasr.registerPlugin("table", YasrPluginTable.default as any);
Yasr.registerPlugin("boolean", YasrPluginBoolean.default as any);
Yasr.registerPlugin("response", YasrPluginResponse.default as any);
Yasr.registerPlugin("error", YasrPluginError.default as any);
export { Plugin, DownloadInfo } from "./plugins";
export default Yasr; | the_stack |
import * as React from "react";
import { CONSTANTS, DEVICE_LIST_KEY, WEBVIEW_MESSAGES } from "../../constants";
import { sendMessage } from "../../utils/MessageUtils";
import "../../styles/Simulator.css";
import PlayLogo from "../../svgs/play_svg";
import StopLogo from "../../svgs/stop_svg";
import ActionBar from "../simulator/ActionBar";
import { BUTTON_NEUTRAL, BUTTON_PRESSED } from "./Cpx_svg_style";
import { CpxImage, updatePinTouch, updateSwitch } from "./CpxImage";
interface ICpxState {
pixels: number[][];
brightness: number;
red_led: boolean;
button_a: boolean;
button_b: boolean;
switch: boolean;
touch: boolean[];
shake: boolean;
}
interface IState {
active_editors: string[];
running_file: string;
selected_file: string;
cpx: ICpxState;
play_button: boolean;
currently_selected_file: string;
}
const DEFAULT_CPX_STATE: ICpxState = {
brightness: 1.0,
button_a: false,
button_b: false,
pixels: [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
],
red_led: false,
switch: false,
touch: [false, false, false, false, false, false, false],
shake: false,
};
class Simulator extends React.Component<{}, IState> {
constructor(props: Readonly<{}>) {
super(props);
this.state = {
active_editors: [],
cpx: DEFAULT_CPX_STATE,
play_button: false,
running_file: "",
selected_file: "",
currently_selected_file: "",
};
this.handleClick = this.handleClick.bind(this);
this.onKeyEvent = this.onKeyEvent.bind(this);
this.onMouseDown = this.onMouseDown.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
this.togglePlayClick = this.togglePlayClick.bind(this);
this.refreshSimulatorClick = this.refreshSimulatorClick.bind(this);
}
handleMessage = (event: any): void => {
const message = event.data; // The JSON data our extension sent
if (message.active_device !== DEVICE_LIST_KEY.CPX) {
return;
}
switch (message.command) {
case "reset-state":
console.log("Clearing the state");
this.setState({
cpx: DEFAULT_CPX_STATE,
play_button: false,
});
break;
case "set-state":
console.log(
"Setting the state: " + JSON.stringify(message.state)
);
this.setState({
cpx: message.state,
play_button: true,
});
break;
case "activate-play":
const newRunningFile = this.state.currently_selected_file;
this.setState({
play_button: !this.state.play_button,
running_file: newRunningFile,
});
break;
case "visible-editors":
console.log(
"Setting active editors",
message.state.activePythonEditors
);
this.setState({
active_editors: message.state.activePythonEditors,
});
break;
case "current-file":
console.log("Setting current file", message.state.running_file);
if (this.state.play_button) {
this.setState({
currently_selected_file: message.state.running_file,
});
} else {
this.setState({
running_file: message.state.running_file,
currently_selected_file: message.state.running_file,
});
}
break;
}
};
componentDidMount() {
console.log("Mounted");
window.addEventListener("message", this.handleMessage);
}
componentWillUnmount() {
// Make sure to remove the DOM listener when the component is unmounted.
window.removeEventListener("message", this.handleMessage);
}
render() {
const playStopImage = this.state.play_button ? StopLogo : PlayLogo;
const playStopLabel = this.state.play_button ? "stop" : "play";
return (
<div className="simulator">
<div className="file-selector">
{this.state.running_file && this.state.play_button
? CONSTANTS.CURRENTLY_RUNNING(this.state.running_file)
: CONSTANTS.FILES_PLACEHOLDER}
</div>
<div className="cpx-container">
<CpxImage
pixels={this.state.cpx.pixels}
brightness={this.state.cpx.brightness}
red_led={this.state.cpx.red_led}
switch={this.state.cpx.switch}
on={this.state.play_button}
onKeyEvent={this.onKeyEvent}
onMouseUp={this.onMouseUp}
onMouseDown={this.onMouseDown}
onMouseLeave={this.onMouseLeave}
/>
</div>
<ActionBar
onTogglePlay={this.togglePlayClick}
onToggleRefresh={this.refreshSimulatorClick}
playStopImage={playStopImage}
playStopLabel={playStopLabel}
/>
</div>
);
}
protected togglePlayClick() {
const button =
window.document.getElementById(CONSTANTS.ID_NAME.PLAY_BUTTON) ||
window.document.getElementById(CONSTANTS.ID_NAME.STOP_BUTTON);
if (button) {
button.focus();
}
sendMessage(WEBVIEW_MESSAGES.TOGGLE_PLAY_STOP, {
selected_file: this.state.selected_file,
state: !this.state.play_button,
});
}
protected refreshSimulatorClick() {
const button = window.document.getElementById(
CONSTANTS.ID_NAME.REFRESH_BUTTON
);
if (button) {
button.focus();
}
sendMessage(WEBVIEW_MESSAGES.REFRESH_SIMULATOR, true);
}
protected onKeyEvent(event: KeyboardEvent, active: boolean) {
let element;
const target = event.target as SVGElement;
// Guard Clause
if (target === undefined) {
return;
}
if ([event.code, event.key].includes(CONSTANTS.KEYBOARD_KEYS.ENTER)) {
element = window.document.getElementById(target.id);
} else if (
[event.code, event.key].includes(CONSTANTS.KEYBOARD_KEYS.A)
) {
element = window.document.getElementById(
CONSTANTS.ID_NAME.BUTTON_A
);
} else if (
[event.code, event.key].includes(CONSTANTS.KEYBOARD_KEYS.B)
) {
element = window.document.getElementById(
CONSTANTS.ID_NAME.BUTTON_B
);
} else if (
[event.code, event.key].includes(CONSTANTS.KEYBOARD_KEYS.C)
) {
element = window.document.getElementById(
CONSTANTS.ID_NAME.BUTTON_AB
);
} else if (
[event.code, event.key].includes(CONSTANTS.KEYBOARD_KEYS.S)
) {
element = window.document.getElementById(CONSTANTS.ID_NAME.SWITCH);
} else if (event.key === CONSTANTS.KEYBOARD_KEYS.CAPITAL_F) {
this.togglePlayClick();
} else if (event.key === CONSTANTS.KEYBOARD_KEYS.CAPITAL_R) {
this.refreshSimulatorClick();
} else {
if (event.shiftKey) {
switch (event.code) {
case CONSTANTS.KEYBOARD_KEYS.NUMERIC_ONE:
element = window.document.getElementById(
CONSTANTS.ID_NAME.PIN_A1
);
break;
case CONSTANTS.KEYBOARD_KEYS.NUMERIC_TWO:
element = window.document.getElementById(
CONSTANTS.ID_NAME.PIN_A2
);
break;
case CONSTANTS.KEYBOARD_KEYS.NUMERIC_THREE:
element = window.document.getElementById(
CONSTANTS.ID_NAME.PIN_A3
);
break;
case CONSTANTS.KEYBOARD_KEYS.NUMERIC_FOUR:
element = window.document.getElementById(
CONSTANTS.ID_NAME.PIN_A4
);
break;
case CONSTANTS.KEYBOARD_KEYS.NUMERIC_FIVE:
element = window.document.getElementById(
CONSTANTS.ID_NAME.PIN_A5
);
break;
case CONSTANTS.KEYBOARD_KEYS.NUMERIC_SIX:
element = window.document.getElementById(
CONSTANTS.ID_NAME.PIN_A6
);
break;
case CONSTANTS.KEYBOARD_KEYS.NUMERIC_SEVEN:
element = window.document.getElementById(
CONSTANTS.ID_NAME.PIN_A7
);
break;
}
}
}
if (element) {
event.preventDefault();
this.handleClick(element, active);
element.focus();
}
}
protected onMouseDown(button: HTMLElement, event: Event) {
event.preventDefault();
this.handleClick(button, true);
button.focus();
}
protected onMouseUp(button: HTMLElement, event: Event) {
event.preventDefault();
this.handleClick(button, false);
}
protected onMouseLeave(button: HTMLElement, event: Event) {
event.preventDefault();
if (button.getAttribute("pressed") === "true") {
this.handleClick(button, false);
}
}
private handleClick(element: HTMLElement, active: boolean) {
let newState;
let message;
if (element.id.includes("BTN")) {
newState = this.handleButtonClick(element, active);
message = "button-press";
} else if (element.id.includes("SWITCH")) {
newState = this.handleSwitchClick();
message = "button-press";
} else if (element.id.includes("PIN")) {
newState = this.handleTouchPinClick(element, active);
message = "sensor-changed";
} else {
return;
}
if (newState && message) {
sendMessage(message, newState);
}
}
private handleButtonClick(button: HTMLElement, active: boolean) {
const ButtonA: boolean = button.id.match(/BTN_A/) !== null;
const ButtonB: boolean = button.id.match(/BTN_B/) !== null;
const ButtonAB: boolean = button.id.match(/BTN_AB/) !== null;
let innerButton;
let newState;
if (ButtonAB) {
innerButton = window.document.getElementById("BTN_AB_INNER");
newState = {
button_a: active,
button_b: active,
};
this.setState({ ...this.state, ...newState });
} else if (ButtonA) {
innerButton = window.document.getElementById("BTN_A_INNER");
newState = {
button_a: active,
};
this.setState({ ...this.state, ...newState });
} else if (ButtonB) {
innerButton = window.document.getElementById("BTN_B_INNER");
newState = {
button_b: active,
};
this.setState({ ...this.state, ...newState });
}
if (innerButton) {
innerButton.style.fill = this.getButtonColor(active);
}
button.setAttribute("pressed", `${active}`);
return newState;
}
private getButtonColor(pressed: boolean) {
const buttonUps = BUTTON_NEUTRAL;
const buttonDown = BUTTON_PRESSED;
return pressed ? buttonDown : buttonUps;
}
private handleSwitchClick() {
const switchIsOn = !this.state.cpx.switch;
updateSwitch(switchIsOn);
this.setState({
...this.state,
cpx: { ...this.state.cpx, switch: switchIsOn },
});
return { switch: switchIsOn };
}
private handleTouchPinClick(pin: HTMLElement, active: boolean): any {
let cpxState = this.state.cpx;
const pinIndex = parseInt(pin.id.charAt(pin.id.length - 1)) - 1;
const pinState = cpxState.touch;
pinState[pinIndex] = active;
cpxState = { ...cpxState, touch: pinState };
this.setState({ ...this.state, ...cpxState });
updatePinTouch(active, pin.id);
return { touch: pinState };
}
}
export default Simulator; | the_stack |
import { Stylesheet } from "../../../src/chef/css/stylesheet";
import { Rule } from "../../../src/chef/css/rule";
import { AttributeMatcher } from "../../../src/chef/css/selectors";
import { ParseError } from "../../../src/chef/helpers";
import { KeyFrameRule, FontFaceRule, ImportRule } from "../../../src/chef/css/at-rules";
describe("Parses selectors", () => {
test("Tag Name", () => {
const css = Stylesheet.fromString("h1 {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({ tagName: "h1" })
});
test("* tag name", () => {
const css = Stylesheet.fromString("* {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({ tagName: "*" });
});
test("Class", () => {
const css = Stylesheet.fromString("div.class1 {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
tagName: "div",
classes: ["class1"]
});
});
test("Multiple classes", () => {
const css = Stylesheet.fromString(".content.main {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
classes: ["content", "main"]
});
});
describe("Pseudo selectors", () => {
test("Pseudo class", () => {
const css = Stylesheet.fromString("li:first-child {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
tagName: "li",
pseudoClasses: [{ name: "first-child" }]
});
});
test("Pseudo class with arguments", () => {
const css = Stylesheet.fromString("li:nth-child(2) {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
tagName: "li",
pseudoClasses: [{ name: "nth-child", args: [{ value: "2" }] }]
});
});
test("Pseudo class with selectors as arguments", () => {
const css = Stylesheet.fromString("div:not(.post) {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
tagName: "div",
pseudoClasses: [{
name: "not", args: [
{ classes: ["post"] }
]
}]
});
});
test("Pseudo element", () => {
const css = Stylesheet.fromString("p::after {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
tagName: "p",
pseudoElements: [{ name: "after" }]
});
});
});
test("Id", () => {
const css = Stylesheet.fromString("#user {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
id: "user"
});
});
test("Throw if multiple ids", () => {
expect.assertions(2);
try {
Stylesheet.fromString("h1#user#x {}");
} catch (error) {
expect(error).toBeInstanceOf(ParseError);
expect(error).toHaveProperty("message", "CSS selector can only contain one id matcher in anom.css:1:11");
}
});
test("Child", () => {
const css = Stylesheet.fromString("div > .user {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
tagName: "div",
child: {
classes: ["user"]
}
});
});
test("Adjacent", () => {
const css = Stylesheet.fromString("h1 + p {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
tagName: "h1",
adjacent: {
tagName: "p"
}
});
});
test("Descendant", () => {
const css = Stylesheet.fromString("div h1 {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
tagName: "div",
descendant: {
tagName: "h1"
}
});
});
test("Descendant of descendant", () => {
const css = Stylesheet.fromString("div h1 i {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
tagName: "div",
descendant: {
tagName: "h1",
descendant: {
tagName: "i"
}
}
});
});
test("Descendant class", () => {
const css = Stylesheet.fromString("div .child {}");
expect((css.rules[0] as Rule).selectors[0]).toMatchObject({
tagName: "div",
descendant: {
classes: ["child"]
}
});
});
test("Group", () => {
const css = Stylesheet.fromString("h1, h2, h3 {}");
expect((css.rules[0] as Rule).selectors).toMatchObject([
{ tagName: "h1" },
{ tagName: "h2" },
{ tagName: "h3" }
]);
});
test("No empty selectors", () => {
expect.assertions(2);
try {
Stylesheet.fromString("{color: red;}")
} catch (error) {
expect(error).toBeInstanceOf(ParseError);
expect(error).toHaveProperty("message", "Expected selector received \"{\" at anom.css:1:1");
}
});
describe("Attributes", () => {
test("Attribute exists", () => {
const css = Stylesheet.fromString("img[alt] {}");
expect((css.rules[0] as Rule).selectors).toMatchObject([
{
tagName: "img",
attributes: [
{
attribute: "alt",
matcher: AttributeMatcher.KeyExists
}
]
}
]);
});
test("Attribute is equal", () => {
const css = Stylesheet.fromString(`div[data-foo="bar"] {}`);
expect((css.rules[0] as Rule).selectors).toMatchObject([
{
tagName: "div",
attributes: [
{
attribute: "data-foo",
matcher: AttributeMatcher.ExactEqual,
value: "bar"
}
]
}
]);
});
test("Attribute some word", () => {
const css = Stylesheet.fromString(`div[class~="foo"] {}`);
expect((css.rules[0] as Rule).selectors).toMatchObject([
{
tagName: "div",
attributes: [
{
attribute: "class",
matcher: AttributeMatcher.SomeWord,
value: "foo"
}
]
}
]);
});
test("Attribute begins with", () => {
const css = Stylesheet.fromString(`div[class|="foo"] {}`);
expect((css.rules[0] as Rule).selectors).toMatchObject([
{
tagName: "div",
attributes: [
{
attribute: "class",
matcher: AttributeMatcher.BeginsWith,
value: "foo"
}
]
}
]);
});
test("Attribute value is prefix", () => {
const css = Stylesheet.fromString(`div[class^="foo"] {}`);
expect((css.rules[0] as Rule).selectors).toMatchObject([
{
tagName: "div",
attributes: [
{
attribute: "class",
matcher: AttributeMatcher.Prefixed,
value: "foo"
}
]
}
]);
});
test("Attribute value is suffix", () => {
const css = Stylesheet.fromString(`div[class$="foo"] {}`);
expect((css.rules[0] as Rule).selectors).toMatchObject([
{
tagName: "div",
attributes: [
{
attribute: "class",
matcher: AttributeMatcher.Suffixed,
value: "foo"
}
]
}
]);
});
test("Attribute value occurs", () => {
const css = Stylesheet.fromString(`div[class*="foo"] {}`);
expect((css.rules[0] as Rule).selectors).toMatchObject([
{
tagName: "div",
attributes: [
{
attribute: "class",
matcher: AttributeMatcher.Occurrence,
value: "foo"
}
]
}
]);
});
});
});
describe("Reads declarations", () => {
test("Simple declarations", () => {
const rule1 = Stylesheet.fromString("h1 {color: red;}").rules[0] as Rule;
const declarations = rule1.declarations;
expect(declarations.size).toBe(1);
expect(declarations.has("color")).toBeTruthy();
expect(declarations.get("color")).toMatchObject([{ value: "red" }]);
});
test("Numbers", () => {
const rule1 = Stylesheet.fromString("h1 {grid-row: 1;}").rules[0] as Rule;
expect(rule1.declarations.get("grid-row")).toMatchObject([{ value: "1" }]);
});
test("Units", () => {
const rule1 = Stylesheet.fromString("h1 {margin-top: 4px;}").rules[0] as Rule;
expect(rule1.declarations.get("margin-top")).toMatchObject([{ value: "4", unit: "px" }]);
});
test("Decimal shorthand", () => {
const rule1 = Stylesheet.fromString("h1 {transition: padding .3s;}").rules[0] as Rule;
expect(rule1.declarations.get("transition")![1]).toMatchObject({ value: ".3", unit: "s" });
});
test("Multiple values", () => {
const rule1 = Stylesheet.fromString("h1 {margin: 4px 3px 2px 1px;}").rules[0] as Rule;
expect(rule1.declarations.get("margin")).toMatchObject([
{ value: "4", unit: "px" },
{ value: "3", unit: "px" },
{ value: "2", unit: "px" },
{ value: "1", unit: "px" },
]);
});
test("Comma separated list", () => {
const rule1 = Stylesheet.fromString(`h1 {font-family: "Helvetica", sans-serif;}`).rules[0] as Rule;
expect(rule1.declarations.get("font-family")).toMatchObject([
{ value: "Helvetica" },
",",
{ value: "sans-serif" },
]);
});
test("Quotation wrapped", () => {
const rule1 = Stylesheet.fromString(`h1 {font-family: "Helvetica", sans-serif;}`).rules[0] as Rule;
expect(rule1.declarations.get("font-family")).toMatchObject([
{ value: "Helvetica", quotationWrapped: true },
",",
{ value: "sans-serif" },
]);
});
test("!important", () => {
const rule1 = Stylesheet.fromString(`h1 {color: red !important;}`).rules[0] as Rule;
expect(rule1.declarations.get("color")).toMatchObject([
{ value: "red" },
{ value: "!important" },
]);
});
xtest("Mix of commented list and non commented", () => {
});
test("Ratio", () => {
const rule1 = Stylesheet.fromString(`img {aspect-ratio: 1/3;}`).rules[0] as Rule;
expect(rule1.declarations.get("aspect-ratio")).toMatchObject([
{ value: "1" },
"/",
{ value: "3" },
]);
});
test("Ratio with span", () => {
const rule1 = Stylesheet.fromString(`.post-image {grid-row: 1 / span 4;}`).rules[0] as Rule;
expect(rule1.declarations.get("grid-row")).toMatchObject([
{ value: "1" },
"/",
{ value: "span" },
{ value: "4" },
]);
});
test("Functions", () => {
const cssString =
`div.image {
background-image: url("http://some.url.here/image.png");
}`;
const declarations = (Stylesheet.fromString(cssString).rules[0] as Rule).declarations;
expect(declarations.size).toBe(1);
expect(declarations.has("background-image")).toBeTruthy();
expect(declarations.get("background-image")![0]).toMatchObject({
name: "url",
arguments: [
{
value: "http://some.url.here/image.png",
quotationWrapped: true,
}
]
});
});
test("At least one value", () => {
expect.assertions(2);
try {
Stylesheet.fromString("h1 {color: ; }")
} catch (error) {
expect(error).toBeInstanceOf(ParseError);
expect(error).toHaveProperty("message", `Expected value received ";" at anom.css:1:12`);
}
});
test("Rule closed", () => {
expect.assertions(2);
try {
Stylesheet.fromString("h1 {color: red; ")
} catch (error) {
expect(error).toBeInstanceOf(ParseError);
expect(error).toHaveProperty("message", `Expected "}" received "End of file" at anom.css:1:16`);
}
});
})
test("Skip comments", () => {
const cssString =
`h1 {
/* I am a comment */
color: red;
}
/* I am a multiline
comment */`;
const css = Stylesheet.fromString(cssString);
expect(css.rules).toHaveLength(1);
});
describe("At rules", () => {
describe("Media query", () => {
});
test("import rule", () => {
const importRule = Stylesheet.fromString(`@import url("./modal.css");`).rules[0] as ImportRule;
expect(importRule).toBeInstanceOf(ImportRule);
expect(importRule.value).toMatchObject([{
name: "url",
arguments: [
{ value: "./modal.css" }
]
}]);
});
test.todo("supports");
test("font-face", () => {
const css =
`@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 100;
font-display: swap;
src: url("font-files/Inter-Thin.woff2?3.13") format("woff2"),
url("font-files/Inter-Thin.woff?3.13") format("woff");
}`;
const fontFaceRule = Stylesheet.fromString(css).rules[0] as FontFaceRule;
expect(fontFaceRule).toBeInstanceOf(FontFaceRule);
expect(fontFaceRule.declarations.length).toBe(5);
});
describe("Keyframes", () => {
test("Name", () => {
const cssString =
`@keyframes Rotate { }`;
const keyframesRule = Stylesheet.fromString(cssString).rules[0] as KeyFrameRule;
expect(keyframesRule.name).toBe("Rotate");
});
test("To from", () => {
const cssString =
`@keyframes Rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}`;
const keyframesRule = Stylesheet.fromString(cssString).rules[0] as KeyFrameRule;
expect(keyframesRule.declarations.size).toBe(2);
expect(keyframesRule.declarations.has("from")).toBeTruthy();
expect(keyframesRule.declarations.has("to")).toBeTruthy();
});
test("Percentages", () => {
const cssString =
`@keyframes Rotate {
0% {
transform: rotate(0deg);
}
50% {
transform: rotate(360deg);
}
}`;
const keyframesRule = Stylesheet.fromString(cssString).rules[0] as KeyFrameRule;
expect(keyframesRule.name).toBe("Rotate");
expect(keyframesRule.declarations.size).toBe(2);
expect(keyframesRule.declarations.has(0)).toBeTruthy();
expect(keyframesRule.declarations.has(50)).toBeTruthy();
});
});
});
describe("Parses nested css", () => {
test("h1 in a header", () => {
const css =
`header {
padding: 12px;
h1 {
font-size: 18px;
}
}`;
const stylesheet = Stylesheet.fromString(css);
expect(stylesheet.rules).toHaveLength(2);
expect((stylesheet.rules[1] as Rule).selectors[0]).toMatchObject({
tagName: "header",
descendant: { tagName: "h1" }
});
});
test("Expand out group", () => {
const css =
`h1, h2, h3 {
a, b, i {
color: green;
}
}`;
const stylesheet = Stylesheet.fromString(css);
expect((stylesheet.rules[0] as Rule).selectors).toHaveLength(3 * 3);
});
test("Deeply nested rules", () => {
const css =
`h1 {
h2 {
h3 {
color: blue;
}
}
}`;
const stylesheet = Stylesheet.fromString(css);
expect((stylesheet.rules[0] as Rule).selectors[0]).toMatchObject({
tagName: "h1",
descendant: {
tagName: "h2",
descendant: {
tagName: "h3",
}
}
});
});
xtest("Pseudo selectors", () => {
const cssString =
`p.info {
font-size: 12px;
:first-child {
content: "Before content";
}
}`;
// const css = stringToTokens(cssString)[0];
// expect(css.Selectors).toEqual(["p.info"]);
// expect(css.Declarations).toEqual(new Map([["font-size", "12px"]]));
// expect(css.SubRules).toHaveLength(1);
// expect(css.SubRules[0].Selectors).toEqual(["::before"]);
// expect(css.SubRules[0].Declarations).toEqual(new Map([["content", ""Before content""]]));
});
xtest("Nth child selector", () => {
const cssString =
`ul {
padding-left: 0px;
li:nth-child(2n) {
text-decoration: underline;
}
}`;
// const css = stringToTokens(cssString)[0];
// expect(css.Selectors).toEqual(["ul"]);
// expect(css.Declarations).toEqual(new Map([["padding-left", "0px"]]));
// expect(css.SubRules).toHaveLength(1);
// expect(css.SubRules[0].Selectors).toEqual(["li:nth-child(2n)"]);
// expect(css.SubRules[0].Declarations).toEqual(new Map([["text-decoration", "underline"]]));
});
test.todo("Under media query");
}); | the_stack |
* @fileoverview Implements functions for handling option lists
*
* @author dpvc@mathjax.org (Davide Cervone)
*/
/*****************************************************************/
/* tslint:disable-next-line:jsdoc-require */
const OBJECT = {}.constructor;
/**
* Check if an object is an object literal (as opposed to an instance of a class)
*/
export function isObject(obj: any) {
return typeof obj === 'object' && obj !== null &&
(obj.constructor === OBJECT || obj.constructor === Expandable);
}
/*****************************************************************/
/**
* Generic list of options
*/
export type OptionList = {[name: string]: any};
/*****************************************************************/
/**
* Used to append an array to an array in default options
* E.g., an option of the form
*
* {
* name: {[APPEND]: [1, 2, 3]}
* }
*
* where 'name' is an array in the default options would end up with name having its
* original value with 1, 2, and 3 appended.
*/
export const APPEND = '[+]';
/**
* Used to remove elements from an array in default options
* E.g., an option of the form
*
* {
* name: {[REMOVE]: [2]}
* }
*
* where 'name' is an array in the default options would end up with name having its
* original value but with any entry of 2 removed So if the original value was [1, 2, 3, 2],
* then the final value will be [1, 3] instead.
*/
export const REMOVE = '[-]';
/**
* Provides options for the option utlities.
*/
export const OPTIONS = {
invalidOption: 'warn' as ('fatal' | 'warn'),
/**
* Function to report messages for invalid options
*
* @param {string} message The message for the invalid parameter.
* @param {string} key The invalid key itself.
*/
optionError: (message: string, _key: string) => {
if (OPTIONS.invalidOption === 'fatal') {
throw new Error(message);
}
console.warn('MathJax: ' + message);
}
};
/**
* A Class to use for options that should not produce warnings if an undefined key is used
*/
export class Expandable {}
/**
* Produces an instance of Expandable with the given values (to be used in defining options
* that can use keys that don't have default values). E.g., default options of the form:
*
* OPTIONS = {
* types: expandable({
* a: 1,
* b: 2
* })
* }
*
* would allow user options of
*
* {
* types: {
* c: 3
* }
* }
*
* without reporting an error.
*/
export function expandable(def: OptionList) {
return Object.assign(Object.create(Expandable.prototype), def);
}
/*****************************************************************/
/**
* Make sure an option is an Array
*/
export function makeArray(x: any): any[] {
return Array.isArray(x) ? x : [x];
}
/*****************************************************************/
/**
* Get all keys and symbols from an object
*
* @param {Optionlist} def The object whose keys are to be returned
* @return {(string | symbol)[]} The list of keys for the object
*/
export function keys(def: OptionList): (string | symbol)[] {
if (!def) {
return [];
}
return (Object.keys(def) as (string | symbol)[]).concat(Object.getOwnPropertySymbols(def));
}
/*****************************************************************/
/**
* Make a deep copy of an object
*
* @param {OptionList} def The object to be copied
* @return {OptionList} The copy of the object
*/
export function copy(def: OptionList): OptionList {
let props: OptionList = {};
for (const key of keys(def)) {
let prop = Object.getOwnPropertyDescriptor(def, key);
let value = prop.value;
if (Array.isArray(value)) {
prop.value = insert([], value, false);
} else if (isObject(value)) {
prop.value = copy(value);
}
if (prop.enumerable) {
props[key as string] = prop;
}
}
return Object.defineProperties(def.constructor === Expandable ? expandable({}) : {}, props);
}
/*****************************************************************/
/**
* Insert one object into another (with optional warnings about
* keys that aren't in the original)
*
* @param {OptionList} dst The option list to merge into
* @param {OptionList} src The options to be merged
* @param {boolean} warn True if a warning should be issued for a src option that isn't already in dst
* @return {OptionList} The modified destination option list (dst)
*/
export function insert(dst: OptionList, src: OptionList, warn: boolean = true): OptionList {
for (let key of keys(src) as string[]) {
//
// Check if the key is valid (i.e., is in the defaults or in an expandable block)
//
if (warn && dst[key] === undefined && dst.constructor !== Expandable) {
if (typeof key === 'symbol') {
key = (key as symbol).toString();
}
OPTIONS.optionError(`Invalid option "${key}" (no default value).`, key);
continue;
}
//
// Shorthands for the source and destination values
//
let sval = src[key], dval = dst[key];
//
// If the source is an object literal and the destination exists and is either an
// object or a function (so can have properties added to it)...
//
if (isObject(sval) && dval !== null &&
(typeof dval === 'object' || typeof dval === 'function')) {
const ids = keys(sval);
//
// Check for APPEND or REMOVE objects:
//
if (
//
// If the destination value is an array...
//
Array.isArray(dval) &&
(
//
// If there is only one key and it is APPEND or REMOVE and the keys value is an array...
//
(ids.length === 1 && (ids[0] === APPEND || ids[0] === REMOVE) && Array.isArray(sval[ids[0]])) ||
//
// Or if there are two keys and they are APPEND and REMOVE and both keys' values
// are arrays...
//
(ids.length === 2 && ids.sort().join(',') === APPEND + ',' + REMOVE &&
Array.isArray(sval[APPEND]) && Array.isArray(sval[REMOVE]))
)
) {
//
// Then remove any values to be removed
//
if (sval[REMOVE]) {
dval = dst[key] = dval.filter(x => sval[REMOVE].indexOf(x) < 0);
}
//
// And append any values to be added (make a copy so as not to modify the original)
//
if (sval[APPEND]) {
dst[key] = [...dval, ...sval[APPEND]];
}
} else {
//
// Otherwise insert the values of the source object into the destination object
//
insert(dval, sval, warn);
}
} else if (Array.isArray(sval)) {
//
// If the source is an array, replace the destination with an empty array
// and copy the source values into it.
//
dst[key] = [];
insert(dst[key], sval, false);
} else if (isObject(sval)) {
//
// If the source is an object literal, set the destination to a copy of it
//
dst[key] = copy(sval);
} else {
//
// Otherwise set the destination to the source value
//
dst[key] = sval;
}
}
return dst;
}
/*****************************************************************/
/**
* Merge options without warnings (so we can add new default values into an
* existing default list)
*
* @param {OptionList} options The option list to be merged into
* @param {OptionList[]} defs The option lists to merge into the first one
* @return {OptionList} The modified options list
*/
export function defaultOptions(options: OptionList, ...defs: OptionList[]): OptionList {
defs.forEach(def => insert(options, def, false));
return options;
}
/*****************************************************************/
/**
* Merge options with warnings about undefined ones (so we can merge
* user options into the default list)
*
* @param {OptionList} options The option list to be merged into
* @param {OptionList[]} defs The option lists to merge into the first one
* @return {OptionList} The modified options list
*/
export function userOptions(options: OptionList, ...defs: OptionList[]): OptionList {
defs.forEach(def => insert(options, def, true));
return options;
}
/*****************************************************************/
/**
* Select a subset of options by key name
*
* @param {OptionList} options The option list from which option values will be taken
* @param {string[]} keys The names of the options to extract
* @return {OptionList} The option list consisting of only the ones whose keys were given
*/
export function selectOptions(options: OptionList, ...keys: string[]): OptionList {
let subset: OptionList = {};
for (const key of keys) {
if (options.hasOwnProperty(key)) {
subset[key] = options[key];
}
}
return subset;
}
/*****************************************************************/
/**
* Select a subset of options by keys from an object
*
* @param {OptionList} options The option list from which the option values will be taken
* @param {OptionList} object The option list whose keys will be used to select the options
* @return {OptionList} The option list consisting of the option values from the first
* list whose keys are those from the second list.
*/
export function selectOptionsFromKeys(options: OptionList, object: OptionList): OptionList {
return selectOptions(options, ...Object.keys(object));
}
/*****************************************************************/
/**
* Separate options into sets: the ones having the same keys
* as the second object, the third object, etc, and the ones that don't.
* (Used to separate an option list into the options needed for several
* subobjects.)
*
* @param {OptionList} options The option list to be split into parts
* @param {OptionList[]} objects The list of option lists whose keys are used to break up
* the original options into separate pieces.
* @return {OptionList[]} The option lists taken from the original based on the
* keys of the other objects. The first one in the list
* consists of the values not appearing in any of the others
* (i.e., whose keys were not in any of the others).
*/
export function separateOptions(options: OptionList, ...objects: OptionList[]): OptionList[] {
let results: OptionList[] = [];
for (const object of objects) {
let exists: OptionList = {}, missing: OptionList = {};
for (const key of Object.keys(options || {})) {
(object[key] === undefined ? missing : exists)[key] = options[key];
}
results.push(exists);
options = missing;
}
results.unshift(options);
return results;
}
/*****************************************************************/
/**
* Look up a value from object literal, being sure it is an
* actual property (not inherited), with a default if not found.
*
* @param {string} name The name of the key to look up.
* @param {OptionList} lookup The list of options to check.
* @param {any} def The default value if the key isn't found.
*/
export function lookup(name: string, lookup: OptionList, def: any = null) {
return (lookup.hasOwnProperty(name) ? lookup[name] : def);
} | the_stack |
import { assertEq, assertDeepEq, assertOk } from '../test-helpers';
import { moment } from '../chain';
describe('week year', () => {
it('iso week year', function () {
// Some examples taken from https://en.wikipedia.org/wiki/ISO_week
assertEq(moment([2005, 0, 1]).isoWeekYear(), 2004);
assertEq(moment([2005, 0, 2]).isoWeekYear(), 2004);
assertEq(moment([2005, 0, 3]).isoWeekYear(), 2005);
assertEq(moment([2005, 11, 31]).isoWeekYear(), 2005);
assertEq(moment([2006, 0, 1]).isoWeekYear(), 2005);
assertEq(moment([2006, 0, 2]).isoWeekYear(), 2006);
assertEq(moment([2007, 0, 1]).isoWeekYear(), 2007);
assertEq(moment([2007, 11, 30]).isoWeekYear(), 2007);
assertEq(moment([2007, 11, 31]).isoWeekYear(), 2008);
assertEq(moment([2008, 0, 1]).isoWeekYear(), 2008);
assertEq(moment([2008, 11, 28]).isoWeekYear(), 2008);
assertEq(moment([2008, 11, 29]).isoWeekYear(), 2009);
assertEq(moment([2008, 11, 30]).isoWeekYear(), 2009);
assertEq(moment([2008, 11, 31]).isoWeekYear(), 2009);
assertEq(moment([2009, 0, 1]).isoWeekYear(), 2009);
assertEq(moment([2010, 0, 1]).isoWeekYear(), 2009);
assertEq(moment([2010, 0, 2]).isoWeekYear(), 2009);
assertEq(moment([2010, 0, 3]).isoWeekYear(), 2009);
assertEq(moment([2010, 0, 4]).isoWeekYear(), 2010);
});
it('week year', function () {
// Some examples taken from https://en.wikipedia.org/wiki/ISO_week
moment.locale('dow: 1,doy: 4', { week: { dow: 1, doy: 4 } }); // like iso
assertEq(moment([2005, 0, 1]).weekYear(), 2004);
assertEq(moment([2005, 0, 2]).weekYear(), 2004);
assertEq(moment([2005, 0, 3]).weekYear(), 2005);
assertEq(moment([2005, 11, 31]).weekYear(), 2005);
assertEq(moment([2006, 0, 1]).weekYear(), 2005);
assertEq(moment([2006, 0, 2]).weekYear(), 2006);
assertEq(moment([2007, 0, 1]).weekYear(), 2007);
assertEq(moment([2007, 11, 30]).weekYear(), 2007);
assertEq(moment([2007, 11, 31]).weekYear(), 2008);
assertEq(moment([2008, 0, 1]).weekYear(), 2008);
assertEq(moment([2008, 11, 28]).weekYear(), 2008);
assertEq(moment([2008, 11, 29]).weekYear(), 2009);
assertEq(moment([2008, 11, 30]).weekYear(), 2009);
assertEq(moment([2008, 11, 31]).weekYear(), 2009);
assertEq(moment([2009, 0, 1]).weekYear(), 2009);
assertEq(moment([2010, 0, 1]).weekYear(), 2009);
assertEq(moment([2010, 0, 2]).weekYear(), 2009);
assertEq(moment([2010, 0, 3]).weekYear(), 2009);
assertEq(moment([2010, 0, 4]).weekYear(), 2010);
moment.defineLocale('dow: 1,doy: 4', null);
moment.locale('dow: 1,doy: 7', { week: { dow: 1, doy: 7 } });
assertEq(moment([2004, 11, 26]).weekYear(), 2004);
assertEq(moment([2004, 11, 27]).weekYear(), 2005);
assertEq(moment([2005, 11, 25]).weekYear(), 2005);
assertEq(moment([2005, 11, 26]).weekYear(), 2006);
assertEq(moment([2006, 11, 31]).weekYear(), 2006);
assertEq(moment([2007, 0, 1]).weekYear(), 2007);
assertEq(moment([2007, 11, 30]).weekYear(), 2007);
assertEq(moment([2007, 11, 31]).weekYear(), 2008);
assertEq(moment([2008, 11, 28]).weekYear(), 2008);
assertEq(moment([2008, 11, 29]).weekYear(), 2009);
assertEq(moment([2009, 11, 27]).weekYear(), 2009);
assertEq(moment([2009, 11, 28]).weekYear(), 2010);
moment.defineLocale('dow: 1,doy: 7', null);
});
// Verifies that the week number, week day computation is correct for all dow, doy combinations
it('week year roundtrip', function () {
var dow, doy, wd, m, localeName;
for (dow = 0; dow < 7; ++dow) {
for (doy = dow; doy < dow + 7; ++doy) {
for (wd = 0; wd < 7; ++wd) {
localeName = 'dow: ' + dow + ', doy: ' + doy;
moment.locale(localeName, { week: { dow: dow, doy: doy } });
// We use the 10th week as the 1st one can spill to the previous year
m = moment('2015 10 ' + wd, 'gggg w d', true);
assertEq(m.format('gggg w d'), '2015 10 ' + wd, 'dow: ' + dow + ' doy: ' + doy + ' wd: ' + wd);
m = moment('2015 10 ' + wd, 'gggg w e', true);
assertEq(m.format('gggg w e'), '2015 10 ' + wd, 'dow: ' + dow + ' doy: ' + doy + ' wd: ' + wd);
moment.defineLocale(localeName, null);
}
}
}
});
it('week numbers 2012/2013', function () {
moment.locale('dow: 6, doy: 12', { week: { dow: 6, doy: 12 } });
assertEq(52, moment('2012-12-28', 'YYYY-MM-DD').week(), '2012-12-28 is week 52'); // 51 -- should be 52?
assertEq(1, moment('2012-12-29', 'YYYY-MM-DD').week(), '2012-12-29 is week 1'); // 52 -- should be 1
assertEq(1, moment('2013-01-01', 'YYYY-MM-DD').week(), '2013-01-01 is week 1'); // 52 -- should be 1
assertEq(2, moment('2013-01-08', 'YYYY-MM-DD').week(), '2013-01-08 is week 2'); // 53 -- should be 2
assertEq(2, moment('2013-01-11', 'YYYY-MM-DD').week(), '2013-01-11 is week 2'); // 53 -- should be 2
assertEq(3, moment('2013-01-12', 'YYYY-MM-DD').week(), '2013-01-12 is week 3'); // 1 -- should be 3
assertEq(52, moment('2012-01-01', 'YYYY-MM-DD').weeksInYear(), 'weeks in 2012 are 52'); // 52
moment.defineLocale('dow: 6, doy: 12', null);
});
it('weeks numbers dow:1 doy:4', function () {
moment.locale('dow: 1, doy: 4', { week: { dow: 1, doy: 4 } });
assertEq(moment([2012, 0, 1]).week(), 52, 'Jan 1 2012 should be week 52');
assertEq(moment([2012, 0, 2]).week(), 1, 'Jan 2 2012 should be week 1');
assertEq(moment([2012, 0, 8]).week(), 1, 'Jan 8 2012 should be week 1');
assertEq(moment([2012, 0, 9]).week(), 2, 'Jan 9 2012 should be week 2');
assertEq(moment([2012, 0, 15]).week(), 2, 'Jan 15 2012 should be week 2');
assertEq(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1');
assertEq(moment([2007, 0, 7]).week(), 1, 'Jan 7 2007 should be week 1');
assertEq(moment([2007, 0, 8]).week(), 2, 'Jan 8 2007 should be week 2');
assertEq(moment([2007, 0, 14]).week(), 2, 'Jan 14 2007 should be week 2');
assertEq(moment([2007, 0, 15]).week(), 3, 'Jan 15 2007 should be week 3');
assertEq(moment([2007, 11, 31]).week(), 1, 'Dec 31 2007 should be week 1');
assertEq(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1');
assertEq(moment([2008, 0, 6]).week(), 1, 'Jan 6 2008 should be week 1');
assertEq(moment([2008, 0, 7]).week(), 2, 'Jan 7 2008 should be week 2');
assertEq(moment([2008, 0, 13]).week(), 2, 'Jan 13 2008 should be week 2');
assertEq(moment([2008, 0, 14]).week(), 3, 'Jan 14 2008 should be week 3');
assertEq(moment([2002, 11, 30]).week(), 1, 'Dec 30 2002 should be week 1');
assertEq(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1');
assertEq(moment([2003, 0, 5]).week(), 1, 'Jan 5 2003 should be week 1');
assertEq(moment([2003, 0, 6]).week(), 2, 'Jan 6 2003 should be week 2');
assertEq(moment([2003, 0, 12]).week(), 2, 'Jan 12 2003 should be week 2');
assertEq(moment([2003, 0, 13]).week(), 3, 'Jan 13 2003 should be week 3');
assertEq(moment([2008, 11, 29]).week(), 1, 'Dec 29 2008 should be week 1');
assertEq(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1');
assertEq(moment([2009, 0, 4]).week(), 1, 'Jan 4 2009 should be week 1');
assertEq(moment([2009, 0, 5]).week(), 2, 'Jan 5 2009 should be week 2');
assertEq(moment([2009, 0, 11]).week(), 2, 'Jan 11 2009 should be week 2');
assertEq(moment([2009, 0, 13]).week(), 3, 'Jan 12 2009 should be week 3');
assertEq(moment([2009, 11, 28]).week(), 53, 'Dec 28 2009 should be week 53');
assertEq(moment([2010, 0, 1]).week(), 53, 'Jan 1 2010 should be week 53');
assertEq(moment([2010, 0, 3]).week(), 53, 'Jan 3 2010 should be week 53');
assertEq(moment([2010, 0, 4]).week(), 1, 'Jan 4 2010 should be week 1');
assertEq(moment([2010, 0, 10]).week(), 1, 'Jan 10 2010 should be week 1');
assertEq(moment([2010, 0, 11]).week(), 2, 'Jan 11 2010 should be week 2');
assertEq(moment([2010, 11, 27]).week(), 52, 'Dec 27 2010 should be week 52');
assertEq(moment([2011, 0, 1]).week(), 52, 'Jan 1 2011 should be week 52');
assertEq(moment([2011, 0, 2]).week(), 52, 'Jan 2 2011 should be week 52');
assertEq(moment([2011, 0, 3]).week(), 1, 'Jan 3 2011 should be week 1');
assertEq(moment([2011, 0, 9]).week(), 1, 'Jan 9 2011 should be week 1');
assertEq(moment([2011, 0, 10]).week(), 2, 'Jan 10 2011 should be week 2');
moment.defineLocale('dow: 1, doy: 4', null);
});
it('weeks numbers dow:6 doy:12', function () {
moment.locale('dow: 6, doy: 12', { week: { dow: 6, doy: 12 } });
assertEq(moment([2011, 11, 31]).week(), 1, 'Dec 31 2011 should be week 1');
assertEq(moment([2012, 0, 6]).week(), 1, 'Jan 6 2012 should be week 1');
assertEq(moment([2012, 0, 7]).week(), 2, 'Jan 7 2012 should be week 2');
assertEq(moment([2012, 0, 13]).week(), 2, 'Jan 13 2012 should be week 2');
assertEq(moment([2012, 0, 14]).week(), 3, 'Jan 14 2012 should be week 3');
assertEq(moment([2006, 11, 30]).week(), 1, 'Dec 30 2006 should be week 1');
assertEq(moment([2007, 0, 5]).week(), 1, 'Jan 5 2007 should be week 1');
assertEq(moment([2007, 0, 6]).week(), 2, 'Jan 6 2007 should be week 2');
assertEq(moment([2007, 0, 12]).week(), 2, 'Jan 12 2007 should be week 2');
assertEq(moment([2007, 0, 13]).week(), 3, 'Jan 13 2007 should be week 3');
assertEq(moment([2007, 11, 29]).week(), 1, 'Dec 29 2007 should be week 1');
assertEq(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1');
assertEq(moment([2008, 0, 4]).week(), 1, 'Jan 4 2008 should be week 1');
assertEq(moment([2008, 0, 5]).week(), 2, 'Jan 5 2008 should be week 2');
assertEq(moment([2008, 0, 11]).week(), 2, 'Jan 11 2008 should be week 2');
assertEq(moment([2008, 0, 12]).week(), 3, 'Jan 12 2008 should be week 3');
assertEq(moment([2002, 11, 28]).week(), 1, 'Dec 28 2002 should be week 1');
assertEq(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1');
assertEq(moment([2003, 0, 3]).week(), 1, 'Jan 3 2003 should be week 1');
assertEq(moment([2003, 0, 4]).week(), 2, 'Jan 4 2003 should be week 2');
assertEq(moment([2003, 0, 10]).week(), 2, 'Jan 10 2003 should be week 2');
assertEq(moment([2003, 0, 11]).week(), 3, 'Jan 11 2003 should be week 3');
assertEq(moment([2008, 11, 27]).week(), 1, 'Dec 27 2008 should be week 1');
assertEq(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1');
assertEq(moment([2009, 0, 2]).week(), 1, 'Jan 2 2009 should be week 1');
assertEq(moment([2009, 0, 3]).week(), 2, 'Jan 3 2009 should be week 2');
assertEq(moment([2009, 0, 9]).week(), 2, 'Jan 9 2009 should be week 2');
assertEq(moment([2009, 0, 10]).week(), 3, 'Jan 10 2009 should be week 3');
assertEq(moment([2009, 11, 26]).week(), 1, 'Dec 26 2009 should be week 1');
assertEq(moment([2010, 0, 1]).week(), 1, 'Jan 1 2010 should be week 1');
assertEq(moment([2010, 0, 2]).week(), 2, 'Jan 2 2010 should be week 2');
assertEq(moment([2010, 0, 8]).week(), 2, 'Jan 8 2010 should be week 2');
assertEq(moment([2010, 0, 9]).week(), 3, 'Jan 9 2010 should be week 3');
assertEq(moment([2011, 0, 1]).week(), 1, 'Jan 1 2011 should be week 1');
assertEq(moment([2011, 0, 7]).week(), 1, 'Jan 7 2011 should be week 1');
assertEq(moment([2011, 0, 8]).week(), 2, 'Jan 8 2011 should be week 2');
assertEq(moment([2011, 0, 14]).week(), 2, 'Jan 14 2011 should be week 2');
assertEq(moment([2011, 0, 15]).week(), 3, 'Jan 15 2011 should be week 3');
moment.defineLocale('dow: 6, doy: 12', null);
});
it('weeks numbers dow:1 doy:7', function () {
moment.locale('dow: 1, doy: 7', { week: { dow: 1, doy: 7 } });
assertEq(moment([2011, 11, 26]).week(), 1, 'Dec 26 2011 should be week 1');
assertEq(moment([2012, 0, 1]).week(), 1, 'Jan 1 2012 should be week 1');
assertEq(moment([2012, 0, 2]).week(), 2, 'Jan 2 2012 should be week 2');
assertEq(moment([2012, 0, 8]).week(), 2, 'Jan 8 2012 should be week 2');
assertEq(moment([2012, 0, 9]).week(), 3, 'Jan 9 2012 should be week 3');
assertEq(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1');
assertEq(moment([2007, 0, 7]).week(), 1, 'Jan 7 2007 should be week 1');
assertEq(moment([2007, 0, 8]).week(), 2, 'Jan 8 2007 should be week 2');
assertEq(moment([2007, 0, 14]).week(), 2, 'Jan 14 2007 should be week 2');
assertEq(moment([2007, 0, 15]).week(), 3, 'Jan 15 2007 should be week 3');
assertEq(moment([2007, 11, 31]).week(), 1, 'Dec 31 2007 should be week 1');
assertEq(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1');
assertEq(moment([2008, 0, 6]).week(), 1, 'Jan 6 2008 should be week 1');
assertEq(moment([2008, 0, 7]).week(), 2, 'Jan 7 2008 should be week 2');
assertEq(moment([2008, 0, 13]).week(), 2, 'Jan 13 2008 should be week 2');
assertEq(moment([2008, 0, 14]).week(), 3, 'Jan 14 2008 should be week 3');
assertEq(moment([2002, 11, 30]).week(), 1, 'Dec 30 2002 should be week 1');
assertEq(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1');
assertEq(moment([2003, 0, 5]).week(), 1, 'Jan 5 2003 should be week 1');
assertEq(moment([2003, 0, 6]).week(), 2, 'Jan 6 2003 should be week 2');
assertEq(moment([2003, 0, 12]).week(), 2, 'Jan 12 2003 should be week 2');
assertEq(moment([2003, 0, 13]).week(), 3, 'Jan 13 2003 should be week 3');
assertEq(moment([2008, 11, 29]).week(), 1, 'Dec 29 2008 should be week 1');
assertEq(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1');
assertEq(moment([2009, 0, 4]).week(), 1, 'Jan 4 2009 should be week 1');
assertEq(moment([2009, 0, 5]).week(), 2, 'Jan 5 2009 should be week 2');
assertEq(moment([2009, 0, 11]).week(), 2, 'Jan 11 2009 should be week 2');
assertEq(moment([2009, 0, 12]).week(), 3, 'Jan 12 2009 should be week 3');
assertEq(moment([2009, 11, 28]).week(), 1, 'Dec 28 2009 should be week 1');
assertEq(moment([2010, 0, 1]).week(), 1, 'Jan 1 2010 should be week 1');
assertEq(moment([2010, 0, 3]).week(), 1, 'Jan 3 2010 should be week 1');
assertEq(moment([2010, 0, 4]).week(), 2, 'Jan 4 2010 should be week 2');
assertEq(moment([2010, 0, 10]).week(), 2, 'Jan 10 2010 should be week 2');
assertEq(moment([2010, 0, 11]).week(), 3, 'Jan 11 2010 should be week 3');
assertEq(moment([2010, 11, 27]).week(), 1, 'Dec 27 2010 should be week 1');
assertEq(moment([2011, 0, 1]).week(), 1, 'Jan 1 2011 should be week 1');
assertEq(moment([2011, 0, 2]).week(), 1, 'Jan 2 2011 should be week 1');
assertEq(moment([2011, 0, 3]).week(), 2, 'Jan 3 2011 should be week 2');
assertEq(moment([2011, 0, 9]).week(), 2, 'Jan 9 2011 should be week 2');
assertEq(moment([2011, 0, 10]).week(), 3, 'Jan 10 2011 should be week 3');
moment.defineLocale('dow: 1, doy: 7', null);
});
it('weeks numbers dow:0 doy:6', function () {
moment.locale('dow: 0, doy: 6', { week: { dow: 0, doy: 6 } });
assertEq(moment([2012, 0, 1]).week(), 1, 'Jan 1 2012 should be week 1');
assertEq(moment([2012, 0, 7]).week(), 1, 'Jan 7 2012 should be week 1');
assertEq(moment([2012, 0, 8]).week(), 2, 'Jan 8 2012 should be week 2');
assertEq(moment([2012, 0, 14]).week(), 2, 'Jan 14 2012 should be week 2');
assertEq(moment([2012, 0, 15]).week(), 3, 'Jan 15 2012 should be week 3');
assertEq(moment([2006, 11, 31]).week(), 1, 'Dec 31 2006 should be week 1');
assertEq(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1');
assertEq(moment([2007, 0, 6]).week(), 1, 'Jan 6 2007 should be week 1');
assertEq(moment([2007, 0, 7]).week(), 2, 'Jan 7 2007 should be week 2');
assertEq(moment([2007, 0, 13]).week(), 2, 'Jan 13 2007 should be week 2');
assertEq(moment([2007, 0, 14]).week(), 3, 'Jan 14 2007 should be week 3');
assertEq(moment([2007, 11, 29]).week(), 52, 'Dec 29 2007 should be week 52');
assertEq(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1');
assertEq(moment([2008, 0, 5]).week(), 1, 'Jan 5 2008 should be week 1');
assertEq(moment([2008, 0, 6]).week(), 2, 'Jan 6 2008 should be week 2');
assertEq(moment([2008, 0, 12]).week(), 2, 'Jan 12 2008 should be week 2');
assertEq(moment([2008, 0, 13]).week(), 3, 'Jan 13 2008 should be week 3');
assertEq(moment([2002, 11, 29]).week(), 1, 'Dec 29 2002 should be week 1');
assertEq(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1');
assertEq(moment([2003, 0, 4]).week(), 1, 'Jan 4 2003 should be week 1');
assertEq(moment([2003, 0, 5]).week(), 2, 'Jan 5 2003 should be week 2');
assertEq(moment([2003, 0, 11]).week(), 2, 'Jan 11 2003 should be week 2');
assertEq(moment([2003, 0, 12]).week(), 3, 'Jan 12 2003 should be week 3');
assertEq(moment([2008, 11, 28]).week(), 1, 'Dec 28 2008 should be week 1');
assertEq(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1');
assertEq(moment([2009, 0, 3]).week(), 1, 'Jan 3 2009 should be week 1');
assertEq(moment([2009, 0, 4]).week(), 2, 'Jan 4 2009 should be week 2');
assertEq(moment([2009, 0, 10]).week(), 2, 'Jan 10 2009 should be week 2');
assertEq(moment([2009, 0, 11]).week(), 3, 'Jan 11 2009 should be week 3');
assertEq(moment([2009, 11, 27]).week(), 1, 'Dec 27 2009 should be week 1');
assertEq(moment([2010, 0, 1]).week(), 1, 'Jan 1 2010 should be week 1');
assertEq(moment([2010, 0, 2]).week(), 1, 'Jan 2 2010 should be week 1');
assertEq(moment([2010, 0, 3]).week(), 2, 'Jan 3 2010 should be week 2');
assertEq(moment([2010, 0, 9]).week(), 2, 'Jan 9 2010 should be week 2');
assertEq(moment([2010, 0, 10]).week(), 3, 'Jan 10 2010 should be week 3');
assertEq(moment([2010, 11, 26]).week(), 1, 'Dec 26 2010 should be week 1');
assertEq(moment([2011, 0, 1]).week(), 1, 'Jan 1 2011 should be week 1');
assertEq(moment([2011, 0, 2]).week(), 2, 'Jan 2 2011 should be week 2');
assertEq(moment([2011, 0, 8]).week(), 2, 'Jan 8 2011 should be week 2');
assertEq(moment([2011, 0, 9]).week(), 3, 'Jan 9 2011 should be week 3');
moment.defineLocale('dow: 0, doy: 6', null);
});
it('week year overflows', function () {
assertEq('2005-01-01', moment.utc('2004-W53-6', moment.ISO_8601, true).format('YYYY-MM-DD'), '2004-W53-6 is 1st Jan 2005');
assertEq('2007-12-31', moment.utc('2008-W01-1', moment.ISO_8601, true).format('YYYY-MM-DD'), '2008-W01-1 is 31st Dec 2007');
});
/* it('weeks overflow', function () {
assertEq(7, moment.utc('2004-W54-1', moment.ISO_8601, true).parsingFlags().overflow, '2004 has only 53 weeks');
assertEq(7, moment.utc('2004-W00-1', moment.ISO_8601, true).parsingFlags().overflow, 'there is no 0th week');
});
it('weekday overflow', function () {
assertEq(8, moment.utc('2004-W30-0', moment.ISO_8601, true).parsingFlags().overflow, 'there is no 0 iso weekday');
assertEq(8, moment.utc('2004-W30-8', moment.ISO_8601, true).parsingFlags().overflow, 'there is no 8 iso weekday');
assertEq(8, moment.utc('2004-w30-7', 'gggg-[w]ww-e', true).parsingFlags().overflow, 'there is no 7 \'e\' weekday');
assertEq(8, moment.utc('2004-w30-7', 'gggg-[w]ww-d', true).parsingFlags().overflow, 'there is no 7 \'d\' weekday');
});*/
// todo: FIX
xit('week year setter works', function () {
for (var year = 2000; year <= 2020; year += 1) {
assertEq(moment.utc('2012-12-31T00:00:00.000Z').isoWeekYear(year).isoWeekYear(), year, 'setting iso-week-year to ' + year);
assertEq(moment.utc('2012-12-31T00:00:00.000Z').weekYear(year).weekYear(), year, 'setting week-year to ' + year);
}
assertEq(moment.utc('2004-W53-1', moment.ISO_8601, true).isoWeekYear(2013).format('GGGG-[W]WW-E'), '2013-W52-1', '2004-W53-1 to 2013');
assertEq(moment.utc('2004-W53-1', moment.ISO_8601, true).isoWeekYear(2020).format('GGGG-[W]WW-E'), '2020-W53-1', '2004-W53-1 to 2020');
assertEq(moment.utc('2005-W52-1', moment.ISO_8601, true).isoWeekYear(2004).format('GGGG-[W]WW-E'), '2004-W52-1', '2005-W52-1 to 2004');
assertEq(moment.utc('2013-W30-4', moment.ISO_8601, true).isoWeekYear(2015).format('GGGG-[W]WW-E'), '2015-W30-4', '2013-W30-4 to 2015');
assertEq(moment.utc('2005-w53-0', 'gggg-[w]ww-e', true).weekYear(2013).format('gggg-[w]ww-e'), '2013-w52-0', '2005-w53-0 to 2013');
assertEq(moment.utc('2005-w53-0', 'gggg-[w]ww-e', true).weekYear(2016).format('gggg-[w]ww-e'), '2016-w53-0', '2005-w53-0 to 2016');
assertEq(moment.utc('2004-w52-0', 'gggg-[w]ww-e', true).weekYear(2005).format('gggg-[w]ww-e'), '2005-w52-0', '2004-w52-0 to 2005');
assertEq(moment.utc('2013-w30-4', 'gggg-[w]ww-e', true).weekYear(2015).format('gggg-[w]ww-e'), '2015-w30-4', '2013-w30-4 to 2015');
});
}); | 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 AppIntegrations extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: AppIntegrations.Types.ClientConfiguration)
config: Config & AppIntegrations.Types.ClientConfiguration;
/**
* Creates and persists a DataIntegration resource. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
createDataIntegration(params: AppIntegrations.Types.CreateDataIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.CreateDataIntegrationResponse) => void): Request<AppIntegrations.Types.CreateDataIntegrationResponse, AWSError>;
/**
* Creates and persists a DataIntegration resource. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
createDataIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.CreateDataIntegrationResponse) => void): Request<AppIntegrations.Types.CreateDataIntegrationResponse, AWSError>;
/**
* Creates an EventIntegration, given a specified name, description, and a reference to an Amazon EventBridge bus in your account and a partner event source that pushes events to that bus. No objects are created in the your account, only metadata that is persisted on the EventIntegration control plane.
*/
createEventIntegration(params: AppIntegrations.Types.CreateEventIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.CreateEventIntegrationResponse) => void): Request<AppIntegrations.Types.CreateEventIntegrationResponse, AWSError>;
/**
* Creates an EventIntegration, given a specified name, description, and a reference to an Amazon EventBridge bus in your account and a partner event source that pushes events to that bus. No objects are created in the your account, only metadata that is persisted on the EventIntegration control plane.
*/
createEventIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.CreateEventIntegrationResponse) => void): Request<AppIntegrations.Types.CreateEventIntegrationResponse, AWSError>;
/**
* Deletes the DataIntegration. Only DataIntegrations that don't have any DataIntegrationAssociations can be deleted. Deleting a DataIntegration also deletes the underlying Amazon AppFlow flow and service linked role. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
deleteDataIntegration(params: AppIntegrations.Types.DeleteDataIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.DeleteDataIntegrationResponse) => void): Request<AppIntegrations.Types.DeleteDataIntegrationResponse, AWSError>;
/**
* Deletes the DataIntegration. Only DataIntegrations that don't have any DataIntegrationAssociations can be deleted. Deleting a DataIntegration also deletes the underlying Amazon AppFlow flow and service linked role. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
deleteDataIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.DeleteDataIntegrationResponse) => void): Request<AppIntegrations.Types.DeleteDataIntegrationResponse, AWSError>;
/**
* Deletes the specified existing event integration. If the event integration is associated with clients, the request is rejected.
*/
deleteEventIntegration(params: AppIntegrations.Types.DeleteEventIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.DeleteEventIntegrationResponse) => void): Request<AppIntegrations.Types.DeleteEventIntegrationResponse, AWSError>;
/**
* Deletes the specified existing event integration. If the event integration is associated with clients, the request is rejected.
*/
deleteEventIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.DeleteEventIntegrationResponse) => void): Request<AppIntegrations.Types.DeleteEventIntegrationResponse, AWSError>;
/**
* Returns information about the DataIntegration. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
getDataIntegration(params: AppIntegrations.Types.GetDataIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.GetDataIntegrationResponse) => void): Request<AppIntegrations.Types.GetDataIntegrationResponse, AWSError>;
/**
* Returns information about the DataIntegration. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
getDataIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.GetDataIntegrationResponse) => void): Request<AppIntegrations.Types.GetDataIntegrationResponse, AWSError>;
/**
* Returns information about the event integration.
*/
getEventIntegration(params: AppIntegrations.Types.GetEventIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.GetEventIntegrationResponse) => void): Request<AppIntegrations.Types.GetEventIntegrationResponse, AWSError>;
/**
* Returns information about the event integration.
*/
getEventIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.GetEventIntegrationResponse) => void): Request<AppIntegrations.Types.GetEventIntegrationResponse, AWSError>;
/**
* Returns a paginated list of DataIntegration associations in the account. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
listDataIntegrationAssociations(params: AppIntegrations.Types.ListDataIntegrationAssociationsRequest, callback?: (err: AWSError, data: AppIntegrations.Types.ListDataIntegrationAssociationsResponse) => void): Request<AppIntegrations.Types.ListDataIntegrationAssociationsResponse, AWSError>;
/**
* Returns a paginated list of DataIntegration associations in the account. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
listDataIntegrationAssociations(callback?: (err: AWSError, data: AppIntegrations.Types.ListDataIntegrationAssociationsResponse) => void): Request<AppIntegrations.Types.ListDataIntegrationAssociationsResponse, AWSError>;
/**
* Returns a paginated list of DataIntegrations in the account. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
listDataIntegrations(params: AppIntegrations.Types.ListDataIntegrationsRequest, callback?: (err: AWSError, data: AppIntegrations.Types.ListDataIntegrationsResponse) => void): Request<AppIntegrations.Types.ListDataIntegrationsResponse, AWSError>;
/**
* Returns a paginated list of DataIntegrations in the account. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
listDataIntegrations(callback?: (err: AWSError, data: AppIntegrations.Types.ListDataIntegrationsResponse) => void): Request<AppIntegrations.Types.ListDataIntegrationsResponse, AWSError>;
/**
* Returns a paginated list of event integration associations in the account.
*/
listEventIntegrationAssociations(params: AppIntegrations.Types.ListEventIntegrationAssociationsRequest, callback?: (err: AWSError, data: AppIntegrations.Types.ListEventIntegrationAssociationsResponse) => void): Request<AppIntegrations.Types.ListEventIntegrationAssociationsResponse, AWSError>;
/**
* Returns a paginated list of event integration associations in the account.
*/
listEventIntegrationAssociations(callback?: (err: AWSError, data: AppIntegrations.Types.ListEventIntegrationAssociationsResponse) => void): Request<AppIntegrations.Types.ListEventIntegrationAssociationsResponse, AWSError>;
/**
* Returns a paginated list of event integrations in the account.
*/
listEventIntegrations(params: AppIntegrations.Types.ListEventIntegrationsRequest, callback?: (err: AWSError, data: AppIntegrations.Types.ListEventIntegrationsResponse) => void): Request<AppIntegrations.Types.ListEventIntegrationsResponse, AWSError>;
/**
* Returns a paginated list of event integrations in the account.
*/
listEventIntegrations(callback?: (err: AWSError, data: AppIntegrations.Types.ListEventIntegrationsResponse) => void): Request<AppIntegrations.Types.ListEventIntegrationsResponse, AWSError>;
/**
* Lists the tags for the specified resource.
*/
listTagsForResource(params: AppIntegrations.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: AppIntegrations.Types.ListTagsForResourceResponse) => void): Request<AppIntegrations.Types.ListTagsForResourceResponse, AWSError>;
/**
* Lists the tags for the specified resource.
*/
listTagsForResource(callback?: (err: AWSError, data: AppIntegrations.Types.ListTagsForResourceResponse) => void): Request<AppIntegrations.Types.ListTagsForResourceResponse, AWSError>;
/**
* Adds the specified tags to the specified resource.
*/
tagResource(params: AppIntegrations.Types.TagResourceRequest, callback?: (err: AWSError, data: AppIntegrations.Types.TagResourceResponse) => void): Request<AppIntegrations.Types.TagResourceResponse, AWSError>;
/**
* Adds the specified tags to the specified resource.
*/
tagResource(callback?: (err: AWSError, data: AppIntegrations.Types.TagResourceResponse) => void): Request<AppIntegrations.Types.TagResourceResponse, AWSError>;
/**
* Removes the specified tags from the specified resource.
*/
untagResource(params: AppIntegrations.Types.UntagResourceRequest, callback?: (err: AWSError, data: AppIntegrations.Types.UntagResourceResponse) => void): Request<AppIntegrations.Types.UntagResourceResponse, AWSError>;
/**
* Removes the specified tags from the specified resource.
*/
untagResource(callback?: (err: AWSError, data: AppIntegrations.Types.UntagResourceResponse) => void): Request<AppIntegrations.Types.UntagResourceResponse, AWSError>;
/**
* Updates the description of a DataIntegration. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
updateDataIntegration(params: AppIntegrations.Types.UpdateDataIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.UpdateDataIntegrationResponse) => void): Request<AppIntegrations.Types.UpdateDataIntegrationResponse, AWSError>;
/**
* Updates the description of a DataIntegration. You cannot create a DataIntegration association for a DataIntegration that has been previously associated. Use a different DataIntegration, or recreate the DataIntegration using the CreateDataIntegration API.
*/
updateDataIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.UpdateDataIntegrationResponse) => void): Request<AppIntegrations.Types.UpdateDataIntegrationResponse, AWSError>;
/**
* Updates the description of an event integration.
*/
updateEventIntegration(params: AppIntegrations.Types.UpdateEventIntegrationRequest, callback?: (err: AWSError, data: AppIntegrations.Types.UpdateEventIntegrationResponse) => void): Request<AppIntegrations.Types.UpdateEventIntegrationResponse, AWSError>;
/**
* Updates the description of an event integration.
*/
updateEventIntegration(callback?: (err: AWSError, data: AppIntegrations.Types.UpdateEventIntegrationResponse) => void): Request<AppIntegrations.Types.UpdateEventIntegrationResponse, AWSError>;
}
declare namespace AppIntegrations {
export type Arn = string;
export type ClientAssociationMetadata = {[key: string]: NonBlankString};
export type ClientId = string;
export interface CreateDataIntegrationRequest {
/**
* The name of the DataIntegration.
*/
Name: Name;
/**
* A description of the DataIntegration.
*/
Description?: Description;
/**
* The KMS key for the DataIntegration.
*/
KmsKey?: NonBlankString;
/**
* The URI of the data source.
*/
SourceURI?: NonBlankString;
/**
* The name of the data and how often it should be pulled from the source.
*/
ScheduleConfig?: ScheduleConfiguration;
/**
* One or more tags.
*/
Tags?: TagMap;
/**
* A unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
*/
ClientToken?: IdempotencyToken;
}
export interface CreateDataIntegrationResponse {
/**
* The Amazon Resource Name (ARN)
*/
Arn?: Arn;
/**
* A unique identifier.
*/
Id?: UUID;
/**
* The name of the DataIntegration.
*/
Name?: Name;
/**
* A description of the DataIntegration.
*/
Description?: Description;
/**
* The KMS key for the DataIntegration.
*/
KmsKey?: NonBlankString;
/**
* The URI of the data source.
*/
SourceURI?: NonBlankString;
/**
* The name of the data and how often it should be pulled from the source.
*/
ScheduleConfiguration?: ScheduleConfiguration;
/**
* One or more tags.
*/
Tags?: TagMap;
/**
* A unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
*/
ClientToken?: IdempotencyToken;
}
export interface CreateEventIntegrationRequest {
/**
* The name of the event integration.
*/
Name: Name;
/**
* The description of the event integration.
*/
Description?: Description;
/**
* The event filter.
*/
EventFilter: EventFilter;
/**
* The EventBridge bus.
*/
EventBridgeBus: EventBridgeBus;
/**
* A unique, case-sensitive identifier that you provide to ensure the idempotency of the request.
*/
ClientToken?: IdempotencyToken;
/**
* One or more tags.
*/
Tags?: TagMap;
}
export interface CreateEventIntegrationResponse {
/**
* The Amazon Resource Name (ARN) of the event integration.
*/
EventIntegrationArn?: Arn;
}
export interface DataIntegrationAssociationSummary {
/**
* The Amazon Resource Name (ARN) of the DataIntegration association.
*/
DataIntegrationAssociationArn?: Arn;
/**
* The Amazon Resource Name (ARN)of the DataIntegration.
*/
DataIntegrationArn?: Arn;
/**
* The identifier for teh client that is associated with the DataIntegration association.
*/
ClientId?: ClientId;
}
export type DataIntegrationAssociationsList = DataIntegrationAssociationSummary[];
export interface DataIntegrationSummary {
/**
* The Amazon Resource Name (ARN) of the DataIntegration.
*/
Arn?: Arn;
/**
* The name of the DataIntegration.
*/
Name?: Name;
/**
* The URI of the data source.
*/
SourceURI?: NonBlankString;
}
export type DataIntegrationsList = DataIntegrationSummary[];
export interface DeleteDataIntegrationRequest {
/**
* A unique identifier for the DataIntegration.
*/
DataIntegrationIdentifier: Identifier;
}
export interface DeleteDataIntegrationResponse {
}
export interface DeleteEventIntegrationRequest {
/**
* The name of the event integration.
*/
Name: Name;
}
export interface DeleteEventIntegrationResponse {
}
export type Description = string;
export type EventBridgeBus = string;
export type EventBridgeRuleName = string;
export interface EventFilter {
/**
* The source of the events.
*/
Source: Source;
}
export interface EventIntegration {
/**
* The Amazon Resource Name (ARN) of the event integration.
*/
EventIntegrationArn?: Arn;
/**
* The name of the event integration.
*/
Name?: Name;
/**
* The event integration description.
*/
Description?: Description;
/**
* The event integration filter.
*/
EventFilter?: EventFilter;
/**
* The Amazon EventBridge bus for the event integration.
*/
EventBridgeBus?: EventBridgeBus;
/**
* The tags.
*/
Tags?: TagMap;
}
export interface EventIntegrationAssociation {
/**
* The Amazon Resource Name (ARN) for the event integration association.
*/
EventIntegrationAssociationArn?: Arn;
/**
* The identifier for the event integration association.
*/
EventIntegrationAssociationId?: UUID;
/**
* The name of the event integration.
*/
EventIntegrationName?: Name;
/**
* The identifier for the client that is associated with the event integration.
*/
ClientId?: ClientId;
/**
* The name of the EventBridge rule.
*/
EventBridgeRuleName?: EventBridgeRuleName;
/**
* The metadata associated with the client.
*/
ClientAssociationMetadata?: ClientAssociationMetadata;
}
export type EventIntegrationAssociationsList = EventIntegrationAssociation[];
export type EventIntegrationsList = EventIntegration[];
export interface GetDataIntegrationRequest {
/**
* A unique identifier.
*/
Identifier: Identifier;
}
export interface GetDataIntegrationResponse {
/**
* The Amazon Resource Name (ARN) for the DataIntegration.
*/
Arn?: Arn;
/**
* A unique identifier.
*/
Id?: UUID;
/**
* The name of the DataIntegration.
*/
Name?: Name;
/**
* The KMS key for the DataIntegration.
*/
Description?: Description;
/**
* The KMS key for the DataIntegration.
*/
KmsKey?: NonBlankString;
/**
* The URI of the data source.
*/
SourceURI?: NonBlankString;
/**
* The name of the data and how often it should be pulled from the source.
*/
ScheduleConfiguration?: ScheduleConfiguration;
/**
* One or more tags.
*/
Tags?: TagMap;
}
export interface GetEventIntegrationRequest {
/**
* The name of the event integration.
*/
Name: Name;
}
export interface GetEventIntegrationResponse {
/**
* The name of the event integration.
*/
Name?: Name;
/**
* The description of the event integration.
*/
Description?: Description;
/**
* The Amazon Resource Name (ARN) for the event integration.
*/
EventIntegrationArn?: Arn;
/**
* The EventBridge bus.
*/
EventBridgeBus?: EventBridgeBus;
/**
* The event filter.
*/
EventFilter?: EventFilter;
/**
* One or more tags.
*/
Tags?: TagMap;
}
export type IdempotencyToken = string;
export type Identifier = string;
export interface ListDataIntegrationAssociationsRequest {
/**
* A unique identifier for the DataIntegration.
*/
DataIntegrationIdentifier: Identifier;
/**
* The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
*/
NextToken?: NextToken;
/**
* The maximum number of results to return per page.
*/
MaxResults?: MaxResults;
}
export interface ListDataIntegrationAssociationsResponse {
/**
* The Amazon Resource Name (ARN) and unique ID of the DataIntegration association.
*/
DataIntegrationAssociations?: DataIntegrationAssociationsList;
/**
* If there are additional results, this is the token for the next set of results.
*/
NextToken?: NextToken;
}
export interface ListDataIntegrationsRequest {
/**
* The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
*/
NextToken?: NextToken;
/**
* The maximum number of results to return per page.
*/
MaxResults?: MaxResults;
}
export interface ListDataIntegrationsResponse {
/**
* The DataIntegrations associated with this account.
*/
DataIntegrations?: DataIntegrationsList;
/**
* If there are additional results, this is the token for the next set of results.
*/
NextToken?: NextToken;
}
export interface ListEventIntegrationAssociationsRequest {
/**
* The name of the event integration.
*/
EventIntegrationName: Name;
/**
* The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
*/
NextToken?: NextToken;
/**
* The maximum number of results to return per page.
*/
MaxResults?: MaxResults;
}
export interface ListEventIntegrationAssociationsResponse {
/**
* The event integration associations.
*/
EventIntegrationAssociations?: EventIntegrationAssociationsList;
/**
* If there are additional results, this is the token for the next set of results.
*/
NextToken?: NextToken;
}
export interface ListEventIntegrationsRequest {
/**
* The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
*/
NextToken?: NextToken;
/**
* The maximum number of results to return per page.
*/
MaxResults?: MaxResults;
}
export interface ListEventIntegrationsResponse {
/**
* The event integrations.
*/
EventIntegrations?: EventIntegrationsList;
/**
* If there are additional results, this is the token for the next set of results.
*/
NextToken?: NextToken;
}
export interface ListTagsForResourceRequest {
/**
* The Amazon Resource Name (ARN) of the resource.
*/
resourceArn: Arn;
}
export interface ListTagsForResourceResponse {
/**
* Information about the tags.
*/
tags?: TagMap;
}
export type MaxResults = number;
export type Name = string;
export type NextToken = string;
export type NonBlankString = string;
export type Object = string;
export type Schedule = string;
export interface ScheduleConfiguration {
/**
* The start date for objects to import in the first flow run.
*/
FirstExecutionFrom?: NonBlankString;
/**
* The name of the object to pull from the data source.
*/
Object?: Object;
/**
* How often the data should be pulled from data source.
*/
ScheduleExpression?: Schedule;
}
export type Source = string;
export type TagKey = string;
export type TagKeyList = TagKey[];
export type TagMap = {[key: string]: TagValue};
export interface TagResourceRequest {
/**
* The Amazon Resource Name (ARN) of the resource.
*/
resourceArn: Arn;
/**
* One or more tags.
*/
tags: TagMap;
}
export interface TagResourceResponse {
}
export type TagValue = string;
export type UUID = string;
export interface UntagResourceRequest {
/**
* The Amazon Resource Name (ARN) of the resource.
*/
resourceArn: Arn;
/**
* The tag keys.
*/
tagKeys: TagKeyList;
}
export interface UntagResourceResponse {
}
export interface UpdateDataIntegrationRequest {
/**
* A unique identifier for the DataIntegration.
*/
Identifier: Identifier;
/**
* The name of the DataIntegration.
*/
Name?: Name;
/**
* A description of the DataIntegration.
*/
Description?: Description;
}
export interface UpdateDataIntegrationResponse {
}
export interface UpdateEventIntegrationRequest {
/**
* The name of the event integration.
*/
Name: Name;
/**
* The description of the event inegration.
*/
Description?: Description;
}
export interface UpdateEventIntegrationResponse {
}
/**
* 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 = "2020-07-29"|"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 AppIntegrations client.
*/
export import Types = AppIntegrations;
}
export = AppIntegrations; | the_stack |
export interface ContractEnumMetadata {
enumValues?: { [name: string]: number; };
}
export interface SerializationData {
requestTypeMetadata?: ContractMetadata;
responseTypeMetadata?: ContractMetadata;
responseIsCollection: boolean;
}
/**
* Metadata for deserializing a particular field on a contract/type
*/
export interface ContractFieldMetadata {
isArray?: boolean;
isDate?: boolean;
enumType?: ContractEnumMetadata;
typeInfo?: ContractMetadata;
isDictionary?: boolean;
dictionaryKeyIsDate?: boolean;
dictionaryValueIsDate?: boolean;
dictionaryKeyEnumType?: ContractEnumMetadata;
dictionaryValueEnumType?: ContractEnumMetadata;
dictionaryValueTypeInfo?: ContractMetadata;
dictionaryValueFieldInfo?: ContractFieldMetadata;
}
/**
* Metadata required for deserializing a given type
*/
export interface ContractMetadata {
fields?: { [fieldName: string]: ContractFieldMetadata; };
}
export interface IWebApiArrayResult {
count: number;
value: any[];
}
/**
* Module for handling serialization and deserialization of data contracts
* (contracts sent from the server using the VSO default REST api serialization settings)
*/
export module ContractSerializer {
var _legacyDateRegExp: RegExp;
/**
* Process a contract in its raw form (e.g. date fields are Dates, and Enums are numbers) and
* return a pure JSON object that can be posted to REST endpoint.
*
* @param data The object to serialize
* @param contractMetadata The type info/metadata for the contract type being serialized
* @param preserveOriginal If true, don't modify the original object. False modifies the original object (the return value points to the data argument).
*/
export function serialize(data: any, contractMetadata: ContractMetadata, preserveOriginal: boolean) {
if (data && contractMetadata) {
if (Array.isArray(data)) {
return _getTranslatedArray(data, contractMetadata, true, preserveOriginal);
}
else {
return _getTranslatedObject(data, contractMetadata, true, preserveOriginal);
}
}
else {
return data;
}
}
/**
* Process a pure JSON object (e.g. that came from a REST call) and transform it into a JS object
* where date strings are converted to Date objects and enum values are converted from strings into
* their numerical value.
*
* @param data The object to deserialize
* @param contractMetadata The type info/metadata for the contract type being deserialize
* @param preserveOriginal If true, don't modify the original object. False modifies the original object (the return value points to the data argument).
* @param unwrapWrappedCollections If true check for wrapped arrays (REST apis will not return arrays directly as the root result but will instead wrap them in a { values: [], count: 0 } object.
*/
export function deserialize(data: any, contractMetadata: ContractMetadata, preserveOriginal: boolean, unwrapWrappedCollections: boolean) {
if (data) {
if (unwrapWrappedCollections && Array.isArray((<IWebApiArrayResult>data).value)) {
// Wrapped json array - unwrap it and send the array as the result
data = (<IWebApiArrayResult>data).value;
}
if (contractMetadata) {
if (Array.isArray(data)) {
data = _getTranslatedArray(data, contractMetadata, false, preserveOriginal);
}
else {
data = _getTranslatedObject(data, contractMetadata, false, preserveOriginal);
}
}
}
return data;
}
function _getTranslatedArray(array: any, typeMetadata: ContractMetadata, serialize: boolean, preserveOriginal: boolean) {
var resultArray: any[] = array;
var arrayCopy: any[] = [];
var i;
for (i = 0; i < array.length; i++) {
var item = array[i];
var processedItem: any;
// handle arrays of arrays
if (Array.isArray(item)) {
processedItem = _getTranslatedArray(item, typeMetadata, serialize, preserveOriginal);
}
else {
processedItem = _getTranslatedObject(item, typeMetadata, serialize, preserveOriginal);
}
if (preserveOriginal) {
arrayCopy.push(processedItem);
if (processedItem !== item) {
resultArray = arrayCopy;
}
}
else {
array[i] = processedItem;
}
}
return resultArray;
}
function _getTranslatedObject(typeObject: any, typeMetadata: ContractMetadata, serialize: boolean, preserveOriginal: boolean) {
var processedItem = typeObject,
copiedItem = false;
if (typeObject && typeMetadata.fields) {
for (var fieldName in typeMetadata.fields) {
var fieldMetadata = typeMetadata.fields[fieldName];
var fieldValue = typeObject[fieldName];
var translatedValue = _getTranslatedField(fieldValue, fieldMetadata, serialize, preserveOriginal);
if (fieldValue !== translatedValue) {
if (preserveOriginal && !copiedItem) {
processedItem = this._extend({}, typeObject);
copiedItem = true;
}
processedItem[fieldName] = translatedValue;
}
}
}
return processedItem;
}
function _getTranslatedField(fieldValue: any, fieldMetadata: ContractFieldMetadata, serialize: boolean, preserveOriginal: boolean) {
if (!fieldValue) {
return fieldValue;
}
if (fieldMetadata.isArray) {
if (Array.isArray(fieldValue)) {
var newArray: any[] = [],
processedArray: any[] = fieldValue;
for(var index = 0; index < fieldValue.length; index++) {
var arrayValue = fieldValue[index];
var processedValue = arrayValue;
if (fieldMetadata.isDate) {
processedValue = _getTranslatedDateValue(arrayValue, serialize);
}
else if (fieldMetadata.enumType) {
processedValue = _getTranslatedEnumValue(fieldMetadata.enumType, arrayValue, serialize);
}
else if (fieldMetadata.typeInfo) {
if (Array.isArray(arrayValue)) {
processedValue = _getTranslatedArray(arrayValue, fieldMetadata.typeInfo, serialize, preserveOriginal);
}
else {
processedValue = _getTranslatedObject(arrayValue, fieldMetadata.typeInfo, serialize, preserveOriginal);
}
}
if (preserveOriginal) {
newArray.push(processedValue);
if (processedValue !== arrayValue) {
processedArray = newArray;
}
}
else {
fieldValue[index] = processedValue;
}
}
return processedArray;
}
else {
return fieldValue;
}
}
else if (fieldMetadata.isDictionary) {
var dictionaryModified = false;
var newDictionary = <any>{};
for(var key in fieldValue) {
var dictionaryValue = fieldValue[key];
var newKey = key,
newValue = dictionaryValue;
if (fieldMetadata.dictionaryKeyIsDate) {
newKey = _getTranslatedDateValue(key, serialize);
}
else if (fieldMetadata.dictionaryKeyEnumType) {
newKey = _getTranslatedEnumValue(fieldMetadata.dictionaryKeyEnumType, key, serialize);
}
if (fieldMetadata.dictionaryValueIsDate) {
newValue = _getTranslatedDateValue(dictionaryValue, serialize);
}
else if (fieldMetadata.dictionaryValueEnumType) {
newValue = _getTranslatedEnumValue(fieldMetadata.dictionaryValueEnumType, dictionaryValue, serialize);
}
else if (fieldMetadata.dictionaryValueTypeInfo) {
newValue = _getTranslatedObject(newValue, fieldMetadata.dictionaryValueTypeInfo, serialize, preserveOriginal);
}
else if (fieldMetadata.dictionaryValueFieldInfo) {
newValue = _getTranslatedField(dictionaryValue, fieldMetadata.dictionaryValueFieldInfo, serialize, preserveOriginal);
}
newDictionary[newKey] = newValue;
if (key !== newKey || dictionaryValue !== newValue) {
dictionaryModified = true;
}
}
return dictionaryModified ? newDictionary : fieldValue;
}
else {
if (fieldMetadata.isDate) {
return _getTranslatedDateValue(fieldValue, serialize);
}
else if (fieldMetadata.enumType) {
return _getTranslatedEnumValue(fieldMetadata.enumType, fieldValue, serialize);
}
else if (fieldMetadata.typeInfo) {
return _getTranslatedObject(fieldValue, fieldMetadata.typeInfo, serialize, preserveOriginal);
}
else {
return fieldValue;
}
}
}
function _getTranslatedEnumValue(enumType: ContractEnumMetadata, valueToConvert: any, serialize: boolean): any {
if (serialize && typeof valueToConvert === "number") {
// Serialize: number --> String
// Because webapi handles the numerical value for enums, there is no need to convert to string.
// Let this fall through to return the numerical value.
}
else if (!serialize && typeof valueToConvert === "string") {
// Deserialize: String --> number
var result = 0;
if (valueToConvert) {
var splitValue = valueToConvert.split(",");
for(var i = 0; i < splitValue.length; i++) {
var valuePart = splitValue[i];
//equivalent to jquery trim
//copied from https://github.com/HubSpot/youmightnotneedjquery/blob/ef987223c20e480fcbfb5924d96c11cd928e1226/comparisons/utils/trim/ie8.js
var enumName = valuePart.replace(/^\s+|\s+$/g, '') || "";
if (enumName) {
var resultPart = enumType.enumValues[enumName];
if (!resultPart) {
// No matching enum value. Try again but case insensitive
var lowerCaseEnumName = enumName.toLowerCase();
if (lowerCaseEnumName !== enumName) {
for(var name in enumType.enumValues) {
var value = enumType.enumValues[name];
if (name.toLowerCase() === lowerCaseEnumName) {
resultPart = value;
break;
}
}
}
}
if (resultPart) {
result |= resultPart;
}
}
}
}
return result;
}
return valueToConvert;
}
function _getTranslatedDateValue(valueToConvert: any, serialize: boolean): any {
if (!serialize && typeof valueToConvert === "string") {
// Deserialize: String --> Date
var dateValue = new Date(valueToConvert);
if (isNaN(<any>dateValue) && navigator.userAgent && /msie/i.test(navigator.userAgent)) {
dateValue = _convertLegacyIEDate(valueToConvert);
}
return dateValue;
}
return valueToConvert;
}
function _convertLegacyIEDate(dateStringValue: string) {
// IE 8/9 does not handle parsing dates in ISO form like:
// 2013-05-13T14:26:54.397Z
var match: RegExpExecArray;
if (!_legacyDateRegExp) {
_legacyDateRegExp = new RegExp("(\\d+)-(\\d+)-(\\d+)T(\\d+):(\\d+):(\\d+).(\\d+)Z");
}
match = _legacyDateRegExp.exec(dateStringValue);
if (match) {
return new Date(Date.UTC(parseInt(match[1]), parseInt(match[2]) - 1, parseInt(match[3]), parseInt(match[4]), parseInt(match[5]), parseInt(match[6]), parseInt(match[7])));
}
else {
return null;
}
}
// jquery extend method in native javascript (used to clone objects)
// copied from https://github.com/HubSpot/youmightnotneedjquery/blob/ef987223c20e480fcbfb5924d96c11cd928e1226/comparisons/utils/extend/ie8.js
var _extend = function(out) {
out = out || {};
for (var i = 1; i < arguments.length; i++) {
if (!arguments[i])
continue;
for (var key in arguments[i]) {
if (arguments[i].hasOwnProperty(key))
out[key] = arguments[i][key];
}
}
return out;
};
} | the_stack |
import { createClassFromInterface } from "@microsoft/applicationinsights-core-js";
function _aiNameFunc(baseName: string) {
let aiName = "ai." + baseName + ".";
return function(name: string) {
return aiName + name;
}
}
let _aiApplication = _aiNameFunc("application");
let _aiDevice = _aiNameFunc("device");
let _aiLocation = _aiNameFunc("location");
let _aiOperation = _aiNameFunc("operation");
let _aiSession = _aiNameFunc("session");
let _aiUser = _aiNameFunc("user");
let _aiCloud = _aiNameFunc("cloud");
let _aiInternal = _aiNameFunc("internal");
export interface IContextTagKeys {
/**
* Application version. Information in the application context fields is always about the application that is sending the telemetry.
*/
readonly applicationVersion: string;
/**
* Application build.
*/
readonly applicationBuild: string;
/**
* Application type id.
*/
readonly applicationTypeId: string;
/**
* Application id.
*/
readonly applicationId: string;
/**
* Application layer.
*/
readonly applicationLayer: string;
/**
* Unique client device id. Computer name in most cases.
*/
readonly deviceId: string;
readonly deviceIp: string;
readonly deviceLanguage: string;
/**
* Device locale using <language>-<REGION> pattern, following RFC 5646. Example 'en-US'.
*/
readonly deviceLocale: string;
/**
* Model of the device the end user of the application is using. Used for client scenarios. If this field is empty then it is derived from the user agent.
*/
readonly deviceModel: string;
readonly deviceFriendlyName: string;
readonly deviceNetwork: string;
readonly deviceNetworkName: string;
/**
* Client device OEM name taken from the browser.
*/
readonly deviceOEMName: string;
readonly deviceOS: string;
/**
* Operating system name and version of the device the end user of the application is using. If this field is empty then it is derived from the user agent. Example 'Windows 10 Pro 10.0.10586.0'
*/
readonly deviceOSVersion: string;
/**
* Name of the instance where application is running. Computer name for on-premisis, instance name for Azure.
*/
readonly deviceRoleInstance: string;
/**
* Name of the role application is part of. Maps directly to the role name in azure.
*/
readonly deviceRoleName: string;
readonly deviceScreenResolution: string;
/**
* The type of the device the end user of the application is using. Used primarily to distinguish JavaScript telemetry from server side telemetry. Examples: 'PC', 'Phone', 'Browser'. 'PC' is the default value.
*/
readonly deviceType: string;
readonly deviceMachineName: string;
readonly deviceVMName: string;
readonly deviceBrowser: string;
/**
* The browser name and version as reported by the browser.
*/
readonly deviceBrowserVersion: string;
/**
* The IP address of the client device. IPv4 and IPv6 are supported. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.
*/
readonly locationIp: string;
/**
* The country of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.
*/
readonly locationCountry: string;
/**
* The province/state of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.
*/
readonly locationProvince: string;
/**
* The city of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.
*/
readonly locationCity: string;
/**
* A unique identifier for the operation instance. The operation.id is created by either a request or a page view. All other telemetry sets this to the value for the containing request or page view. Operation.id is used for finding all the telemetry items for a specific operation instance.
*/
readonly operationId: string;
/**
* The name (group) of the operation. The operation.name is created by either a request or a page view. All other telemetry items set this to the value for the containing request or page view. Operation.name is used for finding all the telemetry items for a group of operations (i.e. 'GET Home/Index').
*/
readonly operationName: string;
/**
* The unique identifier of the telemetry item's immediate parent.
*/
readonly operationParentId: string;
readonly operationRootId: string;
/**
* Name of synthetic source. Some telemetry from the application may represent a synthetic traffic. It may be web crawler indexing the web site, site availability tests or traces from diagnostic libraries like Application Insights SDK itself.
*/
readonly operationSyntheticSource: string;
/**
* The correlation vector is a light weight vector clock which can be used to identify and order related events across clients and services.
*/
readonly operationCorrelationVector: string;
/**
* Session ID - the instance of the user's interaction with the app. Information in the session context fields is always about the end user. When telemetry is sent from a service, the session context is about the user that initiated the operation in the service.
*/
readonly sessionId: string;
/**
* Boolean value indicating whether the session identified by ai.session.id is first for the user or not.
*/
readonly sessionIsFirst: string;
readonly sessionIsNew: string;
readonly userAccountAcquisitionDate: string;
/**
* In multi-tenant applications this is the account ID or name which the user is acting with. Examples may be subscription ID for Azure portal or blog name blogging platform.
*/
readonly userAccountId: string;
/**
* The browser's user agent string as reported by the browser. This property will be used to extract informaiton regarding the customer's browser but will not be stored. Use custom properties to store the original user agent.
*/
readonly userAgent: string;
/**
* Anonymous user id. Represents the end user of the application. When telemetry is sent from a service, the user context is about the user that initiated the operation in the service.
*/
readonly userId: string;
/**
* Store region for UWP applications.
*/
readonly userStoreRegion: string;
/**
* Authenticated user id. The opposite of ai.user.id, this represents the user with a friendly name. Since it's PII information it is not collected by default by most SDKs.
*/
readonly userAuthUserId: string;
readonly userAnonymousUserAcquisitionDate: string;
readonly userAuthenticatedUserAcquisitionDate: string;
readonly cloudName: string;
/**
* Name of the role the application is a part of. Maps directly to the role name in azure.
*/
readonly cloudRole: string;
readonly cloudRoleVer: string;
/**
* Name of the instance where the application is running. Computer name for on-premisis, instance name for Azure.
*/
readonly cloudRoleInstance: string;
readonly cloudEnvironment: string;
readonly cloudLocation: string;
readonly cloudDeploymentUnit: string;
/**
* SDK version. See https://github.com/microsoft/ApplicationInsights-Home/blob/master/SDK-AUTHORING.md#sdk-version-specification for information.
*/
readonly internalSdkVersion: string;
/**
* Agent version. Used to indicate the version of StatusMonitor installed on the computer if it is used for data collection.
*/
readonly internalAgentVersion: string;
/**
* This is the node name used for billing purposes. Use it to override the standard detection of nodes.
*/
readonly internalNodeName: string;
/**
* This identifies the version of the snippet that was used to initialize the SDK
*/
readonly internalSnippet: string;
/**
* This identifies the source of the Sdk script (used to identify whether the SDK was loaded via the CDN)
*/
readonly internalSdkSrc: string;
}
export class ContextTagKeys extends createClassFromInterface<IContextTagKeys>({
applicationVersion: _aiApplication("ver"),
applicationBuild: _aiApplication("build"),
applicationTypeId: _aiApplication("typeId"),
applicationId: _aiApplication("applicationId"),
applicationLayer: _aiApplication("layer"),
deviceId: _aiDevice("id"),
deviceIp: _aiDevice("ip"),
deviceLanguage: _aiDevice("language"),
deviceLocale: _aiDevice("locale"),
deviceModel: _aiDevice("model"),
deviceFriendlyName: _aiDevice("friendlyName"),
deviceNetwork: _aiDevice("network"),
deviceNetworkName: _aiDevice("networkName"),
deviceOEMName: _aiDevice("oemName"),
deviceOS: _aiDevice("os"),
deviceOSVersion: _aiDevice("osVersion"),
deviceRoleInstance: _aiDevice("roleInstance"),
deviceRoleName: _aiDevice("roleName"),
deviceScreenResolution: _aiDevice("screenResolution"),
deviceType: _aiDevice("type"),
deviceMachineName: _aiDevice("machineName"),
deviceVMName: _aiDevice("vmName"),
deviceBrowser: _aiDevice("browser"),
deviceBrowserVersion: _aiDevice("browserVersion"),
locationIp: _aiLocation("ip"),
locationCountry: _aiLocation("country"),
locationProvince: _aiLocation("province"),
locationCity: _aiLocation("city"),
operationId: _aiOperation("id"),
operationName: _aiOperation("name"),
operationParentId: _aiOperation("parentId"),
operationRootId: _aiOperation("rootId"),
operationSyntheticSource: _aiOperation("syntheticSource"),
operationCorrelationVector: _aiOperation("correlationVector"),
sessionId: _aiSession("id"),
sessionIsFirst: _aiSession("isFirst"),
sessionIsNew: _aiSession("isNew"),
userAccountAcquisitionDate: _aiUser("accountAcquisitionDate"),
userAccountId: _aiUser("accountId"),
userAgent: _aiUser("userAgent"),
userId: _aiUser("id"),
userStoreRegion: _aiUser("storeRegion"),
userAuthUserId: _aiUser("authUserId"),
userAnonymousUserAcquisitionDate: _aiUser("anonUserAcquisitionDate"),
userAuthenticatedUserAcquisitionDate: _aiUser("authUserAcquisitionDate"),
cloudName: _aiCloud("name"),
cloudRole: _aiCloud("role"),
cloudRoleVer: _aiCloud("roleVer"),
cloudRoleInstance: _aiCloud("roleInstance"),
cloudEnvironment: _aiCloud("environment"),
cloudLocation: _aiCloud("location"),
cloudDeploymentUnit: _aiCloud("deploymentUnit"),
internalNodeName: _aiInternal("nodeName"),
internalSdkVersion: _aiInternal("sdkVersion"),
internalAgentVersion: _aiInternal("agentVersion"),
internalSnippet: _aiInternal("snippet"),
internalSdkSrc: _aiInternal("sdkSrc")
}) {
constructor() {
super();
}
} | the_stack |
'use strict';
/**
* Error thrown when an argument is invalid.
*
* @augments {Error}
*/
export class ArgumentError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'ArgumentError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
// Set the prototype explicitly.
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, ArgumentError.prototype);
}
}
/**
* Error thrown when an argument has a value that is out of the admissible range.
*
* @augments {Error}
*/
export class ArgumentOutOfRangeError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'ArgumentOutOfRangeError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, ArgumentOutOfRangeError.prototype);
}
}
/**
* Error thrown when the message queue for a device is full.
*
* @augments {Error}
*/
export class DeviceMaximumQueueDepthExceededError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'DeviceMaximumQueueDepthExceededError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, DeviceMaximumQueueDepthExceededError.prototype);
}
}
/**
* Error thrown when a device cannot be found in the IoT Hub instance registry.
*
* @augments {Error}
*/
export class DeviceNotFoundError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'DeviceNotFoundError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, DeviceNotFoundError.prototype);
}
}
/**
* Error thrown when a string that is supposed to have a specific formatting is not formatted properly.
*
* @augments {Error}
*/
export class FormatError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'FormatError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, FormatError.prototype);
}
}
/**
* Error thrown when the connection parameters are wrong and the server refused the connection.
*
* @augments {Error}
*/
export class UnauthorizedError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'UnauthorizedError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, UnauthorizedError.prototype);
}
}
/**
* Error thrown when a feature is not implemented yet but the placeholder is present.
*
* @augments {Error}
*/
export class NotImplementedError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'NotImplementedError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, NotImplementedError.prototype);
}
}
/**
* Error thrown when the device is disconnected and the operation cannot be completed.
*
* @augments {Error}
*/
export class NotConnectedError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'NotConnectedError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, NotConnectedError.prototype);
}
}
/**
* Error thrown the the Azure IoT hub quota has been exceeded. Quotas are reset periodically, this operation will have to wait until then.
* To learn more about quotas, see {@link https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-quotas-throttling|Azure IoT Hub quotas and throttling}
*
* @augments {Error}
*/
export class IotHubQuotaExceededError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'IotHubQuotaExceededError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, IotHubQuotaExceededError.prototype);
}
}
/**
* Error thrown when the message sent is too large: the maximum size is 256Kb.
*
* @augments {Error}
*/
export class MessageTooLargeError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'MessageTooLargeError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, MessageTooLargeError.prototype);
}
}
/**
* Error thrown when an internal server error occured. You may have found a bug?
*
* @augments {Error}
*/
export class InternalServerError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'InternalServerError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, InternalServerError.prototype);
}
}
/**
* Error thrown when the service is unavailable. The operation should be retried.
*
* @augments {Error}
*/
export class ServiceUnavailableError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'ServiceUnavailableError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, ServiceUnavailableError.prototype);
}
}
/**
* Error thrown when the Azure IoT hub was not found.
*
* @augments {Error}
*/
export class IotHubNotFoundError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'IotHubNotFoundError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, IotHubNotFoundError.prototype);
}
}
/**
* Error thrown when IoT Hub has been suspended.
*
* @augments {Error}
*/
export class IoTHubSuspendedError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'IoTHubSuspendedError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, IoTHubSuspendedError.prototype);
}
}
/**
* Error thrown when the job with the specified identifier was not found.
*
* @augments {Error}
*/
export class JobNotFoundError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'JobNotFoundError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, JobNotFoundError.prototype);
}
}
/**
* Error thrown when the maximum number of devices on a specific hub has been reached.
*
* @augments {Error}
*/
export class TooManyDevicesError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'TooManyDevicesError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, TooManyDevicesError.prototype);
}
}
/**
* Error thrown when IoT Hub is throttled due to excessive activity.
* To learn more about quotas, see {@link https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-quotas-throttling|Azure IoT Hub quotas and throttling}
*
* @augments {Error}
*/
export class ThrottlingError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'ThrottlingError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, ThrottlingError.prototype);
}
}
/**
* Error thrown when the device id used for device creation already exists in the Device Identity Registry.
*
* @augments {Error}
*/
export class DeviceAlreadyExistsError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'DeviceAlreadyExistsError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, DeviceAlreadyExistsError.prototype);
}
}
/**
* Error thrown when settling a message fails because the lock token associated with the message is lost.
*
* @augments {Error}
*/
export class DeviceMessageLockLostError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'DeviceMessageLockLostError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, DeviceMessageLockLostError.prototype);
}
}
/**
* Error thrown when the eTag specified is incorrectly formatted or out of date.
*
* @augments {Error}
*/
export class InvalidEtagError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'InvalidEtagError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, InvalidEtagError.prototype);
}
}
/**
* Error thrown when an operation is attempted but is not allowed.
*
* @augments {Error}
*/
export class InvalidOperationError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'InvalidOperationError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, InvalidOperationError.prototype);
}
}
/**
* Error thrown when a condition that should have been met in order to execute an operation was not.
*
* @augments {Error}
*/
export class PreconditionFailedError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'PreconditionFailedError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, PreconditionFailedError.prototype);
}
}
/**
* Error thrown when a timeout occurs
*
* @augments {Error}
*/
export class TimeoutError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'TimeoutError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, TimeoutError.prototype);
}
}
/**
* Error thrown when a device sends a bad response to a device method call.
*
* @augments {Error}
*/
export class BadDeviceResponseError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'BadDeviceResponseError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, BadDeviceResponseError.prototype);
}
}
/**
* Error thrown when the IoT Hub instance doesn't process the device method call in time.
*
* @augments {Error}
*/
export class GatewayTimeoutError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'GatewayTimeoutError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, GatewayTimeoutError.prototype);
}
}
/**
* Error thrown when the device doesn't process the method call in time.
*
* @augments {Error}
*/
export class DeviceTimeoutError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'DeviceTimeoutError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, DeviceTimeoutError.prototype);
}
}
/**
* Error thrown when the c2d feature stopped working at the transport level, requiring the client to retry starting it.
*
* @augments {Error}
*/
export class CloudToDeviceDetachedError extends Error {
innerError: Error;
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'CloudToDeviceDetachedError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, CloudToDeviceDetachedError.prototype);
}
}
/**
* Error thrown when the device methods feature stopped working at the transport level, requiring the client to retry starting it.
*
* @augments {Error}
*/
export class DeviceMethodsDetachedError extends Error {
innerError: Error;
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'DeviceMethodsDetachedError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, DeviceMethodsDetachedError.prototype);
}
}
/**
* Error thrown when the twin feature stopped working at the transport level, requiring the client to retry starting it.
*
* @augments {Error}
*/
export class TwinDetachedError extends Error {
innerError: Error;
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'TwinDetachedError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, TwinDetachedError.prototype);
}
}
/**
* Generic error thrown when a twin request fails with an unknown error code.
*
* @augments {Error}
*/
export class TwinRequestError extends Error {
transportError: any;
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'TwinRequestError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, TwinRequestError.prototype);
}
}
/**
* Error thrown when any operation (local or remote) is cancelled
*
* @augments {Error}
*/
export class OperationCancelledError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'OperationCancelledError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, OperationCancelledError.prototype);
}
}
/**
* Error thrown when a DPS registration operation fails
*
* @augments {Error}
*/
export class DeviceRegistrationFailedError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'ProvisioningRegistrationFailedError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, DeviceRegistrationFailedError.prototype);
}
}
/**
* Error thrown when a low level security device/driver fails.
*
* @augments {Error}
*/
export class SecurityDeviceError extends Error {
constructor(message?: string) {
/* istanbul ignore next */
super(message);
this.name = 'SecurityDeviceError';
this.message = message;
Error.captureStackTrace(this, this.constructor);
Object.setPrototypeOf(this, SecurityDeviceError.prototype);
}
} | the_stack |
namespace dragonBones {
/**
* - The egret event.
* @version DragonBones 4.5
* @language en_US
*/
/**
* - Egret 事件。
* @version DragonBones 4.5
* @language zh_CN
*/
export class EgretEvent extends egret.Event {
/**
* - The event object.
* @see dragonBones.EventObject
* @version DragonBones 4.5
* @language en_US
*/
/**
* - 事件对象。
* @see dragonBones.EventObject
* @version DragonBones 4.5
* @language zh_CN
*/
public get eventObject(): EventObject {
return this.data;
}
}
/**
* @inheritDoc
*/
export class EgretArmatureDisplay extends egret.DisplayObjectContainer implements IArmatureProxy {
private static _cleanBeforeRender(): void { }
/**
* @private
*/
public debugDraw: boolean = false;
/**
* @internal
*/
public _batchEnabled: boolean = !(global["nativeRender"] || global["bricks"]); //
/**
* @internal
*/
public _childDirty: boolean = true;
private _debugDraw: boolean = false;
private _armature: Armature = null as any; //
private _bounds: egret.Rectangle | null = null;
private _debugDrawer: egret.Sprite | null = null;
/**
* @inheritDoc
*/
public dbInit(armature: Armature): void {
this._armature = armature;
if (this._batchEnabled) {
this.$renderNode = new egret.sys.GroupNode();
this.$renderNode.cleanBeforeRender = EgretArmatureDisplay._cleanBeforeRender;
}
}
/**
* @inheritDoc
*/
public dbClear(): void {
this._armature = null as any;
this._bounds = null;
this._debugDrawer = null;
}
/**
* @inheritDoc
*/
public dbUpdate(): void {
const drawed = DragonBones.debugDraw || this.debugDraw;
if (drawed || this._debugDraw) {
this._debugDraw = drawed;
if (this._debugDraw) {
if (this._debugDrawer === null) {
this._debugDrawer = new egret.Sprite();
}
if (this._debugDrawer.parent !== this) {
this.addChild(this._debugDrawer);
}
const boneStep = 2.0;
const graphics = this._debugDrawer.graphics;
graphics.clear();
for (const bone of this._armature.getBones()) {
if (bone.boneData.type === BoneType.Bone) {
const boneLength = Math.max(bone.boneData.length, boneStep);
const startX = bone.globalTransformMatrix.tx;
const startY = bone.globalTransformMatrix.ty;
const aX = startX - bone.globalTransformMatrix.a * boneStep;
const aY = startY - bone.globalTransformMatrix.b * boneStep;
const bX = startX + bone.globalTransformMatrix.a * boneLength;
const bY = startY + bone.globalTransformMatrix.b * boneLength;
const cX = startX + aY - startY;
const cY = startY + aX - startX;
const dX = startX - aY + startY;
const dY = startY - aX + startX;
//
graphics.lineStyle(2.0, 0x00FFFF, 0.7);
graphics.moveTo(aX, aY);
graphics.lineTo(bX, bY);
graphics.moveTo(cX, cY);
graphics.lineTo(dX, dY);
}
else {
const surface = bone as Surface;
const surfaceData = surface._boneData as SurfaceData;
const segmentX = surfaceData.segmentX;
const segmentY = surfaceData.segmentY;
const vertices = surface._vertices;
graphics.lineStyle(2.0, 0xFFFF00, 0.3);
for (let iY = 0; iY < segmentY; ++iY) {
for (let iX = 0; iX < segmentX; ++iX) {
const vertexIndex = (iX + iY * (segmentX + 1)) * 2;
const x = vertices[vertexIndex];
const y = vertices[vertexIndex + 1];
graphics.moveTo(x, y);
graphics.lineTo(vertices[vertexIndex + 2], vertices[vertexIndex + 3]);
graphics.moveTo(x, y);
graphics.lineTo(vertices[vertexIndex + (segmentX + 1) * 2], vertices[vertexIndex + (segmentX + 1) * 2 + 1]);
if (iX === segmentX - 1) {
graphics.moveTo(vertices[vertexIndex + 2], vertices[vertexIndex + 3]);
graphics.lineTo(vertices[vertexIndex + (segmentX + 2) * 2], vertices[vertexIndex + (segmentX + 2) * 2 + 1]);
}
if (iY === segmentY - 1) {
graphics.moveTo(vertices[vertexIndex + (segmentX + 1) * 2], vertices[vertexIndex + (segmentX + 1) * 2 + 1]);
graphics.lineTo(vertices[vertexIndex + (segmentX + 2) * 2], vertices[vertexIndex + (segmentX + 2) * 2 + 1]);
}
}
}
}
}
for (const slot of this._armature.getSlots()) {
const boundingBoxData = slot.boundingBoxData;
if (boundingBoxData !== null) {
let child = this._debugDrawer.getChildByName(slot.name) as egret.Shape;
if (child === null) {
child = new egret.Shape();
child.name = slot.name;
this._debugDrawer.addChild(child);
}
child.graphics.clear();
child.graphics.lineStyle(2.0, 0xFF00FF, 0.7);
switch (boundingBoxData.type) {
case BoundingBoxType.Rectangle:
child.graphics.drawRect(-boundingBoxData.width * 0.5, -boundingBoxData.height * 0.5, boundingBoxData.width, boundingBoxData.height);
break;
case BoundingBoxType.Ellipse:
child.graphics.drawEllipse(-boundingBoxData.width * 0.5, -boundingBoxData.height * 0.5, boundingBoxData.width, boundingBoxData.height);
break;
case BoundingBoxType.Polygon:
const vertices = (boundingBoxData as PolygonBoundingBoxData).vertices;
for (let i = 0; i < vertices.length; i += 2) {
const x = vertices[i];
const y = vertices[i + 1];
if (i === 0) {
child.graphics.moveTo(x, y);
}
else {
child.graphics.lineTo(x, y);
}
}
child.graphics.lineTo(vertices[0], vertices[1]);
break;
default:
break;
}
slot.updateTransformAndMatrix();
slot.updateGlobalTransform();
child.$setMatrix((slot.globalTransformMatrix as any) as egret.Matrix, false);
}
else {
const child = this._debugDrawer.getChildByName(slot.name);
if (child !== null) {
this._debugDrawer.removeChild(child);
}
}
}
}
else if (this._debugDrawer !== null && this._debugDrawer.parent === this) {
this.removeChild(this._debugDrawer);
}
}
if (!isV5 && this._batchEnabled && this._childDirty) {
(this as any).$invalidateContentBounds();
}
}
/**
* @inheritDoc
*/
public dispose(disposeProxy: boolean = true): void {
// tslint:disable-next-line:no-unused-expression
disposeProxy;
if (this._armature !== null) {
this._armature.dispose();
this._armature = null as any;
}
}
/**
* @inheritDoc
*/
public dispatchDBEvent(type: EventStringType, eventObject: EventObject): void {
const event = egret.Event.create(EgretEvent, type);
event.data = eventObject;
super.dispatchEvent(event);
egret.Event.release(event);
}
/**
* @inheritDoc
*/
public hasDBEventListener(type: EventStringType): boolean {
return this.hasEventListener(type);
}
/**
* @inheritDoc
*/
public addDBEventListener(type: EventStringType, listener: (event: EgretEvent) => void, target: any): void {
this.addEventListener(type, listener, target);
}
/**
* @inheritDoc
*/
public removeDBEventListener(type: EventStringType, listener: (event: EgretEvent) => void, target: any): void {
this.removeEventListener(type, listener, target);
}
/**
* - Disable the batch.
* Batch rendering for performance reasons, the boundary properties of the render object are not updated.
* This will not correctly obtain the wide-height properties of the rendered object and the transformation properties of its internal display objects,
* which can turn off batch rendering if you need to use these properties.
* @version DragonBones 5.1
* @language en_US
*/
/**
* - 关闭批次渲染。
* 批次渲染出于性能考虑,不会更新渲染对象的边界属性。
* 这样将无法正确获得渲染对象的宽高属性以及其内部显示对象的变换属性,如果需要使用这些属性,可以关闭批次渲染。
* @version DragonBones 5.1
* @language zh_CN
*/
public disableBatch(): void {
if (!this._batchEnabled || !this._armature) {
return;
}
for (const slot of this._armature.getSlots()) {
// (slot as EgretSlot).transformUpdateEnabled = true;
let display = (slot._geometryData ? slot.meshDisplay : slot.rawDisplay) as (egret.Mesh | egret.Bitmap);
if (!slot.display && display === slot.meshDisplay) {
display = slot.rawDisplay;
}
const node = display.$renderNode as (egret.sys.BitmapNode | egret.sys.MeshNode);
// Transform.
if (node.matrix) {
display.$setMatrix(slot.globalTransformMatrix as any, false);
}
// Color.
node.alpha = 1.0;
node.filter = null as any;
// ZOrder.
this.addChild(display);
}
this._batchEnabled = false;
this.$renderNode.cleanBeforeRender = null as any;
this.$renderNode = null as any;
this.armature.invalidUpdate(null, true);
}
/**
* @inheritDoc
*/
public get armature(): Armature {
return this._armature;
}
/**
* @inheritDoc
*/
public get animation(): Animation {
return this._armature.animation;
}
/**
* @inheritDoc
*/
$measureContentBounds(bounds: egret.Rectangle): void {
if (this._batchEnabled && this._armature) {
if (this._childDirty) {
this._childDirty = false;
let isFirst = true;
const helpRectangle = new egret.Rectangle();
for (const slot of this._armature.getSlots()) {
const display = slot.display;
if (!display || !display.$renderNode || !display.$renderNode.image) {
continue;
}
const matrix = (display.$renderNode as (egret.sys.BitmapNode | egret.sys.MeshNode)).matrix;
if (display === slot.meshDisplay) {
const vertices = ((display as egret.Mesh).$renderNode as egret.sys.MeshNode).vertices;
if (vertices && vertices.length > 0) {
helpRectangle.setTo(999999.0, 999999.0, -999999.0, -999999.0);
for (let i = 0, l = vertices.length; i < l; i += 2) {
const x = vertices[i];
const y = vertices[i + 1];
if (helpRectangle.x > x) helpRectangle.x = x;
if (helpRectangle.width < x) helpRectangle.width = x;
if (helpRectangle.y > y) helpRectangle.y = y;
if (helpRectangle.height < y) helpRectangle.height = y;
}
helpRectangle.width -= helpRectangle.x;
helpRectangle.height -= helpRectangle.y;
}
else {
continue;
}
}
else if (slot._displayFrame) {
const textureData = slot._displayFrame.getTextureData();
if (textureData) {
const scale = textureData.parent.scale;
helpRectangle.x = 0;
helpRectangle.y = 0;
helpRectangle.width = textureData.region.width * scale;
helpRectangle.height = textureData.region.height * scale;
}
else {
continue;
}
}
matrix.$transformBounds(helpRectangle);
const left = helpRectangle.x;
const top = helpRectangle.y;
const right = helpRectangle.x + helpRectangle.width;
const bottom = helpRectangle.y + helpRectangle.height;
if (isFirst) {
isFirst = false;
bounds.x = left;
bounds.y = top;
bounds.width = right;
bounds.height = bottom;
}
else {
if (left < bounds.x) {
bounds.x = left;
}
if (top < bounds.y) {
bounds.y = top;
}
if (right > bounds.width) {
bounds.width = right;
}
if (bottom > bounds.height) {
bounds.height = bottom;
}
}
}
bounds.width -= bounds.x;
bounds.height -= bounds.y;
if (isV5) {
if (this._bounds === null) {
this._bounds = new egret.Rectangle();
}
this._bounds.copyFrom(bounds);
}
}
else if (isV5) {
if (this._bounds === null) {
this._bounds = new egret.Rectangle();
}
bounds.copyFrom(this._bounds);
}
return bounds as any; // V5
}
return super.$measureContentBounds(bounds) as any; // V5
}
}
} | the_stack |
import * as vscode from "vscode";
import type { Argument } from ".";
import { firstVisibleLine as apiFirstVisibleLine, lastVisibleLine as apiLastVisibleLine, middleVisibleLine as apiMiddleVisibleLine, column, columns, Context, Direction, Lines, Positions, SelectionBehavior, Selections, Shift, showMenu } from "../api";
import { PerEditorState } from "../state/editors";
import { unsafeSelections } from "../utils/misc";
/**
* Update selections based on their position in the document.
*/
declare module "./select";
/**
* Select whole buffer.
*
* @keys `%` (normal)
*/
export function buffer(_: Context) {
Selections.set([Selections.wholeBuffer()]);
}
interface PreferredColumnsState {
disposable: vscode.Disposable;
expectedSelections: readonly vscode.Selection[];
preferredColumns: number[];
}
const preferredColumnsToken =
PerEditorState.registerState<PreferredColumnsState>(/* isDisposable= */ false);
/**
* Select vertically.
*
* @param avoidEol If `true`, selections will not select the line break
* character but will instead move to the last character.
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | ----------- | ------------- | --------------------------------- | ------------------------------------------------------------ |
* | Jump down | `down.jump` | `j` (normal) , `down` (normal) | `[".select.vertically", { direction: 1, shift: "jump" }]` |
* | Extend down | `down.extend` | `s-j` (normal), `s-down` (normal) | `[".select.vertically", { direction: 1, shift: "extend" }]` |
* | Jump up | `up.jump` | `k` (normal) , `up` (normal) | `[".select.vertically", { direction: -1, shift: "jump" }]` |
* | Extend up | `up.extend` | `s-k` (normal), `s-up` (normal) | `[".select.vertically", { direction: -1, shift: "extend" }]` |
*
* The following keybindings are also defined:
*
* | Keybinding | Command |
* | ------------------------------ | ----------------------------------------------------------- |
* | `c-f` (normal), `c-f` (insert) | `[".select.vertically", { direction: 1, by: "page" }]` |
* | `c-d` (normal), `c-d` (insert) | `[".select.vertically", { direction: 1, by: "halfPage" }]` |
* | `c-b` (normal), `c-b` (insert) | `[".select.vertically", { direction: -1, by: "page" }]` |
* | `c-u` (normal), `c-u` (insert) | `[".select.vertically", { direction: -1, by: "halfPage" }]` |
*/
export function vertically(
_: Context,
selections: readonly vscode.Selection[],
avoidEol: Argument<boolean> = false,
repetitions: number,
direction = Direction.Forward,
shift = Shift.Select,
by?: Argument<"page" | "halfPage">,
) {
// Adjust repetitions if a `by` parameter is given.
if (by !== undefined) {
const visibleRange = _.editor.visibleRanges[0];
if (by === "page") {
repetitions *= visibleRange.end.line - visibleRange.start.line;
} else if (by === "halfPage") {
repetitions *= ((visibleRange.end.line - visibleRange.start.line) / 2) | 0;
}
}
const document = _.document,
isCharacterMode = _.selectionBehavior === SelectionBehavior.Character;
// TODO: test logic with tabs
const activeEnd = (selection: vscode.Selection) => {
const active = selection.active;
if (active === selection.end && Selections.endsWithEntireLine(selection)) {
return columns(active.line - 1, _.editor) + 1;
} else if (active === selection.start && isCharacterMode) {
return column(active.line, active.character, _.editor) + 1;
}
return column(active.line, active.character, _.editor);
};
// Get or create the `PreferredColumnsState` for this editor.
const editorState = _.getState();
let preferredColumnsState = editorState.get(preferredColumnsToken);
if (preferredColumnsState === undefined) {
// That disposable will be automatically disposed of when the selections in
// the editor change due to an action outside of the current command. When
// it is disposed, it will clear the preferred columns for this editor.
const disposable = _.extension
.createAutoDisposable()
.disposeOnEvent(editorState.onEditorWasClosed)
.addDisposable(vscode.window.onDidChangeTextEditorSelection((e) => {
if (editorState.editor !== e.textEditor) {
return;
}
const expectedSelections = preferredColumnsState!.expectedSelections;
if (e.selections.length === expectedSelections.length
&& e.selections.every((sel, i) => sel.isEqual(expectedSelections[i]))) {
return;
}
editorState.store(preferredColumnsToken, undefined);
disposable.dispose();
}));
editorState.store(
preferredColumnsToken,
preferredColumnsState = {
disposable,
expectedSelections: [],
preferredColumns: selections.map((sel) => activeEnd(sel)),
},
);
}
const newSelections = Selections.map.byIndex((i, selection) => {
// TODO: handle tab characters
const activeLine = isCharacterMode ? Selections.activeLine(selection) : selection.active.line,
targetLine = Lines.clamp(activeLine + repetitions * direction, document),
targetLineLength = columns(targetLine, _.editor);
if (targetLineLength === 0) {
let targetPosition = Positions.lineStart(targetLine);
if (isCharacterMode) {
if (shift === Shift.Jump
|| (direction === Direction.Backward
? selection.contains(targetPosition)
: !selection.contains(targetPosition) || targetPosition.isEqual(selection.active))) {
targetPosition = Positions.next(targetPosition, document) ?? targetPosition;
}
if (direction === Direction.Backward && shift === Shift.Extend
&& Selections.isSingleCharacter(selection, document)) {
selection = new vscode.Selection(
Positions.next(selection.anchor, document) ?? selection.anchor, selection.active);
}
}
return Selections.shift(selection, targetPosition, shift);
}
let targetColumn: number;
const preferredColumns = preferredColumnsState!.preferredColumns,
preferredColumn = i < preferredColumns.length
? preferredColumns[i]
: activeEnd(selection);
if (preferredColumn <= targetLineLength) {
targetColumn = preferredColumn;
} else if (isCharacterMode && !avoidEol) {
if (direction === Direction.Forward && targetLine + 1 < document.lineCount) {
if (shift === Shift.Extend) {
const targetPosition = selection.anchor.line <= targetLine
? Positions.lineBreak(targetLine)
: Positions.lineEnd(targetLine);
return Selections.shift(selection, targetPosition, shift);
}
return Selections.shift(selection, new vscode.Position(targetLine + 1, 0), shift);
} else if (direction === Direction.Backward) {
// We may need to shift left in some cases.
if (shift === Shift.Extend && targetLine < selection.anchor.line) {
return Selections.shift(selection, Positions.lineEnd(targetLine), shift);
}
return Selections.shift(selection, Positions.lineBreak(targetLine), shift);
}
targetColumn = targetLineLength;
} else {
targetColumn = targetLineLength;
}
let newPosition = new vscode.Position(
targetLine,
column.character(targetLine, targetColumn, _.editor, /* roundUp= */ isCharacterMode),
);
if (isCharacterMode && shift !== Shift.Jump) {
const edge = shift === Shift.Extend ? selection.anchor : selection.active;
if (newPosition.isBefore(edge)) {
// Selection is going up or down above the cursor: we must account for
// the translation to character mode.
newPosition = Positions.previous(newPosition, document) ?? newPosition;
}
}
return Selections.shift(selection, newPosition, shift);
});
if (_.selectionBehavior === SelectionBehavior.Character) {
// TODO: if line contains tabs, we should shift left by tabSize
Selections.shiftEmptyLeft(newSelections, document);
}
Selections.set(newSelections);
preferredColumnsState.expectedSelections = unsafeSelections(editorState.editor);
}
/**
* Select horizontally.
*
* @param avoidEol If `true`, selections will automatically skip to the next
* line instead of going after the last character. Does not skip empty lines.
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | ------------ | -------------- | ---------------------------------- | -------------------------------------------------------------- |
* | Jump right | `right.jump` | `l` (normal) , `right` (normal) | `[".select.horizontally", { direction: 1, shift: "jump" }]` |
* | Extend right | `right.extend` | `s-l` (normal), `s-right` (normal) | `[".select.horizontally", { direction: 1, shift: "extend" }]` |
* | Jump left | `left.jump` | `h` (normal) , `left` (normal) | `[".select.horizontally", { direction: -1, shift: "jump" }]` |
* | Extend left | `left.extend` | `s-h` (normal), `s-left` (normal) | `[".select.horizontally", { direction: -1, shift: "extend" }]` |
*/
export function horizontally(
_: Context,
avoidEol: Argument<boolean> = false,
repetitions: number,
direction = Direction.Forward,
shift = Shift.Select,
) {
const mayNeedAdjustment = direction === Direction.Backward
&& _.selectionBehavior === SelectionBehavior.Character;
const newSelections = Selections.map.byIndex((_i, selection, document) => {
let active = selection.active === selection.start
? Selections.activeStart(selection, _)
: Selections.activeEnd(selection, _);
if (mayNeedAdjustment) {
if (shift === Shift.Extend && Selections.isSingleCharacter(selection)) {
active = selection.start;
} else if (shift === Shift.Jump && selection.active === selection.start) {
active = Positions.next(active, _.document) ?? active;
}
}
let target = Positions.offset(active, direction * repetitions, document) ?? active;
if (avoidEol) {
switch (_.selectionBehavior) {
case SelectionBehavior.Caret:
if (target.character === Lines.length(target.line, document) && target.character > 0) {
target = Positions.offset(target, direction, document) ?? target;
}
break;
case SelectionBehavior.Character:
if (target.character === 0
&& (direction === Direction.Forward || target.line === 0
|| !Lines.isEmpty(target.line - 1, document))) {
target = Positions.offset(target, direction, document) ?? target;
}
break;
}
}
return Selections.shift(selection, target, shift);
});
if (_.selectionBehavior === SelectionBehavior.Character) {
Selections.shiftEmptyLeft(newSelections, _.document);
}
Selections.set(newSelections);
}
/**
* Select to.
*
* If a count is specified, this command will shift to the start of the given
* line. If no count is specified, this command will shift open the `goto` menu.
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | --------- | ----------- | -------------- | ------------------------------------- |
* | Go to | `to.jump` | `g` (normal) | `[".select.to", { shift: "jump" }]` |
* | Extend to | `to.extend` | `s-g` (normal) | `[".select.to", { shift: "extend" }]` |
*/
export function to(
_: Context,
count: number,
argument: object,
shift = Shift.Select,
) {
if (count === 0) {
// TODO: Make just merely opening the menu not count as a command execution
// and do not record it.
return showMenu.byName("goto", [argument]);
}
return lineStart(_, count, shift);
}
/**
* Select line below.
*
* @keys `x` (normal)
*/
export function line_below(_: Context, count: number) {
if (count === 0 || count === 1) {
Selections.update.byIndex((_, selection) => {
let line = Selections.activeLine(selection);
if (Selections.isEntireLines(selection) && !selection.isReversed) {
line++;
}
return new vscode.Selection(line, 0, line + 1, 0);
});
} else {
Selections.update.byIndex((_, selection, document) => {
const lastLine = document.lineCount - 1;
let line = Math.min(Selections.activeLine(selection) + count - 1, lastLine);
if (Selections.isEntireLines(selection) && line < lastLine) {
line++;
}
return new vscode.Selection(line, 0, line + 1, 0);
});
}
}
/**
* Extend to line below.
*
* @keys `s-x` (normal)
*/
export function line_below_extend(_: Context, count: number) {
if (count === 0 || count === 1) {
Selections.update.byIndex((_, selection, document) => {
const isFullLine = Selections.endsWithEntireLine(selection),
isSameLine = Selections.isSingleLine(selection),
isFullLineDiff = isFullLine && !(isSameLine && selection.isReversed) ? 1 : 0,
activeLine = Selections.activeLine(selection);
const anchor = isSameLine ? Positions.lineStart(activeLine) : selection.anchor,
active = Positions.lineBreak(activeLine + isFullLineDiff, document);
return new vscode.Selection(anchor, active);
});
} else {
Selections.update.byIndex((_, selection, document) => {
const activeLine = Selections.activeLine(selection),
line = Math.min(activeLine + count - 1, document.lineCount - 1),
isSameLine = Selections.isSingleLine(selection);
const anchor = isSameLine ? Positions.lineStart(activeLine) : selection.anchor,
active = Positions.lineBreak(line, document);
return new vscode.Selection(anchor, active);
});
}
}
/**
* Select line above.
*/
export function line_above(_: Context, count: number) {
if (count === 0 || count === 1) {
Selections.update.byIndex((_, selection) => {
let line = Selections.activeLine(selection);
if (!Selections.isEntireLines(selection)) {
line++;
}
return new vscode.Selection(line, 0, line - 1, 0);
});
} else {
Selections.update.byIndex((_, selection) => {
let line = Math.max(Selections.activeLine(selection) - count + 1, 0);
if (!Selections.isEntireLines(selection)) {
line++;
}
return new vscode.Selection(line, 0, line - 1, 0);
});
}
}
/**
* Extend to line above.
*/
export function line_above_extend(_: Context, count: number) {
if (count === 0 || count === 1) {
Selections.update.byIndex((_, selection) => {
if (selection.isSingleLine) {
let line = Selections.activeLine(selection);
if (!Selections.isEntireLines(selection)) {
line++;
}
return new vscode.Selection(line, 0, line - 1, 0);
}
if (selection.active === selection.end && Selections.isEntireLine(selection)) {
const line = Selections.activeLine(selection);
return new vscode.Selection(line + 1, 0, line - 1, 0);
}
const isFullLine = Selections.activeLineIsFullySelected(selection),
isFullLineDiff = isFullLine ? -1 : 0,
active = new vscode.Position(Selections.activeLine(selection) + isFullLineDiff, 0);
return new vscode.Selection(selection.anchor, active);
});
} else {
Selections.update.byIndex((_, selection, document) => {
let line = Math.max(Selections.activeLine(selection) - count, 0),
anchor = selection.anchor;
if (selection.active === selection.end) {
anchor = selection.active;
}
if (selection.isSingleLine) {
anchor = Positions.lineBreak(selection.anchor.line, document);
line++;
} else if (!Selections.startsWithEntireLine(selection)) {
line++;
}
return new vscode.Selection(anchor, new vscode.Position(line, 0));
});
}
}
/**
* Select to line start.
*
* @keys `a-h` (normal), `home` (normal)
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | -------------------- | ------------------ | ----------------------------------- | ------------------------------------------------------------- |
* | Jump to line start | `lineStart.jump` | | `[".select.lineStart", { shift: "jump" }]` |
* | Extend to line start | `lineStart.extend` | `s-a-h` (normal), `s-home` (normal) | `[".select.lineStart", { shift: "extend" }]` |
* | Jump to line start (skip blank) | `lineStart.skipBlank.jump` | | `[".select.lineStart", { skipBlank: true, shift: "jump" }]` |
* | Extend to line start (skip blank) | `lineStart.skipBlank.extend` | | `[".select.lineStart", { skipBlank: true, shift: "extend" }]` |
* | Jump to first line | `firstLine.jump` | | `[".select.lineStart", { count: 0, shift: "jump" }]` |
* | Extend to first line | `firstLine.extend` | | `[".select.lineStart", { count: 0, shift: "extend" }]` |
*/
export function lineStart(
_: Context,
count: number,
shift = Shift.Select,
skipBlank = false,
) {
if (count > 0) {
const selection = _.selections[0],
newLine = Math.min(_.document.lineCount, count) - 1,
newPosition = skipBlank
? Positions.nonBlankLineStart(newLine, _.document)
: Positions.lineStart(newLine),
newSelection = Selections.shift(selection, newPosition, shift);
Selections.set([newSelection]);
return;
}
Selections.update.byIndex((_, selection) =>
Selections.shift(
selection,
skipBlank
? Positions.nonBlankLineStart(Selections.activeLine(selection))
: Positions.lineStart(Selections.activeLine(selection)),
shift,
),
);
}
/**
* Select to line end.
*
* @param lineBreak If `true`, selects the line break in character selection
* mode.
*
* @keys `a-l` (normal), `end` (normal)
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | ------------------------ | -------------------- | ---------------------------------- | ---------------------------------------------------------- |
* | Extend to line end | `lineEnd.extend` | `s-a-l` (normal), `s-end` (normal) | `[".select.lineEnd", { shift: "extend" }]` |
* | Jump to last character | `documentEnd.jump` | | `[".select.lineEnd", { count: MAX_INT, shift: "jump" }]` |
* | Extend to last character | `documentEnd.extend` | | `[".select.lineEnd", { count: MAX_INT, shift: "extend" }]` |
*/
export function lineEnd(
_: Context,
count: number,
shift = Shift.Select,
lineBreak = false,
) {
const mapSelection = (selection: vscode.Selection, newLine: number) => {
const newActive = Positions.lineEnd(newLine);
if (_.selectionBehavior === SelectionBehavior.Character && shift === Shift.Jump) {
if (lineBreak) {
return Selections.from(newActive, Positions.next(newActive, _.document) ?? newActive);
} else {
return Selections.from(Positions.previous(newActive, _.document) ?? newActive, newActive);
}
}
return Selections.shift(selection, newActive, shift);
};
if (count > 0) {
const newLine = Math.min(_.document.lineCount, count) - 1;
Selections.set([mapSelection(_.mainSelection, newLine)]);
return;
}
Selections.update.byIndex((_, selection) =>
mapSelection(selection, Selections.activeLine(selection)),
);
}
/**
* Select to last line.
*
* #### Variants
*
* | Title | Identifier | Command |
* | ------------------- | ----------------- | ------------------------------------------- |
* | Jump to last line | `lastLine.jump` | `[".select.lastLine", { shift: "jump" }]` |
* | Extend to last line | `lastLine.extend` | `[".select.lastLine", { shift: "extend" }]` |
*/
export function lastLine(_: Context, document: vscode.TextDocument, shift = Shift.Select) {
let line = document.lineCount - 1;
// In case of trailing line break, go to the second last line.
if (line > 0 && document.lineAt(line).text.length === 0) {
line--;
}
Selections.set([Selections.shift(_.mainSelection, Positions.lineStart(line), shift)]);
}
/**
* Select to first visible line.
*
* #### Variants
*
* | Title | Identifier | Command |
* | ---------------------------- | ------------------------- | --------------------------------------------------- |
* | Jump to first visible line | `firstVisibleLine.jump` | `[".select.firstVisibleLine", { shift: "jump" }]` |
* | Extend to first visible line | `firstVisibleLine.extend` | `[".select.firstVisibleLine", { shift: "extend" }]` |
*/
export function firstVisibleLine(_: Context, shift = Shift.Select) {
const selection = _.mainSelection,
toPosition = Positions.lineStart(apiFirstVisibleLine(_.editor));
Selections.set([Selections.shift(selection, toPosition, shift)]);
}
/**
* Select to middle visible line.
*
* #### Variants
*
* | Title | Identifier | Command |
* | ----------------------------- | -------------------------- | ---------------------------------------------------- |
* | Jump to middle visible line | `middleVisibleLine.jump` | `[".select.middleVisibleLine", { shift: "jump" }]` |
* | Extend to middle visible line | `middleVisibleLine.extend` | `[".select.middleVisibleLine", { shift: "extend" }]` |
*/
export function middleVisibleLine(_: Context, shift = Shift.Select) {
const selection = _.mainSelection,
toPosition = Positions.lineStart(apiMiddleVisibleLine(_.editor));
Selections.set([Selections.shift(selection, toPosition, shift)]);
}
/**
* Select to last visible line.
*
* #### Variants
*
* | Title | Identifier | Command |
* | --------------------------- | ------------------------ | -------------------------------------------------- |
* | Jump to last visible line | `lastVisibleLine.jump` | `[".select.lastVisibleLine", { shift: "jump" }]` |
* | Extend to last visible line | `lastVisibleLine.extend` | `[".select.lastVisibleLine", { shift: "extend" }]` |
*/
export function lastVisibleLine(_: Context, shift = Shift.Select) {
const selection = _.mainSelection,
toPosition = Positions.lineStart(apiLastVisibleLine(_.editor));
Selections.set([Selections.shift(selection, toPosition, shift)]);
} | the_stack |
import {SvgFactory} from "../../svgFactory";
import {GridOptionsWrapper} from "../../gridOptionsWrapper";
import {ExpressionService} from "../../expressionService";
import {EventService} from "../../eventService";
import {Constants} from "../../constants";
import {Utils as _} from "../../utils";
import {Events} from "../../events";
import {Autowired, Context} from "../../context/context";
import {Component} from "../../widgets/component";
import {ICellRenderer} from "./iCellRenderer";
import {RowNode} from "../../entities/rowNode";
import {GridApi} from "../../gridApi";
import {CellRendererService} from "../cellRendererService";
import {ValueFormatterService} from "../valueFormatterService";
import {CheckboxSelectionComponent} from "../checkboxSelectionComponent";
import {ColumnController} from "../../columnController/columnController";
var svgFactory = SvgFactory.getInstance();
export class GroupCellRenderer extends Component implements ICellRenderer {
private static TEMPLATE =
'<span>' +
'<span class="ag-group-expanded"></span>' +
'<span class="ag-group-contracted"></span>' +
'<span class="ag-group-checkbox"></span>' +
'<span class="ag-group-value"></span>' +
'<span class="ag-group-child-count"></span>' +
'</span>';
@Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
@Autowired('expressionService') private expressionService: ExpressionService;
@Autowired('eventService') private eventService: EventService;
@Autowired('cellRendererService') private cellRendererService: CellRendererService;
@Autowired('valueFormatterService') private valueFormatterService: ValueFormatterService;
@Autowired('context') private context: Context;
@Autowired('columnController') private columnController: ColumnController;
private eExpanded: HTMLElement;
private eContracted: HTMLElement;
private eCheckbox: HTMLElement;
private eValue: HTMLElement;
private eChildCount: HTMLElement;
private rowNode: RowNode;
private rowIndex: number;
private gridApi: GridApi;
constructor() {
super(GroupCellRenderer.TEMPLATE);
this.eExpanded = this.queryForHtmlElement('.ag-group-expanded');
this.eContracted = this.queryForHtmlElement('.ag-group-contracted');
this.eCheckbox = this.queryForHtmlElement('.ag-group-checkbox');
this.eValue = this.queryForHtmlElement('.ag-group-value');
this.eChildCount = this.queryForHtmlElement('.ag-group-child-count');
}
public init(params: any): void {
this.rowNode = params.node;
this.rowIndex = params.rowIndex;
this.gridApi = params.api;
this.addExpandAndContract(params.eGridCell);
this.addCheckboxIfNeeded(params);
this.addValueElement(params);
this.addPadding(params);
}
private addPadding(params: any): void {
// only do this if an indent - as this overwrites the padding that
// the theme set, which will make things look 'not aligned' for the
// first group level.
var node = this.rowNode;
var suppressPadding = params.suppressPadding;
if (!suppressPadding && (node.footer || node.level > 0)) {
var paddingFactor: any;
if (params.colDef && params.padding >= 0) {
paddingFactor = params.padding;
} else {
paddingFactor = 10;
}
var paddingPx = node.level * paddingFactor;
var reducedLeafNode = this.columnController.isPivotMode() && this.rowNode.leafGroup;
if (node.footer) {
paddingPx += 15;
} else if (!node.isExpandable() || reducedLeafNode) {
paddingPx += 10;
}
this.getGui().style.paddingLeft = paddingPx + 'px';
}
}
private addValueElement(params: any): void {
if (params.innerRenderer) {
this.createFromInnerRenderer(params);
} else if (this.rowNode.footer) {
this.createFooterCell(params);
} else if (this.rowNode.group) {
this.createGroupCell(params);
this.addChildCount(params);
} else {
this.createLeafCell(params);
}
}
private createFromInnerRenderer(params: any): void {
this.cellRendererService.useCellRenderer(params.innerRenderer, this.eValue, params);
}
private createFooterCell(params: any): void {
var footerValue: string;
var groupName = this.getGroupName(params);
if (params.footerValueGetter) {
var footerValueGetter = params.footerValueGetter;
// params is same as we were given, except we set the value as the item to display
var paramsClone: any = _.cloneObject(params);
paramsClone.value = groupName;
if (typeof footerValueGetter === 'function') {
footerValue = footerValueGetter(paramsClone);
} else if (typeof footerValueGetter === 'string') {
footerValue = this.expressionService.evaluate(footerValueGetter, paramsClone);
} else {
console.warn('ag-Grid: footerValueGetter should be either a function or a string (expression)');
}
} else {
footerValue = 'Total ' + groupName;
}
this.eValue.innerHTML = footerValue;
}
private createGroupCell(params: any): void {
// pull out the column that the grouping is on
var rowGroupColumns = params.columnApi.getRowGroupColumns();
// if we are using in memory grid grouping, then we try to look up the column that
// we did the grouping on. however if it is not possible (happens when user provides
// the data already grouped) then we just the current col, ie use cellrenderer of current col
var columnOfGroupedCol = rowGroupColumns[params.node.level];
if (_.missing(columnOfGroupedCol)) {
columnOfGroupedCol = params.column;
}
var colDefOfGroupedCol = columnOfGroupedCol.getColDef();
var groupName = this.getGroupName(params);
var valueFormatted = this.valueFormatterService.formatValue(columnOfGroupedCol, params.node, params.scope, this.rowIndex, groupName);
// reuse the params but change the value
if (colDefOfGroupedCol && typeof colDefOfGroupedCol.cellRenderer === 'function') {
// reuse the params but change the value
params.value = groupName;
params.valueFormatted = valueFormatted;
// because we are talking about the different column to the original, any user provided params
// are for the wrong column, so need to copy them in again.
if (colDefOfGroupedCol.cellRendererParams) {
_.assign(params, colDefOfGroupedCol.cellRendererParams);
}
this.cellRendererService.useCellRenderer(colDefOfGroupedCol.cellRenderer, this.eValue, params);
} else {
var valueToRender = _.exists(valueFormatted) ? valueFormatted : groupName;
if (_.exists(valueToRender) && valueToRender !== '') {
this.eValue.appendChild(document.createTextNode(valueToRender));
}
}
}
private addChildCount(params: any): void {
// only include the child count if it's included, eg if user doing custom aggregation,
// then this could be left out, or set to -1, ie no child count
var suppressCount = params.suppressCount;
if (!suppressCount && params.node.allChildrenCount >= 0) {
this.eChildCount.innerHTML = "(" + params.node.allChildrenCount + ")";
}
}
private getGroupName(params: any): string {
if (params.keyMap && typeof params.keyMap === 'object') {
var valueFromMap = params.keyMap[params.node.key];
if (valueFromMap) {
return valueFromMap;
} else {
return params.node.key;
}
} else {
return params.node.key;
}
}
private createLeafCell(params: any): void {
if (_.exists(params.value)) {
this.eValue.innerHTML = params.value;
}
}
private isUserWantsSelected(params: any): boolean {
if (typeof params.checkbox === 'function') {
return params.checkbox(params);
} else {
return params.checkbox === true;
}
}
private addCheckboxIfNeeded(params: any): void {
var checkboxNeeded = this.isUserWantsSelected(params)
// footers cannot be selected
&& !this.rowNode.footer
// floating rows cannot be selected
&& !this.rowNode.floating
// flowers cannot be selected
&& !this.rowNode.flower;
if (checkboxNeeded) {
var cbSelectionComponent = new CheckboxSelectionComponent();
this.context.wireBean(cbSelectionComponent);
cbSelectionComponent.init({rowNode: this.rowNode});
this.eCheckbox.appendChild(cbSelectionComponent.getGui());
this.addDestroyFunc( ()=> cbSelectionComponent.destroy() );
}
}
private addExpandAndContract(eGroupCell: HTMLElement): void {
var eExpandedIcon = _.createIconNoSpan('groupExpanded', this.gridOptionsWrapper, null, svgFactory.createGroupContractedIcon);
var eContractedIcon = _.createIconNoSpan('groupContracted', this.gridOptionsWrapper, null, svgFactory.createGroupExpandedIcon);
this.eExpanded.appendChild(eExpandedIcon);
this.eContracted.appendChild(eContractedIcon);
this.addDestroyableEventListener(this.eExpanded, 'click', this.onExpandOrContract.bind(this));
this.addDestroyableEventListener(this.eContracted, 'click', this.onExpandOrContract.bind(this));
this.addDestroyableEventListener(eGroupCell, 'dblclick', this.onExpandOrContract.bind(this));
// expand / contract as the user hits enter
this.addDestroyableEventListener(eGroupCell, 'keydown', this.onKeyDown.bind(this));
this.showExpandAndContractIcons();
}
private onKeyDown(event: KeyboardEvent): void {
if (_.isKeyPressed(event, Constants.KEY_ENTER)) {
this.onExpandOrContract();
event.preventDefault();
}
}
public onExpandOrContract(): void {
this.rowNode.expanded = !this.rowNode.expanded;
var refreshIndex = this.getRefreshFromIndex();
this.gridApi.onGroupExpandedOrCollapsed(refreshIndex);
this.showExpandAndContractIcons();
var event: any = {node: this.rowNode};
this.eventService.dispatchEvent(Events.EVENT_ROW_GROUP_OPENED, event)
}
private showExpandAndContractIcons(): void {
var reducedLeafNode = this.columnController.isPivotMode() && this.rowNode.leafGroup;
var expandable = this.rowNode.isExpandable() && !this.rowNode.footer && !reducedLeafNode;
if (expandable) {
// if expandable, show one based on expand state
_.setVisible(this.eExpanded, this.rowNode.expanded);
_.setVisible(this.eContracted, !this.rowNode.expanded);
} else {
// it not expandable, show neither
_.setVisible(this.eExpanded, false);
_.setVisible(this.eContracted, false);
}
}
// if we are showing footers, then opening / closing the group also changes the group
// row, as the 'summaries' move to and from the header and footer. if not using footers,
// then we only need to refresh from this row down.
private getRefreshFromIndex(): number {
if (this.gridOptionsWrapper.isGroupIncludeFooter()) {
return this.rowIndex;
} else {
return this.rowIndex + 1;
}
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [forecast](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonforecast.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Forecast extends PolicyStatement {
public servicePrefix = 'forecast';
/**
* Statement provider for service [forecast](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonforecast.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to create a dataset
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreateDataset.html
*/
public toCreateDataset() {
return this.to('CreateDataset');
}
/**
* Grants permission to create a dataset group
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreateDatasetGroup.html
*/
public toCreateDatasetGroup() {
return this.to('CreateDatasetGroup');
}
/**
* Grants permission to create a dataset import job
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreateDatasetImportJob.html
*/
public toCreateDatasetImportJob() {
return this.to('CreateDatasetImportJob');
}
/**
* Grants permission to create a forecast
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreateForecast.html
*/
public toCreateForecast() {
return this.to('CreateForecast');
}
/**
* Grants permission to create a forecast export job using a forecast resource
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreateForecastExportJob.html
*/
public toCreateForecastExportJob() {
return this.to('CreateForecastExportJob');
}
/**
* Grants permission to create a predictor
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreatePredictor.html
*/
public toCreatePredictor() {
return this.to('CreatePredictor');
}
/**
* Grants permission to create a predictor backtest export job using a predictor
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreatePredictorBacktestExportJob.html
*/
public toCreatePredictorBacktestExportJob() {
return this.to('CreatePredictorBacktestExportJob');
}
/**
* Grants permission to delete a dataset
*
* Access Level: Write
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DeleteDataset.html
*/
public toDeleteDataset() {
return this.to('DeleteDataset');
}
/**
* Grants permission to delete a dataset group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DeleteDatasetGroup.html
*/
public toDeleteDatasetGroup() {
return this.to('DeleteDatasetGroup');
}
/**
* Grants permission to delete a dataset import job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DeleteDatasetImportJob.html
*/
public toDeleteDatasetImportJob() {
return this.to('DeleteDatasetImportJob');
}
/**
* Grants permission to delete a forecast
*
* Access Level: Write
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DeleteForecast.html
*/
public toDeleteForecast() {
return this.to('DeleteForecast');
}
/**
* Grants permission to delete a forecast export job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DeleteForecastExportJob.html
*/
public toDeleteForecastExportJob() {
return this.to('DeleteForecastExportJob');
}
/**
* Grants permission to delete a predictor
*
* Access Level: Write
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DeletePredictor.html
*/
public toDeletePredictor() {
return this.to('DeletePredictor');
}
/**
* Grants permission to delete a predictor backtest export job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DeletePredictorBacktestExportJob.html
*/
public toDeletePredictorBacktestExportJob() {
return this.to('DeletePredictorBacktestExportJob');
}
/**
* Grants permission to delete a resource and its child resources
*
* Access Level: Write
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DeleteResourceTree.html
*/
public toDeleteResourceTree() {
return this.to('DeleteResourceTree');
}
/**
* Grants permission to describe a dataset
*
* Access Level: Read
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DescribeDataset.html
*/
public toDescribeDataset() {
return this.to('DescribeDataset');
}
/**
* Grants permission to describe a dataset group
*
* Access Level: Read
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DescribeDatasetGroup.html
*/
public toDescribeDatasetGroup() {
return this.to('DescribeDatasetGroup');
}
/**
* Grants permission to describe a dataset import job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DescribeDatasetImportJob.html
*/
public toDescribeDatasetImportJob() {
return this.to('DescribeDatasetImportJob');
}
/**
* Grants permission to describe a forecast
*
* Access Level: Read
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DescribeForecast.html
*/
public toDescribeForecast() {
return this.to('DescribeForecast');
}
/**
* Grants permission to describe a forecast export job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DescribeForecastExportJob.html
*/
public toDescribeForecastExportJob() {
return this.to('DescribeForecastExportJob');
}
/**
* Grants permission to describe a predictor
*
* Access Level: Read
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DescribePredictor.html
*/
public toDescribePredictor() {
return this.to('DescribePredictor');
}
/**
* Grants permission to describe a predictor backtest export job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_DescribePredictorBacktestExportJob.html
*/
public toDescribePredictorBacktestExportJob() {
return this.to('DescribePredictorBacktestExportJob');
}
/**
* Grants permission to get the Accuracy Metrics for a predictor
*
* Access Level: Read
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_GetAccuracyMetrics.html
*/
public toGetAccuracyMetrics() {
return this.to('GetAccuracyMetrics');
}
/**
* Grants permission to list all the dataset groups
*
* Access Level: List
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_ListDatasetGroups.html
*/
public toListDatasetGroups() {
return this.to('ListDatasetGroups');
}
/**
* Grants permission to list all the dataset import jobs
*
* Access Level: List
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_ListDatasetImportJobs.html
*/
public toListDatasetImportJobs() {
return this.to('ListDatasetImportJobs');
}
/**
* Grants permission to list all the datasets
*
* Access Level: List
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_ListDatasets.html
*/
public toListDatasets() {
return this.to('ListDatasets');
}
/**
* Grants permission to list all the forecast export jobs
*
* Access Level: List
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_ListForecastExportJobs.html
*/
public toListForecastExportJobs() {
return this.to('ListForecastExportJobs');
}
/**
* Grants permission to list all the forecasts
*
* Access Level: List
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_ListForecasts.html
*/
public toListForecasts() {
return this.to('ListForecasts');
}
/**
* Grants permission to list all the predictor backtest export jobs
*
* Access Level: List
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_ListPredictorBacktestExportJobs.html
*/
public toListPredictorBacktestExportJobs() {
return this.to('ListPredictorBacktestExportJobs');
}
/**
* Grants permission to list all the predictors
*
* Access Level: List
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_ListPredictors.html
*/
public toListPredictors() {
return this.to('ListPredictors');
}
/**
* Grants permission to list the tags for an Amazon Forecast resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to retrieve a forecast for a single item
*
* Access Level: Read
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_forecastquery_QueryForecast.html
*/
public toQueryForecast() {
return this.to('QueryForecast');
}
/**
* Grants permission to stop Amazon Forecast resource jobs
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_StopResource.html
*/
public toStopResource() {
return this.to('StopResource');
}
/**
* Grants permission to associate the specified tags to a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to delete the specified tags for a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update a dataset group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_UpdateDatasetGroup.html
*/
public toUpdateDatasetGroup() {
return this.to('UpdateDatasetGroup');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CreateDataset",
"CreateDatasetGroup",
"CreateDatasetImportJob",
"CreateForecast",
"CreateForecastExportJob",
"CreatePredictor",
"CreatePredictorBacktestExportJob",
"DeleteDataset",
"DeleteDatasetGroup",
"DeleteDatasetImportJob",
"DeleteForecast",
"DeleteForecastExportJob",
"DeletePredictor",
"DeletePredictorBacktestExportJob",
"DeleteResourceTree",
"StopResource",
"UpdateDatasetGroup"
],
"Read": [
"DescribeDataset",
"DescribeDatasetGroup",
"DescribeDatasetImportJob",
"DescribeForecast",
"DescribeForecastExportJob",
"DescribePredictor",
"DescribePredictorBacktestExportJob",
"GetAccuracyMetrics",
"ListTagsForResource",
"QueryForecast"
],
"List": [
"ListDatasetGroups",
"ListDatasetImportJobs",
"ListDatasets",
"ListForecastExportJobs",
"ListForecasts",
"ListPredictorBacktestExportJobs",
"ListPredictors"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type dataset to the statement
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreateDataset.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDataset(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:forecast:${Region}:${Account}:dataset/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type datasetGroup to the statement
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreateDatasetGroup.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDatasetGroup(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:forecast:${Region}:${Account}:dataset-group/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type datasetImportJob to the statement
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreateDatasetImportJob.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDatasetImportJob(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:forecast:${Region}:${Account}:dataset-import-job/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type algorithm to the statement
*
* https://docs.aws.amazon.com/forecast/latest/dg/aws-forecast-choosing-recipes.html
*
* @param resourceId - Identifier for the resourceId.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onAlgorithm(resourceId: string, partition?: string) {
var arn = 'arn:${Partition}:forecast:::algorithm/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type predictor to the statement
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreatePredictor.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onPredictor(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:forecast:${Region}:${Account}:predictor/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type predictorBacktestExportJob to the statement
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreatePredictorBacktestExportJob.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onPredictorBacktestExportJob(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:forecast:${Region}:${Account}:predictor-backtest-export-job/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type forecast to the statement
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreateForecast.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onForecast(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:forecast:${Region}:${Account}:forecast/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type forecastExport to the statement
*
* https://docs.aws.amazon.com/forecast/latest/dg/API_CreateForecastExportJob.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onForecastExport(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:forecast:${Region}:${Account}:forecast-export-job/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import { createStore, compose, Reducer, Store, Action } from 'redux';
import instrument, {
ActionCreators,
EnhancedStore,
LiftedStore,
LiftedState,
} from '../src/instrument';
import { from, Observable } from 'rxjs';
import _ from 'lodash';
type CounterAction = { type: 'INCREMENT' } | { type: 'DECREMENT' };
function counter(state = 0, action: CounterAction) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
type CounterWithBugAction =
| { type: 'INCREMENT' }
| { type: 'DECREMENT' }
| { type: 'SET_UNDEFINED' };
function counterWithBug(state = 0, action: CounterWithBugAction) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return mistake - 1;
case 'SET_UNDEFINED':
return undefined as unknown as number;
default:
return state;
}
}
type CounterWithAnotherBugAction =
| { type: 'INCREMENT' }
| { type: 'DECREMENT' }
| { type: 'SET_UNDEFINED' };
function counterWithAnotherBug(state = 0, action: CounterWithBugAction) {
switch (action.type) {
case 'INCREMENT':
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return (mistake as unknown as number) + 1;
case 'DECREMENT':
return state - 1;
case 'SET_UNDEFINED':
return undefined;
default:
return state;
}
}
type DoubleCounterAction = { type: 'INCREMENT' } | { type: 'DECREMENT' };
function doubleCounter(state = 0, action: DoubleCounterAction) {
switch (action.type) {
case 'INCREMENT':
return state + 2;
case 'DECREMENT':
return state - 2;
default:
return state;
}
}
type CounterWithMultiplyAction =
| { type: 'INCREMENT' }
| { type: 'DECREMENT' }
| { type: 'MULTIPLY' };
function counterWithMultiply(state = 0, action: CounterWithMultiplyAction) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
case 'MULTIPLY':
return state * 2;
default:
return state;
}
}
describe('instrument', () => {
let store: EnhancedStore<number, CounterAction, null>;
let liftedStore: LiftedStore<number, CounterAction, null>;
beforeEach(() => {
store = createStore(counter, instrument());
liftedStore = store.liftedStore;
});
it('should perform actions', () => {
expect(store.getState()).toBe(0);
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(1);
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(2);
});
it('should provide observable', () => {
let lastValue;
// let calls = 0;
from(store as unknown as Observable<number>).subscribe((state) => {
lastValue = state;
// calls++;
});
expect(lastValue).toBe(0);
store.dispatch({ type: 'INCREMENT' });
expect(lastValue).toBe(1);
});
it('should rollback state to the last committed state', () => {
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(2);
liftedStore.dispatch(ActionCreators.commit());
expect(store.getState()).toBe(2);
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(4);
liftedStore.dispatch(ActionCreators.rollback());
expect(store.getState()).toBe(2);
store.dispatch({ type: 'DECREMENT' });
expect(store.getState()).toBe(1);
liftedStore.dispatch(ActionCreators.rollback());
expect(store.getState()).toBe(2);
});
it('should reset to initial state', () => {
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(1);
liftedStore.dispatch(ActionCreators.commit());
expect(store.getState()).toBe(1);
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(2);
liftedStore.dispatch(ActionCreators.rollback());
expect(store.getState()).toBe(1);
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(2);
liftedStore.dispatch(ActionCreators.reset());
expect(store.getState()).toBe(0);
});
it('should toggle an action', () => {
// actionId 0 = @@INIT
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(1);
liftedStore.dispatch(ActionCreators.toggleAction(2));
expect(store.getState()).toBe(2);
liftedStore.dispatch(ActionCreators.toggleAction(2));
expect(store.getState()).toBe(1);
});
it('should set multiple action skip', () => {
// actionId 0 = @@INIT
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(3);
liftedStore.dispatch(ActionCreators.setActionsActive(1, 3, false));
expect(store.getState()).toBe(1);
liftedStore.dispatch(ActionCreators.setActionsActive(0, 2, true));
expect(store.getState()).toBe(2);
liftedStore.dispatch(ActionCreators.setActionsActive(0, 1, true));
expect(store.getState()).toBe(2);
});
it('should sweep disabled actions', () => {
// actionId 0 = @@INIT
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(2);
expect(liftedStore.getState().stagedActionIds).toEqual([0, 1, 2, 3, 4]);
expect(liftedStore.getState().skippedActionIds).toEqual([]);
liftedStore.dispatch(ActionCreators.toggleAction(2));
expect(store.getState()).toBe(3);
expect(liftedStore.getState().stagedActionIds).toEqual([0, 1, 2, 3, 4]);
expect(liftedStore.getState().skippedActionIds).toEqual([2]);
liftedStore.dispatch(ActionCreators.sweep());
expect(store.getState()).toBe(3);
expect(liftedStore.getState().stagedActionIds).toEqual([0, 1, 3, 4]);
expect(liftedStore.getState().skippedActionIds).toEqual([]);
});
it('should jump to state', () => {
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(1);
liftedStore.dispatch(ActionCreators.jumpToState(0));
expect(store.getState()).toBe(0);
liftedStore.dispatch(ActionCreators.jumpToState(1));
expect(store.getState()).toBe(1);
liftedStore.dispatch(ActionCreators.jumpToState(2));
expect(store.getState()).toBe(0);
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(0);
liftedStore.dispatch(ActionCreators.jumpToState(4));
expect(store.getState()).toBe(2);
});
it('should jump to action', () => {
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(1);
liftedStore.dispatch(ActionCreators.jumpToAction(0));
expect(store.getState()).toBe(0);
liftedStore.dispatch(ActionCreators.jumpToAction(1));
expect(store.getState()).toBe(1);
liftedStore.dispatch(ActionCreators.jumpToAction(10));
expect(store.getState()).toBe(1);
});
it('should reorder actions', () => {
const storeWithMultiply = createStore(counterWithMultiply, instrument());
storeWithMultiply.dispatch({ type: 'INCREMENT' });
storeWithMultiply.dispatch({ type: 'DECREMENT' });
storeWithMultiply.dispatch({ type: 'INCREMENT' });
storeWithMultiply.dispatch({ type: 'MULTIPLY' });
expect(storeWithMultiply.liftedStore.getState().stagedActionIds).toEqual([
0, 1, 2, 3, 4,
]);
expect(storeWithMultiply.getState()).toBe(2);
storeWithMultiply.liftedStore.dispatch(ActionCreators.reorderAction(4, 1));
expect(storeWithMultiply.liftedStore.getState().stagedActionIds).toEqual([
0, 4, 1, 2, 3,
]);
expect(storeWithMultiply.getState()).toBe(1);
storeWithMultiply.liftedStore.dispatch(ActionCreators.reorderAction(4, 1));
expect(storeWithMultiply.liftedStore.getState().stagedActionIds).toEqual([
0, 4, 1, 2, 3,
]);
expect(storeWithMultiply.getState()).toBe(1);
storeWithMultiply.liftedStore.dispatch(ActionCreators.reorderAction(4, 2));
expect(storeWithMultiply.liftedStore.getState().stagedActionIds).toEqual([
0, 1, 4, 2, 3,
]);
expect(storeWithMultiply.getState()).toBe(2);
storeWithMultiply.liftedStore.dispatch(ActionCreators.reorderAction(1, 10));
expect(storeWithMultiply.liftedStore.getState().stagedActionIds).toEqual([
0, 4, 2, 3, 1,
]);
expect(storeWithMultiply.getState()).toBe(1);
storeWithMultiply.liftedStore.dispatch(ActionCreators.reorderAction(10, 1));
expect(storeWithMultiply.liftedStore.getState().stagedActionIds).toEqual([
0, 4, 2, 3, 1,
]);
expect(storeWithMultiply.getState()).toBe(1);
storeWithMultiply.liftedStore.dispatch(ActionCreators.reorderAction(1, -2));
expect(storeWithMultiply.liftedStore.getState().stagedActionIds).toEqual([
0, 1, 4, 2, 3,
]);
expect(storeWithMultiply.getState()).toBe(2);
storeWithMultiply.liftedStore.dispatch(ActionCreators.reorderAction(0, 1));
expect(storeWithMultiply.liftedStore.getState().stagedActionIds).toEqual([
0, 1, 4, 2, 3,
]);
expect(storeWithMultiply.getState()).toBe(2);
});
it('should replace the reducer', () => {
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(1);
store.replaceReducer(doubleCounter);
expect(store.getState()).toBe(2);
});
it('should replace the reducer without recomputing actions', () => {
store = createStore(
counter,
instrument(undefined, { shouldHotReload: false })
);
expect(store.getState()).toBe(0);
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(1);
store.replaceReducer(doubleCounter);
expect(store.getState()).toBe(1);
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(3);
store.replaceReducer(
(() => ({ test: true } as unknown)) as Reducer<number, CounterAction>
);
const newStore = store as unknown as Store<{ test: boolean }>;
expect(newStore.getState()).toEqual({ test: true });
});
it('should catch and record errors', () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {
// noop
});
const storeWithBug = createStore(
counterWithBug,
instrument(undefined, { shouldCatchErrors: true })
);
storeWithBug.dispatch({ type: 'INCREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'INCREMENT' });
const { computedStates } = storeWithBug.liftedStore.getState();
expect(computedStates[2].error).toMatch(/ReferenceError/);
expect(computedStates[3].error).toMatch(
/Interrupted by an error up the chain/
);
expect(spy.mock.calls[0][0].toString()).toMatch(/ReferenceError/);
spy.mockReset();
});
it('should catch invalid action type (undefined type)', () => {
expect(() => {
store.dispatch({ type: undefined } as unknown as CounterAction);
}).toThrow(
'Actions may not have an undefined "type" property. ' +
'Have you misspelled a constant?'
);
});
it('should catch invalid action type (function)', () => {
function ActionClass(this: any) {
this.type = 'test';
}
expect(() => {
store.dispatch(new (ActionClass as any)() as CounterAction);
}).toThrow(
'Actions must be plain objects. ' +
'Use custom middleware for async actions.'
);
});
it('should return the last non-undefined state from getState', () => {
const storeWithBug = createStore(counterWithBug, instrument());
storeWithBug.dispatch({ type: 'INCREMENT' });
storeWithBug.dispatch({ type: 'INCREMENT' });
expect(storeWithBug.getState()).toBe(2);
storeWithBug.dispatch({ type: 'SET_UNDEFINED' });
expect(storeWithBug.getState()).toBe(2);
});
it('should not recompute states on every action', () => {
let reducerCalls = 0;
const monitoredStore = createStore(() => reducerCalls++, instrument());
expect(reducerCalls).toBe(1);
monitoredStore.dispatch({ type: 'INCREMENT' });
monitoredStore.dispatch({ type: 'INCREMENT' });
monitoredStore.dispatch({ type: 'INCREMENT' });
expect(reducerCalls).toBe(4);
});
it('should not recompute old states when toggling an action', () => {
let reducerCalls = 0;
const monitoredStore = createStore(() => reducerCalls++, instrument());
const monitoredLiftedStore = monitoredStore.liftedStore;
expect(reducerCalls).toBe(1);
// actionId 0 = @@INIT
monitoredStore.dispatch({ type: 'INCREMENT' });
monitoredStore.dispatch({ type: 'INCREMENT' });
monitoredStore.dispatch({ type: 'INCREMENT' });
expect(reducerCalls).toBe(4);
monitoredLiftedStore.dispatch(ActionCreators.toggleAction(3));
expect(reducerCalls).toBe(4);
monitoredLiftedStore.dispatch(ActionCreators.toggleAction(3));
expect(reducerCalls).toBe(5);
monitoredLiftedStore.dispatch(ActionCreators.toggleAction(2));
expect(reducerCalls).toBe(6);
monitoredLiftedStore.dispatch(ActionCreators.toggleAction(2));
expect(reducerCalls).toBe(8);
monitoredLiftedStore.dispatch(ActionCreators.toggleAction(1));
expect(reducerCalls).toBe(10);
monitoredLiftedStore.dispatch(ActionCreators.toggleAction(2));
expect(reducerCalls).toBe(11);
monitoredLiftedStore.dispatch(ActionCreators.toggleAction(3));
expect(reducerCalls).toBe(11);
monitoredLiftedStore.dispatch(ActionCreators.toggleAction(1));
expect(reducerCalls).toBe(12);
monitoredLiftedStore.dispatch(ActionCreators.toggleAction(3));
expect(reducerCalls).toBe(13);
monitoredLiftedStore.dispatch(ActionCreators.toggleAction(2));
expect(reducerCalls).toBe(15);
});
it('should not recompute states when jumping to state', () => {
let reducerCalls = 0;
const monitoredStore = createStore(() => reducerCalls++, instrument());
const monitoredLiftedStore = monitoredStore.liftedStore;
expect(reducerCalls).toBe(1);
monitoredStore.dispatch({ type: 'INCREMENT' });
monitoredStore.dispatch({ type: 'INCREMENT' });
monitoredStore.dispatch({ type: 'INCREMENT' });
expect(reducerCalls).toBe(4);
const savedComputedStates = monitoredLiftedStore.getState().computedStates;
monitoredLiftedStore.dispatch(ActionCreators.jumpToState(0));
expect(reducerCalls).toBe(4);
monitoredLiftedStore.dispatch(ActionCreators.jumpToState(1));
expect(reducerCalls).toBe(4);
monitoredLiftedStore.dispatch(ActionCreators.jumpToState(3));
expect(reducerCalls).toBe(4);
expect(monitoredLiftedStore.getState().computedStates).toBe(
savedComputedStates
);
});
it('should not recompute states on monitor actions', () => {
let reducerCalls = 0;
const monitoredStore = createStore(() => reducerCalls++, instrument());
const monitoredLiftedStore = monitoredStore.liftedStore;
expect(reducerCalls).toBe(1);
monitoredStore.dispatch({ type: 'INCREMENT' });
monitoredStore.dispatch({ type: 'INCREMENT' });
monitoredStore.dispatch({ type: 'INCREMENT' });
expect(reducerCalls).toBe(4);
const savedComputedStates = monitoredLiftedStore.getState().computedStates;
monitoredLiftedStore.dispatch({ type: 'lol' } as Action);
expect(reducerCalls).toBe(4);
monitoredLiftedStore.dispatch({ type: 'wat' } as Action);
expect(reducerCalls).toBe(4);
expect(monitoredLiftedStore.getState().computedStates).toBe(
savedComputedStates
);
});
describe('maxAge option', () => {
let configuredStore: EnhancedStore<number, CounterAction, null>;
let configuredLiftedStore: LiftedStore<number, CounterAction, null>;
beforeEach(() => {
configuredStore = createStore(
counter,
instrument(undefined, { maxAge: 3 })
);
configuredLiftedStore = configuredStore.liftedStore;
});
it('should auto-commit earliest non-@@INIT action when maxAge is reached', () => {
configuredStore.dispatch({ type: 'INCREMENT' });
configuredStore.dispatch({ type: 'INCREMENT' });
let liftedStoreState = configuredLiftedStore.getState();
expect(configuredStore.getState()).toBe(2);
expect(Object.keys(liftedStoreState.actionsById)).toHaveLength(3);
expect(liftedStoreState.committedState).toBeUndefined();
expect(liftedStoreState.stagedActionIds).toContain(1);
// Trigger auto-commit.
configuredStore.dispatch({ type: 'INCREMENT' });
liftedStoreState = configuredLiftedStore.getState();
expect(configuredStore.getState()).toBe(3);
expect(Object.keys(liftedStoreState.actionsById)).toHaveLength(3);
expect(liftedStoreState.stagedActionIds).not.toContain(1);
expect(liftedStoreState.computedStates[0].state).toBe(1);
expect(liftedStoreState.committedState).toBe(1);
expect(liftedStoreState.currentStateIndex).toBe(2);
});
it('should remove skipped actions once committed', () => {
configuredStore.dispatch({ type: 'INCREMENT' });
configuredLiftedStore.dispatch(ActionCreators.toggleAction(1));
configuredStore.dispatch({ type: 'INCREMENT' });
expect(configuredLiftedStore.getState().skippedActionIds).toContain(1);
configuredStore.dispatch({ type: 'INCREMENT' });
expect(configuredLiftedStore.getState().skippedActionIds).not.toContain(
1
);
});
it('should not auto-commit errors', () => {
const spy = jest.spyOn(console, 'error');
const storeWithBug = createStore(
counterWithBug,
instrument(undefined, { maxAge: 3, shouldCatchErrors: true })
);
const liftedStoreWithBug = storeWithBug.liftedStore;
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'INCREMENT' });
expect(liftedStoreWithBug.getState().stagedActionIds).toHaveLength(3);
storeWithBug.dispatch({ type: 'INCREMENT' });
expect(liftedStoreWithBug.getState().stagedActionIds).toHaveLength(4);
spy.mockReset();
});
it('should auto-commit actions after hot reload fixes error', () => {
const spy = jest.spyOn(console, 'error');
const storeWithBug = createStore(
counterWithBug,
instrument(undefined, { maxAge: 3, shouldCatchErrors: true })
);
const liftedStoreWithBug = storeWithBug.liftedStore;
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'INCREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
expect(liftedStoreWithBug.getState().stagedActionIds).toHaveLength(7);
// Auto-commit 2 actions by "fixing" reducer bug, but introducing another.
storeWithBug.replaceReducer(
counterWithAnotherBug as Reducer<number, CounterWithBugAction>
);
const liftedStoreWithAnotherBug =
liftedStoreWithBug as unknown as LiftedStore<
number,
CounterWithAnotherBugAction,
null
>;
expect(liftedStoreWithAnotherBug.getState().stagedActionIds).toHaveLength(
5
);
// Auto-commit 2 more actions by "fixing" other reducer bug.
storeWithBug.replaceReducer(
counter as Reducer<number, CounterWithBugAction>
);
const liftedStore = liftedStoreWithBug as LiftedStore<
number,
CounterAction,
null
>;
expect(liftedStore.getState().stagedActionIds).toHaveLength(3);
spy.mockReset();
});
it('should update currentStateIndex when auto-committing', () => {
let liftedStoreState;
configuredStore.dispatch({ type: 'INCREMENT' });
configuredStore.dispatch({ type: 'INCREMENT' });
liftedStoreState = configuredLiftedStore.getState();
expect(liftedStoreState.currentStateIndex).toBe(2);
// currentStateIndex should stay at 2 as actions are committed.
configuredStore.dispatch({ type: 'INCREMENT' });
liftedStoreState = configuredLiftedStore.getState();
const currentComputedState =
liftedStoreState.computedStates[liftedStoreState.currentStateIndex];
expect(liftedStoreState.currentStateIndex).toBe(2);
expect(currentComputedState.state).toBe(3);
});
it('should continue to increment currentStateIndex while error blocks commit', () => {
const spy = jest.spyOn(console, 'error');
const storeWithBug = createStore(
counterWithBug,
instrument(undefined, { maxAge: 3, shouldCatchErrors: true })
);
const liftedStoreWithBug = storeWithBug.liftedStore;
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
const liftedStoreState = liftedStoreWithBug.getState();
const currentComputedState =
liftedStoreState.computedStates[liftedStoreState.currentStateIndex];
expect(liftedStoreState.currentStateIndex).toBe(4);
expect(currentComputedState.state).toBe(0);
expect(currentComputedState.error).toBeTruthy();
spy.mockReset();
});
it('should adjust currentStateIndex correctly when multiple actions are committed', () => {
const spy = jest.spyOn(console, 'error');
const storeWithBug = createStore(
counterWithBug,
instrument(undefined, { maxAge: 3, shouldCatchErrors: true })
);
const liftedStoreWithBug = storeWithBug.liftedStore;
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
// Auto-commit 2 actions by "fixing" reducer bug.
storeWithBug.replaceReducer(
counter as Reducer<number, CounterWithBugAction>
);
const liftedStore = liftedStoreWithBug as LiftedStore<
number,
CounterAction,
null
>;
const liftedStoreState = liftedStore.getState();
const currentComputedState =
liftedStoreState.computedStates[liftedStoreState.currentStateIndex];
expect(liftedStoreState.currentStateIndex).toBe(2);
expect(currentComputedState.state).toBe(-4);
spy.mockReset();
});
it('should not allow currentStateIndex to drop below 0', () => {
const spy = jest.spyOn(console, 'error');
const storeWithBug = createStore(
counterWithBug,
instrument(undefined, { maxAge: 3, shouldCatchErrors: true })
);
const liftedStoreWithBug = storeWithBug.liftedStore;
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
storeWithBug.dispatch({ type: 'DECREMENT' });
liftedStoreWithBug.dispatch(ActionCreators.jumpToState(1));
// Auto-commit 2 actions by "fixing" reducer bug.
storeWithBug.replaceReducer(
counter as Reducer<number, CounterWithBugAction>
);
const liftedStore = liftedStoreWithBug as LiftedStore<
number,
CounterAction,
null
>;
const liftedStoreState = liftedStore.getState();
const currentComputedState =
liftedStoreState.computedStates[liftedStoreState.currentStateIndex];
expect(liftedStoreState.currentStateIndex).toBe(0);
expect(currentComputedState.state).toBe(-2);
spy.mockReset();
});
it('should use dynamic maxAge', () => {
let max = 3;
const getMaxAge = jest.fn().mockImplementation(() => max);
store = createStore(
counter,
instrument(undefined, { maxAge: getMaxAge })
);
expect(getMaxAge.mock.calls).toHaveLength(1);
store.dispatch({ type: 'INCREMENT' });
expect(getMaxAge.mock.calls).toHaveLength(2);
store.dispatch({ type: 'INCREMENT' });
expect(getMaxAge.mock.calls).toHaveLength(3);
let liftedStoreState = store.liftedStore.getState();
expect(getMaxAge.mock.calls[0][0].type).toContain('INIT');
expect(getMaxAge.mock.calls[0][1]).toBeUndefined();
expect(getMaxAge.mock.calls[1][0].type).toBe('PERFORM_ACTION');
expect(getMaxAge.mock.calls[1][1].nextActionId).toBe(1);
expect(getMaxAge.mock.calls[1][1].stagedActionIds).toEqual([0]);
expect(getMaxAge.mock.calls[2][1].nextActionId).toBe(2);
expect(getMaxAge.mock.calls[2][1].stagedActionIds).toEqual([0, 1]);
expect(store.getState()).toBe(2);
expect(Object.keys(liftedStoreState.actionsById)).toHaveLength(3);
expect(liftedStoreState.committedState).toBeUndefined();
expect(liftedStoreState.stagedActionIds).toContain(1);
// Trigger auto-commit.
store.dispatch({ type: 'INCREMENT' });
liftedStoreState = store.liftedStore.getState();
expect(store.getState()).toBe(3);
expect(Object.keys(liftedStoreState.actionsById)).toHaveLength(3);
expect(liftedStoreState.stagedActionIds).not.toContain(1);
expect(liftedStoreState.computedStates[0].state).toBe(1);
expect(liftedStoreState.committedState).toBe(1);
expect(liftedStoreState.currentStateIndex).toBe(2);
max = 4;
store.dispatch({ type: 'INCREMENT' });
liftedStoreState = store.liftedStore.getState();
expect(store.getState()).toBe(4);
expect(Object.keys(liftedStoreState.actionsById)).toHaveLength(4);
expect(liftedStoreState.stagedActionIds).not.toContain(1);
expect(liftedStoreState.computedStates[0].state).toBe(1);
expect(liftedStoreState.committedState).toBe(1);
expect(liftedStoreState.currentStateIndex).toBe(3);
max = 3;
store.dispatch({ type: 'INCREMENT' });
liftedStoreState = store.liftedStore.getState();
expect(store.getState()).toBe(5);
expect(Object.keys(liftedStoreState.actionsById)).toHaveLength(3);
expect(liftedStoreState.stagedActionIds).not.toContain(1);
expect(liftedStoreState.computedStates[0].state).toBe(3);
expect(liftedStoreState.committedState).toBe(3);
expect(liftedStoreState.currentStateIndex).toBe(2);
store.dispatch({ type: 'INCREMENT' });
liftedStoreState = store.liftedStore.getState();
expect(store.getState()).toBe(6);
expect(Object.keys(liftedStoreState.actionsById)).toHaveLength(3);
expect(liftedStoreState.stagedActionIds).not.toContain(1);
expect(liftedStoreState.computedStates[0].state).toBe(4);
expect(liftedStoreState.committedState).toBe(4);
expect(liftedStoreState.currentStateIndex).toBe(2);
});
it('should throw error when maxAge < 2', () => {
expect(() => {
createStore(counter, instrument(undefined, { maxAge: 1 }));
}).toThrow(/may not be less than 2/);
});
});
describe('trace option', () => {
let monitoredStore;
let monitoredLiftedStore;
let exportedState;
it('should not include stack trace', () => {
monitoredStore = createStore(counter, instrument());
monitoredLiftedStore = monitoredStore.liftedStore;
monitoredStore.dispatch({ type: 'INCREMENT' });
exportedState = monitoredLiftedStore.getState();
expect(exportedState.actionsById[0].stack).toBeUndefined();
expect(exportedState.actionsById[1].stack).toBeUndefined();
});
it('should include stack trace', () => {
function fn1() {
monitoredStore = createStore(
counter,
instrument(undefined, { trace: true })
);
monitoredLiftedStore = monitoredStore.liftedStore;
monitoredStore.dispatch({ type: 'INCREMENT' });
exportedState = monitoredLiftedStore.getState();
expect(exportedState.actionsById[0].stack).toBeUndefined();
expect(typeof exportedState.actionsById[1].stack).toBe('string');
expect(exportedState.actionsById[1].stack).toMatch(/^Error/);
expect(exportedState.actionsById[1].stack).not.toMatch(/instrument.ts/);
expect(exportedState.actionsById[1].stack).toMatch(/\bfn1\b/);
expect(exportedState.actionsById[1].stack).toMatch(/\bfn2\b/);
expect(exportedState.actionsById[1].stack).toMatch(/\bfn3\b/);
expect(exportedState.actionsById[1].stack).toMatch(/\bfn4\b/);
expect(exportedState.actionsById[1].stack).toContain(
'instrument.spec.ts'
);
expect(exportedState.actionsById[1].stack!.split('\n')).toHaveLength(
10 + 1
); // +1 is for `Error\n`
}
function fn2() {
return fn1();
}
function fn3() {
return fn2();
}
function fn4() {
return fn3();
}
fn4();
});
it('should include only 3 frames for stack trace', () => {
function fn1() {
monitoredStore = createStore(
counter,
instrument(undefined, { trace: true, traceLimit: 3 })
);
monitoredLiftedStore = monitoredStore.liftedStore;
monitoredStore.dispatch({ type: 'INCREMENT' });
exportedState = monitoredLiftedStore.getState();
expect(exportedState.actionsById[0].stack).toBeUndefined();
expect(typeof exportedState.actionsById[1].stack).toBe('string');
expect(exportedState.actionsById[1].stack).toMatch(/\bfn1\b/);
expect(exportedState.actionsById[1].stack).toMatch(/\bfn2\b/);
expect(exportedState.actionsById[1].stack).toMatch(/\bfn3\b/);
expect(exportedState.actionsById[1].stack).not.toMatch(/\bfn4\b/);
expect(exportedState.actionsById[1].stack).toContain(
'instrument.spec.ts'
);
expect(exportedState.actionsById[1].stack!.split('\n')).toHaveLength(
3 + 1
);
}
function fn2() {
return fn1();
}
function fn3() {
return fn2();
}
function fn4() {
return fn3();
}
fn4();
});
it('should force traceLimit value of 3 when Error.stackTraceLimit is 10', () => {
const stackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 10;
function fn1() {
monitoredStore = createStore(
counter,
instrument(undefined, { trace: true, traceLimit: 3 })
);
monitoredLiftedStore = monitoredStore.liftedStore;
monitoredStore.dispatch({ type: 'INCREMENT' });
exportedState = monitoredLiftedStore.getState();
expect(exportedState.actionsById[0].stack).toBeUndefined();
expect(typeof exportedState.actionsById[1].stack).toBe('string');
expect(exportedState.actionsById[1].stack).toMatch(/\bfn1\b/);
expect(exportedState.actionsById[1].stack).toMatch(/\bfn2\b/);
expect(exportedState.actionsById[1].stack).toMatch(/\bfn3\b/);
expect(exportedState.actionsById[1].stack).not.toMatch(/\bfn4\b/);
expect(exportedState.actionsById[1].stack).toContain(
'instrument.spec.ts'
);
expect(exportedState.actionsById[1].stack!.split('\n')).toHaveLength(
3 + 1
);
}
function fn2() {
return fn1();
}
function fn3() {
return fn2();
}
function fn4() {
return fn3();
}
fn4();
Error.stackTraceLimit = stackTraceLimit;
});
it('should force traceLimit value of 5 even when Error.stackTraceLimit is 2', () => {
const stackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 2;
monitoredStore = createStore(
counter,
instrument(undefined, { trace: true, traceLimit: 5 })
);
monitoredLiftedStore = monitoredStore.liftedStore;
monitoredStore.dispatch({ type: 'INCREMENT' });
Error.stackTraceLimit = stackTraceLimit;
exportedState = monitoredLiftedStore.getState();
expect(exportedState.actionsById[0].stack).toBeUndefined();
expect(typeof exportedState.actionsById[1].stack).toBe('string');
expect(exportedState.actionsById[1].stack).toMatch(/^Error/);
expect(exportedState.actionsById[1].stack).toContain(
'instrument.spec.ts'
);
expect(exportedState.actionsById[1].stack!.split('\n')).toHaveLength(
5 + 1
);
});
it('should force default limit of 10 even when Error.stackTraceLimit is 3', () => {
const stackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 3;
function fn1() {
monitoredStore = createStore(
counter,
instrument(undefined, { trace: true })
);
monitoredLiftedStore = monitoredStore.liftedStore;
monitoredStore.dispatch({ type: 'INCREMENT' });
Error.stackTraceLimit = stackTraceLimit;
exportedState = monitoredLiftedStore.getState();
expect(exportedState.actionsById[0].stack).toBeUndefined();
expect(typeof exportedState.actionsById[1].stack).toBe('string');
expect(exportedState.actionsById[1].stack).toMatch(/\bfn1\b/);
expect(exportedState.actionsById[1].stack).toMatch(/\bfn2\b/);
expect(exportedState.actionsById[1].stack).toMatch(/\bfn3\b/);
expect(exportedState.actionsById[1].stack).toMatch(/\bfn4\b/);
expect(exportedState.actionsById[1].stack).toContain(
'instrument.spec.ts'
);
expect(exportedState.actionsById[1].stack!.split('\n')).toHaveLength(
10 + 1
);
}
function fn2() {
return fn1();
}
function fn3() {
return fn2();
}
function fn4() {
return fn3();
}
fn4();
});
it('should include 3 extra frames when Error.captureStackTrace not suported', () => {
// eslint-disable-next-line @typescript-eslint/unbound-method
const captureStackTrace = Error.captureStackTrace;
Error.captureStackTrace = undefined as unknown as () => unknown;
monitoredStore = createStore(
counter,
instrument(undefined, { trace: true, traceLimit: 5 })
);
monitoredLiftedStore = monitoredStore.liftedStore;
monitoredStore.dispatch({ type: 'INCREMENT' });
Error.captureStackTrace = captureStackTrace;
exportedState = monitoredLiftedStore.getState();
expect(exportedState.actionsById[0].stack).toBeUndefined();
expect(typeof exportedState.actionsById[1].stack).toBe('string');
expect(exportedState.actionsById[1].stack).toMatch(/^Error/);
expect(exportedState.actionsById[1].stack).toContain('instrument.ts');
expect(exportedState.actionsById[1].stack).toContain(
'instrument.spec.ts'
);
expect(exportedState.actionsById[1].stack!.split('\n')).toHaveLength(
5 + 3 + 1
);
});
it('should get stack trace from a function', () => {
const traceFn = () => new Error().stack;
monitoredStore = createStore(
counter,
instrument(undefined, { trace: traceFn })
);
monitoredLiftedStore = monitoredStore.liftedStore;
monitoredStore.dispatch({ type: 'INCREMENT' });
exportedState = monitoredLiftedStore.getState();
expect(exportedState.actionsById[0].stack).toBeUndefined();
expect(typeof exportedState.actionsById[1].stack).toBe('string');
expect(exportedState.actionsById[1].stack).toContain(
'at Object.performAction'
);
expect(exportedState.actionsById[1].stack).toContain('instrument.ts');
expect(exportedState.actionsById[1].stack).toContain(
'instrument.spec.ts'
);
});
it('should get stack trace inside setTimeout using a function', () =>
new Promise<void>((done) => {
const stack = new Error().stack;
setTimeout(() => {
const traceFn = () => stack! + new Error().stack!;
monitoredStore = createStore(
counter,
instrument(undefined, { trace: traceFn })
);
monitoredLiftedStore = monitoredStore.liftedStore;
monitoredStore.dispatch({ type: 'INCREMENT' });
exportedState = monitoredLiftedStore.getState();
expect(exportedState.actionsById[0].stack).toBeUndefined();
expect(typeof exportedState.actionsById[1].stack).toBe('string');
expect(exportedState.actionsById[1].stack).toContain(
'at Object.performAction'
);
expect(exportedState.actionsById[1].stack).toContain('instrument.ts');
expect(exportedState.actionsById[1].stack).toContain(
'instrument.spec.ts'
);
done();
});
}));
});
describe('Import State', () => {
let monitoredStore: EnhancedStore<number, CounterAction, null>;
let monitoredLiftedStore: LiftedStore<number, CounterAction, null>;
let exportedState: LiftedState<number, CounterAction, null>;
beforeEach(() => {
monitoredStore = createStore(counter, instrument());
monitoredLiftedStore = monitoredStore.liftedStore;
// Set up state to export
monitoredStore.dispatch({ type: 'INCREMENT' });
monitoredStore.dispatch({ type: 'INCREMENT' });
monitoredStore.dispatch({ type: 'INCREMENT' });
exportedState = monitoredLiftedStore.getState();
});
it('should replay all the steps when a state is imported', () => {
const importMonitoredStore = createStore(counter, instrument());
const importMonitoredLiftedStore = importMonitoredStore.liftedStore;
importMonitoredLiftedStore.dispatch(
ActionCreators.importState(exportedState)
);
expect(importMonitoredLiftedStore.getState()).toEqual(exportedState);
});
it('should replace the existing action log with the one imported', () => {
const importMonitoredStore = createStore(counter, instrument());
const importMonitoredLiftedStore = importMonitoredStore.liftedStore;
importMonitoredStore.dispatch({ type: 'DECREMENT' });
importMonitoredStore.dispatch({ type: 'DECREMENT' });
importMonitoredLiftedStore.dispatch(
ActionCreators.importState(exportedState)
);
expect(importMonitoredLiftedStore.getState()).toEqual(exportedState);
});
it('should allow for state to be imported without replaying actions', () => {
const importMonitoredStore = createStore(counter, instrument());
const importMonitoredLiftedStore = importMonitoredStore.liftedStore;
const noComputedExportedState = Object.assign({}, exportedState);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
delete noComputedExportedState.computedStates;
importMonitoredLiftedStore.dispatch(
ActionCreators.importState(noComputedExportedState, true)
);
const expectedImportedState = Object.assign({}, noComputedExportedState, {
computedStates: undefined,
});
expect(importMonitoredLiftedStore.getState()).toEqual(
expectedImportedState
);
});
it('should include stack trace', () => {
const importMonitoredStore = createStore(
counter,
instrument(undefined, { trace: true })
);
const importMonitoredLiftedStore = importMonitoredStore.liftedStore;
importMonitoredStore.dispatch({ type: 'DECREMENT' });
importMonitoredStore.dispatch({ type: 'DECREMENT' });
const oldState = importMonitoredLiftedStore.getState();
expect(oldState.actionsById[0].stack).toBeUndefined();
expect(typeof oldState.actionsById[1].stack).toBe('string');
importMonitoredLiftedStore.dispatch(ActionCreators.importState(oldState));
expect(importMonitoredLiftedStore.getState()).toEqual(oldState);
expect(
importMonitoredLiftedStore.getState().actionsById[0].stack
).toBeUndefined();
expect(importMonitoredLiftedStore.getState().actionsById[1]).toEqual(
oldState.actionsById[1]
);
});
});
function filterStackAndTimestamps<S, A extends Action<unknown>>(
state: LiftedState<S, A, null>
) {
state.actionsById = _.mapValues(state.actionsById, (action) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
delete action.timestamp;
delete action.stack;
return action;
});
return state;
}
describe('Import Actions', () => {
let monitoredStore: EnhancedStore<number, CounterAction, null>;
let monitoredLiftedStore: LiftedStore<number, CounterAction, null>;
let exportedState: LiftedState<number, CounterAction, null>;
const savedActions = [
{ type: 'INCREMENT' },
{ type: 'INCREMENT' },
{ type: 'INCREMENT' },
] as const;
beforeEach(() => {
monitoredStore = createStore(counter, instrument());
monitoredLiftedStore = monitoredStore.liftedStore;
// Pass actions through component
savedActions.forEach((action) => monitoredStore.dispatch(action));
// get the final state
exportedState = filterStackAndTimestamps(monitoredLiftedStore.getState());
});
it('should replay all the steps when a state is imported', () => {
const importMonitoredStore = createStore(counter, instrument());
const importMonitoredLiftedStore = importMonitoredStore.liftedStore;
importMonitoredLiftedStore.dispatch(
ActionCreators.importState(savedActions)
);
expect(
filterStackAndTimestamps(importMonitoredLiftedStore.getState())
).toEqual(exportedState);
});
it('should replace the existing action log with the one imported', () => {
const importMonitoredStore = createStore(counter, instrument());
const importMonitoredLiftedStore = importMonitoredStore.liftedStore;
importMonitoredStore.dispatch({ type: 'DECREMENT' });
importMonitoredStore.dispatch({ type: 'DECREMENT' });
importMonitoredLiftedStore.dispatch(
ActionCreators.importState(savedActions)
);
expect(
filterStackAndTimestamps(importMonitoredLiftedStore.getState())
).toEqual(exportedState);
});
it('should include stack trace', () => {
const importMonitoredStore = createStore(
counter,
instrument(undefined, { trace: true })
);
const importMonitoredLiftedStore = importMonitoredStore.liftedStore;
importMonitoredStore.dispatch({ type: 'DECREMENT' });
importMonitoredStore.dispatch({ type: 'DECREMENT' });
importMonitoredLiftedStore.dispatch(
ActionCreators.importState(savedActions)
);
expect(
importMonitoredLiftedStore.getState().actionsById[0].stack
).toBeUndefined();
expect(
typeof importMonitoredLiftedStore.getState().actionsById[1].stack
).toBe('string');
expect(
filterStackAndTimestamps(importMonitoredLiftedStore.getState())
).toEqual(exportedState);
});
});
describe('Lock Changes', () => {
it('should lock', () => {
store.dispatch({ type: 'INCREMENT' });
store.liftedStore.dispatch({ type: 'LOCK_CHANGES', status: true });
expect(store.liftedStore.getState().isLocked).toBe(true);
expect(store.liftedStore.getState().nextActionId).toBe(2);
expect(store.getState()).toBe(1);
store.dispatch({ type: 'INCREMENT' });
expect(store.liftedStore.getState().nextActionId).toBe(2);
expect(store.getState()).toBe(1);
liftedStore.dispatch(ActionCreators.toggleAction(1));
expect(store.getState()).toBe(0);
liftedStore.dispatch(ActionCreators.toggleAction(1));
expect(store.getState()).toBe(1);
store.liftedStore.dispatch({ type: 'LOCK_CHANGES', status: false });
expect(store.liftedStore.getState().isLocked).toBe(false);
expect(store.liftedStore.getState().nextActionId).toBe(2);
store.dispatch({ type: 'INCREMENT' });
expect(store.liftedStore.getState().nextActionId).toBe(3);
expect(store.getState()).toBe(2);
});
it('should start locked', () => {
store = createStore(
counter,
instrument(undefined, { shouldStartLocked: true })
);
store.dispatch({ type: 'INCREMENT' });
expect(store.liftedStore.getState().isLocked).toBe(true);
expect(store.liftedStore.getState().nextActionId).toBe(1);
expect(store.getState()).toBe(0);
const savedActions = [
{ type: 'INCREMENT' },
{ type: 'INCREMENT' },
] as const;
store.liftedStore.dispatch(
ActionCreators.importState<number, CounterAction, null>(savedActions)
);
expect(store.liftedStore.getState().nextActionId).toBe(3);
expect(store.getState()).toBe(2);
store.liftedStore.dispatch({ type: 'LOCK_CHANGES', status: false });
expect(store.liftedStore.getState().isLocked).toBe(false);
store.dispatch({ type: 'INCREMENT' });
expect(store.liftedStore.getState().nextActionId).toBe(4);
expect(store.getState()).toBe(3);
});
});
describe('Pause recording', () => {
it('should pause', () => {
expect(store.liftedStore.getState().isPaused).toBe(false);
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.liftedStore.getState().nextActionId).toBe(3);
expect(store.getState()).toBe(2);
store.liftedStore.dispatch(ActionCreators.pauseRecording(true));
expect(store.liftedStore.getState().isPaused).toBe(true);
expect(store.liftedStore.getState().nextActionId).toBe(1);
expect(store.liftedStore.getState().actionsById[0].action).toEqual({
type: '@@INIT',
});
expect(store.getState()).toBe(2);
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.liftedStore.getState().nextActionId).toBe(1);
expect(store.liftedStore.getState().actionsById[0].action).toEqual({
type: '@@INIT',
});
expect(store.getState()).toBe(4);
store.liftedStore.dispatch(ActionCreators.pauseRecording(false));
expect(store.liftedStore.getState().isPaused).toBe(false);
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.liftedStore.getState().nextActionId).toBe(3);
expect(store.liftedStore.getState().actionsById[2].action).toEqual({
type: 'INCREMENT',
});
expect(store.getState()).toBe(6);
});
it('should maintain the history while paused', () => {
store = createStore(
counter,
instrument(undefined, { pauseActionType: '@@PAUSED' })
);
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
expect(store.getState()).toBe(2);
expect(store.liftedStore.getState().nextActionId).toBe(3);
expect(store.liftedStore.getState().isPaused).toBe(false);
store.liftedStore.dispatch(ActionCreators.pauseRecording(true));
expect(store.liftedStore.getState().isPaused).toBe(true);
expect(store.liftedStore.getState().nextActionId).toBe(4);
expect(store.getState()).toBe(2);
store.dispatch({ type: 'INCREMENT' });
expect(store.liftedStore.getState().nextActionId).toBe(4);
store.dispatch({ type: 'INCREMENT' });
expect(store.liftedStore.getState().nextActionId).toBe(4);
expect(store.getState()).toBe(4);
store.liftedStore.dispatch(ActionCreators.pauseRecording(false));
expect(store.liftedStore.getState().isPaused).toBe(false);
expect(store.liftedStore.getState().nextActionId).toBe(1);
expect(store.getState()).toBe(4);
store.dispatch({ type: 'INCREMENT' });
expect(store.liftedStore.getState().nextActionId).toBe(2);
expect(store.getState()).toBe(5);
store.liftedStore.dispatch(ActionCreators.commit());
store.liftedStore.dispatch(ActionCreators.pauseRecording(true));
store.dispatch({ type: 'INCREMENT' });
expect(store.liftedStore.getState().nextActionId).toBe(1);
expect(store.getState()).toBe(6);
});
});
it('throws if reducer is not a function', () => {
expect(() =>
createStore(undefined as unknown as Reducer, instrument())
).toThrow('Expected the reducer to be a function.');
});
it('warns if the reducer is not a function but has a default field that is', () => {
expect(() =>
createStore(
{
default: () => {
// noop
},
} as unknown as Reducer,
instrument()
)
).toThrow(
'Expected the reducer to be a function. ' +
'Instead got an object with a "default" field. ' +
'Did you pass a module instead of the default export? ' +
'Try passing require(...).default instead.'
);
});
it('throws if there are more than one instrument enhancer included', () => {
expect(() => {
createStore(counter, compose(instrument(), instrument()));
}).toThrow(
'DevTools instrumentation should not be applied more than once. ' +
'Check your store configuration.'
);
});
}); | the_stack |
import { faArrowLeft, faClipboard, faFileCode, faFileUpload, faTrashAlt } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { Download, Upload } from '@mui/icons-material'
import { Alert, Box, Button, CardContent, Divider, Grid, MenuItem, styled, Typography } from '@mui/material'
import { useContext, useMemo, useState } from "react"
import ReactGA from 'react-ga'
import { Trans, useTranslation } from "react-i18next"
import CardDark from '../Components/Card/CardDark'
import CardLight from '../Components/Card/CardLight'
import DropdownButton from '../Components/DropdownMenu/DropdownButton'
import SqBadge from '../Components/SqBadge'
import { ArtCharDatabase, DatabaseContext } from "../Database/Database"
import { dbStorage } from '../Database/DBStorage'
import { importGO, ImportResult as GOImportResult } from '../Database/exim/go'
import { exportGOOD, importGOOD, ImportResult as GOODImportResult, ImportResultCounter } from '../Database/exim/good'
import { importMona } from '../Database/exim/mona'
import { languageCodeList } from "../i18n"
import useForceUpdate from '../ReactHooks/useForceUpdate'
export default function SettingsDisplay() {
const { t } = useTranslation(["settings"]);
const [, forceUpdate] = useForceUpdate()
ReactGA.pageview('/setting')
return <CardDark sx={{ my: 1 }}>
<CardContent sx={{ py: 1 }}>
<Typography variant="subtitle1">
<Trans t={t} i18nKey="title" />
</Typography>
</CardContent>
<Divider />
<CardContent sx={{
// select all excluding last
"> div:nth-last-of-type(n+2)": { mb: 2 }
}}>
<LanguageCard />
<DownloadCard forceUpdate={forceUpdate} />
<UploadCard forceUpdate={forceUpdate} />
</CardContent>
</CardDark>
}
function LanguageCard() {
const { t } = useTranslation();
return <CardLight>
<CardContent sx={{ py: 1 }}>
{t("settings:languageCard.selectLanguage")} <SqBadge color="warning">{t("ui:underConstruction")}</SqBadge>
</CardContent>
<Divider />
<CardContent>
<LanguageDropdown />
</CardContent>
</CardLight>
}
const nativeLanguages = {
"chs": "中文 正体字",
"cht": "中文 繁體字",
"de": "Deutsch",
"en": "English",
"es": "español",
"fr": "français",
"id": "Bahasa Indonesia",
"ja": "日本語",
"ko": "한국어",
"pt": "Português",
"ru": "Русский язык",
"th": "ภาษาไทย",
"vi": "Tiếng Việt"
}
export function LanguageDropdown() {
const { t, i18n } = useTranslation(["ui", "settings"]);
const onSetLanguage = (lang) => () => i18n.changeLanguage(lang);
const currentLang = i18n.languages[0];
return <DropdownButton fullWidth title={t('settings:languageCard.languageFormat', { language: t(`languages:${currentLang}`) })}>
{languageCodeList.map((lang) => <MenuItem key={lang} selected={currentLang === lang} disabled={currentLang === lang} onClick={onSetLanguage(lang)}><Trans i18nKey={`languages:${lang}`} />{lang !== currentLang ? ` (${nativeLanguages[lang]})` : ""}</MenuItem>)}
</DropdownButton>
}
function download(JSONstr: string, filename = "data.json") {
const contentType = "application/json;charset=utf-8"
const a = document.createElement('a');
a.download = filename
a.href = `data:${contentType},${encodeURIComponent(JSONstr)}`
a.target = "_blank"
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
function deleteDatabase(t, database: ArtCharDatabase) {
if (!window.confirm(t("uploadCard.goUpload.deleteDatabasePrompt"))) return
dbStorage.clear()
database.reloadStorage()
}
function copyToClipboard() {
navigator.clipboard.writeText(JSON.stringify(exportGOOD(dbStorage)))
.then(() => alert("Copied database to clipboard."))
.catch(console.error)
}
function DownloadCard({ forceUpdate }) {
const database = useContext(DatabaseContext)
const { t } = useTranslation(["settings"]);
const numChar = database._getCharKeys().length
const numArt = database._getArts().length
const numWeapon = database._getWeapons().length
const downloadValid = Boolean(numChar || numArt)
const deleteDB = () => {
deleteDatabase(t, database);
forceUpdate()
}
return <CardLight>
<CardContent sx={{ py: 1 }}>
<Typography variant="subtitle1">
<Trans t={t} i18nKey="downloadCard.databaseDownload" />
</Typography>
</CardContent>
<Divider />
<CardContent>
<Grid container mb={2} spacing={2}>
<Grid item xs={6} md={4}><Typography><Trans t={t} i18nKey="count.chars" /> {numChar}</Typography></Grid>
<Grid item xs={6} md={4}><Typography><Trans t={t} i18nKey="count.arts" /> {numArt}</Typography></Grid>
<Grid item xs={6} md={4}><Typography><Trans t={t} i18nKey="count.weapons" /> {numWeapon}</Typography></Grid>
</Grid>
<Typography variant="caption"><Trans t={t} i18nKey="downloadCard.databaseDisclaimer" /></Typography>
</CardContent>
<Divider />
<CardContent sx={{ py: 1 }}>
<Grid container spacing={2}>
<Grid item><Button disabled={!downloadValid} onClick={() => download(JSON.stringify(exportGOOD(dbStorage)))} startIcon={<Download />}><Trans t={t} i18nKey="downloadCard.button.download" /></Button></Grid>
<Grid item flexGrow={1} ><Button disabled={!downloadValid} color="info" onClick={copyToClipboard} startIcon={<FontAwesomeIcon icon={faClipboard} />}><Trans t={t} i18nKey="downloadCard.button.copy" /></Button></Grid>
<Grid item><Button disabled={!downloadValid} color="error" onClick={deleteDB} startIcon={<FontAwesomeIcon icon={faTrashAlt} />}><Trans t={t} i18nKey="downloadCard.button.delete" /></Button></Grid>
</Grid>
</CardContent>
</CardLight>
}
const InvisInput = styled('input')({
display: 'none',
});
function UploadCard({ forceUpdate }) {
const database = useContext(DatabaseContext)
const { t } = useTranslation("settings");
const [data, setdata] = useState("")
const [filename, setfilename] = useState("")
const [errorMsg, setErrorMsg] = useState("") // TODO localize error msg
const dataObj: UploadData | undefined = useMemo(() => {
if (!data) return
let parsed: any
try {
parsed = JSON.parse(data)
if (typeof parsed !== "object") {
setErrorMsg("uploadCard.error.jsonParse")
return
}
} catch (e) {
setErrorMsg("uploadCard.error.jsonParse")
return
}
// Figure out the file format
if (parsed.version === "1" && ["flower", "feather", "sand", "cup", "head"].some(k => Object.keys(parsed).includes(k))) {
// Parse as mona format
const imported = importMona(parsed, database)
if (!imported) {
setErrorMsg("uploadCard.error.monaInvalid")
return
}
return imported
} else if ("version" in parsed && "characterDatabase" in parsed && "artifactDatabase" in parsed) {
// Parse as GO format
const imported = importGO(parsed)
if (!imported) {
setErrorMsg("uploadCard.error.goInvalid")
return
}
return imported
} else if (parsed.format === "GOOD") {
// Parse as GOOD format
const imported = importGOOD(parsed, database)
if (!imported) {
setErrorMsg("uploadCard.error.goInvalid")
return
}
return imported
}
setErrorMsg("uploadCard.error.unknown")
return
}, [data, database])
const reset = () => {
setdata("")
setfilename("")
forceUpdate()
}
const onUpload = async e => {
const file = e.target.files[0]
e.target.value = null // reset the value so the same file can be uploaded again...
if (file) setfilename(file.name)
const reader = new FileReader()
reader.onload = () => setdata(reader.result as string)
reader.readAsText(file)
}
return <CardLight>
<CardContent sx={{ py: 1 }}><Trans t={t} i18nKey="settings:uploadCard.title" /></CardContent>
<CardContent>
<Grid container spacing={2} sx={{ mb: 1 }}>
<Grid item>
<label htmlFor="icon-button-file">
<InvisInput accept=".json" id="icon-button-file" type="file" onChange={onUpload} />
<Button component="span" startIcon={<Upload />}>Upload</Button>
</label>
</Grid>
<Grid item flexGrow={1}>
<CardDark sx={{ px: 2, py: 1 }}>
<Typography>{filename ? <span><FontAwesomeIcon icon={faFileCode} /> {filename}</span> : <span><FontAwesomeIcon icon={faArrowLeft} /> <Trans t={t} i18nKey="settings:uploadCard.hint" /></span>}</Typography>
</CardDark>
</Grid>
</Grid>
<Typography gutterBottom variant="caption"><Trans t={t} i18nKey="settings:uploadCard.hintPaste" /></Typography>
<Box component="textarea" sx={{ width: "100%", fontFamily: "monospace", minHeight: "10em", mb: 2, resize: "vertical" }} value={data} onChange={e => setdata(e.target.value)} />
{UploadInfo(dataObj) ?? errorMsg}
</CardContent>
{UploadAction(dataObj, reset)}
</CardLight>
}
function UploadInfo(data: UploadData | undefined) {
switch (data?.type) {
case "GO": return <GOUploadInfo data={data} />
case "GOOD": return <GOODUploadInfo data={data} />
}
}
function UploadAction(data: UploadData | undefined, reset: () => void) {
switch (data?.type) {
case "GO":
case "GOOD": return <GOUploadAction data={data} reset={reset} />
}
}
function GOODUploadInfo({ data: { source, artifacts, characters, weapons }, data }: { data: GOODImportResult }) {
const { t } = useTranslation("settings")
return <CardDark>
<CardContent sx={{ py: 1 }}>
<Typography>
<Trans t={t} i18nKey="uploadCard.dbSource" /><strong> {source}</strong>
</Typography>
</CardContent>
<Divider />
<CardContent >
<Grid container spacing={2}>
<Grid item flexGrow={1}>
<MergeResult result={artifacts} type="arts" />
</Grid>
<Grid item flexGrow={1}>
<MergeResult result={weapons} type="weapons" />
</Grid>
<Grid item flexGrow={1}>
<MergeResult result={characters} type="chars" />
</Grid>
</Grid>
</CardContent>
</CardDark>
}
function MergeResult({ result, type }: { result?: ImportResultCounter, type: string }) {
const { t } = useTranslation("settings")
if (!result) return null
return <CardLight >
<CardContent sx={{ py: 1 }}>
<Typography>
<Trans t={t} i18nKey={`count.${type}`} /> {result.total ?? 0}
</Typography>
</CardContent>
<Divider />
<CardContent>
<Typography><Trans t={t} i18nKey="count.new" /> <strong>{result.new}</strong> / {result.total}</Typography>
<Typography><Trans t={t} i18nKey="count.updated" /> <strong>{result.updated}</strong> / {result.total}</Typography>
<Typography><Trans t={t} i18nKey="count.unchanged" /> <strong>{result.unchanged}</strong> / {result.total}</Typography>
<Typography color="warning.main"><Trans t={t} i18nKey="count.removed" /> <strong>{result.removed}</strong></Typography>
{!!result.invalid?.length && <div>
<Typography color="error.main"><Trans t={t} i18nKey="count.invalid" /> <strong>{result.invalid.length}</strong> / {result.total}</Typography>
<Box component="textarea" sx={{ width: "100%", fontFamily: "monospace", minHeight: "10em", resize: "vertical" }} value={JSON.stringify(result.invalid, undefined, 2)} disabled />
</div>}
</CardContent>
</CardLight>
}
function GOUploadInfo({ data: { charCount, artCount } }: { data: GOImportResult }) {
const { t } = useTranslation("settings")
return <CardDark>
<CardContent sx={{ py: 1 }}>
<Trans t={t} i18nKey="uploadCard.goUpload.title" />
</CardContent>
<Divider />
<CardContent><Grid container spacing={1}>
<Grid item xs={12} md={6}> <Typography><Trans t={t} i18nKey="count.chars" /> {charCount}</Typography></Grid>
<Grid item xs={12} md={6}> <Typography><Trans t={t} i18nKey="count.arts" /> {artCount}</Typography></Grid>
{<Grid item xs={12} ><Alert severity="warning" ><Trans t={t} i18nKey="uploadCard.goUpload.migrate" /></Alert></Grid>}
</Grid></CardContent>
</CardDark>
}
function GOUploadAction({ data: { storage }, data, reset }: { data: GOImportResult | GOODImportResult, reset: () => void }) {
const database = useContext(DatabaseContext)
const { t } = useTranslation("settings")
const dataValid = data.type === "GO" ? data.charCount || data.artCount : (data.characters?.total || data.artifacts?.total || data.weapons?.total)
const replaceDB = () => {
dbStorage.removeForKeys(k => k.startsWith("artifact_") || k.startsWith("char_") || k.startsWith("weapon_"))
dbStorage.copyFrom(storage)
database.reloadStorage()
reset()
}
return <><Divider /><CardContent sx={{ py: 1 }}>
<Button color={dataValid ? "success" : "error"} disabled={!dataValid} onClick={replaceDB} startIcon={<FontAwesomeIcon icon={faFileUpload} />}><Trans t={t} i18nKey="settings:uploadCard.replaceDatabase" /></Button>
</CardContent></>
}
type UploadData = GOImportResult | GOODImportResult | the_stack |
import assert from 'assert';
import * as Units from 'thingtalk-units';
import Type, { TypeMap, EntityType, MeasureType, ArrayType } from '../type';
import { normalizeDate } from '../utils/date_utils';
import AstNode from './base';
import NodeVisitor from './visitor';
import { BooleanExpression } from './boolean_expression';
import type { ArgumentDef } from './function_def';
import {
TokenStream,
ConstantToken
} from '../new-syntax/tokenstream';
import List from '../utils/list';
import {
SyntaxPriority,
addParenthesis
} from './syntax_priority';
import {
MeasureEntity,
LocationEntity,
TimeEntity,
GenericEntity,
AnyEntity
} from '../entities';
import * as builtin from '../runtime/values';
export abstract class Location {
static Absolute : typeof AbsoluteLocation;
isAbsolute ! : boolean;
static Relative : typeof RelativeLocation;
isRelative ! : boolean;
static Unresolved : typeof UnresolvedLocation;
isUnresolved ! : boolean;
abstract clone() : Location;
abstract equals(x : unknown) : boolean;
abstract toEntity() : LocationEntity;
abstract toSource() : TokenStream;
}
Location.prototype.isAbsolute = false;
Location.prototype.isRelative = false;
Location.prototype.isUnresolved = false;
export class AbsoluteLocation extends Location {
lat : number;
lon : number;
display : string|null;
constructor(lat : number, lon : number, display : string|null = null) {
super();
assert(typeof lat === 'number');
this.lat = lat;
assert(typeof lon === 'number');
this.lon = lon;
assert(typeof display === 'string' || display === null);
this.display = display;
}
get latitude() {
return this.lat;
}
get longitude() {
return this.lon;
}
toEntity() : LocationEntity {
return { latitude: this.lat, longitude: this.lon, display: this.display };
}
toSource() : TokenStream {
return List.singleton(new ConstantToken('LOCATION', this.toEntity()));
}
toString() : string {
return `Absolute(${this.lat}, ${this.lon}, ${this.display})`;
}
clone() : AbsoluteLocation {
return new AbsoluteLocation(this.lat, this.lon, this.display);
}
equals(other : unknown) : boolean {
return other instanceof AbsoluteLocation && this.lat === other.lat
&& this.lon === other.lon && this.display === other.display;
}
}
AbsoluteLocation.prototype.isAbsolute = true;
Location.Absolute = AbsoluteLocation;
export class RelativeLocation extends Location {
relativeTag : string;
constructor(relativeTag : string) {
super();
assert(typeof relativeTag === 'string');
this.relativeTag = relativeTag;
}
toEntity() : LocationEntity {
throw new Error('Value is not an entity');
}
toSource() : TokenStream {
return List.concat('$location', '.', this.relativeTag);
}
toString() : string {
return `Relative(${this.relativeTag})`;
}
clone() : RelativeLocation {
return new RelativeLocation(this.relativeTag);
}
equals(other : unknown) : boolean {
return other instanceof RelativeLocation && this.relativeTag === other.relativeTag;
}
}
RelativeLocation.prototype.isRelative = true;
Location.Relative = RelativeLocation;
export class UnresolvedLocation extends Location {
name : string;
constructor(name : string) {
super();
this.name = name;
}
toEntity() : LocationEntity {
return { latitude: NaN, longitude: NaN, display: this.name };
}
toSource() : TokenStream {
return List.singleton(new ConstantToken('LOCATION', this.toEntity()));
}
toString() : string {
return `Unresolved(${this.name})`;
}
clone() : UnresolvedLocation {
return new UnresolvedLocation(this.name);
}
equals(other : unknown) : boolean {
return other instanceof UnresolvedLocation && this.name === other.name;
}
}
UnresolvedLocation.prototype.isUnresolved = true;
Location.Unresolved = UnresolvedLocation;
export class DateEdge {
isDateEdge = true;
edge : ('start_of' | 'end_of');
unit : string;
constructor(edge : ('start_of' | 'end_of'), unit : string) {
assert(edge === 'start_of' || edge === 'end_of');
this.edge = edge;
assert(typeof unit === 'string');
this.unit = unit;
}
toSource() : TokenStream {
return List.concat('$' + this.edge, '(', this.unit, ')');
}
equals(other : unknown) : boolean {
return other instanceof DateEdge && this.edge === other.edge && this.unit === other.unit;
}
}
export class DatePiece {
isDatePiece = true;
year : number|null;
month : number|null;
day : number|null;
time : AbsoluteTime|null;
constructor(year : number|null, month : number|null, day : number|null, time : AbsoluteTime|null) {
assert((year !== null && year >= 0) || (month !== null && month > 0) || (day !== null && day > 0));
assert(year === null || month === null || day === null);
this.year = year;
if (year !== null && year >= 0 && year < 100) { // then assume 1950-2050
if (year >= 50)
this.year = 1900 + year;
else
this.year = 2000 + year;
}
this.month = month;
this.day = day;
this.time = time;
}
toSource() : TokenStream {
let syntax : TokenStream = List.concat('new', 'Date', '(');
if (this.year !== null)
syntax = List.concat(syntax, new ConstantToken('NUMBER', this.year));
syntax = List.concat(syntax, ',');
if (this.month !== null)
syntax = List.concat(syntax, new ConstantToken('NUMBER', this.month));
syntax = List.concat(syntax, ',');
if (this.day !== null)
syntax = List.concat(syntax, new ConstantToken('NUMBER', this.day));
if (this.time !== null) {
syntax = List.concat(syntax, ',');
syntax = List.concat(syntax, this.time.toSource());
}
syntax = List.concat(syntax, ')');
return syntax;
}
equals(other : unknown) : boolean {
if (!(other instanceof DatePiece))
return false;
if (!(this.year === other.year
&& this.month === other.month
&& this.day === other.day))
return false;
if (this.time === other.time)
return true;
if (this.time && other.time)
return this.time.equals(other.time);
return false;
}
}
export type WeekDay = ('monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday');
export class WeekDayDate {
isWeekDayDate = true;
weekday : WeekDay;
time : AbsoluteTime|null;
constructor(weekday : string, time : AbsoluteTime|null) {
assert(weekday === 'monday' ||
weekday === 'tuesday' ||
weekday === 'wednesday' ||
weekday === 'thursday' ||
weekday === 'friday' ||
weekday === 'saturday' ||
weekday === 'sunday');
this.weekday = weekday;
this.time = time;
}
toSource() : TokenStream {
if (this.time !== null)
return List.concat('new', 'Date', '(', 'enum', this.weekday, ',', this.time.toSource(), ')');
else
return List.concat('new', 'Date', '(', 'enum', this.weekday, ')');
}
equals(other : unknown) : boolean {
return (other instanceof WeekDayDate && this.weekday === other.weekday
&& (this.time === other.time || !!(this.time && other.time && this.time.equals(other.time))));
}
}
export abstract class Time {
static Absolute : typeof AbsoluteTime;
isAbsolute ! : boolean;
static Relative : typeof RelativeTime;
isRelative ! : boolean;
abstract clone() : Time;
abstract equals(x : unknown) : boolean;
abstract toEntity() : TimeEntity;
abstract toSource() : TokenStream;
}
Time.prototype.isAbsolute = false;
Time.prototype.isRelative = false;
interface TimeLike {
hour : number;
minute : number;
second : number;
}
export class AbsoluteTime extends Time {
hour : number;
minute : number;
second : number;
constructor(hour : number, minute : number, second : number) {
super();
assert(typeof hour === 'number' && Number.isFinite(hour));
this.hour = hour;
assert(typeof minute === 'number' && Number.isFinite(minute));
this.minute = minute;
assert(typeof second === 'number' && Number.isFinite(second));
this.second = second;
}
toEntity() : TimeEntity {
return { hour: this.hour, minute: this.minute, second: this.second };
}
toSource() : TokenStream {
return List.singleton(new ConstantToken('TIME', this.toEntity()));
}
clone() : AbsoluteTime {
return new AbsoluteTime(this.hour, this.minute, this.second);
}
equals(other : unknown) : boolean {
return other instanceof AbsoluteTime && this.hour === other.hour
&& this.minute === other.minute && this.second === other.second;
}
static fromJS(v : string|TimeLike) : AbsoluteTime {
if (typeof v === 'string') {
const [hourstr, minutestr, secondstr] = v.split(':');
const hour = parseInt(hourstr);
const minute = parseInt(minutestr);
let second : number;
if (secondstr === undefined)
second = 0;
else
second = parseInt(secondstr);
return new AbsoluteTime(hour, minute, second);
} else {
return new AbsoluteTime(v.hour, v.minute, v.second);
}
}
toJS() : builtin.Time {
return new builtin.Time(this.hour, this.minute, this.second);
}
}
AbsoluteTime.prototype.isAbsolute = true;
Time.Absolute = AbsoluteTime;
export class RelativeTime extends Time {
relativeTag : string;
constructor(relativeTag : string) {
super();
assert(typeof relativeTag === 'string');
this.relativeTag = relativeTag;
}
toEntity() : TimeEntity {
throw new Error('Value is not an entity');
}
toSource() : TokenStream {
return List.concat('$time', '.', this.relativeTag);
}
clone() : RelativeTime {
return new RelativeTime(this.relativeTag);
}
equals(other : unknown) : boolean {
return other instanceof RelativeTime && this.relativeTag === other.relativeTag;
}
}
RelativeTime.prototype.isRelative = true;
Time.Relative = RelativeTime;
/**
* An AST node that represents a scalar value.
*
* This could be a constant, a slot-filling placeholder, the name of a variable in scope,
* a compound type expression (array or object literal) or a computation expression.
*
* Note that AST node representations are different from runtime representations
* (in {@link Builtin}. AST nodes carry type information, can carry
* additional information that might not be available at runtime, and can represent
* unspecified or unresolved values. Code using the library to manipulate programs statically
* will make use of this class, while code using the library to implement or call Thingpedia
* functions will make use of the runtime representations.
*
*/
export abstract class Value extends AstNode {
static Boolean : typeof BooleanValue;
isBoolean ! : boolean;
static String : typeof StringValue;
isString ! : boolean;
static Number : typeof NumberValue;
isNumber ! : boolean;
static Currency : typeof CurrencyValue;
isCurrency ! : boolean;
static Entity : typeof EntityValue;
isEntity ! : boolean;
static Measure : typeof MeasureValue;
isMeasure ! : boolean;
static Enum : typeof EnumValue;
isEnum ! : boolean;
static Time : typeof TimeValue;
isTime ! : boolean;
static Date : typeof DateValue;
isDate ! : boolean;
static Location : typeof LocationValue;
isLocation ! : boolean;
static RecurrentTimeSpecification : typeof RecurrentTimeSpecificationValue;
isRecurrentTimeSpecification ! : boolean;
static ArgMap : typeof ArgMapValue;
isArgMap ! : boolean;
static Array : typeof ArrayValue;
isArray ! : boolean;
static Object : typeof ObjectValue;
isObject ! : boolean;
static VarRef : typeof VarRefValue;
isVarRef ! : boolean;
static Event : typeof EventValue;
isEvent ! : boolean;
static ContextRef : typeof ContextRefValue;
isContextRef ! : boolean;
static Undefined : typeof UndefinedValue;
isUndefined ! : boolean;
static Filter : typeof FilterValue;
isFilter ! : boolean;
static ArrayField : typeof ArrayFieldValue;
isArrayField ! : boolean;
static Computation : typeof ComputationValue;
isComputation ! : boolean;
get priority() : SyntaxPriority {
return SyntaxPriority.Primary;
}
abstract clone() : Value;
/**
* Check if two Value nodes represent the same ThingTalk value.
*
* It is an error to call this method with a parameter that is not an Ast.Value
*
* @param other - the other value to compare
* @return true if equal, false otherwise
*/
abstract equals(other : Value) : boolean;
/**
* Convert a normalized JS value to the corresponding AST node.
*
* This is the inverse operation of {@link Ast.Value.toJS}.
*
* @param type - the ThingTalk type
* @param v - the JS value to convert
* @return the converted value
*/
static fromJS(type : Type, v : unknown) : Value {
if (type.isBoolean)
return new Value.Boolean(v as boolean);
if (type.isString)
return new Value.String(v as string);
if (type.isNumber)
return new Value.Number(v as number);
if (type.isCurrency) {
if (typeof v === 'number')
return new Value.Currency(v, 'usd');
const o = v as ({ value : number, code : string });
return new Value.Currency(o.value, o.code);
}
if (type instanceof EntityType) {
if (typeof v === 'string')
return new Value.Entity(v, type.type, null);
const o = v as ({ value : string, display : string|null|undefined });
return new Value.Entity(o.value, type.type, o.display||null);
}
if (type instanceof MeasureType)
return new Value.Measure(v as number, type.unit);
if (type.isEnum)
return new Value.Enum(v as string);
if (type.isTime)
return new Value.Time(AbsoluteTime.fromJS(v as string|TimeLike));
if (type.isDate)
return new Value.Date(v as Date);
if (type.isLocation) {
const o = v as ({ x : number, y : number, display : string|null|undefined });
return new Value.Location(new Location.Absolute(o.y, o.x, o.display||null));
}
if (type.isRecurrentTimeSpecification) {
const o = v as builtin.RecurrentTimeRuleLike[];
return new Value.RecurrentTimeSpecification(o.map((r) => RecurrentTimeRule.fromJS(r)));
}
if (type.isArgMap) {
const map : TypeMap = {};
Object.entries(v as ({ [key : string] : string })).forEach(([key, value]) => {
map[key] = Type.fromString(value as string);
});
return new Value.ArgMap(map);
}
if (type instanceof ArrayType) {
const array : Value[] = [];
(v as unknown[]).forEach((elem) => {
array.push(Value.fromJS(type.elem as Type, elem));
});
return new Value.Array(array);
}
throw new TypeError('Invalid type ' + type);
}
/**
* Convert a normalized JSON value to the corresponding AST node.
*
* This is similar to {@link Ast.Value.fromJS} but handles JSON
* serialization of Date values.
*
* @param type - the ThingTalk type
* @param v - the JSON value to convert
* @return the converted value
*/
static fromJSON(type : Type, v : unknown) : Value {
if (type.isDate) {
if (v === null)
return new Value.Date(null);
const date = new Date(v as string|number);
return new Value.Date(date);
} else {
return Value.fromJS(type, v);
}
}
/**
* Retrieve the ThingTalk type of this value.
*
* @return the type
*/
abstract getType() : Type;
/**
* Check if this AST node represent concrete (compilable) value.
*
* Values that are not concrete require normalization by the dialog agent
* (such as entity or location resolution) before a program using them
* is compiled and executed.
*
* @return {boolean} whether the value is concrete
*/
isConcrete() : boolean {
return true;
}
/**
* Check if this AST node represent a compile-time constant value.
*
* Certain expressions in ThingTalk must be constant.
*
* @return {boolean} whether the value is constant
*/
isConstant() : boolean {
return this.isConcrete();
}
/**
* Normalize this AST value and convert it to JS-friendly representation.
*
* This converts the AST representation to something that can be passed to
* a Thingpedia function. Note that the conversion is lossy and loses type
* information.
*
* @return {any} the normlized value
*/
toJS() : unknown {
throw new Error('Value is not a constant');
}
/**
* Convert this AST node to an entity that can be extracted from a sentence.
*/
toEntity() : AnyEntity {
throw new Error('Value is not an entity');
}
}
Value.prototype.isBoolean = false;
Value.prototype.isString = false;
Value.prototype.isNumber = false;
Value.prototype.isCurrency = false;
Value.prototype.isEntity = false;
Value.prototype.isMeasure = false;
Value.prototype.isEnum = false;
Value.prototype.isTime = false;
Value.prototype.isDate = false;
Value.prototype.isLocation = false;
Value.prototype.isRecurrentTimeSpecification = false;
Value.prototype.isArgMap = false;
Value.prototype.isArray = false;
Value.prototype.isObject = false;
Value.prototype.isVarRef = false;
Value.prototype.isEvent = false;
Value.prototype.isContextRef = false;
Value.prototype.isUndefined = false;
Value.prototype.isFilter = false;
Value.prototype.isArrayField = false;
Value.prototype.isComputation = false;
export class ArrayValue extends Value {
value : Value[];
type : Type|null;
constructor(value : Value[], type : Type|null = null) {
super(null);
assert(Array.isArray(value));
this.value = value;
assert(type === null || type instanceof Type);
this.type = type;
}
toSource() : TokenStream {
return List.concat('[', List.join(this.value.map((v) => v.toSource()), ','), ']');
}
toString() : string {
return `Array(${this.value})`;
}
clone() : ArrayValue {
return new ArrayValue(this.value.map((v) => v.clone()), this.type);
}
equals(other : Value) : boolean {
return other instanceof ArrayValue && this.value.length === other.value.length
&& this.value.every((v, i) => v.equals(other.value[i]));
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitValue(this) && visitor.visitArrayValue(this)) {
for (const v of this.value)
v.visit(visitor);
}
visitor.exit(this);
}
isConstant() : boolean {
return this.value.every((v) => v.isConstant());
}
toJS() : unknown[] {
return this.value.map((v) => v.toJS());
}
getType() : Type {
if (this.type)
return this.type;
return new Type.Array(this.value.length ? this.value[0].getType() : Type.Any);
}
}
ArrayValue.prototype.isArray = true;
Value.Array = ArrayValue;
export class VarRefValue extends Value {
name : string;
type : Type|null;
constructor(name : string, type : Type|null = null) {
super(null);
assert(typeof name === 'string');
this.name = name;
assert(type === null || type instanceof Type);
this.type = type;
}
toSource() : TokenStream {
return List.join(this.name.split('.').map((n) => List.singleton(n)), '.');
}
toString() : string {
return `VarRef(${this.name})`;
}
clone() : VarRefValue {
return new VarRefValue(this.name, this.type);
}
equals(other : Value) : boolean {
return other instanceof VarRefValue && this.name === other.name;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitVarRefValue(this);
visitor.exit(this);
}
isConstant() : boolean {
return this.name.startsWith('__const_');
}
getType() : Type {
if (this.type)
return this.type;
if (this.name.startsWith('__const_'))
return typeForConstant(this.name);
return Type.Any;
}
}
VarRefValue.prototype.isVarRef = true;
Value.VarRef = VarRefValue;
const OperatorPriority : { [key : string] : SyntaxPriority } = {
'+': SyntaxPriority.Add,
'-': SyntaxPriority.Add,
'*': SyntaxPriority.Mul,
'/': SyntaxPriority.Mul,
'%': SyntaxPriority.Mul,
'**': SyntaxPriority.Exp
};
export class ComputationValue extends Value {
op : string;
operands : Value[];
overload : Type[]|null;
type : Type|null;
constructor(op : string,
operands : Value[],
overload : Type[]|null = null,
type : Type|null = null) {
super(null);
assert(typeof op === 'string');
this.op = op;
assert(Array.isArray(operands));
this.operands = operands;
assert(overload === null || Array.isArray(overload));
this.overload = overload;
assert(type === null || type instanceof Type);
this.type = type;
}
get priority() : SyntaxPriority {
return OperatorPriority[this.op] || SyntaxPriority.Primary;
}
toSource() : TokenStream {
const priority = OperatorPriority[this.op];
if (priority === undefined) {
// not an infix operator
return List.concat(this.op, '(', List.join(this.operands.map((v) => v.toSource()), ','), ')');
}
assert(this.operands.length === 2);
const [lhs, rhs] = this.operands;
return List.concat(addParenthesis(priority, lhs.priority, lhs.toSource()),
this.op, addParenthesis(priority, rhs.priority, rhs.toSource()));
}
toString() : string {
return `Computation(${this.op}, ${this.operands})`;
}
clone() : ComputationValue {
return new ComputationValue(this.op, this.operands.map((v) => v.clone()), this.overload, this.type);
}
equals(other : Value) : boolean {
return other instanceof ComputationValue && this.op === other.op &&
this.operands.length === other.operands.length &&
this.operands.every((op, i) => op.equals(other.operands[i]));
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitValue(this) && visitor.visitComputationValue(this)) {
for (const v of this.operands)
v.visit(visitor);
}
visitor.exit(this);
}
isConstant() : boolean {
return false;
}
getType() : Type {
if (this.type)
return this.type;
return Type.Any;
}
}
ComputationValue.prototype.isComputation = true;
Value.Computation = ComputationValue;
export class ArrayFieldValue extends Value {
value : Value;
field : string;
type : Type|null;
arg : ArgumentDef|null;
constructor(value : Value,
field : string,
type : Type|null = null,
arg : ArgumentDef|null = null) {
super(null);
assert(value instanceof Value);
this.value = value;
assert(typeof field === 'string');
this.field = field;
assert(type === null || type instanceof Type);
this.type = type;
this.arg = arg;
}
get priority() : SyntaxPriority {
return SyntaxPriority.ArrayField;
}
toSource() : TokenStream {
return List.concat(this.field, 'of', addParenthesis(this.priority, this.value.priority, this.value.toSource()));
}
toString() : string {
return `ArrayField(${this.value}, ${this.field})`;
}
clone() : ArrayFieldValue {
return new ArrayFieldValue(this.value.clone(), this.field, this.type, this.arg);
}
equals(other : Value) : boolean {
return other instanceof ArrayFieldValue && this.value.equals(other.value) &&
this.field === other.field;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitValue(this) && visitor.visitArrayFieldValue(this))
this.value.visit(visitor);
visitor.exit(this);
}
isConstant() : boolean {
return false;
}
toJS() : unknown[] {
return (this.value.toJS() as any[]).map((el) => el[this.field]);
}
getType() : Type {
if (this.type)
return this.type;
return Type.Any;
}
}
ArrayFieldValue.prototype.isArrayField = true;
Value.ArrayField = ArrayFieldValue;
export class FilterValue extends Value {
value : Value;
filter : BooleanExpression;
type : Type|null;
constructor(value : Value, filter : BooleanExpression, type : Type|null = null) {
super(null);
assert(value instanceof Value);
this.value = value;
this.filter = filter;
assert(type === null || type instanceof Type);
this.type = type;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Filter;
}
toSource() : TokenStream {
// note: the filter is parenthesized if it is a lower priority than a comparison
// (ie an "or" or "and")
return List.concat(addParenthesis(this.priority, this.value.priority, this.value.toSource()),
'filter', addParenthesis(SyntaxPriority.Comp, this.filter.priority, this.filter.toSource()));
}
toString() : string {
return `Filter(${this.value}, ${this.filter})`;
}
clone() : FilterValue {
return new FilterValue(this.value.clone(), this.filter.clone(), this.type);
}
equals(other : Value) : boolean {
return other instanceof FilterValue && this.value.equals(other.value) &&
this.filter.equals(other.filter);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitValue(this) && visitor.visitFilterValue(this))
this.value.visit(visitor);
visitor.exit(this);
}
isConstant() : boolean {
return false;
}
getType() : Type {
if (this.type)
return this.type;
return Type.Any;
}
}
FilterValue.prototype.isFilter = true;
Value.Filter = FilterValue;
/**
* A special placeholder for values that must be slot-filled.
*/
export class UndefinedValue extends Value {
local : boolean;
constructor(local = true) {
super(null);
assert(local === true || local === false);
this.local = local;
}
toSource() : TokenStream {
return List.singleton('$?');
}
toString() : string {
return `Undefined(${this.local})`;
}
clone() : UndefinedValue {
return new UndefinedValue(this.local);
}
equals(other : Value) : boolean {
return other instanceof UndefinedValue && this.local === other.local;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitUndefinedValue(this);
visitor.exit(this);
}
isConstant() : boolean {
return false;
}
getType() : Type {
return Type.Any;
}
}
UndefinedValue.prototype.isUndefined = true;
Value.Undefined = UndefinedValue;
export class ContextRefValue extends Value {
name : string;
type : Type;
constructor(name : string, type : Type) {
super(null);
assert(typeof name === 'string');
this.name = name;
assert(type instanceof Type);
this.type = type;
}
toSource() : TokenStream {
return List.concat('$context', '.',
List.join(this.name.split('.').map((n) => List.singleton(n)), '.'),
':', this.type.toSource());
}
toString() : string {
return `ContextRef(${this.name}, ${this.type})`;
}
clone() : ContextRefValue {
return new ContextRefValue(this.name, this.type);
}
equals(other : Value) : boolean {
return other instanceof ContextRefValue && this.name === other.name;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitContextRefValue(this);
visitor.exit(this);
}
isConstant() : boolean {
return false;
}
isConcrete() : boolean {
return false;
}
getType() : Type {
return this.type;
}
}
ContextRefValue.prototype.isContextRef = true;
Value.ContextRef = ContextRefValue;
export class BooleanValue extends Value {
value : boolean;
constructor(value : boolean) {
super(null);
assert(typeof value === 'boolean');
this.value = value;
}
toSource() : TokenStream {
return List.singleton(String(this.value));
}
toString() : string {
return `Boolean(${this.value})`;
}
clone() : BooleanValue {
return new BooleanValue(this.value);
}
equals(other : Value) : boolean {
return other instanceof BooleanValue && this.value === other.value;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitBooleanValue(this);
visitor.exit(this);
}
toJS() : boolean {
return this.value;
}
getType() : Type {
return Type.Boolean;
}
}
BooleanValue.prototype.isBoolean = true;
Value.Boolean = BooleanValue;
export class StringValue extends Value {
value : string;
constructor(value : string) {
super(null);
assert(typeof value === 'string');
this.value = value;
}
toEntity() : string {
return this.value;
}
toSource() : TokenStream {
return List.singleton(new ConstantToken('QUOTED_STRING', this.value));
}
toString() : string {
return `String(${this.value})`;
}
clone() : StringValue {
return new StringValue(this.value);
}
equals(other : Value) : boolean {
return other instanceof StringValue && this.value === other.value;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitStringValue(this);
visitor.exit(this);
}
toJS() : string {
return this.value;
}
getType() : Type {
return Type.String;
}
}
StringValue.prototype.isString = true;
Value.String = StringValue;
export class NumberValue extends Value {
value : number;
constructor(value : number) {
super(null);
assert(typeof value === 'number');
this.value = value;
}
toEntity() : number {
return this.value;
}
toSource() : TokenStream {
return List.singleton(new ConstantToken('NUMBER', this.value));
}
toString() : string {
return `Number(${this.value})`;
}
clone() : NumberValue {
return new NumberValue(this.value);
}
equals(other : Value) : boolean {
return other instanceof NumberValue && this.value === other.value;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitNumberValue(this);
visitor.exit(this);
}
toJS() : number {
return this.value;
}
getType() : Type {
return Type.Number;
}
}
NumberValue.prototype.isNumber = true;
Value.Number = NumberValue;
export class MeasureValue extends Value {
value : number;
unit : string;
constructor(value : number, unit : string) {
super(null);
assert(typeof value === 'number');
this.value = value;
assert(typeof unit === 'string');
this.unit = unit;
}
toEntity() : MeasureEntity {
return { unit: this.unit, value: this.value };
}
toSource() : TokenStream {
return List.singleton(new ConstantToken('MEASURE', this.toEntity()));
}
toString() : string {
return `Measure(${this.value}, ${this.unit})`;
}
clone() : MeasureValue {
return new MeasureValue(this.value, this.unit);
}
equals(other : Value) : boolean {
return other instanceof MeasureValue && this.value === other.value
&& this.unit === other.unit;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitMeasureValue(this);
visitor.exit(this);
}
isConcrete() : boolean {
return !this.unit.startsWith("default");
}
toJS() : number {
return Units.transformToBaseUnit(this.value, this.unit);
}
getType() : Type {
return new Type.Measure(this.unit);
}
}
MeasureValue.prototype.isMeasure = true;
Value.Measure = MeasureValue;
export class CurrencyValue extends Value {
value : number;
code : string;
constructor(value : number, code : string) {
super(null);
assert(typeof value === 'number');
this.value = value;
assert(typeof code === 'string');
this.code = code;
}
toEntity() : MeasureEntity {
return { unit: this.code, value: this.value };
}
toSource() : TokenStream {
return List.singleton(new ConstantToken('CURRENCY', this.toEntity()));
}
toString() : string {
return `Currency(${this.value}, ${this.code})`;
}
clone() : CurrencyValue {
return new CurrencyValue(this.value, this.code);
}
equals(other : Value) : boolean {
return other instanceof CurrencyValue && this.value === other.value
&& this.code === other.code;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitCurrencyValue(this);
visitor.exit(this);
}
toJS() : builtin.Currency {
return new builtin.Currency(this.value, this.code);
}
getType() : Type {
return Type.Currency;
}
}
CurrencyValue.prototype.isCurrency = true;
Value.Currency = CurrencyValue;
export class LocationValue extends Value {
value : Location;
constructor(value : Location) {
super(null);
assert(value instanceof Location);
this.value = value;
}
toEntity() : LocationEntity {
return this.value.toEntity();
}
toSource() : TokenStream {
return this.value.toSource();
}
toString() : string {
return `Location(${this.value})`;
}
clone() : LocationValue {
return new LocationValue(this.value.clone());
}
equals(other : Value) : boolean {
return other instanceof LocationValue && this.value.equals(other.value);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitLocationValue(this);
visitor.exit(this);
}
isConstant() : boolean {
// a relative location is considered a constant, even though it is not concrete
return true;
}
isConcrete() : boolean {
return this.value instanceof AbsoluteLocation;
}
toJS() : builtin.Location {
if (this.value instanceof AbsoluteLocation)
return new builtin.Location(this.value.lat, this.value.lon, this.value.display);
else
throw new TypeError('Location ' + this + ' is unknown');
}
getType() : Type {
return Type.Location;
}
}
LocationValue.prototype.isLocation = true;
Value.Location = LocationValue;
type DateLike = Date | DateEdge | DatePiece | WeekDayDate;
function isValidDate(value : unknown) : boolean {
return value instanceof Date
|| value instanceof DateEdge
|| value instanceof DatePiece
|| value instanceof WeekDayDate;
}
function dateEquals(a : DateLike|null, b : DateLike|null) : boolean {
if (a === null)
return b === null;
if (a instanceof Date)
return b instanceof Date && +a === +b;
return a.equals(b);
}
function dateToSource(date : DateLike) : TokenStream {
if (date instanceof Date)
return List.singleton(new ConstantToken('DATE', date));
return date.toSource();
}
export class DateValue extends Value {
value : DateLike|null;
constructor(value : DateLike|null) {
super(null);
assert(value === null || isValidDate(value));
// a DatePiece with non-null year is actually a fully specified date
if (value instanceof DatePiece && value.year !== null) {
let hour = 0, minute = 0, second = 0;
if (value.time) {
hour = value.time.hour;
minute = value.time.minute;
second = value.time.second;
}
value = new Date(value.year, value.month !== null ? value.month-1 : 0, value.day !== null ? value.day : 1,
hour, minute, second);
}
this.value = value;
}
static now() : DateValue {
return new DateValue(null);
}
toEntity() : Date {
if (this.value instanceof Date)
return this.value;
else
throw new Error('Value is not an entity');
}
toSource() : TokenStream {
if (this.value === null)
return List.singleton('$now');
return dateToSource(this.value);
}
toString() : string {
return `Date(${this.value})`;
}
clone() : DateValue {
return new DateValue(this.value);
}
equals(other : Value) : boolean {
if (!(other instanceof DateValue))
return false;
return dateEquals(this.value, other.value);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitDateValue(this);
visitor.exit(this);
}
toJS() : Date {
return normalizeDate(this.value);
}
getType() : Type {
return Type.Date;
}
}
DateValue.prototype.isDate = true;
Value.Date = DateValue;
export class TimeValue extends Value {
value : Time;
constructor(value : Time) {
super(null);
assert(value instanceof Time);
this.value = value;
}
toEntity() : TimeEntity {
return this.value.toEntity();
}
toSource() : TokenStream {
return this.value.toSource();
}
toString() : string {
return `Time(${this.value})`;
}
clone() : TimeValue {
return new TimeValue(this.value.clone());
}
equals(other : Value) : boolean {
return other instanceof TimeValue && this.value.equals(other.value);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitTimeValue(this);
visitor.exit(this);
}
isConstant() : boolean {
// a relative time is considered a constant, even though it is not concrete
return true;
}
isConcrete() : boolean {
return this.value instanceof AbsoluteTime;
}
toJS() : builtin.Time {
if (this.value instanceof AbsoluteTime)
return this.value.toJS();
else
throw new TypeError('Time is unknown');
}
getType() : Type {
return Type.Time;
}
}
TimeValue.prototype.isTime = true;
Value.Time = TimeValue;
interface RecurrentTimeRuleLike {
beginTime : AbsoluteTime;
endTime : AbsoluteTime;
interval : MeasureValue;
frequency : number;
dayOfWeek : string|null;
beginDate : DateLike|null;
endDate : DateLike|null;
subtract : boolean;
}
/**
* An AST node representing a single rule for a recurrent event.
*
*/
export class RecurrentTimeRule extends AstNode {
beginTime : AbsoluteTime;
endTime : AbsoluteTime;
interval : MeasureValue;
frequency : number;
dayOfWeek : string|null;
beginDate : DateLike|null;
endDate : DateLike|null;
subtract : boolean;
constructor({ beginTime, endTime,
interval = new MeasureValue(1, 'day'),
frequency = 1,
dayOfWeek = null,
beginDate = null,
endDate = null,
subtract = false
} : RecurrentTimeRuleLike) {
super(null);
assert(beginTime instanceof AbsoluteTime);
assert(endTime instanceof AbsoluteTime);
assert(interval instanceof MeasureValue);
assert(typeof frequency === 'number');
assert(dayOfWeek === null || typeof dayOfWeek === 'string');
assert(beginDate === null || isValidDate(beginDate));
assert(endDate === null || isValidDate(endDate));
assert(typeof subtract === 'boolean');
this.beginTime = beginTime;
this.endTime = endTime;
this.interval = interval;
this.frequency = frequency;
this.dayOfWeek = dayOfWeek;
this.beginDate = beginDate;
this.endDate = endDate;
this.subtract = subtract;
}
toSource() : TokenStream {
let src = List.concat('{', ' ',
'beginTime', '=', this.beginTime.toSource(), ',',
'endTime', '=', this.endTime.toSource());
if (this.interval.value !== 1 || this.interval.unit !== 'day')
src = List.concat(src, ',', 'interval', '=', this.interval.toSource());
if (this.frequency !== 1)
src = List.concat(src, ',', 'frequency', '=', new ConstantToken('NUMBER', this.frequency));
if (this.dayOfWeek !== null)
src = List.concat(src, ',', 'dayOfWeek', '=', 'enum', this.dayOfWeek);
if (this.beginDate !== null)
src = List.concat(src, ',', 'beginDate', '=', dateToSource(this.beginDate));
if (this.endDate !== null)
src = List.concat(src, ',', 'endDate', '=', dateToSource(this.endDate));
if (this.subtract)
src = List.concat(src, ',', 'subtract', '=', 'true');
src = List.concat(src, ' ', '}');
return src;
}
toString() : string {
return `RecurrentTimeRule(${this.subtract ? 'subtract' : 'add'} ${this.beginTime} -- ${this.endTime}; ${this.frequency} every ${this.interval}; from ${this.beginDate} to ${this.endDate})`;
}
clone() : RecurrentTimeRule {
return new RecurrentTimeRule(this);
}
equals(other : RecurrentTimeRule) : boolean {
return this.beginTime.equals(other.beginTime) &&
this.endTime.equals(other.endTime) &&
this.interval.equals(other.interval) &&
this.frequency === other.frequency &&
this.dayOfWeek === other.dayOfWeek &&
dateEquals(this.beginDate, other.beginDate) &&
dateEquals(this.endDate, other.endDate);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitRecurrentTimeRule(this))
this.interval.visit(visitor);
visitor.exit(this);
}
static fromJS(v : builtin.RecurrentTimeRuleLike) : RecurrentTimeRule {
return new RecurrentTimeRule({
beginTime: AbsoluteTime.fromJS(v.beginTime),
endTime: AbsoluteTime.fromJS(v.endTime),
interval: new MeasureValue(v.interval, 'ms'),
frequency: v.frequency,
dayOfWeek: v.dayOfWeek !== null ? ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'][v.dayOfWeek] : null,
beginDate: v.beginDate,
endDate: v.endDate,
subtract: v.subtract,
});
}
toJS() : builtin.RecurrentTimeRule {
return new builtin.RecurrentTimeRule({
beginTime: this.beginTime.toJS(),
endTime: this.endTime.toJS(),
interval: this.interval.toJS(),
frequency: this.frequency,
dayOfWeek: this.dayOfWeek ? ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'].indexOf(this.dayOfWeek) : null,
beginDate: this.beginDate ? normalizeDate(this.beginDate) : null,
endDate: this.endDate ? normalizeDate(this.endDate) : null,
subtract: this.subtract
});
}
}
export class RecurrentTimeSpecificationValue extends Value {
rules : RecurrentTimeRule[];
constructor(rules : RecurrentTimeRule[]) {
super(null);
this.rules = rules;
}
toSource() : TokenStream {
return List.concat('new', 'RecurrentTimeSpecification', '(',
List.join(this.rules.map((r) => r.toSource()), ','), ')');
}
toString() : string {
return `RecurrentTimeSpec([${this.rules.join(', ')}])`;
}
clone() : RecurrentTimeSpecificationValue {
return new RecurrentTimeSpecificationValue(this.rules.map((r) => r.clone()));
}
equals(other : Value) : boolean {
return other instanceof RecurrentTimeSpecificationValue
&& this.rules.length === other.rules.length
&& this.rules.every((v, i) => v.equals(other.rules[i]));
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitValue(this) && visitor.visitRecurrentTimeSpecificationValue(this)) {
for (const rule of this.rules)
rule.visit(visitor);
}
visitor.exit(this);
}
toJS() : builtin.RecurrentTimeRule[] {
return this.rules.map((r) => r.toJS());
}
getType() : Type {
return Type.RecurrentTimeSpecification;
}
}
RecurrentTimeSpecificationValue.prototype.isRecurrentTimeSpecification = true;
Value.RecurrentTimeSpecification = RecurrentTimeSpecificationValue;
export class EntityValue extends Value {
value : string|null;
type : string;
display : string|null;
constructor(value : string|null, type : string, display : string|null = null) {
super(null);
assert(value === null || typeof value === 'string');
this.value = value;
assert(typeof type === 'string');
this.type = type;
assert(display === null || typeof display === 'string');
this.display = display;
}
toEntity() : GenericEntity|string {
if (!this.value)
return { value: this.value, display: this.display };
switch (this.type) {
case 'tt:picture':
case 'tt:username':
case 'tt:hashtag':
case 'tt:url':
case 'tt:phone_number':
case 'tt:email_address':
case 'tt:path_name':
return this.value;
default:
return { value: this.value, display: this.display };
}
}
toSource() : TokenStream {
if (!this.value)
return List.singleton(new ConstantToken('GENERIC_ENTITY', this));
switch (this.type) {
case 'tt:picture':
return List.singleton(new ConstantToken('PICTURE', this.value));
case 'tt:username':
return List.singleton(new ConstantToken('USERNAME', this.value));
case 'tt:hashtag':
return List.singleton(new ConstantToken('HASHTAG', this.value));
case 'tt:url':
return List.singleton(new ConstantToken('URL', this.value));
case 'tt:phone_number':
return List.singleton(new ConstantToken('PHONE_NUMBER', this.value));
case 'tt:email_address':
return List.singleton(new ConstantToken('EMAIL_ADDRESS', this.value));
case 'tt:path_name':
return List.singleton(new ConstantToken('PATH_NAME', this.value));
default:
return List.singleton(new ConstantToken('GENERIC_ENTITY', this));
}
}
toString() : string {
return `Entity(${this.value}, ${this.type}, ${this.display})`;
}
clone() : EntityValue {
return new EntityValue(this.value, this.type, this.display);
}
equals(other : Value) : boolean {
return other instanceof EntityValue && this.value === other.value && this.type === other.type;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitEntityValue(this);
visitor.exit(this);
}
isConcrete() : boolean {
return this.value !== null;
}
toJS() : builtin.Entity {
assert(this.value !== null);
return new builtin.Entity(this.value, this.display);
}
getType() : Type {
return new Type.Entity(this.type);
}
}
EntityValue.prototype.isEntity = true;
Value.Entity = EntityValue;
export class EnumValue extends Value {
value : string;
constructor(value : string) {
super(null);
assert(typeof value === 'string');
this.value = value;
}
toSource() : TokenStream {
return List.concat('enum', this.value);
}
toString() : string {
return `Enum(${this.value})`;
}
clone() : EnumValue {
return new EnumValue(this.value);
}
equals(other : Value) : boolean {
return other instanceof EnumValue && this.value === other.value;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitEnumValue(this);
visitor.exit(this);
}
toJS() : string {
return this.value;
}
getType() : Type {
return new Type.Enum([this.value, '*']);
}
}
EnumValue.prototype.isEnum = true;
Value.Enum = EnumValue;
export class EventValue extends Value {
name : string|null;
constructor(name : string|null) {
super(null);
assert(name === null || typeof name === 'string');
this.name = name;
}
toSource() : TokenStream {
if (this.name === null)
return List.singleton('$result');
else
return List.concat('$' + this.name);
}
toString() : string {
return `Event(${this.name})`;
}
clone() : EventValue {
return new EventValue(this.name);
}
equals(other : Value) : boolean {
return other instanceof EventValue && this.name === other.name;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitEventValue(this);
visitor.exit(this);
}
isConstant() : boolean {
return false;
}
getType() : Type {
switch (this.name) {
case 'type':
return new Type.Entity('tt:function');
case 'program_id':
return new Type.Entity('tt:program_id');
case 'source':
return new Type.Entity('tt:contact');
default:
return Type.String;
}
}
}
EventValue.prototype.isEvent = true;
Value.Event = EventValue;
export class ArgMapValue extends Value {
value : TypeMap;
constructor(value : TypeMap) {
super(null);
assert(typeof value === 'object');
this.value = value;
}
toSource() : TokenStream {
return List.concat('new', 'ArgMap', '(',
List.join(Object.entries(this.value).map(([name, type])=> List.concat(name, ':' + type.toString())), ','),
')');
}
toString() : string {
return `ArgMap(${this.value})`;
}
clone() : ArgMapValue {
const clone : TypeMap = {};
for (const key in this.value)
clone[key] = this.value[key];
return new ArgMapValue(clone);
}
equals(other : Value) : boolean {
if (!(other instanceof ArgMapValue))
return false;
const k1 = Object.keys(this.value);
const k2 = Object.keys(other.value);
if (k1.length !== k2.length)
return false;
for (const key of k1) {
if (!other.value[key] || this.value[key].equals(other.value[key]))
return false;
}
return true;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitValue(this) && visitor.visitArgMapValue(this);
visitor.exit(this);
}
toJS() : TypeMap {
return this.value;
}
getType() : Type {
return Type.ArgMap;
}
}
ArgMapValue.prototype.isArgMap = true;
Value.ArgMap = ArgMapValue;
export class ObjectValue extends Value {
value : ({ [key : string] : Value });
type : Type|null;
constructor(value : ({ [key : string] : Value }), type : Type|null = null) {
super(null);
assert(typeof value === 'object');
this.value = value;
assert(type === null || type instanceof Type);
this.type = type;
}
toSource() : TokenStream {
const entries : Array<[string, Value]> = Object.entries(this.value);
if (entries.length > 0) {
return List.concat('{', ' ',
List.join(entries.map(([name, value])=> List.concat(name, '=', value.toSource())), ','),
' ', '}');
} else {
return List.concat('{', '}');
}
}
toString() : string {
return `Object(${this.value})`;
}
clone() : ObjectValue {
const clone : ({ [key : string] : Value }) = {};
for (const key in this.value)
clone[key] = this.value[key].clone();
return new ObjectValue(clone, this.type);
}
equals(other : Value) : boolean {
if (!(other instanceof ObjectValue))
return false;
const k1 = Object.keys(this.value);
const k2 = Object.keys(other.value);
if (k1.length !== k2.length)
return false;
for (const key of k1) {
if (!other.value[key] || this.value[key].equals(other.value[key]))
return false;
}
return true;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitValue(this) && visitor.visitObjectValue(this)) {
for (const key in this.value)
this.value[key].visit(visitor);
}
visitor.exit(this);
}
isConstant() : boolean {
return Object.values(this.value).every((v) => v.isConstant());
}
toJS() : ({ [key : string] : unknown }) {
const obj : ({ [key : string] : unknown }) = {};
Object.entries(this.value).forEach(([key, value]) => {
obj[key] = value.toJS();
});
return obj;
}
getType() : Type {
if (this.type)
return this.type;
return Type.Object;
}
}
ObjectValue.prototype.isObject = true;
Value.Object = ObjectValue;
function unescape(symbol : string) : string {
return symbol.replace(/_([0-9a-fA-Z]{2}|_)/g, (match : string, ch : string) => {
if (ch === '_') return ch;
return String.fromCharCode(parseInt(ch, 16));
});
}
const TYPES : ({ [key : string] : Type }) = {
QUOTED_STRING: Type.String,
NUMBER: Type.Number,
CURRENCY: Type.Currency,
DURATION: new Type.Measure('ms'),
LOCATION: Type.Location,
DATE: Type.Date,
TIME: Type.Time,
EMAIL_ADDRESS: new Type.Entity('tt:email_address'),
PHONE_NUMBER: new Type.Entity('tt:phone_number'),
HASHTAG: new Type.Entity('tt:hashtag'),
USERNAME: new Type.Entity('tt:username'),
URL: new Type.Entity('tt:url'),
PATH_NAME: new Type.Entity('tt:path_name'),
};
function entityTypeToTTType(entityType : string) : Type {
if (entityType.startsWith('GENERIC_ENTITY_'))
return new Type.Entity(entityType.substring('GENERIC_ENTITY_'.length));
else if (entityType.startsWith('MEASURE_'))
return new Type.Measure(entityType.substring('MEASURE_'.length));
else
return TYPES[entityType];
}
function typeForConstant(name : string) : Type {
let measure = /__const_NUMBER_([0-9]+)__([a-z0-9A-Z]+)/.exec(name);
if (measure !== null)
return new Type.Measure(measure[2]);
measure = /__const_MEASURE__([a-z0-9A-Z]+)_([0-9]+)/.exec(name);
if (measure !== null)
return new Type.Measure(measure[1]);
const underscoreindex = name.lastIndexOf('_');
const entitytype = unescape(name.substring('__const_'.length, underscoreindex));
const type = entityTypeToTTType(entitytype);
if (!type)
throw new TypeError(`Invalid __const variable ${name}`);
return type;
} | the_stack |
import { ReflectionClass, ReflectionProperty, typeOf } from '../src/reflection/reflection.js';
import { expect, test } from '@jest/globals';
import { isExtendable } from '../src/reflection/extends.js';
import { stringifyResolvedType } from '../src/reflection/type.js';
export interface OrmEntity {
}
export type FilterQuery<T> = {
[P in keyof T & string]?: T[P];
};
export type Placeholder<T> = () => T;
export type Resolve<T extends { _: Placeholder<any> }> = ReturnType<T['_']>;
export type Replace<T, R> = T & { _: Placeholder<R> };
export type FlattenIfArray<T> = T extends Array<any> ? T[0] : T;
export type FieldName<T> = keyof T & string;
export class DatabaseQueryModel<T extends OrmEntity, FILTER, SORT> {
public withIdentityMap: boolean = true;
public withChangeDetection: boolean = true;
public filter?: FILTER;
public having?: FILTER;
public groupBy: Set<string> = new Set<string>();
public aggregate = new Map<string, { property: ReflectionProperty, func: string }>();
public select: Set<string> = new Set<string>();
public skip?: number;
public itemsPerPage: number = 50;
public limit?: number;
public parameters: { [name: string]: any } = {};
public sort?: SORT;
public returning: (keyof T & string)[] = [];
changed(): void {
}
hasSort(): boolean {
return this.sort !== undefined;
}
/**
* Whether limit/skip is activated.
*/
hasPaging(): boolean {
return this.limit !== undefined || this.skip !== undefined;
}
setParameters(parameters: { [name: string]: any }) {
for (const [i, v] of Object.entries(parameters)) {
this.parameters[i] = v;
}
}
clone(parentQuery: BaseQuery<T>): this {
return this;
}
/**
* Whether only a subset of fields are selected.
*/
isPartial() {
return this.select.size > 0 || this.groupBy.size > 0 || this.aggregate.size > 0;
}
/**
* Whether only a subset of fields are selected.
*/
isAggregate() {
return this.groupBy.size > 0 || this.aggregate.size > 0;
}
getFirstSelect() {
return this.select.values().next().value;
}
isSelected(field: string): boolean {
return this.select.has(field);
}
hasJoins() {
return false;
}
hasParameters(): boolean {
return false;
}
}
export class BaseQuery<T extends OrmEntity> {
//for higher kinded type for selected fields
_!: () => T;
protected createModel<T>() {
return new DatabaseQueryModel<T, T, T>();
}
public model: DatabaseQueryModel<T, T, T>;
constructor(
public readonly classSchema: ReflectionClass<any>,
model?: DatabaseQueryModel<T, T, T>
) {
this.model = model || this.createModel<T>();
}
groupBy<K extends FieldName<T>[]>(...field: K): this {
const c = this.clone();
c.model.groupBy = new Set([...field as string[]]);
return c as any;
}
withSum<K extends FieldName<T>, AS extends string>(field: K, as?: AS): Replace<this, Resolve<this> & { [K in [AS] as `${AS}`]: number }> {
return this.aggregateField(field, 'sum', as) as any;
}
withGroupConcat<K extends FieldName<T>, AS extends string>(field: K, as?: AS): Replace<this, Resolve<this> & { [C in [AS] as `${AS}`]: T[K][] }> {
return this.aggregateField(field, 'group_concat', as);
}
withCount<K extends FieldName<T>, AS extends string>(field: K, as?: AS): Replace<this, Resolve<this> & { [K in [AS] as `${AS}`]: number }> {
return this.aggregateField(field, 'count', as) as any;
}
withMax<K extends FieldName<T>, AS extends string>(field: K, as?: AS): Replace<this, Resolve<this> & { [K in [AS] as `${AS}`]: number }> {
return this.aggregateField(field, 'max', as) as any;
}
withMin<K extends FieldName<T>, AS extends string>(field: K, as?: AS): Replace<this, Resolve<this> & { [K in [AS] as `${AS}`]: number }> {
return this.aggregateField(field, 'min', as) as any;
}
withAverage<K extends FieldName<T>, AS extends string>(field: K, as?: AS): Replace<this, Resolve<this> & { [K in [AS] as `${AS}`]: number }> {
return this.aggregateField(field, 'avg', as) as any;
}
aggregateField<K extends FieldName<T>, AS extends string>(field: K, func: string, as?: AS): Replace<this, Resolve<this> & { [K in [AS] as `${AS}`]: number }> {
throw new Error();
}
select<K extends (keyof Resolve<this>)[]>(...select: K): Replace<this, Pick<Resolve<this>, K[number]>> {
throw new Error();
}
returning(...fields: FieldName<T>[]): this {
throw new Error();
}
skip(value?: number): this {
throw new Error();
}
/**
* Sets the page size when `page(x)` is used.
*/
itemsPerPage(value: number): this {
throw new Error();
}
/**
* Applies limit/skip operations correctly to basically have a paging functionality.
* Make sure to call itemsPerPage() before you call page.
*/
page(page: number): this {
throw new Error();
}
limit(value?: number): this {
throw new Error();
}
parameter(name: string, value: any): this {
throw new Error();
}
parameters(parameters: { [name: string]: any }): this {
throw new Error();
}
disableIdentityMap(): this {
throw new Error();
}
disableChangeDetection(): this {
throw new Error();
}
having(filter?: this['model']['filter']): this {
const c = this.clone();
c.model.having = filter;
return c;
}
filter(filter?: this['model']['filter']): this {
throw new Error();
}
addFilter<K extends keyof T & string>(name: K, value: FilterQuery<T>[K]): this {
throw new Error();
}
sort(sort?: this['model']['sort']): this {
throw new Error();
}
orderBy<K extends FieldName<T>>(field: K, direction: 'asc' | 'desc' = 'asc'): this {
throw new Error();
}
clone(): this {
throw new Error();
}
/**
* Adds a left join in the filter. Does NOT populate the reference with values.
* Accessing `field` in the entity (if not optional field) results in an error.
*/
join<K extends keyof T, ENTITY = FlattenIfArray<T[K]>>(field: K, type: 'left' | 'inner' = 'left', populate: boolean = false): this {
throw new Error();
}
}
export type Methods<T> = { [K in keyof T]: K extends keyof Query<any> ? never : T[K] extends ((...args: any[]) => any) ? K : never }[keyof T];
/**
* This a generic query abstraction which should supports most basics database interactions.
*
* All query implementations should extend this since db agnostic consumers are probably
* coded against this interface via Database<DatabaseAdapter> which uses this GenericQuery.
*/
export class Query<T extends OrmEntity> {
// protected lifts: ClassType[] = [];
//
// static is<T extends ClassType<Query<any>>>(v: Query<any>, type: T): v is InstanceType<T> {
// return v.lifts.includes(type) || v instanceof type;
// }
//
// constructor(
// classSchema: ReflectionClass<T>,
// // protected session: DatabaseSession<any>,
// // protected resolver: GenericQueryResolver<T>
// ) {
// super(classSchema);
// }
//
// static from<Q extends Query<any> & { _: () => T }, T extends ReturnType<InstanceType<B>['_']>, B extends ClassType<Query<any>>>(this: B, query: Q): Replace<InstanceType<B>, Resolve<Q>> {
// throw new Error();
// }
//
// public lift<B extends ClassType<Query<any>>, T extends ReturnType<InstanceType<B>['_']>, THIS extends Query<any> & { _: () => T }>(
// this: THIS, query: B
// ): Replace<InstanceType<B>, Resolve<this>> & Pick<this, Methods<this>> {
// throw new Error();
// }
//
// clone(): this {
// throw new Error();
// }
//
// protected async callOnFetchEvent(query: Query<any>): Promise<this> {
// throw new Error();
// }
//
// protected onQueryResolve(query: Query<any>): this {
// throw new Error();
// }
//
// public async count(fromHas: boolean = false): Promise<number> {
// throw new Error();
// }
//
// public async find(): Promise<Resolve<this>[]> {
// throw new Error();
// }
//
// public async findOneOrUndefined(): Promise<T | undefined> {
// throw new Error();
// }
//
// public async findOne(): Promise<Resolve<this>> {
// throw new Error();
// }
// // //
// // // public async deleteMany(): Promise<DeleteResult<T>> {
// // // throw new Error();
// // // }
// // //
// // // public async deleteOne(): Promise<DeleteResult<T>> {
// // // throw new Error();
// // // }
// // //
// // // protected async delete(query: Query<any>): Promise<DeleteResult<T>> {
// // // throw new Error();
// // // }
// //
// // // public async patchMany(patch: ChangesInterface<T> | Partial<T>): Promise<PatchResult<T>> {
// // // throw new Error();
// // // }
// // //
// // // public async patchOne(patch: ChangesInterface<T> | Partial<T>): Promise<PatchResult<T>> {
// // // throw new Error();
// // // }
// // //
// // // protected async patch(query: Query<any>, patch: Partial<T> | ChangesInterface<T>): Promise<PatchResult<T>> {
// // // throw new Error();
// // // }
// // //
// // // public async has(): Promise<boolean> {
// // // throw new Error();
// // // }
// // //
// // // public async ids(singleKey?: false): Promise<PrimaryKeyFields<T>[]>;
// // // public async ids(singleKey: true): Promise<PrimaryKeyType<T>[]>;
// // // public async ids(singleKey: boolean = false): Promise<PrimaryKeyFields<T>[] | PrimaryKeyType<T>[]> {
// // // throw new Error();
// // // }
public findField<K extends FieldName<T>>(name: K): FieldName<T> {
throw new Error();
}
// public async findOneField<K extends FieldName<T>>(name: K): Promise<T[K]> {
// throw new Error();
// }
//
// public async findOneFieldOrUndefined<K extends FieldName<T>>(name: K): Promise<T[K] | undefined> {
// throw new Error();
// }
}
interface User {
id: number;
username: string;
}
test('complex query', () => {
const queryUser = typeOf<Query<User>>();
const queryAny = typeOf<Query<any>>();
type t1 = Query<User> extends Query<any> ? true : never;
type t2 = Query<any> extends Query<User> ? true : never;
type t3 = FieldName<any>;
expect(stringifyResolvedType(typeOf<t3>())).toBe('string');
type t4 = FieldName<User>;
type t5 = FieldName<any> extends FieldName<User> ? true : never;
type t6 = FieldName<User> extends FieldName<any> ? true : never;
expect(isExtendable(typeOf<FieldName<User>>(), typeOf<FieldName<any>>())).toBe(true);
expect(isExtendable(typeOf<FieldName<any>>(), typeOf<FieldName<User>>())).toBe(false);
expect(isExtendable(queryUser, queryAny)).toBe(true);
expect(isExtendable(queryAny, queryUser)).toBe(false);
});
test('T in constraint', () => {
type Q<T> = {a: keyof T & string};
type qAny = Q<any>;
type qUser = Q<User>;
type t0 = any extends User ? true : never;
type t1 = Q<any> extends Q<User> ? true : never;
type t2 = qAny extends qUser ? true : never;
type t3 = {a: string} extends {a: 'id' | 'username'} ? true : never;
type t4 = string extends 'id' | 'username' ? true : never;
interface Q1<T> {
a: T & string;
}
interface Q2 {
findField(): string;
}
interface Q3 {
findField(): 'id' | 'username';
}
// type t11 = Q1<string> extends Q1<'id' | 'username'> ? true : never;
// type t2 = Q<User> extends Q<any> ? true : never;
// type t21 = Q1<'id' | 'username'> extends Q1<string> ? true : never;
// type t22 = Q2 extends Q3 ? true : never;
//
// type b1 = ReturnType<Q<any>['findField']>;
// type b2 = ReturnType<Q<User>['findField']>;
// type t3 = ReturnType<Q<any>['findField']> extends ReturnType<Q<User>['findField']> ? true : never;
// type t31 = string extends 'user' ? true : never;
// type t32 = { a: string } extends { a: 'user' } ? true : never;
// type t33 = { a(): string } extends { a(): 'user' } ? true : never;
//
// const qAny = typeOf<Q<any>>();
// const qUser = typeOf<Q<User>>();
//
// const c1 = ReflectionClass.from(qAny);
// const c2 = ReflectionClass.from(qUser);
//
// console.log(stringifyResolvedType(c1.getMethod('findField').getReturnType()));
// console.log(stringifyResolvedType(c2.getMethod('findField').getReturnType()));
//
// // console.log(stringifyResolvedType(c1.type));
// // console.log(stringifyResolvedType(c2.type));
//
// expect(isExtendable(qUser, qAny)).toBe(true);
// expect(isExtendable(qAny, qUser)).toBe(true);
}); | the_stack |
import * as path from 'path';
import * as fs from 'fs';
import {
workspace, window, commands, ExtensionContext, StatusBarAlignment, TextEditor, Disposable, TextDocumentSaveReason, Uri,
ProviderResult, Command, Diagnostic, CodeActionContext, WorkspaceFolder, TextDocument, WorkspaceFolderPickOptions,
TextDocumentWillSaveEvent, CodeAction
} from 'vscode';
import {
LanguageClient, LanguageClientOptions, ServerOptions, TextEdit,
RequestType, TextDocumentIdentifier, State as ClientState, NotificationType, TransportKind,
CancellationToken, WorkspaceMiddleware, ConfigurationParams
} from 'vscode-languageclient';
import { exec } from 'child_process';
interface AllFixesParams {
readonly textDocument: TextDocumentIdentifier;
readonly isOnSave: boolean;
}
interface AllFixesResult {
readonly documentVersion: number;
readonly edits: TextEdit[];
readonly ruleId?: string;
readonly overlappingFixes: boolean;
}
namespace AllFixesRequest {
export const type = new RequestType<AllFixesParams, AllFixesResult, void, void>('textDocument/tslint/allFixes');
}
interface NoTSLintLibraryParams {
readonly source: TextDocumentIdentifier;
}
interface NoTSLintLibraryResult {
}
namespace NoTSLintLibraryRequest {
export const type = new RequestType<NoTSLintLibraryParams, NoTSLintLibraryResult, void, void>('tslint/noLibrary');
}
enum Status {
ok = 1,
warn = 2,
error = 3
}
interface StatusParams {
state: Status;
}
namespace StatusNotification {
export const type = new NotificationType<StatusParams, void>('tslint/status');
}
interface Settings {
enable: boolean;
jsEnable: boolean;
rulesDirectory: string | string[];
configFile: string;
ignoreDefinitionFiles: boolean;
exclude: string | string[];
validateWithDefaultConfig: boolean;
nodePath: string | undefined;
run: 'onSave' | 'onType';
alwaysShowRuleFailuresAsWarnings: boolean;
alwaysShowStatus: boolean;
autoFixOnSave: boolean | string[];
packageManager: 'npm' | 'yarn';
trace: any;
workspaceFolderPath: string; // 'virtual' setting sent to the server
}
let willSaveTextDocumentListener: Disposable;
let configurationChangedListener: Disposable;
export function activate(context: ExtensionContext) {
let statusBarItem = window.createStatusBarItem(StatusBarAlignment.Right, 0);
let tslintStatus: Status = Status.ok;
let serverRunning: boolean = false;
statusBarItem.text = 'TSLint';
statusBarItem.command = 'tslint.showOutputChannel';
function showStatusBarItem(show: boolean): void {
if (show) {
statusBarItem.show();
} else {
statusBarItem.hide();
}
}
function updateStatus(status: Status) {
if (tslintStatus !== Status.ok && status === Status.ok) { // an error got addressed fix, write to the output that the status is OK
client.info('vscode-tslint: Status is OK');
}
tslintStatus = status;
updateStatusBarVisibility(window.activeTextEditor);
}
function isTypeScriptDocument(document: TextDocument) {
return document.languageId === 'typescript' || document.languageId === 'typescriptreact';
}
function isJavaScriptDocument(languageId) {
return languageId === 'javascript' || languageId === 'javascriptreact';
}
function isEnabledForJavaScriptDocument(document: TextDocument) {
let isJsEnable = workspace.getConfiguration('tslint', document.uri).get('jsEnable', true);
if (isJsEnable && isJavaScriptDocument(document.languageId)) {
return true;
}
return false;
}
function updateStatusBarVisibility(editor: TextEditor | undefined): void {
switch (tslintStatus) {
case Status.ok:
statusBarItem.text = 'TSLint';
break;
case Status.warn:
statusBarItem.text = '$(alert) TSLint';
break;
case Status.error:
statusBarItem.text = '$(issue-opened) TSLint';
break;
}
let uri = editor ? editor.document.uri : undefined;
let enabled = workspace.getConfiguration('tslint', uri)['enable'];
let alwaysShowStatus = workspace.getConfiguration('tslint', uri)['alwaysShowStatus'];
if (!editor || !enabled || (tslintStatus === Status.ok && !alwaysShowStatus)) {
showStatusBarItem(false);
return;
}
showStatusBarItem(
serverRunning &&
(isTypeScriptDocument(editor.document) || isEnabledForJavaScriptDocument(editor.document))
);
}
window.onDidChangeActiveTextEditor(updateStatusBarVisibility);
updateStatusBarVisibility(window.activeTextEditor);
// We need to go one level up since an extension compile the js code into
// the output folder.
let serverModulePath = path.join(__dirname, '..', 'server', 'tslintServer.js');
// break on start options
//let debugOptions = { execArgv: ["--nolazy", "--inspect-brk=6010", "--trace-warnings"] };
let debugOptions = { execArgv: ["--nolazy", "--inspect=6010"], cwd: process.cwd() };
let runOptions = { cwd: process.cwd() };
let serverOptions: ServerOptions = {
run: { module: serverModulePath, transport: TransportKind.ipc, options: runOptions },
debug: { module: serverModulePath, transport: TransportKind.ipc, options: debugOptions }
};
let clientOptions: LanguageClientOptions = {
documentSelector: [
{ language: 'typescript', scheme: 'file' },
{ language: 'typescriptreact', scheme: 'file' },
{ language: 'javascript', scheme: 'file' },
{ language: 'javascriptreact', scheme: 'file' }
],
synchronize: {
configurationSection: 'tslint',
fileEvents: workspace.createFileSystemWatcher('**/tslint.{json,yml,yaml}')
},
diagnosticCollectionName: 'tslint',
initializationFailedHandler: (error) => {
client.error('Server initialization failed.', error);
client.outputChannel.show(true);
return false;
},
middleware: {
provideCodeActions: (document, range, context, token, next): ProviderResult<(Command | CodeAction)[]> => {
// do not ask server for code action when the diagnostic isn't from tslint
if (!context.diagnostics || context.diagnostics.length === 0) {
return [];
}
let tslintDiagnostics: Diagnostic[] = [];
for (let diagnostic of context.diagnostics) {
if (diagnostic.source === 'tslint') {
tslintDiagnostics.push(diagnostic);
}
}
if (tslintDiagnostics.length === 0) {
return [];
}
let newContext: CodeActionContext = Object.assign({}, context, { diagnostics: tslintDiagnostics } as CodeActionContext);
return next(document, range, newContext, token);
},
workspace: {
configuration: (params: ConfigurationParams, token: CancellationToken, next: Function): any[] => {
if (!params.items) {
return [];
}
let result = next(params, token, next);
let scopeUri = "";
for (let item of params.items) {
if (!item.scopeUri) {
continue;
} else {
scopeUri = item.scopeUri;
}
}
let resource = client.protocol2CodeConverter.asUri(scopeUri);
let workspaceFolder = workspace.getWorkspaceFolder(resource);
if (workspaceFolder) {
convertToAbsolutePaths(result[0], workspaceFolder);
if (workspaceFolder.uri.scheme === 'file') {
result[0].workspaceFolderPath = workspaceFolder.uri.fsPath;
}
}
return result;
}
} as WorkspaceMiddleware
}
};
let client = new LanguageClient('tslint', serverOptions, clientOptions);
client.registerProposedFeatures();
const running = 'Linter is running.';
const stopped = 'Linter has stopped.';
client.onDidChangeState((event) => {
if (event.newState === ClientState.Running) {
client.info(running);
statusBarItem.tooltip = running;
serverRunning = true;
} else {
client.info(stopped);
statusBarItem.tooltip = stopped;
serverRunning = false;
}
updateStatusBarVisibility(window.activeTextEditor);
});
client.onReady().then(() => {
client.onNotification(StatusNotification.type, (params) => {
updateStatus(params.state);
});
client.onRequest(NoTSLintLibraryRequest.type, (params) => {
let uri: Uri = Uri.parse(params.source.uri);
let workspaceFolder = workspace.getWorkspaceFolder(uri);
let packageManager = workspace.getConfiguration('tslint', uri).get('packageManager', 'npm');
client.info(getInstallFailureMessage(uri, workspaceFolder, packageManager));
updateStatus(Status.warn);
return {};
});
});
function getInstallFailureMessage(uri: Uri, workspaceFolder: WorkspaceFolder | undefined, packageManager: string): string {
let localCommands = {
npm: 'npm install tslint',
yarn: 'yarn add tslint'
};
let globalCommands = {
npm: 'npm install -g tslint',
yarn: 'yarn global add tslint'
};
if (workspaceFolder) { // workspace opened on a folder
return [
'',
`Failed to load the TSLint library for the document ${uri.fsPath}`,
'',
`To use TSLint in this workspace please install tslint using \'${localCommands[packageManager]}\' or globally using \'${globalCommands[packageManager]}\'.`,
'TSLint has a peer dependency on `typescript`, make sure that `typescript` is installed as well.',
'You need to reopen the workspace after installing tslint.',
].join('\n');
} else {
return [
`Failed to load the TSLint library for the document ${uri.fsPath}`,
`To use TSLint for single file install tslint globally using \'${globalCommands[packageManager]}\'.`,
'TSLint has a peer dependency on `typescript`, make sure that `typescript` is installed as well.',
'You need to reopen VS Code after installing tslint.',
].join('\n');
}
}
function convertToAbsolutePaths(settings: Settings, folder: WorkspaceFolder) {
let configFile = settings.configFile;
if (configFile) {
settings.configFile = convertAbsolute(configFile, folder);
}
let nodePath = settings.nodePath;
if (nodePath) {
settings.nodePath = convertAbsolute(nodePath, folder);
}
if (settings.rulesDirectory) {
if (Array.isArray(settings.rulesDirectory)) {
for (let i = 0; i < settings.rulesDirectory.length; i++) {
settings.rulesDirectory[i] = convertAbsolute(settings.rulesDirectory[i], folder);
}
} else {
settings.rulesDirectory = convertAbsolute(settings.rulesDirectory, folder);
}
}
}
function convertAbsolute(file: string, folder: WorkspaceFolder): string {
if (path.isAbsolute(file)) {
return file;
}
let folderPath = folder.uri.fsPath;
if (!folderPath) {
return file;
}
return path.join(folderPath, file);
}
async function applyTextEdits(uri: string, documentVersion: number, edits: TextEdit[]): Promise<boolean> {
let textEditor = window.activeTextEditor;
if (textEditor && textEditor.document.uri.toString() === uri) {
if (documentVersion !== -1 && textEditor.document.version !== documentVersion) {
window.showInformationMessage(`TSLint fixes are outdated and can't be applied to the document.`);
return true;
}
return textEditor.edit(mutator => {
for (let edit of edits) {
mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText);
}
});
}
return true;
}
function applyDisableRuleEdit(uri: string, documentVersion: number, edits: TextEdit[]) {
let textEditor = window.activeTextEditor;
if (textEditor && textEditor.document.uri.toString() === uri) {
if (textEditor.document.version !== documentVersion) {
window.showInformationMessage(`TSLint fixes are outdated and can't be applied to the document.`);
}
// prefix disable comment with same indent as line with the diagnostic
let edit = edits[0];
let ruleLine = textEditor.document.lineAt(edit.range.start.line);
let prefixIndex = ruleLine.firstNonWhitespaceCharacterIndex;
let prefix = ruleLine.text.substr(0, prefixIndex);
edit.newText = prefix + edit.newText;
applyTextEdits(uri, documentVersion, edits);
}
}
function showRuleDocumentation(_uri: string, _documentVersion: number, _edits: TextEdit[], ruleId: string) {
const tslintDocBaseURL = "https://palantir.github.io/tslint/rules";
if (!ruleId) {
return;
}
commands.executeCommand('vscode.open', Uri.parse(tslintDocBaseURL + '/' + ruleId));
}
function fixAllProblems(): Thenable<any> | undefined {
// server is not running so there can be no problems to fix
if (!serverRunning) {
return;
}
let textEditor = window.activeTextEditor;
if (!textEditor) {
return;
}
return doFixAllProblems(textEditor.document, undefined); // no time budget
}
function exists(file: string): Promise<boolean> {
return new Promise<boolean>((resolve, _reject) => {
fs.exists(file, (value) => {
resolve(value);
});
});
}
async function findTslint(rootPath: string): Promise<string> {
const platform = process.platform;
if (platform === 'win32' && await exists(path.join(rootPath, 'node_modules', '.bin', 'tslint.cmd'))) {
return path.join('.', 'node_modules', '.bin', 'tslint.cmd');
} else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(rootPath, 'node_modules', '.bin', 'tslint'))) {
return path.join('.', 'node_modules', '.bin', 'tslint');
} else {
return 'tslint';
}
}
async function createDefaultConfiguration() {
let folders = workspace.workspaceFolders;
let folder: WorkspaceFolder | undefined = undefined;
if (!folders) {
window.showErrorMessage('A TSLint configuration file can only be generated if VS Code is opened on a folder.');
return;
}
if (folders.length === 1) {
folder = folders[0];
} else {
const options: WorkspaceFolderPickOptions = {
placeHolder: "Select the folder for generating the 'tslint.json' file"
};
folder = await window.showWorkspaceFolderPick(options);
if (!folder) {
return;
}
}
const folderPath = folder.uri.fsPath;
const tslintConfigFile = path.join(folderPath, 'tslint.json');
if (fs.existsSync(tslintConfigFile)) {
window.showInformationMessage('A TSLint configuration file already exists.');
let document = await workspace.openTextDocument(tslintConfigFile);
window.showTextDocument(document);
} else {
const tslintCmd = await findTslint(folderPath);
const cmd = `${tslintCmd} --init`;
const p = exec(cmd, { cwd: folderPath, env: process.env });
p.on('exit', async (code: number, _signal: string) => {
if (code === 0) {
let document = await workspace.openTextDocument(tslintConfigFile);
window.showTextDocument(document);
} else {
window.showErrorMessage('Could not run `tslint` to generate a configuration file. Please verify that you have `tslint` and `typescript` installed.');
}
});
}
}
function willSaveTextDocument(e: TextDocumentWillSaveEvent) {
let config = workspace.getConfiguration('tslint', e.document.uri);
let autoFix = config.get('autoFixOnSave', false);
if (autoFix) {
let document = e.document;
// only auto fix when the document was manually saved by the user
if (!(isTypeScriptDocument(document) || isEnabledForJavaScriptDocument(document))
|| e.reason !== TextDocumentSaveReason.Manual) {
return;
}
e.waitUntil(
doFixAllProblems(document, 500) // total willSave time budget is 1500
);
}
}
function configurationChanged() {
updateStatusBarVisibility(window.activeTextEditor);
}
function doFixAllProblems(document: TextDocument, timeBudget: number | undefined): Thenable<any> {
let start = Date.now();
let loopCount = 0;
let retry = false;
let lastVersion = document.version;
let promise = client.sendRequest(AllFixesRequest.type, { textDocument: { uri: document.uri.toString() }, isOnSave: true }).then(async (result) => {
while (true) {
// console.log('duration ', Date.now() - start);
if (timeBudget && Date.now() - start > timeBudget) {
console.log(`TSLint auto fix on save maximum time budget (${timeBudget}ms) exceeded.`);
break;
}
if (loopCount++ > 10) {
console.log(`TSLint auto fix on save maximum retries exceeded.`);
break;
}
if (result) {
// ensure that document versions on the client are in sync
if (lastVersion !== document.version) {
window.showInformationMessage("TSLint: Auto fix on save, fixes could not be applied (client version mismatch).");
break;
}
retry = false;
if (lastVersion !== result.documentVersion) {
console.log('TSLint auto fix on save, server document version different than client version');
retry = true; // retry to get the fixes matching the document
} else {
// try to apply the edits from the server
let edits = client.protocol2CodeConverter.asTextEdits(result.edits);
// disable version check by passing -1 as the version, the event loop is blocked during `willSave`
let success = await applyTextEdits(document.uri.toString(), -1, edits);
if (!success) {
window.showInformationMessage("TSLint: Auto fix on save, edits could not be applied");
break;
}
}
lastVersion = document.version;
if (result.overlappingFixes || retry) {
// ask for more non overlapping fixes
result = await client.sendRequest(AllFixesRequest.type, { textDocument: { uri: document.uri.toString() }, isOnSave: true });
} else {
break;
}
} else {
break;
}
}
return null;
});
return promise;
}
configurationChangedListener = workspace.onDidChangeConfiguration(configurationChanged);
willSaveTextDocumentListener = workspace.onWillSaveTextDocument(willSaveTextDocument);
configurationChanged();
context.subscriptions.push(
client.start(),
configurationChangedListener,
willSaveTextDocumentListener,
// internal commands
commands.registerCommand('_tslint.applySingleFix', applyTextEdits),
commands.registerCommand('_tslint.applySameFixes', applyTextEdits),
commands.registerCommand('_tslint.applyAllFixes', fixAllProblems),
commands.registerCommand('_tslint.applyDisableRule', applyDisableRuleEdit),
commands.registerCommand('_tslint.showRuleDocumentation', showRuleDocumentation),
// user commands
commands.registerCommand('tslint.fixAllProblems', fixAllProblems),
commands.registerCommand('tslint.createConfig', createDefaultConfiguration),
commands.registerCommand('tslint.showOutputChannel', () => { client.outputChannel.show(); }),
statusBarItem
);
}
export function deactivate() {
} | the_stack |
* @fileoverview In this file, we will test template validation.
*/
import { expect } from "chai";
import { SchemaValidator } from "../schemaValidator";
import { TemplateValidator } from "../../templateValidator";
(function() {
let MSG = require('@fluid-experimental/property-common').constants.MSG;
let semver = require('semver');
const performValidation = function(async, template, templatePrevious, skipSemver, asyncErrorMessage?) {
let schemaValidator = new SchemaValidator();
if (async) {
// @ts-ignore
return schemaValidator.validate(template, templatePrevious, async, skipSemver).catch((error) => {
expect(error.message).to.have.string(asyncErrorMessage);
});
} else {
return new Promise(resolve => {
resolve(schemaValidator.validate(template, templatePrevious, async, skipSemver));
});
}
};
// Performs both synchronous and asynchronous validation
let validate = function(expectations, template?, templatePrevious?, skipSemver?, asyncErrorMessage?) {
return performValidation(false, template, templatePrevious, skipSemver)
.then(expectations)
.then(performValidation(true, template, templatePrevious, skipSemver, asyncErrorMessage))
.then(expectations);
};
describe('Template Validation', function() {
// --- INPUT ---
describe('input validation', function() {
it('fail: empty template', function() {
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.NO_TEMPLATE);
return result;
};
return validate(expectations);
});
it('fail: template with no typeid', function() {
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.MISSING_TYPE_ID);
return result;
};
return validate(expectations, {});
});
});
// --- TYPEID ---
describe('typeid validation', function() {
it('pass: valid typeid', function() {
let template = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.typeid).to.equal(template.typeid);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template);
});
it('fail: missing semver', function() {
let template = JSON.parse(JSON.stringify(require('../schemas/badMissingSemverInTypeid')));
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.typeid).to.equal(template.typeid);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string('\'TeamLeoValidation2:PointID\' is not valid');
expect(result.errors[0].dataPath).to.equal('/typeid');
return result;
};
return validate(expectations, template);
});
it('fail: invalid semver 1', function() {
let template = JSON.parse(JSON.stringify(require('../schemas/badInvalidSemverInTypeid')));
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.typeid).to.equal(template.typeid);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].dataPath).to.equal('/typeid');
return result;
};
return validate(expectations, template);
});
it('fail: invalid semver 2', function() {
let template = JSON.parse(JSON.stringify(require('../schemas/badInvalidSemverInTypeid')));
template.typeid = 'TeamLeoValidation2:PointID-1.0.01';
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.typeid).to.equal(template.typeid);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.INVALID_VERSION_1);
return result;
};
return validate(expectations, template);
});
it('fail: previous template: invalid semver', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
let badTypeId = 'TeamLeoValidation2:PointID-1.0.0.1';
templatePrevious.typeid = badTypeId;
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.typeid).to.equal(badTypeId);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(`'${badTypeId}' is not valid`);
return result;
};
return validate(expectations, template, templatePrevious, false, 'Invalid Version: 1.0.0.1');
});
});
// --- Template versioning ---
describe('template versioning', function() {
it('fail: version regression: 1.0.0 -> 0.9.9', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-0.9.9';
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.VERSION_REGRESSION_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
describe('same version', function() {
it('pass: same content', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("fail: changed 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.annotation.description = 'Changed!';
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.MODIFIED_TEMPLATE_SAME_VERSION_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it("fail: deleted 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
delete template.annotation;
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.MODIFIED_TEMPLATE_SAME_VERSION_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it("fail: added 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.annotation = { description: 'Test' };
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.MODIFIED_TEMPLATE_SAME_VERSION_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it("fail: changed 'value'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodUIBorder')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.properties[0].properties[0].value = 123456;
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.MODIFIED_TEMPLATE_SAME_VERSION_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it("fail: changed 'id'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.properties[0].properties[0].id = 'xx';
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.MODIFIED_TEMPLATE_SAME_VERSION_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it("fail: changed 'inherits'", function() {
let templatePrevious = JSON.parse(JSON.stringify(
require('../schemas/goodReservedTypes')
));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.inherits = 'Reference<Adsk.Core:Math.Color-1.0.0>';
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.MODIFIED_TEMPLATE_SAME_VERSION_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it('fail: added property', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.properties[0].properties.push({ 'id': 'newPropId', 'typeid': 'Float32' });
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.MODIFIED_TEMPLATE_SAME_VERSION_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it('fail: deleted property', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.properties[0].properties.pop();
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.MODIFIED_TEMPLATE_SAME_VERSION_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
});
describe('incremented patch level', function() {
it('pass: same content', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'patch');
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it('pass: unstable with major content change: 0.0.1 -> 0.0.2', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.typeid = 'TeamLeoValidation2:PointID-0.0.1';
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-0.0.2';
template.properties[1].typeid = 'TeamLeoValidation2:ColorID-9.0.0';
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: changed 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'patch');
template.annotation.description = 'Changed!';
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: deleted 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'patch');
delete template.annotation;
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: added 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'patch');
template.annotation = { description: 'Test' };
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("warn: changed 'value'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodUIBorder')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'Adsk.Core:UI.Border-' + semver.inc('1.0.0', 'patch');
template.properties[0].properties[0].value = 123456;
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings.length).to.be.at.least(1);
expect(result.warnings[0]).to.have.string(MSG.CHANGE_LEVEL_TOO_LOW_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it("warn: changed 'id' (delete, add)", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'patch');
template.properties[0].properties[0].id = 'xx';
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings.length).to.be.at.least(2); // 1st for the delete and the 2nd for the add
expect(result.warnings[0]).to.have.string(MSG.CHANGE_LEVEL_TOO_LOW_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it("warn: changed 'inherits'", function() {
let templatePrevious = JSON.parse(JSON.stringify(
require('../schemas/goodReservedTypes')
));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:Example-' + semver.inc('1.0.0', 'patch');
template.inherits = 'Reference<Adsk.Core:Math.Color-1.0.0>';
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings.length).to.be.at.least(1);
expect(result.warnings[0]).to.have.string(MSG.CHANGE_LEVEL_TOO_LOW_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it('warn: added property', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'patch');
template.properties[0].properties.push({ 'id': 'newPropId', 'typeid': 'Float32' });
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings.length).to.be.at.least(1);
expect(result.warnings[0]).to.have.string(MSG.CHANGE_LEVEL_TOO_LOW_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it('warn: deleted property', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'patch');
template.properties[0].properties.pop();
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings.length).to.be.at.least(1);
expect(result.warnings[0]).to.have.string(MSG.CHANGE_LEVEL_TOO_LOW_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
});
describe('incremented minor level', function() {
it('pass: same content', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'minor');
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: changed 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'minor');
template.annotation.description = 'Changed!';
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: deleted 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'minor');
delete template.annotation;
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: added 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'minor');
template.annotation = { description: 'Test' };
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: changed 'value'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodUIBorder')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'Adsk.Core:UI.Border-' + semver.inc('1.0.0', 'minor');
template.properties[0].properties[0].value = 123456;
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("warn: changed 'id' (delete, add)", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'minor');
template.properties[0].properties[0].id = 'xx';
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings.length).to.be.at.least(1);
expect(result.warnings[0]).to.have.string(MSG.CHANGE_LEVEL_TOO_LOW_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it("warn: changed 'inherits'", function() {
let templatePrevious = JSON.parse(JSON.stringify(
require('../schemas/goodReservedTypes')
));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:Example-' + semver.inc('1.0.0', 'minor');
template.inherits = 'Reference<Adsk.Core:Math.Color-1.0.0>';
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings.length).to.be.at.least(1);
expect(result.warnings[0]).to.have.string(MSG.CHANGE_LEVEL_TOO_LOW_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
it('pass: added property', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'minor');
template.properties[0].properties.push({ 'id': 'newPropId', 'typeid': 'Float32' });
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it('warn: deleted property', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'minor');
template.properties[0].properties.pop();
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings.length).to.be.at.least(1);
expect(result.warnings[0]).to.have.string(MSG.CHANGE_LEVEL_TOO_LOW_1);
return result;
};
return validate(expectations, template, templatePrevious);
});
});
describe('incremented major level', function() {
it('pass: same content', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'major');
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: changed 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'major');
template.annotation.description = 'Changed!';
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: deleted 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'major');
delete template.annotation;
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: added 'annotation'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'major');
template.annotation = { description: 'Test' };
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: changed 'value'", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodUIBorder')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'Adsk.Core:UI.Border-' + semver.inc('1.0.0', 'major');
template.properties[0].properties[0].value = 123456;
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: changed 'id' (delete, add)", function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'major');
template.properties[0].properties[0].id = 'xx';
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it("pass: changed 'inherits'", function() {
let templatePrevious = JSON.parse(JSON.stringify(
require('../schemas/goodReservedTypes')
));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:Example-' + semver.inc('1.0.0', 'major');
template.inherits = 'Reference<Adsk.Core:Math.Color-1.0.0>';
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it('pass: added property', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'major');
template.properties[0].properties.push({ 'id': 'newPropId', 'typeid': 'Float32' });
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
it('pass: deleted property', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
templatePrevious.annotation = { description: 'Test' };
let template = JSON.parse(JSON.stringify(templatePrevious));
template.typeid = 'TeamLeoValidation2:PointID-' + semver.inc('1.0.0', 'major');
template.properties[0].properties.pop();
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious);
});
});
});
describe('skip semver validation', function() {
it('pass: deep equal on scrambled arrays', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
let tmp = template.properties[0].properties[0];
template.properties[0].properties[0] = template.properties[0].properties[2];
template.properties[0].properties[2] = tmp;
tmp = template.properties[1];
template.properties[1] = template.properties[2];
template.properties[2] = tmp;
// Skip semver validation to cause a deep compare
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious, true);
});
it('pass: deep equal with version regression', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious, true);
});
it('pass: preserves input templates', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodPointId')));
let template = JSON.parse(JSON.stringify(templatePrevious));
let copies = [
JSON.parse(JSON.stringify(templatePrevious)),
JSON.parse(JSON.stringify(template))
];
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
expect(templatePrevious).to.deep.equal(copies[0]);
expect(template).to.deep.equal(copies[1]);
return result;
};
return validate(expectations, template, templatePrevious);
});
it('fail: changed value', function() {
let templatePrevious = JSON.parse(JSON.stringify(require('../schemas/goodUIBorder')));
let template = JSON.parse(JSON.stringify(templatePrevious));
template.properties[0].properties[0].value = 123456;
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.warnings).to.be.empty;
expect(result.errors.length).to.be.at.least(1);
expect(result.errors[0].message).to.have.string(MSG.MODIFIED_TEMPLATE_1);
return result;
};
return validate(expectations, template, templatePrevious, true);
});
});
describe('syntax validation', function() {
it('pass: validate a simple file', function() {
let template = require('../schemas/goodPointId');
let expectations = function(result) {
expect(result.isValid).to.equal(true);
return result;
};
return validate(expectations, template, null, true);
});
it('fail: invalid file', function() {
let template = require('../schemas/badPrimitiveTypeid');
let expectations = function(result) {
expect(result.isValid).to.equal(false);
expect(result.errors.length).to.be.greaterThan(0);
expect(result.unresolvedTypes.length).to.equal(1);
return result;
};
return validate(expectations, template, null, true);
});
it('should pass a schema with an empty array of properties', function() {
let EmptyPropertySchema = {
typeid: 'Test:EmptyPropertySchema-1.0.0',
properties: []
};
let expectations = function(result) {
expect(result.isValid).to.equal(true);
return result;
};
return validate(expectations, EmptyPropertySchema, null);
});
});
describe('bugs', function() {
describe('@bugfix Template validation with multiple inheritance', function() {
it('pass: deep equal with multiple inheritance', function() {
let templateString =
'{"typeid":"autodesk.core:translation.controller-1.0.0","inherits":["NamedProperty","NodeProperty"]}';
let templatePrevious = JSON.parse(templateString);
let template = JSON.parse(templateString);
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, template, templatePrevious, true);
});
it('fail: deep equal with out of order multiple inheritance', function() {
let template = JSON.parse('{"typeid":"autodesk.core:translation.controller-1.0.0",' +
'"inherits":["NamedProperty","NodeProperty"]}'
);
let templatePrevious = JSON.parse('{"typeid":"autodesk.core:translation.controller-1.0.0",' +
'"inherits":["NodeProperty","NamedProperty"]}'
);
let expectations = function(result) {
expect(result).property('isValid', false);
expect(result.errors.length).to.be.greaterThan(0);
expect(result.errors[0].message).to.have.string(MSG.MODIFIED_TEMPLATE_1);
return result;
};
return validate(expectations, template, templatePrevious, true);
});
});
describe('@bugfix Local templates with \'abstract\' properties fail validation ' +
'with remote one.', () => {
describe('pass: deep equal between no properties and an empty properties array', () => {
let templateArray = {
typeid: 'SimpleTest:Shape-1.0.0',
properties: []
};
let templateAbstract = {
typeid: 'SimpleTest:Shape-1.0.0'
};
it('source is abstract and target is an empty properties array', function() {
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, templateAbstract, templateArray);
});
it('target is abstract and source is an empty properties array', function() {
let expectations = function(result) {
expect(result).property('isValid', true);
expect(result.errors).to.be.empty;
expect(result.warnings).to.be.empty;
return result;
};
return validate(expectations, templateArray, templateAbstract);
});
});
});
});
describe('Constants', function() {
before(function() {
let schemaValidator = new SchemaValidator();
new TemplateValidator({
skipSemver: true,
inheritsFrom: schemaValidator.inheritsFrom as any,
hasSchema: schemaValidator.hasSchema as any
});
});
let expectationsGenerator = function(msg) {
return function(result) {
expect(result.isValid).to.equal(false);
expect(result.errors.length).to.equal(1);
expect(result.errors[0].message).to.equal(msg);
return result;
};
};
it('should pass a valid template', function() {
let ConstantValid = {
typeid: 'ConstantTest:ConstantValid-1.0.0',
constants: [{ id: 'valid', typeid: 'String', value: 'value' }]
};
let expectations = function(result) {
expect(result.isValid).to.equal(true);
return result;
};
return validate(expectations, ConstantValid, null);
});
it('should fail if constants array has no elements', function() {
let ConstantEmptyArray = {
typeid: 'ConstantTest:ConstantEmptyArray-1.0.0',
constants: []
};
return validate(expectationsGenerator('/constants should NOT have fewer than 1 items'),
ConstantEmptyArray, null, true);
});
it('should fail if constant does not have an id', function() {
let ConstantNoId = {
typeid: 'ConstantTest:ConstantNoId-1.0.0',
constants: [{ typeid: 'String', value: 'value' }]
};
return validate(expectationsGenerator('/constants/0 should have required property \'id\''),
ConstantNoId, null, true);
});
it('should fail if constant does not have a typeid', function() {
let ConstantNoTypeid = {
typeid: 'ConstantTest:ConstantNoTypeid-1.0.0',
constants: [{ id: 'id', value: 'value' }]
};
return validate(
function(result) {
expect(result.isValid).to.equal(false);
//console.log(result.errors);
expect(result.errors.length).to.equal(5);
expect(result.errors[3].message).to.include("should have required property 'inherits'");
expect(result.errors[4].message).to.include("/constants/0 should have required property 'typeid'");
return result;
},
ConstantNoTypeid, null, true
);
});
it('should pass if constant does not have a typeid but maybe inherits from elsewhere', function() {
let ConstantNoTypeid = {
typeid: 'ConstantTest:ConstantNoTypeid-1.0.0',
inherits: 'ConstantTest:ConstantParentWithTypeid-1.0.0',
constants: [{ id: 'id', value: 'value' }]
};
let expectations = function(result) {
expect(result.isValid).to.equal(true);
return result;
};
return validate(expectations, ConstantNoTypeid, null);
});
it('should not fail if constant does not have a value or typedValue', function() {
let ConstantNoValue = {
typeid: 'ConstantTest:ConstantNoValue-1.0.0',
constants: [{ id: 'id', typeid: 'String' }]
};
let expectations = function(result) {
expect(result.isValid).to.equal(true);
return result;
};
return validate(expectations, ConstantNoValue, null, true);
});
it('should pass if constant map with context key type typeid has typeids as keys', function() {
let Constant = {
typeid: 'ConstantTest:Constant-1.0.0',
constants: [{
id: 'map',
typeid: 'Int32',
context: 'map',
contextKeyType: 'typeid',
value: { 'SimpleTest:ConstantTemplate1-1.0.0': 1, 'SimpleTest:ConstantTemplate2-1.0.0': -1 }
}]
};
let expectations = function(result) {
expect(result.isValid).to.equal(true);
return result;
};
return validate(expectations, Constant, null, true);
});
it('should fail if constant map with context key type that is not a valid value', function() {
let ConstantNoValue = {
typeid: 'ConstantTest:ConstantNoValue-1.0.0',
constants: [{
id: 'map',
typeid: 'Int32',
context: 'map',
contextKeyType: 'badvalue',
value: { 'SimpleTest:ConstantTemplate1-1.0.0': 1, 'SimpleTest:ConstantTemplate2-1.0.0': -1 }
}]
};
return validate(
function(result) {
expect(result.isValid).to.equal(false);
expect(result.errors.length).to.equal(1);
expect(result.errors[0].message).to.include('should match one of the following: typeid,string');
return result;
},
ConstantNoValue,
null,
true
);
});
it('should fail if constant map with context key type typeid has invalid typeids as keys', function() {
let ConstantMapWithBadKeys = {
typeid: 'ConstantTest:ConstantMapWithBadKeys-1.0.0',
constants: [{
id: 'map',
typeid: 'Int32',
context: 'map',
contextKeyType: 'typeid',
value: { 'NotATypeId': 1, 'AlsoNotATypeId': -1 }
}]
};
let expectations = function(result) {
expect(result.isValid).to.equal(false);
expect(result.errors.length).to.equal(2);
expect(result.errors[0].message).to.include(
MSG.KEY_MUST_BE_TYPEID + 'NotATypeId');
expect(result.errors[1].message).to.include(
MSG.KEY_MUST_BE_TYPEID + 'AlsoNotATypeId');
return result;
};
return validate(expectations, ConstantMapWithBadKeys, null, true);
});
it('should fail if map with context key type typeid is not constant', function() {
let ConstantMapWithProperty = {
typeid: 'ConstantTest:Outerprop-1.0.0',
properties: [{
id: 'map',
typeid: 'Int32',
context: 'map',
contextKeyType: 'typeid',
value: { 'SimpleTest:ConstantTemplate1-1.0.0': 1, 'SimpleTest:ConstantTemplate2-1.0.0': -1 }
}]
};
let expectations = function(result) {
throw new Error('This should not be called');
};
let failExpectations = function(error) {
expect(error.toString()).to.include(
'SV-013: A map with typeids as keys must be constant');
};
return performValidation(false, ConstantMapWithProperty, null, true)
.then(expectations).catch(failExpectations);
});
});
describe('Async validation', function() {
it('can perform context validation asynchronously', function(done) {
let schemaValidator = new SchemaValidator();
let templateValidator = new TemplateValidator({
inheritsFromAsync: schemaValidator.inheritsFromAsync as any,
hasSchemaAsync: schemaValidator.hasSchemaAsync as any
});
// Doesn't inherit from 'NamedProperty'. Will cause an error
let grandParentSchema = {
'typeid': 'test:grandparentschema-1.0.0'
};
let parentSchema = {
'typeid': 'test:parentschema-1.0.0',
'inherits': ['test:grandparentschema-1.0.0']
};
let childSchema = {
'typeid': 'test:childchema-1.0.0',
properties: [{
id: 'set',
typeid: 'test:parentschema-1.0.0',
context: 'set'
}]
};
schemaValidator.register(grandParentSchema);
schemaValidator.register(parentSchema);
templateValidator.validateAsync(childSchema as any).then(
() => {
done(new Error('Should not be valid!'));
},
error => {
expect(error).to.exist;
done();
}
);
});
});
});
})(); | the_stack |
import { strings } from "../../../strings";
import { Geometry, Point, rgbToHex } from "../../common";
import * as Graphics from "../../graphics";
import { ConstraintSolver, ConstraintStrength } from "../../solver";
import * as Specification from "../../specification";
import { MappingType } from "../../specification";
import {
BoundingBox,
Controls,
DropZones,
Handles,
LinkAnchor,
ObjectClass,
ObjectClassMetadata,
SnappingGuides,
TemplateParameters,
} from "../common";
import { ChartStateManager } from "../state";
import { EmphasizableMarkClass } from "./emphasis";
import {
imageAttributes,
ImageElementAttributes,
ImageElementProperties,
} from "./image.attrs";
export const imagePlaceholder: Specification.Types.Image = {
src:
"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMiAzMiI+PHRpdGxlPmljb25zPC90aXRsZT48cmVjdCB4PSI1LjE1MTI0IiB5PSI2LjY4NDYyIiB3aWR0aD0iMjEuNjk3NTIiIGhlaWdodD0iMTguNjEyNSIgc3R5bGU9ImZpbGw6bm9uZTtzdHJva2U6IzAwMDtzdHJva2UtbGluZWpvaW46cm91bmQ7c3Ryb2tlLXdpZHRoOjAuOTI2MTg0MTE3Nzk0MDM2OXB4Ii8+PHBvbHlnb24gcG9pbnRzPSIyMC4xNSAxMi45NDMgMTMuODExIDIxLjQwNCAxMC4xNTQgMTYuNDk4IDUuMTUxIDIzLjE3NiA1LjE1MSAyNS4zMDYgMTAuODg4IDI1LjMwNiAxNi43MTkgMjUuMzA2IDI2Ljg0OSAyNS4zMDYgMjYuODQ5IDIxLjkzIDIwLjE1IDEyLjk0MyIgc3R5bGU9ImZpbGwtb3BhY2l0eTowLjI7c3Ryb2tlOiMwMDA7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS13aWR0aDowLjcwMDAwMDAwMDAwMDAwMDFweCIvPjxjaXJjbGUgY3g9IjExLjkyMDI3IiBjeT0iMTIuMzk5MjMiIHI9IjEuOTAyMTYiIHN0eWxlPSJmaWxsLW9wYWNpdHk6MC4yO3N0cm9rZTojMDAwO3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZDtzdHJva2Utd2lkdGg6MC43MDAwMDAwMDAwMDAwMDAxcHgiLz48L3N2Zz4=",
width: 100,
height: 100,
};
export { ImageElementAttributes, ImageElementProperties };
export class ImageElementClass extends EmphasizableMarkClass<
ImageElementProperties,
ImageElementAttributes
> {
public static classID = "mark.image";
public static type = "mark";
public static metadata: ObjectClassMetadata = {
displayName: "Image",
iconPath: "FileImage",
creatingInteraction: {
type: "rectangle",
mapping: { xMin: "x1", yMin: "y1", xMax: "x2", yMax: "y2" },
},
};
public static defaultProperties: Partial<ImageElementProperties> = {
...ObjectClass.defaultProperties,
visible: true,
imageMode: "letterbox",
paddingX: 0,
paddingY: 0,
alignX: "middle",
alignY: "middle",
};
public static defaultMappingValues: Partial<ImageElementAttributes> = {
strokeWidth: 1,
opacity: 1,
visible: true,
};
public attributes = imageAttributes;
public attributeNames = Object.keys(imageAttributes);
/** Initialize the state of an element so that everything has a valid value */
public initializeState(): void {
const defaultWidth = 30;
const defaultHeight = 50;
const attrs = this.state.attributes;
attrs.x1 = -defaultWidth / 2;
attrs.y1 = -defaultHeight / 2;
attrs.x2 = +defaultWidth / 2;
attrs.y2 = +defaultHeight / 2;
attrs.cx = 0;
attrs.cy = 0;
attrs.width = defaultWidth;
attrs.height = defaultHeight;
attrs.stroke = null;
attrs.fill = null;
attrs.strokeWidth = 1;
attrs.opacity = 1;
attrs.visible = true;
attrs.image = null;
}
// eslint-disable-next-line
public getAttributePanelWidgets(
manager: Controls.WidgetManager
): Controls.Widget[] {
const parentWidgets = super.getAttributePanelWidgets(manager);
const widgets: Controls.Widget[] = [
manager.verticalGroup(
{
header: strings.objects.general,
},
[
manager.mappingEditor(strings.objects.width, "width", {
hints: { autoRange: true, startWithZero: "always" },
acceptKinds: [Specification.DataKind.Numerical],
defaultAuto: true,
}),
manager.mappingEditor(strings.objects.height, "height", {
hints: { autoRange: true, startWithZero: "always" },
acceptKinds: [Specification.DataKind.Numerical],
defaultAuto: true,
}),
manager.mappingEditor(
strings.objects.visibleOn.visibility,
"visible",
{
defaultValue: true,
}
),
]
),
// manager.sectionHeader(strings.objects.size),
manager.verticalGroup(
{
header: strings.toolbar.image,
},
[
manager.mappingEditor(strings.objects.icon.image, "image", {}),
manager.inputSelect(
{ property: "imageMode" },
{
type: "dropdown",
showLabel: true,
labels: [
strings.objects.image.letterbox,
strings.objects.image.stretch,
],
options: ["letterbox", "stretch"],
label: strings.objects.image.imageMode,
}
),
...(this.object.properties.imageMode == "letterbox"
? [
manager.label(strings.alignment.align),
manager.horizontal(
[0, 1],
manager.inputSelect(
{ property: "alignX" },
{
type: "radio",
options: ["start", "middle", "end"],
icons: [
"AlignHorizontalLeft",
"AlignHorizontalCenter",
"AlignHorizontalRight",
],
labels: [
strings.alignment.left,
strings.alignment.middle,
strings.alignment.right,
],
}
),
manager.inputSelect(
{ property: "alignY" },
{
type: "radio",
options: ["start", "middle", "end"],
icons: [
"AlignVerticalBottom",
"AlignVerticalCenter",
"AlignVerticalTop",
],
labels: [
strings.alignment.bottom,
strings.alignment.middle,
strings.alignment.top,
],
}
)
),
]
: []),
]
),
manager.verticalGroup(
{
header: strings.alignment.padding,
},
[
manager.label(strings.coordinateSystem.x),
manager.inputNumber(
{ property: "paddingX" },
{
updownTick: 1,
showUpdown: true,
}
),
manager.label(strings.coordinateSystem.y),
manager.inputNumber(
{ property: "paddingY" },
{
updownTick: 1,
showUpdown: true,
}
),
]
),
manager.verticalGroup(
{
header: strings.objects.style,
},
[
manager.mappingEditor(strings.objects.fill, "fill", {}),
manager.mappingEditor(strings.objects.stroke, "stroke", {}),
this.object.mappings.stroke != null
? manager.mappingEditor(
strings.objects.strokeWidth,
"strokeWidth",
{
hints: { rangeNumber: [0, 5] },
defaultValue: 1,
numberOptions: {
showSlider: true,
sliderRange: [0, 5],
minimum: 0,
},
}
)
: null,
manager.mappingEditor(strings.objects.opacity, "opacity", {
hints: { rangeNumber: [0, 1] },
defaultValue: 1,
numberOptions: {
showSlider: true,
minimum: 0,
maximum: 1,
step: 0.1,
},
}),
]
),
];
return widgets.concat(parentWidgets);
}
/**
* Get intrinsic constraints between attributes (e.g., x2 - x1 = width for rectangles)
* See description of {@link RectElementClass.buildConstraints} method for details. Image has the same shape, except center point.
*/
public buildConstraints(solver: ConstraintSolver): void {
const [x1, y1, x2, y2, cx, cy, width, height] = solver.attrs(
this.state.attributes,
["x1", "y1", "x2", "y2", "cx", "cy", "width", "height"]
);
solver.addLinear(
ConstraintStrength.HARD,
0,
[
[1, x2],
[-1, x1],
],
[[1, width]]
);
solver.addLinear(
ConstraintStrength.HARD,
0,
[
[1, y2],
[-1, y1],
],
[[1, height]]
);
solver.addLinear(
ConstraintStrength.HARD,
0,
[[2, cx]],
[
[1, x1],
[1, x2],
]
);
solver.addLinear(
ConstraintStrength.HARD,
0,
[[2, cy]],
[
[1, y1],
[1, y2],
]
);
}
// Get the graphical element from the element
// eslint-disable-next-line
public getGraphics(
cs: Graphics.CoordinateSystem,
offset: Point,
// eslint-disable-next-line
glyphIndex: number,
// eslint-disable-next-line
manager: ChartStateManager
): Graphics.Element {
const attrs = this.state.attributes;
const props = this.object.properties;
if (!attrs.visible || !this.object.properties.visible) {
return null;
}
const paddingX = props.paddingX || 0;
const paddingY = props.paddingY || 0;
const alignX = props.alignX || "middle";
const alignY = props.alignY || "middle";
let image = attrs.image || imagePlaceholder;
if (typeof image == "string") {
// Be compatible with old version
image = { src: image, width: 100, height: 100 };
}
const helper = new Graphics.CoordinateSystemHelper(cs);
const g = Graphics.makeGroup([]);
// If fill color is specified, draw a background rect
if (attrs.fill) {
g.elements.push(
helper.rect(
attrs.x1 + offset.x,
attrs.y1 + offset.y,
attrs.x2 + offset.x,
attrs.y2 + offset.y,
{
strokeColor: null,
fillColor: attrs.fill,
}
)
);
}
// Center in local coordiantes
const cx = (attrs.x1 + attrs.x2) / 2;
const cy = (attrs.y1 + attrs.y2) / 2;
// Decide the width/height of the image area
// For special coordinate systems, use the middle lines' length as width/height
const containerWidth = Geometry.pointDistance(
cs.transformPoint(attrs.x1 + offset.x, cy + offset.y),
cs.transformPoint(attrs.x2 + offset.x, cy + offset.y)
);
const containerHeight = Geometry.pointDistance(
cs.transformPoint(cx + offset.x, attrs.y1 + offset.y),
cs.transformPoint(cx + offset.x, attrs.y2 + offset.y)
);
const boxWidth = Math.max(0, containerWidth - paddingX * 2);
const boxHeight = Math.max(0, containerHeight - paddingY * 2);
// Fit image into boxWidth x boxHeight, based on the specified option
let imageWidth: number;
let imageHeight: number;
switch (props.imageMode) {
case "stretch":
{
imageWidth = boxWidth;
imageHeight = boxHeight;
}
break;
case "letterbox":
default:
{
if (image.width / image.height > boxWidth / boxHeight) {
imageWidth = boxWidth;
imageHeight = (image.height / image.width) * boxWidth;
} else {
imageHeight = boxHeight;
imageWidth = (image.width / image.height) * boxHeight;
}
}
break;
}
// Decide the anchor position (px, py) in local coordinates
let px = cx;
let py = cy;
let imgX = -imageWidth / 2;
let imgY = -imageHeight / 2;
if (alignX == "start") {
px = attrs.x1;
imgX = paddingX;
} else if (alignX == "end") {
px = attrs.x2;
imgX = -imageWidth - paddingX;
}
if (alignY == "start") {
py = attrs.y1;
imgY = paddingY;
} else if (alignY == "end") {
py = attrs.y2;
imgY = -imageHeight - paddingY;
}
// Create the image element
const gImage = Graphics.makeGroup([
<Graphics.Image>{
type: "image",
src: image.src,
x: imgX,
y: imgY,
width: imageWidth,
height: imageHeight,
mode: "stretch",
},
]);
gImage.transform = cs.getLocalTransform(px + offset.x, py + offset.y);
g.elements.push(gImage);
// If stroke color is specified, stroke a foreground rect
if (attrs.stroke) {
g.elements.push(
helper.rect(
attrs.x1 + offset.x,
attrs.y1 + offset.y,
attrs.x2 + offset.x,
attrs.y2 + offset.y,
{
strokeColor: attrs.stroke,
strokeWidth: attrs.strokeWidth,
strokeLinejoin: "miter",
fillColor: null,
}
)
);
}
// Apply the opacity
g.style = {
opacity: attrs.opacity,
};
return g;
}
/** Get link anchors for this mark */
// eslint-disable-next-line
public getLinkAnchors(): LinkAnchor.Description[] {
const attrs = this.state.attributes;
const element = this.object._id;
return [
{
element,
points: [
{
x: attrs.x1,
y: attrs.y1,
xAttribute: "x1",
yAttribute: "y1",
direction: { x: -1, y: 0 },
},
{
x: attrs.x1,
y: attrs.y2,
xAttribute: "x1",
yAttribute: "y2",
direction: { x: -1, y: 0 },
},
],
},
{
element,
points: [
{
x: attrs.x2,
y: attrs.y1,
xAttribute: "x2",
yAttribute: "y1",
direction: { x: 1, y: 0 },
},
{
x: attrs.x2,
y: attrs.y2,
xAttribute: "x2",
yAttribute: "y2",
direction: { x: 1, y: 0 },
},
],
},
{
element,
points: [
{
x: attrs.x1,
y: attrs.y1,
xAttribute: "x1",
yAttribute: "y1",
direction: { x: 0, y: -1 },
},
{
x: attrs.x2,
y: attrs.y1,
xAttribute: "x2",
yAttribute: "y1",
direction: { x: 0, y: -1 },
},
],
},
{
element,
points: [
{
x: attrs.x1,
y: attrs.y2,
xAttribute: "x1",
yAttribute: "y2",
direction: { x: 0, y: 1 },
},
{
x: attrs.x2,
y: attrs.y2,
xAttribute: "x2",
yAttribute: "y2",
direction: { x: 0, y: 1 },
},
],
},
{
element,
points: [
{
x: attrs.cx,
y: attrs.y1,
xAttribute: "cx",
yAttribute: "y1",
direction: { x: 0, y: -1 },
},
],
},
{
element,
points: [
{
x: attrs.cx,
y: attrs.y2,
xAttribute: "cx",
yAttribute: "y2",
direction: { x: 0, y: 1 },
},
],
},
{
element,
points: [
{
x: attrs.x1,
y: attrs.cy,
xAttribute: "x1",
yAttribute: "cy",
direction: { x: -1, y: 0 },
},
],
},
{
element,
points: [
{
x: attrs.x2,
y: attrs.cy,
xAttribute: "x2",
yAttribute: "cy",
direction: { x: 1, y: 0 },
},
],
},
];
}
// Get DropZones given current state
public getDropZones(): DropZones.Description[] {
const attrs = this.state.attributes;
const { x1, y1, x2, y2 } = attrs;
return [
<DropZones.Line>{
type: "line",
p1: { x: x2, y: y1 },
p2: { x: x1, y: y1 },
title: "width",
accept: { kind: Specification.DataKind.Numerical },
dropAction: {
scaleInference: {
attribute: "width",
attributeType: Specification.AttributeType.Number,
hints: { autoRange: true, startWithZero: "always" },
},
},
},
<DropZones.Line>{
type: "line",
p1: { x: x1, y: y1 },
p2: { x: x1, y: y2 },
title: "height",
accept: { kind: Specification.DataKind.Numerical },
dropAction: {
scaleInference: {
attribute: "height",
attributeType: Specification.AttributeType.Number,
hints: { autoRange: true, startWithZero: "always" },
},
},
},
];
}
// Get bounding rectangle given current state
public getHandles(): Handles.Description[] {
const attrs = this.state.attributes;
const { x1, y1, x2, y2 } = attrs;
return [
<Handles.Line>{
type: "line",
axis: "x",
actions: [{ type: "attribute", attribute: "x1" }],
value: x1,
span: [y1, y2],
},
<Handles.Line>{
type: "line",
axis: "x",
actions: [{ type: "attribute", attribute: "x2" }],
value: x2,
span: [y1, y2],
},
<Handles.Line>{
type: "line",
axis: "y",
actions: [{ type: "attribute", attribute: "y1" }],
value: y1,
span: [x1, x2],
},
<Handles.Line>{
type: "line",
axis: "y",
actions: [{ type: "attribute", attribute: "y2" }],
value: y2,
span: [x1, x2],
},
<Handles.Point>{
type: "point",
x: x1,
y: y1,
actions: [
{ type: "attribute", source: "x", attribute: "x1" },
{ type: "attribute", source: "y", attribute: "y1" },
],
},
<Handles.Point>{
type: "point",
x: x1,
y: y2,
actions: [
{ type: "attribute", source: "x", attribute: "x1" },
{ type: "attribute", source: "y", attribute: "y2" },
],
},
<Handles.Point>{
type: "point",
x: x2,
y: y1,
actions: [
{ type: "attribute", source: "x", attribute: "x2" },
{ type: "attribute", source: "y", attribute: "y1" },
],
},
<Handles.Point>{
type: "point",
x: x2,
y: y2,
actions: [
{ type: "attribute", source: "x", attribute: "x2" },
{ type: "attribute", source: "y", attribute: "y2" },
],
},
];
}
public getBoundingBox(): BoundingBox.Description {
const attrs = this.state.attributes;
const { x1, y1, x2, y2 } = attrs;
return <BoundingBox.Rectangle>{
type: "rectangle",
cx: (x1 + x2) / 2,
cy: (y1 + y2) / 2,
width: Math.abs(x2 - x1),
height: Math.abs(y2 - y1),
rotation: 0,
};
}
public getSnappingGuides(): SnappingGuides.Description[] {
const attrs = this.state.attributes;
const { x1, y1, x2, y2, cx, cy } = attrs;
return [
<SnappingGuides.Axis>{ type: "x", value: x1, attribute: "x1" },
<SnappingGuides.Axis>{ type: "x", value: x2, attribute: "x2" },
<SnappingGuides.Axis>{ type: "x", value: cx, attribute: "cx" },
<SnappingGuides.Axis>{ type: "y", value: y1, attribute: "y1" },
<SnappingGuides.Axis>{ type: "y", value: y2, attribute: "y2" },
<SnappingGuides.Axis>{ type: "y", value: cy, attribute: "cy" },
];
}
public getTemplateParameters(): TemplateParameters {
const properties = [];
if (
this.object.mappings.strokeWidth &&
this.object.mappings.strokeWidth.type === MappingType.value
) {
properties.push({
objectID: this.object._id,
target: {
attribute: "strokeWidth",
},
type: Specification.AttributeType.Number,
default: this.state.attributes.strokeWidth,
});
}
if (
this.object.mappings.opacity &&
this.object.mappings.opacity.type === MappingType.value
) {
properties.push({
objectID: this.object._id,
target: {
attribute: "opacity",
},
type: Specification.AttributeType.Number,
default: this.state.attributes.opacity,
});
}
if (
this.object.mappings.visible &&
this.object.mappings.visible.type === MappingType.value
) {
properties.push({
objectID: this.object._id,
target: {
attribute: "visible",
},
type: Specification.AttributeType.Number,
default: this.state.attributes.visible,
});
}
if (
this.object.mappings.image &&
this.object.mappings.image.type === MappingType.value
) {
properties.push({
objectID: this.object._id,
target: {
attribute: "image",
},
type: Specification.AttributeType.Image,
default: this.state.attributes.image.src,
});
}
if (
this.object.mappings.fill &&
this.object.mappings.fill.type === MappingType.value
) {
properties.push({
objectID: this.object._id,
target: {
attribute: "fill",
},
type: Specification.AttributeType.Color,
default: rgbToHex(this.state.attributes.fill),
});
}
if (
this.object.mappings.stroke &&
this.object.mappings.stroke.type === MappingType.value
) {
properties.push({
objectID: this.object._id,
target: {
attribute: "stroke",
},
type: Specification.AttributeType.Color,
default: rgbToHex(this.state.attributes.stroke),
});
}
return {
properties,
};
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Manages private and isolated Logic App instances within an Azure virtual network.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleVirtualNetwork = new azure.network.VirtualNetwork("exampleVirtualNetwork", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* addressSpaces: ["10.0.0.0/22"],
* });
* const isesubnet1 = new azure.network.Subnet("isesubnet1", {
* resourceGroupName: exampleResourceGroup.name,
* virtualNetworkName: exampleVirtualNetwork.name,
* addressPrefixes: ["10.0.1.0/26"],
* delegations: [{
* name: "integrationServiceEnvironments",
* serviceDelegation: {
* name: "Microsoft.Logic/integrationServiceEnvironments",
* },
* }],
* });
* const isesubnet2 = new azure.network.Subnet("isesubnet2", {
* resourceGroupName: exampleResourceGroup.name,
* virtualNetworkName: exampleVirtualNetwork.name,
* addressPrefixes: ["10.0.1.64/26"],
* });
* const isesubnet3 = new azure.network.Subnet("isesubnet3", {
* resourceGroupName: exampleResourceGroup.name,
* virtualNetworkName: exampleVirtualNetwork.name,
* addressPrefixes: ["10.0.1.128/26"],
* });
* const isesubnet4 = new azure.network.Subnet("isesubnet4", {
* resourceGroupName: exampleResourceGroup.name,
* virtualNetworkName: exampleVirtualNetwork.name,
* addressPrefixes: ["10.0.1.192/26"],
* });
* const exampleInterationServiceEnvironment = new azure.logicapps.InterationServiceEnvironment("exampleInterationServiceEnvironment", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* skuName: "Developer_0",
* accessEndpointType: "Internal",
* virtualNetworkSubnetIds: [
* isesubnet1.id,
* isesubnet2.id,
* isesubnet3.id,
* isesubnet4.id,
* ],
* tags: {
* environment: "development",
* },
* });
* ```
*
* ## Import
*
* Integration Service Environments can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:logicapps/interationServiceEnvironment:InterationServiceEnvironment example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Logic/integrationServiceEnvironments/ise1
* ```
*/
export class InterationServiceEnvironment extends pulumi.CustomResource {
/**
* Get an existing InterationServiceEnvironment resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: InterationServiceEnvironmentState, opts?: pulumi.CustomResourceOptions): InterationServiceEnvironment {
return new InterationServiceEnvironment(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:logicapps/interationServiceEnvironment:InterationServiceEnvironment';
/**
* Returns true if the given object is an instance of InterationServiceEnvironment. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is InterationServiceEnvironment {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === InterationServiceEnvironment.__pulumiType;
}
/**
* The type of access endpoint to use for the Integration Service Environment. Possible Values are `Internal` and `External`. Changing this forces a new Integration Service Environment to be created.
*/
public readonly accessEndpointType!: pulumi.Output<string>;
/**
* The list of access endpoint ip addresses of connector.
*/
public /*out*/ readonly connectorEndpointIpAddresses!: pulumi.Output<string[]>;
/**
* The list of outgoing ip addresses of connector.
*/
public /*out*/ readonly connectorOutboundIpAddresses!: pulumi.Output<string[]>;
/**
* The Azure Region where the Integration Service Environment should exist. Changing this forces a new Integration Service Environment to be created.
*/
public readonly location!: pulumi.Output<string>;
/**
* The name of the Integration Service Environment. Changing this forces a new Integration Service Environment to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* The name of the Resource Group where the Integration Service Environment should exist. Changing this forces a new Integration Service Environment to be created.
*/
public readonly resourceGroupName!: pulumi.Output<string>;
/**
* The sku name and capacity of the Integration Service Environment. Possible Values for `sku` element are `Developer` and `Premium` and possible values for the `capacity` element are from `0` to `10`. Defaults to `sku` of `Developer` with a `Capacity` of `0` (e.g. `Developer_0`). Changing this forces a new Integration Service Environment to be created when `sku` element is not the same with existing one.
*/
public readonly skuName!: pulumi.Output<string | undefined>;
/**
* A mapping of tags which should be assigned to the Integration Service Environment.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* A list of virtual network subnet ids to be used by Integration Service Environment. Exactly four distinct ids to subnets must be provided. Changing this forces a new Integration Service Environment to be created.
*/
public readonly virtualNetworkSubnetIds!: pulumi.Output<string[]>;
/**
* The list of access endpoint ip addresses of workflow.
*/
public /*out*/ readonly workflowEndpointIpAddresses!: pulumi.Output<string[]>;
/**
* The list of outgoing ip addresses of workflow.
*/
public /*out*/ readonly workflowOutboundIpAddresses!: pulumi.Output<string[]>;
/**
* Create a InterationServiceEnvironment resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: InterationServiceEnvironmentArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: InterationServiceEnvironmentArgs | InterationServiceEnvironmentState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as InterationServiceEnvironmentState | undefined;
inputs["accessEndpointType"] = state ? state.accessEndpointType : undefined;
inputs["connectorEndpointIpAddresses"] = state ? state.connectorEndpointIpAddresses : undefined;
inputs["connectorOutboundIpAddresses"] = state ? state.connectorOutboundIpAddresses : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined;
inputs["skuName"] = state ? state.skuName : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["virtualNetworkSubnetIds"] = state ? state.virtualNetworkSubnetIds : undefined;
inputs["workflowEndpointIpAddresses"] = state ? state.workflowEndpointIpAddresses : undefined;
inputs["workflowOutboundIpAddresses"] = state ? state.workflowOutboundIpAddresses : undefined;
} else {
const args = argsOrState as InterationServiceEnvironmentArgs | undefined;
if ((!args || args.accessEndpointType === undefined) && !opts.urn) {
throw new Error("Missing required property 'accessEndpointType'");
}
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
if ((!args || args.virtualNetworkSubnetIds === undefined) && !opts.urn) {
throw new Error("Missing required property 'virtualNetworkSubnetIds'");
}
inputs["accessEndpointType"] = args ? args.accessEndpointType : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["skuName"] = args ? args.skuName : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["virtualNetworkSubnetIds"] = args ? args.virtualNetworkSubnetIds : undefined;
inputs["connectorEndpointIpAddresses"] = undefined /*out*/;
inputs["connectorOutboundIpAddresses"] = undefined /*out*/;
inputs["workflowEndpointIpAddresses"] = undefined /*out*/;
inputs["workflowOutboundIpAddresses"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(InterationServiceEnvironment.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering InterationServiceEnvironment resources.
*/
export interface InterationServiceEnvironmentState {
/**
* The type of access endpoint to use for the Integration Service Environment. Possible Values are `Internal` and `External`. Changing this forces a new Integration Service Environment to be created.
*/
accessEndpointType?: pulumi.Input<string>;
/**
* The list of access endpoint ip addresses of connector.
*/
connectorEndpointIpAddresses?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The list of outgoing ip addresses of connector.
*/
connectorOutboundIpAddresses?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The Azure Region where the Integration Service Environment should exist. Changing this forces a new Integration Service Environment to be created.
*/
location?: pulumi.Input<string>;
/**
* The name of the Integration Service Environment. Changing this forces a new Integration Service Environment to be created.
*/
name?: pulumi.Input<string>;
/**
* The name of the Resource Group where the Integration Service Environment should exist. Changing this forces a new Integration Service Environment to be created.
*/
resourceGroupName?: pulumi.Input<string>;
/**
* The sku name and capacity of the Integration Service Environment. Possible Values for `sku` element are `Developer` and `Premium` and possible values for the `capacity` element are from `0` to `10`. Defaults to `sku` of `Developer` with a `Capacity` of `0` (e.g. `Developer_0`). Changing this forces a new Integration Service Environment to be created when `sku` element is not the same with existing one.
*/
skuName?: pulumi.Input<string>;
/**
* A mapping of tags which should be assigned to the Integration Service Environment.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A list of virtual network subnet ids to be used by Integration Service Environment. Exactly four distinct ids to subnets must be provided. Changing this forces a new Integration Service Environment to be created.
*/
virtualNetworkSubnetIds?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The list of access endpoint ip addresses of workflow.
*/
workflowEndpointIpAddresses?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The list of outgoing ip addresses of workflow.
*/
workflowOutboundIpAddresses?: pulumi.Input<pulumi.Input<string>[]>;
}
/**
* The set of arguments for constructing a InterationServiceEnvironment resource.
*/
export interface InterationServiceEnvironmentArgs {
/**
* The type of access endpoint to use for the Integration Service Environment. Possible Values are `Internal` and `External`. Changing this forces a new Integration Service Environment to be created.
*/
accessEndpointType: pulumi.Input<string>;
/**
* The Azure Region where the Integration Service Environment should exist. Changing this forces a new Integration Service Environment to be created.
*/
location?: pulumi.Input<string>;
/**
* The name of the Integration Service Environment. Changing this forces a new Integration Service Environment to be created.
*/
name?: pulumi.Input<string>;
/**
* The name of the Resource Group where the Integration Service Environment should exist. Changing this forces a new Integration Service Environment to be created.
*/
resourceGroupName: pulumi.Input<string>;
/**
* The sku name and capacity of the Integration Service Environment. Possible Values for `sku` element are `Developer` and `Premium` and possible values for the `capacity` element are from `0` to `10`. Defaults to `sku` of `Developer` with a `Capacity` of `0` (e.g. `Developer_0`). Changing this forces a new Integration Service Environment to be created when `sku` element is not the same with existing one.
*/
skuName?: pulumi.Input<string>;
/**
* A mapping of tags which should be assigned to the Integration Service Environment.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A list of virtual network subnet ids to be used by Integration Service Environment. Exactly four distinct ids to subnets must be provided. Changing this forces a new Integration Service Environment to be created.
*/
virtualNetworkSubnetIds: pulumi.Input<pulumi.Input<string>[]>;
} | the_stack |
import {ServiceObject, ServiceObjectConfig} from '@google-cloud/common';
import * as promisify from '@google-cloud/promisify';
import arrify = require('arrify');
import * as assert from 'assert';
import {describe, it, before, beforeEach} from 'mocha';
import * as proxyquire from 'proxyquire';
import {CoreOptions, OptionsWithUri, Response} from 'request';
import * as uuid from 'uuid';
import {Change, CreateChangeRequest} from '../src/change';
import {Record, RecordObject, RecordMetadata} from '../src/record';
let promisified = false;
const fakePromisify = Object.assign({}, promisify, {
promisifyAll(esClass: Function, options: promisify.PromisifyAllOptions) {
if (esClass.name !== 'Zone') {
return;
}
promisified = true;
assert.deepStrictEqual(options.exclude, ['change', 'record']);
},
});
let parseOverride: Function | null;
const fakeDnsZonefile = {
parse() {
// eslint-disable-next-line prefer-spread, prefer-rest-params
return (parseOverride || (() => {})).apply(null, arguments);
},
};
let writeFileOverride: Function | null;
let readFileOverride: Function | null;
const fakeFs = {
readFile() {
// eslint-disable-next-line prefer-spread, prefer-rest-params
return (readFileOverride || (() => {})).apply(null, arguments);
},
writeFile() {
// eslint-disable-next-line prefer-spread, prefer-rest-params
return (writeFileOverride || (() => {})).apply(null, arguments);
},
};
class FakeChange {
calledWith_: Array<{}>;
constructor(...args: Array<{}>) {
this.calledWith_ = args;
}
}
class FakeRecord {
calledWith_: Array<{}>;
constructor(...args: Array<{}>) {
this.calledWith_ = args;
}
static fromZoneRecord_(...args: Array<{}>) {
const record = new FakeRecord();
record.calledWith_ = args;
return record;
}
}
class FakeServiceObject extends ServiceObject {
calledWith_: Array<{}>;
constructor(config: ServiceObjectConfig, ...args: Array<{}>) {
super(config);
this.calledWith_ = args;
}
}
let extended = false;
const fakePaginator = {
paginator: {
extend(esClass: Function, methods: string[]) {
if (esClass.name !== 'Zone') {
return;
}
extended = true;
methods = arrify(methods);
assert.strictEqual(esClass.name, 'Zone');
assert.deepStrictEqual(methods, ['getChanges', 'getRecords']);
},
streamify(methodName: string) {
return methodName;
},
},
};
describe('Zone', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let Zone: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let zone: any;
const DNS = {
createZone() {},
};
const ZONE_NAME = 'zone-name';
before(() => {
Zone = proxyquire('../src/zone.js', {
'dns-zonefile': fakeDnsZonefile,
fs: fakeFs,
'@google-cloud/common': {
ServiceObject: FakeServiceObject,
},
'@google-cloud/promisify': fakePromisify,
'@google-cloud/paginator': fakePaginator,
'./change': {
Change: FakeChange,
},
'./record': {Record: FakeRecord},
}).Zone;
});
beforeEach(() => {
parseOverride = null;
readFileOverride = null;
writeFileOverride = null;
zone = new Zone(DNS, ZONE_NAME);
});
describe('instantiation', () => {
it('should promisify all the things', () => {
assert(promisified);
});
it('should extend the correct methods', () => {
assert(extended); // See `fakePaginator.extend`
});
it('should streamify the correct methods', () => {
assert.strictEqual(zone.getChangesStream, 'getChanges');
assert.strictEqual(zone.getRecordsStream, 'getRecords');
});
it('should localize the name', () => {
assert.strictEqual(zone.name, ZONE_NAME);
});
it('should inherit from ServiceObject', done => {
const dnsInstance = Object.assign({}, DNS, {
createZone: {
bind(context: {}) {
assert.strictEqual(context, dnsInstance);
done();
},
},
});
const zone = new Zone(dnsInstance, ZONE_NAME);
assert(zone instanceof ServiceObject);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const calledWith = (zone as any).calledWith_[0];
assert.strictEqual(calledWith.parent, dnsInstance);
assert.strictEqual(calledWith.baseUrl, '/managedZones');
assert.strictEqual(calledWith.id, ZONE_NAME);
assert.deepStrictEqual(calledWith.methods, {
create: true,
exists: true,
get: true,
getMetadata: true,
});
});
});
describe('addRecords', () => {
it('should create a change with additions', done => {
const records = ['a', 'b', 'c'];
zone.createChange = (
options: CreateChangeRequest,
callback: Function
) => {
assert.strictEqual(options.add, records);
callback();
};
zone.addRecords(records, done);
});
});
describe('change', () => {
it('should return a Change object', () => {
const changeId = 'change-id';
const change = zone.change(changeId);
assert(change instanceof FakeChange);
assert.strictEqual(change.calledWith_[0], zone);
assert.strictEqual(change.calledWith_[1], changeId);
});
});
describe('createChange', () => {
function generateRecord(recordJson?: {}) {
recordJson = Object.assign(
{
name: uuid.v1(),
type: uuid.v1(),
rrdatas: [uuid.v1(), uuid.v1()],
},
recordJson
);
return {
toJSON() {
return recordJson! as {rrdatas: Array<{}>};
},
};
}
it('should throw error if add or delete is not provided', () => {
assert.throws(() => {
zone.createChange({}, () => {});
}, /Cannot create a change with no additions or deletions/);
});
it('should parse and rename add to additions', done => {
const recordsToAdd = [generateRecord(), generateRecord()];
const expectedAdditions = recordsToAdd.map(x => x.toJSON());
zone.request = (reqOpts: CoreOptions) => {
assert.strictEqual(reqOpts.json.add, undefined);
assert.deepStrictEqual(reqOpts.json.additions, expectedAdditions);
done();
};
zone.createChange({add: recordsToAdd}, assert.ifError);
});
it('should parse and rename delete to deletions', done => {
const recordsToDelete = [generateRecord(), generateRecord()];
const expectedDeletions = recordsToDelete.map(x => x.toJSON());
zone.request = (reqOpts: CoreOptions) => {
assert.strictEqual(reqOpts.json.delete, undefined);
assert.deepStrictEqual(reqOpts.json.deletions, expectedDeletions);
done();
};
zone.createChange({delete: recordsToDelete}, assert.ifError);
});
it('should group changes by name and type', done => {
const recordsToAdd = [
generateRecord({name: 'name.com.', type: 'mx'}),
generateRecord({name: 'name.com.', type: 'mx'}),
];
zone.request = (reqOpts: CoreOptions) => {
const expectedRRDatas = recordsToAdd
.map(x => x.toJSON().rrdatas)
.reduce((acc, rrdata) => acc.concat(rrdata), []);
assert.deepStrictEqual(reqOpts.json.additions, [
{
name: 'name.com.',
type: 'mx',
rrdatas: expectedRRDatas,
},
]);
done();
};
zone.createChange({add: recordsToAdd}, assert.ifError);
});
it('should make correct API request', done => {
zone.request = (reqOpts: OptionsWithUri) => {
assert.strictEqual(reqOpts.method, 'POST');
assert.strictEqual(reqOpts.uri, '/changes');
done();
};
zone.createChange({add: []}, assert.ifError);
});
describe('error', () => {
const error = new Error('Error.');
const apiResponse = {a: 'b', c: 'd'};
beforeEach(() => {
zone.request = (reqOpts: {}, callback: Function) => {
callback(error, apiResponse);
};
});
it('should execute callback with error & API response', done => {
zone.createChange(
{add: []},
(err: Error, change: Change, apiResponse_: Response) => {
assert.strictEqual(err, error);
assert.strictEqual(apiResponse_, apiResponse);
done();
}
);
});
});
describe('success', () => {
const apiResponse = {id: 1, a: 'b', c: 'd'};
beforeEach(() => {
zone.request = (reqOpts: {}, callback: Function) => {
callback(null, apiResponse);
};
});
it('should execute callback with Change & API response', done => {
const change = {};
zone.change = (id: string) => {
assert.strictEqual(id, apiResponse.id);
return change;
};
zone.createChange(
{add: []},
(err: Error, change_: Change, apiResponse_: Response) => {
assert.ifError(err);
assert.strictEqual(change_, change);
assert.strictEqual(change_.metadata, apiResponse);
assert.strictEqual(apiResponse_, apiResponse);
done();
}
);
});
});
});
describe('delete', () => {
describe('force', () => {
it('should empty the zone', done => {
zone.empty = () => {
done();
};
zone.delete({force: true}, assert.ifError);
});
it('should try to delete again after emptying', done => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(FakeServiceObject.prototype as any).delete = () => {
done();
};
zone.empty = (callback: Function) => {
callback();
};
zone.delete({force: true}, assert.ifError);
});
});
});
describe('deleteRecords', () => {
it('should delete records by type if a string is given', done => {
const recordsToDelete = 'ns';
zone.deleteRecordsByType_ = (types: string[], callback: Function) => {
assert.deepStrictEqual(types, [recordsToDelete]);
callback();
};
zone.deleteRecords(recordsToDelete, done);
});
it('should create a change if record objects given', done => {
const recordsToDelete = {a: 'b', c: 'd'};
zone.createChange = (
options: CreateChangeRequest,
callback: Function
) => {
assert.deepStrictEqual(options.delete, [recordsToDelete]);
callback();
};
zone.deleteRecords(recordsToDelete, done);
});
});
describe('empty', () => {
it('should get all records', done => {
zone.getRecords = () => {
done();
};
zone.empty(assert.ifError);
});
describe('error', () => {
const error = new Error('Error.');
beforeEach(() => {
zone.getRecords = (callback: Function) => {
callback(error);
};
});
it('should execute callback with error', done => {
zone.empty((err: Error) => {
assert.strictEqual(err, error);
done();
});
});
});
describe('success', () => {
const records = [
{type: 'A'},
{type: 'AAAA'},
{type: 'CNAME'},
{type: 'MX'},
{type: 'NAPTR'},
{type: 'NS'},
{type: 'PTR'},
{type: 'SOA'},
{type: 'SPF'},
{type: 'SRV'},
{type: 'TXT'},
];
const expectedRecordsToDelete = records.filter(record => {
return record.type !== 'NS' && record.type !== 'SOA';
});
beforeEach(() => {
zone.getRecords = (callback: Function) => {
callback(null, records);
};
});
it('should execute callback if no records matched', done => {
zone.getRecords = (callback: Function) => {
callback(null, []);
};
zone.empty(done);
});
it('should delete non-NS and non-SOA records', done => {
zone.deleteRecords = (
recordsToDelete: string[],
callback: Function
) => {
assert.deepStrictEqual(recordsToDelete, expectedRecordsToDelete);
callback();
};
zone.empty(done);
});
});
});
describe('export', () => {
const path = './zonefile';
const records = [
{
toString() {
return 'a';
},
},
{
toString() {
return 'a';
},
},
{
toString() {
return 'a';
},
},
{
toString() {
return 'a';
},
},
];
const expectedZonefileContents = 'a\na\na\na';
beforeEach(() => {
zone.getRecords = (callback: Function) => {
callback(null, records);
};
});
describe('get records', () => {
describe('error', () => {
const error = new Error('Error.');
it('should execute callback with error', done => {
zone.getRecords = (callback: Function) => {
callback(error);
};
zone.export(path, (err: Error) => {
assert.strictEqual(err, error);
done();
});
});
});
describe('success', () => {
it('should get all records', done => {
zone.getRecords = () => {
done();
};
zone.export(path, assert.ifError);
});
});
});
describe('write file', () => {
it('should write correct zone file', done => {
writeFileOverride = (
path_: string,
content: string,
encoding: string
) => {
assert.strictEqual(path_, path);
assert.strictEqual(content, expectedZonefileContents);
assert.strictEqual(encoding, 'utf-8');
done();
};
zone.export(path, assert.ifError);
});
describe('error', () => {
const error = new Error('Error.');
beforeEach(() => {
writeFileOverride = (
path: string,
content: string,
encoding: string,
callback: Function
) => {
callback(error);
};
});
it('should execute the callback with an error', done => {
zone.export(path, (err: Error) => {
assert.strictEqual(err, error);
done();
});
});
});
describe('success', () => {
beforeEach(() => {
writeFileOverride = (
path: string,
content: string,
encoding: string,
callback: Function
) => {
callback();
};
});
it('should execute the callback', done => {
zone.export(path, (err: Error) => {
assert.ifError(err);
done();
});
});
});
});
});
describe('getChanges', () => {
it('should accept only a callback', done => {
zone.request = (reqOpts: CoreOptions) => {
assert.deepStrictEqual(reqOpts.qs, {});
done();
};
zone.getChanges(assert.ifError);
});
it('should accept a sort', done => {
const query = {sort: 'desc'};
zone.request = (reqOpts: CoreOptions) => {
assert.strictEqual(reqOpts.qs.sortOrder, 'descending');
assert.strictEqual(reqOpts.qs.sort, undefined);
done();
};
zone.getChanges(query, assert.ifError);
});
it('should make the correct API request', done => {
const query = {a: 'b', c: 'd'};
zone.request = (reqOpts: OptionsWithUri) => {
assert.strictEqual(reqOpts.uri, '/changes');
assert.strictEqual(reqOpts.qs, query);
done();
};
zone.getChanges(query, assert.ifError);
});
describe('error', () => {
const error = new Error('Error.');
const apiResponse = {a: 'b', c: 'd'};
beforeEach(() => {
zone.request = (reqOpts: {}, callback: Function) => {
callback(error, apiResponse);
};
});
it('should execute callback with error & API response', done => {
zone.getChanges(
{},
(
err: Error,
changes: Change[],
nextQuery: {},
apiResponse_: Response
) => {
assert.strictEqual(err, error);
assert.strictEqual(apiResponse_, apiResponse);
done();
}
);
});
});
describe('success', () => {
const apiResponse = {
changes: [{id: 1}],
};
beforeEach(() => {
zone.request = (reqOpts: {}, callback: Function) => {
callback(null, apiResponse);
};
});
it('should build a nextQuery if necessary', done => {
const nextPageToken = 'next-page-token';
const apiResponseWithNextPageToken = Object.assign({}, apiResponse, {
nextPageToken,
});
const expectedNextQuery = {
pageToken: nextPageToken,
};
zone.request = (reqOpts: {}, callback: Function) => {
callback(null, apiResponseWithNextPageToken);
};
zone.getChanges({}, (err: Error, changes: Change[], nextQuery: {}) => {
assert.ifError(err);
assert.deepStrictEqual(nextQuery, expectedNextQuery);
done();
});
});
it('should execute callback with Changes & API response', done => {
const change = {};
zone.change = (id: string) => {
assert.strictEqual(id, apiResponse.changes[0].id);
return change;
};
zone.getChanges(
{},
(
err: Error,
changes: Change[],
nextQuery: {},
apiResponse_: Response
) => {
assert.ifError(err);
assert.strictEqual(changes[0], change);
assert.strictEqual(changes[0].metadata, apiResponse.changes[0]);
assert.strictEqual(apiResponse_, apiResponse);
done();
}
);
});
});
});
describe('getRecords', () => {
describe('error', () => {
const error = new Error('Error.');
const apiResponse = {a: 'b', c: 'd'};
beforeEach(() => {
zone.request = (reqOpts: {}, callback: Function) => {
callback(error, apiResponse);
};
});
it('should execute callback with error & API response', done => {
zone.getRecords(
{},
(
err: Error,
changes: Change[],
nextQuery: {},
apiResponse_: Response
) => {
assert.strictEqual(err, error);
assert.strictEqual(apiResponse_, apiResponse);
done();
}
);
});
it('should not require a query', done => {
zone.getRecords((err: Error) => {
assert.strictEqual(err, error);
done();
});
});
});
describe('success', () => {
const apiResponse = {
rrsets: [{type: 'NS'}],
};
beforeEach(() => {
zone.request = (reqOpts: {}, callback: Function) => {
callback(null, apiResponse);
};
});
it('should execute callback with nextQuery if necessary', done => {
const nextPageToken = 'next-page-token';
const apiResponseWithNextPageToken = Object.assign({}, apiResponse, {
nextPageToken,
});
const expectedNextQuery = {pageToken: nextPageToken};
zone.request = (reqOpts: {}, callback: Function) => {
callback(null, apiResponseWithNextPageToken);
};
zone.getRecords({}, (err: Error, records: Record[], nextQuery: {}) => {
assert.ifError(err);
assert.deepStrictEqual(nextQuery, expectedNextQuery);
done();
});
});
it('should execute callback with Records & API response', done => {
const record = {};
zone.record = (type: string, recordObject: RecordObject) => {
assert.strictEqual(type, apiResponse.rrsets[0].type);
assert.strictEqual(recordObject, apiResponse.rrsets[0]);
return record;
};
zone.getRecords(
{},
(
err: Error,
records: Record[],
nextQuery: {},
apiResponse_: Response
) => {
assert.ifError(err);
assert.strictEqual(records[0], record);
assert.strictEqual(apiResponse_, apiResponse);
done();
}
);
it('should not require a query', done => {
zone.getRecords(done);
});
});
describe('filtering', () => {
it('should accept a string type', done => {
const types = ['MX', 'CNAME'];
zone.getRecords(types, (err: Error, records: Record[]) => {
assert.ifError(err);
assert.strictEqual(records.length, 0);
done();
});
});
it('should accept an array of types', done => {
const type = 'MX';
zone.getRecords(type, (err: Error, records: Record[]) => {
assert.ifError(err);
assert.strictEqual(records.length, 0);
done();
});
});
it('should not send filterByTypes_ in API request', done => {
zone.request = (reqOpts: CoreOptions) => {
assert.strictEqual(reqOpts.qs.filterByTypes_, undefined);
done();
};
zone.getRecords('NS', assert.ifError);
});
});
});
});
describe('import', () => {
const path = './zonefile';
it('should read from the file', done => {
readFileOverride = (path_: string, encoding: string) => {
assert.strictEqual(path, path);
assert.strictEqual(encoding, 'utf-8');
done();
};
zone.import(path, assert.ifError);
});
describe('error', () => {
const error = new Error('Error.');
beforeEach(() => {
readFileOverride = (
path: string,
encoding: string,
callback: Function
) => {
callback(error);
};
});
it('should execute the callback', done => {
zone.import(path, (err: Error) => {
assert.strictEqual(err, error);
done();
});
});
});
describe('success', () => {
const recordType = 'ns';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let parsedZonefile: any = {};
beforeEach(() => {
parsedZonefile = {
[recordType]: {a: 'b', c: 'd'},
};
parseOverride = () => {
return parsedZonefile;
};
readFileOverride = (
path: string,
encoding: string,
callback: Function
) => {
callback();
};
});
it('should add records', done => {
zone.addRecords = (
recordsToCreate: FakeRecord[],
callback: Function
) => {
assert.strictEqual(recordsToCreate.length, 1);
const recordToCreate = recordsToCreate[0];
assert(recordToCreate instanceof FakeRecord);
const args = recordToCreate.calledWith_;
assert.strictEqual(args[0], zone);
assert.strictEqual(args[1], recordType);
assert.strictEqual(args[2], parsedZonefile[recordType]);
callback();
};
zone.import(path, done);
});
it('should use the default ttl', done => {
const defaultTTL = '90';
parsedZonefile.$ttl = defaultTTL;
parsedZonefile[recordType] = {};
parsedZonefile.mx = {ttl: '180'};
zone.addRecords = (recordsToCreate: FakeRecord[]) => {
const record1 = recordsToCreate[0].calledWith_[2];
assert.strictEqual((record1 as RecordMetadata).ttl, defaultTTL);
const record2 = recordsToCreate[1].calledWith_[2];
assert.strictEqual((record2 as RecordMetadata).ttl, '180');
done();
};
zone.import(path, done);
});
});
});
describe('record', () => {
it('should return a Record object', () => {
const type = 'a';
const metadata = {a: 'b', c: 'd'};
const record = zone.record(type, metadata);
assert(record instanceof FakeRecord);
const args = record.calledWith_;
assert.strictEqual(args[0], zone);
assert.strictEqual(args[1], type);
assert.strictEqual(args[2], metadata);
});
});
describe('replaceRecords', () => {
it('should get records', done => {
const recordType = 'ns';
zone.getRecords = (recordType_: string) => {
assert.strictEqual(recordType_, recordType);
done();
};
zone.replaceRecords(recordType, [], assert.ifError);
});
describe('error', () => {
const error = new Error('Error.');
beforeEach(() => {
zone.getRecords = (recordType: string, callback: Function) => {
callback(error);
};
});
it('should execute callback with error', done => {
zone.replaceRecords('a', [], (err: Error) => {
assert.strictEqual(err, error);
done();
});
});
});
describe('success', () => {
const recordsToCreate = [
{a: 'b', c: 'd'},
{a: 'b', c: 'd'},
{a: 'b', c: 'd'},
];
const recordsToDelete = [
{a: 'b', c: 'd'},
{a: 'b', c: 'd'},
{a: 'b', c: 'd'},
];
beforeEach(() => {
zone.getRecords = (recordType: string, callback: Function) => {
callback(null, recordsToDelete);
};
});
it('should create a change', done => {
zone.createChange = (
options: CreateChangeRequest,
callback: Function
) => {
assert.strictEqual(options.add, recordsToCreate);
assert.strictEqual(options.delete, recordsToDelete);
callback();
};
zone.replaceRecords('a', recordsToCreate, done);
});
});
});
describe('deleteRecordsByType_', () => {
it('should get records', done => {
const recordType = 'ns';
zone.getRecords = (recordType_: string) => {
assert.strictEqual(recordType_, recordType);
done();
};
zone.deleteRecordsByType_(recordType, assert.ifError);
});
describe('error', () => {
const error = new Error('Error.');
beforeEach(() => {
zone.getRecords = (recordType: string, callback: Function) => {
callback(error);
};
});
it('should execute callback with error', done => {
zone.deleteRecordsByType_('a', (err: Error) => {
assert.strictEqual(err, error);
done();
});
});
});
describe('success', () => {
const recordsToDelete = [
{a: 'b', c: 'd'},
{a: 'b', c: 'd'},
{a: 'b', c: 'd'},
];
beforeEach(() => {
zone.getRecords = (recordType: string, callback: Function) => {
callback(null, recordsToDelete);
};
});
it('should execute callback if no records matched', done => {
zone.getRecords = (recordType: string, callback: Function) => {
callback(null, []);
};
zone.deleteRecordsByType_('a', done);
});
it('should delete records', done => {
zone.deleteRecords = (records: Record[], callback: Function) => {
assert.strictEqual(records, recordsToDelete);
callback();
};
zone.deleteRecordsByType_('a', done);
});
});
});
}); | the_stack |
import React, { CSSProperties, forwardRef, useMemo } from 'react';
import ReactEcharts from 'echarts-for-react';
import * as echarts from 'echarts/core';
import {
PictorialBarChart,
// 系列类型的定义后缀都为 SeriesOption
PictorialBarSeriesOption,
} from 'echarts/charts';
import {
TooltipComponent,
TooltipComponentOption,
// 组件类型的定义后缀都为 ComponentOption
GridComponent,
GridComponentOption,
SingleAxisComponent,
SingleAxisComponentOption,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { TooltipOption, YAXisOption } from 'echarts/types/dist/shared';
import { merge } from 'lodash-es';
import { imgLeftData, imgRightData } from './img';
import useTheme from '../../hooks/useTheme';
import useBaseChartConfig from '../../hooks/useBaseChartConfig';
import createLinearGradient from '../../utils/createLinearGradient';
// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
type ECOption = echarts.ComposeOption<
PictorialBarSeriesOption | TooltipComponentOption | GridComponentOption | SingleAxisComponentOption
>;
// 注册必须的组件
echarts.use([TooltipComponent, GridComponent, SingleAxisComponent, PictorialBarChart, CanvasRenderer]);
/**
* 双列水平条形图,对应figma柱状图6
*/
export default forwardRef<
ReactEcharts,
{
unit?: string | [string, string];
max: number | [number, number];
leftData: { name: string; data: { name: string; value: number }[] };
rightData: { name: string; data: { name: string; value: number }[] };
style?: CSSProperties;
config?: ECOption;
inModal?: boolean;
onEvents?: Record<string, (params?: any) => void>;
}
>(({ unit = '', max, leftData, rightData, style, config, inModal = false, onEvents }, ref) => {
const theme = useTheme();
const baseChartConfig = useBaseChartConfig(inModal);
const leftUnit = typeof unit === 'string' ? unit : unit[0];
const rightUnit = typeof unit === 'string' ? unit : unit[1];
const leftMax = typeof max === 'number' ? max : max[0];
const rightMax = typeof max === 'number' ? max : max[1];
const option = useMemo(() => {
return merge(
{
legend: {
...baseChartConfig.legend,
},
grid: [
{
show: false,
left: '7%',
top: '5%',
bottom: '10%',
width: '40%',
},
{
show: false,
left: '50%',
top: '5%',
bottom: '10%',
width: '0%',
},
{
show: false,
right: '7%',
top: '5%',
bottom: '10%',
width: '40%',
},
],
tooltip: {
...baseChartConfig.tooltip,
axisPointer: {
...(baseChartConfig.tooltip as TooltipOption).axisPointer,
type: 'shadow',
},
formatter: function (params: any) {
const str = `
<div style="display: flex; align-items: center;">
<div style="
width: 7px;
height: 7px;
background: linear-gradient(180deg, ${params[0]?.color?.colorStops?.[0]?.color} 0%, ${
params[0]?.color?.colorStops?.[1]?.color
} 100%);
margin-right: 4px;
border-radius: 7px;
"></div>
${params[0]?.seriesName}:${params[0]?.data?.value || params[0]?.data} ${params[0]?.data?.unit ?? ''}
</div>
`;
return `
<div style="
background: linear-gradient(180deg, rgba(18, 81, 204, 0.9) 0%, rgba(12, 49, 117, 0.9) 100%);
border: 1px solid #017AFF;
color: #fff;
font-size: ${inModal ? '18px' : '14px'};
line-height: ${inModal ? '25px' : '22px'};
padding: 5px;
border-radius: 6px;
">
<div>${params[0]?.name}</div>
${str}
</div>
`;
},
},
xAxis: [
{
type: 'value',
inverse: true,
name: leftUnit,
nameGap: 5,
nameLocation: 'end',
nameTextStyle: {
...theme.typography[inModal ? 'p0' : 'p2'],
color: theme.colors.gray100,
},
axisLine: {
...(baseChartConfig.xAxis as YAXisOption).axisLine,
show: true,
},
axisTick: {
show: true,
},
axisLabel: {
...(baseChartConfig.xAxis as YAXisOption).axisLabel,
show: true,
},
splitLine: {
show: false,
},
},
{
gridIndex: 1,
show: false,
},
{
gridIndex: 2,
show: true,
type: 'value',
inverse: false,
name: rightUnit,
nameGap: 5,
nameLocation: 'end',
nameTextStyle: {
...theme.typography[inModal ? 'p0' : 'p2'],
color: theme.colors.gray100,
},
axisLine: {
...(baseChartConfig.xAxis as YAXisOption).axisLine,
show: true,
},
axisTick: {
show: true,
},
axisLabel: {
...(baseChartConfig.xAxis as YAXisOption).axisLabel,
show: true,
},
splitLine: {
show: false,
},
},
],
yAxis: [
{
gridIndex: 0,
triggerEvent: true,
inverse: true,
data: getArrByKey(leftData.data, 'name'),
axisLine: {
show: false,
},
splitLine: {
show: false,
},
axisTick: {
show: false,
},
axisLabel: {
show: false,
},
},
{
gridIndex: 1,
type: 'category',
inverse: true,
axisLine: {
show: false,
},
axisTick: {
show: false,
},
axisLabel: {
...(baseChartConfig.yAxis as YAXisOption).axisLabel,
show: true,
interval: 0,
align: 'auto',
verticalAlign: 'middle',
},
data: getArrByKey(leftData.data, 'name'),
},
{
gridIndex: 2,
triggerEvent: true,
inverse: true,
data: getArrByKey(rightData.data, 'name'),
axisLine: {
show: false,
},
splitLine: {
show: false,
},
axisTick: {
show: false,
},
axisLabel: {
show: false,
},
},
],
series: [
// 左侧
{
name: leftData.name,
type: 'pictorialBar',
xAxisIndex: 0,
yAxisIndex: 0,
gridIndex: 0,
silent: true,
itemStyle: {
color: createLinearGradient(theme.colors.primary300, false),
},
symbolRepeat: 'fixed',
symbolMargin: 2,
symbol: 'rect',
symbolClip: true,
symbolSize: [3, 8],
symbolOffset: [-18, 0],
symbolPosition: 'start',
symbolBoundingData: leftMax * 0.85,
data: leftData.data,
z: 3,
animationEasing: 'elasticOut',
},
{
name: leftData.name,
type: 'pictorialBar',
xAxisIndex: 0,
yAxisIndex: 0,
gridIndex: 0,
itemStyle: {
color: theme.colors.assist1100,
opacity: 0.2,
},
symbolRepeat: 'fixed',
symbolMargin: 2,
symbol: 'rect',
symbolClip: true,
symbolSize: [3, 8],
symbolOffset: [-18, 0],
symbolPosition: 'start',
symbolBoundingData: leftMax * 0.85,
data: leftData.data.map(() => leftMax),
z: 2,
animationEasing: 'elasticOut',
},
{
name: leftData.name,
type: 'pictorialBar',
xAxisIndex: 0,
yAxisIndex: 0,
gridIndex: 0,
symbol: 'image://' + imgLeftData,
symbolOffset: [0, 0],
symbolSize: ['100%', 24],
symbolClip: true,
symbolBoundingData: leftMax,
data: leftData.data.map(() => leftMax),
z: 1,
},
// 右侧
{
name: rightData.name,
type: 'pictorialBar',
xAxisIndex: 2,
yAxisIndex: 2,
gridIndex: 2,
silent: true,
itemStyle: {
color: createLinearGradient(theme.colors.primary50, false),
},
symbolRepeat: 'fixed',
symbolMargin: 2,
symbol: 'rect',
symbolClip: true,
symbolSize: [3, 8],
symbolOffset: [18, 0],
symbolPosition: 'start',
symbolBoundingData: rightMax * 0.85,
data: rightData.data,
z: 3,
animationEasing: 'elasticOut',
},
{
name: rightData.name,
type: 'pictorialBar',
xAxisIndex: 2,
yAxisIndex: 2,
gridIndex: 2,
itemStyle: {
color: theme.colors.assist1100,
opacity: 0.2,
},
symbolRepeat: 'fixed',
symbolMargin: 2,
symbol: 'rect',
symbolClip: true,
symbolOffset: [18, 0],
symbolSize: [3, 8],
symbolPosition: 'start',
symbolBoundingData: rightMax * 0.85,
data: rightData.data.map(() => rightMax),
z: 2,
animationEasing: 'elasticOut',
},
{
name: rightData.name,
type: 'pictorialBar',
xAxisIndex: 2,
yAxisIndex: 2,
gridIndex: 2,
symbol: 'image://' + imgRightData,
symbolOffset: [0, 0],
symbolSize: ['100%', 24],
symbolClip: true,
symbolBoundingData: rightMax,
data: rightData.data.map(() => rightMax),
z: 1,
},
],
},
config
) as ECOption;
}, [
baseChartConfig.legend,
baseChartConfig.tooltip,
baseChartConfig.xAxis,
baseChartConfig.yAxis,
leftUnit,
theme.typography,
theme.colors.gray100,
theme.colors.primary300,
theme.colors.assist1100,
theme.colors.primary50,
inModal,
rightUnit,
leftData.data,
leftData.name,
rightData.data,
rightData.name,
leftMax,
rightMax,
config,
]);
return <ReactEcharts ref={ref} echarts={echarts} option={option} style={style} onEvents={onEvents} />;
});
function getArrByKey(list: { name: string; value: number }[], key: string) {
return list.map(item => item[key]);
} | the_stack |
import * as babel from '@babel/types';
import * as jsdoc from 'doctrine';
import * as fsExtra from 'fs-extra';
import * as minimatch from 'minimatch';
import * as path from 'path';
import * as analyzer from 'polymer-analyzer';
import {Function as AnalyzerFunction} from 'polymer-analyzer/lib/javascript/function';
import Uri from 'vscode-uri';
import {closureParamToTypeScript, closureTypeToTypeScript} from './closure-types';
import {isEsModuleDocument, resolveImportExportFeature} from './es-modules';
import * as ts from './ts-ast';
/**
* Configuration for declaration generation.
*/
export interface Config {
/**
* Skip source files whose paths match any of these glob patterns. If
* undefined, defaults to excluding "index.html" and directories ending in
* "test" or "demo".
*/
excludeFiles?: string[];
/**
* The same as `excludeFiles`, for backwards compatibility. Will be removed in
* next major version.
*/
exclude?: string[];
/**
* Do not emit any declarations for features that have any of these
* identifiers.
*/
excludeIdentifiers?: string[];
/**
* Remove any triple-slash references to these files, specified as paths
* relative to the analysis root directory.
*/
removeReferences?: string[];
/**
* Additional files to insert as triple-slash reference statements. Given the
* map `a: b[]`, a will get an additional reference statement for each file
* path in b. All paths are relative to the analysis root directory.
*/
addReferences?: {[filepath: string]: string[]};
/**
* Whenever a type with a name in this map is encountered, replace it with
* the given name. Note this only applies to named types found in places like
* function/method parameters and return types. It does not currently rename
* e.g. entire generated classes.
*/
renameTypes?: {[name: string]: string};
/**
* A map from an ES module path (relative to the analysis root directory) to
* an array of identifiers exported by that module. If any of those
* identifiers are encountered in a generated typings file, an import for that
* identifier from the specified module will be inserted into the typings
* file.
*/
autoImport?: {[modulePath: string]: string[]};
/**
* If true, outputs declarations in 'goog:' modules instead of using
* simple ES modules. This is a temporary hack to account for how modules are
* resolved for TypeScript inside google3. This is probably not at all useful
* for anyone but the Polymer team.
*/
googModules?: boolean;
/**
* If true, does not log warnings detected when analyzing code,
* only diagnostics of Error severity.
*/
hideWarnings?: boolean;
}
const defaultExclude = [
'index.html',
'test/**',
'demo/**',
];
/**
* Analyze all files in the given directory using Polymer Analyzer, and return
* TypeScript declaration document strings in a map keyed by relative path.
*/
export async function generateDeclarations(
rootDir: string, config: Config): Promise<Map<string, string>> {
// Note that many Bower projects also have a node_modules/, but the reverse is
// unlikely.
const isBowerProject =
await fsExtra.pathExists(path.join(rootDir, 'bower_components')) === true;
const a = new analyzer.Analyzer({
urlLoader: new analyzer.FsUrlLoader(rootDir),
urlResolver: new analyzer.PackageUrlResolver({
packageDir: rootDir,
componentDir: isBowerProject ? 'bower_components/' : 'node_modules/',
}),
moduleResolution: isBowerProject ? undefined : 'node',
});
const analysis = await a.analyzePackage();
const outFiles = new Map<string, string>();
for (const tsDoc of await analyzerToAst(analysis, config, rootDir)) {
outFiles.set(tsDoc.path, tsDoc.serialize());
}
return outFiles;
}
/**
* Make TypeScript declaration documents from the given Polymer Analyzer
* result.
*/
async function analyzerToAst(
analysis: analyzer.Analysis, config: Config, rootDir: string):
Promise<ts.Document[]> {
const excludeFiles = (config.excludeFiles || config.exclude || defaultExclude)
.map((p) => new minimatch.Minimatch(p));
const addReferences = config.addReferences || {};
const removeReferencesResolved = new Set(
(config.removeReferences || []).map((r) => path.resolve(rootDir, r)));
const renameTypes = new Map(Object.entries(config.renameTypes || {}));
// Map from identifier to the module path that exports it.
const autoImportMap = new Map<string, string>();
if (config.autoImport !== undefined) {
for (const importPath in config.autoImport) {
for (const identifier of config.autoImport[importPath]) {
autoImportMap.set(identifier, importPath);
}
}
}
const analyzerDocs = [
...analysis.getFeatures({kind: 'html-document'}),
...analysis.getFeatures({kind: 'js-document'}),
];
// We want to produce one declarations file for each file basename. There
// might be both `foo.html` and `foo.js`, and we want their declarations to be
// combined into a signal `foo.d.ts`. So we first group Analyzer documents by
// their declarations filename.
const declarationDocs = new Map<string, analyzer.Document[]>();
for (const jsDoc of analyzerDocs) {
// For every HTML or JS file, Analyzer is going to give us 1) the top-level
// document, and 2) N inline documents for any nested content (e.g. script
// tags in HTML). The top-level document will give us all the nested
// features we need, so skip any inline ones.
if (jsDoc.isInline) {
continue;
}
const sourcePath = analyzerUrlToRelativePath(jsDoc.url, rootDir);
if (sourcePath === undefined) {
console.warn(
`Skipping source document without local file URL: ${jsDoc.url}`);
continue;
}
if (excludeFiles.some((r) => r.match(sourcePath))) {
continue;
}
const filename = makeDeclarationsFilename(sourcePath);
let docs = declarationDocs.get(filename);
if (!docs) {
docs = [];
declarationDocs.set(filename, docs);
}
docs.push(jsDoc);
}
const tsDocs = [];
const warnings = [...analysis.getWarnings()];
for (const [declarationsFilename, analyzerDocs] of declarationDocs) {
const tsDoc = new ts.Document({
path: declarationsFilename,
header: makeHeader(
analyzerDocs.map((d) => analyzerUrlToRelativePath(d.url, rootDir))
.filter((url): url is string => url !== undefined)),
tsLintDisables: [{
ruleName: 'variable-name',
why: `Describing an API that's defined elsewhere.`,
}],
});
for (const analyzerDoc of analyzerDocs) {
if (isEsModuleDocument(analyzerDoc)) {
tsDoc.isEsModule = true;
}
}
for (const analyzerDoc of analyzerDocs) {
const generator = new TypeGenerator(
tsDoc,
analysis,
analyzerDoc,
rootDir,
config.excludeIdentifiers || []);
generator.handleDocument();
warnings.push(...generator.warnings);
}
for (const ref of tsDoc.referencePaths) {
const resolvedRef = path.resolve(rootDir, path.dirname(tsDoc.path), ref);
if (removeReferencesResolved.has(resolvedRef)) {
tsDoc.referencePaths.delete(ref);
}
}
for (const ref of addReferences[tsDoc.path] || []) {
tsDoc.referencePaths.add(path.relative(path.dirname(tsDoc.path), ref));
}
for (const node of tsDoc.traverse()) {
if (node.kind === 'name') {
const renamed = renameTypes.get(node.name);
if (renamed !== undefined) {
node.name = renamed;
}
}
}
addAutoImports(tsDoc, autoImportMap);
tsDoc.simplify();
// Include even documents with no members. They might be dependencies of
// other files via the HTML import graph, and it's simpler to have empty
// files than to try and prune the references (especially across packages).
tsDocs.push(tsDoc);
}
const filteredWarnings = warnings.filter((warning) => {
if (config.hideWarnings && warning.severity !== analyzer.Severity.ERROR) {
return false;
}
const sourcePath =
analyzerUrlToRelativePath(warning.sourceRange.file, rootDir);
return sourcePath !== undefined &&
!excludeFiles.some((pattern) => pattern.match(sourcePath));
});
const warningPrinter =
new analyzer.WarningPrinter(process.stderr, {maxCodeLines: 1});
await warningPrinter.printWarnings(filteredWarnings);
if (filteredWarnings.some(
(warning) => warning.severity === analyzer.Severity.ERROR)) {
throw new Error('Encountered error generating types.');
}
if (config.googModules) {
return tsDocs.map((d) => transformToGoogStyle(d, rootDir));
}
return tsDocs;
}
/**
* Insert imports into the typings for any referenced identifiers listed in the
* autoImport configuration, unless they are already imported.
*/
function addAutoImports(tsDoc: ts.Document, autoImport: Map<string, string>) {
const alreadyImported = getImportedIdentifiers(tsDoc);
for (const node of tsDoc.traverse()) {
if (node.kind === 'name') {
let importSpecifier = autoImport.get(node.name);
if (importSpecifier === undefined) {
continue;
}
if (alreadyImported.has(node.name)) {
continue;
}
if (importSpecifier.startsWith('.')) {
if (makeDeclarationsFilename(importSpecifier) === tsDoc.path) {
// Don't import from yourself.
continue;
}
importSpecifier =
path.relative(path.dirname(tsDoc.path), importSpecifier);
if (!importSpecifier.startsWith('.')) {
importSpecifier = './' + importSpecifier;
}
}
tsDoc.members.push(new ts.Import({
identifiers: [{identifier: node.name}],
fromModuleSpecifier: importSpecifier,
}));
alreadyImported.add(node.name);
}
}
}
function getPackageName(rootDir: string) {
let packageInfo: {name?: string};
try {
packageInfo = JSON.parse(
fsExtra.readFileSync(path.join(rootDir, 'package.json'), 'utf-8'));
} catch {
return undefined;
}
return packageInfo.name;
}
function googModuleForNameBasedImportSpecifier(spec: string) {
const name =
// remove trailing .d.ts and .js
spec.replace(/(\.d\.ts|\.js)$/, '')
// foo-bar.dom becomes fooBarDom
.replace(/[-\.](\w)/g, (_, s) => s.toUpperCase())
// remove leading @
.replace(/^@/g, '')
// slash separated paths becomes dot separated namespace
.replace(/\//g, '.');
// add goog: at the beginning
return `goog:${name}`;
}
/* Note: this function modifies tsDoc. */
function transformToGoogStyle(tsDoc: ts.Document, rootDir: string) {
const packageName = getPackageName(rootDir);
if (!tsDoc.isEsModule || !packageName) {
return tsDoc;
}
for (const child of tsDoc.traverse()) {
if (child.kind === 'import' || child.kind === 'export') {
if (!child.fromModuleSpecifier) {
continue;
}
let spec = child.fromModuleSpecifier;
if (spec.startsWith('.')) {
spec = path.join(
packageName,
path.relative(
rootDir, path.join(rootDir, path.dirname(tsDoc.path), spec))
.replace(/^\.\//, ''));
}
const elementName = spec.split('/')[1];
let trailingComment: undefined|string = undefined;
if (elementName && !/\./.test(elementName)) {
trailingComment =
` // from //third_party/javascript/polymer/v2/${elementName}`;
}
const googSpecifier = googModuleForNameBasedImportSpecifier(spec);
if (googSpecifier !== undefined) {
child.fromModuleSpecifier = googSpecifier;
child.trailingComment = trailingComment;
}
}
}
let googModuleName =
googModuleForNameBasedImportSpecifier(path.join(packageName, tsDoc.path));
if (googModuleName === undefined) {
googModuleName = tsDoc.path;
}
return new ts.Document({
path: tsDoc.path,
header: tsDoc.header,
referencePaths: tsDoc.referencePaths,
tsLintDisables: tsDoc.tsLintDisables,
isEsModule: false,
members: [new ts.Namespace(
{name: googModuleName, members: tsDoc.members, style: 'module'})]
});
}
/**
* Return all local identifiers imported by the given typings.
*/
function getImportedIdentifiers(tsDoc: ts.Document): Set<string> {
const identifiers = new Set<string>();
for (const member of tsDoc.members) {
if (member.kind === 'import') {
for (const {identifier, alias} of member.identifiers) {
if (identifier !== ts.AllIdentifiers) {
identifiers.add(alias || identifier);
}
}
}
}
return identifiers;
}
/**
* Analyzer always returns fully specified URLs with a protocol and an absolute
* path (e.g. "file:/foo/bar"). Return just the file path, relative to our
* project root.
*/
function analyzerUrlToRelativePath(
analyzerUrl: string, rootDir: string): string|undefined {
const parsed = Uri.parse(analyzerUrl);
if (parsed.scheme !== 'file' || parsed.authority || !parsed.fsPath) {
return undefined;
}
return path.relative(rootDir, parsed.fsPath);
}
/**
* Create a TypeScript declarations filename for the given source document URL.
* Simply replaces the file extension with `d.ts`.
*/
function makeDeclarationsFilename(sourceUrl: string): string {
const parsed = path.parse(sourceUrl);
return path.join(parsed.dir, parsed.name) + '.d.ts';
}
/**
* Generate the header comment to show at the top of a declarations document.
*/
function makeHeader(sourceUrls: string[]): string {
return `DO NOT EDIT
This file was automatically generated by
https://github.com/Polymer/tools/tree/master/packages/gen-typescript-declarations
To modify these typings, edit the source file(s):
${sourceUrls.map((url) => ' ' + url).join('\n')}`;
}
class TypeGenerator {
public warnings: analyzer.Warning[] = [];
private excludeIdentifiers: Set<String>;
/**
* Identifiers in this set will always be considered resolvable, e.g.
* for when determining what identifiers should be exported.
*/
private forceResolvable = new Set<string>();
constructor(
private root: ts.Document, private analysis: analyzer.Analysis,
private analyzerDoc: analyzer.Document, private rootDir: string,
excludeIdentifiers: string[]) {
this.excludeIdentifiers = new Set(excludeIdentifiers);
}
private warn(feature: analyzer.Feature, message: string) {
this.warnings.push(new analyzer.Warning({
message,
sourceRange: feature.sourceRange!,
severity: analyzer.Severity.WARNING,
// We don't really need specific codes.
code: 'GEN_TYPESCRIPT_DECLARATIONS_WARNING',
parsedDocument: this.analyzerDoc.parsedDocument,
}));
}
/**
* Extend the given TypeScript declarations document with all of the relevant
* items in the given Polymer Analyzer document.
*/
handleDocument() {
for (const feature of this.analyzerDoc.getFeatures()) {
if ([...feature.identifiers].some(
(id) => this.excludeIdentifiers.has(id))) {
continue;
}
if (isPrivate(feature)) {
continue;
}
if (feature.kinds.has('element')) {
this.handleElement(feature as analyzer.Element);
} else if (feature.kinds.has('behavior')) {
this.handleBehavior(feature as analyzer.PolymerBehavior);
} else if (feature.kinds.has('element-mixin')) {
this.handleMixin(feature as analyzer.ElementMixin);
} else if (feature.kinds.has('class')) {
this.handleClass(feature as analyzer.Class);
} else if (feature.kinds.has('function')) {
this.handleFunction(feature as AnalyzerFunction);
} else if (feature.kinds.has('namespace')) {
this.handleNamespace(feature as analyzer.Namespace);
} else if (feature.kinds.has('html-import')) {
// Sometimes an Analyzer document includes an import feature that is
// inbound (things that depend on me) instead of outbound (things I
// depend on). For example, if an HTML file has a <script> tag for a JS
// file, then the JS file's Analyzer document will include that <script>
// tag as an import feature. We only care about outbound dependencies,
// hence this check.
if (feature.sourceRange &&
feature.sourceRange.file === this.analyzerDoc.url) {
this.handleHtmlImport(feature as analyzer.Import);
}
} else if (feature.kinds.has('js-import')) {
this.handleJsImport(feature as analyzer.JavascriptImport);
} else if (feature.kinds.has('export')) {
this.handleJsExport(feature as analyzer.Export);
}
}
}
/**
* Add the given Element to the given TypeScript declarations document.
*/
private handleElement(feature: analyzer.Element) {
// Whether this element has a constructor that is assigned and can be
// called. If it does we'll emit a class, otherwise an interface.
let constructable;
let fullName; // Fully qualified reference, e.g. `Polymer.DomModule`.
let shortName; // Just the last part of the name, e.g. `DomModule`.
let parent; // Where in the namespace tree does this live.
if (feature.className) {
constructable = true;
let namespacePath;
[namespacePath, shortName] = splitReference(feature.className);
fullName = feature.className;
parent = findOrCreateNamespace(this.root, namespacePath);
} else if (feature.tagName) {
// No `className` means this is an element defined by a call to the
// Polymer function without a LHS assignment. We'll follow the convention
// of the Closure Polymer Pass, and emit a global namespace interface
// called `FooBarElement` (given a `tagName` of `foo-bar`). More context
// here:
//
// https://github.com/google/closure-compiler/wiki/Polymer-Pass#element-type-names-for-1xhybrid-call-syntax
// https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/PolymerClassDefinition.java#L128
constructable = false;
shortName = kebabToCamel(feature.tagName) + 'Element';
fullName = shortName;
parent = this.root;
} else {
this.warn(feature, `Could not find element name.`);
return;
}
const legacyPolymerInterfaces = [];
if (isPolymerElement(feature)) {
legacyPolymerInterfaces.push(...feature.behaviorAssignments.map(
(behavior) => behavior.identifier));
if (feature.isLegacyFactoryCall) {
if (this.root.isEsModule) {
legacyPolymerInterfaces.push('LegacyElementMixin');
if (!getImportedIdentifiers(this.root).has('LegacyElementMixin')) {
this.root.members.push(new ts.Import({
identifiers: [{identifier: 'LegacyElementMixin'}],
fromModuleSpecifier:
'@polymer/polymer/lib/legacy/legacy-element-mixin.js',
}));
}
} else {
legacyPolymerInterfaces.push('Polymer.LegacyElementMixin');
}
legacyPolymerInterfaces.push('HTMLElement');
}
}
if (constructable) {
this.handleClass(feature);
if (legacyPolymerInterfaces.length > 0) {
// Augment the class interface.
parent.members.push(new ts.Interface({
name: shortName,
extends: legacyPolymerInterfaces,
}));
}
} else {
parent.members.push(new ts.Interface({
name: shortName,
description: feature.description || feature.summary,
properties: this.handleProperties(feature.properties.values()),
// Don't worry about about static methods when we're not
// constructable. Since there's no handle to the constructor, they
// could never be called.
methods: this.handleMethods(feature.methods.values()),
extends: [
...feature.mixins.map((mixin) => mixin.identifier),
...legacyPolymerInterfaces,
],
}));
if (isPolymerElement(feature) && feature.isLegacyFactoryCall &&
this.root.isEsModule) {
this.root.members.push(
new ts.Export({identifiers: [{identifier: shortName}]}));
}
}
// The `HTMLElementTagNameMap` global interface maps custom element tag
// names to their definitions, so that TypeScript knows that e.g.
// `dom.createElement('my-foo')` returns a `MyFoo`. Augment the map with
// this custom element.
if (feature.tagName) {
const elementMap = findOrCreateInterface(
this.root.isEsModule ? findOrCreateGlobalNamespace(this.root) :
this.root,
'HTMLElementTagNameMap');
elementMap.properties.push(new ts.Property({
name: feature.tagName,
type: new ts.NameType(fullName),
}));
}
}
/**
* Add the given Polymer Behavior to the given TypeScript declarations
* document.
*/
private handleBehavior(feature: analyzer.PolymerBehavior) {
if (!feature.className) {
this.warn(feature, `Could not find a name for behavior.`);
return;
}
const [namespacePath, className] = splitReference(feature.className);
const ns = findOrCreateNamespace(this.root, namespacePath);
// An interface with the properties and methods that this behavior adds to
// an element. Note that behaviors are not classes, they are just data
// objects which the Polymer library uses to augment element classes.
ns.members.push(new ts.Interface({
name: className,
description: feature.description || feature.summary,
extends: feature.behaviorAssignments.map((b) => b.identifier),
properties: this.handleProperties(feature.properties.values()),
methods: this.handleMethods(feature.methods.values()),
}));
// The value that contains the actual definition of the behavior for
// Polymer. It's not important to know the shape of this object, so the
// `object` type is good enough. The main use of this is to make statements
// like `Polymer.mixinBehaviors([Polymer.SomeBehavior], ...)` compile.
ns.members.push(new ts.ConstValue({
name: className,
type: new ts.NameType('object'),
}));
}
/**
* Add the given Mixin to the given TypeScript declarations document.
*/
private handleMixin(feature: analyzer.ElementMixin) {
const [namespacePath, mixinName] = splitReference(feature.name);
const parentNamespace = findOrCreateNamespace(this.root, namespacePath);
const transitiveMixins = [...this.transitiveMixins(feature)];
const constructorName = mixinName + 'Constructor';
// The mixin function. It takes a constructor, and returns an intersection
// of 1) the given constructor, 2) the constructor for this mixin, 3) the
// constructors for any other mixins that this mixin also applies.
parentNamespace.members.push(new ts.Function({
name: mixinName,
description: feature.description,
templateTypes: ['T extends new (...args: any[]) => {}'],
params: [
new ts.ParamType({name: 'base', type: new ts.NameType('T')}),
],
returns: new ts.IntersectionType([
new ts.NameType('T'),
new ts.NameType(constructorName),
...transitiveMixins.map(
(mixin) => new ts.NameType(mixin.name + 'Constructor'))
]),
}));
if (this.root.isEsModule) {
// We need to import all of the synthetic constructor interfaces that our
// own signature references. We can assume they're exported from the same
// module that the mixin is defined in.
for (const mixin of transitiveMixins) {
if (mixin.sourceRange === undefined) {
continue;
}
const rootRelative =
analyzerUrlToRelativePath(mixin.sourceRange.file, this.rootDir);
if (rootRelative === undefined) {
continue;
}
const fileRelative =
path.relative(path.dirname(this.root.path), rootRelative);
const fromModuleSpecifier =
fileRelative.startsWith('.') ? fileRelative : './' + fileRelative;
const identifiers = [{identifier: mixin.name + 'Constructor'}];
if (!getImportedIdentifiers(this.root).has(mixin.name)) {
identifiers.push({identifier: mixin.name});
}
this.root.members.push(new ts.Import({
identifiers,
fromModuleSpecifier,
}));
}
}
// The interface for a constructor of this mixin. Returns the instance
// interface (see below) when instantiated, and may also have methods of its
// own (static methods from the mixin class).
parentNamespace.members.push(new ts.Interface({
name: constructorName,
methods: [
new ts.Method({
name: 'new',
params: [
new ts.ParamType({
name: 'args',
type: new ts.ArrayType(ts.anyType),
rest: true,
}),
],
returns: new ts.NameType(mixinName),
}),
...this.handleMethods(feature.staticMethods.values()),
],
}));
if (this.root.isEsModule) {
// If any other mixin applies us, it will need to import our synthetic
// constructor interface.
this.root.members.push(
new ts.Export({identifiers: [{identifier: constructorName}]}));
}
// The interface for instances of this mixin. Has the same name as the
// function.
parentNamespace.members.push(
new ts.Interface({
name: mixinName,
properties: this.handleProperties(feature.properties.values()),
methods: this.handleMethods(feature.methods.values()),
extends: transitiveMixins.map((mixin) => mixin.name),
}),
);
}
/**
* Mixins can automatically apply other mixins, indicated by the @appliesMixin
* annotation. However, since those mixins may themselves apply other mixins,
* to know the full set of them we need to traverse down the tree.
*/
private transitiveMixins(
parentMixin: analyzer.ElementMixin,
result?: Set<analyzer.ElementMixin>): Set<analyzer.ElementMixin> {
if (result === undefined) {
result = new Set();
}
for (const childRef of parentMixin.mixins) {
const childMixinSet = this.analysis.getFeatures(
{id: childRef.identifier, kind: 'element-mixin'});
if (childMixinSet.size !== 1) {
this.warn(
parentMixin,
`Found ${childMixinSet.size} features for mixin ` +
`${childRef.identifier}, expected 1.`);
continue;
}
const childMixin = childMixinSet.values().next().value;
result.add(childMixin);
this.transitiveMixins(childMixin, result);
}
return result;
}
/**
* Add the given Class to the given TypeScript declarations document.
*/
private handleClass(feature: analyzer.Class) {
if (!feature.className) {
this.warn(feature, `Could not find a name for class.`);
return;
}
const [namespacePath, name] = splitReference(feature.className);
const m = new ts.Class({name});
m.description = feature.description;
m.properties = this.handleProperties(feature.properties.values());
m.methods = [
...this.handleMethods(feature.staticMethods.values(), {isStatic: true}),
...this.handleMethods(feature.methods.values())
];
m.constructorMethod =
this.handleConstructorMethod(feature.constructorMethod);
if (feature.superClass !== undefined) {
m.extends = feature.superClass.identifier;
}
m.mixins = feature.mixins.map((mixin) => mixin.identifier);
findOrCreateNamespace(this.root, namespacePath).members.push(m);
}
/**
* Add the given Function to the given TypeScript declarations document.
*/
private handleFunction(feature: AnalyzerFunction) {
const [namespacePath, name] = splitReference(feature.name);
const f = new ts.Function({
name,
description: feature.description || feature.summary,
templateTypes: feature.templateTypes,
returns: closureTypeToTypeScript(
feature.return && feature.return.type, feature.templateTypes),
returnsDescription: feature.return && feature.return.desc
});
for (const param of feature.params || []) {
// TODO Handle parameter default values. Requires support from Analyzer
// which only handles this for class method parameters currently.
f.params.push(closureParamToTypeScript(
param.name, param.type, feature.templateTypes));
}
findOrCreateNamespace(this.root, namespacePath).members.push(f);
}
/**
* Convert the given Analyzer properties to their TypeScript declaration
* equivalent.
*/
private handleProperties(analyzerProperties: Iterable<analyzer.Property>):
ts.Property[] {
const tsProperties = <ts.Property[]>[];
for (const property of analyzerProperties) {
if (property.inheritedFrom || property.privacy === 'private' ||
this.excludeIdentifiers.has(property.name)) {
continue;
}
const p = new ts.Property({
name: property.name,
// TODO If this is a Polymer property with no default value, then the
// type should really be `<type>|undefined`.
type: closureTypeToTypeScript(property.type),
readOnly: property.readOnly,
});
p.description = property.description || '';
tsProperties.push(p);
}
return tsProperties;
}
/**
* Convert the given Analyzer methods to their TypeScript declaration
* equivalent.
*/
private handleMethods(analyzerMethods: Iterable<analyzer.Method>, opts?: {
isStatic?: boolean
}): ts.Method[] {
const tsMethods = <ts.Method[]>[];
for (const method of analyzerMethods) {
if (method.inheritedFrom || method.privacy === 'private' ||
this.excludeIdentifiers.has(method.name)) {
continue;
}
tsMethods.push(this.handleMethod(method, opts));
}
return tsMethods;
}
/**
* Convert the given Analyzer method to the equivalent TypeScript declaration
*/
private handleMethod(method: analyzer.Method, opts?: {isStatic?: boolean}):
ts.Method {
const m = new ts.Method({
name: method.name,
returns: closureTypeToTypeScript(method.return && method.return.type),
returnsDescription: method.return && method.return.desc,
isStatic: opts && opts.isStatic,
ignoreTypeCheck: this.documentationHasSuppressTypeCheck(method.jsdoc)
});
m.description = method.description || '';
let requiredAhead = false;
for (const param of reverseIter(method.params || [])) {
const tsParam = closureParamToTypeScript(param.name, param.type);
tsParam.description = param.description || '';
if (param.defaultValue !== undefined) {
// Parameters with default values generally behave like optional
// parameters. However, unlike optional parameters, they may be
// followed by a required parameter, in which case the default value is
// set by explicitly passing undefined.
if (!requiredAhead) {
tsParam.optional = true;
} else {
tsParam.type = new ts.UnionType([tsParam.type, ts.undefinedType]);
}
} else if (!tsParam.optional) {
requiredAhead = true;
}
// Analyzer might know this is a rest parameter even if there was no
// JSDoc type annotation (or if it was wrong).
tsParam.rest = tsParam.rest || !!param.rest;
if (tsParam.rest && tsParam.type.kind !== 'array') {
// Closure rest parameter types are written without the Array syntax,
// but in TypeScript they must be explicitly arrays.
tsParam.type = new ts.ArrayType(tsParam.type);
}
m.params.unshift(tsParam);
}
return m;
}
private documentationHasSuppressTypeCheck(annotation: jsdoc.Annotation|
undefined): boolean {
if (!annotation) {
return false;
}
const annotationValue = annotation.tags.find((e) => e.title === 'suppress');
return annotationValue && annotationValue.description === '{checkTypes}' ||
false;
}
private handleConstructorMethod(method?: analyzer.Method): ts.Method
|undefined {
if (!method) {
return;
}
const m = this.handleMethod(method);
m.returns = undefined;
return m;
}
/**
* Add the given namespace to the given TypeScript declarations document.
*/
private handleNamespace(feature: analyzer.Namespace) {
const ns = findOrCreateNamespace(this.root, feature.name.split('.'));
if (ns.kind === 'namespace') {
ns.description = feature.description || feature.summary || '';
}
}
/**
* Add a JavaScript import to the TypeScript declarations.
*/
private handleJsImport(feature: analyzer.JavascriptImport) {
const node = feature.astNode.node;
if (babel.isImportDeclaration(node)) {
const identifiers: ts.ImportSpecifier[] = [];
for (const specifier of node.specifiers) {
if (babel.isImportSpecifier(specifier)) {
// E.g. import {Foo, Bar as Baz} from './foo.js'
if (this.isResolvable(specifier.imported.name, feature)) {
identifiers.push({
identifier: specifier.imported.name,
alias: specifier.local.name,
});
}
} else if (babel.isImportDefaultSpecifier(specifier)) {
// E.g. import foo from './foo.js'
if (this.isResolvable('default', feature)) {
identifiers.push({
identifier: 'default',
alias: specifier.local.name,
});
}
} else if (babel.isImportNamespaceSpecifier(specifier)) {
// E.g. import * as foo from './foo.js'
identifiers.push({
identifier: ts.AllIdentifiers,
alias: specifier.local.name,
});
this.forceResolvable.add(specifier.local.name);
}
}
if (identifiers.length > 0) {
this.root.members.push(new ts.Import({
identifiers: identifiers,
fromModuleSpecifier: node.source && node.source.value,
}));
}
} else if (
// Exports are handled as exports below. Analyzer also considers them
// imports when they export from another module.
!babel.isExportNamedDeclaration(node) &&
!babel.isExportAllDeclaration(node)) {
this.warn(feature, `Import with AST type ${node.type} not supported.`);
}
}
/**
* Add a JavaScript export to the TypeScript declarations.
*/
private handleJsExport(feature: analyzer.Export) {
const node = feature.astNode.node;
if (babel.isExportAllDeclaration(node)) {
// E.g. export * from './foo.js'
this.root.members.push(new ts.Export({
identifiers: ts.AllIdentifiers,
fromModuleSpecifier: node.source && node.source.value,
}));
} else if (babel.isExportNamedDeclaration(node)) {
const identifiers = [];
if (node.declaration) {
// E.g. export class Foo {}
for (const identifier of feature.identifiers) {
if (this.isResolvable(identifier, feature)) {
identifiers.push({identifier});
}
}
} else {
// E.g. export {Foo, Bar as Baz}
for (const specifier of node.specifiers) {
if (this.isResolvable(specifier.exported.name, feature) ||
this.isResolvable(specifier.local.name, feature)) {
identifiers.push({
identifier: specifier.local.name,
alias: specifier.exported.name,
});
}
}
}
if (identifiers.length > 0) {
this.root.members.push(new ts.Export({
identifiers,
fromModuleSpecifier: node.source && node.source.value,
}));
}
} else {
this.warn(
feature,
`Export feature with AST node type ${node.type} not supported.`);
}
}
/**
* True if the given identifier can be resolved to a feature that will be
* exported as a TypeScript type.
*/
private isResolvable(
identifier: string,
fromFeature: analyzer.JavascriptImport|analyzer.Export) {
if (this.forceResolvable.has(identifier)) {
return true;
}
if (this.excludeIdentifiers.has(identifier)) {
return false;
}
const resolved =
resolveImportExportFeature(fromFeature, identifier, this.analyzerDoc);
return resolved !== undefined && resolved.feature !== undefined &&
!isPrivate(resolved.feature) && !isBehaviorImpl(resolved);
}
/**
* Add an HTML import to a TypeScript declarations file. For a given HTML
* import, we assume there is a corresponding declarations file that was
* generated by this same process.
*/
private handleHtmlImport(feature: analyzer.Import) {
let sourcePath = analyzerUrlToRelativePath(feature.url, this.rootDir);
if (sourcePath === undefined) {
this.warn(
feature,
`Skipping HTML import without local file URL: ${feature.url}`);
return;
}
// When we analyze a package's Git repo, our dependencies are installed to
// "<repo>/bower_components". However, when this package is itself installed
// as a dependency, our own dependencies will instead be siblings, one
// directory up the tree.
//
// Analyzer (since 2.5.0) will set an import feature's URL to the resolved
// dependency path as discovered on disk. An import for "../foo/foo.html"
// will be resolved to "bower_components/foo/foo.html". Transform the URL
// back to the style that will work when this package is installed as a
// dependency.
sourcePath =
sourcePath.replace(/^(bower_components|node_modules)\//, '../');
// Polymer is a special case where types are output to the "types/"
// subdirectory instead of as sibling files, in order to avoid cluttering
// the repo. It would be more pure to store this fact in the Polymer
// gen-tsd.json config file and discover it when generating types for repos
// that depend on it, but that's probably more complicated than we need,
// assuming no other repos deviate from emitting their type declarations as
// sibling files.
sourcePath = sourcePath.replace(/^\.\.\/polymer\//, '../polymer/types/');
this.root.referencePaths.add(path.relative(
path.dirname(this.root.path), makeDeclarationsFilename(sourcePath)));
}
}
/**
* Iterate over an array backwards.
*/
function* reverseIter<T>(arr: T[]) {
for (let i = arr.length - 1; i >= 0; i--) {
yield arr[i];
}
}
/**
* Find a document's global namespace declaration, or create one if it doesn't
* exist.
*/
function findOrCreateGlobalNamespace(doc: ts.Document): ts.GlobalNamespace {
for (const member of doc.members) {
if (member.kind === 'globalNamespace') {
return member;
}
}
const globalNamespace = new ts.GlobalNamespace();
doc.members.push(globalNamespace);
return globalNamespace;
}
/**
* Traverse the given node to find the namespace AST node with the given path.
* If it could not be found, add one and return it.
*/
function findOrCreateNamespace(
root: ts.Document|ts.Namespace|ts.GlobalNamespace,
path: string[]): ts.Document|ts.Namespace|ts.GlobalNamespace {
if (!path.length) {
return root;
}
let first: ts.Namespace|undefined;
for (const member of root.members) {
if (member.kind === 'namespace' && member.name === path[0]) {
first = member;
break;
}
}
if (!first) {
first = new ts.Namespace({name: path[0]});
root.members.push(first);
}
return findOrCreateNamespace(first, path.slice(1));
}
/**
* Traverse the given node to find the interface AST node with the given path.
* If it could not be found, add one and return it.
*/
function findOrCreateInterface(
root: ts.Document|ts.Namespace|ts.GlobalNamespace,
reference: string): ts.Interface {
const [namespacePath, name] = splitReference(reference);
const namespace_ = findOrCreateNamespace(root, namespacePath);
for (const member of namespace_.members) {
if (member.kind === 'interface' && member.name === name) {
return member;
}
}
const i = new ts.Interface({name});
namespace_.members.push(i);
return i;
}
/**
* Type guard that checks if a Polymer Analyzer feature is a PolymerElement.
*/
function isPolymerElement(feature: analyzer.Feature):
feature is analyzer.PolymerElement {
return feature.kinds.has('polymer-element');
}
/**
* Return whether a reference looks like it is a FooBehaviorImpl style behavior
* object, which we want to ignore.
*
* Polymer behavior libraries are often written like:
*
* /** @polymerBehavior FooBehavior *\/
* export const FooBehaviorImpl = {};
*
* /** @polymerBehavior *\/
* export const FooBehavior = [FooBehaviorImpl, OtherBehavior];
*
* In this case, Analyzer merges FooBehaviorImpl into FooBehavior and does not
* emit a behavior feature for FooBehaviorImpl. However, there is still an
* export feature for FooBehaviorImpl, so we exclude it here.
*/
function isBehaviorImpl(reference: analyzer.Reference<analyzer.Feature>) {
return reference.feature !== undefined &&
reference.feature.kinds.has('behavior') &&
(reference.feature as analyzer.PolymerBehavior).name !==
reference.identifier;
}
interface MaybePrivate {
privacy?: 'public'|'private'|'protected';
}
/**
* Return whether the given Analyzer feature has "private" visibility.
*/
function isPrivate(feature: analyzer.Feature&MaybePrivate): boolean {
return feature.privacy === 'private';
}
/**
* Convert kebab-case to CamelCase.
*/
function kebabToCamel(s: string): string {
return s.replace(/(^|-)(.)/g, (_match, _p0, p1) => p1.toUpperCase());
}
/**
* Split a reference into an array of namespace path parts, and a name part
* (e.g. `"Foo.Bar.Baz"` => `[ ["Foo", "Bar"], "Baz" ]`).
*/
function splitReference(reference: string): [string[], string] {
const parts = reference.split('.');
const namespacePath = parts.slice(0, -1);
const name = parts[parts.length - 1];
return [namespacePath, name];
} | the_stack |
import { Editor, MarkdownView, Notice, Plugin } from "obsidian";
import * as CodeMirror from "codemirror";
import ImageUploader from "./uploader/ImageUploader";
// eslint-disable-next-line import/no-cycle
import ImgurPluginSettingsTab from "./ui/ImgurPluginSettingsTab";
import ApiError from "./uploader/ApiError";
import UploadStrategy from "./UploadStrategy";
import buildUploaderFrom from "./uploader/imgUploaderFactory";
import RemoteUploadConfirmationDialog from "./ui/RemoteUploadConfirmationDialog";
export interface ImgurPluginSettings {
uploadStrategy: string;
clientId: string;
showRemoteUploadConfirmation: boolean;
}
const DEFAULT_SETTINGS: ImgurPluginSettings = {
uploadStrategy: UploadStrategy.ANONYMOUS_IMGUR.id,
clientId: null,
showRemoteUploadConfirmation: true,
};
type Handlers = {
drop: (cm: CodeMirror.Editor, event: DragEvent) => void;
paste: (cm: CodeMirror.Editor, event: ClipboardEvent) => void;
};
export default class ImgurPlugin extends Plugin {
settings: ImgurPluginSettings;
private readonly cmAndHandlersMap = new Map<CodeMirror.Editor, Handlers>();
private imgUploaderField: ImageUploader;
get imgUploader(): ImageUploader {
return this.imgUploaderField;
}
private async loadSettings() {
this.settings = {
...DEFAULT_SETTINGS,
...((await this.loadData()) as ImgurPluginSettings),
};
}
async saveSettings(): Promise<void> {
await this.saveData(this.settings);
}
onunload(): void {
this.restoreOriginalHandlers();
}
private restoreOriginalHandlers() {
this.cmAndHandlersMap.forEach((originalHandlers, cm) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(cm as any)._handlers.drop[0] = originalHandlers.drop;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(cm as any)._handlers.paste[0] = originalHandlers.paste;
});
}
async onload(): Promise<void> {
await this.loadSettings();
this.addSettingTab(new ImgurPluginSettingsTab(this.app, this));
this.setupImgurHandlers();
this.setupImagesUploader();
}
setupImagesUploader(): void {
this.imgUploaderField = buildUploaderFrom(this.settings);
}
private setupImgurHandlers() {
this.registerCodeMirror((cm: CodeMirror.Editor) => {
const originalHandlers = this.backupOriginalHandlers(cm);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(cm as any)._handlers.drop[0] = async (
_: CodeMirror.Editor,
event: DragEvent
) => {
if (!this.imgUploader) {
ImgurPlugin.showUnconfiguredPluginNotice();
originalHandlers.drop(_, event);
return;
}
if (
event.dataTransfer.types.length !== 1 ||
event.dataTransfer.types[0] !== "Files"
) {
originalHandlers.drop(_, event);
return;
}
// Preserve files before showing modal, otherwise they will be lost from the event
const { files } = event.dataTransfer;
if (this.settings.showRemoteUploadConfirmation) {
const modal = new RemoteUploadConfirmationDialog(this.app);
modal.open();
const userResp = await modal.response();
switch (userResp.shouldUpload) {
case undefined:
return;
case true:
if (userResp.alwaysUpload) {
this.settings.showRemoteUploadConfirmation = false;
this.saveSettings()
.then(() => {})
.catch(() => {});
}
break;
case false: {
// This case forces me to compose new event, the old does not have any files already
const filesArr: Array<File> = new Array<File>(files.length);
for (let i = 0; i < filesArr.length; i += 1) {
filesArr[i] = files[i];
}
originalHandlers.drop(
_,
ImgurPlugin.composeNewDragEvent(event, filesArr)
);
return;
}
default:
return;
}
}
for (let i = 0; i < files.length; i += 1) {
if (!files[i].type.startsWith("image")) {
// using original handlers if at least one of drag-and drop files is not an image
// It is not possible to call DragEvent.dataTransfer#clearData(images) here
// to split images and non-images processing
originalHandlers.drop(_, event);
return;
}
}
// Adding newline to avoid messing images pasted via default handler
// with any text added by the plugin
this.getEditor().replaceSelection("\n");
const promises: Promise<void>[] = [];
const filesFailedToUpload: File[] = [];
for (let i = 0; i < files.length; i += 1) {
const image = files[i];
const uploadPromise = this.uploadFileAndEmbedImgurImage(image).catch(
() => {
filesFailedToUpload.push(image);
}
);
promises.push(uploadPromise);
}
await Promise.all(promises);
if (filesFailedToUpload.length === 0) return;
const newEvt = ImgurPlugin.composeNewDragEvent(
event,
filesFailedToUpload
);
originalHandlers.drop(_, newEvt);
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(cm as any)._handlers.paste[0] = async (
_: CodeMirror.Editor,
e: ClipboardEvent
) => {
if (!this.imgUploader) {
ImgurPlugin.showUnconfiguredPluginNotice();
originalHandlers.paste(_, e);
return;
}
const { files } = e.clipboardData;
if (files.length === 0 || !files[0].type.startsWith("image")) {
originalHandlers.paste(_, e);
return;
}
if (this.settings.showRemoteUploadConfirmation) {
const modal = new RemoteUploadConfirmationDialog(this.app);
modal.open();
const userResp = await modal.response();
switch (userResp.shouldUpload) {
case undefined:
return;
case true:
if (userResp.alwaysUpload) {
this.settings.showRemoteUploadConfirmation = false;
this.saveSettings()
.then(() => {})
.catch(() => {});
}
break;
case false:
originalHandlers.paste(_, e);
return;
default:
return;
}
}
for (let i = 0; i < files.length; i += 1) {
this.uploadFileAndEmbedImgurImage(files[i]).catch(() => {
const dataTransfer = new DataTransfer();
dataTransfer.items.add(files[i]);
const newEvt = new ClipboardEvent("paste", {
clipboardData: dataTransfer,
});
originalHandlers.paste(_, newEvt);
});
}
};
});
}
private static composeNewDragEvent(
originalEvent: DragEvent,
failedUploads: File[]
) {
const dataTransfer = failedUploads.reduce((dt, fileFailedToUpload) => {
dt.items.add(fileFailedToUpload);
return dt;
}, new DataTransfer());
return new DragEvent(originalEvent.type, {
dataTransfer,
clientX: originalEvent.clientX,
clientY: originalEvent.clientY,
});
}
private static showUnconfiguredPluginNotice() {
const fiveSecondsMillis = 5_000;
// eslint-disable-next-line no-new
new Notice(
"⚠️ Please configure Imgur plugin or disable it",
fiveSecondsMillis
);
}
private backupOriginalHandlers(cm: CodeMirror.Editor) {
if (!this.cmAndHandlersMap.has(cm)) {
this.cmAndHandlersMap.set(cm, {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
drop: (cm as any)._handlers.drop[0],
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
paste: (cm as any)._handlers.paste[0],
});
}
return this.cmAndHandlersMap.get(cm);
}
private async uploadFileAndEmbedImgurImage(file: File) {
const pasteId = (Math.random() + 1).toString(36).substr(2, 5);
this.insertTemporaryText(pasteId);
let imgUrl: string;
try {
imgUrl = await this.imgUploaderField.upload(file);
} catch (e) {
if (e instanceof ApiError) {
this.handleFailedUpload(
pasteId,
`Upload failed, remote server returned an error: ${e.message}`
);
} else {
// eslint-disable-next-line no-console
console.error("Failed imgur request: ", e);
this.handleFailedUpload(
pasteId,
"⚠️Imgur upload failed, check dev console"
);
}
throw e;
}
this.embedMarkDownImage(pasteId, imgUrl);
}
private insertTemporaryText(pasteId: string) {
const progressText = ImgurPlugin.progressTextFor(pasteId);
this.getEditor().replaceSelection(`${progressText}\n`);
}
private static progressTextFor(id: string) {
return `![Uploading file...${id}]()`;
}
private embedMarkDownImage(pasteId: string, imageUrl: string) {
const progressText = ImgurPlugin.progressTextFor(pasteId);
const markDownImage = ``;
ImgurPlugin.replaceFirstOccurrence(
this.getEditor(),
progressText,
markDownImage
);
}
private handleFailedUpload(pasteId: string, message: string) {
const progressText = ImgurPlugin.progressTextFor(pasteId);
ImgurPlugin.replaceFirstOccurrence(
this.getEditor(),
progressText,
`<!--${message}-->`
);
}
private getEditor(): Editor {
const mdView = this.app.workspace.activeLeaf.view as MarkdownView;
return mdView.editor;
}
private static replaceFirstOccurrence(
editor: Editor,
target: string,
replacement: string
) {
const lines = editor.getValue().split("\n");
for (let i = 0; i < lines.length; i += 1) {
const ch = lines[i].indexOf(target);
if (ch !== -1) {
const from = { line: i, ch };
const to = { line: i, ch: ch + target.length };
editor.replaceRange(replacement, from, to);
break;
}
}
}
} | the_stack |
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { BaseDialog, IDialogConfiguration } from '@microsoft/sp-dialog';
import {
autobind, PrimaryButton, Button,
DialogFooter, DialogContent,
Spinner, SpinnerSize,
TagPicker, ITag, Label, Callout
} from '@microsoft/office-ui-fabric-react-bundle'; // 'office-ui-fabric-react';
import * as pnp from '@pnp/sp';
import {
IFillMetadataDialogContentProps, IFillMetadataDialogContentState, IMetadataNewsItem,
IMetadataRefinerInfo, ILookupInfo, ILookupFieldValue, unescapeHTML
} from '../../interfaces';
import styles from './FillMetadataDialog.module.scss';
class FillMetadataDialogContent extends React.Component<IFillMetadataDialogContentProps, IFillMetadataDialogContentState> {
private saveButtonElement: HTMLElement | null;
constructor(props) {
super(props);
this.state = {
loading: true,
submitting: false,
error: null,
hasError: false,
loadedItem: null
};
pnp.sp.setup({
sp: {
headers: {
Accept: 'application/json;odata=verbose'
},
baseUrl: this.props.webUrl
}
});
}
// To make component render quickly the actual data retrieval starts after initial render in componentDidMount event
public componentDidMount() {
this.loadItem();
}
// Rendering logic
public render(): JSX.Element {
return (
this.state.loading ?
(
<Spinner size={SpinnerSize.large} label='Loading...' ariaLive='assertive' />
) :
(<DialogContent
title={this.state.loadedItem.title}
onDismiss={this.props.close}
showCloseButton={true}
>
{this.state.hasError ?
<Callout
className={styles.errorCallout}
role={'alertdialog'}
gapSpace={0}
target={this.saveButtonElement}
onDismiss={() => this.setState({hasError: false})}
setInitialFocus={true}
>
<div>
<p className={styles.header}>
An error has occurred
</p>
</div>
<div className={styles.content}>
<p>
{this.state.error}
</p>
</div>
</Callout> :
null}
{/* For each lookup field in loaded item create a TagPicker component */}
{this.state.loadedItem.lookupMetadata.map((lm, i) => {
let selected = [];
if (lm.lookupValues != null && lm.lookupValues.length > 0) {
for (let val of lm.lookupValues) {
const filterResult = lm.allLookupValues.filter(v => v.lookupId == val.lookupId);
if (filterResult != null && filterResult.length > 0) {
selected.push({ key: filterResult[0].lookupId.toString(), name: unescapeHTML(filterResult[0].lookupValue)});
}
}
}
return (
<div style={{padding: "10px", minWidth: "400px", color: "white"}}>
<Label>{lm.lookupFieldDisplayName}</Label>
<TagPicker className={styles.tagPicker}
itemLimit={lm.lookupFieldIsMultiValue ? 100 : 1}
pickerSuggestionsProps={{
suggestionsHeaderText: 'Suggested items',
noResultsFoundText: 'No matches found',
}}
onResolveSuggestions={(filter, selectedItems) => this.resolveTagSuggestions(filter, selectedItems, lm.allLookupValues)}
defaultSelectedItems={selected}
onChange={(items?: ITag[]) => this.processTagItemsChange(items == null ? [] : items, lm.lookupFieldInternalName)}
/>
</div>);
})}
<DialogFooter>
<Button text='Cancel' title='Cancel' onClick={this.props.close} disabled={this.state.submitting} />
<span ref={(btn) => this.saveButtonElement = btn}>
<PrimaryButton
text='Save' title='Save' disabled={this.state.submitting}
onClick={() => this.submit(this.state.loadedItem)} />
</span>
</DialogFooter>
</DialogContent>)
);
}
// Update the state information to reflect the UI change in tag picker
@autobind
private processTagItemsChange(items: ITag[], fieldInternalName: string) {
for (let lm of this.state.loadedItem.lookupMetadata) {
if (lm.lookupFieldInternalName == fieldInternalName) {
lm.lookupValues = items.map(item => {
return {
lookupId: parseInt(item.key),
lookupValue: item.name
} as ILookupFieldValue;
});
break;
}
}
this.setState({ loadedItem: {...this.state.loadedItem}}, () => console.log(this.state.loadedItem));
}
// Return suggestons for a picker
@autobind
private resolveTagSuggestions(filterText: string, selectedItems: ITag[], allItems: ILookupFieldValue[]): ITag[] {
let results = [];
if (filterText) {
results = allItems
.filter(item => item.lookupValue != null && item.lookupValue.toLowerCase().indexOf(filterText.toLowerCase()) === 0)
.filter(item => !this.listContainsDocument({ key: item.lookupId.toString(), name: item.lookupValue }, selectedItems))
.map(r => {
return {
key: r.lookupId.toString(),
name: unescapeHTML(r.lookupValue)
} as ITag;
});
}
return results;
}
private listContainsDocument(tag: ITag, tagList: ITag[]) {
if (!tagList || !tagList.length || tagList.length === 0) {
return false;
}
return tagList.filter(compareTag => compareTag.key === tag.key).length > 0;
}
// Load current site pages item
// As well as load all items from all lookup lists
// Takes longer to load, but faster to fill once loaded
private loadItem() {
this.setState({loading: true});
const sitePagesName = 'Site Pages';
let refinerFieldInfos: IMetadataRefinerInfo[] = [];
// Load fields information from SitePages list
pnp.sp.web.lists.getByTitle(sitePagesName).fields.filter("ReadOnlyField eq false and Hidden eq false and substringof('Lookup',TypeAsString)")
.select("Title", "InternalName", "LookupList", "TypeAsString")
.get().then((res: any[]) => {
for (let f of res) {
if (!refinerFieldInfos.some(ri => ri.InternalName == f.InternalName)) {
refinerFieldInfos.push({
IsSelected: false,
DisplayName: f.Title,
InternalName: f.InternalName,
IsMultiValue: f.TypeAsString == 'Lookup' ? false : true,
List: f.LookupList
});
}
}
// Load all items from lookup lists
this.loadItemInternal(refinerFieldInfos).then(loadedItem => {
let allDataRetrievalPromises: Promise<any[]>[] = [];
for (let refinerInfo of refinerFieldInfos) {
let lookupMetadataItem = loadedItem.lookupMetadata.filter(lm => lm.lookupFieldInternalName == refinerInfo.InternalName)[0];
if (lookupMetadataItem != null) {
let promise = pnp.sp.web.lists.getById(lookupMetadataItem.lookupFieldLookupList).items.getAll();
allDataRetrievalPromises.push(promise);
promise.then(results => {
lookupMetadataItem.allLookupValues = results.map(result => {
return {
lookupId: result.ID,
lookupValue: result.Title
} as ILookupFieldValue;
});
});
}
}
Promise.all(allDataRetrievalPromises).then((promiseResults: any[][]) => {
this.setState({
loading: false,
loadedItem
});
}).catch(this.handleError);
});
}).catch(this.handleError);
}
// Load all items from lookup lists
private loadItemInternal(refinerFieldInfos: IMetadataRefinerInfo[]) {
let promise = new Promise<IMetadataNewsItem>((resolve, reject) => {
const noOfLookupsBeforeThrottle = 6;
let noOfRequests = Math.floor(refinerFieldInfos.length / noOfLookupsBeforeThrottle) + 1;
let loadPromises: Promise<any>[] = [];
let loadedItem = {
id: this.props.itemId,
content: null,
lookupMetadata: []
} as IMetadataNewsItem;
for (let i = 0; i < noOfRequests; i++) {
let numerOfRefinersToGet = noOfLookupsBeforeThrottle;
if (numerOfRefinersToGet + i * noOfLookupsBeforeThrottle > refinerFieldInfos.length) {
numerOfRefinersToGet = refinerFieldInfos.length % noOfLookupsBeforeThrottle;
}
let getFrom = 0;
let getTo = (i + 1) * numerOfRefinersToGet;
if (i > 0) {
getFrom = i * noOfLookupsBeforeThrottle - 1;
}
// Load the target item from SitePages list
let currentRefiners = refinerFieldInfos.slice(getFrom, getTo);
let p = this.constructNewsItemRequest(currentRefiners);
loadPromises.push(p);
p.then(item => {
loadedItem.title = item.Title;
for (let refinerInfo of currentRefiners) {
let lookupMetadataItem: ILookupInfo = null;
if (loadedItem.lookupMetadata.some(lm => lm.lookupFieldInternalName == refinerInfo.InternalName)) {
lookupMetadataItem = loadedItem.lookupMetadata.filter(lm => lm.lookupFieldInternalName == refinerInfo.InternalName)[0];
} else {
lookupMetadataItem = {
lookupFieldInternalName: refinerInfo.InternalName,
lookupFieldDisplayName: refinerInfo.DisplayName,
lookupFieldIsMultiValue: refinerInfo.IsMultiValue,
lookupFieldLookupList: refinerInfo.List,
lookupValues: [],
allLookupValues: []
};
loadedItem.lookupMetadata.push(lookupMetadataItem);
}
// TODO: ensure multilookup works as well
if (item[refinerInfo.InternalName] != null) {
lookupMetadataItem.lookupValues.push({
lookupId: item[refinerInfo.InternalName].Id,
lookupValue: item[refinerInfo.InternalName].Value
});
}
}
});
}
Promise.all(loadPromises).then(() => {
resolve(loadedItem);
});
});
return promise;
}
// Load target item from SitePages, return Promise object
private constructNewsItemRequest(ris: IMetadataRefinerInfo[]) {
const sitePagesName = 'Site Pages';
let toSelect: string[] = ["Title", "Author/Name", "Editor/Name", "Author/Title", "Editor/Title"];
let toExpand: string[] = ["Author", "Editor"];
ris.forEach(ri => {
toSelect.push(`${ri.InternalName}/Title`);
toSelect.push(`${ri.InternalName}/Id`);
toExpand.push(ri.InternalName);
});
let promise = pnp.sp.web.lists.getByTitle(sitePagesName).items.getById(this.props.itemId).select(...toSelect).expand(...toExpand).get();
return promise;
}
// Save state information to a list item
@autobind
private submit(itemInfo: IMetadataNewsItem): void {
this.setState({submitting: true});
let updateInfo = {};
for (let lm of itemInfo.lookupMetadata) {
if (lm.lookupValues == null || lm.lookupValues.length < 1) {
updateInfo[`${lm.lookupFieldInternalName}Id`] = null;
} else {
let values = lm.lookupValues.map(v => v.lookupId);
if (lm.lookupFieldIsMultiValue) {
updateInfo[`${lm.lookupFieldInternalName}Id`] = {results: values};
} else {
updateInfo[`${lm.lookupFieldInternalName}Id`] = values[0];
}
}
}
pnp.sp.web.lists.getByTitle('Site Pages').items.getById(itemInfo.id).update(updateInfo).then((res: pnp.ItemUpdateResult) => {
this.props.close();
}).catch(error => {
this.setState({
error: `There was a problem updating metadata.
Inner error: ${error.data.responseBody["odata.error"].message.value}`,
hasError: true,
submitting: false
});
});
}
private handleError(error: any) {
console.log(error);
this.setState({loading: false});
}
}
// Container component for dialog content
export default class FillMetadataDialog extends BaseDialog {
public itemId: number;
public webUrl: string;
public render(): void {
ReactDOM.render(<FillMetadataDialogContent
webUrl={this.webUrl}
close={this.close}
itemId={this.itemId}
submit={this.submit}
/>, this.domElement);
}
public getConfig(): IDialogConfiguration {
return {
isBlocking: false
};
}
@autobind
private submit(): void {
this.close();
}
} | the_stack |
import { IncomingHttpHeaders } from 'http';
export interface HttpServiceConfig {
baseURL?: string;
headers?: Record<string, any>;
}
export interface HttpServiceResponse<T extends any = any> {
protocol: string;
hostname: string;
path: string;
method: string;
headers: IncomingHttpHeaders;
statusCode: number;
statusMessage: string;
data: T;
}
export interface CredentialsInterface {
/**
* Consumer key
*/
clientKey: string;
/**
* Consumer secret
*/
clientSecret: string;
initiatorPassword: string;
securityCredential?: string;
certificatePath?: string | null;
}
export interface AuthorizeResponseInterface {
access_token: string;
expires_in: string;
}
export interface B2CInterface {
Initiator: string;
/**
* The amount to be transacted.
*/
Amount: number;
/**
* The Party sending the funds. Either msisdn or business short code
*/
PartyA: string;
/**
* The Party receiving the funds. Either msisdn or business short code
*/
PartyB: string;
/**
* This is a publicly accessible url where mpesa will send the response to when the request times out. Must accept POST requests
*/
QueueTimeOutURL: string;
/**
* This is a publicly accessible url where mpesa will send the response to. Must accept POST requests
*/
ResultURL: string;
/**
* `TransactionReversal` - Reversal for an erroneous C2B transaction.
*
* `SalaryPayment` - Used to send money from an employer to employees e.g. salaries
*
* `BusinessPayment` - Used to send money from business to customer e.g. refunds
*
* `PromotionPayment` - Used to send money when promotions take place e.g. raffle winners
*
* `AccountBalance` - Used to check the balance in a paybill/buy goods account (includes utility, MMF, Merchant, Charges paid account).
*
* `CustomerPayBillOnline` - Used to simulate a transaction taking place in the case of C2B Simulate Transaction or to initiate a transaction on behalf of the customer (STK Push).
*
* `TransactionStatusQuery` - Used to query the details of a transaction.
*
* `CheckIdentity` - Similar to STK push, uses M-Pesa PIN as a service.
*
* `BusinessPayBill` - Sending funds from one paybill to another paybill
*
* `BusinessBuyGoods` - sending funds from buy goods to another buy goods.
*
* `DisburseFundsToBusiness` - Transfer of funds from utility to MMF account.
*
* `BusinessToBusinessTransfer` - Transferring funds from one paybills MMF to another paybills MMF account.
*
* `BusinessTransferFromMMFToUtility` - Transferring funds from paybills MMF to another paybills utility account.
*
*/
CommandID: CommandID;
Occasion?: string;
Remarks?: string;
}
export type CommandID =
| 'SalaryPayment'
| 'BusinessPayment'
| 'PromotionPayment'
| 'AccountBalance'
| 'TransactionStatusQuery'
| 'TransactionReversal';
export interface B2CResponseInterface {
ConversationID: string;
OriginatorConversationID: string;
/**
* M-Pesa Result and Response Codes
*
* `0` - Success
*
* `1` - Insufficient Funds
*
* `2` - Less Than Minimum Transaction Value
*
* `3` - More Than Maximum Transaction Value
*
* `4` - Would Exceed Daily Transfer Limit
*
* `5` - Would Exceed Minimum Balance
*
* `6` - Unresolved Primary Party
*
* `7` - Unresolved Receiver Party
*
* `8` - Would Exceed Maxiumum Balance
*
* `11` - Debit Account Invalid
*
* `12` - Credit Account Invalid
*
* `13` - Unresolved Debit Account
*
* `14` - Unresolved Credit Account
*
* `15` - Duplicate Detected
*
* `17` - Internal Failure
*
* `20` - Unresolved Initiator
*
* `26` - Traffic blocking condition in place
*
*/
ResponseCode: string;
ResponseDescription: string;
}
export interface B2BInterface {
InitiatorName: string;
/**
* The amount to be transacted.
*/
Amount: number;
/**
* The Party sending the funds. Either msisdn or business short code
*/
PartyA: string;
/**
* The Party receiving the funds. Either msisdn or business short code
*/
PartyB: string;
/**
* This is what the customer would enter as the account number when making payment to a paybill
*/
AccountReference: any;
/**
* This is a publicly accessible url where mpesa will send the response to when the request times out. Must accept POST requests
*/
QueueTimeOutURL: string;
/**
* This is a publicly accessible url where mpesa will send the response to. Must accept POST requests
*/
ResultURL: string;
/**
* `TransactionReversal` - Reversal for an erroneous C2B transaction.
*
* `SalaryPayment` - Used to send money from an employer to employees e.g. salaries
*
* `BusinessPayment` - Used to send money from business to customer e.g. refunds
*
* `PromotionPayment` - Used to send money when promotions take place e.g. raffle winners
*
* `AccountBalance` - Used to check the balance in a paybill/buy goods account (includes utility, MMF, Merchant, Charges paid account).
*
* `CustomerPayBillOnline` - Used to simulate a transaction taking place in the case of C2B Simulate Transaction or to initiate a transaction on behalf of the customer (STK Push).
*
* `TransactionStatusQuery` - Used to query the details of a transaction.
*
* `CheckIdentity` - Similar to STK push, uses M-Pesa PIN as a service.
*
* `BusinessPayBill` - Sending funds from one paybill to another paybill
*
* `BusinessBuyGoods` - sending funds from buy goods to another buy goods.
*
* `DisburseFundsToBusiness` - Transfer of funds from utility to MMF account.
*
* `BusinessToBusinessTransfer` - Transferring funds from one paybills MMF to another paybills MMF account.
*
* `BusinessTransferFromMMFToUtility` - Transferring funds from paybills MMF to another paybills utility account.
*
*/
CommandID?: string;
/**
* Identifier types - both sender and receiver - identify an M-Pesa transaction’s sending and receiving party as either a shortcode, a till number or a MSISDN (phone number). There are three identifier types that can be used with M-Pesa APIs.
*
* `1` - MSISDN
*
* `2` - Till Number
*
* `4` - Shortcode
*/
SenderIdentifierType?: IdentifierType;
/**
* Identifier types - both sender and receiver - identify an M-Pesa transaction’s sending and receiving party as either a shortcode, a till number or a MSISDN (phone number). There are three identifier types that can be used with M-Pesa APIs.
*
* `1` - MSISDN
*
* `2` - Till Number
*
* `4` - Shortcode
*/
RecieverIdentifierType?: IdentifierType;
Remarks?: string;
}
export type IdentifierType = '1' | '2' | '4';
export interface AccountBalanceInterface {
Initiator: string;
/**
* The Party sending the funds. Either msisdn or business short code
*/
PartyA: string;
/**
* Identifier types - both sender and receiver - identify an M-Pesa transaction’s sending and receiving party as either a shortcode, a till number or a MSISDN (phone number). There are three identifier types that can be used with M-Pesa APIs.
*
* `1` - MSISDN
*
* `2` - Till Number
*
* `4` - Shortcode
*/
IdentifierType: IdentifierType;
/**
* This is a publicly accessible url where mpesa will send the response to when the request times out. Must accept POST requests
*/
QueueTimeOutURL: string;
/**
* This is a publicly accessible url where mpesa will send the response to. Must accept POST requests
*/
ResultURL: string;
/**
* `TransactionReversal` - Reversal for an erroneous C2B transaction.
*
* `SalaryPayment` - Used to send money from an employer to employees e.g. salaries
*
* `BusinessPayment` - Used to send money from business to customer e.g. refunds
*
* `PromotionPayment` - Used to send money when promotions take place e.g. raffle winners
*
* `AccountBalance` - Used to check the balance in a paybill/buy goods account (includes utility, MMF, Merchant, Charges paid account).
*
* `CustomerPayBillOnline` - Used to simulate a transaction taking place in the case of C2B Simulate Transaction or to initiate a transaction on behalf of the customer (STK Push).
*
* `TransactionStatusQuery` - Used to query the details of a transaction.
*
* `CheckIdentity` - Similar to STK push, uses M-Pesa PIN as a service.
*
* `BusinessPayBill` - Sending funds from one paybill to another paybill
*
* `BusinessBuyGoods` - sending funds from buy goods to another buy goods.
*
* `DisburseFundsToBusiness` - Transfer of funds from utility to MMF account.
*
* `BusinessToBusinessTransfer` - Transferring funds from one paybills MMF to another paybills MMF account.
*
* `BusinessTransferFromMMFToUtility` - Transferring funds from paybills MMF to another paybills utility account.
*
*/
CommandID: CommandID;
Remarks?: string;
}
export interface AccountBalanceResponseInterface {
OriginatorConversationID: string;
ConversationID: string;
/**
* M-Pesa Result and Response Codes
*
* `0` - Success
*
* `1` - Insufficient Funds
*
* `2` - Less Than Minimum Transaction Value
*
* `3` - More Than Maximum Transaction Value
*
* `4` - Would Exceed Daily Transfer Limit
*
* `5` - Would Exceed Minimum Balance
*
* `6` - Unresolved Primary Party
*
* `7` - Unresolved Receiver Party
*
* `8` - Would Exceed Maxiumum Balance
*
* `11` - Debit Account Invalid
*
* `12` - Credit Account Invalid
*
* `13` - Unresolved Debit Account
*
* `14` - Unresolved Credit Account
*
* `15` - Duplicate Detected
*
* `17` - Internal Failure
*
* `20` - Unresolved Initiator
*
* `26` - Traffic blocking condition in place
*
*/
ResponseCode: string;
ResponseDescription: string;
}
export interface TransactionStatusInterface {
Initiator: string;
TransactionID: string;
/**
* The Party sending the funds. Either msisdn or business short code
*/
PartyA: string;
/**
* Identifier types - both sender and receiver - identify an M-Pesa transaction’s sending and receiving party as either a shortcode, a till number or a MSISDN (phone number). There are three identifier types that can be used with M-Pesa APIs.
*
* `1` - MSISDN
*
* `2` - Till Number
*
* `4` - Shortcode
*/
IdentifierType: IdentifierType;
/**
* This is a publicly accessible url where mpesa will send the response to. Must accept POST requests
*/
ResultURL: string;
/**
* This is a publicly accessible url where mpesa will send the response to when the request times out. Must accept POST requests
*/
QueueTimeOutURL: string;
/**
* `TransactionReversal` - Reversal for an erroneous C2B transaction.
*
* `SalaryPayment` - Used to send money from an employer to employees e.g. salaries
*
* `BusinessPayment` - Used to send money from business to customer e.g. refunds
*
* `PromotionPayment` - Used to send money when promotions take place e.g. raffle winners
*
* `AccountBalance` - Used to check the balance in a paybill/buy goods account (includes utility, MMF, Merchant, Charges paid account).
*
* `CustomerPayBillOnline` - Used to simulate a transaction taking place in the case of C2B Simulate Transaction or to initiate a transaction on behalf of the customer (STK Push).
*
* `TransactionStatusQuery` - Used to query the details of a transaction.
*
* `CheckIdentity` - Similar to STK push, uses M-Pesa PIN as a service.
*
* `BusinessPayBill` - Sending funds from one paybill to another paybill
*
* `BusinessBuyGoods` - sending funds from buy goods to another buy goods.
*
* `DisburseFundsToBusiness` - Transfer of funds from utility to MMF account.
*
* `BusinessToBusinessTransfer` - Transferring funds from one paybills MMF to another paybills MMF account.
*
* `BusinessTransferFromMMFToUtility` - Transferring funds from paybills MMF to another paybills utility account.
*
*/
CommandID?: CommandID;
Remarks?: string;
Occasion?: string;
}
export interface TransactionStatusResponseInterface {
OriginatorConversationID: string;
ConversationID: string;
/**
* M-Pesa Result and Response Codes
*
* `0` - Success
*
* `1` - Insufficient Funds
*
* `2` - Less Than Minimum Transaction Value
*
* `3` - More Than Maximum Transaction Value
*
* `4` - Would Exceed Daily Transfer Limit
*
* `5` - Would Exceed Minimum Balance
*
* `6` - Unresolved Primary Party
*
* `7` - Unresolved Receiver Party
*
* `8` - Would Exceed Maxiumum Balance
*
* `11` - Debit Account Invalid
*
* `12` - Credit Account Invalid
*
* `13` - Unresolved Debit Account
*
* `14` - Unresolved Credit Account
*
* `15` - Duplicate Detected
*
* `17` - Internal Failure
*
* `20` - Unresolved Initiator
*
* `26` - Traffic blocking condition in place
*
*/
ResponseCode: string;
ResponseDescription: string;
}
export interface ReversalInterface {
Initiator: string;
TransactionID: string;
/**
* The amount to be transacted.
*/
Amount: number;
ReceiverParty: string;
/**
* This is a publicly accessible url where mpesa will send the response to. Must accept POST requests
*/
ResultURL: string;
/**
* This is a publicly accessible url where mpesa will send the response to when the request times out. Must accept POST requests
*/
QueueTimeOutURL: string;
/**
* `TransactionReversal` - Reversal for an erroneous C2B transaction.
*
* `SalaryPayment` - Used to send money from an employer to employees e.g. salaries
*
* `BusinessPayment` - Used to send money from business to customer e.g. refunds
*
* `PromotionPayment` - Used to send money when promotions take place e.g. raffle winners
*
* `AccountBalance` - Used to check the balance in a paybill/buy goods account (includes utility, MMF, Merchant, Charges paid account).
*
* `CustomerPayBillOnline` - Used to simulate a transaction taking place in the case of C2B Simulate Transaction or to initiate a transaction on behalf of the customer (STK Push).
*
* `TransactionStatusQuery` - Used to query the details of a transaction.
*
* `CheckIdentity` - Similar to STK push, uses M-Pesa PIN as a service.
*
* `BusinessPayBill` - Sending funds from one paybill to another paybill
*
* `BusinessBuyGoods` - sending funds from buy goods to another buy goods.
*
* `DisburseFundsToBusiness` - Transfer of funds from utility to MMF account.
*
* `BusinessToBusinessTransfer` - Transferring funds from one paybills MMF to another paybills MMF account.
*
* `BusinessTransferFromMMFToUtility` - Transferring funds from paybills MMF to another paybills utility account.
*
*/
CommandID: CommandID;
/**
* Identifier types - both sender and receiver - identify an M-Pesa transaction’s sending and receiving party as either a shortcode, a till number or a MSISDN (phone number). There are three identifier types that can be used with M-Pesa APIs.
*
* `1` - MSISDN
*
* `2` - Till Number
*
* `4` - Shortcode
*/
RecieverIdentifierType?: '1' | '2' | '4';
Remarks?: string;
Occasion?: string;
}
export interface ReversalResponseInterface {
OriginatorConversationID: string;
ConversationID: string;
/**
* M-Pesa Result and Response Codes
*
* `0` - Success
*
* `1` - Insufficient Funds
*
* `2` - Less Than Minimum Transaction Value
*
* `3` - More Than Maximum Transaction Value
*
* `4` - Would Exceed Daily Transfer Limit
*
* `5` - Would Exceed Minimum Balance
*
* `6` - Unresolved Primary Party
*
* `7` - Unresolved Receiver Party
*
* `8` - Would Exceed Maxiumum Balance
*
* `11` - Debit Account Invalid
*
* `12` - Credit Account Invalid
*
* `13` - Unresolved Debit Account
*
* `14` - Unresolved Credit Account
*
* `15` - Duplicate Detected
*
* `17` - Internal Failure
*
* `20` - Unresolved Initiator
*
* `26` - Traffic blocking condition in place
*
*/
ResponseCode: string;
ResponseDescription: string;
}
export interface StkPushInterface {
/**
* The organization shortcode used to receive the transaction.
*/
BusinessShortCode: number;
/**
* The amount to be transacted.
*/
Amount: number;
/**
* The Party sending the funds. Either msisdn or business short code
*/
PartyA: string;
/**
* The Party receiving the funds. Either msisdn or business short code
*/
PartyB: string;
/**
* The MSISDN of the involved party
*/
PhoneNumber: string;
/**
* This is a publicly accessible url where mpesa will send the response to. Must accept POST requests
*/
CallBackURL: string;
/**
* This is what the customer would enter as the account number when making payment to a paybill
*/
AccountReference: string;
/**
* Lipa Na Mpesa Pass Key.
*/
passKey: string;
TransactionType?: TransactionType;
TransactionDesc?: string;
}
export type TransactionType =
| 'CustomerPayBillOnline'
| 'CustomerBuyGoodsOnline';
export interface StkPushResponseInterface {
MerchantRequestID: string;
CheckoutRequestID: string;
/**
* M-Pesa Result and Response Codes
*
* `0` - Success
*
* `1` - Insufficient Funds
*
* `2` - Less Than Minimum Transaction Value
*
* `3` - More Than Maximum Transaction Value
*
* `4` - Would Exceed Daily Transfer Limit
*
* `5` - Would Exceed Minimum Balance
*
* `6` - Unresolved Primary Party
*
* `7` - Unresolved Receiver Party
*
* `8` - Would Exceed Maxiumum Balance
*
* `11` - Debit Account Invalid
*
* `12` - Credit Account Invalid
*
* `13` - Unresolved Debit Account
*
* `14` - Unresolved Credit Account
*
* `15` - Duplicate Detected
*
* `17` - Internal Failure
*
* `20` - Unresolved Initiator
*
* `26` - Traffic blocking condition in place
*
*/
ResponseCode: string;
ResponseDescription: string;
CustomerMessage: string;
}
export interface StkQueryInterface {
/**
* The organization shortcode used to receive the transaction.
*/
BusinessShortCode: number;
CheckoutRequestID: string;
passKey: any;
}
export interface StkQueryResponseInterface {
/**
* M-Pesa Result and Response Codes
*
* `0` - Success
*
* `1` - Insufficient Funds
*
* `2` - Less Than Minimum Transaction Value
*
* `3` - More Than Maximum Transaction Value
*
* `4` - Would Exceed Daily Transfer Limit
*
* `5` - Would Exceed Minimum Balance
*
* `6` - Unresolved Primary Party
*
* `7` - Unresolved Receiver Party
*
* `8` - Would Exceed Maxiumum Balance
*
* `11` - Debit Account Invalid
*
* `12` - Credit Account Invalid
*
* `13` - Unresolved Debit Account
*
* `14` - Unresolved Credit Account
*
* `15` - Duplicate Detected
*
* `17` - Internal Failure
*
* `20` - Unresolved Initiator
*
* `26` - Traffic blocking condition in place
*
*/
ResponseCode: string;
ResponseDescription: string;
MerchantRequestID: string;
CheckoutRequestID: string;
ResultCode: string;
ResultDesc: string;
}
export interface C2BRegisterInterface {
ShortCode: number;
/**
* This is a publicly accessible url where mpesa will send the confirmation to. Must accept POST requests
*/
ConfirmationURL: string;
/**
* This is a publicly accessible url where mpesa will send the validation to. Must accept POST requests
*/
ValidationURL: string;
ResponseType: ResponseType;
}
export type ResponseType = 'Completed' | 'Cancelled';
export interface C2BRegisterResponseInterface {
ConversationID: string;
OriginatorCoversationID: string;
ResponseDescription: string;
}
export interface C2BSimulateInterface {
/**
* `TransactionReversal` - Reversal for an erroneous C2B transaction.
*
* `SalaryPayment` - Used to send money from an employer to employees e.g. salaries
*
* `BusinessPayment` - Used to send money from business to customer e.g. refunds
*
* `PromotionPayment` - Used to send money when promotions take place e.g. raffle winners
*
* `AccountBalance` - Used to check the balance in a paybill/buy goods account (includes utility, MMF, Merchant, Charges paid account).
*
* `CustomerPayBillOnline` - Used to simulate a transaction taking place in the case of C2B Simulate Transaction or to initiate a transaction on behalf of the customer (STK Push).
*
* `TransactionStatusQuery` - Used to query the details of a transaction.
*
* `CheckIdentity` - Similar to STK push, uses M-Pesa PIN as a service.
*
* `BusinessPayBill` - Sending funds from one paybill to another paybill
*
* `BusinessBuyGoods` - sending funds from buy goods to another buy goods.
*
* `DisburseFundsToBusiness` - Transfer of funds from utility to MMF account.
*
* `BusinessToBusinessTransfer` - Transferring funds from one paybills MMF to another paybills MMF account.
*
* `BusinessTransferFromMMFToUtility` - Transferring funds from paybills MMF to another paybills utility account.
*
*/
CommandID: TransactionType;
/**
* The amount to be transacted.
*/
Amount: number;
/**
* Phone number
*/
Msisdn: number;
BillRefNumber?: any;
ShortCode: number;
}
export interface C2BSimulateResponseInterface {
ConversationID: string;
OriginatorCoversationID: string;
ResponseDescription: string;
} | the_stack |
import { TestApiProvider } from '@backstage/test-utils';
import { screen, render, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import {
SearchContextProvider,
useSearch,
searchApiRef,
} from '@backstage/plugin-search-react';
import { SearchFilter } from './SearchFilter';
const SearchContextFilterSpy = ({ name }: { name: string }) => {
const { filters } = useSearch();
const value = filters[name];
return (
<span data-testid={`${name}-filter-spy`}>
{Array.isArray(value) ? value.join(',') : value}
</span>
);
};
describe('SearchFilter.Autocomplete', () => {
const query = jest.fn().mockResolvedValue({});
const emptySearchContext = {
term: '',
types: [],
filters: {},
};
const name = 'field';
const values = ['value1', 'value2'];
it('renders as expected', async () => {
render(
<TestApiProvider apis={[[searchApiRef, { query }]]}>
<SearchContextProvider>
<SearchFilter.Autocomplete name={name} values={values} />
</SearchContextProvider>
</TestApiProvider>,
);
const autocomplete = screen.getByRole('combobox');
const input = within(autocomplete).getByRole('textbox');
await userEvent.click(input);
await waitFor(() => {
screen.getByRole('listbox');
});
expect(screen.getByRole('option', { name: values[0] })).toBeInTheDocument();
expect(screen.getByRole('option', { name: values[1] })).toBeInTheDocument();
});
it('renders as expected with async values', async () => {
render(
<TestApiProvider apis={[[searchApiRef, { query }]]}>
<SearchContextProvider>
<SearchFilter.Autocomplete name={name} values={async () => values} />
</SearchContextProvider>
</TestApiProvider>,
);
const autocomplete = screen.getByRole('combobox');
const input = within(autocomplete).getByRole('textbox');
await userEvent.click(input);
await waitFor(() => {
screen.getByRole('listbox');
});
expect(screen.getByRole('option', { name: values[0] })).toBeInTheDocument();
expect(screen.getByRole('option', { name: values[1] })).toBeInTheDocument();
});
it('does not affect unrelated filter state', async () => {
render(
<TestApiProvider apis={[[searchApiRef, { query }]]}>
<SearchContextProvider
initialState={{
...emptySearchContext,
...{ filters: { unrelated: 'value' } },
}}
>
<SearchFilter.Autocomplete name={name} values={values} />
<SearchContextFilterSpy name={name} />
<SearchContextFilterSpy name="unrelated" />
</SearchContextProvider>
</TestApiProvider>,
);
// The spy should show the initial value.
expect(screen.getByTestId('unrelated-filter-spy')).toHaveTextContent(
'value',
);
// Select a value from the autocomplete filter.
const autocomplete = screen.getByRole('combobox');
const input = within(autocomplete).getByRole('textbox');
await userEvent.click(input);
await waitFor(() => {
screen.getByRole('listbox');
});
await userEvent.click(screen.getByRole('option', { name: values[1] }));
// Wait for the autocomplete filter's value to change.
await waitFor(() => {
expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent(
values[1],
);
});
// Unrelated filter spy should maintain the same value.
expect(screen.getByTestId('unrelated-filter-spy')).toHaveTextContent(
'value',
);
});
describe('single', () => {
it('renders as expected with defaultValue', async () => {
render(
<TestApiProvider apis={[[searchApiRef, { query }]]}>
<SearchContextProvider>
<SearchFilter.Autocomplete
name={name}
values={values}
defaultValue={values[1]}
/>
<SearchContextFilterSpy name={name} />
</SearchContextProvider>
</TestApiProvider>,
);
const autocomplete = screen.getByRole('combobox');
const input = within(autocomplete).getByRole('textbox');
await waitFor(() => {
expect(input).toHaveValue(values[1]);
expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent(
values[1],
);
});
});
it('renders as expected with initial context', async () => {
render(
<TestApiProvider apis={[[searchApiRef, { query }]]}>
<SearchContextProvider
initialState={{
...emptySearchContext,
...{ filters: { [name]: values[0] } },
}}
>
<SearchFilter.Autocomplete name={name} values={values} />
<SearchContextFilterSpy name={name} />
</SearchContextProvider>
</TestApiProvider>,
);
const autocomplete = screen.getByRole('combobox');
const input = within(autocomplete).getByRole('textbox');
await waitFor(() => {
expect(input).toHaveValue(values[0]);
expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent(
values[0],
);
});
});
it('sets filter state when selecting a value', async () => {
render(
<TestApiProvider apis={[[searchApiRef, { query }]]}>
<SearchContextProvider>
<SearchFilter.Autocomplete name={name} values={values} />
<SearchContextFilterSpy name={name} />
</SearchContextProvider>
</TestApiProvider>,
);
// Select the first option in the autocomplete.
const autocomplete = screen.getByRole('combobox');
const input = within(autocomplete).getByRole('textbox');
await userEvent.click(input);
await waitFor(() => {
screen.getByRole('listbox');
});
await userEvent.click(screen.getByRole('option', { name: values[0] }));
// The value should be present in the context.
await waitFor(() => {
expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent(
values[0],
);
});
// Click the "Clear" button to remove the value.
const clearButton = within(autocomplete).getByLabelText('Clear');
await userEvent.click(clearButton);
// That value should have been unset from the context.
await waitFor(() => {
expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent('');
});
});
});
describe('multiple', () => {
it('renders as expected with defaultValue', async () => {
render(
<TestApiProvider apis={[[searchApiRef, { query }]]}>
<SearchContextProvider>
<SearchFilter.Autocomplete
multiple
name={name}
values={values}
defaultValue={values}
/>
<SearchContextFilterSpy name={name} />
</SearchContextProvider>
</TestApiProvider>,
);
await waitFor(() => {
expect(screen.getByText(values[0])).toBeInTheDocument();
expect(screen.getByText(values[1])).toBeInTheDocument();
expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent(
values.join(','),
);
});
});
it('renders as expected with initial context', async () => {
render(
<TestApiProvider apis={[[searchApiRef, { query }]]}>
<SearchContextProvider
initialState={{
...emptySearchContext,
...{ filters: { [name]: values } },
}}
>
<SearchFilter.Autocomplete multiple name={name} values={values} />
<SearchContextFilterSpy name={name} />
</SearchContextProvider>
</TestApiProvider>,
);
await waitFor(() => {
expect(screen.getByText(values[0])).toBeInTheDocument();
expect(screen.getByText(values[1])).toBeInTheDocument();
expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent(
values.join(','),
);
});
});
it('respects tag limit configuration', async () => {
render(
<TestApiProvider apis={[[searchApiRef, { query }]]}>
<SearchContextProvider>
<SearchFilter.Autocomplete
multiple
limitTags={1}
name={name}
values={values}
/>
</SearchContextProvider>
</TestApiProvider>,
);
const autocomplete = screen.getByRole('combobox');
const input = within(autocomplete).getByRole('textbox');
// Select the second value.
await userEvent.click(input);
await waitFor(() => {
screen.getByRole('listbox');
});
await userEvent.click(screen.getByRole('option', { name: values[1] }));
await waitFor(() => {
expect(
screen.getByRole('button', { name: values[1] }),
).toBeInTheDocument();
});
// Select the first value.
await userEvent.click(input);
await waitFor(() => {
screen.getByRole('listbox');
});
await userEvent.click(screen.getByRole('option', { name: values[0] }));
await waitFor(() => {
expect(
screen.getByRole('button', { name: values[0] }),
).toBeInTheDocument();
});
// Blur the field and only one tag should be shown with a +1.
input.blur();
expect(
screen.queryByRole('button', { name: values[0] }),
).not.toBeInTheDocument();
expect(screen.getByText('+1')).toBeInTheDocument();
});
it('sets filter state when selecting a value', async () => {
render(
<TestApiProvider apis={[[searchApiRef, { query }]]}>
<SearchContextProvider>
<SearchFilter.Autocomplete multiple name={name} values={values} />
<SearchContextFilterSpy name={name} />
</SearchContextProvider>
</TestApiProvider>,
);
const autocomplete = screen.getByRole('combobox');
// Select both values in the autocomplete.
const input = within(autocomplete).getByRole('textbox');
await userEvent.click(input);
await waitFor(() => {
screen.getByRole('listbox');
});
await userEvent.click(screen.getByRole('option', { name: values[0] }));
await userEvent.click(input);
await waitFor(() => {
screen.getByRole('listbox');
});
await userEvent.click(screen.getByRole('option', { name: values[1] }));
// Both options should be present in the context.
await waitFor(() => {
expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent(
values.join(','),
);
});
// Click the "Clear" button to remove the value.
const clearButton = within(autocomplete).getByLabelText('Clear');
await userEvent.click(clearButton);
// There should be no content in the filter context.
await waitFor(() => {
expect(screen.getByTestId(`${name}-filter-spy`)).toHaveTextContent('');
});
});
});
}); | the_stack |
export type Alignment = 1 | 2 | 4 | 8;
/* @internal */
export const littleEndian = new DataView(new Int32Array([1]).buffer).getInt32(0, /*littleEndian*/ true) === 1;
/* @internal */
export interface ArrayBufferViewConstructor {
new (size: number): ArrayBufferView & Record<number, number | bigint>;
new (buffer: ArrayBufferLike, byteOffset?: number): ArrayBufferView & Record<number, number | bigint>;
BYTES_PER_ELEMENT: number;
}
/* @internal */
export const enum NumberType {
Int8 = "Int8",
Int16 = "Int16",
Int32 = "Int32",
Uint8 = "Uint8",
Uint16 = "Uint16",
Uint32 = "Uint32",
Float32 = "Float32",
Float64 = "Float64",
BigInt64 = "BigInt64",
BigUint64 = "BigUint64",
}
type AtomicNumberTypes =
| NumberType.Int8
| NumberType.Int16
| NumberType.Int32
| NumberType.Uint8
| NumberType.Uint16
| NumberType.Uint32;
/* @internal */
export interface NumberTypeToType {
[NumberType.Int8]: number;
[NumberType.Int16]: number;
[NumberType.Int32]: number;
[NumberType.Uint8]: number;
[NumberType.Uint16]: number;
[NumberType.Uint32]: number;
[NumberType.Float32]: number;
[NumberType.Float64]: number;
[NumberType.BigInt64]: bigint;
[NumberType.BigUint64]: bigint;
}
/* @internal */
export interface NumberTypeToTypedArray {
[NumberType.Int8]: Int8Array;
[NumberType.Int16]: Int16Array;
[NumberType.Int32]: Int32Array;
[NumberType.Uint8]: Uint8Array;
[NumberType.Uint16]: Uint16Array;
[NumberType.Uint32]: Uint32Array;
[NumberType.Float32]: Float32Array;
[NumberType.Float64]: Float64Array;
[NumberType.BigInt64]: BigInt64Array;
[NumberType.BigUint64]: BigUint64Array;
}
type NumberTypeToCoersion<N extends NumberType> = (value: any) => NumberTypeToType[N];
/* @internal */
export function sizeOf(nt: NumberType): Alignment {
switch (nt) {
case NumberType.Int8:
case NumberType.Uint8:
return 1;
case NumberType.Int16:
case NumberType.Uint16:
return 2;
case NumberType.Int32:
case NumberType.Uint32:
case NumberType.Float32:
return 4;
case NumberType.Float64:
case NumberType.BigInt64:
case NumberType.BigUint64:
return 8;
}
}
/* @internal */
export function putValueInView(view: DataView, nt: NumberType, byteOffset: number, value: number | bigint, isLittleEndian?: boolean) {
if (view.buffer instanceof SharedArrayBuffer && isAtomic(nt) && typeof value === "number" && ((view.byteOffset + byteOffset) % sizeOf(nt)) === 0) {
return putValueInBuffer(view.buffer, nt, view.byteOffset + byteOffset, value, isLittleEndian);
}
switch (nt) {
case NumberType.Int8: return view.setInt8(byteOffset, coerceValue(nt, value));
case NumberType.Int16: return view.setInt16(byteOffset, coerceValue(nt, value), isLittleEndian);
case NumberType.Int32: return view.setInt32(byteOffset, coerceValue(nt, value), isLittleEndian);
case NumberType.Uint8: return view.setUint8(byteOffset, coerceValue(nt, value));
case NumberType.Uint16: return view.setUint16(byteOffset, coerceValue(nt, value), isLittleEndian);
case NumberType.Uint32: return view.setUint32(byteOffset, coerceValue(nt, value), isLittleEndian);
case NumberType.Float32: return view.setFloat32(byteOffset, coerceValue(nt, value), isLittleEndian);
case NumberType.Float64: return view.setFloat64(byteOffset, coerceValue(nt, value), isLittleEndian);
case NumberType.BigInt64: return view.setBigInt64(byteOffset, coerceValue(nt, value), isLittleEndian);
case NumberType.BigUint64: return view.setBigUint64(byteOffset, coerceValue(nt, value), isLittleEndian);
}
}
/* @internal */
export function getValueFromView<N extends NumberType>(view: DataView, nt: N, byteOffset: number, isLittleEndian?: boolean): NumberTypeToType[N];
/* @internal */
export function getValueFromView(view: DataView, nt: NumberType, byteOffset: number, isLittleEndian?: boolean): number | bigint {
// attempt an atomic read
if (view.buffer instanceof SharedArrayBuffer && isAtomic(nt) && ((view.byteOffset + byteOffset) % sizeOf(nt)) === 0) {
return getValueFromBuffer(view.buffer, nt, view.byteOffset + byteOffset, isLittleEndian);
}
switch (nt) {
case NumberType.Int8: return view.getInt8(byteOffset);
case NumberType.Int16: return view.getInt16(byteOffset, isLittleEndian);
case NumberType.Int32: return view.getInt32(byteOffset, isLittleEndian);
case NumberType.Uint8: return view.getUint8(byteOffset);
case NumberType.Uint16: return view.getUint16(byteOffset, isLittleEndian);
case NumberType.Uint32: return view.getUint32(byteOffset, isLittleEndian);
case NumberType.Float32: return view.getFloat32(byteOffset, isLittleEndian);
case NumberType.Float64: return view.getFloat64(byteOffset, isLittleEndian);
case NumberType.BigInt64: return view.getBigInt64(byteOffset, isLittleEndian);
case NumberType.BigUint64: return view.getBigUint64(byteOffset, isLittleEndian);
}
}
interface GenerationRecord<V> {
generation: number;
phase: number;
counter: number;
value: V;
}
class WeakGenerativeCache<K extends object, V> {
private _generations = [
// gen 0
[new WeakMap<K, GenerationRecord<V>>(), new WeakMap<K, GenerationRecord<V>>()],
// gen 1
[new WeakMap<K, GenerationRecord<V>>()],
// gen 2
[new WeakMap<K, GenerationRecord<V>>()],
];
private _gen0Phase = 0;
private _accessCounter = 0;
has(key: K) {
const record = this._find(key);
if (record) {
this._access(key, record);
return true;
}
return false;
}
get(key: K) {
const record = this._find(key);
if (record) {
this._access(key, record);
this._prune();
return record.value;
}
}
set(key: K, value: V) {
let record = this._find(key);
if (!record) {
this._prune();
record = { generation: 0, phase: this._gen0Phase, counter: 0, value };
this._generations[record.generation][record.phase].set(key, record);
}
else {
this._access(key, record);
this._prune();
record.value = value;
}
}
delete(key: K) {
const record = this._find(key);
if (record) {
this._generations[record.generation][record.phase].delete(key);
this._prune();
return true;
}
return false;
}
clear() {
for (const generation of this._generations) {
for (let i = 0; i < generation.length; i++) {
generation[i] = new WeakMap();
}
}
this._accessCounter = 0;
this._gen0Phase = 0;
}
private _find(key: K) {
for (const generation of this._generations) {
for (const phase of generation) {
const record = phase.get(key);
if (record) return record;
}
}
}
private _access(key: K, record: GenerationRecord<V>) {
if (record.generation < 2) {
record.counter++;
if (this._shouldPromote(record)) {
const currentGen = this._generations[record.generation][record.phase];
currentGen.delete(key);
record.generation++;
record.phase = 0;
record.counter = 1;
const nextGen = this._generations[record.generation][record.phase];
nextGen.set(key, record);
}
}
}
private _shouldPromote(record: GenerationRecord<V>) {
switch (record.generation) {
case 0: return record.counter >= 1;
case 1: return record.counter >= 2;
}
return false;
}
private _prune() {
this._accessCounter++;
if (this._accessCounter >= 10) {
this._gen0Phase = this._gen0Phase ? 0 : 1;
this._generations[0][this._gen0Phase] = new WeakMap()
this._accessCounter = 0;
}
}
}
const dataViewCache = new WeakGenerativeCache<ArrayBufferLike, DataView>();
const int8ArrayCache = new WeakGenerativeCache<SharedArrayBuffer, Int8Array>();
const int16ArrayCache = new WeakGenerativeCache<SharedArrayBuffer, Int16Array>();
const int32ArrayCache = new WeakGenerativeCache<SharedArrayBuffer, Int32Array>();
const uint8ArrayCache = new WeakGenerativeCache<SharedArrayBuffer, Uint8Array>();
const uint16ArrayCache = new WeakGenerativeCache<SharedArrayBuffer, Uint16Array>();
const uint32ArrayCache = new WeakGenerativeCache<SharedArrayBuffer, Uint32Array>();
const float32ArrayCache = new WeakGenerativeCache<SharedArrayBuffer, Float32Array>();
const float64ArrayCache = new WeakGenerativeCache<SharedArrayBuffer, Float64Array>();
const bigInt64ArrayCache = new WeakGenerativeCache<SharedArrayBuffer, BigInt64Array>();
const bigUint64ArrayCache = new WeakGenerativeCache<SharedArrayBuffer, BigUint64Array>();
/* @internal */
export function putValueInBuffer(buffer: ArrayBufferLike, nt: NumberType, byteOffset: number, value: number | bigint, isLittleEndian: boolean = false) {
// attempt an atomic write
if (buffer instanceof SharedArrayBuffer && isAtomic(nt) && typeof value === "number") {
const size = sizeOf(nt);
if ((byteOffset % size) === 0) {
// aligned within the buffer
const array = getTypedArray(buffer, nt);
const arrayIndex = byteOffset / size;
const coercedValue = coerceValue(nt, value);
const correctedValue = size === 1 || isLittleEndian === littleEndian ? coercedValue : swapByteOrder(nt, coercedValue);
Atomics.store(array, arrayIndex, correctedValue);
return;
}
}
putValueInView(getDataView(buffer), nt, byteOffset, value, isLittleEndian);
}
/* @internal */
export function getValueFromBuffer<N extends NumberType>(buffer: ArrayBufferLike, nt: N, byteOffset: number, isLittleEndian?: boolean): NumberTypeToType[N];
/* @internal */
export function getValueFromBuffer<N extends NumberType>(buffer: ArrayBufferLike, nt: N, byteOffset: number, isLittleEndian: boolean = false): number | bigint {
// attempt an atomic read
if (buffer instanceof SharedArrayBuffer && isAtomic(nt)) {
const size = sizeOf(nt);
if ((byteOffset % size) === 0) {
// aligned within the buffer
const array = getTypedArray(buffer, nt);
const arrayIndex = byteOffset / size;
const value = Atomics.load(array, arrayIndex);
return size === 1 || isLittleEndian === littleEndian ? value : swapByteOrder(nt, value);
}
}
return getValueFromView(getDataView(buffer), nt, byteOffset, isLittleEndian);
}
function getTypedArrayConstructor<N extends NumberType>(nt: N): new (buffer: ArrayBufferLike) => NumberTypeToTypedArray[N];
function getTypedArrayConstructor(nt: NumberType) {
switch (nt) {
case NumberType.Int8: return Int8Array;
case NumberType.Int16: return Int16Array;
case NumberType.Int32: return Int32Array;
case NumberType.Uint8: return Uint8Array;
case NumberType.Uint16: return Uint16Array;
case NumberType.Uint32: return Uint32Array;
case NumberType.Float32: return Float32Array;
case NumberType.Float64: return Float64Array;
case NumberType.BigInt64: return BigInt64Array;
case NumberType.BigUint64: return BigUint64Array;
}
}
function getTypedArrayCache<N extends NumberType>(nt: N): WeakGenerativeCache<SharedArrayBuffer, NumberTypeToTypedArray[N]>;
function getTypedArrayCache(nt: NumberType) {
switch (nt) {
case NumberType.Int8: return int8ArrayCache;
case NumberType.Int16: return int16ArrayCache;
case NumberType.Int32: return int32ArrayCache;
case NumberType.Uint8: return uint8ArrayCache;
case NumberType.Uint16: return uint16ArrayCache;
case NumberType.Uint32: return uint32ArrayCache;
case NumberType.Float32: return float32ArrayCache;
case NumberType.Float64: return float64ArrayCache;
case NumberType.BigInt64: return bigInt64ArrayCache;
case NumberType.BigUint64: return bigUint64ArrayCache;
}
}
function getTypedArray<N extends NumberType>(buffer: SharedArrayBuffer, nt: N): NumberTypeToTypedArray[N] {
const cache = getTypedArrayCache(nt);
let array = cache.get(buffer);
if (!array) {
const ctor = getTypedArrayConstructor(nt);
array = new ctor(buffer);
cache.set(buffer, array);
}
return array;
}
function getDataView(buffer: ArrayBufferLike) {
let view = dataViewCache.get(buffer);
if (!view) {
view = new DataView(buffer);
dataViewCache.set(buffer, view);
}
return view;
}
function isAtomic(nt: NumberType): nt is AtomicNumberTypes {
switch (nt) {
case NumberType.Int8:
case NumberType.Int16:
case NumberType.Int32:
case NumberType.Uint8:
case NumberType.Uint16:
case NumberType.Uint32:
return true;
}
return false;
}
const tempDataView = new DataView(new ArrayBuffer(8));
function swapByteOrder<N extends NumberType>(nt: N, value: NumberTypeToType[N]): NumberTypeToType[N] {
putValueInView(tempDataView, nt, 0, value, false);
return getValueFromView(tempDataView, nt, 0, true);
}
function getTypeCoersion<N extends NumberType>(nt: N): NumberTypeToCoersion<N>;
function getTypeCoersion(nt: NumberType) {
switch (nt) {
case NumberType.Int8:
case NumberType.Int16:
case NumberType.Int32:
case NumberType.Uint8:
case NumberType.Uint16:
case NumberType.Uint32:
case NumberType.Float32:
case NumberType.Float64:
return Number;
case NumberType.BigInt64:
case NumberType.BigUint64:
return BigInt;
}
}
const sizeCoersionArrays: { [N in NumberType]?: NumberTypeToTypedArray[N]; } = {};
/* @internal */
export function coerceValue<N extends NumberType>(nt: N, value: number | bigint): NumberTypeToType[N];
/* @internal */
export function coerceValue<N extends NumberType>(nt: N, value: number | bigint): number | bigint {
const typeCoersion = getTypeCoersion(nt);
const coerced = typeCoersion(value);
const sizeCoersionArray = sizeCoersionArrays[nt] || (sizeCoersionArrays[nt] = new (getTypedArrayConstructor(nt))(new ArrayBuffer(sizeOf(nt))));
sizeCoersionArray![0] = coerced;
return sizeCoersionArray![0];
} | the_stack |
import React from "react"
import ReactDOM from "react-dom"
import { observer } from "mobx-react"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faCommentAlt } from "@fortawesome/free-solid-svg-icons/faCommentAlt"
import { faTimes } from "@fortawesome/free-solid-svg-icons/faTimes"
import { observable, action, toJS, computed } from "mobx"
import classnames from "classnames"
import { faPaperPlane } from "@fortawesome/free-solid-svg-icons/faPaperPlane"
import { BAKED_BASE_URL } from "../settings/clientSettings"
import { stringifyUnkownError } from "../clientUtils/Util"
const sendFeedback = (feedback: Feedback) =>
new Promise((resolve, reject) => {
const json = toJS(feedback)
const req = new XMLHttpRequest()
json.environment = `Current URL: ${window.location.href}\nUser Agent: ${navigator.userAgent}\nViewport: ${window.innerWidth}x${window.innerHeight}`
req.addEventListener("readystatechange", () => {
if (req.readyState === 4) {
if (req.status !== 200)
reject(`${req.status} ${req.statusText}`)
else resolve(undefined)
}
})
req.open(
"POST",
`https://owid-feedback.netlify.app/.netlify/functions/hello`
)
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
req.send(JSON.stringify(json))
})
class Feedback {
@observable name: string = ""
@observable email: string = ""
@observable message: string = ""
environment: string = ""
@action.bound clear() {
this.name = ""
this.email = ""
this.message = ""
}
}
const vaccinationRegex = /vaccination|vaccine|doses|vaccinat/i
const licensingRegex = /license|licensing|copyright|permission|permit/i
const citationRegex = /cite|citation|citing|reference/i
const translateRegex = /translat/i
enum SpecialFeedbackTopic {
Vaccination,
Licensing,
Citation,
Translation,
}
interface SpecialTopicMatcher {
regex: RegExp
topic: SpecialFeedbackTopic
}
const topicMatchers: SpecialTopicMatcher[] = [
{ regex: vaccinationRegex, topic: SpecialFeedbackTopic.Vaccination },
{ regex: licensingRegex, topic: SpecialFeedbackTopic.Licensing },
{ regex: citationRegex, topic: SpecialFeedbackTopic.Citation },
{ regex: translateRegex, topic: SpecialFeedbackTopic.Translation },
]
const vaccineNotice = (
<a
key="vaccineNotice"
href={`${BAKED_BASE_URL}/covid-vaccinations#frequently-asked-questions`}
target="_blank"
rel="noreferrer"
>
Covid Vaccines Questions
</a>
)
const copyrightNotice = (
<a
key="copyrightNotice"
href={`${BAKED_BASE_URL}/faqs#how-is-your-work-copyrighted`}
target="_blank"
rel="noreferrer"
>
Copyright Queries
</a>
)
const citationNotice = (
<a
key="citationNotice"
href={`${BAKED_BASE_URL}/faqs#how-should-i-cite-your-work`}
target="_blank"
rel="noreferrer"
>
How to Cite our Work
</a>
)
const translateNotice = (
<a
key="translateNotice"
href={`${BAKED_BASE_URL}/faqs#can-i-translate-your-work-into-another-language`}
target="_blank"
rel="noreferrer"
>
Translating our work
</a>
)
const topicNotices = new Map<SpecialFeedbackTopic, JSX.Element>([
[SpecialFeedbackTopic.Vaccination, vaccineNotice],
[SpecialFeedbackTopic.Citation, citationNotice],
[SpecialFeedbackTopic.Licensing, copyrightNotice],
[SpecialFeedbackTopic.Translation, translateNotice],
])
@observer
export class FeedbackForm extends React.Component<{
onClose?: () => void
autofocus?: boolean
}> {
feedback: Feedback = new Feedback()
@observable loading: boolean = false
@observable done: boolean = false
@observable error: string | undefined
async submit() {
try {
await sendFeedback(this.feedback)
this.feedback.clear()
this.done = true
} catch (err) {
this.error = stringifyUnkownError(err)
} finally {
this.loading = false
}
}
@action.bound onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()
this.done = false
this.error = undefined
this.loading = true
this.submit()
}
@action.bound onName(e: React.ChangeEvent<HTMLInputElement>) {
this.feedback.name = e.currentTarget.value
}
@action.bound onEmail(e: React.ChangeEvent<HTMLInputElement>) {
this.feedback.email = e.currentTarget.value
}
@action.bound onMessage(e: React.ChangeEvent<HTMLTextAreaElement>) {
this.feedback.message = e.currentTarget.value
}
@action.bound onClose() {
if (this.props.onClose) {
this.props.onClose()
}
// Clear the form after closing, in case the user has a 2nd message to send later.
this.done = false
}
@computed private get specialTopic(): SpecialFeedbackTopic | undefined {
const { message } = this.feedback
return topicMatchers.find((matcher) => matcher.regex.test(message))
?.topic
}
renderBody() {
const { loading, done, specialTopic } = this
const autofocus = this.props.autofocus ?? true
if (done) {
return (
<div className="doneMessage">
<div className="icon">
<FontAwesomeIcon icon={faPaperPlane} />
</div>
<div className="message">
<h3>Thank you for your feedback</h3>
<p>
We read all feedback, but due to a high volume of
messages we are not able to reply to all.
</p>
</div>
<div className="actions">
<button onClick={this.onClose}>Close</button>
</div>
</div>
)
}
const notices = specialTopic
? topicNotices.get(specialTopic)
: undefined
return (
<React.Fragment>
<div className="header">Leave us feedback</div>
<div className="notice">
<p>
<strong>Have a question?</strong> You may find an answer
in:
<br />
<a
href={`${BAKED_BASE_URL}/faqs`}
target="_blank"
rel="noreferrer"
>
<strong>General FAQ</strong>
</a>{" "}
or{" "}
<a
href={`${BAKED_BASE_URL}/covid-vaccinations#frequently-asked-questions`}
target="_blank"
rel="noreferrer"
>
<strong>Vaccinations FAQ</strong>
</a>
</p>
</div>
<div className="formBody">
<div className="formSection formSectionExpand">
<label htmlFor="feedback.message">Message</label>
<textarea
id="feedback.message"
onChange={this.onMessage}
rows={5}
minLength={30}
required
disabled={loading}
/>
{notices ? (
<div className="topic-notice">
Your question may be answered in{" "}
<strong>{notices}</strong>.
</div>
) : null}
</div>
<div className="formSection">
<label htmlFor="feedback.name">Your name</label>
<input
id="feedback.name"
onChange={this.onName}
autoFocus={autofocus}
disabled={loading}
/>
</div>
<div className="formSection">
<label htmlFor="feedback.email">Email address</label>
<input
id="feedback.email"
onChange={this.onEmail}
type="email"
required
disabled={loading}
/>
</div>
{this.error ? (
<div style={{ color: "red" }}>{this.error}</div>
) : undefined}
{this.done ? (
<div style={{ color: "green" }}>
Thanks for your feedback!
</div>
) : undefined}
</div>
<div className="footer">
<button type="submit" disabled={loading}>
Send message
</button>
</div>
</React.Fragment>
)
}
render() {
return (
<form
className={classnames("FeedbackForm", {
loading: this.loading,
})}
onSubmit={this.onSubmit}
>
{this.renderBody()}
</form>
)
}
}
@observer
export class FeedbackPrompt extends React.Component {
@observable isOpen: boolean = false
@action.bound toggleOpen() {
this.isOpen = !this.isOpen
}
@action.bound onClose() {
this.isOpen = false
}
@action.bound onClickOutside() {
this.onClose()
}
render() {
return (
<div
className={`feedbackPromptContainer${
this.isOpen ? " active" : ""
}`}
>
{/* We are keeping the form always rendered to avoid wiping all contents
when a user accidentally closes the form */}
<div style={{ display: this.isOpen ? "block" : "none" }}>
<div className="overlay" onClick={this.onClickOutside} />
<div className="box">
<FeedbackForm onClose={this.onClose} />
</div>
</div>
{this.isOpen ? (
<button className="prompt" onClick={this.toggleOpen}>
<FontAwesomeIcon icon={faTimes} /> Close
</button>
) : (
<button
className="prompt"
data-track-note="page-open-feedback"
onClick={this.toggleOpen}
>
<FontAwesomeIcon icon={faCommentAlt} /> Feedback
</button>
)}
</div>
)
}
}
export function runFeedbackPage() {
ReactDOM.render(
<div className="box">
<FeedbackForm />
</div>,
document.querySelector(".FeedbackPage main")
)
} | the_stack |
import { LoanMasterNodeRegTestContainer } from './loan_container'
import BigNumber from 'bignumber.js'
import { Testing } from '@defichain/jellyfish-testing'
import { FixedIntervalPricePagination } from '../../../src/category/oracle'
const container = new LoanMasterNodeRegTestContainer()
const testing = Testing.create(container)
let oracleId: string
let timestamp: number
const priceFeeds = [
{ token: 'DFI', currency: 'USD' },
{ token: 'TSLA', currency: 'USD' },
{ token: 'UBER', currency: 'USD' },
{ token: 'GOOGL', currency: 'USD' },
{ token: 'AMZN', currency: 'USD' }
]
async function setup (): Promise<void> {
// token setup
const aliceColAddr = await testing.generateAddress()
await testing.token.dfi({ address: aliceColAddr, amount: 100000 })
await testing.generate(1)
// oracle setup
const addr = await testing.generateAddress()
oracleId = await testing.rpc.oracle.appointOracle(addr, priceFeeds, { weightage: 1 })
await testing.generate(1)
timestamp = Math.floor(new Date().getTime() / 1000)
await testing.rpc.oracle.setOracleData(
oracleId,
timestamp,
{
prices: [
{ tokenAmount: '1@DFI', currency: 'USD' },
{ tokenAmount: '2@TSLA', currency: 'USD' },
{ tokenAmount: '8@UBER', currency: 'USD' },
{ tokenAmount: '2@GOOGL', currency: 'USD' },
{ tokenAmount: '8@AMZN', currency: 'USD' }
]
}
)
await testing.generate(1)
// setCollateralToken DFI
await testing.rpc.loan.setCollateralToken({
token: 'DFI',
factor: new BigNumber(1),
fixedIntervalPriceId: 'DFI/USD'
})
await testing.generate(1)
// setLoanToken TSLA
await testing.rpc.loan.setLoanToken({
symbol: 'TSLA',
fixedIntervalPriceId: 'TSLA/USD'
})
await testing.generate(1)
// setLoanToken UBER
await testing.rpc.loan.setLoanToken({
symbol: 'UBER',
fixedIntervalPriceId: 'UBER/USD'
})
await testing.generate(1)
// setLoanToken GOOGL
await testing.rpc.loan.setLoanToken({
symbol: 'GOOGL',
fixedIntervalPriceId: 'GOOGL/USD'
})
await testing.generate(1)
// setLoanToken AMZN
await testing.rpc.loan.setLoanToken({
symbol: 'AMZN',
fixedIntervalPriceId: 'AMZN/USD'
})
await testing.generate(1)
}
describe('Oracle', () => {
beforeAll(async () => {
await testing.container.start()
await testing.container.waitForWalletCoinbaseMaturity()
await setup()
})
afterAll(async () => {
await testing.container.stop()
})
it('should listFixedIntervalPrices', async () => {
{
const prices = await testing.rpc.oracle.listFixedIntervalPrices()
expect(prices).toStrictEqual([
{
priceFeedId: 'DFI/USD',
activePrice: new BigNumber('1'),
nextPrice: new BigNumber('1'),
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'AMZN/USD',
activePrice: new BigNumber('0'),
nextPrice: new BigNumber('8'),
timestamp: expect.any(Number),
isLive: false
},
{
priceFeedId: 'TSLA/USD',
activePrice: new BigNumber('2'),
nextPrice: new BigNumber('2'),
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'UBER/USD',
activePrice: new BigNumber('8'),
nextPrice: new BigNumber('8'),
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'GOOGL/USD',
activePrice: new BigNumber('2'),
nextPrice: new BigNumber('2'),
timestamp: expect.any(Number),
isLive: true
}
])
}
{
await testing.container.waitForPriceValid('AMZN/USD')
const prices = await testing.rpc.oracle.listFixedIntervalPrices()
expect(prices[1]).toStrictEqual({
priceFeedId: 'AMZN/USD',
activePrice: new BigNumber('8'),
nextPrice: new BigNumber('8'),
timestamp: expect.any(Number),
isLive: true
})
}
{
await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '32@UBER', currency: 'USD' }] })
await testing.container.waitForPriceInvalid('UBER/USD')
const pricesBefore = await testing.rpc.oracle.listFixedIntervalPrices()
expect(pricesBefore[3]).toStrictEqual({
priceFeedId: 'UBER/USD',
activePrice: new BigNumber('8'),
nextPrice: new BigNumber('32'),
timestamp: expect.any(Number),
isLive: false
})
await testing.container.waitForPriceValid('UBER/USD')
const pricesAfter = await testing.rpc.oracle.listFixedIntervalPrices()
expect(pricesAfter[3]).toStrictEqual({
priceFeedId: 'UBER/USD',
activePrice: new BigNumber('32'),
nextPrice: new BigNumber('32'),
timestamp: expect.any(Number),
isLive: true
})
}
// should listFixedIntervalPrices with latest price
{
await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '10@TSLA', currency: 'USD' }] })
await testing.generate(1)
await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '12@TSLA', currency: 'USD' }] })
await testing.generate(1)
await testing.container.waitForPriceInvalid('TSLA/USD')
const prices = await testing.rpc.oracle.listFixedIntervalPrices()
expect(prices[2]).toStrictEqual({
priceFeedId: 'TSLA/USD',
activePrice: new BigNumber('2'),
nextPrice: new BigNumber('12'), // ensure its the latest set price
timestamp: expect.any(Number),
isLive: false
})
}
})
it('should listFixedIntervalPrices with limit', async () => {
const prices = await testing.rpc.oracle.listFixedIntervalPrices({ limit: 1 })
expect(prices.length).toStrictEqual(1)
})
it('should listFixedIntervalPrices with pagination start', async () => {
{
const pagination: FixedIntervalPricePagination = {
start: 'DFI/USD'
}
const prices = await testing.rpc.oracle.listFixedIntervalPrices(pagination)
expect(prices[0].priceFeedId).toStrictEqual('DFI/USD')
}
{
const pagination: FixedIntervalPricePagination = {
start: 'UBER/USD'
}
const prices = await testing.rpc.oracle.listFixedIntervalPrices(pagination)
expect(prices[0].priceFeedId).toStrictEqual('UBER/USD')
}
})
})
describe('Multi Oracles', () => {
beforeAll(async () => {
await testing.container.start()
await testing.container.waitForWalletCoinbaseMaturity()
await setup()
})
afterAll(async () => {
await testing.container.stop()
})
it('should listFixedIntervalPrices with several oracles', async () => {
// another oracle setup
{
const addr = await testing.generateAddress()
const oracleId1 = await testing.rpc.oracle.appointOracle(addr, priceFeeds, { weightage: 1 })
await testing.generate(1)
await testing.rpc.oracle.setOracleData(
oracleId1,
timestamp,
{
prices: [
{ tokenAmount: '1@DFI', currency: 'USD' },
{ tokenAmount: '2@TSLA', currency: 'USD' },
{ tokenAmount: '8@UBER', currency: 'USD' },
{ tokenAmount: '5@GOOGL', currency: 'USD' },
{ tokenAmount: '9@AMZN', currency: 'USD' }
]
}
)
await testing.generate(1)
const oracle = await testing.rpc.oracle.getOracleData(oracleId)
expect(oracle.tokenPrices[2]).toStrictEqual({
token: 'GOOGL',
currency: 'USD',
amount: 2,
timestamp: expect.any(Number)
})
expect(oracle.tokenPrices[0]).toStrictEqual({
token: 'AMZN',
currency: 'USD',
amount: 8,
timestamp: expect.any(Number)
})
const oracle1 = await testing.rpc.oracle.getOracleData(oracleId1)
expect(oracle1.tokenPrices[2]).toStrictEqual({
token: 'GOOGL',
currency: 'USD',
amount: 5,
timestamp: expect.any(Number)
})
expect(oracle1.tokenPrices[0]).toStrictEqual({
token: 'AMZN',
currency: 'USD',
amount: 9,
timestamp: expect.any(Number)
})
}
{
const prices = await testing.rpc.oracle.listPrices()
expect(prices[2]).toStrictEqual({
token: 'GOOGL',
currency: 'USD',
price: new BigNumber('3.5'),
ok: true
})
expect(prices[0]).toStrictEqual({
token: 'AMZN',
currency: 'USD',
price: new BigNumber('8.5'),
ok: true
})
}
{
await testing.generate(2)
const prices = await testing.container.call('listfixedintervalprices')
expect(prices).toStrictEqual([
{
priceFeedId: 'DFI/USD',
activePrice: 1,
nextPrice: 1,
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'AMZN/USD',
activePrice: 0, // weird
nextPrice: 8,
timestamp: expect.any(Number),
isLive: false
},
{
priceFeedId: 'TSLA/USD',
activePrice: 2,
nextPrice: 2,
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'UBER/USD',
activePrice: 8,
nextPrice: 8,
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'GOOGL/USD',
activePrice: 2,
nextPrice: 2,
timestamp: expect.any(Number),
isLive: true
}
])
}
{
await testing.generate(1)
const prices = await testing.container.call('listfixedintervalprices')
expect(prices).toStrictEqual([
{
priceFeedId: 'DFI/USD',
activePrice: 1,
nextPrice: 1,
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'AMZN/USD',
activePrice: 8,
nextPrice: 8.5,
timestamp: expect.any(Number),
isLive: true // weird
},
{
priceFeedId: 'TSLA/USD',
activePrice: 2,
nextPrice: 2,
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'UBER/USD',
activePrice: 8,
nextPrice: 8,
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'GOOGL/USD',
activePrice: 2,
nextPrice: 3.5,
timestamp: expect.any(Number),
isLive: false
}
])
}
{
await testing.rpc.oracle.setOracleData(
oracleId,
timestamp,
{
prices: [
{ tokenAmount: '1@DFI', currency: 'USD' },
{ tokenAmount: '2@TSLA', currency: 'USD' },
{ tokenAmount: '8@UBER', currency: 'USD' },
{ tokenAmount: '10@GOOGL', currency: 'USD' },
{ tokenAmount: '15@AMZN', currency: 'USD' }
]
}
)
await testing.container.waitForPriceInvalid('GOOGL/USD')
await testing.container.waitForPriceInvalid('AMZN/USD')
const prices = await testing.rpc.oracle.listFixedIntervalPrices()
expect(prices).toStrictEqual([
{
priceFeedId: 'DFI/USD',
activePrice: new BigNumber('1'),
nextPrice: new BigNumber('1'),
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'AMZN/USD',
activePrice: new BigNumber('8.5'),
nextPrice: new BigNumber('12'),
timestamp: expect.any(Number),
isLive: false
},
{
priceFeedId: 'TSLA/USD',
activePrice: new BigNumber('2'),
nextPrice: new BigNumber('2'),
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'UBER/USD',
activePrice: new BigNumber('8'),
nextPrice: new BigNumber('8'),
timestamp: expect.any(Number),
isLive: true
},
{
priceFeedId: 'GOOGL/USD',
activePrice: new BigNumber('3.5'),
nextPrice: new BigNumber('7.5'),
timestamp: expect.any(Number),
isLive: false
}
])
}
})
}) | the_stack |
const sendbird = new SendBird({ appId: APP_ID });
const options = new SendBirdSyncManager.Options();
options.messageCollectionCapacity = MESSAGE_COLLECTION_CAPACITY;
options.messageResendPolicy = MESSAGE_RESEND_POLICY;
options.automaticMessageResendRetryCount = AUTOMATIC_MESSAGE_RESEND_RETRY_COUNT;
options.maxFailedMessageCountPerChannel = MAX_FAILED_MESSAGE_COUNT_PER_CHANNEL;
options.failedMessageRetentionDays = FAILED_MESSAGE_RETENTION_DAYS;
SendBirdSyncManager.sendbird = sendbird;
SendBirdSyncManager.setup(USER_ID, options, () => {
sendbird.setErrorFirstCallback(true);
sendbird
.connect(USER_ID)
.then(user => {
// Do something...
})
.catch(error => {
// Handle error.
});
});
const sendbird = new SendBird({ appId: APP_ID, localCacheEnabled: true });
sendbird.setErrorFirstCallback(true);
sendbird
.connect(USER_ID)
.then(user => {
// Do something...
})
.catch(error => {
// Handle error.
});
const myGroupChannelListQuery = sendbird.GroupChannel.createMyGroupChannelListQuery();
myGroupChannelListQuery.includeEmpty = INCLUDE_EMPTY;
myGroupChannelListQuery.order = ORDER;
myGroupChannelListQuery.limit = LIMIT;
const channelCollection = new SendBirdSyncManager.ChannelCollection(myGroupChannelListQuery);
const groupChannelFilter = new sendbird.GroupChannelFilter();
groupChannelFilter.includeEmpty = INCLUDE_EMPTY;
const groupChannelCollection = sendbird.GroupChannel.createGroupChannelCollection()
.setOrder(ORDER)
.setFilter(FILTER)
.setLimit(LIMIT)
.build();
const collectionHandler = new SendBirdSyncManager.ChannelCollection.CollectionHandler();
collectionHandler.onChannelEvent = (action, channels) => {
switch (action) {
case 'insert':
// Do something...
break;
case 'update':
// Do something...
break;
case 'move':
// Do something...
break;
case 'remove':
// Do something...
break;
case 'clear':
// Do something...
break;
}
};
channelCollection.setCollectionHandler(collectionHandler);
channelCollection.setGroupChannelCollectionHandler({
onChannelsAdded: (context, channels) => {
// Do something...
},
onChannelsUpdated: (context, channels) => {
// Do something...
},
onChannelsDeleted: (context, channelUrls) => {
// Do something...
}
});
channelCollection.fetch(() => {
// Do something...
});
if (groupChannelCollection.hasMore) {
groupChannelCollection
.loadMore()
.then(channels => {
// Do something...
})
.catch(error => {
// Handle error.
});
}
channelCollection.setCollectionHandler(null);
channelCollection.remove();
groupChannelCollection.dispose();
const messageFilter = {
messageTypeFilter: MESSAGE_TYPE_FILTER
};
const messageCollection = new SendBirdSyncManager.MessageCollection(channel, messageFilter, STARTING_POINT);
messageCollection.limit = LIMIT;
const messageFilter = new sendbird.MessageFilter();
messageFilter.messageType = MESSAGE_TYPE;
const messageCollection = channel
.createMessageCollection()
.setFilter(messageFilter)
.setStartingPoint(STARTING_POINT)
.setLimit(LIMIT)
.build();
const messageCollectionHandler = new SendBirdSyncManager.MessageCollection.CollectionHandler();
messageCollectionHandler.onPendingMessageEvent = (messages, action) => {
// Do something...
};
messageCollectionHandler.onSucceededMessageEvent = (messages, action) => {
// Do something...
};
messageCollectionHandler.onFailedMessageEvent = (messages, action, reason) => {
// Do something...
};
messageCollectionHandler.onNewMessage = message => {
// Do something...
};
messageCollectionHandler.onMessageEvent = (action, messages, action) => {
// Do something...
};
messageCollectionHandler.onChannelUpdated = channel => {
// Do something...
};
messageCollectionHandler.onChannelDeleted = channel => {
// Do something...
};
messageCollection.setCollectionHandler(messageCollectionHandler);
messageCollection.setMessageCollectionHandler({
onMessagesAdded: (context, channel, messages) => {
// Do something...
},
onMessagesUpdated: (context, channel, messages) => {
// Do something...
},
onMessagesDeleted: (context, channel, messages) => {
// Do something...
},
onChannelUpdated: (context, channel) => {
// Do something...
},
onChannelDeleted: (context, channel) => {
// Do something...
},
onHugeGapDetected: () => {
// Do something...
}
});
messageCollection
.initialize(MESSAGE_COLLECTION_INIT_POLICY)
.onCacheResult((error, messages) => {
if (error) {
// Handle error.
}
// Do something...
})
.onApiResult((error, messages) => {
if (error) {
// Handle error.
}
// Do something...
});
messageCollection.fetchSucceededMessages('next', error => {
if (error) {
// Handle error;
}
// Do something...
});
if (messageCollection.hasNext) {
messageCollection
.loadNext()
.then(messages => {
// Do something...
})
.catch(error => {
// Handle error.
});
}
messageCollection.fetchSucceededMessages('prev', error => {
if (error) {
// Handle error;
}
// Do something...
});
if (messageCollection.hasPrevious) {
messageCollection
.loadPrevious()
.then(messages => {
// Do something...
})
.catch(error => {
// Handle error.
});
}
const pendingMessage = channel.sendUserMessage(USER_MESSAGE_PARAMS, (error, message) => {
messageCollection.handleSendMessageResponse(error, message);
});
messageCollection.appendMessage(pendingMessage);
channel.sendUserMessage(USER_MESSAGE_PARAMS, (error, message) => {
/**
* Pending message will be delivered to `MessageCollectionHandler.onMessagesAdded()`.
* The result of sending, either a succeeded or failed message, will be delivered to `MessageCollectionHandler.onMessagesUpdated()`.
* Do NOT add the pending, succeeded or failed message objects from the return value of `sendUserMessage()`, `sendFileMessage()`, and from the callback.
*/
});
const pendingMessage = channel.sendFileMessage(FILE_MESSAGE_PARAMS, (error, message) => {
messageCollection.handleSendMessageResponse(error, message);
});
messageCollection.appendMessage(pendingMessage);
channel.sendFileMessage(FILE_MESSAGE_PARAMS, (error, message) => {
/**
* Pending message will be delivered to `MessageCollectionHandler.onMessagesAdded()`.
* The result of sending, either a succeeded or failed message, will be delivered to `MessageCollectionHandler.onMessagesUpdated()`.
* Do NOT add the pending, succeeded or failed message objects from the return value of `sendUserMessage()`, `sendFileMessage()`, and from the callback.
*/
});
const pendingMessage = channel.resendUserMessage(failedMessage, (error, message) => {
messageCollection.handleSendMessageResponse(error, message);
});
messageCollection.appendMessage(pendingMessage);
channel.resendUserMessage(failedMessage, (error, message) => {
/**
* Pending message will be delivered to `MessageCollectionHandler.onMessagesUpdated()`.
* The result of sending, either a succeeded or failed message, will be delivered to `MessageCollectionHandler.onMessagesUpdated()`.
* Do NOT add the pending, succeeded or failed message objects from the return value of `resendUserMessage()`, `resendFileMessage()`, and from the callback.
*/
});
const pendingMessage = channel.resendFileMessage(failedMessage, (error, message) => {
messageCollection.handleSendMessageResponse(error, message);
});
messageCollection.appendMessage(pendingMessage);
channel.resendFileMessage(failedMessage, (error, message) => {
/**
* Pending message will be delivered to `MessageCollectionHandler.onMessagesUpdated()`.
* The result of sending, either a succeeded or failed message, will be delivered to `MessageCollectionHandler.onMessagesUpdated()`.
* Do NOT add the pending, succeeded or failed message objects from the return value of `resendUserMessage()`, `resendFileMessage()`, and from the callback.
*/
});
messageCollection.setCollectionHandler(null);
messageCollection.remove();
messageCollection.dispose();
messageCollectionHandler.onNewMessage = message => {
// Do something...
};
const channelHandler = new sendbird.ChannelHandler();
channelHandler.onMessageReceived = (channel, message) => {
// Do something...
};
sendbird.addChannelHandler(CHANNEL_HANDLER_KEY, channelHandler);
channel.updateUserMessage(message.messageId, USER_MESSAGE_PARAMS, (error, message) => {
messageCollection.updateMessage(message);
});
channel.updateUserMessage(message.messageId, USER_MESSAGE_PARAMS, (error, message) => {
/**
* Updated message will be handled internally and will be delivered to `MessageCollectionHandler.onMessagesUpdated()`.
*/
});
channel.deleteMessage(message, error => {
messageCollection.deleteMessage(message);
});
channel.deleteMessage(message, error => {
/**
* The result will be delivered to `MessageCollectionHandler.onMessagesDeleted()`.
*/
});
messageCollection.deleteMessage(failedMessage);
messageCollection
.removeFailedMessages(failedMessages)
.then(requestIds => {
// Do something...
})
.catch(error => {
// Handle error.
});
messageCollection
.removeAllFailedMessages()
.then(() => {
// Do something...
})
.catch(error => {
// Handle error.
});
messageCollection.resetViewpointTimestamp(TIMESTAMP);
messageCollection.dispose();
messageCollection = channel
.createMessageCollection()
.setFilter(messageFilter)
.setStartingPoint(messageCollection.startingPoint)
.setLimit(LIMIT)
.build();
messageCollection
.initialize(MESSAGE_COLLECTION_INIT_POLICY)
.onCacheResult((error, messages) => {
if (error) {
// Handle error.
}
// Do something...
})
.onApiResult((error, messages) => {
if (error) {
// Handle error.
}
// Do something...
});
messageCollection.fetchPendingMessages(error => {
if (error) {
// Handle error;
}
// Do something...
});
const pendingMessages = messageCollection.pendingMessages;
messageCollection.fetchFailedMessages(error => {
if (error) {
// Handle error;
}
// Do something...
});
const failedMessages = messageCollection.failedMessages;
const messageCount = messageCollection.messageCount;
const messageCount = messageCollection.succeededMessages.length;
SendBirdSyncManager.getInstance().clearCache(error => {
if (error) {
// Handle error.
}
// Do something...
});
sendbird
.clearCachedMessages(CHANNEL_URLS)
.then(() => {
// Do something...
})
.catch(error => {
// Handle error.
}); | the_stack |
namespace egret {
/**
* @private
* 格式化弧线角度的值
*/
function clampAngle(value): number {
value %= Math.PI * 2;
if (value < 0) {
value += Math.PI * 2;
}
return value;
}
/**
* @private
* 根据传入的锚点组返回贝塞尔曲线上的一组点,返回类型为egret.Point[];
* @param pointsData 锚点组,保存着所有控制点的x和y坐标,格式为[x0,y0,x1,y1,x2,y2...]
* @param pointsAmount 要获取的点的总个数,实际返回点数不一定等于该属性,与范围有关
* @param range 要获取的点与中心锚点的范围值,0~1之间
* @returns egret.Point[];
*/
function createBezierPoints(pointsData: number[], pointsAmount: number): egret.Point[] {
let points = [];
for (let i = 0; i < pointsAmount; i++) {
const point = getBezierPointByFactor(pointsData, i / pointsAmount);
if (point)
points.push(point);
}
return points;
}
/**
* @private
* 根据锚点组与取值系数获取贝塞尔曲线上的一点
* @param pointsData 锚点组,保存着所有控制点的x和y坐标,格式为[x0,y0,x1,y1,x2,y2...]
* @param t 取值系数
* @returns egret.Point
*/
function getBezierPointByFactor(pointsData: number[], t: number): egret.Point {
let i = 0;
let x = 0, y = 0;
const len = pointsData.length;
//根据传入的数据数量判断是二次贝塞尔还是三次贝塞尔
if (len / 2 == 3) {
//二次
const x0 = pointsData[i++];
const y0 = pointsData[i++];
const x1 = pointsData[i++];
const y1 = pointsData[i++];
const x2 = pointsData[i++];
const y2 = pointsData[i++];
x = getCurvePoint(x0, x1, x2, t);
y = getCurvePoint(y0, y1, y2, t);
} else if (len / 2 == 4) {
//三次
const x0 = pointsData[i++];
const y0 = pointsData[i++];
const x1 = pointsData[i++];
const y1 = pointsData[i++];
const x2 = pointsData[i++];
const y2 = pointsData[i++];
const x3 = pointsData[i++];
const y3 = pointsData[i++];
x = getCubicCurvePoint(x0, x1, x2, x3, t);
y = getCubicCurvePoint(y0, y1, y2, y3, t);
}
return egret.Point.create(x, y);
}
/**
* 通过factor参数获取二次贝塞尔曲线上的位置
* 公式为B(t) = (1-t)^2 * P0 + 2t(1-t) * P1 + t^2 * P2
* @param value0 P0
* @param value1 P1
* @param value2 P2
* @param factor t,从0到1的闭区间
*/
function getCurvePoint(value0: number, value1: number, value2: number, factor: number): number {
const result = Math.pow((1 - factor), 2) * value0 + 2 * factor * (1 - factor) * value1 + Math.pow(factor, 2) * value2;
return result;
}
/**
* 通过factor参数获取三次贝塞尔曲线上的位置
* 公式为B(t) = (1-t)^3 * P0 + 3t(1-t)^2 * P1 + 3t^2 * (1-t) t^2 * P2 + t^3 *P3
* @param value0 P0
* @param value1 P1
* @param value2 P2
* @param value3 P3
* @param factor t,从0到1的闭区间
*/
function getCubicCurvePoint(value0: number, value1: number, value2: number, value3: number, factor: number): number {
const result = Math.pow((1 - factor), 3) * value0 + 3 * factor * Math.pow((1 - factor), 2) * value1 + 3 * (1 - factor) * Math.pow(factor, 2) * value2 + Math.pow(factor, 3) * value3;
return result;
}
/**
* The Graphics class contains a set of methods for creating vector shape. Display objects that support drawing include Sprite and Shape objects. Each class in these classes includes the graphics attribute that is a Graphics object.
* The following auxiliary functions are provided for ease of use: drawRect(), drawRoundRect(), drawCircle(), and drawEllipse().
* @see http://edn.egret.com/cn/docs/page/136 Draw Rectangle
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/display/Graphics.ts
* @language en_US
*/
/**
* Graphics 类包含一组可用来创建矢量形状的方法。支持绘制的显示对象包括 Sprite 和 Shape 对象。这些类中的每一个类都包括 graphics 属性,该属性是一个 Graphics 对象。
* 以下是为便于使用而提供的一些辅助函数:drawRect()、drawRoundRect()、drawCircle() 和 drawEllipse()。
* @see http://edn.egret.com/cn/docs/page/136 绘制矩形
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/display/Graphics.ts
* @language zh_CN
*/
export class Graphics extends HashObject {
/**
* Initializes a Graphics object.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 创建一个 Graphics 对象。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public constructor() {
super();
this.$renderNode = new sys.GraphicsNode();
}
/**
* @private
*/
$renderNode: sys.GraphicsNode;
/**
* 绑定到的目标显示对象
*/
public $targetDisplay: DisplayObject;
$targetIsSprite: boolean;
/**
* @private
* 设置绑定到的目标显示对象
*/
$setTarget(target: DisplayObject): void {
if (this.$targetDisplay) {
this.$targetDisplay.$renderNode = null;
}
target.$renderNode = this.$renderNode;
this.$targetDisplay = target;
this.$targetIsSprite = target instanceof Sprite;
}
/**
* 当前移动到的坐标X
*/
private lastX: number = 0;
/**
* 当前移动到的坐标Y
*/
private lastY: number = 0;
/**
* 当前正在绘制的填充
*/
private fillPath: sys.Path2D = null;
/**
* 当前正在绘制的线条
*/
private strokePath: sys.StrokePath = null;
/**
* 线条的左上方宽度
*/
private topLeftStrokeWidth = 0;
/**
* 线条的右下方宽度
*/
private bottomRightStrokeWidth = 0;
/**
* 对1像素和3像素特殊处理,向右下角偏移0.5像素,以显示清晰锐利的线条。
*/
private setStrokeWidth(width: number) {
switch (width) {
case 1:
this.topLeftStrokeWidth = 0;
this.bottomRightStrokeWidth = 1;
break;
case 3:
this.topLeftStrokeWidth = 1;
this.bottomRightStrokeWidth = 2;
break;
default:
let half = Math.ceil(width * 0.5) | 0;
this.topLeftStrokeWidth = half;
this.bottomRightStrokeWidth = half;
break;
}
}
/**
* Specify a simple single color fill that will be used for subsequent calls to other Graphics methods (for example, lineTo() and drawCircle()) when drawing.
* Calling the clear() method will clear the fill.
* @param color Filled color
* @param alpha Filled Alpha value
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 指定一种简单的单一颜色填充,在绘制时该填充将在随后对其他 Graphics 方法(如 lineTo() 或 drawCircle())的调用中使用。
* 调用 clear() 方法会清除填充。
* @param color 填充的颜色
* @param alpha 填充的 Alpha 值
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public beginFill(color: number, alpha: number = 1): void {
color = +color || 0;
alpha = +alpha || 0;
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setBeginFill(color, alpha);
}
this.fillPath = this.$renderNode.beginFill(color, alpha, this.strokePath);
if (this.$renderNode.drawData.length > 1) {
this.fillPath.moveTo(this.lastX, this.lastY);
}
}
/**
* Specifies a gradient fill used by subsequent calls to other Graphics methods (such as lineTo() or drawCircle()) for the object.
* Calling the clear() method clears the fill.
* @param type A value from the GradientType class that specifies which gradient type to use: GradientType.LINEAR or GradientType.RADIAL.
* @param colors An array of RGB hexadecimal color values used in the gradient; for example, red is 0xFF0000, blue is 0x0000FF, and so on. You can specify up to 15 colors. For each color, specify a corresponding value in the alphas and ratios parameters.
* @param alphas An array of alpha values for the corresponding colors in the colors array;
* @param ratios An array of color distribution ratios; valid values are 0-255.
* @param matrix A transformation matrix as defined by the egret.Matrix class. The egret.Matrix class includes a createGradientBox() method, which lets you conveniently set up the matrix for use with the beginGradientFill() method.
* @platform Web,Native
* @version Egret 2.4
* @language en_US
*/
/**
* 指定一种渐变填充,用于随后调用对象的其他 Graphics 方法(如 lineTo() 或 drawCircle())。
* 调用 clear() 方法会清除填充。
* @param type 用于指定要使用哪种渐变类型的 GradientType 类的值:GradientType.LINEAR 或 GradientType.RADIAL。
* @param colors 渐变中使用的 RGB 十六进制颜色值的数组(例如,红色为 0xFF0000,蓝色为 0x0000FF,等等)。对于每种颜色,请在 alphas 和 ratios 参数中指定对应值。
* @param alphas colors 数组中对应颜色的 alpha 值数组。
* @param ratios 颜色分布比率的数组。有效值为 0 到 255。
* @param matrix 一个由 egret.Matrix 类定义的转换矩阵。egret.Matrix 类包括 createGradientBox() 方法,通过该方法可以方便地设置矩阵,以便与 beginGradientFill() 方法一起使用
* @platform Web,Native
* @version Egret 2.4
* @language zh_CN
*/
public beginGradientFill(type: string, colors: number[], alphas: number[], ratios: number[], matrix: egret.Matrix = null): void {
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setBeginGradientFill(type, colors, alphas, ratios, matrix);
}
this.fillPath = this.$renderNode.beginGradientFill(type, colors, alphas, ratios, matrix, this.strokePath);
if (this.$renderNode.drawData.length > 1) {
this.fillPath.moveTo(this.lastX, this.lastY);
}
}
/**
* Apply fill to the lines and curves added after the previous calling to the beginFill() method.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 对从上一次调用 beginFill()方法之后添加的直线和曲线应用填充。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public endFill(): void {
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setEndFill();
}
this.fillPath = null;
}
/**
* Specify a line style that will be used for subsequent calls to Graphics methods such as lineTo() and drawCircle().
* @param thickness An integer, indicating the thickness of the line in points. Valid values are 0 to 255. If a number is not specified, or if the parameter is undefined, a line is not drawn. If a value less than 0 is passed, the default value is 0. Value 0 indicates hairline thickness; the maximum thickness is 255. If a value greater than 255 is passed, the default value is 255.
* @param color A hexadecimal color value of the line (for example, red is 0xFF0000, and blue is 0x0000FF, etc.). If no value is specified, the default value is 0x000000 (black). Optional.
* @param alpha Indicates Alpha value of the line's color. Valid values are 0 to 1. If no value is specified, the default value is 1 (solid). If the value is less than 0, the default value is 0. If the value is greater than 1, the default value is 1.
* @param pixelHinting A boolean value that specifies whether to hint strokes to full pixels. This affects both the position of anchors of a curve and the line stroke size itself. With pixelHinting set to true, the line width is adjusted to full pixel width. With pixelHinting set to false, disjoints can appear for curves and straight lines.
* @param scaleMode Specifies the scale mode to be used
* @param caps Specifies the value of the CapsStyle class of the endpoint type at the end of the line. (default = CapsStyle.ROUND)
* @param joints Specifies the type of joint appearance of corner. (default = JointStyle.ROUND)
* @param miterLimit Indicates the limit number of cut miter.
* @param lineDash set the line dash.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 指定一种线条样式以用于随后对 lineTo() 或 drawCircle() 等 Graphics 方法的调用。
* @param thickness 一个整数,以点为单位表示线条的粗细,有效值为 0 到 255。如果未指定数字,或者未定义该参数,则不绘制线条。如果传递的值小于 0,则默认值为 0。值 0 表示极细的粗细;最大粗细为 255。如果传递的值大于 255,则默认值为 255。
* @param color 线条的十六进制颜色值(例如,红色为 0xFF0000,蓝色为 0x0000FF 等)。如果未指明值,则默认值为 0x000000(黑色)。可选。
* @param alpha 表示线条颜色的 Alpha 值的数字;有效值为 0 到 1。如果未指明值,则默认值为 1(纯色)。如果值小于 0,则默认值为 0。如果值大于 1,则默认值为 1。
* @param pixelHinting 布尔型值,指定是否提示笔触采用完整像素。它同时影响曲线锚点的位置以及线条笔触大小本身。在 pixelHinting 设置为 true 的情况下,线条宽度会调整到完整像素宽度。在 pixelHinting 设置为 false 的情况下,对于曲线和直线可能会出现脱节。
* @param scaleMode 用于指定要使用的比例模式
* @param caps 用于指定线条末端处端点类型的 CapsStyle 类的值。默认值:CapsStyle.ROUND
* @param joints 指定用于拐角的连接外观的类型。默认值:JointStyle.ROUND
* @param miterLimit 用于表示剪切斜接的极限值的数字。
* @param lineDash 设置虚线样式。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public lineStyle(thickness: number = NaN, color: number = 0, alpha: number = 1.0, pixelHinting: boolean = false,
scaleMode: string = "normal", caps: string = null, joints: string = null, miterLimit: number = 3, lineDash?: number[]): void {
thickness = +thickness || 0;
color = +color || 0;
alpha = +alpha || 0;
miterLimit = +miterLimit || 0;
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setLineStyle(thickness, color,
alpha, pixelHinting, scaleMode, caps, joints, miterLimit);
}
if (thickness <= 0) {
this.strokePath = null;
this.setStrokeWidth(0);
}
else {
this.setStrokeWidth(thickness);
this.strokePath = this.$renderNode.lineStyle(thickness, color, alpha, caps, joints, miterLimit, lineDash);
if (this.$renderNode.drawData.length > 1) {
this.strokePath.moveTo(this.lastX, this.lastY);
}
}
}
/**
* Draw a rectangle
* @param x x position of the center, relative to the registration point of the parent display object (in pixels).
* @param y y position of the center, relative to the registration point of the parent display object (in pixels).
* @param width Width of the rectangle (in pixels).
* @param height Height of the rectangle (in pixels).
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 绘制一个矩形
* @param x 圆心相对于父显示对象注册点的 x 位置(以像素为单位)。
* @param y 相对于父显示对象注册点的圆心的 y 位置(以像素为单位)。
* @param width 矩形的宽度(以像素为单位)。
* @param height 矩形的高度(以像素为单位)。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public drawRect(x: number, y: number, width: number, height: number): void {
x = +x || 0;
y = +y || 0;
width = +width || 0;
height = +height || 0;
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setDrawRect(x, y, width, height);
}
let fillPath = this.fillPath;
let strokePath = this.strokePath;
fillPath && fillPath.drawRect(x, y, width, height);
strokePath && strokePath.drawRect(x, y, width, height);
this.extendBoundsByPoint(x + width, y + height);
this.updatePosition(x, y);
this.dirty();
}
/**
* Draw a rectangle with rounded corners.
* @param x x position of the center, relative to the registration point of the parent display object (in pixels).
* @param y y position of the center, relative to the registration point of the parent display object (in pixels).
* @param width Width of the rectangle (in pixels).
* @param height Height of the rectangle (in pixels).
* @param ellipseWidth Width used to draw an ellipse with rounded corners (in pixels).
* @param ellipseHeight Height used to draw an ellipse with rounded corners (in pixels). (Optional) If no value is specified, the default value matches the value of the ellipseWidth parameter.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 绘制一个圆角矩形。
* @param x 圆心相对于父显示对象注册点的 x 位置(以像素为单位)。
* @param y 相对于父显示对象注册点的圆心的 y 位置(以像素为单位)。
* @param width 矩形的宽度(以像素为单位)。
* @param height 矩形的高度(以像素为单位)。
* @param ellipseWidth 用于绘制圆角的椭圆的宽度(以像素为单位)。
* @param ellipseHeight 用于绘制圆角的椭圆的高度(以像素为单位)。 (可选)如果未指定值,则默认值与为 ellipseWidth 参数提供的值相匹配。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public drawRoundRect(x: number, y: number, width: number, height: number, ellipseWidth: number, ellipseHeight?: number): void {
x = +x || 0;
y = +y || 0;
width = +width || 0;
height = +height || 0;
ellipseWidth = +ellipseWidth || 0;
ellipseHeight = +ellipseHeight || 0;
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setDrawRoundRect(x, y, width, height, ellipseWidth, ellipseHeight);
}
let fillPath = this.fillPath;
let strokePath = this.strokePath;
fillPath && fillPath.drawRoundRect(x, y, width, height, ellipseWidth, ellipseHeight);
strokePath && strokePath.drawRoundRect(x, y, width, height, ellipseWidth, ellipseHeight);
let radiusX = (ellipseWidth * 0.5) | 0;
let radiusY = ellipseHeight ? (ellipseHeight * 0.5) | 0 : radiusX;
let right = x + width;
let bottom = y + height;
let ybw = bottom - radiusY;
this.extendBoundsByPoint(x, y);
this.extendBoundsByPoint(right, bottom);
this.updatePosition(right, ybw);
this.dirty();
}
/**
* Draw a circle.
* @param x x position of the center, relative to the registration point of the parent display object (in pixels).
* @param y y position of the center, relative to the registration point of the parent display object (in pixels).
* @param r Radius of the circle (in pixels).
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 绘制一个圆。
* @param x 圆心相对于父显示对象注册点的 x 位置(以像素为单位)。
* @param y 相对于父显示对象注册点的圆心的 y 位置(以像素为单位)。
* @param radius 圆的半径(以像素为单位)。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public drawCircle(x: number, y: number, radius: number): void {
x = +x || 0;
y = +y || 0;
radius = +radius || 0;
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setDrawCircle(x, y, radius);
}
let fillPath = this.fillPath;
let strokePath = this.strokePath;
fillPath && fillPath.drawCircle(x, y, radius);
strokePath && strokePath.drawCircle(x, y, radius);
//-1 +2 解决WebGL裁切问题
this.extendBoundsByPoint(x - radius - 1, y - radius - 1);
this.extendBoundsByPoint(x + radius + 2, y + radius + 2);
this.updatePosition(x + radius, y);
this.dirty();
}
/**
* Draw an ellipse.
* @param x A number indicating the horizontal position, relative to the registration point of the parent display object (in pixels).
* @param y A number indicating the vertical position, relative to the registration point of the parent display object (in pixels).
* @param width Width of the rectangle (in pixels).
* @param height Height of the rectangle (in pixels).
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 绘制一个椭圆。
* @param x 一个表示相对于父显示对象注册点的水平位置的数字(以像素为单位)。
* @param y 一个表示相对于父显示对象注册点的垂直位置的数字(以像素为单位)。
* @param width 矩形的宽度(以像素为单位)。
* @param height 矩形的高度(以像素为单位)。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public drawEllipse(x: number, y: number, width: number, height: number): void {
x = +x || 0;
y = +y || 0;
width = +width || 0;
height = +height || 0;
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setDrawEllipse(x, y, width, height);
}
let fillPath = this.fillPath;
let strokePath = this.strokePath;
fillPath && fillPath.drawEllipse(x, y, width, height);
strokePath && strokePath.drawEllipse(x, y, width, height);
//-1 +2 解决WebGL裁切问题
this.extendBoundsByPoint(x - 1, y - 1);
this.extendBoundsByPoint(x + width + 2, y + height + 2);
this.updatePosition(x + width, y + height * 0.5);
this.dirty();
}
/**
* Move the current drawing position to (x, y). If any of these parameters is missed, calling this method will fail and the current drawing position keeps unchanged.
* @param x A number indicating the horizontal position, relative to the registration point of the parent display object (in pixels).
* @param y A number indicating the vertical position, relative to the registration point of the parent display object (in pixels).
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 将当前绘图位置移动到 (x, y)。如果缺少任何一个参数,则此方法将失败,并且当前绘图位置不改变。
* @param x 一个表示相对于父显示对象注册点的水平位置的数字(以像素为单位)。
* @param y 一个表示相对于父显示对象注册点的垂直位置的数字(以像素为单位)。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public moveTo(x: number, y: number): void {
x = +x || 0;
y = +y || 0;
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setMoveTo(x, y);
}
let fillPath = this.fillPath;
let strokePath = this.strokePath;
fillPath && fillPath.moveTo(x, y);
strokePath && strokePath.moveTo(x, y);
this.includeLastPosition = false;
this.lastX = x;
this.lastY = y;
this.dirty();
}
/**
* Draw a straight line from the current drawing position to (x, y) using the current line style; the current drawing position is then set to (x, y).
* @param x A number indicating the horizontal position, relative to the registration point of the parent display object (in pixels).
* @param y A number indicating the vertical position, relative to the registration point of the parent display object (in pixels).
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 使用当前线条样式绘制一条从当前绘图位置开始到 (x, y) 结束的直线;当前绘图位置随后会设置为 (x, y)。
* @param x 一个表示相对于父显示对象注册点的水平位置的数字(以像素为单位)。
* @param y 一个表示相对于父显示对象注册点的垂直位置的数字(以像素为单位)。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public lineTo(x: number, y: number): void {
x = +x || 0;
y = +y || 0;
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setLineTo(x, y);
}
let fillPath = this.fillPath;
let strokePath = this.strokePath;
fillPath && fillPath.lineTo(x, y);
strokePath && strokePath.lineTo(x, y);
this.updatePosition(x, y);
this.dirty();
}
/**
* Draw a quadratic Bezier curve from the current drawing position to (anchorX, anchorY) using the current line style according to the control points specified by (controlX, controlY). The current drawing position is then set to (anchorX, anchorY).
* If the curveTo() method is called before the moveTo() method, the default value of the current drawing position is (0, 0). If any of these parameters is missed, calling this method will fail and the current drawing position keeps unchanged.
* The drawn curve is a quadratic Bezier curve. A quadratic Bezier curve contains two anchor points and one control point. The curve interpolates the two anchor points and bends to the control point.
* @param controlX A number indicating the horizontal position of the control point, relative to the registration point of the parent display object.
* @param controlY A number indicating the vertical position of the control point, relative to the registration point of the parent display object.
* @param anchorX A number indicating the horizontal position of the next anchor point, relative to the registration point of the parent display object.
* @param anchorY A number indicating the vertical position of the next anchor point, relative to the registration point of the parent display object.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 使用当前线条样式和由 (controlX, controlY) 指定的控制点绘制一条从当前绘图位置开始到 (anchorX, anchorY) 结束的二次贝塞尔曲线。当前绘图位置随后设置为 (anchorX, anchorY)。
* 如果在调用 moveTo() 方法之前调用了 curveTo() 方法,则当前绘图位置的默认值为 (0, 0)。如果缺少任何一个参数,则此方法将失败,并且当前绘图位置不改变。
* 绘制的曲线是二次贝塞尔曲线。二次贝塞尔曲线包含两个锚点和一个控制点。该曲线内插这两个锚点,并向控制点弯曲。
* @param controlX 一个数字,指定控制点相对于父显示对象注册点的水平位置。
* @param controlY 一个数字,指定控制点相对于父显示对象注册点的垂直位置。
* @param anchorX 一个数字,指定下一个锚点相对于父显示对象注册点的水平位置。
* @param anchorY 一个数字,指定下一个锚点相对于父显示对象注册点的垂直位置。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public curveTo(controlX: number, controlY: number, anchorX: number, anchorY: number): void {
controlX = +controlX || 0;
controlY = +controlY || 0;
anchorX = +anchorX || 0;
anchorY = +anchorY || 0;
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setCurveTo(controlX, controlY,
anchorX, anchorY);
}
let fillPath = this.fillPath;
let strokePath = this.strokePath;
fillPath && fillPath.curveTo(controlX, controlY, anchorX, anchorY);
strokePath && strokePath.curveTo(controlX, controlY, anchorX, anchorY);
let lastX = this.lastX || 0;
let lastY = this.lastY || 0;
let bezierPoints = createBezierPoints([lastX, lastY, controlX, controlY, anchorX, anchorY], 50);
for (let i = 0; i < bezierPoints.length; i++) {
let point = bezierPoints[i];
this.extendBoundsByPoint(point.x, point.y);
egret.Point.release(point);
}
this.extendBoundsByPoint(anchorX, anchorY);
this.updatePosition(anchorX, anchorY);
this.dirty();
}
/**
* Draws a cubic Bezier curve from the current drawing position to the specified anchor. Cubic Bezier curves consist of two anchor points and two control points. The curve interpolates the two anchor points and two control points to the curve.
* @param controlX1 Specifies the first control point relative to the registration point of the parent display the horizontal position of the object.
* @param controlY1 Specifies the first control point relative to the registration point of the parent display the vertical position of the object.
* @param controlX2 Specify the second control point relative to the registration point of the parent display the horizontal position of the object.
* @param controlY2 Specify the second control point relative to the registration point of the parent display the vertical position of the object.
* @param anchorX Specifies the anchor point relative to the registration point of the parent display the horizontal position of the object.
* @param anchorY Specifies the anchor point relative to the registration point of the parent display the vertical position of the object.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 从当前绘图位置到指定的锚点绘制一条三次贝塞尔曲线。三次贝塞尔曲线由两个锚点和两个控制点组成。该曲线内插这两个锚点,并向两个控制点弯曲。
* @param controlX1 指定首个控制点相对于父显示对象的注册点的水平位置。
* @param controlY1 指定首个控制点相对于父显示对象的注册点的垂直位置。
* @param controlX2 指定第二个控制点相对于父显示对象的注册点的水平位置。
* @param controlY2 指定第二个控制点相对于父显示对象的注册点的垂直位置。
* @param anchorX 指定锚点相对于父显示对象的注册点的水平位置。
* @param anchorY 指定锚点相对于父显示对象的注册点的垂直位置。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public cubicCurveTo(controlX1: number, controlY1: number, controlX2: number,
controlY2: number, anchorX: number, anchorY: number): void {
controlX1 = +controlX1 || 0;
controlY1 = +controlY1 || 0;
controlX2 = +controlX2 || 0;
controlY2 = +controlY2 || 0;
anchorX = +anchorX || 0;
anchorY = +anchorY || 0;
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setCubicCurveTo(controlX1,
controlY1, controlX2, controlY2, anchorX, anchorY);
}
let fillPath = this.fillPath;
let strokePath = this.strokePath;
fillPath && fillPath.cubicCurveTo(controlX1, controlY1, controlX2, controlY2, anchorX, anchorY);
strokePath && strokePath.cubicCurveTo(controlX1, controlY1, controlX2, controlY2, anchorX, anchorY);
let lastX = this.lastX || 0;
let lastY = this.lastY || 0;
let bezierPoints = createBezierPoints([lastX, lastY, controlX1, controlY1, controlX2, controlY2, anchorX, anchorY], 50);
for (let i = 0; i < bezierPoints.length; i++) {
let point = bezierPoints[i];
this.extendBoundsByPoint(point.x, point.y);
egret.Point.release(point);
}
this.extendBoundsByPoint(anchorX, anchorY);
this.updatePosition(anchorX, anchorY);
this.dirty();
}
/**
* adds an arc to the path which is centered at (x, y) position with radius r starting at startAngle and ending
* at endAngle going in the given direction by anticlockwise (defaulting to clockwise).
* @param x The x coordinate of the arc's center.
* @param y The y coordinate of the arc's center.
* @param radius The arc's radius.
* @param startAngle The angle at which the arc starts, measured clockwise from the positive x axis and expressed in radians.
* @param endAngle The angle at which the arc ends, measured clockwise from the positive x axis and expressed in radians.
* @param anticlockwise if true, causes the arc to be drawn counter-clockwise between the two angles. By default it is drawn clockwise.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 绘制一段圆弧路径。圆弧路径的圆心在 (x, y) 位置,半径为 r ,根据anticlockwise (默认为顺时针)指定的方向从 startAngle 开始绘制,到 endAngle 结束。
* @param x 圆弧中心(圆心)的 x 轴坐标。
* @param y 圆弧中心(圆心)的 y 轴坐标。
* @param radius 圆弧的半径。
* @param startAngle 圆弧的起始点, x轴方向开始计算,单位以弧度表示。
* @param endAngle 圆弧的终点, 单位以弧度表示。
* @param anticlockwise 如果为 true,逆时针绘制圆弧,反之,顺时针绘制。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public drawArc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void {
if (radius < 0 || startAngle === endAngle) {
return;
}
x = +x || 0;
y = +y || 0;
radius = +radius || 0;
startAngle = +startAngle || 0;
endAngle = +endAngle || 0;
anticlockwise = !!anticlockwise;
startAngle = clampAngle(startAngle);
endAngle = clampAngle(endAngle);
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setDrawArc(x, y, radius,
startAngle, endAngle, anticlockwise);
}
let fillPath = this.fillPath;
let strokePath = this.strokePath;
if (fillPath) {
fillPath.$lastX = this.lastX;
fillPath.$lastY = this.lastY;
fillPath.drawArc(x, y, radius, startAngle, endAngle, anticlockwise);
}
if (strokePath) {
strokePath.$lastX = this.lastX;
strokePath.$lastY = this.lastY;
strokePath.drawArc(x, y, radius, startAngle, endAngle, anticlockwise);
}
if (anticlockwise) {
this.arcBounds(x, y, radius, endAngle, startAngle);
}
else {
this.arcBounds(x, y, radius, startAngle, endAngle);
}
let endX = x + Math.cos(endAngle) * radius;
let endY = y + Math.sin(endAngle) * radius;
this.updatePosition(endX, endY);
this.dirty();
}
private dirty(): void {
let self = this;
self.$renderNode.dirtyRender = true;
if (!egret.nativeRender) {
const target = self.$targetDisplay;
target.$cacheDirty = true;
let p = target.$parent;
if (p && !p.$cacheDirty) {
p.$cacheDirty = true;
p.$cacheDirtyUp();
}
let maskedObject = target.$maskedObject;
if (maskedObject && !maskedObject.$cacheDirty) {
maskedObject.$cacheDirty = true;
maskedObject.$cacheDirtyUp();
}
}
}
/**
* @private
* 测量圆弧的矩形大小
*/
private arcBounds(x: number, y: number, radius: number, startAngle: number, endAngle: number): void {
let PI = Math.PI;
if (Math.abs(startAngle - endAngle) < 0.01) {
this.extendBoundsByPoint(x - radius, y - radius);
this.extendBoundsByPoint(x + radius, y + radius);
return;
}
if (startAngle > endAngle) {
endAngle += PI * 2;
}
let startX = Math.cos(startAngle) * radius;
let endX = Math.cos(endAngle) * radius;
let xMin = Math.min(startX, endX);
let xMax = Math.max(startX, endX);
let startY = Math.sin(startAngle) * radius;
let endY = Math.sin(endAngle) * radius;
let yMin = Math.min(startY, endY);
let yMax = Math.max(startY, endY);
let startRange = startAngle / (PI * 0.5);
let endRange = endAngle / (PI * 0.5);
for (let i = Math.ceil(startRange); i <= endRange; i++) {
switch (i % 4) {
case 0:
xMax = radius;
break;
case 1:
yMax = radius;
break;
case 2:
xMin = -radius;
break;
case 3:
yMin = -radius;
break;
}
}
xMin = Math.floor(xMin);
yMin = Math.floor(yMin);
xMax = Math.ceil(xMax);
yMax = Math.ceil(yMax);
this.extendBoundsByPoint(xMin + x, yMin + y);
this.extendBoundsByPoint(xMax + x, yMax + y);
}
/**
* Clear graphics that are drawn to this Graphics object, and reset fill and line style settings.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 清除绘制到此 Graphics 对象的图形,并重置填充和线条样式设置。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public clear(): void {
if (egret.nativeRender) {
this.$targetDisplay.$nativeDisplayObject.setGraphicsClear();
}
this.$renderNode.clear();
this.updatePosition(0, 0);
this.minX = Infinity;
this.minY = Infinity;
this.maxX = -Infinity;
this.maxY = -Infinity;
this.dirty();
}
/**
* @private
*/
private minX: number = Infinity;
/**
* @private
*/
private minY: number = Infinity;
/**
* @private
*/
private maxX: number = -Infinity;
/**
* @private
*/
private maxY: number = -Infinity;
/**
* @private
*/
private extendBoundsByPoint(x: number, y: number): void {
this.extendBoundsByX(x);
this.extendBoundsByY(y);
}
/**
* @private
*/
private extendBoundsByX(x: number): void {
this.minX = Math.min(this.minX, x - this.topLeftStrokeWidth);
this.maxX = Math.max(this.maxX, x + this.bottomRightStrokeWidth);
this.updateNodeBounds();
}
/**
* @private
*/
private extendBoundsByY(y: number): void {
this.minY = Math.min(this.minY, y - this.topLeftStrokeWidth);
this.maxY = Math.max(this.maxY, y + this.bottomRightStrokeWidth);
this.updateNodeBounds();
}
/**
* @private
*/
private updateNodeBounds(): void {
let node = this.$renderNode;
node.x = this.minX;
node.y = this.minY;
node.width = Math.ceil(this.maxX - this.minX);
node.height = Math.ceil(this.maxY - this.minY);
}
/**
* 是否已经包含上一次moveTo的坐标点
*/
private includeLastPosition: boolean = true;
/**
* 更新当前的lineX和lineY值,并标记尺寸失效。
* @private
*/
private updatePosition(x: number, y: number): void {
if (!this.includeLastPosition) {
this.extendBoundsByPoint(this.lastX, this.lastY);
this.includeLastPosition = true;
}
this.lastX = x;
this.lastY = y;
this.extendBoundsByPoint(x, y);
}
/**
* @private
*/
$measureContentBounds(bounds: Rectangle): void {
if (this.minX === Infinity) {
bounds.setEmpty();
}
else {
bounds.setTo(this.minX, this.minY, this.maxX - this.minX, this.maxY - this.minY);
}
}
/**
* @private
*
*/
$hitTest(stageX: number, stageY: number): DisplayObject {
let target = this.$targetDisplay;
let m = target.$getInvertedConcatenatedMatrix();
let localX = m.a * stageX + m.c * stageY + m.tx;
let localY = m.b * stageX + m.d * stageY + m.ty;
let buffer = sys.canvasHitTestBuffer;
buffer.resize(3, 3);
let node = this.$renderNode;
let matrix = Matrix.create();
matrix.identity();
matrix.translate(1 - localX, 1 - localY);
sys.canvasRenderer.drawNodeToBuffer(node, buffer, matrix, true);
Matrix.release(matrix);
try {
let data = buffer.getPixels(1, 1);
if (data[3] === 0) {
return null;
}
}
catch (e) {
throw new Error(sys.tr(1039));
}
return target;
}
/**
* @private
*/
public $onRemoveFromStage(): void {
if (this.$renderNode) {
this.$renderNode.clean();
}
if (egret.nativeRender) {
egret_native.NativeDisplayObject.disposeGraphicData(this);
}
}
}
} | the_stack |
import { isValid, transpose, toStr, convertToDash, mapObject } from "./utils";
import bezier from "./bezier-easing";
import rgba from "./color-rgba";
export const limit = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);
/**
* The format to use when defining custom easing functions
*/
export type TypeEasingFunction = (t: number, params?: (string | number)[], duration?: number) => number;
export type TypeColor = string | number | Array<string | number>;
export type TypeRGBAFunction = (color: TypeColor) => number[];
/**
Easing Functions from anime.js, they are tried and true, so, its better to use them instead of other alternatives
*/
export const Quad: TypeEasingFunction = t => Math.pow(t, 2);
export const Cubic: TypeEasingFunction = t => Math.pow(t, 3);
export const Quart: TypeEasingFunction = t => Math.pow(t, 4);
export const Quint: TypeEasingFunction = t => Math.pow(t, 5);
export const Expo: TypeEasingFunction = t => Math.pow(t, 6);
export const Sine: TypeEasingFunction = t => 1 - Math.cos((t * Math.PI) / 2);
export const Circ: TypeEasingFunction = t => 1 - Math.sqrt(1 - t * t);
export const Back: TypeEasingFunction = t => t * t * (3 * t - 2);
export const Bounce: TypeEasingFunction = t => {
let pow2: number, b = 4;
while (t < ((pow2 = Math.pow(2, --b)) - 1) / 11) { }
return 1 / Math.pow(4, 3 - b) - 7.5625 * Math.pow((pow2 * 3 - 2) / 22 - t, 2);
};
export const Elastic: TypeEasingFunction = (t, params: number[] = []) => {
let [amplitude = 1, period = 0.5] = params;
const a = limit(amplitude, 1, 10);
const p = limit(period, 0.1, 2);
if (t === 0 || t === 1) return t;
return -a *
Math.pow(2, 10 * (t - 1)) *
Math.sin(
((t - 1 - (p / (Math.PI * 2)) * Math.asin(1 / a)) * (Math.PI * 2)) / p
);
};
export const Spring: TypeEasingFunction = (
t: number,
params: number[] = [],
duration?: number
) => {
let [
mass = 1,
stiffness = 100,
damping = 10,
velocity = 0
] = params;
mass = limit(mass, 0.1, 1000);
stiffness = limit(stiffness, 0.1, 1000);
damping = limit(damping, 0.1, 1000);
velocity = limit(velocity, 0.1, 1000);
const w0 = Math.sqrt(stiffness / mass);
const zeta = damping / (2 * Math.sqrt(stiffness * mass));
const wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0;
const a = 1;
const b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;
let progress = duration ? (duration * t) / 1000 : t;
if (zeta < 1) {
progress =
Math.exp(-progress * zeta * w0) *
(a * Math.cos(wd * progress) + b * Math.sin(wd * progress));
} else {
progress = (a + b * progress) * Math.exp(-progress * w0);
}
if (t === 0 || t === 1) return t;
return 1 - progress;
};
/**
* Cache the durations at set easing parameters
*/
export const EasingDurationCache: Map<string | TypeEasingFunction, number> = new Map();
/**
* The threshold for an infinite loop
*/
export const INTINITE_LOOP_LIMIT = 10000;
/**
* The spring easing function will only look smooth at certain durations, with certain parameters.
* This functions returns the optimal duration to create a smooth springy animation based on physics
*
* Note: it can also be used to determine the optimal duration of other types of easing function, but be careful of "in-"
* easing functions, because of the nature of the function it can sometimes create an infinite loop, I suggest only using
* `getEasingDuration` for `spring`, specifically "out-spring" and "spring"
*/
export const getEasingDuration = (easing: string | TypeEasingFunction = "spring") => {
if (EasingDurationCache.has(easing))
return EasingDurationCache.get(easing);
const easingFunction = typeof easing == "function" ? easing : GetEasingFunction(easing as string);
const params = typeof easing == "function" ? [] : parseEasingParameters(easing);
const frame = 1 / 6;
let elapsed = 0;
let rest = 0;
let count = 0;
while (++count < INTINITE_LOOP_LIMIT) {
elapsed += frame;
if (easingFunction(elapsed, params, null) === 1) {
rest++;
if (rest >= 16) break;
} else {
rest = 0;
}
}
const duration = elapsed * frame * 1000;
EasingDurationCache.set(easing, duration);
return duration;
}
/**
These Easing Functions are based off of the Sozi Project's easing functions
https://github.com/sozi-projects/Sozi/blob/d72e44ebd580dc7579d1e177406ad41e632f961d/src/js/player/Timing.js
*/
export const Steps: TypeEasingFunction = (t: number, params = []) => {
let [steps = 10, type] = params as [number, string];
const trunc = type == "start" ? Math.ceil : Math.floor;
return trunc(limit(t, 0, 1) * steps) / steps;
};
export const Bezier: TypeEasingFunction = (t: number, params: number[] = []) => {
let [mX1, mY1, mX2, mY2] = params;
return bezier(mX1, mY1, mX2, mY2)(t);
};
/** The default `ease-in` easing function */
export const easein: TypeEasingFunction = bezier(0.42, 0.0, 1.0, 1.0);
/** Converts easing functions to their `out`counter parts */
export const EaseOut = (ease: TypeEasingFunction): TypeEasingFunction => {
return (t, params = [], duration?: number) => 1 - ease(1 - t, params, duration);
}
/** Converts easing functions to their `in-out` counter parts */
export const EaseInOut = (ease: TypeEasingFunction): TypeEasingFunction => {
return (t, params = [], duration?: number) =>
t < 0.5 ? ease(t * 2, params, duration) / 2 : 1 - ease(t * -2 + 2, params, duration) / 2;
}
/** Converts easing functions to their `out-in` counter parts */
export const EaseOutIn = (ease: TypeEasingFunction): TypeEasingFunction => {
return (t, params = [], duration?: number) => {
return t < 0.5
? (1 - ease(1 - t * 2, params, duration)) / 2
: (ease(t * 2 - 1, params, duration) + 1) / 2;
};
}
/**
* The default list of easing functions, do note this is different from {@link EASING}
*/
export const EasingFunctions: { [key: string]: TypeEasingFunction } = {
steps: Steps,
"step-start": t => Steps(t, [1, "start"]),
"step-end": t => Steps(t, [1, "end"]),
linear: t => t,
"cubic-bezier": Bezier,
ease: t => Bezier(t, [0.25, 0.1, 0.25, 1.0]),
in: easein,
out: EaseOut(easein),
"in-out": EaseInOut(easein),
"out-in": EaseOutIn(easein),
"in-quad": Quad,
"out-quad": EaseOut(Quad),
"in-out-quad": EaseInOut(Quad),
"out-in-quad": EaseOutIn(Quad),
"in-cubic": Cubic,
"out-cubic": EaseOut(Cubic),
"in-out-cubic": EaseInOut(Cubic),
"out-in-cubic": EaseOutIn(Cubic),
"in-quart": Quart,
"out-quart": EaseOut(Quart),
"in-out-quart": EaseInOut(Quart),
"out-in-quart": EaseOutIn(Quart),
"in-quint": Quint,
"out-quint": EaseOut(Quint),
"in-out-quint": EaseInOut(Quint),
"out-in-quint": EaseOutIn(Quint),
"in-expo": Expo,
"out-expo": EaseOut(Expo),
"in-out-expo": EaseInOut(Expo),
"out-in-expo": EaseOutIn(Expo),
"in-sine": Sine,
"out-sine": EaseOut(Sine),
"in-out-sine": EaseInOut(Sine),
"out-in-sine": EaseOutIn(Sine),
"in-circ": Circ,
"out-circ": EaseOut(Circ),
"in-out-circ": EaseInOut(Circ),
"out-in-circ": EaseOutIn(Circ),
"in-back": Back,
"out-back": EaseOut(Back),
"in-out-back": EaseInOut(Back),
"out-in-back": EaseOutIn(Back),
"in-bounce": Bounce,
"out-bounce": EaseOut(Bounce),
"in-out-bounce": EaseInOut(Bounce),
"out-in-bounce": EaseOutIn(Bounce),
"in-elastic": Elastic,
"out-elastic": EaseOut(Elastic),
"in-out-elastic": EaseInOut(Elastic),
"out-in-elastic": EaseOutIn(Elastic),
spring: Spring,
"spring-in": Spring,
"spring-out": EaseOut(Spring),
"spring-in-out": EaseInOut(Spring),
"spring-out-in": EaseOutIn(Spring)
};
export let EasingFunctionKeys = Object.keys(EasingFunctions);
/**
* Allows you to register new easing functions
*/
export const registerEasingFunction = (key: string, fn: TypeEasingFunction) => {
Object.assign(EasingFunctions, {
[key]: fn
});
EasingFunctionKeys = Object.keys(EasingFunctions);
}
/**
* Allows you to register multiple new easing functions
*/
export const registerEasingFunctions = (...obj: Array<typeof EasingFunctions>) => {
Object.assign(EasingFunctions, ...obj);
EasingFunctionKeys = Object.keys(EasingFunctions);
}
/**
* Convert string easing to their proper form
*/
export const ComplexEasingSyntax = (ease: string) =>
convertToDash(ease)
.replace(/^ease-/, "") // Remove the "ease-" keyword
.replace(/(\(|\s).+/, "") // Remove the function brackets and parameters
.toLowerCase()
.trim();
/** Re-maps a number from one range to another. Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. */
export const GetEasingFunction = (ease: string) => {
let search = ComplexEasingSyntax(ease);
if (EasingFunctionKeys.includes(search))
return EasingFunctions[search];
return null;
};
/** Convert easing parameters to Array of numbers, e.g. "spring(2, 500)" to [2, 500] */
export const parseEasingParameters = (str: string) => {
const match = /(\(|\s)([^)]+)\)?/.exec(str);
return match ? match[2].split(",").map(value => {
let num = parseFloat(value);
return !Number.isNaN(num) ? num : value.trim();
}) : [];
};
/** map `t` from 0 to 1, to `start` to `end` */
export const scale = (t: number, start: number, end: number) => start + (end - start) * t;
/** Rounds numbers to a fixed decimal place */
export const toFixed = (value: number, decimal: number) =>
Math.round(value * 10 ** decimal) / 10 ** decimal;
/**
Given an Array of numbers, estimate the resulting number, at a `t` value between 0 to 1
Based on d3.interpolateBasis [https://github.com/d3/d3-interpolate#interpolateBasis],
check out the link above for more detail.
Basic interpolation works by scaling `t` from 0 - 1, to some start number and end number, in this case lets use
0 as our start number and 100 as our end number, so, basic interpolation would interpolate between 0 to 100.
If we use a `t` of 0.5, the interpolated value between 0 to 100, is 50.
{@link interpolateNumber} takes it further, by allowing you to interpolate with more than 2 values,
it allows for multiple values.
E.g. Given an Array of values [0, 100, 0], and a `t` of 0.5, the interpolated value would become 100.
*/
export const interpolateNumber = (t: number, values: number[], decimal = 3) => {
// nth index
let n = values.length - 1;
// The current index given t
let i = limit(Math.floor(t * n), 0, n - 1);
let start = values[i];
let end = values[i + 1];
let progress = (t - i / n) * n;
return toFixed(scale(progress, start, end), decimal);
};
/** If a value can be converted to a valid number, then it's most likely a number */
export const isNumberLike = (num: string | number) => {
let value = parseFloat(num as string);
return typeof value == "number" && !Number.isNaN(value);
};
/**
Given an Array of values, find a value using `t` (`t` goes from 0 to 1), by
using `t` to estimate the index of said value in the array of `values`
*/
export const interpolateUsingIndex = (t: number, values: (string | number)[]) => {
// limit `t`, to a min of 0 and a max of 1
t = limit(t, 0, 1);
// nth index
let n = values.length - 1;
// The current index given t
let i = Math.round(t * n);
return values[i];
};
/**
Functions the same way {@link interpolateNumber} works.
Convert strings to numbers, and then interpolates the numbers,
at the end if there are units on the first value in the `values` array,
it will use that unit for the interpolated result.
Make sure to read {@link interpolateNumber}.
*/
export const interpolateString = (t: number, values: (string | number)[], decimal = 3) => {
let units = "";
// If the first value looks like a number with a unit
if (isNumberLike(values[0]))
units = toStr(values[0]).replace(/^\d+/, "");
return interpolateNumber(t, values.map(parseFloat), decimal) + units;
};
/**
Use the `color-rgba` npm package, to convert all color formats to an Array of rgba values,
e.g. `[red, green, blue, alpha]`. Then, use the {@link interpolateNumber} functions to interpolate over the array
_**Note**: the red, green, and blue colors are rounded to intergers with no decimal places,
while the alpha color gets rounded to a specific decimal place_
Make sure to read {@link interpolateNumber}.
*/
export const interpolateColor = (t: number, values: TypeColor[], decimal = 3) => {
return transpose(...values.map(rgba as TypeRGBAFunction)).map((colors: number[], i) => {
let result = interpolateNumber(t, colors);
return i < 3 ? Math.round(result) : toFixed(result, decimal);
});
};
/**
Convert value to string, then trim any extra white space and line terminator characters from the string.
*/
export const trim = (str: string) => toStr(str).trim();
/**
Converts "10px solid red #555 rgba(255, 0,5,6, 7) "
to [ '10px', 'solid', 'red', '#555', 'rgba(255, 0,5,6, 7)' ]
*/
export const ComplexStrtoArr = (str: string) => {
return (
trim(str)
.replace(/(\d|\)|\w)\s/g, (match) => match[0] + "__")
.split("__")
.map(trim)
// Remove invalid values
.filter(isValid)
);
};
/**
Interpolates all types of values including number, string, color, and complex values.
Complex values are values like "10px solid red", that border, and other CSS Properties use.
Make sure to read {@link interpolateNumber}, {@link interpolateString}, {@link interpolateColor}, and {@link interpolateUsingIndex}.
*/
export const interpolateComplex = (t: number, values: (string | number | TypeColor)[], decimal = 3) => {
// Interpolate numbers
let isNumber = values.every(v => typeof v == "number");
if (isNumber)
return interpolateNumber(t, values as number[], decimal);
// Interpolate colors
let isColor = values.every(v => isValid(rgba(v ?? null)));
if (isColor)
return `rgba(${interpolateColor(t, values, decimal)})`;
// Interpolate complex values and strings
let isString = values.some(v => typeof v == "string");
if (isString) {
// Interpolate complex values like "10px solid red"
let isComplex = values.some(v => /(\d|\)|\w)\s/.test(trim(v as string)));
if (isComplex) {
return transpose(...values.map(ComplexStrtoArr))
.map((value) => interpolateComplex(t, value, decimal))
.join(" ");
}
// Interpolate strings with numbers, e.g. "5px"
let isLikeNumber = values.every(v => isNumberLike(v as string));
if (isLikeNumber)
return interpolateString(t, values as (number | string)[], decimal);
// Interpolate pure strings, e.g. "inherit", "solid", etc...
else return interpolateUsingIndex(t, values as string[]);
}
};
/**
* Custom Easing has 3 properties they are `easing` (all the easings from [#easing](#easing) are supported on top of custom easing functions, like spring, bounce, etc...), `numPoints` (the size of the Array the Custom Easing function should create), and `decimal` (the number of decimal places of the values within said Array).
*
* | Properties | Default Value |
* | ----------- | ----------------------- |
* | `easing` | `spring(1, 100, 10, 0)` |
* | `numPoints` | `50` |
* | `decimal` | `3` |
*/
export type TypeCustomEasingOptions = {
/**
*
* By default, Custom Easing support easing functions, in the form,
*
* | constant | accelerate | decelerate | accelerate-decelerate | decelerate-accelerate |
* | :--------- | :----------------- | :------------- | :-------------------- | :-------------------- |
* | linear | ease-in / in | ease-out / out | ease-in-out / in-out | ease-out-in / out-in |
* | ease | in-sine | out-sine | in-out-sine | out-in-sine |
* | steps | in-quad | out-quad | in-out-quad | out-in-quad |
* | step-start | in-cubic | out-cubic | in-out-cubic | out-in-cubic |
* | step-end | in-quart | out-quart | in-out-quart | out-in-quart |
* | | in-quint | out-quint | in-out-quint | out-in-quint |
* | | in-expo | out-expo | in-out-expo | out-in-expo |
* | | in-circ | out-circ | in-out-circ | out-in-circ |
* | | in-back | out-back | in-out-back | out-in-back |
* | | in-bounce | out-bounce | in-out-bounce | out-in-bounce |
* | | in-elastic | out-elastic | in-out-elastic | out-in-elastic |
* | | spring / spring-in | spring-out | spring-in-out | spring-out-in |
*
* All **Elastic** easing's can be configured using theses parameters,
*
* `*-elastic(amplitude, period)`
*
* Each parameter comes with these defaults
*
* | Parameter | Default Value |
* | --------- | ------------- |
* | amplitude | `1` |
* | period | `0.5` |
*
* ***
*
* All **Spring** easing's can be configured using theses parameters,
*
* `spring-*(mass, stiffness, damping, velocity)`
*
* Each parameter comes with these defaults
*
* | Parameter | Default Value |
* | --------- | ------------- |
* | mass | `1` |
* | stiffness | `100` |
* | damping | `10` |
* | velocity | `0` |
*
* You can create your own custom cubic-bezier easing curves. Similar to css you type `cubic-bezier(...)` with 4 numbers representing the shape of the bezier curve, for example, `cubic-bezier(0.47, 0, 0.745, 0.715)` this is the bezier curve for `in-sine`.
*
* _**Note**: the `easing` property supports the original values and functions for easing as well, for example, `steps(1)`, and etc... are supported._
*
* _**Note**: you can also use camelCase when defining easing functions, e.g. `inOutCubic` to represent `in-out-cubic`_
*
*/
easing?: string | TypeEasingFunction,
numPoints?: number,
decimal?: number,
duration?: number
};
/**
* returns a CustomEasingOptions object from a easing "string", or function
*/
export const CustomEasingOptions = (options: TypeCustomEasingOptions | string | TypeEasingFunction = {}) => {
let isEasing = typeof options == "string" || typeof options == "function";
let {
easing = "spring(1, 100, 10, 0)",
numPoints = 100,
decimal = 3,
duration
} = (isEasing ? { easing: options } : options) as TypeCustomEasingOptions;
return { easing, numPoints, decimal, duration };
}
/**
Cache calculated tween points for commonly used easing functions
*/
export const TweenCache = new Map();
/**
* Create an Array of tween points using easing functions.
* The array is `numPoints` large, which is by default 50.
* Easing function can be custom defined, so, instead of string you can use functions,
* e.g.
* ```ts
* tweenPts({
* easing: t => t,
* numPoints: 50
* })
* ```
Based on https://github.com/w3c/csswg-drafts/issues/229#issuecomment-861415901
*/
export const EasingPts = ({ easing, numPoints, duration }: TypeCustomEasingOptions = {}): number[] => {
const pts = [];
const key = `${easing}${numPoints}`;
if (TweenCache.has(key)) return TweenCache.get(key);
const easingFunction = typeof easing == "function" ? easing : GetEasingFunction(easing as string);
const params = typeof easing == "function" ? [] : parseEasingParameters(easing);
for (let i = 0; i < numPoints; i++) {
pts[i] = easingFunction(i / (numPoints - 1), params, duration);
}
TweenCache.set(key, pts);
return pts;
};
/**
* Update the duration of `spring` and `spring-in` easings ot use optimal durations
*/
const updateDuration = (optionsObj: TypeCustomEasingOptions = {}) => {
if (typeof optionsObj.easing == "string") {
let easing = ComplexEasingSyntax(optionsObj.easing as string);
if (/(spring|spring-in)$/i.test(easing)) {
optionsObj.duration = getEasingDuration(optionsObj.easing);
}
}
}
/**
* Generates an Array of values using easing functions which in turn create the effect of custom easing.
* To use this properly make sure to set the easing animation option to "linear".
* Check out a demo of CustomEasing at <https://codepen.io/okikio/pen/abJMWNy?editors=0010>
*
* Custom Easing has 3 properties they are `easing` (all the easings from {@link EasingFunctions} are supported on top of custom easing functions like spring, bounce, etc...), `numPoints` (the size of the Array the Custom Easing function should create), and `decimal` (the number of decimal places of the values within said Array).
*
* | Properties | Default Value |
* | ----------- | ----------------------- |
* | `easing` | `spring(1, 100, 10, 0)` |
* | `numPoints` | `50` |
* | `decimal` | `3` |
*
* By default, Custom Easing support easing functions, in the form,
*
* | constant | accelerate | decelerate | accelerate-decelerate | decelerate-accelerate |
* | :--------- | :----------------- | :------------- | :-------------------- | :-------------------- |
* | linear | ease-in / in | ease-out / out | ease-in-out / in-out | ease-out-in / out-in |
* | ease | in-sine | out-sine | in-out-sine | out-in-sine |
* | steps | in-quad | out-quad | in-out-quad | out-in-quad |
* | step-start | in-cubic | out-cubic | in-out-cubic | out-in-cubic |
* | step-end | in-quart | out-quart | in-out-quart | out-in-quart |
* | | in-quint | out-quint | in-out-quint | out-in-quint |
* | | in-expo | out-expo | in-out-expo | out-in-expo |
* | | in-circ | out-circ | in-out-circ | out-in-circ |
* | | in-back | out-back | in-out-back | out-in-back |
* | | in-bounce | out-bounce | in-out-bounce | out-in-bounce |
* | | in-elastic | out-elastic | in-out-elastic | out-in-elastic |
* | | spring / spring-in | spring-out | spring-in-out | spring-out-in |
*
* All **Elastic** easing's can be configured using theses parameters,
*
* `*-elastic(amplitude, period)`
*
* Each parameter comes with these defaults
*
* | Parameter | Default Value |
* | --------- | ------------- |
* | amplitude | `1` |
* | period | `0.5` |
*
* ***
*
* All **Spring** easing's can be configured using theses parameters,
*
* `spring-*(mass, stiffness, damping, velocity)`
*
* Each parameter comes with these defaults
*
* | Parameter | Default Value |
* | --------- | ------------- |
* | mass | `1` |
* | stiffness | `100` |
* | damping | `10` |
* | velocity | `0` |
*
* You can create your own custom cubic-bezier easing curves. Similar to css you type `cubic-bezier(...)` with 4 numbers representing the shape of the bezier curve, for example, `cubic-bezier(0.47, 0, 0.745, 0.715)` this is the bezier curve for `in-sine`.
*
* _**Note**: the `easing` property supports the original values and functions for easing as well, for example, `steps(1)`, and etc... are supported._
*
* _**Note**: you can also use camelCase when defining easing functions, e.g. `inOutCubic` to represent `in-out-cubic`_
*
* e.g.
* ```ts
* import { animate, CustomEasing, EaseOut, Quad } from "@okikio/animate";
* animate({
* target: "div",
*
* // Notice how only, the first value in the Array uses the "px" unit
* border: CustomEasing(["1px solid red", "3 dashed green", "2 solid black"], {
* // This is a custom easing function
* easing: EaseOut(Quad)
* }),
*
* translateX: CustomEasing([0, 250], {
* easing: "linear",
*
* // You can change the size of Array for the CustomEasing function to generate
* numPoints: 200,
*
* // The number of decimal places to round, final values in the generated Array
* decimal: 5,
* }),
*
* // You can set the easing without an object
* // Also, if units are detected in the values Array,
* // the unit of the first value in the values Array are
* // applied to other values in the values Array, even if they
* // have prior units
* rotate: CustomEasing(["0turn", 1, 0, 0.5], "out"),
* "background-color": CustomEasing(["#616aff", "white"]),
* easing: "linear"
* }),
*
* // TIP... Use linear easing for the proper effect
* easing: "linear"
* })
* ```
*/
export const CustomEasing = (values: (string | number)[], options: TypeCustomEasingOptions | string | TypeEasingFunction = {}) => {
let optionsObj = CustomEasingOptions(options);
updateDuration(optionsObj);
return EasingPts(optionsObj).map((t) =>
interpolateComplex(t, values, optionsObj.decimal)
);
};
/**
* Returns an array containing `[easing pts, duration]`, it's meant to be a self enclosed way to create spring easing.
* Springs have an optimal duration; using `getEasingDuration()` we are able to have the determine the optimal duration for a spring with given parameters.
*
* By default it will only give the optimal duration for `spring` or `spring-in` easing, this is to avoid infinite loops caused by the `getEasingDuration()` function.
*
* Internally the `SpringEasing` uses {@link CustomEasing}, read more on it, to understand how the `SpringEasing` function works.
*
* e.g.
* ```ts
* import { animate, SpringEasing } from "@okikio/animate";
*
* // `duration` is the optimal duration for the spring with the set parameters
* let [translateX, duration] = SpringEasing([0, 250], "spring(5, 100, 10, 1)");
* // or
* // `duration` is 5000 here
* let [translateX, duration] = SpringEasing([0, 250], {
* easing: "spring(5, 100, 10, 1)",
* numPoints: 50,
* duration: 5000,
* decimal: 3
* });
*
* animate({
* target: "div",
* translateX,
* duration
* });
* ```
*/
export const SpringEasing = (values: (string | number)[], options: TypeCustomEasingOptions = {}) => {
let optionsObj = CustomEasingOptions(options);
let { duration } = optionsObj;
updateDuration(optionsObj);
return [
CustomEasing(values, optionsObj),
isValid(duration) ? duration : optionsObj.duration
]
};
/**
* Applies the same custom easings to all properties of the object and returns an object with each property having an array of custom eased values
*
* If you use the `spring` or `spring-in` easings it will also return the optimal duration as a key in the object it returns.
* If you set `duration` to a number, it will prioritize that `duration` over optimal duration given by the spring easings.
*
* Read more about {@link CustomEasing}
*
* e.g.
* ```ts
* import { animate, ApplyCustomEasing } from "@okikio/animate";
* animate({
* target: "div",
*
* ...ApplyCustomEasing({
* border: ["1px solid red", "3 dashed green", "2 solid black"],
* translateX: [0, 250],
* rotate: ["0turn", 1, 0, 0.5],
* "background-color": ["#616aff", "white"],
*
* // You don't need to enter any parameters, you can just use the default values
* easing: "spring",
*
* // You can change the size of Array for the CustomEasing function to generate
* numPoints: 200,
*
* // The number of decimal places to round, final values in the generated Array
* decimal: 5,
*
* // You can also set the duration from here.
* // When using spring animations, the duration you set here is not nesscary,
* // since by default springs will try to determine the most appropriate duration for the spring animation.
* // But the duration value here will override `spring` easings optimal duration value
* duration: 3000
* })
* })
* ```
*/
export const ApplyCustomEasing = (options: TypeCustomEasingOptions & { [key: string]: number | string | TypeEasingFunction | (number | string)[] } = {}) => {
let { easing, numPoints, decimal, duration, ...rest } = options;
let optionsObj = { easing, numPoints, decimal, duration };
updateDuration(optionsObj);
let properties = mapObject(rest, (value: (string | number)[]) => CustomEasing(value, optionsObj));
let durationObj = {};
if (isValid(duration)) durationObj = { duration };
else if (isValid(optionsObj.duration)) durationObj = { duration: optionsObj.duration };
return Object.assign({}, properties, durationObj);
} | the_stack |
declare module 'meteor/kschingiz:meteor-elastic-apm' {
/// <reference types="node" />
import { IncomingMessage, ServerResponse } from 'http'
export = agent
declare const agent: Agent
declare class Agent implements Taggable, StartSpanFn {
// Configuration
start(options?: AgentConfigOptions): Agent
isStarted(): boolean
setFramework(options: { name?: string; version?: string; overwrite?: boolean }): void
addPatch(modules: string | Array<string>, handler: string | PatchHandler): void
removePatch(modules: string | Array<string>, handler: string | PatchHandler): void
clearPatches(modules: string | Array<string>): void
// Data collection hooks
middleware: { connect(): Connect.ErrorHandleFunction }
lambda(handler: AwsLambda.Handler): AwsLambda.Handler
lambda(type: string, handler: AwsLambda.Handler): AwsLambda.Handler
handleUncaughtExceptions(fn?: (err: Error) => void): void
// Errors
captureError(err: Error | string | ParameterizedMessageObject, callback?: CaptureErrorCallback): void
captureError(
err: Error | string | ParameterizedMessageObject,
options?: CaptureErrorOptions,
callback?: CaptureErrorCallback
): void
// Distributed Tracing
currentTraceparent: string | null
currentTraceIds: {
'trace.id'?: string
'transaction.id'?: string
'span.id'?: string
}
// Transactions
startTransaction(name?: string | null, options?: TransactionOptions): Transaction | null
startTransaction(name: string | null, type: string | null, options?: TransactionOptions): Transaction | null
startTransaction(
name: string | null,
type: string | null,
subtype: string | null,
options?: TransactionOptions
): Transaction | null
startTransaction(
name: string | null,
type: string | null,
subtype: string | null,
action: string | null,
options?: TransactionOptions
): Transaction | null
setTransactionName(name: string): void
endTransaction(result?: string | number, endTime?: number): void
currentTransaction: Transaction | null
// Spans
startSpan(name?: string | null, options?: SpanOptions): Span | null
startSpan(name: string | null, type: string | null, options?: SpanOptions): Span | null
startSpan(name: string | null, type: string | null, subtype: string | null, options?: SpanOptions): Span | null
startSpan(
name: string | null,
type: string | null,
subtype: string | null,
action: string | null,
options?: SpanOptions
): Span | null
currentSpan: Span | null
// Context
setLabel(name: string, value: LabelValue): boolean
addLabels(labels: Labels): boolean
setUserContext(user: UserObject): void
setCustomContext(custom: object): void
// Transport
addFilter(fn: FilterFn): void
addErrorFilter(fn: FilterFn): void
addSpanFilter(fn: FilterFn): void
addTransactionFilter(fn: FilterFn): void
flush(callback?: Function): void
destroy(): void
// Utils
logger: Logger
// Custom metrics
registerMetric(name: string, callback: Function): void
registerMetric(name: string, labels: Labels, callback: Function): void
}
declare class GenericSpan implements Taggable {
// The following properties and methods are currently not documented as their API isn't considered official:
// timestamp, ended, id, traceId, parentId, sampled, duration()
type: string | null
subtype: string | null
action: string | null
traceparent: string
setType(type?: string | null, subtype?: string | null, action?: string | null): void
setLabel(name: string, value: LabelValue): boolean
addLabels(labels: Labels): boolean
}
declare class Transaction extends GenericSpan implements StartSpanFn {
// The following properties and methods are currently not documented as their API isn't considered official:
// setUserContext(), setCustomContext(), toJSON(), setDefaultName(), setDefaultNameFromRequest()
name: string
result: string | number
startSpan(name?: string | null, options?: SpanOptions): Span | null
startSpan(name: string | null, type: string | null, options?: SpanOptions): Span | null
startSpan(name: string | null, type: string | null, subtype: string | null, options?: SpanOptions): Span | null
startSpan(
name: string | null,
type: string | null,
subtype: string | null,
action: string | null,
options?: SpanOptions
): Span | null
ensureParentId(): string
end(result?: string | number | null, endTime?: number): void
}
declare class Span extends GenericSpan {
// The following properties and methods are currently not documented as their API isn't considered official:
// customStackTrace(), setDbContext()
transaction: Transaction
name: string
end(endTime?: number): void
}
interface AgentConfigOptions {
disableMeteorInstrumentations?: string[]
abortedErrorThreshold?: string // Also support `number`, but as we're removing this functionality soon, there's no need to advertise it
active?: boolean
addPatch?: KeyValueConfig
apiRequestSize?: string // Also support `number`, but as we're removing this functionality soon, there's no need to advertise it
apiRequestTime?: string // Also support `number`, but as we're removing this functionality soon, there's no need to advertise it
asyncHooks?: boolean
captureBody?: CaptureBody
captureErrorLogStackTraces?: CaptureErrorLogStackTraces
captureExceptions?: boolean
captureHeaders?: boolean
captureSpanStackTraces?: boolean
containerId?: string
disableInstrumentations?: string | string[]
environment?: string
errorMessageMaxLength?: string // Also support `number`, but as we're removing this functionality soon, there's no need to advertise it
errorOnAbortedRequests?: boolean
filterHttpHeaders?: boolean
frameworkName?: string
frameworkVersion?: string
globalLabels?: KeyValueConfig
hostname?: string
ignoreUrls?: Array<string | RegExp>
ignoreUserAgents?: Array<string | RegExp>
instrument?: boolean
instrumentIncomingHTTPRequests?: boolean
kubernetesNamespace?: string
kubernetesNodeName?: string
kubernetesPodName?: string
kubernetesPodUID?: string
logLevel?: LogLevel
logUncaughtExceptions?: boolean
logger?: Logger
metricsInterval?: string // Also support `number`, but as we're removing this functionality soon, there's no need to advertise it
payloadLogFile?: string
centralConfig?: boolean
secretToken?: string
serverCaCertFile?: string
serverTimeout?: string // Also support `number`, but as we're removing this functionality soon, there's no need to advertise it
serverUrl?: string
serviceName?: string
serviceVersion?: string
sourceLinesErrorAppFrames?: number
sourceLinesErrorLibraryFrames?: number
sourceLinesSpanAppFrames?: number
sourceLinesSpanLibraryFrames?: number
stackTraceLimit?: number
transactionMaxSpans?: number
transactionSampleRate?: number
usePathAsTransactionName?: boolean
verifyServerCert?: boolean
}
interface CaptureErrorOptions {
request?: IncomingMessage
response?: ServerResponse
timestamp?: number
handled?: boolean
user?: UserObject
labels?: Labels
tags?: Labels
custom?: object
message?: string
}
interface Labels {
[key: string]: LabelValue
}
interface UserObject {
id?: string | number
username?: string
email?: string
}
interface ParameterizedMessageObject {
message: string
params: Array<any>
}
interface Logger {
fatal(msg: string, ...args: any[]): void
fatal(obj: {}, msg?: string, ...args: any[]): void
error(msg: string, ...args: any[]): void
error(obj: {}, msg?: string, ...args: any[]): void
warn(msg: string, ...args: any[]): void
warn(obj: {}, msg?: string, ...args: any[]): void
info(msg: string, ...args: any[]): void
info(obj: {}, msg?: string, ...args: any[]): void
debug(msg: string, ...args: any[]): void
debug(obj: {}, msg?: string, ...args: any[]): void
trace(msg: string, ...args: any[]): void
trace(obj: {}, msg?: string, ...args: any[]): void
[propName: string]: any
}
interface TransactionOptions {
startTime?: number
childOf?: Transaction | Span | string
}
interface SpanOptions {
childOf?: Transaction | Span | string
}
type CaptureBody = 'off' | 'errors' | 'transactions' | 'all'
type CaptureErrorLogStackTraces = 'never' | 'messages' | 'always'
type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'
type CaptureErrorCallback = (err: Error | null, id: string) => void
type FilterFn = (payload: Payload) => Payload | boolean | void
type LabelValue = string | number | boolean | null | undefined
type KeyValueConfig = string | Labels | Array<Array<LabelValue>>
type Payload = { [propName: string]: any }
type PatchHandler = (exports: any, agent: Agent, options: PatchOptions) => any
interface PatchOptions {
version: string | undefined
enabled: boolean
}
interface Taggable {
setLabel(name: string, value: LabelValue): boolean
addLabels(labels: Labels): boolean
}
interface StartSpanFn {
startSpan(name?: string | null, options?: SpanOptions): Span | null
startSpan(name: string | null, type: string | null, options?: SpanOptions): Span | null
startSpan(name: string | null, type: string | null, subtype: string | null, options?: SpanOptions): Span | null
startSpan(
name: string | null,
type: string | null,
subtype: string | null,
action: string | null,
options?: SpanOptions
): Span | null
}
// Inlined from @types/aws-lambda - start
declare namespace AwsLambda {
interface CognitoIdentity {
cognitoIdentityId: string
cognitoIdentityPoolId: string
}
interface ClientContext {
client: ClientContextClient
custom?: any
env: ClientContextEnv
}
interface ClientContextClient {
installationId: string
appTitle: string
appVersionName: string
appVersionCode: string
appPackageName: string
}
interface ClientContextEnv {
platformVersion: string
platform: string
make: string
model: string
locale: string
}
type Callback<TResult = any> = (error?: Error | null | string, result?: TResult) => void
interface Context {
// Properties
callbackWaitsForEmptyEventLoop: boolean
functionName: string
functionVersion: string
invokedFunctionArn: string
memoryLimitInMB: number
awsRequestId: string
logGroupName: string
logStreamName: string
identity?: CognitoIdentity
clientContext?: ClientContext
// Functions
getRemainingTimeInMillis(): number
// Functions for compatibility with earlier Node.js Runtime v0.10.42
// For more details see http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-using-old-runtime.html#nodejs-prog-model-oldruntime-context-methods
done(error?: Error, result?: any): void
fail(error: Error | string): void
succeed(messageOrObject: any): void
succeed(message: string, object: any): void
}
type Handler<TEvent = any, TResult = any> = (
event: TEvent,
context: Context,
callback: Callback<TResult>
) => void | Promise<TResult>
}
// Inlined from @types/connect - start
declare namespace Connect {
type NextFunction = (err?: any) => void
type ErrorHandleFunction = (err: any, req: IncomingMessage, res: ServerResponse, next: NextFunction) => void
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { ActivityLogAlerts } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { MonitorClient } from "../monitorClient";
import {
ActivityLogAlertResource,
ActivityLogAlertsListBySubscriptionIdOptionalParams,
ActivityLogAlertsListByResourceGroupOptionalParams,
ActivityLogAlertsCreateOrUpdateOptionalParams,
ActivityLogAlertsCreateOrUpdateResponse,
ActivityLogAlertsGetOptionalParams,
ActivityLogAlertsGetResponse,
ActivityLogAlertsDeleteOptionalParams,
ActivityLogAlertPatchBody,
ActivityLogAlertsUpdateOptionalParams,
ActivityLogAlertsUpdateResponse,
ActivityLogAlertsListBySubscriptionIdResponse,
ActivityLogAlertsListByResourceGroupResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing ActivityLogAlerts operations. */
export class ActivityLogAlertsImpl implements ActivityLogAlerts {
private readonly client: MonitorClient;
/**
* Initialize a new instance of the class ActivityLogAlerts class.
* @param client Reference to the service client
*/
constructor(client: MonitorClient) {
this.client = client;
}
/**
* Get a list of all activity log alerts in a subscription.
* @param options The options parameters.
*/
public listBySubscriptionId(
options?: ActivityLogAlertsListBySubscriptionIdOptionalParams
): PagedAsyncIterableIterator<ActivityLogAlertResource> {
const iter = this.listBySubscriptionIdPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listBySubscriptionIdPagingPage(options);
}
};
}
private async *listBySubscriptionIdPagingPage(
options?: ActivityLogAlertsListBySubscriptionIdOptionalParams
): AsyncIterableIterator<ActivityLogAlertResource[]> {
let result = await this._listBySubscriptionId(options);
yield result.value || [];
}
private async *listBySubscriptionIdPagingAll(
options?: ActivityLogAlertsListBySubscriptionIdOptionalParams
): AsyncIterableIterator<ActivityLogAlertResource> {
for await (const page of this.listBySubscriptionIdPagingPage(options)) {
yield* page;
}
}
/**
* Get a list of all activity log alerts in a resource group.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: ActivityLogAlertsListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<ActivityLogAlertResource> {
const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listByResourceGroupPagingPage(
resourceGroupName: string,
options?: ActivityLogAlertsListByResourceGroupOptionalParams
): AsyncIterableIterator<ActivityLogAlertResource[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: ActivityLogAlertsListByResourceGroupOptionalParams
): AsyncIterableIterator<ActivityLogAlertResource> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* Create a new activity log alert or update an existing one.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param activityLogAlertName The name of the activity log alert.
* @param activityLogAlert The activity log alert to create or use for the update.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
activityLogAlertName: string,
activityLogAlert: ActivityLogAlertResource,
options?: ActivityLogAlertsCreateOrUpdateOptionalParams
): Promise<ActivityLogAlertsCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, activityLogAlertName, activityLogAlert, options },
createOrUpdateOperationSpec
);
}
/**
* Get an activity log alert.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param activityLogAlertName The name of the activity log alert.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
activityLogAlertName: string,
options?: ActivityLogAlertsGetOptionalParams
): Promise<ActivityLogAlertsGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, activityLogAlertName, options },
getOperationSpec
);
}
/**
* Delete an activity log alert.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param activityLogAlertName The name of the activity log alert.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
activityLogAlertName: string,
options?: ActivityLogAlertsDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, activityLogAlertName, options },
deleteOperationSpec
);
}
/**
* Updates an existing ActivityLogAlertResource's tags. To update other fields use the CreateOrUpdate
* method.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param activityLogAlertName The name of the activity log alert.
* @param activityLogAlertPatch Parameters supplied to the operation.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
activityLogAlertName: string,
activityLogAlertPatch: ActivityLogAlertPatchBody,
options?: ActivityLogAlertsUpdateOptionalParams
): Promise<ActivityLogAlertsUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
activityLogAlertName,
activityLogAlertPatch,
options
},
updateOperationSpec
);
}
/**
* Get a list of all activity log alerts in a subscription.
* @param options The options parameters.
*/
private _listBySubscriptionId(
options?: ActivityLogAlertsListBySubscriptionIdOptionalParams
): Promise<ActivityLogAlertsListBySubscriptionIdResponse> {
return this.client.sendOperationRequest(
{ options },
listBySubscriptionIdOperationSpec
);
}
/**
* Get a list of all activity log alerts in a resource group.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: ActivityLogAlertsListByResourceGroupOptionalParams
): Promise<ActivityLogAlertsListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.ActivityLogAlertResource
},
201: {
bodyMapper: Mappers.ActivityLogAlertResource
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.activityLogAlert,
queryParameters: [Parameters.apiVersion11],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.activityLogAlertName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ActivityLogAlertResource
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion11],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.activityLogAlertName
],
headerParameters: [Parameters.accept],
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion11],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.activityLogAlertName
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.ActivityLogAlertResource
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.activityLogAlertPatch,
queryParameters: [Parameters.apiVersion11],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.activityLogAlertName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listBySubscriptionIdOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/microsoft.insights/activityLogAlerts",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ActivityLogAlertList
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion11],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ActivityLogAlertList
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion11],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import path = require('path');
import Tacks = require('tacks');
import tempy = require('tempy');
import pectinBabelrc from '../lib/pectin-babelrc';
const { Dir, File, Symlink } = Tacks;
// spicy symlink prep
const REPO_ROOT = path.resolve('.');
const BABEL_RUNTIME_DEFAULT_VERSION = require('@babel/runtime/package.json').version;
const BABEL_RUNTIME_COREJS2_VERSION = require('@babel/runtime-corejs2/package.json').version;
const BABEL_RUNTIME_COREJS3_VERSION = require('@babel/runtime-corejs3/package.json').version;
function createFixture(spec): string {
const cwd = tempy.directory();
new Tacks(
Dir({
// spicy symlink necessary due to potential runtime package resolution
// eslint-disable-next-line @typescript-eslint/camelcase
node_modules: Symlink(path.relative(cwd, path.join(REPO_ROOT, 'node_modules'))),
...spec,
})
).create(cwd);
return cwd;
}
// tempy creates subdirectories with hexadecimal names that are 32 characters long
const TEMP_DIR_REGEXP = /([^\s"]*[\\/][0-9a-f]{32})([^\s"]*)/g;
// the excluded quotes are due to other snapshot serializers mutating the raw input
expect.addSnapshotSerializer({
test(val) {
return typeof val === 'string' && TEMP_DIR_REGEXP.test(val);
},
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore (the types are wrong, yet again)
serialize(val: string, config, indentation: string, depth: number) {
const str = val.replace(TEMP_DIR_REGEXP, (match, cwd, subPath) =>
path.join('<REPO_ROOT>', subPath)
);
// top-level strings don't need quotes, but nested ones do (object properties, etc)
return depth ? `"${str}"` : str;
},
});
describe('pectin-babelrc', () => {
describe('with implicit cwd', () => {
afterEach(() => {
// avoid polluting other test state
process.chdir(REPO_ROOT);
});
it('begins search for config from process.cwd()', async () => {
const pkg = {
name: 'implicit-cwd',
};
const cwd = createFixture({
'.babelrc': File({
presets: ['@babel/env'],
}),
'package.json': File(pkg),
});
process.chdir(cwd);
const rc = await pectinBabelrc(pkg);
expect(rc).toHaveProperty('cwd', cwd);
});
});
it('generates config for rollup-plugin-babel', async () => {
const pkg = {
name: 'babel-7-config',
dependencies: {
lodash: '^4.17.4',
},
};
const cwd = createFixture({
'.babelrc': File({
presets: ['@babel/env'],
}),
'package.json': File(pkg),
});
const rc = await pectinBabelrc(pkg, cwd);
expect(rc).toMatchInlineSnapshot(`
Object {
"babelrc": false,
"cwd": "<REPO_ROOT>",
"exclude": "node_modules/**",
"extensions": Array [
".js",
".jsx",
".es6",
".es",
".mjs",
".ts",
".tsx",
],
"plugins": Array [],
"presets": Array [
"@babel/env",
],
}
`);
});
it('enables runtimeHelpers when @babel/runtime is a dependency', async () => {
const pkg = {
name: 'helpers-runtime',
dependencies: {
'@babel/runtime': '^7.0.0',
'lodash': '^4.17.4',
},
};
const cwd = createFixture({
'.babelrc': File({
presets: ['@babel/preset-env'],
}),
'package.json': File(pkg),
});
const rc = await pectinBabelrc(pkg, cwd);
expect(rc).toHaveProperty('runtimeHelpers', true);
});
it('does not mutate cached config', async () => {
const pkg = {
name: 'no-mutate',
dependencies: {
lodash: '^4.17.4',
},
};
const cwd = createFixture({
'.babelrc': File({
presets: ['@babel/preset-env'],
plugins: ['lodash'],
}),
'package.json': File(pkg),
});
const opts = await pectinBabelrc(pkg, cwd);
// cosmiconfig caches live objects
opts.foo = 'bar';
const rc = await pectinBabelrc(pkg, cwd);
expect(rc).not.toHaveProperty('foo');
});
it('finds babel.config.js config', async () => {
const pkg = {
name: 'with-babel-config-js',
};
const cwd = createFixture({
'babel.config.js': File(`
module.exports = {
presets: ['@babel/preset-env'],
};
`),
'package.json': File(pkg),
});
const rc = await pectinBabelrc(pkg, cwd);
expect(rc).toMatchInlineSnapshot(`
Object {
"babelrc": false,
"cwd": "<REPO_ROOT>",
"exclude": "node_modules/**",
"extensions": Array [
".js",
".jsx",
".es6",
".es",
".mjs",
".ts",
".tsx",
],
"plugins": Array [],
"presets": Array [
"@babel/preset-env",
],
}
`);
});
it('finds .babelrc.js config', async () => {
const pkg = {
name: 'with-babelrc-js',
};
const cwd = createFixture({
'.babelrc.js': File(`
module.exports = {
presets: ['@babel/preset-env'],
};
`),
'package.json': File(pkg),
});
const rc = await pectinBabelrc(pkg, cwd);
expect(rc).toMatchInlineSnapshot(`
Object {
"babelrc": false,
"cwd": "<REPO_ROOT>",
"exclude": "node_modules/**",
"extensions": Array [
".js",
".jsx",
".es6",
".es",
".mjs",
".ts",
".tsx",
],
"plugins": Array [],
"presets": Array [
"@babel/preset-env",
],
}
`);
});
it('finds pkg.babel config', async () => {
const pkg = {
name: 'with-babel-prop',
babel: {
presets: ['@babel/preset-env'],
},
};
const cwd = createFixture({
'package.json': File(pkg),
});
const rc = await pectinBabelrc(pkg, cwd);
expect(rc).toMatchInlineSnapshot(`
Object {
"babelrc": false,
"cwd": "<REPO_ROOT>",
"exclude": "node_modules/**",
"extensions": Array [
".js",
".jsx",
".es6",
".es",
".mjs",
".ts",
".tsx",
],
"plugins": Array [],
"presets": Array [
"@babel/preset-env",
],
}
`);
});
it('does not duplicate simple runtime transform', async () => {
const pkg = {
name: 'no-duplicate-transform-simple',
dependencies: {
'@babel/runtime': '^7.0.0',
},
};
const cwd = createFixture({
'.babelrc': File({
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-transform-runtime', 'lodash'],
}),
'package.json': File(pkg),
});
const opts = await pectinBabelrc(pkg, cwd, { format: 'esm' });
expect(opts).toHaveProperty('plugins', [
'@babel/plugin-syntax-dynamic-import',
[
'@babel/plugin-transform-runtime',
{ useESModules: true, version: BABEL_RUNTIME_DEFAULT_VERSION },
],
'lodash',
]);
});
it('does not duplicate advanced runtime transform', async () => {
const pkg = {
name: 'no-duplicate-transform-advanced',
dependencies: {
'@babel/runtime': '^7.0.0',
},
};
const cwd = createFixture({
'.babelrc': File({
presets: ['@babel/env'],
plugins: [
'graphql-tag',
[
'@babel/transform-runtime',
{
corejs: true,
},
],
],
}),
'package.json': File(pkg),
});
const opts = await pectinBabelrc(pkg, cwd, { format: 'esm' });
expect(opts).toHaveProperty('plugins', [
'@babel/plugin-syntax-dynamic-import',
'graphql-tag',
[
'@babel/transform-runtime',
{
corejs: true,
useESModules: true,
version: BABEL_RUNTIME_DEFAULT_VERSION,
},
],
]);
});
it('adds missing config to advanced runtime transform', async () => {
const pkg = {
name: 'add-config-transform-advanced',
dependencies: {
'@babel/runtime': '^7.0.0',
},
};
const cwd = createFixture({
'.babelrc': File({
presets: ['@babel/env'],
// admittedly weird...
plugins: [['@babel/plugin-transform-runtime']],
}),
'package.json': File(pkg),
});
const opts = await pectinBabelrc(pkg, cwd, { format: 'esm' });
expect(opts).toHaveProperty('plugins', [
'@babel/plugin-syntax-dynamic-import',
[
'@babel/plugin-transform-runtime',
{ useESModules: true, version: BABEL_RUNTIME_DEFAULT_VERSION },
],
]);
});
it('passes { corejs: 2 } to runtime transform when alternate dependency detected', async () => {
const pkg = {
name: 'add-config-transform-advanced',
dependencies: {
'@babel/runtime-corejs2': '^7.0.0',
},
};
const cwd = createFixture({
'.babelrc': File({
presets: ['@babel/env'],
}),
'package.json': File(pkg),
});
const opts = await pectinBabelrc(pkg, cwd, { format: 'esm' });
expect(opts).toHaveProperty('plugins', [
'@babel/plugin-syntax-dynamic-import',
[
'@babel/plugin-transform-runtime',
{ useESModules: true, corejs: 2, version: BABEL_RUNTIME_COREJS2_VERSION },
],
]);
});
it('passes { corejs: 3 } to runtime transform when alternate dependency detected', async () => {
const pkg = {
name: 'add-config-transform-advanced',
dependencies: {
'@babel/runtime-corejs3': '^7.4.0',
},
};
const cwd = createFixture({
'.babelrc': File({
presets: ['@babel/env'],
}),
'package.json': File(pkg),
});
const opts = await pectinBabelrc(pkg, cwd, { format: 'esm' });
expect(opts).toHaveProperty('plugins', [
'@babel/plugin-syntax-dynamic-import',
[
'@babel/plugin-transform-runtime',
{ useESModules: true, corejs: 3, version: BABEL_RUNTIME_COREJS3_VERSION },
],
]);
});
it('does not duplicate existing @babel/syntax-dynamic-import plugin', async () => {
const pkg = {
name: 'no-duplicate-syntax',
dependencies: {
lodash: '*',
},
};
const cwd = createFixture({
'.babelrc': File({
presets: ['@babel/preset-env'],
plugins: ['lodash', '@babel/syntax-dynamic-import'],
}),
'package.json': File(pkg),
});
const opts = await pectinBabelrc(pkg, cwd, { format: 'esm' });
expect(opts).toHaveProperty('plugins', ['lodash', '@babel/syntax-dynamic-import']);
});
it('does not add syntax-dynamic-import plugin to non-ESM format', async () => {
const pkg = {
name: 'no-cjs-dynamic-import',
dependencies: {
lodash: '*',
},
};
const cwd = createFixture({
'.babelrc': File({
presets: ['@babel/preset-env'],
plugins: ['lodash'],
}),
'package.json': File(pkg),
});
const opts = await pectinBabelrc(pkg, cwd, { format: 'cjs' });
expect(opts).toHaveProperty('plugins', ['lodash']);
});
it('throws an error when .babelrc preset is missing', async () => {
const pkg = {
name: 'no-presets',
dependencies: {
lodash: '^4.17.4',
},
};
const cwd = createFixture({
'.babelrc': File({
plugins: ['lodash'],
}),
'package.json': File(pkg),
});
try {
await pectinBabelrc(pkg, cwd);
} catch (err) {
expect(err.message).toMatchInlineSnapshot(
`"At least one preset (like @babel/preset-env) is required in .babelrc"`
);
}
expect.assertions(1);
});
it('throws an error when pkg.babel preset is missing', async () => {
const pkg = {
name: 'no-prop-presets',
babel: {
plugins: ['lodash'],
},
dependencies: {
lodash: '^4.17.4',
},
};
const cwd = createFixture({
'package.json': File(pkg),
});
try {
await pectinBabelrc(pkg, cwd);
} catch (err) {
expect(err.message).toMatchInlineSnapshot(
`"At least one preset (like @babel/preset-env) is required in \\"babel\\" config block of package.json"`
);
}
expect.assertions(1);
});
it('throws an error when no babel config found', async () => {
const pkg = {
name: 'no-babel-config',
dependencies: {
lodash: '^4.17.4',
},
};
const cwd = createFixture({
'package.json': File(pkg),
});
try {
await pectinBabelrc(pkg, cwd);
} catch (err) {
expect(err.message).toMatchInlineSnapshot(
`"Babel configuration is required for no-babel-config, but no config file was found."`
);
}
expect.assertions(1);
});
it('works all together', async () => {
const pkg1 = {
name: 'pkg1',
};
const pkg2 = {
name: 'pkg2',
babel: {
presets: ['@babel/env'],
plugins: ['lodash'],
},
};
const pkg3 = {
name: 'pkg3',
dependencies: {
'@babel/runtime': '*',
},
};
const pkg4 = {
name: 'pkg4',
dependencies: {
'@babel/runtime': '*',
},
};
const cwd = createFixture({
'package.json': File({
name: 'monorepo',
private: true,
babel: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-proposal-object-rest-spread'],
},
}),
'packages': Dir({
pkg1: Dir({
'package.json': File(pkg1),
}),
pkg2: Dir({
'package.json': File(pkg2),
}),
pkg3: Dir({
'.babelrc': File({
presets: ['@babel/preset-env'],
}),
'package.json': File(pkg3),
}),
pkg4: Dir({
'package.json': File(pkg4),
}),
}),
});
const [config1, config2, config3, config4] = await Promise.all([
pectinBabelrc(pkg1, path.join(cwd, 'packages', 'pkg1')),
pectinBabelrc(pkg2, path.join(cwd, 'packages', 'pkg2')),
pectinBabelrc(pkg3, path.join(cwd, 'packages', 'pkg3')),
pectinBabelrc(pkg4, path.join(cwd, 'packages', 'pkg4'), { format: 'esm' }),
]);
expect(config1).toMatchInlineSnapshot(`
Object {
"babelrc": false,
"cwd": "<REPO_ROOT>/packages/pkg1",
"exclude": "node_modules/**",
"extensions": Array [
".js",
".jsx",
".es6",
".es",
".mjs",
".ts",
".tsx",
],
"plugins": Array [
"@babel/plugin-proposal-object-rest-spread",
],
"presets": Array [
"@babel/preset-env",
],
}
`);
expect(config2).toMatchInlineSnapshot(`
Object {
"babelrc": false,
"cwd": "<REPO_ROOT>/packages/pkg2",
"exclude": "node_modules/**",
"extensions": Array [
".js",
".jsx",
".es6",
".es",
".mjs",
".ts",
".tsx",
],
"plugins": Array [
"lodash",
],
"presets": Array [
"@babel/env",
],
}
`);
expect(config3).toMatchInlineSnapshot(`
Object {
"babelrc": false,
"cwd": "<REPO_ROOT>/packages/pkg3",
"exclude": "node_modules/**",
"extensions": Array [
".js",
".jsx",
".es6",
".es",
".mjs",
".ts",
".tsx",
],
"plugins": Array [
Array [
"@babel/plugin-transform-runtime",
Object {
"useESModules": false,
"version": "${BABEL_RUNTIME_DEFAULT_VERSION}",
},
],
],
"presets": Array [
"@babel/preset-env",
],
"runtimeHelpers": true,
}
`);
expect(config4).toMatchInlineSnapshot(`
Object {
"babelrc": false,
"cwd": "<REPO_ROOT>/packages/pkg4",
"exclude": "node_modules/**",
"extensions": Array [
".js",
".jsx",
".es6",
".es",
".mjs",
".ts",
".tsx",
],
"plugins": Array [
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-proposal-object-rest-spread",
Array [
"@babel/plugin-transform-runtime",
Object {
"useESModules": true,
"version": "${BABEL_RUNTIME_DEFAULT_VERSION}",
},
],
],
"presets": Array [
"@babel/preset-env",
],
"runtimeHelpers": true,
}
`);
});
}); | the_stack |
import { App, getCurrentInstance, nextTick, onUnmounted, unref } from 'vue';
import {
setupDevtoolsPlugin,
DevtoolsPluginApi,
CustomInspectorNode,
CustomInspectorState,
InspectorNodeTag,
ComponentInstance,
} from '@vue/devtools-api';
import { PrivateFieldContext, PrivateFormContext } from './types';
import { keysOf, normalizeField, setInPath, throttle } from './utils';
import { isObject } from '../../shared';
function installDevtoolsPlugin(app: App) {
if (__DEV__) {
setupDevtoolsPlugin(
{
id: 'vee-validate-devtools-plugin',
label: 'VeeValidate Plugin',
packageName: 'vee-validate',
homepage: 'https://vee-validate.logaretm.com/v4',
app,
logo: 'https://vee-validate.logaretm.com/v4/logo.png',
},
setupApiHooks
);
}
}
const DEVTOOLS_FORMS: Record<string, PrivateFormContext & { _vm?: ComponentInstance | null }> = {};
const DEVTOOLS_FIELDS: Record<string, PrivateFieldContext & { _vm?: ComponentInstance | null }> = {};
let API: DevtoolsPluginApi<Record<string, any>> | undefined;
export const refreshInspector = throttle(() => {
setTimeout(async () => {
await nextTick();
API?.sendInspectorState(INSPECTOR_ID);
API?.sendInspectorTree(INSPECTOR_ID);
}, 100);
}, 100);
export function registerFormWithDevTools(form: PrivateFormContext) {
const vm = getCurrentInstance();
if (!API) {
const app = vm?.appContext.app;
if (!app) {
return;
}
installDevtoolsPlugin(app);
}
DEVTOOLS_FORMS[form.formId] = { ...form };
DEVTOOLS_FORMS[form.formId]._vm = vm;
onUnmounted(() => {
delete DEVTOOLS_FORMS[form.formId];
refreshInspector();
});
refreshInspector();
}
export function registerSingleFieldWithDevtools(field: PrivateFieldContext) {
const vm = getCurrentInstance();
if (!API) {
const app = vm?.appContext.app;
if (!app) {
return;
}
installDevtoolsPlugin(app);
}
DEVTOOLS_FIELDS[field.id] = { ...field };
DEVTOOLS_FIELDS[field.id]._vm = vm;
onUnmounted(() => {
delete DEVTOOLS_FIELDS[field.id];
refreshInspector();
});
refreshInspector();
}
const INSPECTOR_ID = 'vee-validate-inspector';
const COLORS = {
error: 0xbd4b4b,
success: 0x06d77b,
unknown: 0x54436b,
white: 0xffffff,
black: 0x000000,
blue: 0x035397,
purple: 0xb980f0,
orange: 0xf5a962,
gray: 0xbbbfca,
};
let SELECTED_NODE: ((PrivateFormContext | PrivateFieldContext) & { _vm?: ComponentInstance | null }) | null = null;
function setupApiHooks(api: DevtoolsPluginApi<Record<string, any>>) {
API = api;
// let highlightTimeout: number | null = null;
function highlightSelected() {
// const vm = SELECTED_NODE?._vm;
// if (!vm) {
// return;
// }
// if (highlightTimeout) {
// window.clearTimeout(highlightTimeout);
// }
// api.unhighlightElement();
// api.highlightElement(vm);
// highlightTimeout = window.setTimeout(() => {
// api.unhighlightElement();
// highlightTimeout = null;
// }, 3000);
}
api.addInspector({
id: INSPECTOR_ID,
icon: 'rule',
label: 'vee-validate',
noSelectionText: 'Select a vee-validate node to inspect',
actions: [
{
icon: 'done_outline',
tooltip: 'Validate selected item',
action: async () => {
if (!SELECTED_NODE) {
console.error('There is not a valid selected vee-validate node or component');
return;
}
const result = await SELECTED_NODE.validate();
console.log(result);
},
},
{
icon: 'delete_sweep',
tooltip: 'Clear validation state of the selected item',
action: () => {
if (!SELECTED_NODE) {
console.error('There is not a valid selected vee-validate node or component');
return;
}
if ('id' in SELECTED_NODE) {
SELECTED_NODE.resetField();
return;
}
SELECTED_NODE.resetForm();
},
},
],
});
api.on.getInspectorTree(payload => {
if (payload.inspectorId !== INSPECTOR_ID) {
return;
}
const forms = Object.values(DEVTOOLS_FORMS);
const fields = Object.values(DEVTOOLS_FIELDS);
payload.rootNodes = [
...forms.map(mapFormForDevtoolsInspector),
...fields.map(field => mapFieldForDevtoolsInspector(field)),
];
});
api.on.getInspectorState((payload, ctx) => {
if (payload.inspectorId !== INSPECTOR_ID || ctx.currentTab !== `custom-inspector:${INSPECTOR_ID}`) {
return;
}
const { form, field, type } = decodeNodeId(payload.nodeId);
if (form && type === 'form') {
payload.state = buildFormState(form);
SELECTED_NODE = form;
highlightSelected();
return;
}
if (field && type === 'field') {
payload.state = buildFieldState(field);
SELECTED_NODE = field;
highlightSelected();
return;
}
SELECTED_NODE = null;
});
}
function mapFormForDevtoolsInspector(form: PrivateFormContext): CustomInspectorNode {
const { textColor, bgColor } = getTagTheme(form);
const formTreeNodes = {};
Object.values(form.fieldsByPath.value).forEach(field => {
const fieldInstance: PrivateFieldContext | undefined = Array.isArray(field) ? field[0] : field;
if (!fieldInstance) {
return;
}
setInPath(formTreeNodes, unref(fieldInstance.name), mapFieldForDevtoolsInspector(fieldInstance, form));
});
function buildFormTree(tree: any[] | Record<string, any>, path: string[] = []): CustomInspectorNode {
const key = [...path].pop();
if ('id' in tree) {
return {
...tree,
label: key || tree.label,
} as CustomInspectorNode;
}
if (isObject(tree)) {
return {
id: `${path.join('.')}`,
label: key || '',
children: Object.keys(tree).map(key => buildFormTree(tree[key], [...path, key])),
};
}
if (Array.isArray(tree)) {
return {
id: `${path.join('.')}`,
label: `${key}[]`,
children: tree.map((c, idx) => buildFormTree(c, [...path, String(idx)])),
};
}
return { id: '', label: '', children: [] };
}
const { children } = buildFormTree(formTreeNodes);
return {
id: encodeNodeId(form),
label: 'Form',
children,
tags: [
{
label: 'Form',
textColor,
backgroundColor: bgColor,
},
{
label: `${Object.keys(form.fieldsByPath.value).length} fields`,
textColor: COLORS.white,
backgroundColor: COLORS.unknown,
},
],
};
}
function mapFieldForDevtoolsInspector(
field: PrivateFieldContext | PrivateFieldContext[],
form?: PrivateFormContext
): CustomInspectorNode {
const fieldInstance = normalizeField(field) as PrivateFieldContext;
const { textColor, bgColor } = getTagTheme(fieldInstance);
const isGroup = Array.isArray(field) && field.length > 1;
return {
id: encodeNodeId(form, fieldInstance, !isGroup),
label: unref(fieldInstance.name),
children: Array.isArray(field) ? field.map(fieldItem => mapFieldForDevtoolsInspector(fieldItem, form)) : undefined,
tags: [
isGroup
? undefined
: {
label: 'Field',
textColor,
backgroundColor: bgColor,
},
!form
? {
label: 'Standalone',
textColor: COLORS.black,
backgroundColor: COLORS.gray,
}
: undefined,
!isGroup && fieldInstance.type === 'checkbox'
? {
label: 'Checkbox',
textColor: COLORS.white,
backgroundColor: COLORS.blue,
}
: undefined,
!isGroup && fieldInstance.type === 'radio'
? {
label: 'Radio',
textColor: COLORS.white,
backgroundColor: COLORS.purple,
}
: undefined,
isGroup
? {
label: 'Group',
textColor: COLORS.black,
backgroundColor: COLORS.orange,
}
: undefined,
].filter(Boolean) as InspectorNodeTag[],
};
}
function encodeNodeId(form?: PrivateFormContext, field?: PrivateFieldContext, encodeIndex = true): string {
const fieldPath = form ? unref(field?.name) : field?.id;
const fieldGroup = fieldPath ? form?.fieldsByPath.value[fieldPath] : undefined;
let idx: number | undefined;
if (encodeIndex && field && Array.isArray(fieldGroup)) {
idx = fieldGroup.indexOf(field);
}
const idObject = { f: form?.formId, ff: fieldPath, idx, type: field ? 'field' : 'form' };
return btoa(JSON.stringify(idObject));
}
function decodeNodeId(nodeId: string): {
field?: PrivateFieldContext & { _vm?: ComponentInstance | null };
form?: PrivateFormContext & { _vm?: ComponentInstance | null };
type?: 'form' | 'field';
} {
try {
const idObject = JSON.parse(atob(nodeId));
const form = DEVTOOLS_FORMS[idObject.f];
if (!form && idObject.ff) {
const field = DEVTOOLS_FIELDS[idObject.ff];
if (!field) {
return {};
}
return {
type: idObject.type,
field,
};
}
if (!form) {
return {};
}
const fieldGroup = form.fieldsByPath.value[idObject.ff];
return {
type: idObject.type,
form,
field: Array.isArray(fieldGroup) ? fieldGroup[idObject.idx || 0] : fieldGroup,
};
} catch (err) {
// console.error(`Devtools: [vee-validate] Failed to parse node id ${nodeId}`);
}
return {};
}
function buildFieldState(field: PrivateFieldContext): CustomInspectorState {
const { errors, meta, value } = field;
return {
'Field state': [
{ key: 'errors', value: errors.value },
{
key: 'initialValue',
value: meta.initialValue,
},
{
key: 'currentValue',
value: value.value,
},
{
key: 'touched',
value: meta.touched,
},
{
key: 'dirty',
value: meta.dirty,
},
{
key: 'valid',
value: meta.valid,
},
],
};
}
function buildFormState(form: PrivateFormContext): CustomInspectorState {
const { errorBag, meta, values, isSubmitting, submitCount } = form;
return {
'Form state': [
{
key: 'submitCount',
value: submitCount.value,
},
{
key: 'isSubmitting',
value: isSubmitting.value,
},
{
key: 'touched',
value: meta.value.touched,
},
{
key: 'dirty',
value: meta.value.dirty,
},
{
key: 'valid',
value: meta.value.valid,
},
{
key: 'initialValues',
value: meta.value.initialValues,
},
{
key: 'currentValues',
value: values,
},
{
key: 'errors',
value: keysOf(errorBag.value).reduce((acc, key) => {
const message = errorBag.value[key]?.[0];
if (message) {
acc[key] = message;
}
return acc;
}, {} as Record<string, string | undefined>),
},
],
};
}
/**
* Resolves the tag color based on the form state
*/
function getTagTheme(fieldOrForm: PrivateFormContext | PrivateFieldContext) {
// const fallbackColors = {
// bgColor: COLORS.unknown,
// textColor: COLORS.white,
// };
const isValid = 'id' in fieldOrForm ? fieldOrForm.meta.valid : fieldOrForm.meta.value.valid;
return {
bgColor: isValid ? COLORS.success : COLORS.error,
textColor: isValid ? COLORS.black : COLORS.white,
};
} | the_stack |
'use strict';
//core
import * as assert from 'assert';
import * as path from 'path';
import * as fs from 'fs';
//npm
import async = require('async');
import chalk from 'chalk';
// project
import log from './logging';
import {EVCb, NLUDotJSON, NluMap, PkgJSON} from "./index";
import {q} from './search-queue';
import {mapPaths} from "./map-paths";
import {
determineIfReinstallIsNeeded,
getDepsListFromNluJSON,
getDevKeys,
getProdKeys,
getSearchRootsFromNluConf
} from "./utils";
import {NLURunOpts} from "./commands/run/cmd-line-opts";
const searchedPaths = {} as { [key: string]: true };
export const rootPaths: Array<string> = [];
export type Task = (cb: EVCb<any>) => void;
// searchQueue used to prevent too many dirs searched at once
const searchQueue = async.queue<Task, any>((task, cb) => task(cb), 8);
//////////////////////////////////////////////////////////////////////
export const makeFindProject = function (mainProjectName: string, totalList: Map<string, true>, map: NluMap,
ignore: Array<RegExp>, opts: NLURunOpts, status: any, conf: NLUDotJSON) {
const isPathSearchableBasic = (item: string) => {
item = path.normalize(item);
if (!path.isAbsolute(item)) {
throw new Error('Path to be searched is not absolute:' + item);
}
if (searchedPaths[item]) {
opts.verbosity > 2 && log.info('already searched this path, not searching again:', chalk.bold(item));
return false;
}
return true;
};
const isPathSearchable = function (item: string) {
// if a path is not searchable, this returns true
// iow, if a path is searchable, this returns falsy
item = path.normalize(item);
if (!path.isAbsolute(item)) {
throw new Error('Path to be searched is not absolute:' + item);
}
if (searchedPaths[item]) {
opts.verbosity > 2 && log.info('already searched this path, not searching again:', chalk.bold(item));
return false;
}
let goodPth = '';
const keys = Object.keys(searchedPaths);
// important - note that this section is not merely checking for equality.
// it is instead checking to see if an existing search path is shorter
// than the new search path, and if so, we don't need to add the new one
const match = keys.some(pth => {
if (item.startsWith(pth)) {
goodPth = pth;
return true;
}
});
if (match && opts.verbosity > 1) {
log.info(chalk.blue('path has already been covered:'));
log.info('potential new path:', chalk.bold(item));
log.info('already searched path:', chalk.bold(goodPth));
}
return match;
};
/////////////////////////////////////////////////////////////////////////
const isIgnored = (pth: string): boolean => {
return ignore.some(r => {
if (r.test(pth)) {
if (opts.verbosity > 3) {
log.warning(`Path with value "${pth}" was ignored because it matched the following regex:`);
log.warning(`${r}`);
}
return true;
}
});
};
///////////////////////////////////////////////////////////////////////////
return function findProject(item: string, cb: EVCb<any>): void {
item = path.normalize(item);
if (!isPathSearchableBasic(item)) {
return process.nextTick(cb);
}
searchedPaths[item] = true;
rootPaths.push(item);
log.info('New path being searched:', chalk.blue(item));
(function getMarkers(dir, cb) {
if (isIgnored(String(dir + '/'))) {
if (opts.verbosity > 2) {
log.warning('path ignored => ', dir);
}
return process.nextTick(cb);
}
if (status.searching === false) {
opts.verbosity > 2 && log.error('There was an error so we short-circuited search.');
return process.nextTick(cb);
}
searchedPaths[dir] = true;
searchQueue.push(callback => {
fs.readdir(dir, (err, items) => {
callback();
if (err) {
log.error(err.message || err);
if (String(err.message || err).match(/permission denied/)) {
return cb(null);
}
return cb(err);
}
if (status.searching === false) {
opts.verbosity > 2 && log.error('There was an error so we short-circuited search.');
return process.nextTick(cb);
}
items = items.map(function (item) {
return path.resolve(dir, item);
});
let deps: Array<string>, npmlinkup: NLUDotJSON, hasNLUJSONFile = false;
try {
npmlinkup = require(path.resolve(dir + '/.nlu.json'));
hasNLUJSONFile = true;
if (npmlinkup && npmlinkup.searchable === false) {
log.warn('The following dir is not searchable:', dir);
return cb(null);
}
}
catch (e) {
npmlinkup = {} as NLUDotJSON;
}
async.eachLimit(items, 7, (item: string, cb: EVCb<any>) => {
if (isIgnored(String(item))) {
if (opts.verbosity > 2) {
log.warning('path ignored => ', item);
}
return process.nextTick(cb);
}
fs.lstat(item, function (err, stats) {
if (err) {
log.warning('warning => maybe a symlink? => ', item);
return cb();
}
if (status.searching === false) {
opts.verbosity > 1 && log.error('There was an error so we short-circuited search.');
return process.nextTick(cb);
}
if (stats.isSymbolicLink()) {
opts.verbosity > 2 && log.warning('warning => looks like a symlink => ', item);
return cb();
}
if (stats.isDirectory()) {
if (!isPathSearchableBasic(item)) {
return cb(null);
}
if (isIgnored(String(item + '/'))) {
if (opts.verbosity > 2) {
log.warning('path ignored by settings/regex => ', item);
}
cb(null);
}
else {
// continue drilling down
getMarkers(item, cb);
}
return;
}
if (!stats.isFile()) {
if (opts.verbosity > 2) {
log.warning('Not a directory or file (maybe a symlink?) => ', item);
}
return cb(null);
}
let dirname = path.dirname(item);
let filename = path.basename(item);
if (String(filename) !== 'package.json') {
return cb(null);
}
let pkg: PkgJSON, linkable = null;
try {
pkg = require(item);
}
catch (err) {
return cb(err);
}
try {
linkable = pkg.nlu.linkable;
}
catch (err) {
//ignore
}
if (linkable === false) {
return cb(null);
}
if (pkg.name === mainProjectName && linkable !== true) {
if (opts.verbosity > 1) {
log.info('Another project on your fs has your main projects package.json name, at path:', chalk.yellow.bold(dirname));
}
return cb(null);
}
if (npmlinkup.linkable === false) {
log.warn(`Skipping project at dir "${dirname}" because 'linkable' was set to false.`);
return cb(null);
}
const pkgFromConf = conf.packages[pkg.name] || {};
npmlinkup = Object.assign({}, pkgFromConf, npmlinkup);
try {
deps = getDepsListFromNluJSON(npmlinkup);
assert(Array.isArray(deps),
`the 'list' property in an .nlu.json file is not an Array instance for '${filename}'.`);
}
catch (err) {
log.error(chalk.redBright('Could not parse list/packages/deps properties from .nlu.json file at this path:'));
log.error(chalk.redBright.bold(dirname));
return cb(err);
}
deps.forEach(item => {
totalList.set(item, true);
});
if(map[dirname]){
log.warn('Map already has key: ' + dirname);
return process.nextTick(cb);
}
const m = map[dirname] = {
name: pkg.name,
bin: pkg.bin || null,
hasNLUJSONFile,
isMainProject: false,
linkToItself: Boolean(npmlinkup.linkToItself),
runInstall: Boolean(npmlinkup.alwaysReinstall),
path: dirname,
deps: deps,
package: pkg,
searchRoots: null as Array<string>,
installedSet: new Set(),
linkedSet: {}
};
const nm = path.resolve(dirname + '/node_modules');
const keys = opts.production ? getProdKeys(pkg) : getDevKeys(pkg);
async.autoInject({
addToSearchRoots(cb: EVCb<any>) {
const searchRoots = getSearchRootsFromNluConf(npmlinkup);
if (searchRoots.length < 1) {
return process.nextTick(cb, null);
}
mapPaths(searchRoots, dirname, (err: any, roots: Array<string>) => {
if (err) {
return cb(err);
}
m.searchRoots = roots.slice(0);
roots.forEach(r => {
if (isPathSearchable(r)) {
log.info(chalk.cyan('Given the .nlu.json file at this path:'), chalk.bold(dirname));
log.info(chalk.cyan('We are adding this to the search queue:'), chalk.bold(r));
q.push(cb => findProject(r, cb));
}
});
cb(null);
});
}
}, cb);
});
}, cb);
});
});
})(item, cb);
}
}; | the_stack |
import {IOas20NodeVisitor, IOas30NodeVisitor, IOasNodeVisitor} from "./visitor.iface";
import {Oas20Document} from "../models/2.0/document.model";
import {OasExtension} from "../models/extension.model";
import {Oas20PathItem} from "../models/2.0/path-item.model";
import {Oas20Operation} from "../models/2.0/operation.model";
import {Oas20Parameter, Oas20ParameterBase, Oas20ParameterDefinition} from "../models/2.0/parameter.model";
import {Oas20Response, Oas20ResponseBase, Oas20ResponseDefinition} from "../models/2.0/response.model";
import {
Oas20AdditionalPropertiesSchema,
Oas20AllOfSchema,
Oas20ItemsSchema,
Oas20PropertySchema,
Oas20Schema,
Oas20SchemaDefinition
} from "../models/2.0/schema.model";
import {Oas20Header} from "../models/2.0/header.model";
import {Oas20Example} from "../models/2.0/example.model";
import {Oas20Items} from "../models/2.0/items.model";
import {OasNode, OasValidationProblem} from "../models/node.model";
import {OasExtensibleNode} from "../models/enode.model";
import {Oas20Scopes} from "../models/2.0/scopes.model";
import {Oas20SecurityDefinitions} from "../models/2.0/security-definitions.model";
import {Oas20SecurityScheme} from "../models/2.0/security-scheme.model";
import {Oas20Definitions} from "../models/2.0/definitions.model";
import {Oas20ParametersDefinitions} from "../models/2.0/parameters-definitions.model";
import {Oas20ResponsesDefinitions} from "../models/2.0/responses-definitions.model";
import {OasDocument} from "../models/document.model";
import {OasInfo} from "../models/common/info.model";
import {OasContact} from "../models/common/contact.model";
import {OasLicense} from "../models/common/license.model";
import {Oas30Document} from "../models/3.0/document.model";
import {Oas30ServerVariable} from "../models/3.0/server-variable.model";
import {Oas30LinkServer, Oas30Server} from "../models/3.0/server.model";
import {OasSecurityRequirement} from "../models/common/security-requirement.model";
import {OasExternalDocumentation} from "../models/common/external-documentation.model";
import {OasTag} from "../models/common/tag.model";
import {OasPaths} from "../models/common/paths.model";
import {OasPathItem} from "../models/common/path-item.model";
import {OasResponses} from "../models/common/responses.model";
import {OasHeader} from "../models/common/header.model";
import {OasOperation} from "../models/common/operation.model";
import {OasXML} from "../models/common/xml.model";
import {OasSchema} from "../models/common/schema.model";
import {Oas30Parameter, Oas30ParameterBase, Oas30ParameterDefinition} from "../models/3.0/parameter.model";
import {Oas30Response, Oas30ResponseBase, Oas30ResponseDefinition} from "../models/3.0/response.model";
import {Oas30RequestBody, Oas30RequestBodyDefinition} from "../models/3.0/request-body.model";
import {
Oas30AdditionalPropertiesSchema,
Oas30AllOfSchema,
Oas30AnyOfSchema,
Oas30ItemsSchema,
Oas30NotSchema,
Oas30OneOfSchema,
Oas30PropertySchema,
Oas30Schema,
Oas30SchemaDefinition
} from "../models/3.0/schema.model";
import {Oas30CallbackPathItem, Oas30PathItem} from "../models/3.0/path-item.model";
import {Oas30Operation} from "../models/3.0/operation.model";
import {Oas30Header, Oas30HeaderDefinition} from "../models/3.0/header.model";
import {Oas30MediaType} from "../models/3.0/media-type.model";
import {Oas30Encoding} from "../models/3.0/encoding.model";
import {IOasIndexedNode} from "../models/inode.model";
import {Oas30Example, Oas30ExampleDefinition} from "../models/3.0/example.model";
import {Oas30Link, Oas30LinkDefinition} from "../models/3.0/link.model";
import {Oas30LinkParameterExpression} from "../models/3.0/link-parameter-expression.model";
import {Oas30Callback, Oas30CallbackDefinition} from "../models/3.0/callback.model";
import {Oas30Components} from "../models/3.0/components.model";
import {Oas30OAuthFlows} from "../models/3.0/oauth-flows.model";
import {
Oas30AuthorizationCodeOAuthFlow,
Oas30ClientCredentialsOAuthFlow, Oas30ImplicitOAuthFlow, Oas30OAuthFlow,
Oas30PasswordOAuthFlow
} from "../models/3.0/oauth-flow.model";
import {OasSecurityScheme} from "../models/common/security-scheme.model";
import {Oas30SecurityScheme} from "../models/3.0/security-scheme.model";
import {Oas20Headers} from "../models/2.0/headers.model";
import {Oas30LinkRequestBodyExpression} from "../models/3.0/link-request-body-expression.model";
import {Oas30Discriminator} from "../models/3.0/discriminator.model";
/**
* Interface implemented by all traversers.
*/
export interface IOasTraverser {
traverse(node: OasNode): void;
}
/**
* Used to traverse an OAS tree and call an included visitor for each node.
*/
export abstract class OasTraverser implements IOasNodeVisitor, IOasTraverser {
/**
* Constructor.
* @param visitor
*/
constructor(protected visitor: IOasNodeVisitor) {}
/**
* Called to traverse an OAS 2.0 tree starting at the given node and traversing
* down until this node and all child nodes have been visited.
* @param node
*/
public traverse(node: OasNode): void {
node.accept(this);
}
/**
* Traverse into the given node, unless it's null.
* @param node
*/
protected traverseIfNotNull(node: OasNode): void {
if (node) {
node.accept(this);
}
}
/**
* Traverse the items of the given array.
* @param items
*/
protected traverseArray(items: OasNode[]): void {
if (Array.isArray(items)) {
for (let item of items) {
this.traverseIfNotNull(item);
}
}
}
/**
* Traverse the children of an indexed node.
* @param indexedNode
*/
protected traverseIndexedNode(indexedNode: IOasIndexedNode<OasNode>): void {
let itemNames: string[] = indexedNode.getItemNames();
if (itemNames && itemNames.length > 0) {
for (let itemName of itemNames) {
let item: OasNode = indexedNode.getItem(itemName);
this.traverseIfNotNull(item);
}
}
}
/**
* Traverse the extension nodes, if any are found.
* @param node
*/
protected traverseExtensions(node: OasExtensibleNode): void {
this.traverseArray(node.extensions());
}
/**
* Traverse the validation problems, if any exist. Validation problems would
* only exist if validation has been performed on the data model.
* @param {OasNode} node
*/
protected traverseValidationProblems(node: OasNode): void {
this.traverseArray(node.validationProblems());
}
/**
* Visit the document.
* @param node
*/
public abstract visitDocument(node: OasDocument): void;
/**
* Visit the info object.
* @param node
*/
public visitInfo(node: OasInfo): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.contact);
this.traverseIfNotNull(node.license);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the contact object.
* @param node
*/
public visitContact(node: OasContact): void {
node.accept(this.visitor);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the license object.
* @param node
*/
public visitLicense(node: OasLicense): void {
node.accept(this.visitor);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the paths.
* @param node
*/
public visitPaths(node: OasPaths): void {
node.accept(this.visitor);
this.traverseIndexedNode(node);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the path item.
* @param node
*/
public abstract visitPathItem(node: OasPathItem): void;
/**
* Visit the operation.
* @param node
*/
public abstract visitOperation(node: OasOperation): void;
/**
* Visit the header.
* @param node
*/
public abstract visitHeader(node: OasHeader): void;
/**
* Visit the header.
* @param node
*/
public abstract visitSchema(node: OasSchema): void;
/**
* Visit the responses.
* @param node
*/
public visitResponses(node: OasResponses): void {
node.accept(this.visitor);
this.traverseIndexedNode(node);
this.traverseIfNotNull(node.default);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the scopes.
* @param node
*/
public visitXML(node: OasXML): void {
node.accept(this.visitor);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the security requirement.
* @param node
*/
public visitSecurityRequirement(node: OasSecurityRequirement): void {
node.accept(this.visitor);
this.traverseValidationProblems(node);
}
/**
* Visit the security scheme.
* @param node
*/
public abstract visitSecurityScheme(node: OasSecurityScheme): void;
/**
* Visit the tag.
* @param node
*/
public visitTag(node: OasTag): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.externalDocs);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the external doc.
* @param node
*/
public visitExternalDocumentation(node: OasExternalDocumentation): void {
node.accept(this.visitor);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the extension.
* @param node
*/
public visitExtension(node: OasExtension): void {
node.accept(this.visitor);
this.traverseValidationProblems(node);
}
/**
* Visit the validation problem.
* @param {OasValidationProblem} node
*/
public visitValidationProblem(node: OasValidationProblem): void {
node.accept(this.visitor);
// Don't traverse the validation problem's validation problems. :)
}
}
/**
* Used to traverse an OAS 2.0 tree and call an included visitor for each node.
*/
export class Oas20Traverser extends OasTraverser implements IOas20NodeVisitor {
/**
* Constructor.
* @param visitor
*/
constructor(visitor: IOas20NodeVisitor) {
super(visitor);
}
/**
* Visit the document.
* @param node
*/
public visitDocument(node: Oas20Document): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.info);
this.traverseIfNotNull(node.paths);
this.traverseIfNotNull(node.definitions);
this.traverseIfNotNull(node.parameters);
this.traverseIfNotNull(node.responses);
this.traverseIfNotNull(node.securityDefinitions);
this.traverseArray(node.security);
this.traverseArray(node.tags);
this.traverseIfNotNull(node.externalDocs);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the path item.
* @param node
*/
public visitPathItem(node: Oas20PathItem): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.get);
this.traverseIfNotNull(node.put);
this.traverseIfNotNull(node.post);
this.traverseIfNotNull(node.delete);
this.traverseIfNotNull(node.options);
this.traverseIfNotNull(node.head);
this.traverseIfNotNull(node.patch);
this.traverseArray(node.parameters);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the operation.
* @param node
*/
public visitOperation(node: Oas20Operation): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.externalDocs);
this.traverseArray(node.parameters);
this.traverseIfNotNull(node.responses);
this.traverseArray(node.security);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit a parameter.
* @param node
*/
private visitParameterBase(node: Oas20ParameterBase): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.schema);
this.traverseIfNotNull(node.items);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the parameter.
* @param node
*/
public visitParameter(node: Oas20Parameter): void {
this.visitParameterBase(node);
}
/**
* Visit the parameter definition.
* @param node
*/
public visitParameterDefinition(node: Oas20ParameterDefinition): void {
this.visitParameterBase(node);
}
private visitResponseBase(node: Oas20ResponseBase): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.schema);
this.traverseIfNotNull(node.headers);
this.traverseIfNotNull(node.examples);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the response.
* @param node
*/
public visitResponse(node: Oas20Response): void {
this.visitResponseBase(node);
}
/**
* Visit the headers.
* @param node
*/
public visitHeaders(node: Oas20Headers): void {
node.accept(this.visitor);
this.traverseIndexedNode(node);
this.traverseValidationProblems(node);
}
/**
* Visit the response definition.
* @param node
*/
public visitResponseDefinition(node: Oas20ResponseDefinition): void {
this.visitResponseBase(node);
}
/**
* Visit the schema.
* @param node
*/
public visitSchema(node: Oas20Schema): void {
node.accept(this.visitor);
if (node.items !== null && Array.isArray(node.items)) {
this.traverseArray(<Oas20ItemsSchema[]>node.items);
} else {
this.traverseIfNotNull(<Oas20ItemsSchema>node.items);
}
this.traverseArray(node.allOf);
let propNames: string[] = node.propertyNames();
if (propNames && propNames.length > 0) {
for (let propName of propNames) {
let prop: Oas20Schema = node.property(propName) as Oas20Schema;
this.traverseIfNotNull(prop);
}
}
if (typeof node.additionalProperties !== "boolean") {
this.traverseIfNotNull(<Oas20AdditionalPropertiesSchema>node.additionalProperties);
}
this.traverseIfNotNull(node.xml);
this.traverseIfNotNull(node.externalDocs);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the schema.
* @param node
*/
public visitPropertySchema(node: Oas20PropertySchema): void {
this.visitSchema(node);
}
/**
* Visit the schema.
* @param node
*/
public visitSchemaDefinition(node: Oas20SchemaDefinition): void {
this.visitSchema(node);
}
/**
* Visit the schema.
* @param node
*/
public visitAdditionalPropertiesSchema(node: Oas20AdditionalPropertiesSchema): void {
this.visitSchema(node);
}
/**
* Visit the schema.
* @param node
*/
public visitAllOfSchema(node: Oas20AllOfSchema): void {
this.visitSchema(node);
}
/**
* Visit the schema.
* @param node
*/
public visitItemsSchema(node: Oas20ItemsSchema): void {
this.visitSchema(node);
}
/**
* Visit the header.
* @param node
*/
public visitHeader(node: Oas20Header): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.items);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the example.
* @param node
*/
public visitExample(node: Oas20Example): void {
node.accept(this.visitor);
this.traverseValidationProblems(node);
}
/**
* Visit the items.
* @param node
*/
public visitItems(node: Oas20Items): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.items);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the security definitions.
* @param node
*/
public visitSecurityDefinitions(node: Oas20SecurityDefinitions): void {
node.accept(this.visitor);
this.traverseIndexedNode(node);
this.traverseValidationProblems(node);
}
/**
* Visit the security scheme.
* @param node
*/
public visitSecurityScheme(node: Oas20SecurityScheme): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.scopes);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the scopes.
* @param node
*/
public visitScopes(node: Oas20Scopes): void {
node.accept(this.visitor);
this.traverseValidationProblems(node);
}
/**
* Visit the definitions.
* @param node
*/
public visitDefinitions(node: Oas20Definitions): void {
node.accept(this.visitor);
this.traverseIndexedNode(node);
this.traverseValidationProblems(node);
}
/**
* Visit the definitions.
* @param node
*/
public visitParametersDefinitions(node: Oas20ParametersDefinitions): void {
node.accept(this.visitor);
this.traverseIndexedNode(node);
this.traverseValidationProblems(node);
}
/**
* Visit the responses.
* @param node
*/
public visitResponsesDefinitions(node: Oas20ResponsesDefinitions): void {
node.accept(this.visitor);
this.traverseIndexedNode(node);
this.traverseValidationProblems(node);
}
}
/**
* Used to traverse an OAS 3.0 tree and call an included visitor for each node.
*/
export class Oas30Traverser extends OasTraverser implements IOas30NodeVisitor {
/**
* Constructor.
* @param visitor
*/
constructor(visitor: IOas30NodeVisitor) {
super(visitor);
}
/**
* Visit the document.
* @param node
*/
public visitDocument(node: Oas30Document): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.info);
this.traverseArray(node.servers);
this.traverseIfNotNull(node.paths);
this.traverseIfNotNull(node.components);
this.traverseArray(node.security);
this.traverseArray(node.tags);
this.traverseIfNotNull(node.externalDocs);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitPathItem(node: Oas30PathItem): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.get);
this.traverseIfNotNull(node.put);
this.traverseIfNotNull(node.post);
this.traverseIfNotNull(node.delete);
this.traverseIfNotNull(node.options);
this.traverseIfNotNull(node.head);
this.traverseIfNotNull(node.patch);
this.traverseIfNotNull(node.trace);
this.traverseArray(node.parameters);
this.traverseArray(node.servers);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitOperation(node: Oas30Operation): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.externalDocs);
this.traverseArray(node.parameters);
this.traverseIfNotNull(node.responses);
this.traverseIfNotNull(node.requestBody);
this.traverseArray(node.getCallbacks());
this.traverseArray(node.security);
this.traverseArray(node.servers);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitHeader(node: Oas30Header): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.schema);
this.traverseArray(node.getExamples());
this.traverseArray(node.getMediaTypes());
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitSchema(node: Oas30Schema): void {
node.accept(this.visitor);
if (Array.isArray(node.items)) {
this.traverseArray(<Oas20ItemsSchema[]>node.items);
} else {
this.traverseIfNotNull(<Oas20ItemsSchema>node.items);
}
this.traverseArray(node.allOf);
let propNames: string[] = node.propertyNames();
if (propNames && propNames.length > 0) {
for (let propName of propNames) {
let prop: Oas20Schema = node.property(propName) as Oas20Schema;
this.traverseIfNotNull(prop);
}
}
if (typeof node.additionalProperties !== "boolean") {
this.traverseIfNotNull(<Oas20AdditionalPropertiesSchema>node.additionalProperties);
}
this.traverseArray(node.oneOf);
this.traverseArray(node.anyOf);
this.traverseIfNotNull(node.not);
this.traverseIfNotNull(node.discriminator);
this.traverseIfNotNull(node.xml);
this.traverseIfNotNull(node.externalDocs);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitDiscriminator(node: Oas30Discriminator): void {
node.accept(this.visitor);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitParameter(node: Oas30Parameter): void {
this.visitParameterBase(node);
}
/**
* Visit the node.
* @param node
*/
public visitParameterDefinition(node: Oas30ParameterDefinition): void {
this.visitParameterBase(node);
}
/**
* Visit a parameter.
* @param node
*/
private visitParameterBase(node: Oas30ParameterBase): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.schema);
this.traverseArray(node.getExamples());
this.traverseArray(node.getMediaTypes());
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitResponse(node: Oas30Response): void {
this.visitResponseBase(node);
}
/**
* Visit the node.
* @param node
*/
public visitResponseDefinition(node: Oas30ResponseDefinition): void {
this.visitResponseBase(node);
}
/**
* Visit a response.
* @param node
*/
private visitResponseBase(node: Oas30ResponseBase): void {
node.accept(this.visitor);
this.traverseArray(node.getMediaTypes());
this.traverseArray(node.getLinks());
this.traverseArray(node.getHeaders());
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitLink(node: Oas30Link): void {
node.accept(this.visitor);
this.traverseArray(node.getLinkParameterExpressions());
this.traverseIfNotNull(node.requestBody);
this.traverseIfNotNull(node.server);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitLinkParameterExpression(node: Oas30LinkParameterExpression): void {
node.accept(this.visitor);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitLinkRequestBodyExpression(node: Oas30LinkRequestBodyExpression): void {
node.accept(this.visitor);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitLinkServer(node: Oas30LinkServer): void {
this.visitServer(node);
}
/**
* Visit the node.
* @param node
*/
public visitRequestBody(node: Oas30RequestBody): void {
node.accept(this.visitor);
this.traverseArray(node.getMediaTypes());
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitMediaType(node: Oas30MediaType): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.schema);
this.traverseArray(node.getExamples());
this.traverseArray(node.getEncodings());
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitEncoding(node: Oas30Encoding): void {
node.accept(this.visitor);
this.traverseArray(node.getHeaders());
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitExample(node: Oas30Example): void {
node.accept(this.visitor);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitCallback(node: Oas30Callback): void {
node.accept(this.visitor);
this.traverseIndexedNode(node);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitCallbackPathItem(node: Oas30CallbackPathItem): void {
this.visitPathItem(node);
}
/**
* Visit the node.
* @param node
*/
public visitAllOfSchema(node: Oas30AllOfSchema): void {
this.visitSchema(node);
}
/**
* Visit the node.
* @param node
*/
public visitAnyOfSchema(node: Oas30AnyOfSchema): void {
this.visitSchema(node);
}
/**
* Visit the node.
* @param node
*/
public visitOneOfSchema(node: Oas30OneOfSchema): void {
this.visitSchema(node);
}
/**
* Visit the node.
* @param node
*/
public visitNotSchema(node: Oas30NotSchema): void {
this.visitSchema(node);
}
/**
* Visit the node.
* @param node
*/
public visitPropertySchema(node: Oas30PropertySchema): void {
this.visitSchema(node);
}
/**
* Visit the node.
* @param node
*/
public visitItemsSchema(node: Oas30ItemsSchema): void {
this.visitSchema(node);
}
/**
* Visit the node.
* @param node
*/
public visitAdditionalPropertiesSchema(node: Oas30AdditionalPropertiesSchema): void {
this.visitSchema(node);
}
/**
* Visit the node.
* @param node
*/
public visitComponents(node: Oas30Components): void {
node.accept(this.visitor);
this.traverseArray(node.getSchemaDefinitions());
this.traverseArray(node.getResponseDefinitions());
this.traverseArray(node.getParameterDefinitions());
this.traverseArray(node.getExampleDefinitions());
this.traverseArray(node.getRequestBodyDefinitions());
this.traverseArray(node.getHeaderDefinitions());
this.traverseArray(node.getSecuritySchemes());
this.traverseArray(node.getLinkDefinitions());
this.traverseArray(node.getCallbackDefinitions());
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitExampleDefinition(node: Oas30ExampleDefinition): void {
this.visitExample(node);
}
/**
* Visit the node.
* @param node
*/
public visitRequestBodyDefinition(node: Oas30RequestBodyDefinition): void {
this.visitRequestBody(node);
}
/**
* Visit the node.
* @param node
*/
public visitHeaderDefinition(node: Oas30HeaderDefinition): void {
this.visitHeader(node);
}
/**
* Visit the node.
* @param node
*/
public visitSecurityScheme(node: Oas30SecurityScheme): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.flows);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitOAuthFlows(node: Oas30OAuthFlows): void {
node.accept(this.visitor);
this.traverseIfNotNull(node.implicit);
this.traverseIfNotNull(node.password);
this.traverseIfNotNull(node.clientCredentials);
this.traverseIfNotNull(node.authorizationCode);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitImplicitOAuthFlow(node: Oas30ImplicitOAuthFlow): void {
this.visitOAuthFlow(node);
}
/**
* Visit the node.
* @param node
*/
public visitPasswordOAuthFlow(node: Oas30PasswordOAuthFlow): void {
this.visitOAuthFlow(node);
}
/**
* Visit the node.
* @param node
*/
public visitClientCredentialsOAuthFlow(node: Oas30ClientCredentialsOAuthFlow): void {
this.visitOAuthFlow(node);
}
/**
* Visit the node.
* @param node
*/
public visitAuthorizationCodeOAuthFlow(node: Oas30AuthorizationCodeOAuthFlow): void {
this.visitOAuthFlow(node);
}
/**
* Visit the node.
* @param node
*/
private visitOAuthFlow(node: Oas30OAuthFlow): void {
node.accept(this.visitor);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitLinkDefinition(node: Oas30LinkDefinition): void {
this.visitLink(node);
}
/**
* Visit the node.
* @param node
*/
public visitCallbackDefinition(node: Oas30CallbackDefinition): void {
this.visitCallback(node);
}
/**
* Visit the node.
* @param node
*/
public visitSchemaDefinition(node: Oas30SchemaDefinition): void {
this.visitSchema(node);
}
/**
* Visit the node.
* @param node
*/
public visitServer(node: Oas30Server): void {
node.accept(this.visitor);
this.traverseArray(node.getServerVariables());
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
/**
* Visit the node.
* @param node
*/
public visitServerVariable(node: Oas30ServerVariable): void {
node.accept(this.visitor);
this.traverseExtensions(node);
this.traverseValidationProblems(node);
}
}
/**
* Used to traverse up an OAS tree and call an included visitor for each node.
*/
export abstract class OasReverseTraverser implements IOasNodeVisitor, IOasTraverser {
/**
* Constructor.
* @param visitor
*/
constructor(protected visitor: IOasNodeVisitor) {}
/**
* Traverse the given node.
* @param node
*/
public traverse(node: OasNode): void {
node.accept(this);
}
public visitDocument(node: OasDocument): void {
node.accept(this.visitor);
}
public visitInfo(node: OasInfo): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitContact(node: OasContact): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitLicense(node: OasLicense): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitPaths(node: OasPaths): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitPathItem(node: OasPathItem): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitOperation(node: OasOperation): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitResponses(node: OasResponses): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitSchema(node: OasSchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitHeader(node: OasHeader): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitXML(node: OasXML): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitSecurityScheme(node: OasSecurityScheme): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitSecurityRequirement(node: OasSecurityRequirement): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitTag(node: OasTag): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitExternalDocumentation(node: OasExternalDocumentation): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitExtension(node: OasExtension): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitValidationProblem(node: OasValidationProblem): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
}
/**
* Used to traverse up an OAS 2.0 tree and call an included visitor for each node.
*/
export class Oas20ReverseTraverser extends OasReverseTraverser implements IOas20NodeVisitor, IOasTraverser {
/**
* Constructor.
* @param visitor
*/
constructor(visitor: IOas20NodeVisitor) {
super(visitor);
}
public visitParameter(node: Oas20Parameter): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitParameterDefinition(node: Oas20ParameterDefinition): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitResponse(node: Oas20Response): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitHeaders(node: Oas20Headers): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitResponseDefinition(node: Oas20ResponseDefinition): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitExample(node: Oas20Example): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitItems(node: Oas20Items): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitSecurityDefinitions(node: Oas20SecurityDefinitions): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitScopes(node: Oas20Scopes): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitSchemaDefinition(node: Oas20SchemaDefinition): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitPropertySchema(node: Oas20PropertySchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitAdditionalPropertiesSchema(node: Oas20AdditionalPropertiesSchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitAllOfSchema(node: Oas20AllOfSchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitItemsSchema(node: Oas20ItemsSchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitDefinitions(node: Oas20Definitions): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitParametersDefinitions(node: Oas20ParametersDefinitions): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
public visitResponsesDefinitions(node: Oas20ResponsesDefinitions): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
}
/**
* Used to traverse up an OAS 3.0 tree and call an included visitor for each node.
*/
export class Oas30ReverseTraverser extends OasReverseTraverser implements IOas30NodeVisitor, IOasTraverser {
/**
* Constructor.
* @param visitor
*/
constructor(visitor: IOas30NodeVisitor) {
super(visitor);
}
visitParameter(node: Oas30Parameter): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitParameterDefinition(node: Oas30ParameterDefinition): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitResponse(node: Oas30Response): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitLink(node: Oas30Link): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitLinkParameterExpression(node: Oas30LinkParameterExpression): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitLinkRequestBodyExpression(node: Oas30LinkRequestBodyExpression): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitLinkServer(node: Oas30LinkServer): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitResponseDefinition(node: Oas30ResponseDefinition): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitRequestBody(node: Oas30RequestBody): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitMediaType(node: Oas30MediaType): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitEncoding(node: Oas30Encoding): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitExample(node: Oas30Example): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitCallback(node: Oas30Callback): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitCallbackPathItem(node: Oas30CallbackPathItem): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitAllOfSchema(node: Oas30AllOfSchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitAnyOfSchema(node: Oas30AnyOfSchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitOneOfSchema(node: Oas30OneOfSchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitNotSchema(node: Oas30NotSchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitPropertySchema(node: Oas30PropertySchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitItemsSchema(node: Oas30ItemsSchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitAdditionalPropertiesSchema(node: Oas30AdditionalPropertiesSchema): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitDiscriminator(node: Oas30Discriminator): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitComponents(node: Oas30Components): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitExampleDefinition(node: Oas30ExampleDefinition): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitRequestBodyDefinition(node: Oas30RequestBodyDefinition): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitHeaderDefinition(node: Oas30HeaderDefinition): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitOAuthFlows(node: Oas30OAuthFlows): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitImplicitOAuthFlow(node: Oas30ImplicitOAuthFlow): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitPasswordOAuthFlow(node: Oas30PasswordOAuthFlow): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitClientCredentialsOAuthFlow(node: Oas30ClientCredentialsOAuthFlow): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitAuthorizationCodeOAuthFlow(node: Oas30AuthorizationCodeOAuthFlow): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitLinkDefinition(node: Oas30LinkDefinition): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitCallbackDefinition(node: Oas30CallbackDefinition): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitSchemaDefinition(node: Oas30SchemaDefinition): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitServer(node: Oas30Server): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
visitServerVariable(node: Oas30ServerVariable): void {
node.accept(this.visitor);
this.traverse(node.parent());
}
} | the_stack |
import { BlazorDotnetObject, Component, removeClass } from '@syncfusion/ej2-base';
import { EventHandler, isNullOrUndefined } from '@syncfusion/ej2-base';
export abstract class SignatureBase extends Component<HTMLCanvasElement> {
/* Private variables */
private pointX: number;
private pointY: number;
/* time of the current point(x,y) of the corrdinates*/
private time: number;
private startPoint: Point;
private controlPoint1 : Point;
private controlPoint2 : Point;
private endPoint : Point;
private pointColl: Point[];
private canvasContext: CanvasRenderingContext2D;
private lastVelocity: number;
private lastWidth: number;
private incStep: number;
private snapColl: string[];
/* minDistance(distance between the two point) was calaculated for smoothness.*/
private minDistance: number = 5;
private previous: number = 0;
/* interval handles for the smoothness in the mouse move event.*/
private interval: number = 30;
private timeout: number | null = null;
private storedArgs: MouseEvent & TouchEvent;
private isSignatureEmpty: boolean = true;
private backgroundLoaded: boolean | null = null;
private fileType: SignatureFileType;
private fileName: string;
private clearArray: number[] = [];
private isBlazor: boolean = false;
private isResponsive: boolean = false;
private dotnetRef: BlazorDotnetObject;
/**
* Gets or sets the background color of the component.
*
*/
public backgroundColor: string;
/**
* Gets or sets the background image for the component.
*
*/
public backgroundImage: string;
/**
* Gets or sets whether to disable the signature component where the opacity is set to show disabled state.
*
*/
public disabled: boolean;
/**
* Gets or sets whether to prevent the interaction in signature component.
*
*/
public isReadOnly: boolean;
/**
* Gets or sets whether to save the signature along with Background Color and background Image while saving.
*
*/
public saveWithBackground: boolean;
/**
* Gets or sets the stroke color of the signature.
*
*/
public strokeColor: string;
/**
* Gets or sets the minimum stroke width for signature.
*
*/
public minStrokeWidth: number;
/**
* Gets or sets the maximum stroke width for signature.
*
*/
public maxStrokeWidth: number;
/**
* Gets or sets the velocity to calculate the stroke thickness based on the pressure of the contact on the digitizer surface.
*
*/
public velocity: number;
/**
* Gets or sets the last signature url to maintain the persist state.
*
*/
public signatureValue: string;
/**
* To Initialize the component rendering
*
* @private
* @param {HTMLCanvasElement} element - Specifies the canvas element.
* @param {BlazorDotnetObject} dotnetRef - Specifies for blazor client to server communication.
* @returns {void}
*/
public initialize(element: HTMLCanvasElement, dotnetRef?: BlazorDotnetObject): void {
this.element = element;
this.canvasContext = this.element.getContext('2d');
this.canvasContext.canvas.tabIndex = 0;
if (dotnetRef) {
this.dotnetRef = dotnetRef;
this.isBlazor = true;
if (this.signatureValue) {
this.loadPersistedSignature();
}
}
this.setHTMLProperties();
if (isNullOrUndefined(this.signatureValue)) {
this.updateSnapCollection(true);
}
this.wireEvents();
if (!this.isBlazor) {
this.trigger('created', null);
}
}
private wireEvents(): void {
if (isNullOrUndefined(this.pointColl) && !this.isReadOnly && !this.disabled) {
EventHandler.add(this.canvasContext.canvas, 'mousedown touchstart', this.mouseDownHandler, this);
EventHandler.add(this.canvasContext.canvas, 'keydown', this.keyboardHandler, this);
window.addEventListener('resize', this.resizeHandler.bind(this));
} else if (this.pointColl) {
EventHandler.add(this.canvasContext.canvas, 'mousemove touchmove', this.mouseMoveHandler, this);
EventHandler.add(this.canvasContext.canvas, 'mouseup touchend', this.mouseUpHandler, this);
EventHandler.add(document, 'mouseup', this.mouseUpHandler, this);
}
}
private unwireEvents(type: string): void {
if (type === 'mouseup' || type === 'touchend') {
EventHandler.remove(this.canvasContext.canvas, 'mousemove touchmove', this.mouseMoveHandler);
EventHandler.remove(this.canvasContext.canvas, 'mouseup touchend', this.mouseUpHandler);
EventHandler.remove(document, 'mouseup', this.mouseUpHandler);
} else {
EventHandler.remove(this.canvasContext.canvas, 'mousedown touchstart', this.mouseDownHandler);
EventHandler.remove(this.canvasContext.canvas, 'keydown', this.keyboardHandler);
window.removeEventListener('resize', this.resizeHandler);
}
}
private setHTMLProperties(): void {
if (this.element.height === 150 && this.element.width === 300) {
this.element.height = this.element.offsetHeight;
this.element.width = this.element.offsetWidth;
this.isResponsive = true;
}
this.canvasContext.scale(1, 1);
this.canvasContext.fillStyle = this.strokeColor;
if (this.backgroundImage) {
this.canvasContext.canvas.style.backgroundImage = 'url(' + this.backgroundImage + ')';
this.canvasContext.canvas.style.backgroundRepeat = "no-repeat";
} else if (this.backgroundColor) {
this.canvasContext.canvas.style.backgroundColor = this.backgroundColor;
}
}
private mouseDownHandler(e : MouseEvent & TouchEvent): void {
if (e.buttons === 1 || e.buttons === 2 || e.type === 'touchstart') {
if (e.type === 'touchstart') {
e.preventDefault();
e.stopPropagation();
}
this.beginStroke(e);
this.wireEvents();
}
}
private mouseMoveHandler(e: MouseEvent & TouchEvent): void {
if (e.buttons === 1 || e.buttons === 2 || e.type === 'touchmove') {
if (e.type === 'touchmove') {
e.preventDefault();
e.stopPropagation();
}
if (this.interval) {
this.updateStrokeWithThrottle(e);
} else {
this.updateStroke(e);
}
}
}
private mouseUpHandler(e: MouseEvent & TouchEvent): void {
const args: SignatureChangeEventArgs = { actionName: 'strokeUpdate'};
if (e.type === 'touchstart') {
e.preventDefault();
e.stopPropagation();
}
this.endDraw();
this.updateSnapCollection();
this.unwireEvents(e.type);
if (!this.isBlazor) {
this.trigger('change', args);
} else {
this.dotnetRef.invokeMethodAsync('TriggerEventAsync', 'mouseUp');
}
this.signatureValue = this.snapColl[this.incStep];
}
private keyboardHandler(e : KeyboardEvent): void {
const args: SignatureBeforeSaveEventArgs = {fileName: 'Signature', type: 'Png', cancel: false};
switch (e.key) {
case 'Delete':
this.clear();
break;
case (e.ctrlKey && 's'):
if (!this.isBlazor) {
this.trigger('beforeSave', args, (observableSaveArgs: SignatureBeforeSaveEventArgs) => {
if (!args.cancel) {
this.save(observableSaveArgs.type, observableSaveArgs.fileName);
}
});
} else {
this.dotnetRef.invokeMethodAsync('TriggerEventAsync', 'beforeSave');
}
e.preventDefault();
e.stopImmediatePropagation();
break;
case (e.ctrlKey && 'z'):
this.undo();
break;
case (e.ctrlKey && 'y'):
this.redo();
break;
}
}
private resizeHandler(): void {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const proxy: SignatureBase = this;
if (this.isResponsive) {
this.canvasContext.canvas.width = this.element.offsetWidth;
this.canvasContext.canvas.height = this.element.offsetHeight;
this.canvasContext.scale(1, 1);
}
const restoreImg: HTMLImageElement = new Image();
restoreImg.src = this.snapColl[this.incStep];
restoreImg.onload = () => {
proxy.canvasContext.clearRect(0, 0, proxy.element.width, proxy.element.height);
proxy.canvasContext.drawImage(restoreImg, 0, 0, proxy.element.width, proxy.element.height);
};
}
private beginStroke(e : MouseEvent & TouchEvent): void {
this.refresh();
this.updateStroke(e);
}
private updateStroke(e : MouseEvent & TouchEvent): void {
const point: Point = this.createPoint(e);
this.addPoint(point);
}
private updateStrokeWithThrottle(args: MouseEvent & TouchEvent): void {
const now: number = Date.now();
const remaining: number = this.interval - (now - this.previous);
this.storedArgs = args;
if (remaining <= 0 || remaining > this.interval) {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
this.previous = now;
this.updateStroke(this.storedArgs);
if (!this.timeout) {
this.storedArgs = null;
}
} else if (!this.timeout) {
this.timeout = window.setTimeout(this.delay.bind(this), remaining);
}
}
private delay(): void {
this.previous = Date.now();
this.timeout = null;
this.updateStroke(this.storedArgs);
if (!this.timeout) {
this.storedArgs = null;
}
}
private createPoint(e: MouseEvent & TouchEvent): Point {
const rect: DOMRect = this.canvasContext.canvas.getBoundingClientRect() as DOMRect;
if (e.type === 'mousedown' || e.type === 'mousemove') {
return this.point(e.clientX - rect.left, e.clientY - rect.top, new Date().getTime());
} else {
return this.point(e.touches[0].clientX - rect.left, e.touches[0].clientY - rect.top, new Date().getTime());
}
}
/* Returns the current point corrdinates(x, y) and time.*/
private point(pointX: number, pointY: number, time: number): Point {
this.pointX = pointX;
this.pointY = pointY;
this.time = time || new Date().getTime();
return { x: this.pointX, y: this.pointY, time: this.time };
}
private addPoint(point: Point): void {
const points: Point[] = this.pointColl; let controlPoint1: Point; let controlPoint2: Point;
const lastPoint: Point = points.length > 0 && points[points.length - 1];
const isLastPointTooClose: boolean = lastPoint ? this.distanceTo(lastPoint) <= this.minDistance : false;
if (!lastPoint || !(lastPoint && isLastPointTooClose)) {
points.push(point);
if (points.length > 2) {
if (points.length === 3) {
points.unshift(points[0]);
}
controlPoint1 = (this.calculateCurveControlPoints(points[0], points[1], points[2])).controlPoint2;
controlPoint2 = (this.calculateCurveControlPoints(points[1], points[2], points[3])).controlPoint1;
this.startPoint = points[1]; this.controlPoint1 = controlPoint1;
this.controlPoint2 = controlPoint2; this.endPoint = points[2];
this.startDraw();
points.shift();
}
}
}
private startDraw(): void {
let velocity: number;
velocity = this.pointVelocityCalc(this.startPoint);
velocity = this.velocity * velocity + (1 - this.velocity) * this.lastVelocity;
const newWidth: number = Math.max(this.maxStrokeWidth / (velocity + 1), this.minStrokeWidth);
this.curveDraw(this.lastWidth, newWidth);
this.lastVelocity = velocity;
this.lastWidth = newWidth;
}
private endDraw(): void {
const canDrawCurve: boolean = this.pointColl.length > 2; const point: Point = this.pointColl[0];
if (!canDrawCurve && point) {
this.strokeDraw(point);
}
}
/* Calculate the Bezier (x, y) coordinate of the curve. */
private curveDraw(startWidth: number, endWidth: number): void {
const context: CanvasRenderingContext2D = this.canvasContext;
let width: number; let i: number; let t1: number; let t2: number;
let t3: number; let u1: number; let u2: number; let u3: number; let x: number; let y: number;
const widthValue: number = endWidth - startWidth;
const bezierLength: number = this.bezierLengthCalc();
const drawSteps : number = Math.ceil(bezierLength) * 2;
context.beginPath();
for (i = 0; i < drawSteps; i++) {
t1 = i / drawSteps; t2 = t1 * t1; t3 = t2 * t1;
u1 = 1 - t1; u2 = u1 * u1; u3 = u2 * u1;
x = u3 * this.startPoint.x; x += 3 * u2 * t1 * this.controlPoint1.x;
x += 3 * u1 * t2 * this.controlPoint2.x; x += t3 * this.endPoint.x;
y = u3 * this.startPoint.y; y += 3 * u2 * t1 * this.controlPoint1.y;
y += 3 * u1 * t2 * this.controlPoint2.y; y += t3 * this.endPoint.y;
width = Math.min(startWidth + t3 * widthValue, this.maxStrokeWidth);
this.arcDraw(x, y, width);
}
context.closePath();
context.fill();
this.isSignatureEmpty = false;
}
private strokeDraw(point: Point): void {
const context: CanvasRenderingContext2D = this.canvasContext;
const pointSize: number = (this.minStrokeWidth + this.maxStrokeWidth) / 2;
context.beginPath();
this.arcDraw( point.x, point.y, pointSize);
context.closePath();
context.fill();
this.isSignatureEmpty = false;
}
private arcDraw(x: number, y: number, size: number): void {
const context: CanvasRenderingContext2D = this.canvasContext;
context.moveTo(x, y);
context.arc(x, y, size, 0, 2 * Math.PI, false);
}
/* Utility functions for Bezier algorithm*/
private calculateCurveControlPoints(p1: Point, p2: Point, p3: Point): {controlPoint1: Point, controlPoint2: Point} {
const dx1: number = p1.x - p2.x; const dy1: number = p1.y - p2.y;
const dx2: number = p2.x - p3.x; const dy2: number = p2.y - p3.y;
const m1: Point = { x: (p1.x + p2.x) / 2.0, y: (p1.y + p2.y) / 2.0 };
const m2: Point = { x: (p2.x + p3.x) / 2.0, y: (p2.y + p3.y) / 2.0 };
const l1: number = Math.sqrt(dx1 * dx1 + dy1 * dy1);
const l2: number = Math.sqrt(dx2 * dx2 + dy2 * dy2);
const dxm: number = (m1.x - m2.x); const dym: number = (m1.y - m2.y);
const k: number = l2 / (l1 + l2);
const cm: Point = { x: m2.x + dxm * k, y: m2.y + dym * k };
const tx: number = p2.x - cm.x; const ty: number = p2.y - cm.y;
return {
controlPoint1: this.point(m1.x + tx, m1.y + ty, 0),
controlPoint2: this.point(m2.x + tx, m2.y + ty, 0)
};
}
/* Returns approximated bezier length of the curuve.*/
private bezierLengthCalc(): number {
const steps: number = 10; let length: number = 0; let i: number; let t: number; let pointx1: number;
let pointy1: number; let pointx2: number; let pointy2: number; let pointx3: number; let pointy3: number;
for (i = 0; i <= steps; i++) {
t = i / steps;
pointx1 = this.bezierPointCalc(t, this.startPoint.x, this.controlPoint1.x, this.controlPoint2.x, this.endPoint.x);
pointy1 = this.bezierPointCalc(t, this.startPoint.y, this.controlPoint1.y, this.controlPoint2.y, this.endPoint.y);
if (i > 0) {
pointx3 = pointx1 - pointx2;
pointy3 = pointy1 - pointy2;
length += Math.sqrt(pointx3 * pointx3 + pointy3 * pointy3);
}
pointx2 = pointx1;
pointy2 = pointy1;
}
return length;
}
/* Calculate parametric value of x or y given t and the
four point(startpoint, controlpoint1, controlpoint2, endpoint) coordinates of a cubic bezier curve.*/
private bezierPointCalc(t: number, startpoint: number, cp1: number, cp2: number, endpoint: number): number {
return startpoint * (1.0 - t) * (1.0 - t) * (1.0 - t) + 3.0 * cp1 * (1.0 - t) * (1.0 - t) * t + 3.0 *
cp2 * (1.0 - t) * t * t + endpoint * t * t * t;
}
/* Velocity between the current point and last point.*/
private pointVelocityCalc(startPoint: Point): number {
return (this.time !== startPoint.time) ? this.distanceTo(startPoint) / (this.time - startPoint.time) : 0;
}
/* Distance between the current point and last point.*/
private distanceTo(start: Point): number {
return Math.sqrt(Math.pow(this.pointX - start.x, 2) + Math.pow(this.pointY - start.y, 2));
}
private isRead(isRead: boolean): void {
if (isRead) {
EventHandler.remove(this.canvasContext.canvas, 'mousedown touchstart', this.mouseDownHandler);
} else if (!this.disabled) {
EventHandler.add(this.canvasContext.canvas, 'mousedown touchstart', this.mouseDownHandler, this);
}
}
private enableOrDisable(isDisable: boolean): void {
this.disabled = isDisable;
if (isDisable) {
this.reDraw('0.5');
this.isRead(true);
} else {
this.reDraw('1');
this.isRead(false);
}
}
private reDraw(opacity?: string): void {
const data: ImageData = this.canvasContext.getImageData(0, 0, this.element.width, this.element.height);
this.canvasContext.clearRect(0, 0, this.element.width, this.element.height);
this.element.style.opacity = opacity;
this.canvasContext.putImageData(data, 0, 0);
}
private updateSnapCollection(isClear?: boolean): void {
if (isNullOrUndefined(this.incStep)) {
this.incStep = -1;
this.incStep++;
this.snapColl = [];
this.clearArray = [];
}
else {
this.incStep++;
}
if (this.incStep < this.snapColl.length) {
this.snapColl.length = this.incStep;
}
if (this.incStep > 0) {
const canvasNew: HTMLCanvasElement = this.createElement('canvas', { className: 'e-' + this.getModuleName() + '-wrapper' });
const canvasContextNew: CanvasRenderingContext2D = canvasNew.getContext('2d');
canvasNew.width = this.canvasContext.canvas.width;
canvasNew.height = this.canvasContext.canvas.height;
canvasContextNew.drawImage(this.canvasContext.canvas, 0, 0, canvasNew.width, canvasNew.height);
this.snapColl.push(canvasNew.toDataURL());
} else {
this.snapColl.push(this.canvasContext.canvas.toDataURL());
}
if (isClear) {
this.clearArray.push(this.incStep);
}
}
private setBackgroundImage(imageSrc: string): void {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const proxy: SignatureBase = this;
const imageObj: HTMLImageElement = new Image();
imageObj.crossOrigin = 'anonymous';
imageObj.src = imageSrc;
imageObj.onload = () => {
proxy.canvasContext.globalCompositeOperation = 'source-over';
proxy.canvasContext.drawImage(imageObj, 0, 0, proxy.element.width, proxy.element.height);
proxy.updateSnapCollection();
proxy.saveBackground(true);
};
this.canvasContext.clearRect( 0, 0, this.canvasContext.canvas.width, this.canvasContext.canvas.height);
}
private setBackgroundColor(color: string): void {
const canvasEle: CanvasRenderingContext2D = this.canvasContext;
canvasEle.strokeStyle = color;
let i: number; let j: number;
for ( i = 1; i <= canvasEle.canvas.width; i++) {
for ( j = 1; j <= canvasEle.canvas.height; j++) {
canvasEle.strokeRect( 0, 0, i, j);
}
}
this.updateSnapCollection();
}
protected loadPersistedSignature(): void {
if (isNullOrUndefined(this.signatureValue)) {
return;
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
const proxy: SignatureBase = this;
const lastImage: HTMLImageElement = new Image();
lastImage.src = this.signatureValue;
lastImage.onload = () => {
proxy.canvasContext.clearRect(0, 0, proxy.element.width, proxy.element.height);
proxy.canvasContext.drawImage(lastImage, 0, 0);
proxy.updateSnapCollection();
};
this.isSignatureEmpty = false;
}
/**
* To get the signature as Blob.
*
* @param {string} url - specify the url/base 64 string to get blob of the signature.
* @returns {Blob}.
*/
public getBlob(url: string): Blob {
const arr: string[] = url.split(','); const type: string = arr[0].match(/:(.*?);/)[1];
const bstr: string = atob(arr[1]); let n: number = bstr.length; const u8arr: Uint8Array = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: type });
}
private download(blob: Blob, fileName: string): void {
const blobUrl: string = URL.createObjectURL(blob);
const a: HTMLAnchorElement = document.createElement('a');
a.href = blobUrl;
a.target = '_parent';
a.download = fileName;
(document.body || document.documentElement).appendChild(a);
a.click();
a.parentNode.removeChild(a);
}
/**
* To refresh the signature.
*
* @private
* @returns {void}.
*/
public refresh(): void {
this.pointColl = [];
this.lastVelocity = 0;
this.lastWidth = (this.minStrokeWidth + this.maxStrokeWidth) / 2;
}
/**
* Erases all the signature strokes signed by user.
*
* @returns {void}.
*/
public clear(): void {
const args: SignatureChangeEventArgs = { actionName: 'clear'};
this.canvasContext.clearRect( 0, 0, this.canvasContext.canvas.width, this.canvasContext.canvas.height);
this.refresh();
this.updateSnapCollection(true);
this.isSignatureEmpty = true;
if (!this.isBlazor) {
this.trigger('change', args);
} else {
this.dotnetRef.invokeMethodAsync('TriggerEventAsync', 'Clear');
}
}
/**
* Undo the last user action.
*
* @returns {void}.
*/
public undo(): void {
const args: SignatureChangeEventArgs = { actionName: 'undo'};
// eslint-disable-next-line @typescript-eslint/no-this-alias
const proxy: SignatureBase = this;
if (this.incStep > 0) {
this.incStep--;
const undoImg: HTMLImageElement = new Image();
undoImg.src = this.snapColl[this.incStep];
undoImg.onload = () => {
proxy.canvasContext.clearRect(0, 0, proxy.element.width, proxy.element.height);
proxy.canvasContext.drawImage(undoImg, 0, 0, proxy.element.width, proxy.element.height);
};
}
this.isClear();
if (!this.isBlazor) {
this.trigger('change', args);
} else {
this.dotnetRef.invokeMethodAsync('TriggerEventAsync', 'Undo');
}
}
/**
* Redo the last user action.
*
* @returns {void}.
*/
public redo(): void {
const args: SignatureChangeEventArgs = { actionName: 'redo'};
// eslint-disable-next-line @typescript-eslint/no-this-alias
const proxy: SignatureBase = this;
if (this.incStep < this.snapColl.length - 1) {
this.incStep++;
const redoImg: HTMLImageElement = new Image();
redoImg.src = this.snapColl[this.incStep];
redoImg.onload = () => {
proxy.canvasContext.clearRect(0, 0, proxy.element.width, proxy.element.height);
proxy.canvasContext.drawImage(redoImg, 0, 0, proxy.element.width, proxy.element.height);
};
}
this.isClear();
if (!this.isBlazor) {
this.trigger('change', args);
} else {
this.dotnetRef.invokeMethodAsync('TriggerEventAsync', 'Redo');
}
}
private isClear(): void {
if (this.clearArray) {
let empty: boolean = false;
for (let i: number = 0; i < this.clearArray.length; i++) {
if (this.clearArray[i] === this.incStep) {
this.isSignatureEmpty = true;
empty = true;
}
}
if (!empty) {
this.isSignatureEmpty = false;
}
}
}
/**
* To check whether the signature is empty or not.
*
* @returns {boolean}.
*/
public isEmpty(): boolean {
return this.isSignatureEmpty;
}
/**
* To check whether the undo collection is empty or not.
*
* @returns {boolean}.
*/
public canUndo(): boolean {
return this.incStep > 0;
}
/**
* To check whether the redo collection is empty or not.
*
* @returns {boolean}.
*/
public canRedo(): boolean {
return this.incStep < this.snapColl.length - 1;
}
/**
* To draw the signature based on the given text, with the font family and font size.
*
* @param {string} text - specify text to be drawn as signature.
* @param {string} fontFamily - specify font family of a signature.
* @param {number} fontSize - specify font size of a signature.
*
* @returns {void}.
*/
public draw(text: string, fontFamily?: string, fontSize?: number): void {
this.canvasContext.clearRect(0, 0, this.canvasContext.canvas.width, this.canvasContext.canvas.height);
fontFamily = fontFamily || 'Arial';
fontSize = fontSize || 30;
this.canvasContext.font = fontSize + 'px ' + fontFamily;
this.canvasContext.textAlign = 'center';
this.canvasContext.textBaseline = 'middle';
this.canvasContext.fillText(text, this.element.width / 2, this.element.height / 2);
this.updateSnapCollection();
this.isSignatureEmpty = false;
}
/**
* To load the signature with the given base 64 string, height and width.
*
* @param {string} signature - specify the url/base 64 string to be drawn as signature.
* @param {number} width - specify the width of the loaded signature image.
* @param {number} height - specify the height of the loaded signature image.
* @returns {void}.
*/
public load(signature: string, width?: number, height?: number): void {
height = height || this.element.height;
width = width || this.element.width;
this.canvasContext.clearRect(0, 0, this.canvasContext.canvas.width, this.canvasContext.canvas.height);
// eslint-disable-next-line @typescript-eslint/no-this-alias
const proxy: SignatureBase = this;
const bitmapImage: HTMLImageElement = new Image();
bitmapImage.src = signature;
if (signature.slice(0,4) !== 'data') {
bitmapImage.crossOrigin = 'anonymous';
}
bitmapImage.onload = () => {
Promise.all([
createImageBitmap(bitmapImage, 0, 0, width, height)
]).then((results: ImageBitmap[]) => {
const tempCanvas: HTMLCanvasElement = document.createElement('canvas');
tempCanvas.width = width;
tempCanvas.height = height;
tempCanvas.getContext('2d').drawImage(results[0], 0, 0);
if (signature.slice(0,4) !== 'data') {
proxy.canvasContext.globalCompositeOperation = 'source-over';
}
proxy.canvasContext.drawImage(tempCanvas, 0, 0, width, height, 0, 0, proxy.element.width, proxy.element.height);
proxy.updateSnapCollection();
});
};
this.isSignatureEmpty = false;
}
private saveBackground(savebg: boolean): void {
let imageSrc: string;
if (savebg && this.backgroundImage) {
imageSrc = this.snapColl[this.incStep - 1];
} else {
imageSrc = this.snapColl[this.incStep];
}
if (!savebg) {
this.canvasContext.clearRect( 0, 0, this.canvasContext.canvas.width, this.canvasContext.canvas.height);
if (this.backgroundImage) {
this.setBackgroundImage(this.backgroundImage);
} else if (this.backgroundColor) {
this.setBackgroundColor(this.backgroundColor);
savebg = true;
}
}
if (savebg) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const proxy: SignatureBase = this;
const imageObj: HTMLImageElement = new Image();
imageObj.crossOrigin = 'anonymous';
imageObj.src = imageSrc;
imageObj.onload = () => {
proxy.backgroundLoaded = true;
proxy.canvasContext.globalCompositeOperation = 'source-over';
proxy.canvasContext.drawImage(imageObj, 0, 0, proxy.element.width, proxy.element.height);
proxy.save(proxy.fileType, proxy.fileName);
};
}
}
/**
* To save the signature with the given file type and file name.
*
* @param {SignatureFileType} type - specify type of the file to be saved a signature.
* @param {string} fileName - specify name of the file to be saved a signature.
*
* @returns {void}.
*/
public save(type?: SignatureFileType, fileName?: string): void {
if (this.saveWithBackground && this.backgroundLoaded == null && (this.backgroundImage || this.backgroundColor)) {
this.backgroundLoaded = false;
this.fileType = type; this.fileName = fileName;
this.saveBackground(false);
} else if (type === 'Svg') {
fileName = fileName || 'Signature';
this.toSVG(fileName);
} else if (type === 'Jpeg') {
fileName = fileName || 'Signature';
if (!this.saveWithBackground || this.saveWithBackground && !(this.backgroundImage || this.backgroundColor)) {
this.toJPEG(fileName);
} else {
const dataURL: string = this.canvasContext.canvas.toDataURL('image/jpeg');
this.download(this.getBlob(dataURL), fileName + '.' + 'jpeg');
}
} else {
fileName = fileName || 'Signature';
const dataURL: string = this.canvasContext.canvas.toDataURL('image/png');
this.download(this.getBlob(dataURL), fileName + '.' + 'png');
}
if (this.saveWithBackground && this.backgroundLoaded) {
this.resetSnap();
}
}
private resetSnap(): void {
this.canvasContext.clearRect( 0, 0, this.canvasContext.canvas.width, this.canvasContext.canvas.height);
// eslint-disable-next-line @typescript-eslint/no-this-alias
const proxy: SignatureBase = this;
const restoreObj: HTMLImageElement = new Image();
restoreObj.src = this.snapColl[this.incStep - 1];
restoreObj.onload = () => {
proxy.canvasContext.drawImage(restoreObj, 0, 0, proxy.element.width, proxy.element.height);
proxy.updateSnapCollection();
};
this.backgroundLoaded = null;
this.snapColl.pop(); this.incStep--;
this.snapColl.pop(); this.incStep--;
}
private toJPEG(fileName: string): void {
const imageSrc: string = this.snapColl[this.incStep];
this.setBackgroundColor('#ffffff');
// eslint-disable-next-line @typescript-eslint/no-this-alias
const proxy: SignatureBase = this;
const imageObj: HTMLImageElement = new Image();
imageObj.crossOrigin = 'anonymous';
imageObj.src = imageSrc;
imageObj.onload = () => {
proxy.canvasContext.globalCompositeOperation = 'source-over';
proxy.canvasContext.drawImage(imageObj, 0, 0, proxy.element.width, proxy.element.height);
const dataURL: string = proxy.canvasContext.canvas.toDataURL('image/jpeg');
proxy.download(proxy.getBlob(dataURL), fileName + '.' + 'jpeg');
proxy.canvasContext.clearRect( 0, 0, proxy.canvasContext.canvas.width, proxy.canvasContext.canvas.height);
this.resizeHandler();
};
this.snapColl.pop();
this.incStep--;
}
private toSVG(fileName?: string): string {
const dataUrl: string = this.canvasContext.canvas.toDataURL();
const svg: SVGSVGElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', this.canvasContext.canvas.width.toString());
svg.setAttribute('height', this.canvasContext.canvas.height.toString());
const XLinkNS: string = 'http://www.w3.org/1999/xlink';
const img: SVGImageElement = document.createElementNS('http://www.w3.org/2000/svg', 'image');
img.setAttributeNS(null, 'height', this.canvasContext.canvas.height.toString());
img.setAttributeNS(null, 'width', this.canvasContext.canvas.width.toString());
img.setAttributeNS(XLinkNS, 'xlink:href', dataUrl);
svg.appendChild(img);
const prefix: string = 'data:image/svg+xml;base64,';
const header: string = '<svg' + ' xmlns="http://www.w3.org/2000/svg"' + ' xmlns:xlink="http://www.w3.org/1999/xlink"'
+ ` width="${this.canvasContext.canvas.width}"` + ` height="${this.canvasContext.canvas.height}"` + '>';
const footer: string = '</svg>';
const body: string = svg.innerHTML;
const data: string = header + body + footer;
const svgDataUrl: string = prefix + btoa(data);
if (fileName == null) {
return svgDataUrl;
} else {
this.download(this.getBlob(svgDataUrl), fileName + '.' + 'svg');
return null;
}
}
/**
* To save the signature as Blob.
*
* @returns {Blob}.
*/
public saveAsBlob(): Blob {
return this.getBlob(this.canvasContext.canvas.toDataURL('image/png'));
}
/**
* To get the signature as Base 64.
*
* @private
* @param {SignatureFileType} type - Specifies the type of the image format.
* @returns {string}.
*/
public getSignature(type?: SignatureFileType): string {
if (type === 'Jpeg') {
const imgData: ImageData = this.canvasContext.getImageData(0, 0, this.element.width, this.element.height);
const data: Uint8ClampedArray = imgData.data;
for (let i: number = 0; i < data.length; i += 4) {
if (data[i + 3] < 255) {
data[i] = 255 - data[i];
data[i + 1] = 255 - data[i + 1];
data[i + 2] = 255 - data[i + 2];
data[i + 3] = 255 - data[i + 3];
}
}
this.canvasContext.putImageData(imgData, 0, 0);
const dataURL: string = this.canvasContext.canvas.toDataURL('image/jpeg');
this.resizeHandler();
return dataURL;
} else if (type === 'Svg') {
return this.toSVG(null);
} else {
return this.canvasContext.canvas.toDataURL('image/png');
}
}
/**
* Get component name.
*
* @returns {string} - Module Name
* @private
*/
protected getModuleName(): string {
return 'signature';
}
/**
* To get the properties to be maintained in the persisted state.
*
* @returns {string} - Persist data
*/
protected getPersistData(): string {
this.signatureValue = this.snapColl[this.incStep];
return this.addOnPersist(['signatureValue']);
}
/**
* Removes the component from the DOM and detaches all its related event handlers.
* Also it maintains the initial input element from the DOM.
*
* @method destroy
* @returns {void}
*/
public destroy(): void {
this.unwireEvents(null);
removeClass([this.element], 'e-' + this.getModuleName());
this.element.removeAttribute('tabindex');
this.pointColl = null;
super.destroy();
}
/**
* Modified onPropertyChanged method for both blazor and EJ2 signature component.
*
* @private
* @param {string} key - Specifies the property, which changed.
* @param {string} value - Specifies the property value changed.
* @returns {void}
*/
public propertyChanged(key: string, value: string | boolean | number): void {
const canvasNew: CanvasRenderingContext2D = this.canvasContext;
switch (key) {
case 'backgroundColor':
canvasNew.canvas.style.backgroundColor = value as string;
this.backgroundColor = value as string;
break;
case 'backgroundImage':
canvasNew.canvas.style.backgroundImage = 'url(' + value + ')';
this.backgroundImage = value as string;
break;
case 'strokeColor':
canvasNew.fillStyle = value as string;
this.strokeColor = value as string;
break;
case 'saveWithBackground':
this.saveWithBackground = value as boolean;
break;
case 'maxStrokeWidth':
this.maxStrokeWidth = value as number;
break;
case 'minStrokeWidth':
this.minStrokeWidth = value as number;
break;
case 'velocity':
this.velocity = value as number;
break;
case 'isReadOnly':
this.isRead(value as boolean);
break;
case 'disabled':
this.enableOrDisable(value as boolean);
break;
}
}
}
/**
* Interface for Point object.
*/
interface Point {
/**
* Gets or sets the x position of the point.
*/
x: number;
/**
* Gets or sets the y position of the point.
*/
y: number;
/**
* Gets or sets the time.
*/
time?: number;
}
/**
* Defines the signature file type.
*/
export type SignatureFileType = 'Png' | 'Jpeg' | 'Svg' ;
/**
* Interface for before save the canvas as image.
*/
export interface SignatureBeforeSaveEventArgs {
/**
* Gets or sets whether to cancel the save action. You can cancel and perform save operation programmatically.
*/
cancel?: boolean;
/**
* Gets or sets the file name to be saved.
*/
fileName?: string;
/**
* Gets or sets the file type to be saved.
*/
type?: SignatureFileType;
}
/**
* Interface for changes occur in the signature.
*/
export interface SignatureChangeEventArgs {
/**
* Gets or sets the action name of the signature.
*/
actionName: string;
} | the_stack |
export const enum Delta {
/** No changes */
Unmodified = 0,
/** Entry does not exist in old version */
Added = 1,
/** Entry does not exist in new version */
Deleted = 2,
/** Entry content changed between old and new */
Modified = 3,
/** Entry was renamed between old and new */
Renamed = 4,
/** Entry was copied from another old entry */
Copied = 5,
/** Entry is ignored item in workdir */
Ignored = 6,
/** Entry is untracked item in workdir */
Untracked = 7,
/** Type of entry changed between old and new */
Typechange = 8,
/** Entry is unreadable */
Unreadable = 9,
/** Entry in the index is conflicted */
Conflicted = 10
}
export interface DiffOptions {
/**
* When generating output, include the names of unmodified files if they
* are included in the `Diff`. Normally these are skipped in the formats
* that list files (e.g. name-only, name-status, raw). Even with this these
* will not be included in the patch format.
*/
showUnmodified?: boolean
}
/** An enumeration of all possible kinds of references. */
export const enum ReferenceType {
/** A reference which points at an object id. */
Direct = 0,
/** A reference which points at another reference. */
Symbolic = 1,
Unknown = 2
}
/** An enumeration of the possible directions for a remote. */
export const enum Direction {
/** Data will be fetched (read) from this remote. */
Fetch = 0,
/** Data will be pushed (written) to this remote. */
Push = 1
}
export interface Progress {
totalObjects: number
indexedObjects: number
receivedObjects: number
localObjects: number
totalDeltas: number
indexedDeltas: number
receivedBytes: number
}
export const enum RepositoryState {
Clean = 0,
Merge = 1,
Revert = 2,
RevertSequence = 3,
CherryPick = 4,
CherryPickSequence = 5,
Bisect = 6,
Rebase = 7,
RebaseInteractive = 8,
RebaseMerge = 9,
ApplyMailbox = 10,
ApplyMailboxOrRebase = 11
}
export const enum RepositoryOpenFlags {
/** Only open the specified path; don't walk upward searching. */
NoSearch = 0,
/** Search across filesystem boundaries. */
CrossFS = 1,
/** Force opening as bare repository, and defer loading its config. */
Bare = 2,
/** Don't try appending `/.git` to the specified repository path. */
NoDotGit = 3,
/** Respect environment variables like `$GIT_DIR`. */
FromEnv = 4
}
/** An iterator over the diffs in a delta */
export class Deltas {
[Symbol.iterator](): Iterator<DiffDelta, void, void>
}
export class DiffDelta {
/** Returns the number of files in this delta. */
numFiles(): number
/** Returns the status of this entry */
status(): Delta
/**
* Return the file which represents the "from" side of the diff.
*
* What side this means depends on the function that was used to generate
* the diff and will be documented on the function itself.
*/
oldFile(): DiffFile
/**
* Return the file which represents the "to" side of the diff.
*
* What side this means depends on the function that was used to generate
* the diff and will be documented on the function itself.
*/
newFile(): DiffFile
}
export class DiffFile {
/**
* Returns the path, in bytes, of the entry relative to the working
* directory of the repository.
*/
path(): string | null
}
export class Diff {
/**
* Merge one diff into another.
*
* This merges items from the "from" list into the "self" list. The
* resulting diff will have all items that appear in either list.
* If an item appears in both lists, then it will be "merged" to appear
* as if the old version was from the "onto" list and the new version
* is from the "from" list (with the exception that if the item has a
* pending DELETE in the middle, then it will show as deleted).
*/
merge(diff: Diff): void
/** Returns an iterator over the deltas in this diff. */
deltas(): Deltas
/** Check if deltas are sorted case sensitively or insensitively. */
isSortedIcase(): boolean
}
export class Reference {
/**
* Ensure the reference name is well-formed.
*
* Validation is performed as if [`ReferenceFormat::ALLOW_ONELEVEL`]
* was given to [`Reference.normalize_name`]. No normalization is
* performed, however.
*
* ```ts
* import { Reference } from '@napi-rs/simple-git'
*
* console.assert(Reference.is_valid_name("HEAD"));
* console.assert(Reference.is_valid_name("refs/heads/main"));
*
* // But:
* console.assert(!Reference.is_valid_name("main"));
* console.assert(!Reference.is_valid_name("refs/heads/*"));
* console.assert(!Reference.is_valid_name("foo//bar"));
* ```
*/
static isValidName(name: string): boolean
/** Check if a reference is a local branch. */
isBranch(): boolean
/** Check if a reference is a note. */
isNote(): boolean
/** Check if a reference is a remote tracking branch */
isRemote(): boolean
/** Check if a reference is a tag */
isTag(): boolean
kind(): ReferenceType
/**
* Get the full name of a reference.
*
* Returns `None` if the name is not valid utf-8.
*/
name(): string | null
/**
* Get the full shorthand of a reference.
*
* This will transform the reference name into a name "human-readable"
* version. If no shortname is appropriate, it will return the full name.
*
* Returns `None` if the shorthand is not valid utf-8.
*/
shorthand(): string | null
/**
* Get the OID pointed to by a direct reference.
*
* Only available if the reference is direct (i.e. an object id reference,
* not a symbolic one).
*/
target(): string | null
/**
* Return the peeled OID target of this reference.
*
* This peeled OID only applies to direct references that point to a hard
* Tag object: it is the result of peeling such Tag.
*/
targetPeel(): string | null
/**
* Peel a reference to a tree
*
* This method recursively peels the reference until it reaches
* a tree.
*/
peelToTree(): Tree
/**
* Get full name to the reference pointed to by a symbolic reference.
*
* May return `None` if the reference is either not symbolic or not a
* valid utf-8 string.
*/
symbolicTarget(): string | null
/**
* Resolve a symbolic reference to a direct reference.
*
* This method iteratively peels a symbolic reference until it resolves to
* a direct reference to an OID.
*
* If a direct reference is passed as an argument, a copy of that
* reference is returned.
*/
resolve(): Reference
/**
* Rename an existing reference.
*
* This method works for both direct and symbolic references.
*
* If the force flag is not enabled, and there's already a reference with
* the given name, the renaming will fail.
*/
rename(newName: string, force: boolean, msg: string): Reference
}
export class Remote {
/** Ensure the remote name is well-formed. */
static isValidName(name: string): boolean
/**
* Get the remote's name.
*
* Returns `None` if this remote has not yet been named or if the name is
* not valid utf-8
*/
name(): string | null
/**
* Get the remote's url.
*
* Returns `None` if the url is not valid utf-8
*/
url(): string | null
/**
* Get the remote's pushurl.
*
* Returns `None` if the pushurl is not valid utf-8
*/
pushurl(): string | null
/**
* Get the remote's default branch.
*
* The remote (or more exactly its transport) must have connected to the
* remote repository. This default branch is available as soon as the
* connection to the remote is initiated and it remains available after
* disconnecting.
*/
defaultBranch(): string
/** Open a connection to a remote. */
connect(dir: Direction): void
/** Check whether the remote is connected */
connected(): boolean
/** Disconnect from the remote */
disconnect(): void
/**
* Cancel the operation
*
* At certain points in its operation, the network code checks whether the
* operation has been cancelled and if so stops the operation.
*/
stop(): void
fetch(refspecs: string[], cb?: (progress: Progress) => void): void
}
export class RemoteCallbacks {
constructor()
transferProgress(callback: (...args: any[]) => any): void
pushTransferProgress(callback: (a: number, b: number, c: number) => void): void
}
export class FetchOptions {
constructor()
remoteCallback(callback: RemoteCallbacks): void
}
export class Repository {
static init(p: string): Repository
/**
* Find and open an existing repository, with additional options.
*
* If flags contains REPOSITORY_OPEN_NO_SEARCH, the path must point
* directly to a repository; otherwise, this may point to a subdirectory
* of a repository, and `open_ext` will search up through parent
* directories.
*
* If flags contains REPOSITORY_OPEN_CROSS_FS, the search through parent
* directories will not cross a filesystem boundary (detected when the
* stat st_dev field changes).
*
* If flags contains REPOSITORY_OPEN_BARE, force opening the repository as
* bare even if it isn't, ignoring any working directory, and defer
* loading the repository configuration for performance.
*
* If flags contains REPOSITORY_OPEN_NO_DOTGIT, don't try appending
* `/.git` to `path`.
*
* If flags contains REPOSITORY_OPEN_FROM_ENV, `open_ext` will ignore
* other flags and `ceiling_dirs`, and respect the same environment
* variables git does. Note, however, that `path` overrides `$GIT_DIR`; to
* respect `$GIT_DIR` as well, use `open_from_env`.
*
* ceiling_dirs specifies a list of paths that the search through parent
* directories will stop before entering. Use the functions in std::env
* to construct or manipulate such a path list.
*/
static openExt(path: string, flags: RepositoryOpenFlags, ceilingDirs: Array<string>): Repository
/**
* Attempt to open an already-existing repository at or above `path`
*
* This starts at `path` and looks up the filesystem hierarchy
* until it finds a repository.
*/
static discover(path: string): Repository
constructor(gitDir: string)
/** Retrieve and resolve the reference pointed at by HEAD. */
head(): Reference
isShallow(): boolean
isEmpty(): boolean
isWorktree(): boolean
/**
* Returns the path to the `.git` folder for normal repositories or the
* repository itself for bare repositories.
*/
path(): string
/** Returns the current state of this repository */
state(): RepositoryState
/**
* Get the path of the working directory for this repository.
*
* If this repository is bare, then `None` is returned.
*/
workdir(): string | null
/**
* Set the path to the working directory for this repository.
*
* If `update_link` is true, create/update the gitlink file in the workdir
* and set config "core.worktree" (if workdir is not the parent of the .git
* directory).
*/
setWorkdir(path: string, updateGitlink: boolean): void
/**
* Get the currently active namespace for this repository.
*
* If there is no namespace, or the namespace is not a valid utf8 string,
* `None` is returned.
*/
namespace(): string | null
/** Set the active namespace for this repository. */
setNamespace(namespace: string): void
/** Remove the active namespace for this repository. */
removeNamespace(): void
/**
* Retrieves the Git merge message.
* Remember to remove the message when finished.
*/
message(): string
/** Remove the Git merge message. */
removeMessage(): void
/** List all remotes for a given repository */
remotes(): Array<string>
/** Get the information for a particular remote */
remote(name: string): Remote
/** Lookup a reference to one of the objects in a repository. */
findTree(oid: string): Tree
/**
* Create a diff between a tree and the working directory.
*
* The tree you provide will be used for the "old_file" side of the delta,
* and the working directory will be used for the "new_file" side.
*
* This is not the same as `git diff <treeish>` or `git diff-index
* <treeish>`. Those commands use information from the index, whereas this
* function strictly returns the differences between the tree and the files
* in the working directory, regardless of the state of the index. Use
* `tree_to_workdir_with_index` to emulate those commands.
*
* To see difference between this and `tree_to_workdir_with_index`,
* consider the example of a staged file deletion where the file has then
* been put back into the working dir and further modified. The
* tree-to-workdir diff for that file is 'modified', but `git diff` would
* show status 'deleted' since there is a staged delete.
*
* If `None` is passed for `tree`, then an empty tree is used.
*/
diffTreeToWorkdir(oldTree?: Tree | undefined | null): Diff
/**
* Create a diff between a tree and the working directory using index data
* to account for staged deletes, tracked files, etc.
*
* This emulates `git diff <tree>` by diffing the tree to the index and
* the index to the working directory and blending the results into a
* single diff that includes staged deleted, etc.
*/
diffTreeToWorkdirWithIndex(oldTree?: Tree | undefined | null): Diff
getFileLatestModifiedDate(filepath: string): number
getFileLatestModifiedDateAsync(filepath: string, signal?: AbortSignal | undefined | null): Promise<number>
}
export class Tree {
/** Get the id (SHA1) of a repository object */
id(): string
} | the_stack |
import 'vs/css!./media/viewlet';
import { localize } from 'vs/nls';
import { Registry } from 'vs/platform/platform';
import { Viewlet, ViewletRegistry, Extensions as ViewletExtensions, ViewletDescriptor } from 'vs/workbench/browser/viewlet';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { TPromise } from 'vs/base/common/winjs.base';
import { Dimension, Builder, $ } from 'vs/base/browser/builder';
import * as dom from 'vs/base/browser/dom';
import { Package, PackageDb } from 'vs/rw/rpm/browser/db';
import { TerminalAction } from 'vs/rw/rpm/browser/actions';
import { ExtensionCommandService } from 'vs/rw/rpm/browser/command';
import { CommandService } from 'vs/platform/commands/common/commandService';
import { IMessageService } from 'vs/platform/message/common/message';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
import { ScrollableElementResolvedOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions';
import { ScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import electron = require('electron');
import cp = require('child_process');
import path = require('path');
import * as logging from 'vs/rw/logging';
import conf from 'vs/rw/config';
export function laterEv(f: (e: any) => void): (e: any) => void {
var td: any = null;
return function (e: any): void {
clearTimeout(td);
td = setTimeout(() => f(e), 600);
};
}
function escape(str) {
return str.replace(/\</g, '<');
}
function renderPackageList(pkgs: Array<Package>) {
var items = [];
for (var pkg of pkgs) {
var item =
// <img src="http://nodejs.cn/static/images/logo.svg" width="40px" height="40px" alt="img" />
`<li class="viewlet-rpm-item" data-homepage="${pkg.homepage}" data-name="${pkg.name}" data-id="${pkg.id}">
<div class="viewlet-rpm-content">
<h3>${escape(pkg.name)}</h3>
<p>${escape(pkg.description)}</p>
<div class="viewlet-rpm-menu">
<button class="viewlet-rpm-install install" data-pkgname="${pkg.name}">INSTALL</button>
<span class="viewlet-rpm-desc">${escape(pkg.version)}</span>
<span class="viewlet-rpm-desc">${escape(pkg.status)}</span>
</div>
</div>
</li>`;
items.push(item);
}
return `<ul class="viewlet-rpm-list">${items.join('')}</ul>`;
}
export class RPMViewlet extends Viewlet {
private static MODULE_ID = 'vs/rw/rpm/browser/viewlet';
private static CONSTRUTOR = 'RPMViewlet';
private static ID = 'roboware.rpm.viewlet';
private static LABEL = localize('rpm', "ROS Packages Manager");
private static CSS_CLASS = 'rpm';
private static ORDER = 50;
public static registry() {
Registry
.as<ViewletRegistry>(ViewletExtensions.Viewlets)
.registerViewlet(
new ViewletDescriptor(
RPMViewlet.MODULE_ID,
RPMViewlet.CONSTRUTOR,
RPMViewlet.ID,
RPMViewlet.LABEL,
RPMViewlet.CSS_CLASS,
RPMViewlet.ORDER));
}
private db: PackageDb;
private root: Builder;
private disposables: IDisposable[];
private partition: number;
private terminalAction: TerminalAction;
private extensionCommand: CommandService;
private working: boolean;
private timer: any;
private syncLock: boolean;
private pkgs: Array<Package>;
private currPkgname: string;
private meta: boolean;
private scrollableElement: ScrollableElement;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IThemeService themeService: IThemeService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IStorageService storageService: IStorageService,
@IEditorGroupService private editorGroupService: IEditorGroupService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@IConfigurationService private configurationService: IConfigurationService,
@IInstantiationService private instantiationService: IInstantiationService,
@IMessageService private messageService: IMessageService
) {
super(RPMViewlet.ID, telemetryService, themeService);
this.db = new PackageDb(path.join(conf.rpm.home, conf.rosDistro + '.json'));
this.disposables = [];
this.partition = 1;
this.terminalAction = TerminalAction.createInstance(instantiationService);
this.extensionCommand = ExtensionCommandService.createInstance();
this.working = false;
this.timer = null;
this.syncLock = false;
this.pkgs = null;
this.currPkgname = '';
this.meta = true;
}
public dispose(): void {
this.disposables = dispose(this.disposables);
super.dispose();
}
public create(parent: Builder): TPromise<void> {
super.create(parent);
this.root = parent;
var children = $(
`<div class="viewlet-rpm">
<div class="viewlet-rpm-box">
<div class="viewlet-rpm-header">
<select class="viewlet-rpm-select monaco-workbench">
<option value="meta">metapackages</option>
<option value="all">packages</option>
</select>
<div class="viewlet-rpm-input-wrapper">
<input type="text" class="viewlet-rpm-input" />
</div>
</div>
<ul class="viewlet-rpm-list">
</ul>
</div>
</div>`);
this.scrollableElement = new ScrollableElement(children.getHTMLElement(), {
canUseTranslate3d: true,
alwaysConsumeMouseWheel: true,
horizontal: ScrollbarVisibility.Hidden,
vertical: ScrollbarVisibility.Auto,
useShadows: true
} as ScrollableElementResolvedOptions);
this.scrollableElement.onScroll((e) => {
var scrollTop = e.scrollTop;
var box = (document.querySelector('.viewlet-rpm .viewlet-rpm-box')) as HTMLElement;
box.style.top = -scrollTop + 'px';
});
parent.addClass('viewlet-rpm-wrapper');
parent.append(this.scrollableElement.getDomNode());
parent.on('click', (e: Event, bd: Builder, unbind: IDisposable) => {
var target = e.target as HTMLElement;
if (dom.hasClass(target, 'viewlet-rpm-install')) {
this.onInstall(target as HTMLButtonElement);
return;
}
var li = dom.findParentWithClass(target, 'viewlet-rpm-item');
if (li) {
this.onHomepage(li as HTMLLIElement);
return;
}
});
var onInput = laterEv(this.onInput.bind(this));
parent.on('input', (e: Event, bd: Builder, unbind: IDisposable) => {
var target = e.target as HTMLElement;
if (dom.hasClass(target, 'viewlet-rpm-input')) {
onInput(target as HTMLInputElement);
}
});
parent.on('change', (e: Event, bd: Builder, unbind: IDisposable) => {
var target = e.target as HTMLElement;
if (dom.hasClass(target, 'viewlet-rpm-select')) {
this.onChange(target as HTMLSelectElement);
}
});
return this.renderPackageList();
}
private sync(time: number) {
if (this.working && !this.syncLock) {
clearTimeout(this.timer);
this.syncLock = true;
this.timer = setTimeout(() => {
cp.exec(`rospack list-names`, (err, stdout: string, stderr: string) => {
cp.exec(`rosstack list-names`, (err2, stdout2: string, stderr2: string) => {
this.syncLock = false;
if (!err && this.working && !err2) {
var names = stdout.split('\n');
var names2 = stdout2.split('\n');
var items = document.querySelectorAll('.viewlet-rpm-item');
for (var i = 0, len = items.length; i < len; i++) {
var item = $(items[i] as HTMLElement);
var name = item.attr('data-name');
var btn = items[i].querySelector('.viewlet-rpm-install');
li: {
for (var j = 0, l = names.length; j < l; j++) {
if (name === names[j]) {
btn.innerHTML = 'UNINSTALL';
dom.removeClass(btn as HTMLElement, 'install');
dom.addClass(btn as HTMLElement, 'uninstall');
break li;
}
}
for (var j = 0, l = names2.length; j < l; j++) {
if (name === names2[j]) {
btn.innerHTML = 'UNINSTALL';
dom.removeClass(btn as HTMLElement, 'install');
dom.addClass(btn as HTMLElement, 'uninstall');
break li;
}
}
btn.innerHTML = 'INSTALL';
dom.removeClass(btn as HTMLElement, 'uninstall');
dom.addClass(btn as HTMLElement, 'install');
}
}
for (var i = 0, len = this.pkgs.length; i < len; i++) {
li: {
for (var j = 0, length = names.length; j < length; j++) {
if (this.pkgs[i].name === names[j]) {
this.pkgs[i].isInstalled = true;
break li;
}
}
for (var j = 0, length = names2.length; j < length; j++) {
if (this.pkgs[i].name === names2[j]) {
this.pkgs[i].isInstalled = true;
break li;
}
}
this.pkgs[i].isInstalled = false;
}
}
}
this.sync(1 * 1000);
});
});
}, time);
}
}
private onChange(select: HTMLSelectElement) {
this.meta = select.value === 'meta';
this.renderPackageList(this.currPkgname);
}
private onInstall(button: HTMLButtonElement) {
var pkgname = button.getAttribute('data-pkgname');
var install = dom.hasClass(button, 'install') ? 'install' : 'remove';
this.terminalAction
.run(`sudo apt-get ${install} ros-${conf.rosDistro}-${pkgname.replace(/\_/g, '-')}`)
.then((args) => {
electron.ipcRenderer.send('count-rpm-package', JSON.stringify({
distro: conf.rosDistro,
name: pkgname,
date: new Date(),
action: install
}));
}, (err) => {
logging.error(err.message);
});
}
private onInput(input: HTMLInputElement) {
this.currPkgname = input.value;
this.renderPackageList(input.value);
}
private onHomepage(li: HTMLLIElement) {
var items = this.root.select('.viewlet-rpm-item');
for (var i = 0, len = items.length; i < len; i++) {
items.item(i).removeClass('gray');
}
$(li).addClass('gray');
this.extensionCommand
.executeCommand('extension.view.rpmweb', $(li).attr('data-homepage'))
.then((args) => {
//console.log('extension command .')
}, (err) => {
logging.error(err.message);
});
}
private renderPackageList(pkgname = ''): TPromise<void> {
var parent = this.root;
if (this.pkgs === null) {
return this.db
.getPackagesByLikename(this.partition, conf.rosDistro, pkgname)
.then((pkgs: Array<Package>) => {
this.working = true;
this.pkgs = pkgs;
if (this.meta) {
parent.select('.viewlet-rpm-list').innerHtml(renderPackageList(this.pkgs.filter((pkg) => {
return pkg.isMetaPackage;
})));
} else {
parent.select('.viewlet-rpm-list').innerHtml(renderPackageList(this.pkgs));
}
}, (err) => logging.error(err.message));
} else {
if (this.meta) {
parent.select('.viewlet-rpm-list').innerHtml(renderPackageList(this.pkgs.filter((pkg) => {
return pkg.isMetaPackage && pkg.name.search(pkgname) > -1;
})));
} else {
parent.select('.viewlet-rpm-list').innerHtml(renderPackageList(this.pkgs.filter((pkg) => {
return pkg.name.search(pkgname) > -1;
})));
}
return TPromise.as(null);
}
}
public setVisible(visible: boolean): TPromise<void> {
if (!visible) {
this.working = false;
}
this.sync(0);
return TPromise.as(null);
}
public layout(dimension: Dimension): void {
this.scrollableElement.updateState({
height: dom.getContentHeight(this.root.getHTMLElement()),//dimension.height || dom.getContentHeight(this._domNode)
scrollHeight: document.querySelector('.viewlet-rpm .viewlet-rpm-box').scrollHeight
});
}
} | the_stack |
import 'd3-transition';
import {
rgb as d3_rgb,
} from 'd3-color';
import {
HierarchyPointNode as d3_HierarchyPointNode,
TreeLayout as d3_TreeLayout,
tree as d3_tree,
hierarchy as d3_hierarchy,
} from 'd3-hierarchy';
import {
BaseType as d3_BaseType,
Selection as d3_Selection,
select as d3_select,
event as d3_event,
mouse as d3_mouse,
} from 'd3-selection';
import {
zoom as d3_zoom,
zoomIdentity as d3_zoomIdentity,
} from 'd3-zoom';
import * as fs from 'file-saver';
import {wrap, diagonal} from '@noworkflow/utils';
import {TrialConfig} from './config';
import {VisibleTrialNode, VisibleTrialEdge} from './structures';
import {
TrialGraphData, TrialNodeData,
TrialEdgeData
} from './structures';
export
class TrialGraph {
i: number;
config: TrialConfig;
transform: any;
div: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>;
svg: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>;
g: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>;
zoom: any;
tooltipDiv: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>;
tree: d3_TreeLayout<{}>;
root: VisibleTrialNode;
graphId: string;
nodes: d3_HierarchyPointNode<{}>[];
alledges: TrialEdgeData[];
t1: number;
t2: number;
minDuration: { [trial: string]: number };
maxDuration: { [trial: string]: number };
totalDuration: { [trial: string]: number };
maxTotalDuration: number;
colors: { [trial: string]: number };
constructor(graphId:string, div: any, config: any={}) {
this.i = 0;
let defaultConfig: TrialConfig = {
customSize: function(g:TrialGraph) {
return [
g.config.width,
g.config.height,
]
},
customMouseOver: (g:TrialGraph, d: VisibleTrialNode, name: string) => false,
customMouseOut: (g:TrialGraph, d: VisibleTrialNode) => false,
customForm: (g: TrialGraph, form: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>) => null,
duration: 750,
top: 50,
right: 30,
bottom: 80,
left: 30,
width: 900,
height: 500,
useTooltip: false,
fontSize: 10,
labelFontSize: 10,
nodeSizeX: 47,
nodeSizeY: 100,
};
this.config = (Object as any).assign({}, defaultConfig, config);
this.graphId = graphId;
this.zoom = d3_zoom()
.on("zoom", () => this.zoomFunction())
.on("start", () => d3_select('body').style("cursor", "move"))
.on("end", () => d3_select('body').style("cursor", "auto"))
.wheelDelta(() => {
return -d3_event.deltaY * (d3_event.deltaMode ? 120 : 1) / 2000;
})
this.div = d3_select(div)
let form = d3_select(div)
.append("form")
.classed("trial-toolbar", true);
this.svg = d3_select(div)
.append("div")
.append("svg")
.attr("width", this.config.width)
.attr("height", this.config.height)
.call(this.zoom);
this.createMarker('end', 'enormal', 'black');
this.createMarker('endbefore', 'ebefore', 'red');
this.createMarker('endafter', 'eafter', 'green');
this.g = this.svg.append("g")
.attr("id", this._graphId())
.attr("transform", "translate(0,0)")
.classed('TrialGraph', true);
this.tree = d3_tree()
.nodeSize([
this.config.nodeSizeX,
this.config.nodeSizeY
]);
// **Toolbar**
this.createToolbar(form);
// Tooltip
this.tooltipDiv = d3_select("body").append("div")
.attr("class", "now-tooltip now-trial-tooltip")
.style("opacity", 0)
.on("mouseout", () => {
this.closeTooltip();
});
// Zoom
this.svg
.call(this.zoom.transform, d3_zoomIdentity.translate(
this.config.left + this.config.width / 2,
this.config.top
))
}
init(data: TrialGraphData, t1: number, t2: number) {
this.t1 = t1;
this.t2 = t2;
this.minDuration = data.min_duration;
this.maxDuration = data.max_duration;
this.totalDuration = {};
this.totalDuration[t1] = this.maxDuration[t1] - this.minDuration[t1];
this.totalDuration[t2] = this.maxDuration[t2] - this.minDuration[t2];
this.maxTotalDuration = Math.max(
this.totalDuration[t1], this.totalDuration[t2]
);
this.colors = data.colors;
if (!data.root) return;
this.root = d3_hierarchy(data.root, function(d) { return d.children; }) as VisibleTrialNode;
this.root.x0 = 0;
this.root.y0 = (this.config.width) / 2;
this.alledges = data.edges;
this.update(this.root);
}
createToolbar(form: d3_Selection<d3_BaseType, {}, HTMLElement | null, any>) {
let self = this;
form = form.append("div")
.classed("buttons", true);
this.config.customForm(this, form);
// Reset zoom
form.append("a")
.classed("toollink", true)
.attr("id", "trial-" + this.graphId + "-restore-zoom")
.attr("href", "#")
.attr("title", "Restore zoom")
.on("click", () => this.restorePosition())
.append("i")
.classed("fa fa-eye", true)
// Toggle Tooltips
let tooltipsToggle = form.append("input")
.attr("id", "trial-" + this.graphId + "-toolbar-tooltips")
.attr("type", "checkbox")
.attr("name", "trial-toolbar-tooltips")
.attr("value", "show")
.property("checked", this.config.useTooltip)
.on("change", () => {
this.closeTooltip();
this.config.useTooltip = tooltipsToggle.property("checked");
});
form.append("label")
.attr("for", "trial-" + this.graphId + "-toolbar-tooltips")
.attr("title", "Show tooltips on mouse hover")
.append("i")
.classed("fa fa-comment", true)
// Download SVG
form.append("a")
.classed("toollink", true)
.attr("id", "trial-" + this.graphId + "-download")
.attr("href", "#")
.attr("title", "Download graph SVG")
.on("click", () => {
this.download();
})
.append("i")
.classed("fa fa-download", true)
// Set Font Size
let fontToggle = form.append("input")
.attr("id", "trial-" + this.graphId + "-toolbar-fonts")
.attr("type", "checkbox")
.attr("name", "trial-toolbar-fonts")
.attr("value", "show")
.property("checked", false)
.on("change", () => {
let display = fontToggle.property("checked")? "inline-block" : "none";
fontSize.style("display", display);
labelFontSize.style("display", display);
});
form.append("label")
.attr("for", "trial-" + this.graphId + "-toolbar-fonts")
.attr("title", "Set font size")
.append("i")
.classed("fa fa-font", true)
let fontSize = form.append("input")
.attr("type", "number")
.attr("value", this.config.fontSize)
.style("width", "50px")
.style("display", "none")
.attr("title", "Node font size")
.on("change", () => {
this.config.fontSize = fontSize.property("value");
this.svg.selectAll(".node text").attr("font-size", this.config.fontSize);
})
let labelFontSize = form.append("input")
.attr("type", "number")
.attr("value", this.config.labelFontSize)
.style("width", "50px")
.style("display", "none")
.attr("title", "Arrow font size")
.on("change", () => {
this.config.labelFontSize = labelFontSize.property("value");
this.svg.selectAll("text.label_text").attr("font-size", this.config.labelFontSize);
})
// Set distances
let setDistances = function() {
self.config.nodeSizeX = distanceX.property("value");
self.config.nodeSizeY = distanceY.property("value");
self.wrapText()
self.tree
.nodeSize([
self.config.nodeSizeX,
self.config.nodeSizeY
]);
self.update(self.root);
}
// Set Distance X
let distanceXToggle = form.append("input")
.attr("id", "trial-" + this.graphId + "-toolbar-distance-x")
.attr("type", "checkbox")
.attr("name", "trial-toolbar-distance-x")
.attr("value", "show")
.property("checked", false)
.on("change", () => {
let display = distanceXToggle.property("checked")? "inline-block" : "none";
distanceX.style("display", display);
});
form.append("label")
.attr("for", "trial-" + this.graphId + "-toolbar-distance-x")
.attr("title", "Set horizontal distance")
.append("i")
.classed("fa fa-arrows-h", true)
let distanceX = form.append("input")
.attr("type", "number")
.attr("value", this.config.nodeSizeX)
.style("width", "65px")
.style("display", "none")
.attr("title", "Node horizontal distance")
.on("change", setDistances)
// Set Distance Y
let distanceYToggle = form.append("input")
.attr("id", "trial-" + this.graphId + "-toolbar-distance-y")
.attr("type", "checkbox")
.attr("name", "trial-toolbar-distance-y")
.attr("value", "show")
.property("checked", false)
.on("change", () => {
let display = distanceYToggle.property("checked")? "inline-block" : "none";
distanceY.style("display", display);
});
form.append("label")
.attr("for", "trial-" + this.graphId + "-toolbar-distance-y")
.attr("title", "Set vertical distance")
.append("i")
.classed("fa fa-arrows-v", true)
let distanceY = form.append("input")
.attr("type", "number")
.attr("value", this.config.nodeSizeY)
.style("width", "65px")
.style("display", "none")
.attr("title", "Node vertical distance")
.on("change", setDistances)
// Submit
form.append("input")
.attr("type", "submit")
.attr("name", "prevent-enter")
.attr("onclick", "return false;")
.style("display", "none");
}
load(data: TrialGraphData, t1: number, t2: number) {
this.init(data, t1, t2);
this.updateWindow();
}
restorePosition(): void {
this.wrapText();
this.svg
.call(this.zoom.transform, d3_zoomIdentity.translate(
this.config.left + this.config.width / 2,
this.config.top
))
}
updateWindow(): void {
let size = this.config.customSize(this);
this.config.width = size[0];
this.config.height = size[1];
this.svg
.attr("width", size[0])
.attr("height", size[1]);
}
update(source: VisibleTrialNode) {
let treeData = this.tree(this.root);
this.nodes = treeData.descendants();
var node = this.g.selectAll('g.node')
.data(this.nodes, (d: any) => {return d.id || (d.id = ++this.i); });
let validNodes: { [key: string]: VisibleTrialNode } = {};
this.nodes.forEach((node: VisibleTrialNode) => {
validNodes[node.data.index] = node;
});
var edges: VisibleTrialEdge[] = this.alledges.filter((edge: TrialEdgeData) => {
let source: VisibleTrialNode = validNodes[edge.source];
let target: VisibleTrialNode = validNodes[edge.target];
if (source == undefined || target == undefined) {
return false;
}
return true;
}).map((edge) => {
let source: VisibleTrialNode = validNodes[edge.source];
let target: VisibleTrialNode = validNodes[edge.target];
var copy: any = { ...edge };
copy.id = edge.source + "-" + edge.target;
copy.source = source;
copy.target = target;
return copy as VisibleTrialEdge;
});
this.updateNodes(source, node);
this.updateLinks(source, edges);
this.updateLinkLabels(edges);
// Store old positions for transition
this.nodes.forEach(function(d: VisibleTrialNode, i: number){
d.x0 = d.x;
d.y0 = d.y;
});
this.wrapText();
}
download(name?: string) {
var isFileSaverSupported = false;
try {
isFileSaverSupported = !!new Blob();
} catch (e) {
alert("blob not supported");
}
name = (name === undefined)? "trial.svg" : name;
let gnode: any = this.g.node()
var bbox = gnode.getBBox();
var width = this.svg.attr("width"), height = this.svg.attr("height");
this.g.attr("transform", "translate(" + (-bbox.x + 5) +", " +(-bbox.y + 5) +")");
let svgNode: any = this.svg
.attr("title", "Trial")
.attr("version", 1.1)
.attr("width", bbox.width + 10)
.attr("height", bbox.height + 10)
.attr("xmlns", "http://www.w3.org/2000/svg")
.node();
var html = svgNode.parentNode.innerHTML;
html = '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ' + html.slice(4);
this.svg
.attr("width", width)
.attr("height", height);
this.g.attr("transform", this.transform);
if (isFileSaverSupported) {
var blob = new Blob([html], {type: "image/svg+xml"});
fs.saveAs(blob, name);
}
}
wrapText() {
this.svg.selectAll(".node text")
.call(wrap, this.config.nodeSizeX);
}
private calculateColor(d: TrialNodeData, trial_id: number): any {
var proportion = Math.round(255 * (1.0 - (d.duration[trial_id] / this.maxTotalDuration)));
//Math.round(510 * (node.duration - self.min_duration[node.trial_id]) / self.total_duration[node.trial_id]);
return d3_rgb(255, proportion, proportion, 255).toString();
}
private closeTooltip(): void {
this.tooltipDiv.transition()
.duration(500)
.style("opacity", 0);
this.tooltipDiv.classed("hidden", true);
}
private showTooltip(d: TrialNodeData, trial_id: number) {
this.tooltipDiv.classed("hidden", false);
this.tooltipDiv.transition()
.duration(200)
.style("opacity", 0.9);
this.tooltipDiv.html(d.tooltip[trial_id])
.style("left", (d3_event.pageX - 3) + "px")
.style("top", (d3_event.pageY - 28) + "px");
}
private createMarker(name: string, cls: string, fill: string) {
this.svg.append("svg:defs").selectAll("marker")
.data([name])
.enter().append("svg:marker")
.attr("id", this.graphId + "-" + name)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 10)
.attr("refY", 0)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.classed(cls, true)
.attr("fill", fill)
.attr("d", "M0,-5L10,0L0,5");
}
private defaultNodeStroke(d: VisibleTrialNode) {
let color = this.colors[d.data.trial_ids[0]];
if (d.data.trial_ids.length > 1 || color == 0) {
return "#000";
}
if (color == 1) {
return "red";
}
return "green";
}
private nodeClick(d: VisibleTrialNode) {
if (d.children) {
d._children = d.children;
delete d.children;
} else {
d.children = d._children;
delete d._children;
}
this.update(d);
}
private updateNodes(source: VisibleTrialNode, node: any) {
let self = this;
var nodeEnter = node.enter().append('g')
.attr("id", (d: VisibleTrialNode) => {
return "node-" + this.graphId + "-" + d.data.index;
})
.attr('class', 'node')
.attr("cursor", "pointer")
.attr('transform', (d: VisibleTrialNode) => {
return "translate(" + source.x + "," + source.y + ")";
})
.on('click', (d: VisibleTrialNode) => this.nodeClick(d))
.on('mouseover', function(d: VisibleTrialNode) {
if (self.config.useTooltip) {
self.closeTooltip();
if (d3_mouse(this)[0] < 10) {
self.showTooltip(d.data, self.t1);
} else {
self.showTooltip(d.data, self.t2);
}
}
self.config.customMouseOver(self, d, name);
return false;
}).on('mouseout', function (d: VisibleTrialNode) {
self.config.customMouseOut(self, d);
})
// Circle for new nodes
nodeEnter.append('rect')
.attr('class', 'node')
.attr('rx', 1e-6)
.attr('ry', 1e-6)
.attr('width', 1e-6)
.attr('height', 1e-6)
.attr("stroke", (d: VisibleTrialNode) => this.defaultNodeStroke(d))
.attr("stroke-width", "3px")
.attr("fill", (d: VisibleTrialNode) => {
if (d.data.trial_ids.length == 1) {
return this.calculateColor(d.data, this.t1);
}
var grad = this.svg.append("svg:defs")
.append("linearGradient")
.attr("id", "grad-" + this.graphId + "-" + d.data.index)
.attr("x1", "100%")
.attr("x2", "0%")
.attr("y1", "0%")
.attr("y2", "0%");
grad.append("stop")
.attr("offset", "50%")
.attr("stop-color", this.calculateColor(d.data, this.t2));
grad.append("stop")
.attr("offset", "50%")
.attr("stop-color", this.calculateColor(d.data, this.t1));
return "url(#grad-" + this.graphId + "-" + d.data.index + ")";
});
// Text for new nodes
nodeEnter.append('text')
.attr("dy", ".35em")
.attr("font-family", "sans-serif")
.attr("font-size", this.config.fontSize + "px")
.attr("pointer-events", "none")
.attr("fill", "#000")
.attr("y", 24)
.attr("x", 10)
.attr("text-anchor", "middle")
.text((d: VisibleTrialNode) => { return d.data.name; })
nodeEnter.append("path")
.attr("stroke", "#000")
.attr("d", function (d: VisibleTrialNode) {
if (d.data.trial_ids.length > 1) {
return "M10," + 0 +
"L10," + 20;
}
return "M0,0L0,0";
});
// Update
var nodeUpdate = nodeEnter.merge(node);
// Transition to proper position
nodeUpdate.transition()
.duration(this.config.duration)
.attr("transform", (d: VisibleTrialNode) => {
let color = this.colors[d.data.trial_ids[0]];
d.dy = 0;
if (color == 1){
d.dy = -40;
} else if (color == 2) {
d.dy = 40;
}
return "translate(" + (d.x - 10) + "," + (d.y + d.dy - 10) + ")";
});
// Update the node attributes and style
nodeUpdate.select('rect.node')
.attr('width', 20)
.attr('height', 20)
.attr('rx', 20)
.attr('ry', 20)
.attr("rx", (d: VisibleTrialNode) => {
return d._children ? 0 : 20;
})
.attr("ry", (d: VisibleTrialNode) => {
return d._children ? 0 : 20;
})
.attr('cursor', 'pointer');
// Remove exiting nodes
var nodeExit = node.exit().transition()
.duration(this.config.duration)
.attr("transform", function(d: VisibleTrialNode) {
return "translate(" + source.x + "," + source.y + ")";
})
.remove();
// Reduce node rects size to 0 on exit
nodeExit.select('rect')
.attr('rx', 1e-6)
.attr('ry', 1e-6)
.attr('width', 1e-6)
.attr('height', 1e-6);
// Reduce opacity of labels on exit
nodeExit.select('text')
.style('fill-opacity', 1e-6);
}
private updateLinks(source: VisibleTrialNode, edges: VisibleTrialEdge[]) {
var link = this.g.selectAll('path.link')
.data(edges, (d: VisibleTrialEdge) => d.id);
// Enter any new links at the parent's previous position.
var linkEnter = link.enter().insert('path', "g")
.attr("class", "link")
.attr("id", (d: VisibleTrialEdge, i: number) => {
return "pathId-" + this.graphId + "-" + d.id;
})
.attr("fill", "none")
.attr("stroke-width", "1.5px")
.attr('d', (d: VisibleTrialEdge) => {
var o = {y: source.y0, x: source.x0}
return diagonal(o, o)
})
.attr("marker-end", (d: VisibleTrialEdge) => {
let count = 0;
for (let trial_id in d.count) {
if (trial_id == this.t1.toString()) {
count += 1;
}
if (trial_id == this.t2.toString()) {
count += 2;
}
}
if (count == 0 || count == 3) { // Single trial or diff
return "url(#" + this.graphId + "-end)";
}
if (count == 1) { // First trial
return "url(#" + this.graphId + "-endbefore)";
}
if (count == 2) { // Second trial
return "url(#" + this.graphId + "-endafter)";
}
return "";
})
.attr('stroke', (d: VisibleTrialEdge) => {
if (d.type === 'sequence') {
return '#07F';
}
return '#666';
})
.attr('stroke-dasharray', (d: VisibleTrialEdge) => {
if (d.type === 'return') {
return '10,2';
}
return 'none';
});
// UPDATE
var linkUpdate = linkEnter.merge(link)
// Transition back to the parent element position
linkUpdate.transition()
.duration(this.config.duration)
.attr('d', (d: VisibleTrialEdge) => {
if (d.source.dy == undefined) {
d.source.dy = 0;
}
if (d.target.dy == undefined) {
d.target.dy = 0;
}
let
sd = d.source.data,
td = d.target.data,
x1 = d.source.x,
y1 = d.source.y + d.source.dy,
x2 = d.target.x,
y2 = d.target.y + d.target.dy,
dx = x2 - x1,
dy = y2 - y1,
theta = Math.atan(dx / dy),
phi = Math.atan(dy / dx),
r = 10 + 2,
sin_theta = r * Math.sin(theta),
cos_theta = r * Math.cos(theta),
sin_phi = r * Math.sin(phi),
cos_phi = r * Math.cos(phi),
m1 = (y2 > y1) ? 1 : -1,
m2 = (x2 > x1) ? -1 : 1;
if (d.type === 'initial') {
// Initial
return `M ${(x2 - 20)},${(y2 - 20)}
L ${(x2 - r / 2.0)},${(y2 - r / 2.0)}`;
} else if (d.type === 'call' || d.type == 'return') {
// Call/Return
x1 += m1 * sin_theta;
x2 += m2 * cos_phi;
y1 += m1 * cos_theta;
y2 += m2 * sin_phi;
if (dx === 0) {
if (y1 > y2) {
//y1 -= 10
y2 += 20
} else {
//y1 += 10
y2 -= 20
}
}
return `M ${x1}, ${y1}
L ${x2}, ${y2}`;
} else if (dx === 0 && dy === 0) {
// Loop
return `M ${x1}, ${y1}
A 15,20
-45,1,1
${x2 + 5},${y2 + 8}`;
} else if (sd.parent_index == td.parent_index) {
// Same caller
if (dy === 0 && sd.children_index == td.children_index - 1) {
// Immediate sequence
return `M ${x1}, ${y1}
L ${(x2 + m2 * cos_phi)}, ${y2}`;
} else {
let sign = -1;
if (y1 < y2) {
x1 += m1 * sin_theta;
y1 += m1 * cos_theta;
y2 -= r;
sign = -1;
} else if (y2 < y1) {
x1 += m1 * sin_theta;
y1 += m1 * cos_theta;
y2 += r;
sign = 1;
} else if (x1 >= x2) {
y1 += r;
y2 += r;
sign = 2;
} else {
y1 -= r;
y2 -= r;
sign = -1;
}
return `M ${x1}, ${y1}
C ${(x1 + x2) / 2} ${y1 + r * sign},
${(x1 + x2) / 2} ${y2 + r * sign},
${x2} ${y2}`;
}
}
// Other caller
x1 += m1 * sin_theta;
y1 += m1 * cos_theta;
x2 += m2 * cos_phi;
y2 += m2 * sin_phi;
return `M ${x1} ${y1}
C ${(x1 + x2) / 2} ${y1},
${(x1 + x2) / 2} ${y2},
${x2} ${y2}`
});
// Remove any exiting links
link.exit()//.transition()
.attr('d', function(d: VisibleTrialEdge) {
return diagonal(d.source, d.target)
})
.remove(); // linkExit
}
private updateLinkLabels(edges: VisibleTrialEdge[]) {
var labelPath = this.g.selectAll(".label_text")
.data(edges, (d: VisibleTrialEdge) => d.id);
var labelEnter = labelPath.enter().append("text")
.attr("class", "label_text")
.attr("font-family", "sans-serif")
.attr("font-size", this.config.labelFontSize + "px")
.attr("pointer-events", "none")
.attr("fill", "#000")
.attr("text-anchor", "middle")
.attr("dx", (d: VisibleTrialEdge) => {
if (d.source.x == d.target.x) {
return 29;
}
return (Math.abs(d.source.x - d.target.x) - 10) / 2;
})
.attr("dy", -3)
.attr("id", (d: VisibleTrialEdge, i: number) => {
return "pathlabel-" + this.graphId + "-" + d.id;
})
.append("textPath")
.attr("xlink:href", (d: VisibleTrialEdge, i: number) => {
return "#pathId-" + this.graphId + "-" + d.id;
})
.text((d: VisibleTrialEdge) => {
if (d.type === 'initial') {
return '';
}
if (this.t1 == this.t2 || !d.count[this.t2]) {
return d.count[this.t1].toString();
} else if (!d.count[this.t1]) {
return d.count[this.t2].toString();
}
return d.count[this.t1] + ', ' + d.count[this.t2];
});
labelEnter.merge(labelPath)
labelPath.exit().remove();
}
private zoomFunction() {
this.closeTooltip();
this.transform = d3_event.transform;
this.g.attr("transform", d3_event.transform);
}
private _graphId(): string {
return "trial-graph-" + this.graphId;
}
} | the_stack |
import * as angular from 'angular';
import * as _ from "underscore";
import {AccessControlService} from '../../../services/AccessControlService';
const moduleName = require('./module-name');
import '../module-require';
import './module-require';
export class DefineFeedController implements ng.IComponentController {
requestedTemplate:any = this.$transition$.params().templateName || '';
requestedTemplateId:any = this.$transition$.params().templateId || '';
/**
* Indicates if feeds may be imported from an archive.
* @type {boolean}
*/
allowImport:boolean = false;
/**
* the layout choosen. Either 'first', or 'all' changed via the 'more' link
* @type {string}
*/
layout:string = 'first';
/**
* The selected template
* @type {null}
*/
template:any = null;
/**
* The model for creating the feed
* @type {*}
*/
model:any;
/**
* All the templates available
* @type {Array}
*/
allTemplates:Array<any>;
/**
* Array of the first n templates to be displayed prior to the 'more' link
* @type {Array}
*/
firstTemplates:Array<any>;
/**
* flag to indicate we need to display the 'more templates' link
* @type {boolean}
*/
displayMoreLink:boolean = false;
/**
* Flag to indicate we are cloning
* This is set via a $transition$ param in the init() method
* @type {boolean}
*/
cloning:boolean = false;
/**
* After the stepper is initialized this will get called to setup access control
* @param stepper
*/
onStepperInitialized = (function(stepper:any) {
var accessChecks = {entityAccess: this.accessControlService.checkEntityAccessControlled(), securityGroups: this.FeedSecurityGroups.isEnabled()};
this.$q.all(accessChecks).then( (response:any) => {
var entityAccess = this.accessControlService.isEntityAccessControlled();
var securityGroupsAccess = response.securityGroups;
//disable the access control step
if (!entityAccess && !securityGroupsAccess) {
//Access Control is second to last step 0 based array indexc
stepper.deactivateStep(this.model.totalSteps - 2);
}
if (this.cloning) {
this.hideCloningDialog();
}
});
}).bind(this);
/**
* hide the cloning dialog
*/
hideCloningDialog() {
this.$mdDialog.hide();
}
/**
* Click the more link to show all the template cards
*/
more() {
this.layout = 'all';
};
/**
* Navigate to the import feed screen
*/
gotoImportFeed = (function() {
this.StateService.FeedManager().Feed().navigatetoImportFeed();
}).bind(this);
/**
* Select a template
* @param template
*/
selectTemplate(template:any) {
this.model.templateId = template.id;
this.model.templateName = template.templateName;
//setup some initial data points for the template
this.model.defineTable = template.defineTable;
this.model.allowPreconditions = template.allowPreconditions;
this.model.dataTransformationFeed = template.dataTransformation;
// Determine table option
if (template.templateTableOption) {
this.model.templateTableOption = template.templateTableOption;
} else if (template.defineTable) {
this.model.templateTableOption = "DEFINE_TABLE";
} else if (template.dataTransformation) {
this.model.templateTableOption = "DATA_TRANSFORMATION";
} else {
this.model.templateTableOption = "NO_TABLE";
}
//set the total pre-steps for this feed to be 0. They will be taken from the templateTableOption
this.model.totalPreSteps = 0;
//When rendering the pre-step we place a temp tab/step in the front for the initial steps to transclude into and then remove it.
//set this render flag to false initially
this.model.renderTemporaryPreStep = false;
// Load table option
if (this.model.templateTableOption !== "NO_TABLE") {
this.UiComponentsService.getTemplateTableOption(this.model.templateTableOption)
.then( (tableOption:any) => {
//if we have a pre-stepper configured set the properties
if(angular.isDefined(tableOption.preStepperTemplateUrl) && tableOption.preStepperTemplateUrl != null){
this.model.totalPreSteps = tableOption.totalPreSteps
this.model.renderTemporaryPreStep = true;
}
//signal the service that we should track rendering the table template
//We want to run our initializer when both the Pre Steps and the Feed Steps have completed.
//this flag will be picked up in the TableOptionsStepperDirective.js
this.UiComponentsService.startStepperTemplateRender(tableOption);
//add the template steps + 5 (general, feedDetails, properties, access, schedule)
this.model.totalSteps = tableOption.totalSteps + 5;
}, () => {
this.$mdDialog.show(
this.$mdDialog.alert()
.clickOutsideToClose(true)
.title("Create Failed")
.textContent("The template table option could not be loaded.")
.ariaLabel("Failed to create feed")
.ok("Got it!")
);
this.StateService.FeedManager().Feed().navigateToFeeds();
});
} else {
this.model.totalSteps = 5;
}
};
/**
* Cancel the stepper
*/
cancelStepper() {
this.FeedService.resetFeed();
this.model.totalSteps = null;
};
/**
* Return a list of the Registered Templates in the system
* @returns {HttpPromise}
*/
getRegisteredTemplates() {
var successFn = (response:any) => {
if (response.data) {
var data = _.chain(response.data).filter((template) => {
return template.state === 'ENABLED'
}).sortBy('order')
.value();
if (data.length > 1) {
this.displayMoreLink = true;
}
this.allTemplates = data;
this.firstTemplates = _.first(data, 3);
if (this.cloning) {
this.model = this.FeedService.cloneFeed();
var registeredTemplate = this.model.registeredTemplate;
var templateObj = {
id: registeredTemplate.id,
templateName: registeredTemplate.templateName,
defineTable: registeredTemplate.defineTable,
allowPreconditions: registeredTemplate.allowPreconditions,
dataTransformation: registeredTemplate.dataTransformation,
templateTableOption: registeredTemplate.templateTableOption
}
this.selectTemplate(templateObj);
}
}
};
var errorFn = (err:any) => {
};
var promise = this.$http.get(this.RestUrlService.GET_REGISTERED_TEMPLATES_URL);
promise.then(successFn, errorFn);
return promise;
}
/**
* initialize the controller
*/
init() {
var isCloning = this.$transition$.params().bcExclude_cloning;
var cloneFeedName = this.$transition$.params().bcExclude_cloneFeedName;
this.cloning = angular.isUndefined(isCloning) ? false : isCloning;
var feedDescriptor = this.$transition$.params().feedDescriptor || '';
this.model.feedDescriptor = feedDescriptor;
this.getRegisteredTemplates().then((response:any) =>{
if(angular.isDefined(this.requestedTemplate) && this.requestedTemplate != ''){
var match = _.find(this.allTemplates,(template:any) => {
return template.templateName == this.requestedTemplate || template.id == this.requestedTemplateId;
});
if(angular.isDefined(match)) {
this.FeedService.resetFeed();
if(angular.isDefined(feedDescriptor) && feedDescriptor != ''){
this.model.feedDescriptor =feedDescriptor;
}
this.selectTemplate(match);
}
}
});
if (this.cloning) {
this.showCloningDialog(cloneFeedName);
}
// Fetch the allowed actions
this.accessControlService.getUserAllowedActions()
.then( (actionSet:any) => {
this.allowImport = this.accessControlService.hasAction(AccessControlService.FEEDS_IMPORT, actionSet.actions);
});
}
/**
* Show a dialog while the cloning is setting up the stepper with the data
* @param cloneFeedName
*/
showCloningDialog(cloneFeedName:any) {
if (angular.isUndefined(cloneFeedName)) {
cloneFeedName = "the feed";
}
this.$mdDialog.show({
templateUrl: './clone-feed-dialog.html',
parent: angular.element(document.body),
clickOutsideToClose: true,
locals: {
feedName: cloneFeedName
},
controller: CloningDialogController,
fullscreen: true
});
function CloningDialogController($scope:any, $mdDialog:any, feedName:any) {
$scope.feedName = feedName;
$scope.closeDialog = function () {
$mdDialog.hide();
}
}
}
constructor (private $scope:any, private $http:any, private $mdDialog:any, private $q:any, private $transition$:any
, private accessControlService:AccessControlService, private FeedService:any, private FeedSecurityGroups:any, private RestUrlService:any, private StateService:any
, private UiComponentsService:any) {
var self = this;
this.model = FeedService.createFeedModel;
if(angular.isUndefined(this.model)){
FeedService.resetFeed();
}
/**
* The total number of steps to deisplay and render for the feed stepper
* @type {null}
*/
this.model.totalSteps = null;
/**
* The stepper url.
*
* @type {string}
*/
this.model.stepperTemplateUrl= 'js/feed-mgr/feeds/define-feed/define-feed-stepper.html'
this.requestedTemplate = $transition$.params().templateName || '';
this.requestedTemplateId = $transition$.params().templateId || '';
this.allTemplates = [];
this.firstTemplates = [];
this.displayMoreLink = false;
this.cloning = false;
//initialize the controller
this.init();
};
}
const module = angular.module(moduleName).controller('DefineFeedController',
["$scope", "$http", "$mdDialog", "$q", "$transition$", "AccessControlService", "FeedService", "FeedSecurityGroups", "RestUrlService", "StateService",
"UiComponentsService", DefineFeedController]);
export default module; | the_stack |
import * as fs from 'fs';
import * as stopify from '../src/entrypoints/compiler';
import * as assert from 'assert';
import * as fixtures from './testFixtures.js';
import * as types from '../src/types';
// The compiler produces code that expects Stopify and its runtime compiler to
// be a global variable.
(global as any).stopify = stopify;
function setupGlobals(runner: stopify.AsyncRun & stopify.AsyncEval) {
var globals: any = {
assert: assert,
require: function(str: string) {
if (str === 'assert') {
return assert;
}
else {
throw 'unknown library';
}
},
Math: Math,
Number: Number,
String: String,
WeakMap: WeakMap, // TODO(arjun): We rely on this for tests?!
console: console,
Array: Array,
Object: Object
};
runner.g = globals;
}
function harness(code: string,
compilerOpts: Partial<stopify.CompilerOpts> = { },
runtimeOpts: Partial<stopify.RuntimeOpts> = {
yieldInterval: 1,
estimator: 'countdown'
}) {
const runner = stopify.stopifyLocally(code, compilerOpts, runtimeOpts);
if (runner.kind === 'error') {
throw runner.exception;
}
setupGlobals(runner);
return runner;
}
test('in a function (not method), this should be the global this', done => {
const runner = harness(`
var x = this;
var y;
function foo() {
y = this;
}
foo();`);
runner.run(result => {
expect(result).toMatchObject({ type: 'normal' });
expect(runner.g.x).toBe(global);
expect(runner.g.y).toBe(runner.g.x);
done();
});
});
test('can refer to arguments', done => {
const runner = harness(`
var x = this;
var y;
function foo() {
y = arguments.length;
}
foo(1,2,3);`);
runner.run(result => {
expect(result).toMatchObject({ type: 'normal' });
expect(runner.g.y).toBe(3);
done();
});
});
test('external HOF', done => {
const runner = harness(`
result = 4000 + externalFunction(function(x) { return x + 1; });`);
// Without Stopify, this function would be:
// function(f) { return f(20) + 300; }
runner.g.externalFunction = function(f: any) {
runner.externalHOF(complete => {
runner.runStopifiedCode(
() => f(20),
(result) => {
if (result.type === 'normal') {
complete({ type: 'normal', value: result.value + 300 });
}
else {
complete(result);
}
});
});
}
runner.run(result => {
expect(result).toMatchObject({ type: 'normal' });
expect(runner.g.result).toBe(4321);
done();
});
});
// NOTE(arjun): This test can probably be simplified further. The real issue
// is that boxing/unboxing of the argument x gets mixed up, and I don't think
// the externalHOF is needed to trigger it.
test('external HOF with arguments materialization', done => {
const runner = harness(`
function check(y) { return y === 900; }
function oracle(x) {
arguments.length; // force arguments materialization
externalFunction(function() { }); // needed
function escape() { return x; } // force x to be boxed
r = check(x);
}
oracle(900)`);
// Without Stopify, this function would be:
// function(f) { return f(20) + 300; }
runner.g.externalFunction = function(f: any) {
runner.externalHOF(complete => {
runner.runStopifiedCode(
() => f(),
(result) => {
if (result.type === 'normal') {
complete({ type: 'normal', value: result.value });
}
else {
complete(result);
}
});
});
};
runner.run(result => {
expect(result).toMatchObject({ type: 'normal' });
expect(runner.g.r).toBe(true);
done();
});
});
function expectNontermination(code: string,
compilerOpts: Partial<types.CompilerOpts>,
onDone: () => void) {
let timers: NodeJS.Timer[] = [ ];
function clearTimers() {
timers.forEach(timerId => clearTimeout(timerId));
}
const runtimeOpts: Partial<types.RuntimeOpts> = {
estimator: 'countdown',
yieldInterval: 10
};
const runner = harness(code, compilerOpts, runtimeOpts);
runner.run(result => {
clearTimers();
assert(false, `program terminated with ${JSON.stringify(result)}`);
});
timers.push(setTimeout(() => {
runner.pause(line => {
clearTimers();
onDone();
});
timers.push(setTimeout(() => {
clearTimers();
assert(false, 'program did not pause');
}, 5000));
}, 5000));
}
describe('stopping nonterminating programs', () => {
test('infinite loop (lazy, nontermination)', onDone => {
expectNontermination(`while (true) { }`,
{ captureMethod: 'lazy' }, onDone);
}, 12 * 1000);
test('infinite loop (eager, nontermination)', onDone => {
expectNontermination(`while (true) { }`,
{ captureMethod: 'eager' }, onDone);
}, 12 * 1000);
test('infinite loop (retval, nontermination)', onDone => {
expectNontermination(`while (true) { }`,
{ captureMethod: 'retval' }, onDone);
}, 12 * 1000);
});
function runTest(code: string,
compilerOpts: Partial<types.CompilerOpts>,
runtimeOpts: Partial<types.RuntimeOpts>,
onDone: () => void) {
let runner = harness(code, compilerOpts, runtimeOpts);
let done = false;
runner.run(result => {
if (done) {
return;
}
done = true;
expect(result).toMatchObject({ type: 'normal' });
onDone();
});
setTimeout(() => {
if (done) {
return;
}
done = true;
runner.pause(() => undefined);
assert(false);
}, 10000);
}
describe('in-file tests', function() {
for (let filename of fixtures.unitTests) {
test(`in-file ${filename} (lazy, wrapper)`, done => {
let code = fs.readFileSync(filename, { encoding: 'utf-8' });
runTest(code, {
captureMethod: 'lazy',
newMethod: 'wrapper',
jsArgs: 'full'
}, {
yieldInterval: 1,
estimator: 'countdown'
}, done);
});
test(`in-file ${filename} (lazy, direct)`, done => {
let code = fs.readFileSync(filename, { encoding: 'utf-8' });
runTest(code, {
captureMethod: 'lazy',
newMethod: 'direct',
jsArgs: 'full'
}, {
yieldInterval: 1,
estimator: 'countdown'
}, done);
});
test(`in-file ${filename} (catch, direct)`, done => {
let code = fs.readFileSync(filename, { encoding: 'utf-8' });
runTest(code, {
captureMethod: 'catch',
newMethod: 'wrapper',
jsArgs: 'full'
}, {
yieldInterval: 1,
estimator: 'countdown'
}, done);
});
}
});
describe('integration tests', function () {
for (let filename of fixtures.intTests) {
test(`integration: ${filename} lazy-wrapper`, done => {
let code = fs.readFileSync(filename, { encoding: 'utf-8' });
runTest(code, {
captureMethod: 'lazy',
newMethod: 'wrapper',
jsArgs: 'full'
}, { }, done);
}, 30000);
test(`integration: ${filename} eager-wrapper`, done => {
let code = fs.readFileSync(filename, { encoding: 'utf-8' });
runTest(code, {
captureMethod: 'eager',
newMethod: 'wrapper',
jsArgs: 'full'
}, { }, done);
}, 30000);
test(`integration: ${filename} retval-wrapper`, done => {
let code = fs.readFileSync(filename, { encoding: 'utf-8' });
runTest(code, {
captureMethod: 'retval',
newMethod: 'wrapper',
jsArgs: 'full'
}, { }, done);
}, 30000);
}
});
describe('Test cases that require deep stacks',() => {
const runtimeOpts: Partial<types.RuntimeOpts> = {
stackSize: 100,
restoreFrames: 1,
estimator: 'countdown',
yieldInterval: 25
};
test.skip('non-tail recursive function (deep, lazy)', onDone => {
const runner = harness(`
function sum(x) {
if (x <= 1) {
return 1;
} else {
return x + sum(x-1);
}
}
assert.equal(sum(200), 1250025000);
`, { captureMethod: 'lazy' }, runtimeOpts);
runner.run(result => {
expect(result).toEqual({ type: 'normal' });
onDone();
});
}, 10000);
test.skip('non-tail recursive function (deep, eager)', onDone => {
const runner = harness(`
function sum(x) {
if (x <= 1) {
return 1;
} else {
return x + sum(x-1);
}
}
assert.equal(sum(200), 1250025000);
`, { captureMethod: 'eager' }, runtimeOpts);
runner.run(result => {
expect(result).toEqual({ type: 'normal' });
onDone();
});
}, 10000);
// This test makes sure that an exception thrown from a stack
// frame is properly threaded through a captured stack.
test.skip('deep stacks with exceptions (deep, eager)', onDone => {
const runner = harness(`
const assert = require('assert');
function sumThrow(n) {
if (n <= 0) {
throw 0;
}
else {
try {
sumThrow(n - 1);
}
catch(e) {
throw e + n;
}
}
}
try {
sumThrow(50000)
}
catch(e) {
assert.equal(e, 1250025000)
}
`, { captureMethod: 'eager' }, runtimeOpts);
runner.run(result => {
expect(result).toEqual({ type: 'normal' });
onDone();
});
}, 10000);
}); | the_stack |
import { schema } from '@kbn/config-schema';
import { IRouter, ResponseError, IKibanaResponse, KibanaResponseFactory } from 'kibana/server';
import { API_PREFIX, CONFIGURATION_API_PREFIX, isValidResourceName } from '../../common';
// TODO: consider to extract entity CRUD operations and put it into a client class
export function defineRoutes(router: IRouter) {
const internalUserSchema = schema.object({
description: schema.maybe(schema.string()),
password: schema.maybe(schema.string()),
backend_roles: schema.arrayOf(schema.string(), { defaultValue: [] }),
attributes: schema.any({ defaultValue: {} }),
});
const actionGroupSchema = schema.object({
description: schema.maybe(schema.string()),
allowed_actions: schema.arrayOf(schema.string()),
// type field is not supported in legacy implementation, comment it out for now.
// type: schema.oneOf([
// schema.literal('cluster'),
// schema.literal('index'),
// schema.literal('kibana'),
// ]),
});
const roleMappingSchema = schema.object({
description: schema.maybe(schema.string()),
backend_roles: schema.arrayOf(schema.string(), { defaultValue: [] }),
hosts: schema.arrayOf(schema.string(), { defaultValue: [] }),
users: schema.arrayOf(schema.string(), { defaultValue: [] }),
});
const roleSchema = schema.object({
description: schema.maybe(schema.string()),
cluster_permissions: schema.arrayOf(schema.string(), { defaultValue: [] }),
tenant_permissions: schema.arrayOf(schema.any(), { defaultValue: [] }),
index_permissions: schema.arrayOf(schema.any(), { defaultValue: [] }),
});
const tenantSchema = schema.object({
description: schema.string(),
});
const accountSchema = schema.object({
password: schema.string(),
current_password: schema.string(),
});
const schemaMap: any = {
internalusers: internalUserSchema,
actiongroups: actionGroupSchema,
rolesmapping: roleMappingSchema,
roles: roleSchema,
tenants: tenantSchema,
account: accountSchema,
};
function validateRequestBody(resourceName: string, requestBody: any): any {
const inputSchema = schemaMap[resourceName];
if (!inputSchema) {
throw new Error(`Unknown resource ${resourceName}`);
}
inputSchema.validate(requestBody); // throws error if validation fail
}
function validateEntityId(resourceName: string) {
if (!isValidResourceName(resourceName)) {
return 'Invalid entity name or id.';
}
}
/**
* Lists resources by resource name.
*
* The response format is:
* {
* "total": <total_entity_count>,
* "data": {
* "entity_id_1": { <entity_structure> },
* "entity_id_2": { <entity_structure> },
* ...
* }
* }
*
* e.g. when listing internal users, response may look like:
* {
* "total": 2,
* "data": {
* "api_test_user2": {
* "hash": "",
* "reserved": false,
* "hidden": false,
* "backend_roles": [],
* "attributes": {},
* "description": "",
* "static": false
* },
* "api_test_user1": {
* "hash": "",
* "reserved": false,
* "hidden": false,
* "backend_roles": [],
* "attributes": {},
* "static": false
* }
* }
*
* when listing action groups, response will look like:
* {
* "total": 2,
* "data": {
* "read": {
* "reserved": true,
* "hidden": false,
* "allowed_actions": ["indices:data/read*", "indices:admin/mappings/fields/get*"],
* "type": "index",
* "description": "Allow all read operations",
* "static": false
* },
* "cluster_all": {
* "reserved": true,
* "hidden": false,
* "allowed_actions": ["cluster:*"],
* "type": "cluster",
* "description": "Allow everything on cluster level",
* "static": false
* }
* }
*
* role:
* {
* "total": 2,
* "data": {
* "kibana_user": {
* "reserved": true,
* "hidden": false,
* "description": "Provide the minimum permissions for a kibana user",
* "cluster_permissions": ["cluster_composite_ops"],
* "index_permissions": [{
* "index_patterns": [".kibana", ".kibana-6", ".kibana_*"],
* "fls": [],
* "masked_fields": [],
* "allowed_actions": ["read", "delete", "manage", "index"]
* }, {
* "index_patterns": [".tasks", ".management-beats"],
* "fls": [],
* "masked_fields": [],
* "allowed_actions": ["indices_all"]
* }],
* "tenant_permissions": [],
* "static": false
* },
* "all_access": {
* "reserved": true,
* "hidden": false,
* "description": "Allow full access to all indices and all cluster APIs",
* "cluster_permissions": ["*"],
* "index_permissions": [{
* "index_patterns": ["*"],
* "fls": [],
* "masked_fields": [],
* "allowed_actions": ["*"]
* }],
* "tenant_permissions": [{
* "tenant_patterns": ["*"],
* "allowed_actions": ["kibana_all_write"]
* }],
* "static": false
* }
* }
* }
*
* rolesmapping:
* {
* "total": 2,
* "data": {
* "security_manager": {
* "reserved": false,
* "hidden": false,
* "backend_roles": [],
* "hosts": [],
* "users": ["zengyan", "admin"],
* "and_backend_roles": []
* },
* "all_access": {
* "reserved": false,
* "hidden": false,
* "backend_roles": [],
* "hosts": [],
* "users": ["zengyan", "admin", "indextest"],
* "and_backend_roles": []
* }
* }
* }
*
* tenants:
* {
* "total": 2,
* "data": {
* "global_tenant": {
* "reserved": true,
* "hidden": false,
* "description": "Global tenant",
* "static": false
* },
* "test tenant": {
* "reserved": false,
* "hidden": false,
* "description": "tenant description",
* "static": false
* }
* }
* }
*/
router.get(
{
path: `${API_PREFIX}/${CONFIGURATION_API_PREFIX}/{resourceName}`,
validate: {
params: schema.object({
resourceName: schema.string(),
}),
},
},
async (context, request, response): Promise<IKibanaResponse<any | ResponseError>> => {
const client = context.security_plugin.esClient.asScoped(request);
let esResp;
try {
esResp = await client.callAsCurrentUser('opendistro_security.listResource', {
resourceName: request.params.resourceName,
});
return response.ok({
body: {
total: Object.keys(esResp).length,
data: esResp,
},
});
} catch (error) {
console.log(JSON.stringify(error));
return errorResponse(response, error);
}
}
);
/**
* Gets entity by id.
*
* the response format differs from different resource types. e.g.
*
* for internal user, response will look like:
* {
* "hash": "",
* "reserved": false,
* "hidden": false,
* "backend_roles": [],
* "attributes": {},
* "static": false
* }
*
* for role, response will look like:
* {
* "reserved": true,
* "hidden": false,
* "description": "Allow full access to all indices and all cluster APIs",
* "cluster_permissions": ["*"],
* "index_permissions": [{
* "index_patterns": ["*"],
* "fls": [],
* "masked_fields": [],
* "allowed_actions": ["*"]
* }],
* "tenant_permissions": [{
* "tenant_patterns": ["*"],
* "allowed_actions": ["kibana_all_write"]
* }],
* "static": false
* }
*
* for roles mapping, response will look like:
* {
* "reserved": true,
* "hidden": false,
* "description": "Allow full access to all indices and all cluster APIs",
* "cluster_permissions": ["*"],
* "index_permissions": [{
* "index_patterns": ["*"],
* "fls": [],
* "masked_fields": [],
* "allowed_actions": ["*"]
* }],
* "tenant_permissions": [{
* "tenant_patterns": ["*"],
* "allowed_actions": ["kibana_all_write"]
* }],
* "static": false
* }
*
* for action groups, response will look like:
* {
* "reserved": true,
* "hidden": false,
* "allowed_actions": ["indices:data/read*", "indices:admin/mappings/fields/get*"],
* "type": "index",
* "description": "Allow all read operations",
* "static": false
* }
*
* for tenant, response will look like:
* {
* "reserved": true,
* "hidden": false,
* "description": "Global tenant",
* "static": false
* },
*/
router.get(
{
path: `${API_PREFIX}/${CONFIGURATION_API_PREFIX}/{resourceName}/{id}`,
validate: {
params: schema.object({
resourceName: schema.string(),
id: schema.string(),
}),
},
},
async (context, request, response): Promise<IKibanaResponse<any | ResponseError>> => {
const client = context.security_plugin.esClient.asScoped(request);
let esResp;
try {
esResp = await client.callAsCurrentUser('opendistro_security.getResource', {
resourceName: request.params.resourceName,
id: request.params.id,
});
return response.ok({ body: esResp[request.params.id] });
} catch (error) {
return errorResponse(response, error);
}
}
);
/**
* Deletes an entity by id.
*/
router.delete(
{
path: `${API_PREFIX}/${CONFIGURATION_API_PREFIX}/{resourceName}/{id}`,
validate: {
params: schema.object({
resourceName: schema.string(),
id: schema.string({
minLength: 1,
}),
}),
},
},
async (context, request, response): Promise<IKibanaResponse<any | ResponseError>> => {
const client = context.security_plugin.esClient.asScoped(request);
let esResp;
try {
esResp = await client.callAsCurrentUser('opendistro_security.deleteResource', {
resourceName: request.params.resourceName,
id: request.params.id,
});
return response.ok({
body: {
message: esResp.message,
},
});
} catch (error) {
return errorResponse(response, error);
}
}
);
/**
* Update object with out Id. Resource identification is expected to computed from headers. Eg: auth headers
*
* Request sample:
* /configuration/account
* {
* "password": "new-password",
* "current_password": "old-password"
* }
*/
router.post(
{
path: `${API_PREFIX}/${CONFIGURATION_API_PREFIX}/{resourceName}`,
validate: {
params: schema.object({
resourceName: schema.string(),
}),
body: schema.any(),
},
},
async (context, request, response): Promise<IKibanaResponse<any | ResponseError>> => {
try {
validateRequestBody(request.params.resourceName, request.body);
} catch (error) {
return response.badRequest({ body: error });
}
const client = context.security_plugin.esClient.asScoped(request);
let esResp;
try {
esResp = await client.callAsCurrentUser('opendistro_security.saveResourceWithoutId', {
resourceName: request.params.resourceName,
body: request.body,
});
return response.ok({
body: {
message: esResp.message,
},
});
} catch (error) {
return errorResponse(response, error);
}
}
);
/**
* Update entity by Id.
*/
router.post(
{
path: `${API_PREFIX}/${CONFIGURATION_API_PREFIX}/{resourceName}/{id}`,
validate: {
params: schema.object({
resourceName: schema.string(),
id: schema.string({
validate: validateEntityId,
}),
}),
body: schema.any(),
},
},
async (context, request, response): Promise<IKibanaResponse<any | ResponseError>> => {
try {
validateRequestBody(request.params.resourceName, request.body);
} catch (error) {
return response.badRequest({ body: error });
}
const client = context.security_plugin.esClient.asScoped(request);
let esResp;
try {
esResp = await client.callAsCurrentUser('opendistro_security.saveResource', {
resourceName: request.params.resourceName,
id: request.params.id,
body: request.body,
});
return response.ok({
body: {
message: esResp.message,
},
});
} catch (error) {
return errorResponse(response, error);
}
}
);
/**
* Gets authentication info of the user.
*
* The response looks like:
* {
* "user": "User [name=admin, roles=[], requestedTenant=__user__]",
* "user_name": "admin",
* "user_requested_tenant": "__user__",
* "remote_address": "127.0.0.1:35044",
* "backend_roles": [],
* "custom_attribute_names": [],
* "roles": ["all_access", "security_manager"],
* "tenants": {
* "another_tenant": true,
* "admin": true,
* "global_tenant": true,
* "aaaaa": true,
* "test tenant": true
* },
* "principal": null,
* "peer_certificates": "0",
* "sso_logout_url": null
* }
*/
router.get(
{
path: `${API_PREFIX}/auth/authinfo`,
validate: false,
},
async (context, request, response): Promise<IKibanaResponse<any | ResponseError>> => {
const client = context.security_plugin.esClient.asScoped(request);
let esResp;
try {
esResp = await client.callAsCurrentUser('opendistro_security.authinfo');
return response.ok({
body: esResp,
});
} catch (error) {
return errorResponse(response, error);
}
}
);
/**
* Gets audit log configuration。
*
* Sample payload:
* {
* "enabled":true,
* "audit":{
* "enable_rest":false,
* "disabled_rest_categories":[
* "FAILED_LOGIN",
* "AUTHENTICATED"
* ],
* "enable_transport":true,
* "disabled_transport_categories":[
* "GRANTED_PRIVILEGES"
* ],
* "resolve_bulk_requests":true,
* "log_request_body":false,
* "resolve_indices":true,
* "exclude_sensitive_headers":true,
* "ignore_users":[
* "admin",
* ],
* "ignore_requests":[
* "SearchRequest",
* "indices:data/read/*"
* ]
* },
* "compliance":{
* "enabled":true,
* "internal_config":false,
* "external_config":false,
* "read_metadata_only":false,
* "read_watched_fields":{
* "indexName1":[
* "field1",
* "fields-*"
* ]
* },
* "read_ignore_users":[
* "kibanaserver",
* "operator/*"
* ],
* "write_metadata_only":false,
* "write_log_diffs":false,
* "write_watched_indices":[
* "indexName2",
* "indexPatterns-*"
* ],
* "write_ignore_users":[
* "admin"
* ]
* }
* }
*/
router.get(
{
path: `${API_PREFIX}/configuration/audit`,
validate: false,
},
async (context, request, response): Promise<IKibanaResponse<any | ResponseError>> => {
const client = context.security_plugin.esClient.asScoped(request);
let esResp;
try {
esResp = await client.callAsCurrentUser('opendistro_security.getAudit');
return response.ok({
body: esResp,
});
} catch (error) {
return response.custom({
statusCode: error.statusCode,
body: parseEsErrorResponse(error),
});
}
}
);
/**
* Update audit log configuration。
*
* Sample payload:
* {
* "enabled":true,
* "audit":{
* "enable_rest":false,
* "disabled_rest_categories":[
* "FAILED_LOGIN",
* "AUTHENTICATED"
* ],
* "enable_transport":true,
* "disabled_transport_categories":[
* "GRANTED_PRIVILEGES"
* ],
* "resolve_bulk_requests":true,
* "log_request_body":false,
* "resolve_indices":true,
* "exclude_sensitive_headers":true,
* "ignore_users":[
* "admin",
* ],
* "ignore_requests":[
* "SearchRequest",
* "indices:data/read/*"
* ]
* },
* "compliance":{
* "enabled":true,
* "internal_config":false,
* "external_config":false,
* "read_metadata_only":false,
* "read_watched_fields":{
* "indexName1":[
* "field1",
* "fields-*"
* ]
* },
* "read_ignore_users":[
* "kibanaserver",
* "operator/*"
* ],
* "write_metadata_only":false,
* "write_log_diffs":false,
* "write_watched_indices":[
* "indexName2",
* "indexPatterns-*"
* ],
* "write_ignore_users":[
* "admin"
* ]
* }
* }
*/
router.post(
{
path: `${API_PREFIX}/configuration/audit/config`,
validate: {
body: schema.any(),
},
},
async (context, request, response) => {
const client = context.security_plugin.esClient.asScoped(request);
let esResp;
try {
esResp = await client.callAsCurrentUser('opendistro_security.saveAudit', {
body: request.body,
});
return response.ok({
body: {
message: esResp.message,
},
});
} catch (error) {
return errorResponse(response, error);
}
}
);
/**
* Deletes cache.
*
* Sample response: {"message":"Cache flushed successfully."}
*/
router.delete(
{
path: `${API_PREFIX}/configuration/cache`,
validate: false,
},
async (context, request, response) => {
const client = context.security_plugin.esClient.asScoped(request);
let esResponse;
try {
esResponse = await client.callAsCurrentUser('opendistro_security.clearCache');
return response.ok({
body: {
message: esResponse.message,
},
});
} catch (error) {
return errorResponse(response, error);
}
}
);
/**
* Gets permission info of current user.
*
* Sample response:
* {
* "user": "User [name=admin, roles=[], requestedTenant=__user__]",
* "user_name": "admin",
* "has_api_access": true,
* "disabled_endpoints": {}
* }
*/
router.get(
{
path: `${API_PREFIX}/restapiinfo`,
validate: false,
},
async (context, request, response) => {
const client = context.security_plugin.esClient.asScoped(request);
try {
const esResponse = await client.callAsCurrentUser('opendistro_security.restapiinfo');
return response.ok({
body: esResponse,
});
} catch (error) {
return response.badRequest({
body: error,
});
}
}
);
/**
* Validates DLS (document level security) query.
*
* Request payload is an ES query.
*/
router.post(
{
path: `${API_PREFIX}/${CONFIGURATION_API_PREFIX}/validatedls/{indexName}`,
validate: {
params: schema.object({
// in legacy plugin implmentation, indexName is not used when calling ES API.
indexName: schema.maybe(schema.string()),
}),
body: schema.any(),
},
},
async (context, request, response) => {
const client = context.security_plugin.esClient.asScoped(request);
try {
const esResponse = await client.callAsCurrentUser('opendistro_security.validateDls', {
body: request.body,
});
return response.ok({
body: esResponse,
});
} catch (error) {
return errorResponse(response, error);
}
}
);
/**
* Gets index mapping.
*
* Calling ES _mapping API under the hood. see
* https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-mapping.html
*/
router.post(
{
path: `${API_PREFIX}/${CONFIGURATION_API_PREFIX}/index_mappings`,
validate: {
body: schema.object({
index: schema.arrayOf(schema.string()),
}),
},
},
async (context, request, response) => {
const client = context.security_plugin.esClient.asScoped(request);
try {
const esResponse = await client.callAsCurrentUser('opendistro_security.getIndexMappings', {
index: request.body.index.join(','),
ignore_unavailable: true,
allow_no_indices: true,
});
return response.ok({
body: esResponse,
});
} catch (error) {
return errorResponse(response, error);
}
}
);
/**
* Gets all indices, and field mappings.
*
* Calls ES API '/_all/_mapping/field/*' under the hood. see
* https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-mapping.html
*/
router.get(
{
path: `${API_PREFIX}/${CONFIGURATION_API_PREFIX}/indices`,
validate: false,
},
async (context, request, response) => {
const client = context.security_plugin.esClient.asScoped(request);
try {
const esResponse = await client.callAsCurrentUser('opendistro_security.indices');
return response.ok({
body: esResponse,
});
} catch (error) {
return errorResponse(response, error);
}
}
);
}
function parseEsErrorResponse(error: any) {
if (error.response) {
try {
const esErrorResponse = JSON.parse(error.response);
return esErrorResponse.reason || error.response;
} catch (parsingError) {
return error.response;
}
}
return error.message;
}
function errorResponse(response: KibanaResponseFactory, error: any) {
return response.custom({
statusCode: error.statusCode,
body: parseEsErrorResponse(error),
});
} | the_stack |
import _ from 'lodash';
import { Content, DSL, FileTypes } from '@foxpage/foxpage-server-types';
import { LOG, PRE, TYPE } from '../../../config/constant';
import * as Model from '../../models';
import { FolderFileContent, UpdateTypeContent } from '../../types/content-types';
import { FoxCtx, TypeStatus } from '../../types/index-types';
import { AppResource } from '../../types/validates/app-validate-types';
import { generationId, randStr } from '../../utils/tools';
import { BaseService } from '../base-service';
import * as Service from '../index';
export class ContentInfoService extends BaseService<Content> {
private static _instance: ContentInfoService;
constructor() {
super(Model.content);
}
/**
* Single instance
* @returns ContentInfoService
*/
public static getInstance (): ContentInfoService {
this._instance || (this._instance = new ContentInfoService());
return this._instance;
}
/**
* New content details, only query statements required by the transaction are generated,
* and details of the created content are returned
* @param {Partial<Content>} params
* @returns Content
*/
create (params: Partial<Content>, options: { ctx: FoxCtx }): Content {
const contentDetail: Content = {
id: params.id || generationId(PRE.CONTENT),
title: _.trim(params?.title) || '',
fileId: params.fileId || '',
tags: params?.tags || [],
liveVersionNumber: params.liveVersionNumber || 0,
creator: params?.creator || options.ctx.userInfo.id,
};
options.ctx.transactions.push(Model.content.addDetailQuery(contentDetail));
options.ctx.operations.push({
action: LOG.CREATE,
category: LOG.CATEGORY_APPLICATION,
content: {
id: contentDetail.id,
contentId: contentDetail.id,
fileId: params.fileId,
after: contentDetail,
},
});
return contentDetail;
}
/**
* Create content details, if it is not component content, create version information by default
* @param {Partial<Content>} params
* @param {FileTypes} type
* @param {any} content?
* @returns Content
*/
addContentDetail (
params: Partial<Content>,
options: { ctx: FoxCtx; type: FileTypes; content?: any },
): Content {
const contentDetail = this.create(params, { ctx: options.ctx });
if ([TYPE.COMPONENT, TYPE.EDITOR, TYPE.LIBRARY].indexOf(options.type) === -1) {
Service.version.info.create(
{ contentId: contentDetail.id, content: options?.content || {} },
{ ctx: options.ctx, fileId: params.fileId },
);
}
return contentDetail;
}
/**
* Update content details
* @param {UpdateTypeContent} params
* @returns Promise
*/
async updateContentDetail (
params: UpdateTypeContent,
options: { ctx: FoxCtx },
): Promise<Record<string, number>> {
const contentDetail = await this.getDetailById(params.id);
if (!contentDetail || contentDetail.deleted) {
return { code: 1 }; // Invalid content ID
}
const fileDetail = await Service.file.info.getDetailById(contentDetail.fileId);
if (!fileDetail || fileDetail.deleted || fileDetail.type !== params.type) {
return { code: 2 }; // Check whether the file type is consistent with the specified type
}
if (params.title && contentDetail.title !== params.title) {
const contentExist = await Service.content.check.nameExist(contentDetail.id, {
fileId: contentDetail.fileId,
title: params.title,
});
if (contentExist) {
return { code: 3 }; // Duplicate content name
}
}
// Update content information
options.ctx.transactions.push(
Model.content.updateDetailQuery(params.id, _.pick(params, ['title', 'tags'])),
);
const content = {
id: contentDetail.id,
contentId: contentDetail.id,
dataType: fileDetail.type,
before: contentDetail,
};
options.ctx.operations.push({
action: LOG.CONTENT_UPDATE,
category: LOG.CATEGORY_APPLICATION,
content: content,
});
// tag update log
if (contentDetail.liveVersionNumber > 0 && params.tags !== contentDetail.tags) {
options.ctx.operations.push({
action: LOG.CONTENT_TAG,
category: LOG.CATEGORY_APPLICATION,
content: content,
});
}
return { code: 0 };
}
/**
* Update the specified data directly
* @param {string} id
* @param {Partial<Content>} params
* @returns void
*/
updateContentItem (id: string, params: Partial<Content>, options: { ctx: FoxCtx; fileId?: string }): void {
options.ctx.transactions.push(Model.content.updateDetailQuery(id, params));
options.ctx.operations.push(
...Service.log.addLogItem(LOG.UPDATE, Object.assign({ id }, params), { fileId: options?.fileId }),
);
}
/**
* Set the specified content to be deleted
* @param {string} contentId
* @returns Promise
*/
async setContentDeleteStatus (
params: TypeStatus,
options: { ctx: FoxCtx },
): Promise<Record<string, number>> {
// Get content details
const contentDetail = await this.getDetailById(params.id);
if (!contentDetail) {
return { code: 1 }; // Invalid content information
}
// If there is a live version, you need to check whether it is referenced by other content
if (params.status && contentDetail.liveVersionNumber) {
const relations = await Service.relation.getContentRelationalByIds(contentDetail.fileId, [params.id]);
if (relations.length > 0) {
return { code: 2 }; // There is referenced relation information
}
}
const versionList = await Service.version.list.getVersionByContentIds([params.id]);
// Set the enabled status, or update the status directly if there is no live version
options.ctx.transactions.push(this.setDeleteStatus(params.id, params.status));
options.ctx.transactions.push(
Service.version.info.batchUpdateDetailQuery({ contentId: params.id }, { deleted: true }),
);
// Save logs
options.ctx.operations.push(
...Service.log.addLogItem(LOG.CONTENT_REMOVE, [contentDetail], { fileId: contentDetail?.fileId }),
...Service.log.addLogItem(LOG.VERSION_REMOVE, versionList, { fileId: contentDetail?.fileId }),
);
return { code: 0 };
}
/**
* Set the delete status of the specified content in batches,
* @param {Content[]} contentList
* @returns void
*/
batchSetContentDeleteStatus (contentList: Content[], options: { ctx: FoxCtx; status?: boolean }): void {
const status = options.status === false ? false : true;
options.ctx.transactions.push(this.setDeleteStatus(_.map(contentList, 'id'), status));
options.ctx.operations.push(...Service.log.addLogItem(LOG.CONTENT_REMOVE, contentList));
}
/**
* Get the resource type from all the parents of content, and get the corresponding application resource details
* @param {AppResource[]} appResource
* @param {Record<string} contentParentObject
* @param {} FolderFileContent[]>
* @returns Record
*/
getContentResourceTypeInfo (
appResource: AppResource[],
contentParentObject: Record<string, FolderFileContent[]>,
): Record<string, AppResource> {
const appResourceObject = _.keyBy(appResource, 'id');
let contentResource: Record<string, AppResource> = {};
for (const contentId in contentParentObject) {
for (const folder of contentParentObject[contentId]) {
folder.tags &&
folder.tags.forEach((tag) => {
if (tag.resourceId) {
contentResource[contentId] = appResourceObject[tag.resourceId] || {};
}
});
if (contentResource[contentId]) {
break;
}
}
}
return contentResource;
}
/**
* Copy content from specified content information
* At the same time copy the version information from the specified content version information
* @param {Content} sourceContentInfo
* @param {DSL} sourceContentVersion
* @param {{relations:Record<string} options
* @param {Record<string} string>;tempRelations
* @param {} string>}
* @returns Record
*/
copyContent (
sourceContentInfo: Content,
sourceContentVersion: DSL,
options: {
ctx: FoxCtx;
relations: Record<string, Record<string, string>>;
tempRelations: Record<string, Record<string, string>>;
setLive?: boolean;
},
): Record<string, Record<string, string>> {
// Create new content page information
const contentId =
options.relations[sourceContentInfo.id]?.newId ||
options.tempRelations[sourceContentInfo.id]?.newId ||
generationId(PRE.CONTENT);
options.relations[sourceContentInfo.id] = {
newId: contentId,
oldName: sourceContentInfo.title,
newName:
options.tempRelations[sourceContentInfo.id]?.title || [sourceContentInfo.title, randStr(4)].join('_'),
};
Service.content.info.create(
{
id: contentId,
title: options.relations[sourceContentInfo.id].newName,
fileId: options.relations[sourceContentInfo.fileId].newId || '',
tags: (sourceContentInfo.tags || []).concat({ copyFrom: sourceContentVersion.id }),
liveVersionNumber: options.setLive ? 1 : 0, // default set the first version to live while copy from store
},
{ ctx: options.ctx },
);
// Create new content version information
options.relations = Service.version.info.copyContentVersion(
sourceContentVersion,
contentId,
Object.assign({ create: true }, options),
);
return options.relations;
}
/**
* get content extension from detail,eg extendId, mockId
* @param contentDetail
* @returns
*/
getContentExtension (contentDetail: Content, extensionName: string[] = ['extendId']) {
let extendInfo: Record<string, any> = {};
(contentDetail?.tags || []).forEach(tag => {
extendInfo = _.merge(extendInfo, _.pick(tag, extensionName));
});
return extendInfo;
}
} | the_stack |
import {collect, deepCopy, Deferred, safeForEach} from "../util/helpers";
import {Disposable, IDisposable, ImmediateDisposable, mkDisposable} from "./disposable";
import {
childResult,
Destroy,
NoUpdate, setToUndefined, setValue,
SetValue,
UpdateKey,
UpdateLike,
UpdateOf, UpdateResult,
valueToUpdate
} from ".";
import {__getProxyTarget, __readOnlyProxyObject} from "./readonly";
export type Observer<S> = (value: S, update: UpdateResult<S>, updateSource: any) => void
export type PreObserver<S> = (value: S) => Observer<S>
export type Updater<S> = (currentState: Readonly<S>) => UpdateOf<S>
/**
* Types for describing state updates
*/
export interface ObservableState<S> extends IDisposable {
state: S
addObserver(fn: Observer<S>, path?: string): IDisposable
addPreObserver(fn: PreObserver<S>, path?: string): IDisposable
observeMapped<T>(mapper: (value: S) => T, fn: (mapped: T) => void, path?: string): IDisposable
}
export interface StateView<S> extends ObservableState<S> {
view<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): StateView<S[K]>
viewOpt<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateView<Exclude<S[K], undefined>>
observeKey<K extends keyof S>(key: K, fn: Observer<S[K]>, subPath?: string): IDisposable
preObserveKey<K extends keyof S>(key: K, fn: PreObserver<S[K]>, subPath?: string): IDisposable
filterSource(filter: (source: any) => boolean): StateView<S>
fork(disposeContext?: IDisposable): StateView<S>
}
export interface OptionalStateView<S> extends ObservableState<S | undefined> {
view<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateView<Exclude<S[K], undefined>>
viewOpt<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateView<Exclude<S[K], undefined>>
observeKey<K extends keyof S>(key: K, fn: Observer<S[K] | undefined>, subPath?: string): IDisposable
preObserveKey<K extends keyof S>(key: K, fn: PreObserver<S[K] | undefined>, subPath?: string): IDisposable
filterSource(filter: (source: any) => boolean): OptionalStateView<S>
fork(disposeContext?: IDisposable): OptionalStateView<S>
}
export interface UpdatableState<S> extends ObservableState<S> {
/**
* Update the state. The update is not guaranteed to have been applied by the time this method returns! (see updateAsync)
*/
update(updates: Updater<S>, updateSource?: any, updatePath?: string): void
/**
* Update the state, returning a Promise which will be completed when the update has been applied and all its observers
* have been notified.
*/
updateAsync(updates: Updater<S>, updateSource?: any, updatePath?: string): Promise<Readonly<S>>
}
export interface StateHandler<S> extends StateView<S>, UpdatableState<S> {
lens<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): StateHandler<S[K]>
lensOpt<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateHandler<Exclude<S[K], undefined>>
updateField<K extends keyof S>(key: K, update: Updater<S[K]>, updateSource?: any, updateSubpath?: string): void
filterSource(filter: (source: any) => boolean): StateHandler<S>
fork(disposeContext?: IDisposable): StateHandler<S>
}
export const StateHandler = {
from<T extends object>(state: T): StateHandler<T> { return new ObjectStateHandler(state) }
}
export interface OptionalStateHandler<S> extends OptionalStateView<S>, UpdatableState<S | undefined> {
lens<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateHandler<Exclude<S[K], undefined>>
lensOpt<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateHandler<Exclude<S[K], undefined>>
updateField<K extends keyof S>(key: K, update: Updater<S[K] | undefined>, updateSource?: any, updateSubpath?: string): void
filterSource(filter: (source: any) => boolean): OptionalStateHandler<S>
fork(disposeContext?: IDisposable): OptionalStateHandler<S>
}
function filterObserver<S>(fn: Observer<S>, filter?: (src: any) => boolean): Observer<S> {
if (!filter)
return fn;
return (value, update, updateSource) => {
if (filter(updateSource)) {
fn(value, update, updateSource)
}
}
}
function filterPreObserver<S>(fn: PreObserver<S>, filter?: (src: any) => boolean): PreObserver<S> {
if (!filter)
return fn;
return pre => {
const obs = fn(pre);
return (value, update, updateSource) => {
if (filter(updateSource)) {
obs(value, update, updateSource)
}
}
}
}
function keyObserver<S, K extends keyof S, V extends S[K] = S[K]>(key: K, fn: Observer<V>, filter?: (src: any) => boolean): Observer<S> {
return (value, result, updateSource) => {
const down = childResult(result, key);
if (!(down.update instanceof Destroy) && down.update !== NoUpdate) {
if (!filter || filter(updateSource)) {
fn(value[key as keyof S] as V, down as UpdateResult<V>, updateSource)
}
}
}
}
function keyPreObserver<S, K extends keyof S, V extends S[K] = S[K]>(key: K, fn: PreObserver<V>, filter?: (src: any) => boolean): PreObserver<S> {
return preS => {
const obs = fn(preS[key as keyof S] as V);
return (value, result, updateSource) => {
const down = childResult(result, key);
if (down && down.update !== NoUpdate) {
if (!filter || filter(updateSource)) {
obs(value[key] as V, down as UpdateResult<V>, updateSource)
}
}
}
}
}
function keyUpdater<S, K extends keyof S>(key: K, updater: Updater<S[K]>): Updater<S> {
return (s: Readonly<S>) => new UpdateKey<S, K>(key, valueToUpdate(updater(s[key])))
}
function combineFilters(first?: (source: any) => boolean, second?: (source: any) => boolean): ((source: any) => boolean) | undefined {
if (first && second) {
return source => first(source) && second(source)
}
return first || second
}
function cleanPath(pathStr: string): string[] {
if (pathStr.length === 0) return []
let path = pathStr.split('.')
if (path[path.length - 1] === '') {
path = path.slice(0, path.length - 1);
}
return path;
}
class ObserverDict<T> {
private children: Record<string, ObserverDict<T>> = {};
private observers: (T & IDisposable)[] = [];
constructor(private path: string[] = []) {}
add(observer: T, path: string): IDisposable {
return this.addAt(observer, cleanPath(path))
}
private addAt(observer: T, path: string[]): IDisposable {
if (path.length === 0) {
const disposable = mkDisposable(observer, () => {
const idx = this.observers.indexOf(disposable);
if (idx >= 0) {
this.observers.splice(idx, 1);
}
});
// NOTE: `unshift` because we iterate through observers backwards
this.observers.unshift(disposable);
return disposable;
} else {
const first = path[0];
if (!this.children[first]) {
this.children[first] = new ObserverDict([...this.path, first]);
}
return this.children[first].addAt(observer, path.slice(1));
}
}
forEach(path: string[], fn: (observer: T) => void): void {
// NOTE: copy path so mutation in forEachAt doesn't affect upstream.
path = [...path];
this.forEachAt(path, fn);
}
private forEachAt(path: string[], fn: (observer: T) => void): void {
// NOTE: iterating through observers backwards because observers sometimes remove themselves from this list
// during iteration.
safeForEach(this.observers, t => {
try {
fn(t)
} catch (e) {
console.error(e);
}
});
if (path.length === 0) {
for (const child of Object.values(this.children)) {
child.forEachAt(path, fn);
}
} else {
const child = path.shift()!;
if (this.children[child]) {
this.children[child].forEachAt(path, fn);
}
}
}
collect<U>(path: string[], fn: (observer: T) => U): U[] {
const result: U[] = [];
this.forEach(path, obs => result.push(fn(obs)));
return result;
}
clear(): void {
this.observers.forEach(obs => obs.tryDispose());
this.observers = [];
}
get length(): number {
let len = this.observers.length;
for (const child of Object.values(this.children)) {
len += child.length;
}
return len;
}
}
export class ObjectStateHandler<S extends object> extends Disposable implements StateHandler<S> {
// internal, mutable state
private mutableState: S;
// private read-only view of state
private readOnlyState: S;
// observers receive the updated state, the update, and the update source and perform side-effects
private observers: ObserverDict<Observer<S>> = new ObserverDict();
// pre-observers receive the previous state; and return function that receive the updated state, the update, and
// the update source, which performs side-effects. This is useful if an observer needs to copy any values from the
// previous state, or decide what to based on the previous state.
private preObservers: ObserverDict<PreObserver<S>> = new ObserverDict();
// public, read-only view of state
get state(): Readonly<S> { return this.readOnlyState }
constructor(state: S, readonly path: string = "", readonly sourceFilter: (source?: any) => boolean = () => true) {
super();
this.mutableState = state;
this.readOnlyState = __readOnlyProxyObject(state);
this.onDispose.then(() => {
this.observers.clear();
this.preObservers.clear();
})
}
private isUpdating: boolean = false;
private updateQueue: [(state: Readonly<S>) => UpdateOf<S>, any, string[], Deferred<Readonly<S>> | undefined][] = [];
protected handleUpdate(updateFn: (state: Readonly<S>) => UpdateOf<S>, updateSource: any, updatePath: string[], promise?: Deferred<Readonly<S>>): void {
const update = valueToUpdate(updateFn(this.state));
if (update === NoUpdate) {
if (promise) {
promise.resolve(this.state)
}
return;
}
const preObservers = this.preObservers.collect(updatePath, obs => obs(this.state));
const updateResult = update.applyMutate(this.mutableState);
const updatedObj = __getProxyTarget(updateResult.newValue);
if (!Object.is(this.mutableState, updatedObj)) {
this.mutableState = updatedObj
this.readOnlyState = __readOnlyProxyObject(this.mutableState);
}
if (updateResult.update !== NoUpdate) {
if (this.sourceFilter(updateSource)) {
const src = updateSource ?? this;
preObservers.forEach(observer => observer(this.state, updateResult, src));
this.observers.forEach(updatePath, observer => observer(this.state, updateResult, src));
}
}
if (promise) {
promise.resolve(this.state);
}
}
private runUpdates() {
if (!this.isUpdating) {
this.isUpdating = true;
try {
while (this.updateQueue.length > 0) {
const updateFields = this.updateQueue.shift();
if (updateFields) {
this.handleUpdate(...updateFields);
}
}
} finally {
this.isUpdating = false;
}
}
}
update(updateFn: (state: S) => UpdateOf<S>, updateSource?: any, updatePath?: string): void {
this.updateQueue.push([updateFn, updateSource, cleanPath(updatePath ?? this.path), undefined]);
this.runUpdates();
}
updateAsync(updateFn: (state: S) => UpdateOf<S>, updateSource?: any, updatePath?: string): Promise<Readonly<S>> {
const promise = new Deferred<Readonly<S>>();
this.updateQueue.push([updateFn, updateSource, cleanPath(updatePath ?? this.path), promise]);
this.runUpdates();
return promise;
}
updateField<K extends keyof S>(key: K, updateFn: Updater<S[K]>, updateSource?: any, updateSubPath?: string): void {
this.update(keyUpdater(key, updateFn), updateSource, `${key}.` + (updateSubPath ?? ''))
}
private addObserverAt(fn: Observer<S>, path: string): IDisposable {
return this.observers.add(fn, path).disposeWith(this);
}
private addPreObserverAt(fn: PreObserver<S>, path: string): IDisposable {
return this.preObservers.add(fn, path).disposeWith(this);
}
addObserver(fn: Observer<S>, path?: string): IDisposable {
return this.addObserverAt(fn, path ?? '');
}
addPreObserver(fn: PreObserver<S>, path?: string): IDisposable {
return this.addPreObserverAt(fn, path ?? '');
}
observeKey<K extends keyof S>(key: K, fn: Observer<S[K]>, subPath?: string): IDisposable {
return this.addObserverAt(
keyObserver(key, fn),
`${key}.` + (subPath ?? '')
)
}
preObserveKey<K extends keyof S>(key: K, fn: PreObserver<S[K]>, subPath?: string): IDisposable {
return this.addPreObserverAt(
keyPreObserver(key, fn),
`${key}.` + (subPath ?? '')
)
}
observeMapped<T>(mapper: (value: S) => T, fn: (mapped: T) => void, path?: string): IDisposable {
return this.addObserver(value => fn(mapper(value)), path)
}
view<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): StateView<S[K]> {
return new KeyLens(this, key, combineFilters(this.sourceFilter, sourceFilter))
}
viewOpt<K extends keyof S>(key : K, sourceFilter?: (source: any) => boolean): OptionalStateView<Exclude<S[K], undefined>> {
return new OptionalKeyLens<S, K>(this as any as OptionalStateHandler<S>, key, combineFilters(this.sourceFilter, sourceFilter))
}
lens<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): StateHandler<S[K]> {
return new KeyLens(this, key, combineFilters(this.sourceFilter, sourceFilter))
}
lensOpt<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateHandler<Exclude<S[K], undefined>> {
return new OptionalKeyLens(this as any as OptionalStateHandler<S>, key, combineFilters(this.sourceFilter, sourceFilter))
}
filterSource(filter: (source: any) => boolean): StateHandler<S> {
return new BaseHandler(this, combineFilters(this.sourceFilter, filter))
}
fork(disposeContext?: IDisposable): StateHandler<S> {
return new BaseHandler(this);
}
get observerCount(): number { return this.observers.length + this.preObservers.length }
}
export class BaseView<S> extends Disposable implements StateView<S> {
constructor(protected parent: StateView<S>, protected readonly sourceFilter?: (source: any) => boolean) {
super();
this.disposeWith(parent);
}
get state(): S { return this.parent.state }
addObserver(fn: Observer<S>, path?: string): IDisposable {
return this.parent.addObserver(filterObserver(fn, this.sourceFilter), path).disposeWith(this);
}
addPreObserver(fn: PreObserver<S>, path?: string): IDisposable {
return this.parent.addPreObserver(filterPreObserver(fn, this.sourceFilter), path).disposeWith(this);
}
observeKey<K extends keyof S>(key: K, fn: Observer<S[K]>, subPath?: string): IDisposable {
return this.parent.observeKey(key, filterObserver(fn, this.sourceFilter), subPath).disposeWith(this);
}
preObserveKey<K extends keyof S>(key: K, fn: PreObserver<S[K]>, subPath?: string): IDisposable {
return this.parent.preObserveKey(key, filterPreObserver(fn, this.sourceFilter), subPath).disposeWith(this);
}
observeMapped<T>(mapper: (value: S) => T, fn: (mapped: T) => void, path?: string): IDisposable {
return this.addObserver(v => fn(mapper(v)), path)
}
view<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): StateView<S[K]> {
return this.parent.view(key, combineFilters(this.sourceFilter, sourceFilter)).disposeWith(this);
}
viewOpt<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateView<Exclude<S[K], undefined>> {
return this.parent.viewOpt(key, combineFilters(this.sourceFilter, sourceFilter)).disposeWith(this);
}
filterSource(filter: (source: any) => boolean): StateView<S> {
return new BaseView(this.parent, combineFilters(this.sourceFilter, filter)).disposeWith(this);
}
fork(disposeContext?: IDisposable): StateView<S> {
const fork = new BaseView(this.parent, this.sourceFilter).disposeWith(this);
return disposeContext ? fork.disposeWith(disposeContext) : fork;
}
}
export class BaseHandler<S> extends BaseView<S> implements StateHandler<S> {
constructor(protected parent: StateHandler<S>, sourceFilter?: (source: any) => boolean) {
super(parent, sourceFilter);
this.disposeWith(parent);
}
get state(): S { return this.parent.state }
addObserver(fn: Observer<S>, path?: string): IDisposable {
return this.parent.addObserver(filterObserver(fn, this.sourceFilter), path).disposeWith(this);
}
addPreObserver(fn: PreObserver<S>, path?: string): IDisposable {
return this.parent.addPreObserver(filterPreObserver(fn, this.sourceFilter), path).disposeWith(this);
}
lens<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): StateHandler<S[K]> {
return this.parent.lens(key, combineFilters(this.sourceFilter, sourceFilter)).disposeWith(this);
}
lensOpt<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateHandler<Exclude<S[K], undefined>> {
return this.parent.lensOpt(key, combineFilters(this.sourceFilter, sourceFilter)).disposeWith(this);
}
observeKey<K extends keyof S>(key: K, fn: Observer<S[K]>, subPath?: string): IDisposable {
return this.parent.observeKey(key, filterObserver(fn, this.sourceFilter), subPath).disposeWith(this);
}
preObserveKey<K extends keyof S>(key: K, fn: PreObserver<S[K]>, subPath?: string): IDisposable {
return this.parent.preObserveKey(key, filterPreObserver(fn, this.sourceFilter), subPath).disposeWith(this);
}
observeMapped<T>(mapper: (value: S) => T, fn: (mapped: T) => void, path?: string): IDisposable {
return this.addObserver(v => fn(mapper(v)), path)
}
update(updateFn: Updater<S>, updateSource?: any, updatePath?: string): void {
return this.parent.update(updateFn, updateSource, updatePath)
}
updateAsync(updateFn: Updater<S>, updateSource?: any, updatePath?: string): Promise<Readonly<S>> {
return this.parent.updateAsync(updateFn, updateSource, updatePath);
}
updateField<K extends keyof S>(key: K, updateFn: Updater<S[K]>, updateSource?: any, updateSubpath?: string): void {
return this.parent.updateField(key, updateFn, updateSource, updateSubpath)
}
view<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): StateView<S[K]> {
return this.parent.view(key, combineFilters(this.sourceFilter, sourceFilter)).disposeWith(this);
}
viewOpt<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateView<Exclude<S[K], undefined>> {
return this.parent.viewOpt(key, combineFilters(this.sourceFilter, sourceFilter)).disposeWith(this);
}
filterSource(filter: (source: any) => boolean): StateHandler<S> {
return new BaseHandler(this.parent, combineFilters(this.sourceFilter, filter)).disposeWith(this);
}
fork(disposeContext?: IDisposable): StateHandler<S> {
const fork = new BaseHandler(this.parent, this.sourceFilter).disposeWith(this);
return disposeContext ? fork.disposeWith(disposeContext) : fork;
}
}
class KeyView<S, K extends keyof S> extends Disposable implements StateView<S[K]> {
constructor(protected parent: StateView<S>, protected key: K, protected sourceFilter?: (source: any) => boolean) {
super();
this.disposeWith(parent);
}
get state(): S[K] {
return this.parent.state[this.key];
}
addObserver(fn: Observer<S[K]>, path?: string): IDisposable {
return this.parent.observeKey(this.key, filterObserver(fn, this.sourceFilter), path).disposeWith(this);
}
addPreObserver(fn: PreObserver<S[K]>, path?: string): IDisposable {
return this.parent.preObserveKey(this.key, filterPreObserver(fn, this.sourceFilter), path).disposeWith(this);
}
observeKey<K1 extends keyof S[K]>(key: K1, fn: Observer<S[K][K1]>, subPath?: string): IDisposable {
return this.parent.observeKey(this.key, keyObserver(key, fn, this.sourceFilter), `${key}.` + (subPath ?? '')).disposeWith(this);
}
preObserveKey<K1 extends keyof S[K]>(key: K1, fn: PreObserver<S[K][K1]>, subPath?: string): IDisposable {
return this.parent.preObserveKey(this.key, keyPreObserver(key, fn, this.sourceFilter), `${key}.` + (subPath ?? '')).disposeWith(this);
}
observeMapped<T>(mapper: (value: S[K]) => T, fn: (mapped: T) => void, path?: string): IDisposable {
return this.addObserver(value => fn(mapper(value)), path)
}
view<K1 extends keyof S[K]>(key: K1, sourceFilter?: (source: any) => boolean): StateView<S[K][K1]> {
return new KeyView<S[K], K1>(this, key, combineFilters(this.sourceFilter, sourceFilter)).disposeWith(this)
}
viewOpt<K1 extends keyof S[K]>(key: K1, sourceFilter?: (source: any) => boolean): OptionalStateView<Exclude<S[K][K1], undefined>> {
return new OptionalKeyLens(this as any as OptionalStateHandler<S[K]>, key, combineFilters(this.sourceFilter, sourceFilter)).disposeWith(this)
}
filterSource(filter: (source: any) => boolean): StateView<S[K]> {
return new KeyView(this.parent, this.key, combineFilters(this.sourceFilter, filter)).disposeWith(this);
}
fork(disposeContext?: IDisposable): StateView<S[K]> {
const fork = new KeyView(this.parent, this.key, this.sourceFilter).disposeWith(this);
return disposeContext ? fork.disposeWith(disposeContext) : fork;
}
}
class KeyLens<S, K extends keyof S> extends KeyView<S, K> implements StateHandler<S[K]> {
constructor(protected parent: StateHandler<S>, key: K, sourceFilter?: (source: any) => boolean) {
super(parent, key, sourceFilter);
this.disposeWith(parent);
}
lens<K1 extends keyof S[K]>(key: K1, sourceFilter?: (source: any) => boolean): StateHandler<S[K][K1]> {
return new KeyLens(this, key, combineFilters(this.sourceFilter, sourceFilter)).disposeWith(this);
}
lensOpt<K1 extends keyof S[K]>(key: K1, sourceFilter?: (source: any) => boolean): OptionalStateHandler<Exclude<S[K][K1], undefined>> {
return new OptionalKeyLens(this as any as OptionalStateHandler<S[K]>, key, combineFilters(this.sourceFilter, sourceFilter)).disposeWith(this)
}
update(updateFn: Updater<S[K]>, updateSource?: any, updatePath?: string) {
return this.parent.updateField(this.key, updateFn, updateSource, updatePath);
}
updateAsync(updateFn: Updater<S[K]>, updateSource?: any, updatePath?: string): Promise<Readonly<S[K]>> {
return this.parent.updateAsync(keyUpdater(this.key, updateFn), updateSource, `${this.key}.` + (updatePath ?? '')).then(
s => s[this.key]
)
}
updateField<K1 extends keyof S[K]>(key: K1, updateFn: Updater<S[K][K1]>, updateSource?: any, updateSubPath?: string) {
return this.parent.updateField(this.key, keyUpdater(key, updateFn), updateSource, `${key}.` + (updateSubPath ?? ''))
}
filterSource(filter: (source: any) => boolean): StateHandler<S[K]> {
return new KeyLens(this.parent, this.key, combineFilters(this.sourceFilter, filter)).disposeWith(this);
}
fork(disposeContext?: IDisposable): StateHandler<S[K]> {
const fork = new KeyLens(this.parent, this.key, this.sourceFilter).disposeWith(this);
return disposeContext ? fork.disposeWith(disposeContext) : fork;
}
}
class OptionalKeyView<S, K extends keyof S, V extends Exclude<S[K], undefined> = Exclude<S[K], undefined>> extends Disposable implements OptionalStateView<V> {
constructor(protected readonly parent: OptionalStateView<S>, protected readonly key: K, protected readonly sourceFilter?: (source: any) => boolean) {
super();
this.disposeWith(parent);
}
get state(): V | undefined {
return this.parent.state !== undefined ? this.parent.state[this.key] as V : undefined;
}
addObserver(fn: Observer<V | undefined>, path?: string): IDisposable {
return (this.parent as StateView<S>).addObserver(
filterObserver(
(parentValue, updateResult, updateSource) => {
if (parentValue !== undefined) {
fn(
parentValue[this.key] as V,
childResult<S, K, V>(updateResult, this.key),
updateSource);
} else {
fn(undefined, {update: Destroy.Instance, newValue: undefined}, updateSource);
}
},
this.sourceFilter
), `${this.key}.` + (path ?? '')).disposeWith(this);
}
addPreObserver(fn: PreObserver<V | undefined>, path?: string): IDisposable {
return (this.parent as StateView<S>).addPreObserver(
filterPreObserver(
pre => {
const obs = fn((pre?.[this.key]) as V | undefined)
return (parentValue, updateResult, updateSource) => {
if (parentValue !== undefined) {
obs(
parentValue[this.key] as V,
childResult<S, K, V>(updateResult, this.key),
updateSource);
} else {
obs(undefined, setToUndefined, updateSource);
}
}
},
this.sourceFilter
), `${this.key}.` + (path ?? '')).disposeWith(this);
}
observeKey<K1 extends keyof V>(childKey: K1, fn: Observer<V[K1] | undefined>, subPath?: string): IDisposable {
return this.parent.addObserver(
filterObserver(
(parentValue, parentResult, updateSource) => {
if (parentValue !== undefined) {
const value: V = parentValue[this.key] as V;
const result: UpdateResult<V> = childResult<S, K, V>(parentResult as UpdateResult<S>, this.key)
if (value !== undefined) {
const childValue: V[K1] = value[childKey];
const childUpdateResult = childResult(result, childKey);
fn(childValue, childUpdateResult, updateSource);
} else {
fn(undefined, setToUndefined, updateSource);
}
} else {
fn(undefined, setToUndefined, updateSource);
}
},
this.sourceFilter
), `${this.key}.${childKey}` + (subPath ?? '')).disposeWith(this)
}
preObserveKey<K1 extends keyof V>(childKey: K1, fn: PreObserver<V[K1] | undefined>, subPath?: string): IDisposable {
return this.parent.addPreObserver(
filterPreObserver(
prev => {
const obs = fn((prev?.[this.key] as V | undefined)?.[childKey]);
return (parentValue, parentResult, updateSource) => {
if (parentValue !== undefined) {
const value: V = parentValue[this.key] as V;
const result: UpdateResult<V> = childResult<S, K, V>(parentResult as UpdateResult<S>, this.key)
if (value !== undefined) {
const childValue: V[K1] = value[childKey]
const childUpdateResult = childResult<V, K1>(result, childKey);
obs(childValue, childUpdateResult, updateSource);
} else {
obs(undefined, setToUndefined, updateSource);
}
} else {
obs(undefined, setToUndefined, updateSource);
}
}
},
this.sourceFilter
), `${this.key}.${childKey}` + (subPath ?? '')).disposeWith(this)
}
observeMapped<T>(mapper: (value: (V | undefined)) => T, fn: (mapped: T) => void, path?: string): IDisposable {
return this.addObserver(value => fn(mapper(value)))
}
view<K1 extends keyof V>(key: K1): OptionalStateView<Exclude<V[K1], undefined>> {
return new OptionalKeyView<V, K1>(this, key).disposeWith(this);
}
viewOpt<K1 extends keyof V>(key: K1): OptionalStateView<Exclude<V[K1], undefined>> {
return new OptionalKeyView<V, K1>(this, key).disposeWith(this);
}
filterSource(filter: (source: any) => boolean): OptionalStateView<V> {
return new OptionalKeyView<S, K, V>(this.parent, this.key, combineFilters(this.sourceFilter, filter)).disposeWith(this);
}
fork(disposeContext?: IDisposable): OptionalStateView<V> {
const fork = new OptionalKeyView<S, K, V>(this.parent, this.key, this.sourceFilter).disposeWith(this);
return disposeContext ? fork.disposeWith(disposeContext) : fork;
}
}
class OptionalKeyLens<S, K extends keyof S, V extends Exclude<S[K], undefined> = Exclude<S[K], undefined>> extends OptionalKeyView<S, K, V> implements OptionalStateHandler<V> {
constructor(protected parent: OptionalStateHandler<S>, key: K, sourceFilter?: (source: any) => boolean) {
super(parent, key, sourceFilter);
this.disposeWith(parent);
}
lens<K1 extends keyof V>(key: K1): OptionalStateHandler<Exclude<V[K1], undefined>> {
return new OptionalKeyLens<V, K1>(this, key).disposeWith(this);
}
lensOpt<K1 extends keyof V>(key: K1): OptionalStateHandler<Exclude<V[K1], undefined>> {
return new OptionalKeyLens<V, K1>(this, key).disposeWith(this);
}
update(updateFn: Updater<V | undefined>, updateSource?: any, updatePath?: string): void {
return this.parent.updateField(this.key, updateFn, updateSource, updatePath);
}
updateAsync(updateFn: Updater<V | undefined>, updateSource?: any, updatePath?: string): Promise<Readonly<V | undefined>> {
return this.parent.updateAsync(keyUpdater(this.key, updateFn as Updater<S[K]>), updateSource, `${this.key}.` + (updatePath ?? '')).then(
maybeS => maybeS !== undefined ? maybeS[this.key] as V | undefined : undefined
)
}
updateField<K1 extends keyof V>(childKey: K1, updateFn: Updater<V[K1] | undefined>, updateSource?: any, updateSubPath?: string): void {
return this.parent.updateField(this.key, keyUpdater<V, K1>(childKey, updateFn as Updater<V[K1]>), updateSource, `${childKey}.` + (updateSubPath ?? ''))
}
filterSource(filter: (source: any) => boolean): OptionalStateHandler<V> {
return new OptionalKeyLens<S, K, V>(this.parent, this.key, combineFilters(this.sourceFilter, filter)).disposeWith(this);
}
fork(disposeContext?: IDisposable): OptionalStateHandler<V> {
const fork = new OptionalKeyLens<S, K, V>(this.parent, this.key, this.sourceFilter).disposeWith(this);
return disposeContext ? fork.disposeWith(disposeContext) : fork;
}
}
export class ProxyStateView<S> extends Disposable implements StateView<S> {
private observers: ([Observer<S>, IDisposable, IDisposable, string | undefined])[] = [];
private preObservers: ([PreObserver<S>, IDisposable, IDisposable, string | undefined])[] = [];
constructor(private parent: StateView<S>) {
super();
}
setParent(parent: StateView<S>) {
const oldState = deepCopy(this.state);
this.parent = parent;
const preObs: Observer<S>[] = [];
safeForEach(this.preObservers, (obs, idx, arr) => {
const [fn, disposer, parentObs, path] = obs;
parentObs.dispose();
if (disposer.isDisposed) {
arr.splice(idx, 1);
} else {
obs[2] = parent.addPreObserver(v => fn(v), path);
preObs.push(fn(oldState));
}
})
// need to notify the observers immediately now, since the "state" is changing
const newState = parent.state;
const updateResult = setValue<S, S>(newState).applyMutate(oldState);
preObs.forEach(obs => obs(newState, updateResult, this))
safeForEach(this.observers, (obs, idx, arr) => {
const [fn, disposer, parentObs, path] = obs;
parentObs.dispose();
if (disposer.isDisposed) {
arr.splice(idx, 1);
} else {
obs[2] = parent.addObserver((v, u, s) => fn(v, u, s), path);
fn(newState, updateResult, this);
}
})
}
get state(): S {
return this.parent.state
};
addObserver(fn: Observer<S>, path?: string): IDisposable {
const disposable = new Disposable().disposeWith(this);
const parentObs = this.parent.addObserver((v, u, s) => fn(v, u, s), path).disposeWith(disposable);
this.observers.push(([fn, disposable, parentObs, path]));
return disposable;
}
addPreObserver(fn: PreObserver<S>, path?: string): IDisposable {
const disposable = new Disposable().disposeWith(this);
const parentObs = this.parent?.addPreObserver(v => fn(v), path).disposeWith(disposable);
this.preObservers.push(([fn, disposable, parentObs, path]));
return disposable;
}
filterSource(filter: (source: any) => boolean): StateView<S> {
return new BaseView<S>(this, filter);
}
fork(disposeContext?: IDisposable): StateView<S> {
const fork = new BaseView<S>(this).disposeWith(this);
return disposeContext ? fork.disposeWith(disposeContext) : fork;
}
// @ts-ignore
observeKey<K extends keyof S>(key: K, fn: Observer<S[K]>, subPath?: string): IDisposable {
return this.addObserver(
keyObserver<S, K, S[K]>(key, fn),
`${key}.` + (subPath ?? '')
);
}
observeMapped<T>(mapper: (value: (S)) => T, fn: (mapped: T) => void, path?: string): IDisposable {
return this.addObserver(value => fn(mapper(value)), path)
}
preObserveKey<K extends keyof S>(key: K, fn: PreObserver<(S)[K]>, subPath?: string): IDisposable {
return this.addPreObserver(
keyPreObserver(key, fn),
`${key}.` + (subPath ?? '')
)
}
view<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): StateView<S[K]> {
return new KeyView(this, key, sourceFilter);
}
viewOpt<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateView<Exclude<(S)[K], undefined>> {
return new OptionalKeyView(this as any as OptionalStateView<S>, key, sourceFilter);
}
}
export class ConstView<S> extends Disposable implements StateView<S> {
constructor(readonly state: S) {
super();
}
addObserver(fn: Observer<S>, path?: string): IDisposable {
return new Disposable().disposeWith(this);
}
addPreObserver(fn: PreObserver<S>, path?: string): IDisposable {
return new Disposable().disposeWith(this);
}
filterSource(filter: (source: any) => boolean): StateView<S> {
return this;
}
fork(disposeContext?: IDisposable): StateView<S> {
if (disposeContext) {
return new ConstView(this.state).disposeWith(disposeContext);
}
return this;
}
observeKey<K extends keyof S>(key: K, fn: Observer<S[K]>, subPath?: string): IDisposable {
return new Disposable().disposeWith(this);
}
observeMapped<T>(mapper: (value: S) => T, fn: (mapped: T) => void, path?: string): IDisposable {
return new Disposable().disposeWith(this);
}
preObserveKey<K extends keyof S>(key: K, fn: PreObserver<S[K]>, subPath?: string): IDisposable {
return new Disposable().disposeWith(this);
}
view<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): StateView<S[K]> {
return new ConstView(this.state[key]).disposeWith(this);
}
viewOpt<K extends keyof S>(key: K, sourceFilter?: (source: any) => boolean): OptionalStateView<Exclude<S[K], undefined>> {
return new ConstView(this.state[key]).disposeWith(this) as any as OptionalStateView<Exclude<S[K], undefined>>;
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.