text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { ChangeDetectorRef, Component, Inject } from '@angular/core';
import {
BehaviorSubject,
combineLatest as observableCombineLatest,
Observable,
Subscription
} from 'rxjs';
import { distinctUntilChanged, filter, map, mergeMap, switchMap, tap } from 'rxjs/operators';
import { SectionModelComponent } from '../models/section.model';
import { hasValue, isNotEmpty, isNotUndefined, isUndefined } from '../../../shared/empty.util';
import { SectionUploadService } from './section-upload.service';
import { CollectionDataService } from '../../../core/data/collection-data.service';
import { GroupDataService } from '../../../core/eperson/group-data.service';
import { ResourcePolicyService } from '../../../core/resource-policy/resource-policy.service';
import { SubmissionUploadsConfigService } from '../../../core/config/submission-uploads-config.service';
import { SubmissionUploadsModel } from '../../../core/config/models/config-submission-uploads.model';
import { SubmissionFormsModel } from '../../../core/config/models/config-submission-forms.model';
import { SectionsType } from '../sections-type';
import { renderSectionFor } from '../sections-decorator';
import { SectionDataObject } from '../models/section-data.model';
import { SubmissionObjectEntry } from '../../objects/submission-objects.reducer';
import { AlertType } from '../../../shared/alert/aletr-type';
import { RemoteData } from '../../../core/data/remote-data';
import { Group } from '../../../core/eperson/models/group.model';
import { SectionsService } from '../sections.service';
import { SubmissionService } from '../../submission.service';
import { Collection } from '../../../core/shared/collection.model';
import { AccessConditionOption } from '../../../core/config/models/config-access-condition-option.model';
import { followLink } from '../../../shared/utils/follow-link-config.model';
import { getFirstSucceededRemoteData } from '../../../core/shared/operators';
export const POLICY_DEFAULT_NO_LIST = 1; // Banner1
export const POLICY_DEFAULT_WITH_LIST = 2; // Banner2
export interface AccessConditionGroupsMapEntry {
accessCondition: string;
groups: Group[];
}
/**
* This component represents a section that contains submission's bitstreams
*/
@Component({
selector: 'ds-submission-section-upload',
styleUrls: ['./section-upload.component.scss'],
templateUrl: './section-upload.component.html',
})
@renderSectionFor(SectionsType.Upload)
export class SubmissionSectionUploadComponent extends SectionModelComponent {
/**
* The AlertType enumeration
* @type {AlertType}
*/
public AlertTypeEnum = AlertType;
/**
* The array containing the keys of file list array
* @type {Array}
*/
public fileIndexes: string[] = [];
/**
* The file list
* @type {Array}
*/
public fileList: any[] = [];
/**
* The array containing the name of the files
* @type {Array}
*/
public fileNames: string[] = [];
/**
* The collection name this submission belonging to
* @type {string}
*/
public collectionName: string;
/**
* Default access conditions of this collection
* @type {Array}
*/
public collectionDefaultAccessConditions: any[] = [];
/**
* Define if collection access conditions policy type :
* POLICY_DEFAULT_NO_LIST : is not possible to define additional access group/s for the single file
* POLICY_DEFAULT_WITH_LIST : is possible to define additional access group/s for the single file
* @type {number}
*/
public collectionPolicyType: number;
/**
* The configuration for the bitstream's metadata form
*/
public configMetadataForm$: Observable<SubmissionFormsModel>;
/**
* List of available access conditions that could be set to files
*/
public availableAccessConditionOptions: AccessConditionOption[]; // List of accessConditions that an user can select
/**
* Is the upload required
* @type {boolean}
*/
public required$ = new BehaviorSubject<boolean>(true);
/**
* Array to track all subscriptions and unsubscribe them onDestroy
* @type {Array}
*/
protected subs: Subscription[] = [];
/**
* Initialize instance variables
*
* @param {SectionUploadService} bitstreamService
* @param {ChangeDetectorRef} changeDetectorRef
* @param {CollectionDataService} collectionDataService
* @param {GroupDataService} groupService
* @param {ResourcePolicyService} resourcePolicyService
* @param {SectionsService} sectionService
* @param {SubmissionService} submissionService
* @param {SubmissionUploadsConfigService} uploadsConfigService
* @param {SectionDataObject} injectedSectionData
* @param {string} injectedSubmissionId
*/
constructor(private bitstreamService: SectionUploadService,
private changeDetectorRef: ChangeDetectorRef,
private collectionDataService: CollectionDataService,
private groupService: GroupDataService,
private resourcePolicyService: ResourcePolicyService,
protected sectionService: SectionsService,
private submissionService: SubmissionService,
private uploadsConfigService: SubmissionUploadsConfigService,
@Inject('sectionDataProvider') public injectedSectionData: SectionDataObject,
@Inject('submissionIdProvider') public injectedSubmissionId: string) {
super(undefined, injectedSectionData, injectedSubmissionId);
}
/**
* Initialize all instance variables and retrieve collection default access conditions
*/
onSectionInit() {
const config$ = this.uploadsConfigService.findByHref(this.sectionData.config, true, false, followLink('metadata')).pipe(
getFirstSucceededRemoteData(),
map((config) => config.payload));
// retrieve configuration for the bitstream's metadata form
this.configMetadataForm$ = config$.pipe(
switchMap((config: SubmissionUploadsModel) =>
config.metadata.pipe(
getFirstSucceededRemoteData(),
map((remoteData: RemoteData<SubmissionFormsModel>) => remoteData.payload)
)
));
this.subs.push(
this.submissionService.getSubmissionObject(this.submissionId).pipe(
filter((submissionObject: SubmissionObjectEntry) => isNotUndefined(submissionObject) && !submissionObject.isLoading),
filter((submissionObject: SubmissionObjectEntry) => isUndefined(this.collectionId) || this.collectionId !== submissionObject.collection),
tap((submissionObject: SubmissionObjectEntry) => this.collectionId = submissionObject.collection),
mergeMap((submissionObject: SubmissionObjectEntry) => this.collectionDataService.findById(submissionObject.collection)),
filter((rd: RemoteData<Collection>) => isNotUndefined((rd.payload))),
tap((collectionRemoteData: RemoteData<Collection>) => this.collectionName = collectionRemoteData.payload.name),
// TODO review this part when https://github.com/DSpace/dspace-angular/issues/575 is resolved
/* mergeMap((collectionRemoteData: RemoteData<Collection>) => {
return this.resourcePolicyService.findByHref(
(collectionRemoteData.payload as any)._links.defaultAccessConditions.href
);
}),
filter((defaultAccessConditionsRemoteData: RemoteData<ResourcePolicy>) =>
defaultAccessConditionsRemoteData.hasSucceeded),
tap((defaultAccessConditionsRemoteData: RemoteData<ResourcePolicy>) => {
if (isNotEmpty(defaultAccessConditionsRemoteData.payload)) {
this.collectionDefaultAccessConditions = Array.isArray(defaultAccessConditionsRemoteData.payload)
? defaultAccessConditionsRemoteData.payload : [defaultAccessConditionsRemoteData.payload];
}
}),*/
mergeMap(() => config$),
).subscribe((config: SubmissionUploadsModel) => {
this.required$.next(config.required);
this.availableAccessConditionOptions = isNotEmpty(config.accessConditionOptions) ? config.accessConditionOptions : [];
this.collectionPolicyType = this.availableAccessConditionOptions.length > 0
? POLICY_DEFAULT_WITH_LIST
: POLICY_DEFAULT_NO_LIST;
this.changeDetectorRef.detectChanges();
}),
// retrieve submission's bitstreams from state
observableCombineLatest(this.configMetadataForm$,
this.bitstreamService.getUploadedFileList(this.submissionId, this.sectionData.id)).pipe(
filter(([configMetadataForm, fileList]: [SubmissionFormsModel, any[]]) => {
return isNotEmpty(configMetadataForm) && isNotUndefined(fileList);
}),
distinctUntilChanged())
.subscribe(([configMetadataForm, fileList]: [SubmissionFormsModel, any[]]) => {
this.fileList = [];
this.fileIndexes = [];
this.fileNames = [];
this.changeDetectorRef.detectChanges();
if (isNotUndefined(fileList) && fileList.length > 0) {
fileList.forEach((file) => {
this.fileList.push(file);
this.fileIndexes.push(file.uuid);
this.fileNames.push(this.getFileName(configMetadataForm, file));
});
}
this.changeDetectorRef.detectChanges();
}
)
);
}
/**
* Return file name from metadata
*
* @param configMetadataForm
* the bitstream's form configuration
* @param fileData
* the file metadata
*/
private getFileName(configMetadataForm: SubmissionFormsModel, fileData: any): string {
const metadataName: string = configMetadataForm.rows[0].fields[0].selectableMetadata[0].metadata;
let title: string;
if (isNotEmpty(fileData.metadata) && isNotEmpty(fileData.metadata[metadataName])) {
title = fileData.metadata[metadataName][0].display;
} else {
title = fileData.uuid;
}
return title;
}
/**
* Get section status
*
* @return Observable<boolean>
* the section status
*/
protected getSectionStatus(): Observable<boolean> {
// if not mandatory, always true
// if mandatory, at least one file is required
return observableCombineLatest(this.required$,
this.bitstreamService.getUploadedFileList(this.submissionId, this.sectionData.id),
(required,fileList: any[]) => {
return (!required || (isNotUndefined(fileList) && fileList.length > 0));
});
}
/**
* Method provided by Angular. Invoked when the instance is destroyed.
*/
onSectionDestroy() {
this.subs
.filter((subscription) => hasValue(subscription))
.forEach((subscription) => subscription.unsubscribe());
}
} | the_stack |
import { easeOut, easeIn } from './timingFunctions'
const slideAnimations = {
// Slides object down to original position
slideDownEnterFast: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateY(-${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateY(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '400ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// Slides object in from top to bottom
slideDownEnterMedium: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateY(-${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateY(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '500ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// Slides object in from top to bottom
slideDownEnterSlow: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateY(-${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateY(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '700ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// Slides object in from top to bottom
slideUpEnterFast: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateY(${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateY(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '400ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// Slides object in from down to up
slideUpEnterMedium: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateY(${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateY(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '500ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// Slides object in from bottom to top
slideUpEnterSlow: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateY(${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateY(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '700ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// ---Horizontal Slide Animations---- //
// Slides object in from right to left
slideLeftEnterFast: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateX(${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateX(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '400ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// Slides object in from right to left
slideLeftEnterMedium: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateX(${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateX(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '500ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// Slides object in from right to left
slideLeftEnterSlow: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateX(${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateX(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '700ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// Slides object in from left to right
slideRightEnterFast: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateX(-${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateX(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '400ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// Slides object in from left to right
slideRightEnterMedium: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateX(-${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateX(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '500ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// Slides object in from left to right
slideRightEnterSlow: {
keyframe: ({ distance }) => ({
'0%': {
transform: `translateX(-${distance})`,
opacity: 0,
},
'100%': {
transform: 'translateX(0px)',
opacity: 1,
},
}),
keyframeParams: { distance: '20px' },
duration: '700ms',
timingFunction: easeOut,
direction: 'forward',
fillMode: 'forwards',
},
// Slide Exit Animation///
slideDownExitFast: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateY(0px)',
opacity: 1,
},
'100%': {
transform: `translateY(${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '400ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
slideDownExitMedium: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateY(0px)',
opacity: 1,
},
'100%': {
transform: `translateY(${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '400ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
slideDownExitSlow: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateY(0px)',
opacity: 1,
},
'100%': {
transform: `translateY(${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '500ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
slideUpExitFast: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateY(0px)',
opacity: 1,
},
'100%': {
transform: `translateY(-${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '300ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
slideUpExitMedium: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateY(0px)',
opacity: 1,
},
'100%': {
transform: `translateY(-${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '400ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
slideUpExitSlow: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateY(0px)',
opacity: 1,
},
'100%': {
transform: `translateY(-${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '500ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
slideRightExitFast: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateX(0px)',
opacity: 1,
},
'100%': {
transform: `translateX(${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '300ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
slideRightExitMedium: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateX(0px)',
opacity: 1,
},
'100%': {
transform: `translateX(${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '400ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
slideRightExitSlow: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateX(0px)',
opacity: 1,
},
'100%': {
transform: `translateX(${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '500ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
slideLeftExitFast: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateX(0px)',
opacity: 1,
},
'100%': {
transform: `translateX(-${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '300ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
slideLeftExitMedium: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateX(0px)',
opacity: 1,
},
'100%': {
transform: `translateX(-${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '400ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
slideLeftExitSlow: {
keyframe: ({ distance }) => ({
'0%': {
transform: 'translateX(0px)',
opacity: 1,
},
'100%': {
transform: `translateX(-${distance})`,
opacity: 0,
},
}),
keyframeParams: { distance: '20px' },
duration: '500ms',
timingFunction: easeIn,
direction: 'forward',
fillMode: 'forwards',
},
}
export default slideAnimations | the_stack |
import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpHeaders, HttpResponse} from '@angular/common/http';
import {Observable, Subject} from 'rxjs';
import * as utpl from 'uri-templates';
import {URITemplate} from 'uri-templates';
import {AppService, RequestHeader} from '../app.service';
import {Link} from '../response-explorer/response-explorer.component';
export enum EventType {FillHttpRequest}
export enum Command {Get, Post, Put, Patch, Delete, Document}
export class HttpRequestEvent {
constructor(public type: EventType, public command: Command,
public uri: string, public jsonSchema?: any, public halFormsTemplate?: any) {
}
}
export class UriTemplateParameter {
constructor(public key: string, public value: string) {
}
}
export class Response {
constructor(public httpResponse: HttpResponse<any>, public httpErrorResponse: HttpErrorResponse) {
}
}
@Injectable({
providedIn: 'root'
})
export class RequestService {
private responseSubject: Subject<Response> = new Subject<Response>();
private responseObservable: Observable<Response> = this.responseSubject.asObservable();
private needInfoSubject: Subject<any> = new Subject<any>();
private needInfoObservable: Observable<any> = this.needInfoSubject.asObservable();
private documentationSubject: Subject<string> = new Subject<string>();
private documentationObservable: Observable<string> = this.documentationSubject.asObservable();
private requestHeaders: HttpHeaders = new HttpHeaders(
{
Accept: 'application/prs.hal-forms+json, application/hal+json, application/json, */*'
});
private customRequestHeaders: RequestHeader[];
constructor(private appService: AppService, private http: HttpClient) {
}
getResponseObservable(): Observable<Response> {
return this.responseObservable;
}
getNeedInfoObservable(): Observable<any> {
return this.needInfoObservable;
}
getDocumentationObservable(): Observable<string> {
return this.documentationObservable;
}
getUri(uri: string) {
if (!uri || uri.trim().length === 0) {
return;
}
this.processCommand(Command.Get, uri);
}
requestUri(uri: string, httpMethod: string, body?: string, contentType?: string) {
let headers = this.requestHeaders;
if (contentType || httpMethod.toLowerCase() === 'post' || httpMethod.toLowerCase() === 'put' || httpMethod.toLowerCase() === 'patch') {
if (contentType) {
headers = headers.set('Content-Type', contentType);
} else {
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
}
} else {
this.appService.setUri(uri);
}
this.http.request(httpMethod, uri, {headers, observe: 'response', body}).subscribe(
(response: HttpResponse<any>) => {
this.responseSubject.next(new Response(response, null));
},
(error: HttpErrorResponse) => {
this.responseSubject.next(new Response(null, error));
}
);
}
processCommand(command: Command, uri: string, halFormsTemplate?: any) {
if (command === Command.Get && !this.isUriTemplated(uri) && !halFormsTemplate) {
this.requestUri(uri, 'GET');
} else if (command === Command.Get || command === Command.Post || command === Command.Put || command === Command.Patch) {
const event = new HttpRequestEvent(EventType.FillHttpRequest, command, uri);
if (halFormsTemplate || command === Command.Get) {
event.halFormsTemplate = halFormsTemplate;
this.needInfoSubject.next(event);
} else {
this.getJsonSchema(event);
}
return;
} else if (command === Command.Delete) {
if (this.isUriTemplated(uri)) {
const uriTemplate: URITemplate = utpl(uri);
uri = uriTemplate.fill({});
}
this.requestUri(uri, 'DELETE');
} else if (command === Command.Document) {
this.documentationSubject.next(uri);
}
}
getJsonSchema(httpRequestEvent: HttpRequestEvent) {
let uri = httpRequestEvent.uri;
if (this.isUriTemplated(uri)) {
const uriTemplate: URITemplate = utpl(uri);
uri = uriTemplate.fill({});
}
this.http.request('HEAD', uri,
{headers: this.requestHeaders, observe: 'response'}).subscribe(
(response: HttpResponse<any>) => {
let hasProfile = false;
const linkHeader = response.headers.get('link');
if (linkHeader) {
const w3cLinks = linkHeader.split(',');
let profileUri;
w3cLinks.forEach((w3cLink) => {
const parts = w3cLink.split(';');
const hrefWrappedWithBrackets = parts[0];
const href = hrefWrappedWithBrackets.slice(1, parts[0].length - 1);
const w3cRel = parts[1];
const relWrappedWithQuotes = w3cRel.split('=')[1];
const rel = relWrappedWithQuotes.slice(1, relWrappedWithQuotes.length - 1);
if (rel.toLowerCase() === 'profile') {
profileUri = href;
}
});
if (profileUri) {
hasProfile = true;
let headers = new HttpHeaders(
{
Accept: 'application/schema+json'
});
if (this.customRequestHeaders) {
for (const requestHeader of this.customRequestHeaders) {
headers = headers.append(requestHeader.key, requestHeader.value);
}
}
this.http.get(profileUri, {headers, observe: 'response'}).subscribe(
(httpResponse: HttpResponse<any>) => {
const jsonSchema = httpResponse.body;
// this would be for removing link relations from the POST, PUT and PATCH editor
//
// Object.keys(jsonSchema.properties).forEach(function (property) {
// if (jsonSchema.properties[property].hasOwnProperty('format') &&
// jsonSchema.properties[property].format === 'uri') {
// delete jsonSchema.properties[property];
// }
// });
// since we use those properties to generate a editor for POST, PUT and PATCH,
// "readOnly" properties should not be displayed
Object.keys(jsonSchema.properties).forEach((property) => {
if (jsonSchema.properties[property].hasOwnProperty('readOnly') &&
jsonSchema.properties[property].readOnly === true) {
delete jsonSchema.properties[property];
}
});
httpRequestEvent.jsonSchema = jsonSchema;
this.needInfoSubject.next(httpRequestEvent);
},
() => {
console.warn('Cannot get JSON schema for: ', profileUri);
this.needInfoSubject.next(httpRequestEvent);
}
);
}
}
if (!hasProfile) {
this.needInfoSubject.next(httpRequestEvent);
}
},
() => {
console.warn('Cannot get JSON schema information for: ', uri);
this.needInfoSubject.next(httpRequestEvent);
}
);
}
setCustomHeaders(requestHeaders: RequestHeader[]) {
this.customRequestHeaders = requestHeaders;
this.requestHeaders = new HttpHeaders();
let addDefaultAcceptHeader = true;
for (const requestHeader of requestHeaders) {
if (requestHeader.key.toLowerCase() === 'accept') {
addDefaultAcceptHeader = false;
}
this.requestHeaders = this.requestHeaders.append(requestHeader.key, requestHeader.value);
}
if (addDefaultAcceptHeader === true) {
this.requestHeaders = this.requestHeaders.append(
'Accept', 'application/prs.hal-forms+json, application/hal+json, application/json, */*');
}
}
getInputType(jsonSchemaType: string, jsonSchemaFormat?: string): string {
switch (jsonSchemaType.toLowerCase()) {
case 'integer':
return 'number';
case 'string':
if (jsonSchemaFormat) {
switch (jsonSchemaFormat.toLowerCase()) {
// The following enables the dat time editor in most browsers
// I have disabled this because the date time formats
// are often very different, so type=text is more flexible
//
// case 'date-time':
// return 'datetime-local';
case 'uri':
return 'url';
}
}
return 'text';
default:
return 'text';
}
}
isUriTemplated(uri: string) {
const uriTemplate = utpl(uri);
return uriTemplate.varNames.length > 0;
}
computeHalFormsOptionsFromLink(property: any) {
if (!(property.options && property.options.link && property.options.link.href)) {
return;
}
let headers = new HttpHeaders().set('Accept', 'application/json');
if (property.options.link.type) {
headers = headers.set('Accept', property.options.link.type);
}
if (this.isUriTemplated(property.options.link.href)) {
const uriTemplate: URITemplate = utpl(property.options.link.href);
property.options.link.href = uriTemplate.fill({});
}
this.http.get(property.options.link.href, {headers, observe: 'response'}).subscribe((response: HttpResponse<any>) => {
property.options.inline = response.body;
const contentType = response.headers.get('content-type');
if (contentType
&& (contentType.startsWith('application/prs.hal-forms+json') || contentType.startsWith('application/hal+json'))
&& response.body._embedded) {
property.options.inline = response.body._embedded[Object.keys(response.body._embedded)[0]];
}
});
}
getHttpOptions(link: Link): void {
let href = link.href;
if(this.isUriTemplated(href)) {
const uriTemplate: URITemplate = utpl(href);
href = uriTemplate.fill({});
}
let headers = new HttpHeaders().set('Accept', '*/*');
this.http.options(href, {headers, observe: 'response'}).subscribe(
(httpResponse: HttpResponse<any>) => {
link.options = httpResponse.headers.get('allow');
},
() => {
console.warn('Cannot get OPTIONS for: ', link);
link.options = 'http-options-error';
}
)
}
} | the_stack |
import { getTextWidth } from './textHelpers';
import { formatStats } from './formatStats';
import { setLegendAccess } from './accessibilityUtils';
import { symbols } from './symbols';
import {
getAccessibleStrokes,
getContrastingStroke,
calculateRelativeLuminance,
calculateLuminance,
visaColorToHex
} from './colors';
import { checkHovered, checkClicked, checkInteraction } from './interaction';
import { select } from 'd3-selection';
import { easeCircleIn } from 'd3-ease';
import 'd3-transition';
export const drawLegend = ({
root,
uniqueID,
width,
height,
colorArr,
baseColorArr,
hideStrokes,
dashPatterns,
scale,
steps,
margin,
padding,
duration,
type,
secondary,
fontSize,
data,
labelKey,
label,
symbol,
format,
hide,
hoverHighlight,
clickHighlight,
groupAccessor,
interactionKeys,
hoverStyle,
clickStyle,
hoverOpacity
}: {
root?: any;
uniqueID?: string;
width?: any;
height?: any;
colorArr?: any;
baseColorArr?: any;
hideStrokes?: boolean;
dashPatterns?: any;
scale?: any;
steps?: any;
margin?: any;
padding?: any;
duration?: any;
type?: any;
secondary?: any;
fontSize?: any;
data?: any;
labelKey?: any;
label?: any;
symbol?: any;
format?: any;
hide?: any;
hoverHighlight?: any;
clickHighlight?: any;
groupAccessor?: string;
interactionKeys?: any;
hoverStyle?: any;
clickStyle?: any;
hoverOpacity?: number;
}) => {
const totalWidth = width + padding.left + padding.right + 5;
const leftOffset = padding.left + margin.left;
const offsetLegend = type === 'scatter' || type === 'key' || type === 'line' || type === 'bar';
const legendWidth = steps ? width / steps : 0;
const legendHeight = 15;
height = hide ? 0 : height + (offsetLegend ? 25 : 5);
const opacity = hide ? 0 : 1;
if (type === 'parallel') {
type = 'line';
}
root.attr('viewBox', '0 0 ' + totalWidth + ' ' + height);
let paddingWrapper = root.select('.legend-padding-wrapper');
if (!root.select('.legend-padding-wrapper').size()) {
paddingWrapper = root.append('g').attr('class', 'legend-padding-wrapper');
}
const symbolMod = !symbol ? 4 : 7;
paddingWrapper.attr(
'transform',
`translate(${(offsetLegend ? leftOffset : 0) + symbolMod},${offsetLegend ? 24 : 4})`
);
switch (type) {
default:
root
.attr('opacity', opacity)
.attr('width', totalWidth)
.attr('height', height)
.attr('style', hide ? 'display: none;' : null)
.attr('transform', `translate(0, 0)`);
const defaultLegend = paddingWrapper.selectAll('.legend.default').data([0].concat(colorArr));
root.selectAll('.key').remove();
root.selectAll('.gradient').remove();
defaultLegend
.enter()
.append('g')
.attr('class', 'legend default')
.merge(defaultLegend)
.attr('transform', (_, i) =>
i === 0 ? `translate(${leftOffset}, 20)` : `translate(${(i - 1) * legendWidth + leftOffset}, 20)`
)
.each((d, i, n) => {
const gridLabel =
i === 0
? formatStats(scale.invertExtent(colorArr[0])[0], format)
: formatStats(scale.invertExtent(d)[1], format);
const labelPosition = i === 0 ? 0 : legendWidth;
const colorGrid = select(n[i])
.selectAll('rect')
.data([d]);
let context = colorGrid
.enter()
.append('rect')
.attr('opacity', 0)
.merge(colorGrid)
.attr('width', legendWidth)
.attr('height', legendHeight)
.attr('x', 0)
.attr('y', 0)
.attr('fill', d);
let exitContext = colorGrid.exit();
const gridText = select(n[i])
.selectAll('text')
.data([d]);
let textContext = gridText
.enter()
.append('text')
.attr('opacity', 0)
.merge(gridText)
.attr('dx', labelPosition)
.attr('dy', '2.5em')
.text(gridLabel);
let textExit = gridText.exit();
if (duration) {
context = context
.transition()
.duration(duration)
.ease(easeCircleIn);
exitContext = exitContext
.transition()
.duration(duration)
.ease(easeCircleIn);
textContext = textContext
.transition()
.duration(duration)
.ease(easeCircleIn);
textExit = textExit
.transition()
.duration(duration)
.ease(easeCircleIn);
}
context.attr('opacity', opacity);
exitContext.attr('opacity', 0).remove();
textContext.attr('opacity', opacity);
textExit.attr('opacity', 0).remove();
});
defaultLegend.exit().remove();
break;
case 'gradient':
const gradientId = new Date().getTime();
// draw legend as a gradient band
root
.attr('width', totalWidth)
.attr('height', height)
.attr('style', hide ? 'display: none;' : null)
.attr('transform', `translate(0, 20)`)
.attr('opacity', opacity);
root.selectAll('.key').remove();
root.selectAll('.default').remove();
const textDiv = paddingWrapper.selectAll('text.gradient').data([0].concat(colorArr));
let textContext = textDiv
.enter()
.append('text')
.attr('class', 'legend-text gradient')
.merge(textDiv)
.attr('transform', (_, i) =>
i === 0 ? `translate(${leftOffset}, 0)` : `translate(${(i - 1) * legendWidth + leftOffset}, 0)`
)
.attr('opacity', 0)
.attr('dx', (_, i) => (i === 0 ? 0 : legendWidth))
.attr('dy', '2.5em')
.text((d, i) =>
i === 0
? formatStats(scale.invertExtent(colorArr[0])[0], format)
: formatStats(scale.invertExtent(d)[1], format)
);
let textExit = textDiv.exit();
if (duration) {
textContext = textContext
.transition()
.duration(duration)
.ease(easeCircleIn);
textExit = textExit
.transition()
.duration(duration)
.ease(easeCircleIn);
}
textContext.attr('opacity', (_, i) => (i === 0 || i === colorArr.length ? opacity : 0));
textExit.attr('opacity', 0).remove();
if (!paddingWrapper.selectAll('.legend').empty()) {
paddingWrapper.selectAll('.legend').remove();
}
const gradientDiv = paddingWrapper.append('g').attr('class', 'legend gradient');
gradientDiv
.append('defs')
.append('linearGradient')
.attr('id', 'mainGradient-' + gradientId)
.selectAll('stop')
.data(colorArr)
.enter()
.append('stop')
.attr('offset', (_, i) => (100 / colorArr.length) * (i + 1) + '%')
.attr('stop-color', d => d);
gradientDiv
.append('rect')
.attr('class', 'legend-gradient')
.attr('x', leftOffset)
.attr('y', 0)
.attr('width', width)
.attr('height', legendHeight)
.attr('style', 'fill: url(#mainGradient-' + gradientId + ')');
break;
case 'key':
let accumWidth = 0;
let yPos = 0;
root
.attr('width', totalWidth)
.attr('height', height)
.attr('opacity', opacity)
.attr('style', hide ? 'display: none;' : null);
const currentKeyLegend = paddingWrapper.selectAll('.legend.key').data(colorArr);
root.selectAll('.default').remove();
root.selectAll('.gradient').remove();
currentKeyLegend
.enter()
.append('g')
.attr('class', 'legend key')
.merge(currentKeyLegend)
.each((d, i, n) => {
const prevLabel =
i === 0
? ''
: label
? label[i - 1]
: formatStats(scale.invertExtent(colorArr[i - 1])[0], format) +
'-' +
formatStats(scale.invertExtent(colorArr[i - 1])[1], format);
accumWidth = i === 0 ? 0 : accumWidth + getTextWidth(prevLabel, fontSize) + 40;
if (accumWidth + getTextWidth(prevLabel, fontSize) > width) {
//wrap legends if the length is larger than chart width
accumWidth = 0;
yPos += fontSize + 10; // line height
}
const keyLabel = label
? label[i]
: formatStats(scale.invertExtent(d)[0], format) + '-' + formatStats(scale.invertExtent(d)[1], format);
const keyDot = select(n[i])
.selectAll('rect')
.data([d]);
let context = keyDot
.enter()
.append('rect')
.attr('opacity', 0)
.merge(keyDot)
.attr('fill', d)
.attr('width', 15)
.attr('height', 15);
let exitContext = keyDot.exit();
const keyText = select(n[i])
.selectAll('text')
.data([keyLabel]);
let textContext = keyText
.enter()
.append('text')
.attr('class', 'key-text')
.attr('opacity', 0)
.merge(keyText)
.attr('dx', '.2em')
.attr('dy', 13)
.text(keyLabel);
let textExit = keyText.exit();
if (duration) {
context = context
.transition()
.duration(duration)
.ease(easeCircleIn);
exitContext = exitContext
.transition()
.duration(duration)
.ease(easeCircleIn);
textContext = textContext
.transition()
.duration(duration)
.ease(easeCircleIn);
textExit = textExit
.transition()
.duration(duration)
.ease(easeCircleIn);
}
context
.attr('x', accumWidth)
.attr('y', yPos)
.attr('opacity', opacity);
exitContext.attr('opacity', 0).remove();
textContext
.attr('x', accumWidth + 20)
.attr('y', yPos)
.attr('opacity', opacity);
textExit.attr('opacity', 0).remove();
});
currentKeyLegend.exit().remove();
break;
case 'line':
let accumWidthLine = 0;
let yPosLine = 0;
let strokeWidth = 3;
const dashIdealSize = [28, 28, 26, 28, 26];
root
.attr('width', totalWidth)
.attr('height', height)
.attr('opacity', 1)
.attr('style', hide ? 'display: none;' : null);
const currentLineLegend = paddingWrapper.selectAll('.legend').data(data);
currentLineLegend
.enter()
.append('g')
.attr('class', 'legend')
.merge(currentLineLegend)
.each((d, i, n) => {
const prevLabel = i === 0 ? '' : label ? label[i - 1] : data[i - 1].key;
const keyLabel = label ? label[i] : d.key;
accumWidthLine = i === 0 ? 0 : accumWidthLine + getTextWidth(prevLabel, fontSize) + 60;
if (accumWidthLine + getTextWidth(keyLabel, fontSize) > width) {
//wrap legends if the length is larger than chart width
accumWidthLine = 0;
yPosLine += fontSize + 10; // line height
}
const keyDot = select(n[i])
.selectAll('line')
.data([d.key]);
let context = keyDot
.enter()
.append('line')
.merge(keyDot)
.style('stroke-width', secondary.includes(d.key) ? strokeWidth - 1 : strokeWidth)
.style('stroke', colorArr[i])
.style(
'stroke-dasharray',
secondary.includes(d.key) ? '2,2' : dashPatterns && i < dashPatterns.length ? dashPatterns[i] : ''
)
.attr('stroke-width', secondary.includes(d.key) ? strokeWidth - 1 : strokeWidth)
.attr('stroke', colorArr[i])
.attr(
'stroke-dasharray',
secondary.includes(d.key) ? '2,2' : dashPatterns && i < dashPatterns.length ? dashPatterns[i] : ''
)
.style('opacity', opacity);
let exitContext = keyDot.exit();
const keyText = select(n[i])
.selectAll('text')
.data([d.key]);
let textContext = keyText
.enter()
.append('text')
.attr('class', 'key-text')
.attr('opacity', 0)
.merge(keyText)
.attr('dx', '.2em')
.attr('dy', 13)
.text(keyLabel);
let textExit = keyText.exit();
if (duration) {
context = context
.transition()
.duration(duration)
.ease(easeCircleIn);
exitContext = exitContext
.transition()
.duration(duration)
.ease(easeCircleIn);
textContext = textContext
.transition()
.duration(duration)
.ease(easeCircleIn);
textExit = textExit
.transition()
.duration(duration)
.ease(easeCircleIn);
}
context
.attr('x1', accumWidthLine)
.attr(
'x2',
accumWidthLine +
(secondary.includes(d.key) ? 30 : dashPatterns && i < dashPatterns.length ? dashIdealSize[i] : 30)
)
.attr('y1', yPosLine + 8)
.attr('y2', yPosLine + 8);
exitContext.attr('opacity', 0).remove();
textContext
.attr(
'x',
accumWidthLine +
5 +
(secondary.includes(d.key) ? 30 : dashPatterns && i < dashPatterns.length ? dashIdealSize[i] : 30)
)
.attr('y', yPosLine)
.attr('opacity', opacity);
textExit.attr('opacity', 0).remove();
});
currentLineLegend.exit().remove();
break;
case 'bar':
let accumWidthBar = 0;
let yPosBar = 0;
root
.attr('width', totalWidth)
.attr('height', height)
.attr('opacity', opacity)
.attr('style', hide ? 'display: none;' : null);
const currentBarLegend = paddingWrapper.selectAll('.legend.bar').data(data);
currentBarLegend
.enter()
.append('g')
.attr('class', 'legend bar')
.merge(currentBarLegend)
.each((d, i, n) => {
const prevLabel =
i === 0
? ''
: label && label[i - 1]
? format
? formatStats(label[i - 1], format)
: label[i - 1]
: format
? formatStats(data[i - 1][labelKey], format)
: data[i - 1][labelKey];
const keyLabel =
label && label[i]
? format
? formatStats(label[i], format)
: label[i]
: format
? formatStats(d[labelKey], format)
: d[labelKey];
accumWidthBar = i === 0 ? 0 : accumWidthBar + getTextWidth(prevLabel, fontSize) + 45;
if (accumWidthBar + getTextWidth(keyLabel, fontSize) > width) {
//wrap legends if the length is larger than chart width
accumWidthBar = 0;
yPosBar += fontSize + 10; // line height
}
const keyDot = select(n[i])
.selectAll('rect')
.data([d[labelKey]]);
let context = keyDot
.enter()
.append('rect')
.attr('class', 'bar-rect')
.attr('opacity', 0)
.merge(keyDot)
.attr('fill', scale ? scale(d[labelKey]) : colorArr[i] || colorArr(d[labelKey]))
.attr('width', 20)
.attr('height', 20);
let exitContext = keyDot.exit();
const keyText = select(n[i])
.selectAll('text')
.data([d[labelKey]]);
let textContext = keyText
.enter()
.append('text')
.attr('class', 'bar-text')
.attr('opacity', 0)
.merge(keyText)
.attr('dx', '.2em')
.attr('dy', 16)
.text(keyLabel);
let textExit = keyText.exit();
if (duration) {
context = context
.transition()
.duration(duration)
.ease(easeCircleIn);
exitContext = exitContext
.transition()
.duration(duration)
.ease(easeCircleIn);
textContext = textContext
.transition()
.duration(duration)
.ease(easeCircleIn);
textExit = textExit
.transition()
.duration(duration)
.ease(easeCircleIn);
}
context
.attr('x', accumWidthBar)
.attr('y', yPosBar)
.attr('opacity', opacity);
exitContext.attr('opacity', 0).remove();
textContext
.attr('x', accumWidthBar + 25)
.attr('y', yPosBar)
.attr('opacity', opacity);
textExit.attr('opacity', 0).remove();
});
currentBarLegend.exit().remove();
break;
case 'scatter':
let accumWidthScatter = 0;
let yPosScatter = 0;
root
.attr('width', totalWidth)
.attr('height', height)
.attr('opacity', opacity)
.attr('style', hide ? 'display: none;' : null);
const currentScatterLegend = paddingWrapper.selectAll('.legend').data(data);
currentScatterLegend
.enter()
.append('g')
.attr('class', 'legend')
.merge(currentScatterLegend)
.each((d, i, n) => {
const prevLabel = i === 0 ? '' : label ? label[i - 1] : data[i - 1].key;
const keyLabel = label ? label[i] : d.key;
accumWidthScatter = i === 0 ? 0 : accumWidthScatter + getTextWidth(prevLabel, fontSize) + 50;
if (accumWidthScatter + getTextWidth(keyLabel, fontSize) > width) {
//wrap legends if the length is larger than chart width
accumWidthScatter = 0;
yPosScatter += fontSize + 10; // line height
}
const keyDot = select(n[i])
.selectAll('path')
.data([d]);
let context = keyDot
.enter()
.append('path')
.attr('opacity', 0)
.merge(keyDot)
.attr('fill', colorArr[i]);
let exitContext = keyDot.exit();
const keyText = select(n[i])
.selectAll('text')
.data([d]);
let textContext = keyText
.enter()
.append('text')
.attr('class', 'key-text')
.attr('opacity', 0)
.merge(keyText)
.attr('dx', '.2em')
.attr('dy', 13)
.text(keyLabel);
let textExit = keyText.exit();
if (duration) {
context = context
.transition()
.duration(duration)
.ease(easeCircleIn);
exitContext = exitContext
.transition()
.duration(duration)
.ease(easeCircleIn);
textContext = textContext
.transition()
.duration(duration)
.ease(easeCircleIn);
textExit = textExit
.transition()
.duration(duration)
.ease(easeCircleIn);
}
context
.attr('transform', `translate(` + (+accumWidthScatter + 4) + `,` + (+yPosScatter + 8) + `) scale(4)`)
.attr('d', symbols[symbol[i] || symbol[0]].general)
.attr('opacity', opacity);
exitContext.attr('opacity', 0).remove();
textContext
.attr('x', accumWidthScatter + 15)
.attr('y', yPosScatter)
.attr('opacity', opacity);
textExit.attr('opacity', 0).remove();
});
currentScatterLegend.exit().remove();
break;
}
if (baseColorArr && !hideStrokes) {
const isArray = Array.isArray(baseColorArr);
root.selectAll('.legend').each((d, i, n) => {
const baseColor =
isArray && baseColorArr.length === 1
? baseColorArr[0]
: isArray
? baseColorArr[i]
: baseColorArr[i] || baseColorArr(d[labelKey]);
if (baseColor) {
const contrast = calculateRelativeLuminance(calculateLuminance(baseColor), 1);
const contrastFriendlyColor = contrast < 3 ? getContrastingStroke(baseColor) : baseColor;
select(n[i].firstElementChild).attr('data-base-color', baseColor);
select(n[i].firstElementChild).attr('stroke', contrastFriendlyColor);
select(n[i].firstElementChild).attr('stroke-width', 1);
}
});
} else if (type !== 'line') {
root
.selectAll('.legend')
.selectAll('*')
.attr('stroke', 'none')
.attr('stroke-width', 0);
}
root.attr('data-type', type || 'default');
root.selectAll('.legend *:first-child').each((_, i, n) => {
const me = select(n[i]);
if (me.attr('fill')) {
me.attr('data-fill', me.attr('fill'));
}
if (me.attr('stroke')) {
me.attr('data-stroke', me.attr('stroke'));
}
if (me.attr('stroke-width')) {
me.attr('data-stroke-width', me.attr('stroke-width'));
}
});
setLegendInteractionState({
root,
uniqueID,
interactionKeys,
groupAccessor,
hoverHighlight,
clickHighlight,
hoverStyle,
clickStyle,
hoverOpacity
});
setLegendAccess(root.node(), uniqueID);
};
export const setLegendInteractionState = ({
root,
uniqueID,
interactionKeys,
groupAccessor,
hoverHighlight,
clickHighlight,
hoverStyle,
clickStyle,
hoverOpacity
}: {
root?: any;
uniqueID?: string;
interactionKeys?: any;
groupAccessor?: string;
hoverHighlight?: any;
clickHighlight?: any;
hoverStyle?: any;
clickStyle?: any;
hoverOpacity?: number;
}) => {
const type = root.attr('data-type');
if (type !== 'gradient') {
root.selectAll('.legend').each((d, i, n) => {
const child = select(n[i].firstElementChild);
const text = select(n[i]).select('text');
const datum = !d.values ? d : d.values[0];
const validLegendInteraction =
groupAccessor && interactionKeys.length === 1 && interactionKeys[0] === groupAccessor;
const hovered = checkHovered(datum, hoverHighlight, interactionKeys) && validLegendInteraction;
const clicked = checkClicked(datum, clickHighlight, interactionKeys) && validLegendInteraction;
const fill = child.attr('data-fill');
const stroke = child.attr('data-stroke');
let resultingStroke = '';
if (fill) {
const clickColor = clickStyle ? visaColorToHex(clickStyle.color) : '';
const hoverColor = hoverStyle ? visaColorToHex(hoverStyle.color) : '';
const resultingFill = clicked ? clickColor || fill : hovered && hoverColor ? hoverColor : fill;
child.attr('fill', resultingFill);
child.style('fill', resultingFill);
const hasStroke = child.attr('stroke');
const baseColor = child.attr('data-base-color');
const resultingClick =
type !== 'scatter'
? [getContrastingStroke(clickColor || baseColor || fill)]
: getAccessibleStrokes(clickColor || baseColor || fill);
const resultingHover =
type !== 'scatter'
? [getContrastingStroke(hoverColor || baseColor || fill)]
: getAccessibleStrokes(hoverColor || baseColor || fill);
resultingStroke = clicked
? resultingClick[1] || resultingClick[0]
: hovered
? resultingHover[1] || resultingHover[0]
: hasStroke
? stroke
: getContrastingStroke(fill);
} else if (stroke) {
const clickColor =
clickStyle && clickStyle.color ? getAccessibleStrokes(visaColorToHex(clickStyle.color)) : [stroke];
const hoverColor =
hoverStyle && hoverStyle.color ? getAccessibleStrokes(visaColorToHex(hoverStyle.color)) : [stroke];
resultingStroke = clicked ? clickColor[1] || clickColor[0] : hovered ? hoverColor[1] || hoverColor[0] : stroke;
}
child.attr('stroke', resultingStroke);
child.style('stroke', resultingStroke);
const baseStrokeWidth = parseFloat(child.attr('data-stroke-width')) || (stroke === 'none' ? 0 : 1);
const strokeWidthDenominator = baseStrokeWidth < 1 ? baseStrokeWidth : 1;
const strokeWidthMultiplier = type !== 'line' ? 1 : 2;
const scale = type !== 'scatter' ? 1 : 4;
child.attr(
'stroke-width',
(clicked
? clickStyle && clickStyle.strokeWidth && strokeWidthDenominator
? (parseFloat(clickStyle.strokeWidth + '') * strokeWidthMultiplier) / strokeWidthDenominator
: baseStrokeWidth
: hovered && hoverStyle && hoverStyle.strokeWidth && strokeWidthDenominator
? (parseFloat(hoverStyle.strokeWidth + '') * strokeWidthMultiplier) / strokeWidthDenominator
: baseStrokeWidth) / scale
);
child.style('stroke-width', child.attr('stroke-width'));
const disableDash = type === 'scatter' || type === 'line';
child.attr(
'stroke-dasharray',
hovered && !clicked && !disableDash ? '8 6' : type !== 'line' ? 'none' : child.attr('stroke-dasharray')
);
child.style('stroke-dasharray', child.attr('stroke-dasharray'));
const opacity = checkInteraction(d, 1, hoverOpacity, hoverHighlight, clickHighlight || [], interactionKeys);
child.attr('opacity', opacity);
text.attr('opacity', !opacity ? 0 : 1);
});
}
}; | the_stack |
/**
* @license Copyright © 2013 onwards, Andrew Whewell
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview Handles the storage of configuration options on the browser side.
*/
namespace VRS
{
export var globalOptions: GlobalOptions = VRS.globalOptions || {};
VRS.globalOptions.configSuppressEraseOldSiteConfig = VRS.globalOptions.configSuppressEraseOldSiteConfig !== undefined ? VRS.globalOptions.configSuppressEraseOldSiteConfig : true; // True if the old site's configuration is not to be erased by the new site. If you set this to false it could lead the new site to be slighty less efficient when sending requests to the server.
/**
* Describes the options that can be passed to the import setting methods on ConfigStorage.
*/
export interface ConfigStorage_ImportOptions
{
overwrite?: boolean;
resetBeforeImport?: boolean;
ignoreLanguage?: boolean;
ignoreSplitters?: boolean;
ignoreCurrentLocation?: boolean;
ignoreAutoSelect?: boolean;
ignoreRequestFeedId?: boolean;
}
/**
* Handles the loading and saving of the site's configuration.
*/
export class ConfigStorage
{
/**
* The leading text for all VRS key names.
*/
private _VRSKeyPrefix = 'VRadarServer-';
/**
* Gets or sets the prefix that distinguishes these options from other options stored for VRS by the browser.
*/
private _Prefix = '';
getPrefix() : string
{
return this._Prefix;
}
setPrefix(prefix: string)
{
this._Prefix = prefix;
}
/**
* Gets the size in bytes of the configuration options stored by the browser.
*/
getStorageSize() : number
{
return $.jStorage.storageSize();
}
/**
* Gets a description of the storage engine used by this object to record configuration options.
*/
getStorageEngine() : string
{
return 'jStorage-' + $.jStorage.currentBackend();
}
/**
* Gets a value indicating that the user has saved settings. Ignores some settings that are auto-saved without
* any user intervention.
*/
getHasSettings() : boolean
{
var result = false;
$.each(this.getAllVirtualRadarKeys(false), function(idx, keyName) {
if(keyName !== 'VRadarServer-#global#-Localise') result = true;
return !result;
});
return result;
}
/**
* Checks that we have local storage available and displays an appropriate warning if we do not.
*/
warnIfMissing()
{
if(!$.jStorage.currentBackend()) {
VRS.pageHelper.showMessageBox(VRS.$$.Warning, VRS.$$.NoLocalStorage);
}
}
/**
* Loads a value from storage.
*/
load(key: string, defaultValue?: any) : any
{
return this.doLoad(key, defaultValue, false);
}
/**
* Loads a value from storage without using the page prefix. Only use for configuration settings that are
* to be saved across every page on the site.
*/
loadWithoutPrefix(key: string, defaultValue?: any) : any
{
return this.doLoad(key, defaultValue, true);
};
private doLoad(key: string, defaultValue?: any, ignorePrefix: boolean = false)
{
key = this.normaliseKey(key, ignorePrefix);
return $.jStorage.get(key, defaultValue);
}
/**
* Saves a value to storage.
*/
save(key: string, value: any)
{
this.doSave(key, value, false);
}
/**
* Saves a value to storage without using the prefix. Use for settings that need to persist across the entire site.
*/
saveWithoutPrefix(key: string, value: any)
{
this.doSave(key, value, true);
}
private doSave(key: string, value: any, ignorePrefix: boolean)
{
key = this.normaliseKey(key, ignorePrefix);
$.jStorage.set(key, value);
}
/**
* Deletes a value from storage.
*/
erase(key: string, ignorePrefix: boolean)
{
key = this.normaliseKey(key, ignorePrefix);
$.jStorage.deleteKey(key);
};
/**
* Removes configuration values stored by previous versions of VRS.
*/
cleanupOldStorage()
{
if(!VRS.globalOptions.configSuppressEraseOldSiteConfig) {
// Remove the cookies used by later versions of VRS.
this.eraseCookie('googleMapOptions');
this.eraseCookie('googleMapHomePin');
this.eraseCookie('flightSimOptions');
this.eraseCookie('reportMapOptions');
// Way way WAY back VRS used to store lots of cookies - zap all of those, just in case
this.eraseCookie('gmOptTraceType');
this.eraseCookie('gmOptMapLatitude');
this.eraseCookie('gmOptMapLongitude');
this.eraseCookie('gmOptMapType');
this.eraseCookie('gmOptMapZoom');
this.eraseCookie('gmOptAutoDeselect');
this.eraseCookie('gmOptAutoSelectClosest');
this.eraseCookie('gmOptRefreshSeconds');
this.eraseCookie('gmOptDisanceInKm');
this.eraseCookie('gmOptShowOutlines');
this.eraseCookie('gmOptPinTextLines');
this.eraseCookie('gmOptcallOutSelected');
this.eraseCookie('gmOptcallOutSelectedVol');
}
}
private eraseCookie(name)
{
var yesterday = new Date(new Date().getTime() + (-1 * 86400000));
document.cookie = name + '=; path=/; expires=' + yesterday.toUTCString();
}
/**
* Mangles the key to avoid clashes with other applications / instances of VRS objects.
*/
normaliseKey(key: string, ignorePrefix: boolean)
{
if(!key) throw 'A storage key must be supplied';
var result = this._VRSKeyPrefix;
result += ignorePrefix ? '#global#-' : this._Prefix ? '#' + this._Prefix + '#-' : '';
result += key;
return result;
}
/**
* Returns an array of every key for every Virtual Radar Server settings held by the browser.
*/
getAllVirtualRadarKeys(stripVrsPrefix: boolean = true) : string[]
{
var result: string[] = [];
var self = this;
var vrsKeyPrefixLength = this._VRSKeyPrefix.length;
$.each($.jStorage.index(), function(idx, key) {
if(VRS.stringUtility.startsWith(key, self._VRSKeyPrefix)) {
var keyName = stripVrsPrefix ? key.substr(vrsKeyPrefixLength) : this;
result.push(String(keyName));
}
});
return result;
}
/**
* Returns the value of a setting stored by the browser using the full key passed across, i.e. without adding
* the user-configured prefix. Note that the global VRS prefix is always added to the key.
*/
getContentWithoutPrefix(key: string) : any
{
return $.jStorage.get(this._VRSKeyPrefix + key, null);
}
/**
* Deletes the value stored at the key without adding the user-configured prefix to the key. Note that the
* global VRS prefix is always added to the key.
*/
removeContentWithoutPrefix(key: string)
{
$.jStorage.deleteKey(this._VRSKeyPrefix + key);
}
/**
* Deletes all stored values.
*/
removeAllContent()
{
var self = this;
$.each(this.getAllVirtualRadarKeys(), function() {
self.removeContentWithoutPrefix(this);
});
}
/**
* Serialises the settings into a string and returns that string.
*/
exportSettings()
{
var keys = this.getAllVirtualRadarKeys(false);
var settings = { ver: 1, values: {} };
$.each(keys, function(idx, key) {
var obj = $.jStorage.get(key, null);
if(obj !== null) settings.values[key] = obj;
});
var json = $.toJSON(settings);
return json;
};
/**
* Takes a serialised settings string, as created by exportSettings, and deserialises it. Overwrites the
* current configuration with the deserialised values.
*/
importSettings(exportString: string, options: ConfigStorage_ImportOptions)
{
options = $.extend({}, <ConfigStorage_ImportOptions> {
overwrite: true,
resetBeforeImport: false,
ignoreLanguage: false,
ignoreSplitters: false,
ignoreCurrentLocation: false,
ignoreAutoSelect: false,
ignoreRequestFeedId: false
}, options);
if(exportString) {
var settings = $.parseJSON(exportString);
if(settings && settings.ver) {
switch(settings.ver) {
case 1:
if(options.resetBeforeImport) {
this.removeAllContent();
}
for(var keyName in settings.values) {
if(settings.values.hasOwnProperty(keyName)) {
if(this.isValidImportKey(keyName, options)) {
var value = settings.values[keyName];
this.adjustImportValues(keyName, value, options);
if(value) {
$.jStorage.set(keyName, value);
}
}
}
}
break;
default:
throw 'These settings were exported from a later version of VRS. They cannot be loaded.';
}
}
}
}
/**
* Returns true if the key name passed across represents a valid import key.
*/
private isValidImportKey(keyName: string, options: ConfigStorage_ImportOptions) : boolean
{
var result = false;
if(keyName && VRS.stringUtility.startsWith(keyName, this._VRSKeyPrefix)) {
if(options.overwrite || $.jStorage.get(keyName, null) === null) {
result = true;
if(result && options.ignoreLanguage && keyName === 'VRadarServer-#global#-Localise') result = false;
if(result && options.ignoreSplitters && VRS.stringUtility.contains(keyName, '#-vrsSplitterPosition-')) result = false;
if(result && options.ignoreCurrentLocation && VRS.stringUtility.contains(keyName, '#-vrsCurrentLocation-')) result = false;
if(result && options.ignoreAutoSelect && VRS.stringUtility.contains(keyName, '#-vrsAircraftAutoSelect-')) result = false;
}
}
return result;
}
/**
* Modifies an imported value to comply with the options passed across.
*/
private adjustImportValues(keyName: string, value: any, options: ConfigStorage_ImportOptions)
{
if(options.ignoreRequestFeedId) {
var isVrsAircraftListFetcherValue = VRS.stringUtility.contains(keyName, '#-vrsAircraftListFetcher-');
if(isVrsAircraftListFetcherValue) {
if(value['requestFeedId'] !== undefined) delete value['requestFeedId'];
}
}
}
}
/**
* The pre-built singleton configuration storage object.
*/
export var configStorage: ConfigStorage = VRS.configStorage || new VRS.ConfigStorage();
} | the_stack |
import { action } from 'mobx';
import { observer } from 'mobx-react';
import React from 'react';
import { MapStyles } from '../styles/MapStyles';
import { GameQueryType } from '../transport/GameQueryType';
import { MapActor, Player, PlayerRace, MapItem } from '../transport/Model';
import { capitalize, formatTime } from '../Util';
import { IGameContext } from './Game';
import { MeterBar } from './MeterBar';
import { TooltipTrigger } from './TooltipTrigger';
export const StatusBar = observer((props: IStatusBarProps) => {
const player = props.context.player;
const actorPanels = new Array<[number, JSX.Element]>();
player.level.actors.forEach((actor: MapActor, id: number) => {
if (actor.isCurrentlyPerceived) {
actorPanels.push([actor.nextActionTick, <ActorPanel
actor={actor}
context={props.context}
key={id} />]);
}
});
const sortedActors = actorPanels.sort((a, b) => a[0] - b[0]).map(a => a[1]);
sortedActors.unshift(<CharacterPanel {...props} key={-1} />);
const itemPanels = new Array<JSX.Element>();
player.level.items.forEach((item: MapItem, id: number) => {
if (item.isCurrentlyPerceived) {
itemPanels.push(<ItemPanel
item={item}
context={props.context}
key={id} />);
}
});
return <div className="statusBar__wrapper">
{sortedActors}
{itemPanels}
</div>;
});
interface IStatusBarProps {
context: IGameContext;
}
@observer
class CharacterPanel extends React.PureComponent<IStatusBarProps, {}> {
@action.bound
showCharacterScreen(event: React.KeyboardEvent<HTMLAnchorElement> | React.MouseEvent<HTMLAnchorElement>) {
if (event.type == 'click' || event.type == 'contextmenu' || (event as React.KeyboardEvent<HTMLAnchorElement>).key == 'Enter') {
this.props.context.showDialog(GameQueryType.PlayerAttributes);
event.preventDefault();
}
}
@action.bound
highlight(event: React.MouseEvent<HTMLDivElement>) {
const player = this.props.context.player;
const mapPlayer = player.level.actors.get(player.id);
if (mapPlayer != undefined) {
player.level.tileClasses[mapPlayer.levelY][mapPlayer.levelX].push('map__tile_highlight');
}
}
@action.bound
clear(event: React.MouseEvent<HTMLDivElement>) {
const player = this.props.context.player;
const mapPlayer = player.level.actors.get(player.id);
if (mapPlayer !== undefined) {
const classes = player.level.tileClasses[mapPlayer.levelY][mapPlayer.levelX]
let index = classes.indexOf('map__tile_highlight');
if (index !== -1) {
classes.splice(index, 1);
}
// Clear any lingering highlights
index = classes.indexOf('map__tile_highlight');
if (index !== -1) {
classes.splice(index, 1);
}
}
}
componentDidUpdate(prevProps: any) {
}
render() {
const player = this.props.context.player;
const styles = MapStyles.Instance;
const playerGlyph = styles.actors['player'];
//TODO: Add status effects
return <div className="statusBar__panel" role="status" onMouseEnter={this.highlight} onMouseLeave={this.clear}>
<div className="statusBar__element">
<PlayerLocation player={player} />
</div>
<div className="statusBar__element">
{playerGlyph.char}: <RaceList player={player} showCharacterScreen={this.showCharacterScreen} />
</div>
<div className="statusBar__element">
<HpBar player={player} />
</div>
<div className="statusBar__element">
<EpBar player={player} />
</div>
<div className="statusBar__element">
<XpBar player={player} />
</div>
</div>;
}
}
@observer
class ActorPanel extends React.PureComponent<IActorPanelProps, {}> {
@action.bound
showActorAttributes(event: React.KeyboardEvent<HTMLAnchorElement> | React.MouseEvent<HTMLAnchorElement>) {
if (event.type === 'click' || event.type === 'contextmenu' || (event as React.KeyboardEvent<HTMLAnchorElement>).key === 'Enter') {
this.props.context.showDialog(GameQueryType.ActorAttributes, this.props.actor.id);
event.preventDefault();
}
}
@action.bound
highlight(event: React.MouseEvent<HTMLDivElement>) {
const actor = this.props.actor;
this.props.context.player.level.tileClasses[actor.levelY][actor.levelX].push('map__tile_highlight');
}
@action.bound
clear(event: React.MouseEvent<HTMLDivElement>) {
const actor = this.props.actor;
const classes = this.props.context.player.level.tileClasses[actor.levelY][actor.levelX];
let index = classes.indexOf('map__tile_highlight');
if (index !== -1) {
classes.splice(index, 1);
}
// Clear any lingering highlights
index = classes.indexOf('map__tile_highlight');
if (index !== -1) {
classes.splice(index, 1);
}
}
render() {
const actor = this.props.actor;
const styles = MapStyles.Instance;
let glyph = styles.actors[actor.baseName];
if (glyph === undefined) {
glyph = Object.assign({ char: actor.baseName[0] }, styles.actors['default']);
}
const action = actor.nextAction.type === null ? "Do nothing" : actor.nextAction.name;
return <div className="statusBar__panel" onMouseEnter={this.highlight} onMouseLeave={this.clear}>
<div className="statusBar__element">
<span style={glyph.style}>{glyph.char}</span>: <ActorName actor={actor} showActorAttributes={this.showActorAttributes} />
{' +'}{formatTime(actor.nextActionTick - this.props.context.player.nextActionTick)} [{action}]
</div>
<div className="statusBar__smallElement">
<ActorHpBar actor={actor} />
</div>
<div className="statusBar__smallElement">
<ActorEpBar actor={actor} />
</div>
{/*TODO: Add status effects*/}
</div>;
}
}
interface IActorPanelProps {
context: IGameContext;
actor: MapActor;
}
const HpBar = observer((props: IPlayerStatusProps) => {
const player = props.player;
let hpClass = 'bg-success';
if (player.hp * 5 <= player.maxHp) {
hpClass = 'bg-danger';
} else if (player.hp * 3 <= player.maxHp) {
hpClass = 'bg-warning';
}
return <MeterBar label={`HP: ${player.hp}/${player.maxHp}`}>
<MeterBar className={hpClass} now={player.hp} max={player.maxHp} />
<MeterBar className="bg-recentHp progress-bar-striped" now={0} max={player.maxHp} />
<MeterBar className="bg-dark" now={player.maxHp - player.hp} max={player.maxHp} />
</MeterBar>;
});
const EpBar = observer((props: IPlayerStatusProps) => {
const player = props.player;
let ep = `EP: ${player.ep}/${player.maxEp - player.reservedEp}`;
if (player.reservedEp !== 0) {
ep += `(${player.maxEp})`;
}
return <MeterBar label={ep}>
<MeterBar className="bg-primary" now={player.ep} max={player.maxEp} />
<MeterBar className="bg-dark" now={player.maxEp - player.ep - player.reservedEp} max={player.maxEp} />
<MeterBar className="bg-secondary" now={player.reservedEp} max={player.maxEp} />
</MeterBar>;
});
const XpBar = observer((props: IPlayerStatusProps) => {
const player = props.player;
return <MeterBar label={`XP: ${player.xP}/${player.nextLevelXP}`}>
<MeterBar className="bg-currentXp" now={player.xP} max={player.nextLevelXP} />
<MeterBar className="bg-dark" now={player.nextLevelXP - player.xP} max={player.nextLevelXP} />
</MeterBar>;
});
interface IPlayerStatusProps {
player: Player;
}
const ActorHpBar = observer((props: IActorStatusProps) => {
const actor = props.actor;
return <MeterBar label={`HP: ${actor.hp}/${actor.maxHp}`}>
<MeterBar className="bg-danger" now={actor.hp} max={actor.maxHp} />
<MeterBar className="bg-dark" now={actor.maxHp - actor.hp} max={actor.maxHp} />
</MeterBar>;
});
const ActorEpBar = observer((props: IActorStatusProps) => {
const actor = props.actor;
return <MeterBar label={`EP: ${actor.ep}/${actor.maxEp}`}>
<MeterBar className="bg-primary" now={actor.ep} max={actor.maxEp} />
<MeterBar className="bg-dark" now={actor.maxEp - actor.ep} max={actor.maxEp} />
</MeterBar>;
});
interface IActorStatusProps {
actor: MapActor;
};
const RaceList = observer((props: IPlayerRacesProps) => {
const player = props.player;
const races = Array.from(player.races.values(), r => <RaceStatus race={r} player={player} key={r.id} />);
return <>
<a tabIndex={1} role="button" onClick={props.showCharacterScreen} onContextMenu={props.showCharacterScreen} onKeyPress={props.showCharacterScreen}>
{player.name}
</a> {races}
</>;
});
interface IPlayerRacesProps extends IPlayerStatusProps {
showCharacterScreen: ((event: React.KeyboardEvent<HTMLAnchorElement> | React.MouseEvent<HTMLAnchorElement>) => void)
};
const RaceStatus = observer(({ race, player }: IRaceStatusProps) => {
const raceString = `${race.shortName}(${race.xpLevel}) `;
let className = '';
if (race.id === player.learningRace.id) {
className = 'font-weight-bold';
}
return <TooltipTrigger
id={`tooltip-race-${race.id}`}
tooltip={capitalize(race.name)}
>
<span className={className}>{raceString}</span>
</TooltipTrigger>;
});
interface IRaceStatusProps extends IPlayerStatusProps {
race: PlayerRace;
}
const ActorName = observer((props: IActorNameProps) => {
const actor = props.actor;
return <a tabIndex={1} role="button" onClick={props.showActorAttributes} onContextMenu={props.showActorAttributes} onKeyPress={props.showActorAttributes}>
<span>{actor.name}</span>
</a>;
});
interface IActorNameProps extends IActorStatusProps {
showActorAttributes: ((event: React.KeyboardEvent<HTMLAnchorElement> | React.MouseEvent<HTMLAnchorElement>) => void);
};
const PlayerLocation = observer((props: IPlayerStatusProps) => {
const player = props.player;
const level = player.level;
let currentTime = <span>{formatTime(player.nextActionTick, true)}</span>;
return <span>{level.branchName}({level.depth}) {currentTime}</span>;
});
@observer
class ItemPanel extends React.PureComponent<IItemPanelProps, {}> {
@action.bound
showItemAttributes(event: React.KeyboardEvent<HTMLAnchorElement> | React.MouseEvent<HTMLAnchorElement>) {
if (event.type === 'click' || event.type === 'contextmenu' || (event as React.KeyboardEvent<HTMLAnchorElement>).key === 'Enter') {
this.props.context.showDialog(GameQueryType.ItemAttributes, this.props.item.id);
event.preventDefault();
}
}
@action.bound
highlight(event: React.MouseEvent<HTMLDivElement>) {
const item = this.props.item;
this.props.context.player.level.tileClasses[item.levelY][item.levelX].push('map__tile_highlight');
}
@action.bound
clear(event: React.MouseEvent<HTMLDivElement>) {
const item = this.props.item;
const classes = this.props.context.player.level.tileClasses[item.levelY][item.levelX];
let index = classes.indexOf('map__tile_highlight');
if (index !== -1) {
classes.splice(index, 1);
}
// Clear any lingering highlights
index = classes.indexOf('map__tile_highlight');
if (index !== -1) {
classes.splice(index, 1);
}
}
render() {
const item = this.props.item;
const styles = MapStyles.Instance;
const glyph = styles.items[item.type];
if (glyph === undefined) {
throw `Item type ${item.type} not supported.`;
}
return <div className="statusBar__panel" onMouseEnter={this.highlight} onMouseLeave={this.clear}>
<div className="statusBar__element">
<span style={glyph.style}>{glyph.char}</span>: <ItemName item={item} showItemAttributes={this.showItemAttributes} />
</div>
</div>;
}
}
interface IItemPanelProps {
context: IGameContext;
item: MapItem;
}
const ItemName = observer((props: IItemNameProps) => {
return <a tabIndex={1} role="button" onClick={props.showItemAttributes} onContextMenu={props.showItemAttributes} onKeyPress={props.showItemAttributes}>
<span>{props.item.name}</span>
</a>;
});
interface IItemNameProps {
item: MapItem;
showItemAttributes: ((event: React.KeyboardEvent<HTMLAnchorElement> | React.MouseEvent<HTMLAnchorElement>) => void);
}; | the_stack |
import { IPython } from "./ipython";
declare var IPython: IPython;
import { Telemetry, ClientInfo } from "./telemetry";
import { Chart } from "chart.js";
import { DisplayableState, addToolbarButton as addToolbarButton, attachDumpMachineToolbar, createNewCanvas, createToolbarContainer, PlotStyle, updateChart } from "./plotting";
import { defineQSharpMode } from "./syntax";
import { draw, Circuit, StyleConfig, STYLES } from "@microsoft/quantum-viz.js";
declare global {
interface Window {
iqsharp: Kernel;
}
}
interface Complex {
Real: number;
Imaginary: number;
Phase: number;
Magnitude: number;
}
class Kernel {
hostingEnvironment: string | undefined;
iqsharpVersion: string | undefined;
telemetryOptOut?: boolean | null;
constructor() {
if (IPython.notebook.kernel.is_connected()) {
this.onStart();
} else {
IPython.notebook.kernel.events.on("kernel_ready.Kernel", args => this.onStart());
}
}
onStart() {
this.requestEcho();
this.requestClientInfo();
this.setupMeasurementHistogramDataListener();
this.setupDebugSessionHandlers();
this.initExecutionPathVisualizer();
}
setupDebugSessionHandlers() {
let activeSessions = new Map<string, {
chart: Chart,
lastState: DisplayableState | null,
plotStyle: PlotStyle
}>();
let update = (debugSession: string, plotStyle: PlotStyle) => {
activeSessions.get(debugSession).plotStyle = plotStyle;
let state = (activeSessions.get(debugSession)).lastState;
if (state !== null) {
updateChart(
activeSessions.get(debugSession).plotStyle,
activeSessions.get(debugSession).chart,
state
);
}
};
IPython.notebook.kernel.register_iopub_handler(
"iqsharp_debug_sessionstart", message => {
console.log("iqsharp_debug_sessionstart message received", message);
let debugSession: string = message.content.debug_session;
let stateDivId: (string | null) = message.content.div_id;
if (stateDivId != null) {
let stateDiv = document.getElementById(stateDivId);
if (stateDiv != null) {
// Create necessary elements so a large chart will scroll
let chartWrapperDiv = document.createElement("div");
chartWrapperDiv.style.overflowX = "scroll";
let innerChartWrapperDiv = document.createElement("div");
innerChartWrapperDiv.style.height = "350px";
stateDiv.appendChild(chartWrapperDiv);
chartWrapperDiv.appendChild(innerChartWrapperDiv);
let { chart: chart } = createNewCanvas(innerChartWrapperDiv);
activeSessions.set(debugSession, {
chart: chart,
lastState: null,
plotStyle: "amplitude-squared"
});
// Create toolbar container and insert at the beginning of the state div
let toolbarContainer = createToolbarContainer("Chart options:");
stateDiv.insertBefore(toolbarContainer, stateDiv.firstChild);
// Create buttons to change plot style
addToolbarButton(toolbarContainer, "Measurement Probability", event => update(debugSession, "amplitude-squared"));
addToolbarButton(toolbarContainer, "Amplitude and Phase", event => update(debugSession, "amplitude-phase"));
addToolbarButton(toolbarContainer, "Real and Imaginary", event => update(debugSession, "real-imag"));
// Create debug toolbar
let debugContainer = createToolbarContainer("Debug controls:");
debugContainer.className = "iqsharp-debug-toolbar";
stateDiv.insertBefore(debugContainer, stateDiv.firstChild);
addToolbarButton(debugContainer, "▶️ Next step", event => this.advanceDebugger(debugSession));
}
}
}
);
IPython.notebook.kernel.register_iopub_handler(
"iqsharp_debug_opstart",
message => {
console.log("iqsharp_debug_opstart message received", message);
let state: DisplayableState = message.content.state;
let debugSession: string = message.content.debug_session;
activeSessions.get(debugSession).lastState = state;
update(debugSession, activeSessions.get(debugSession).plotStyle);
}
);
IPython.notebook.kernel.register_iopub_handler(
"iqsharp_debug_sessionend",
message => {
console.log("iqsharp_debug_sessionend message received", message);
let stateDivId: (string | null) = message.content.div_id;
if (stateDivId != null) {
let stateDiv = document.getElementById(stateDivId);
if (stateDiv != null) {
// Disable any buttons in the debug toolbar
stateDiv.querySelectorAll(".iqsharp-debug-toolbar button").forEach(button => {
(<HTMLInputElement>button).disabled = true;
});
}
}
}
);
}
advanceDebugger(debugSession: string) {
console.log("Sending iqsharp_debug_advance message");
IPython.notebook.kernel.send_shell_message(
"iqsharp_debug_advance",
{ debug_session: debugSession },
{
shell: {
reply: (message) => {
console.log("Got iqsharp_debug_advance reply:", message);
}
}
}
);
}
setupMeasurementHistogramDataListener() {
IPython.notebook.kernel.comm_manager.register_target<{state: DisplayableState}>(
"iqsharp_state_dump",
(comm, message) => {
console.log("iqsharp_state_dump comm session opened", message);
let state = message.content.data.state;
let stateDivId = state.div_id;
if (stateDivId != null) {
let stateDiv = document.getElementById(stateDivId);
if (stateDiv != null) {
let { chart: chart } = createNewCanvas(stateDiv, state);
attachDumpMachineToolbar(chart, state);
}
}
comm.close();
}
);
}
requestEcho() {
let value = "hello!";
let comm = IPython.notebook.kernel.comm_manager.new_comm("iqsharp_echo");
comm.on_msg((message) => {
console.log("Got echo output via comms:", message);
});
comm.on_close((message) => {
console.log("Echo comm closed:", message);
})
comm.send(value);
}
getOriginQueryString() {
return (new URLSearchParams(window.location.search)).get("origin");
}
requestClientInfo() {
// The other thing we will want to do as the kernel starts up is to
// pass along information from the client that would not otherwise be
// available. For example, the browser user agent isn't exposed to the
// kernel by the Jupyter protocol, since the client may not even be in a
// browser at all.
let comm_session = IPython.notebook.kernel.comm_manager.new_comm(
"iqsharp_clientinfo",
{
"user_agent": navigator.userAgent,
"client_language": navigator.language,
"client_host": location.hostname,
"client_origin": this.getOriginQueryString(),
}
);
comm_session.on_msg((message) => {
let client_info = message.content.data;
console.log("clientinfo_reply message", client_info);
this.hostingEnvironment = client_info.hosting_environment;
this.iqsharpVersion = client_info.iqsharp_version;
this.telemetryOptOut = client_info.telemetry_opt_out;
console.log(`Using IQ# version ${this.iqsharpVersion} on hosting environment ${this.hostingEnvironment}.`);
this.initTelemetry();
});
}
initTelemetry() {
if (this.telemetryOptOut) {
console.log("Telemetry is turned-off");
return;
}
const isLocalEnvironment =
location.hostname == "localhost"
|| location.hostname == "127.0.0.1"
|| this.hostingEnvironment == null
|| this.hostingEnvironment == "";
const forceEnableClientTelemetry =
this.hostingEnvironment == "FORCE_ENABLE_CLIENT_TELEMETRY";
if (!forceEnableClientTelemetry && isLocalEnvironment) {
console.log("Client telemetry disabled on local environment");
return;
}
Telemetry.origin = this.getOriginQueryString();
Telemetry.clientInfoAvailable.on((clientInfo: ClientInfo) => {
IPython.notebook.kernel.comm_manager.new_comm(
"iqsharp_clientinfo",
{
"client_country": clientInfo.CountryCode,
"client_id": clientInfo.Id,
"client_isnew": clientInfo.IsNew,
"client_first_origin": clientInfo.FirstOrigin,
}
);
});
Telemetry.initAsync();
}
addCopyListener(elementId: string, data: string) {
document.getElementById(elementId).onclick = async (ev: MouseEvent) => {
await navigator.clipboard.writeText(data);
};
}
initExecutionPathVisualizer() {
IPython.notebook.kernel.register_iopub_handler(
"render_execution_path",
message => {
const {
executionPath,
id,
renderDepth,
style,
}: { executionPath: Circuit; id: string; renderDepth: number; style: string } = message.content;
// Get styles
const userStyleConfig: StyleConfig = STYLES[style] || {};
const container = document.getElementById(id);
if (container != null) {
draw(executionPath, container, userStyleConfig);
}
}
);
}
}
export function onload() {
defineQSharpMode();
window.iqsharp = new Kernel();
console.log("Loaded IQ# kernel-specific extension!");
} | the_stack |
import { handler } from "./list.ts";
import {
cleanupDatabase,
createAPIGatewayProxyEventV2,
createContext,
} from "../../utils/test_utils.ts";
import { assert, assertEquals } from "../../test_deps.ts";
import { Database } from "../../utils/database.ts";
const database = new Database(Deno.env.get("MONGO_URI")!);
Deno.test({
name: "`/modules` success",
async fn() {
try {
for (let i = 0; i < 5; i++) {
await database.saveModule({
name: `ltest${i}`,
description: "ltest repo",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
star_count: i,
type: "github",
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
}
const res = await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {}),
createContext(),
);
assertEquals(
res,
{
body:
'{"success":true,"data":{"total_count":5,"options":{"limit":20,"page":1,"sort":"stars"},"results":[{"name":"ltest4","description":"ltest repo","star_count":4},{"name":"ltest3","description":"ltest repo","star_count":3},{"name":"ltest2","description":"ltest repo","star_count":2},{"name":"ltest1","description":"ltest repo","star_count":1},{"name":"ltest0","description":"ltest repo","star_count":0}]}}',
headers: {
"content-type": "application/json",
},
statusCode: 200,
},
);
assertEquals(
await handler(
createAPIGatewayProxyEventV2("GET", "/modules?simple=1", {
queryStringParameters: {
simple: "1",
},
}),
createContext(),
),
{
body: '["ltest0","ltest1","ltest2","ltest3","ltest4"]',
headers: {
"cache-control": "max-age=60, must-revalidate",
"content-type": "application/json",
},
statusCode: 200,
},
);
assertEquals(
await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
page: "2",
limit: "2",
},
}),
createContext(),
),
{
body:
'{"success":true,"data":{"total_count":5,"options":{"limit":2,"page":2,"sort":"stars"},"results":[{"name":"ltest2","description":"ltest repo","star_count":2},{"name":"ltest1","description":"ltest repo","star_count":1}]}}',
headers: {
"content-type": "application/json",
},
statusCode: 200,
},
);
assertEquals(
await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
page: "5",
limit: "2",
},
}),
createContext(),
),
{
body:
'{"success":true,"data":{"total_count":5,"options":{"limit":2,"page":5,"sort":"stars"},"results":[]}}',
headers: {
"content-type": "application/json",
},
statusCode: 200,
},
);
} finally {
await cleanupDatabase(database);
}
},
});
Deno.test({
name: "`/modules` limit & page out of bounds",
async fn() {
try {
for (let i = 0; i < 5; i++) {
await database.saveModule({
name: `ltest${i}`,
description: "ltest repo",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
star_count: i,
type: "github",
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
}
assertEquals(
await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
page: "0",
},
}),
createContext(),
),
{
body:
'{"success":false,"error":"the page number must not be lower than 1"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
},
);
assertEquals(
await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
page: "-1",
},
}),
createContext(),
),
{
body:
'{"success":false,"error":"the page number must not be lower than 1"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
},
);
assertEquals(
await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
limit: "0",
},
}),
createContext(),
),
{
body:
'{"success":false,"error":"the limit may not be larger than 100 or smaller than 1"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
},
);
assertEquals(
await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
limit: "-1",
},
}),
createContext(),
),
{
body:
'{"success":false,"error":"the limit may not be larger than 100 or smaller than 1"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
},
);
assertEquals(
await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
limit: "101",
},
}),
createContext(),
),
{
body:
'{"success":false,"error":"the limit may not be larger than 100 or smaller than 1"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
},
);
} finally {
await cleanupDatabase(database);
}
},
});
Deno.test({
name: "`/modules` sort order",
async fn() {
try {
for (let i = 0; i < 5; i++) {
await database.saveModule({
name: `ltest${i}`,
description: "ltest repo",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
star_count: i, // varying number of stars
type: "github",
is_unlisted: false,
created_at: new Date(2020, 1, i),
} // varying creation dates
);
}
let res = await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
limit: "1",
},
}),
createContext(),
);
// default value
assertEquals(
res,
{
body:
'{"success":true,"data":{"total_count":5,"options":{"limit":1,"page":1,"sort":"stars"},"results":[{"name":"ltest4","description":"ltest repo","star_count":4}]}}',
headers: {
"content-type": "application/json",
},
statusCode: 200,
},
);
res = await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
limit: "1",
sort: "stars",
},
}),
createContext(),
);
// star count
assertEquals(
res,
{
body:
'{"success":true,"data":{"total_count":5,"options":{"limit":1,"page":1,"sort":"stars"},"results":[{"name":"ltest4","description":"ltest repo","star_count":4}]}}',
headers: {
"content-type": "application/json",
},
statusCode: 200,
},
);
res = await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
limit: "1",
sort: "oldest",
},
}),
createContext(),
);
// oldest modules
assertEquals(
res,
{
body:
'{"success":true,"data":{"total_count":5,"options":{"limit":1,"page":1,"sort":"oldest"},"results":[{"name":"ltest0","description":"ltest repo","star_count":0}]}}',
headers: {
"content-type": "application/json",
},
statusCode: 200,
},
);
res = await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
limit: "1",
sort: "newest",
},
}),
createContext(),
);
// newest modules
assertEquals(
res,
{
body:
'{"success":true,"data":{"total_count":5,"options":{"limit":1,"page":1,"sort":"newest"},"results":[{"name":"ltest4","description":"ltest repo","star_count":4}]}}',
headers: {
"content-type": "application/json",
},
statusCode: 200,
},
);
} finally {
await cleanupDatabase(database);
}
},
});
Deno.test({
name: "`/modules` random sort order",
async fn() {
try {
for (let i = 0; i < 5; i++) {
await database.saveModule({
name: `ltest${i}`,
description: "ltest repo",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
star_count: i,
type: "github",
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
let res = await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
sort: "random",
},
}),
createContext(),
// deno-lint-ignore no-explicit-any
) as any;
let body = JSON.parse(res.body);
assert(res);
assertEquals(res.statusCode, 200);
assertEquals(
body.data?.options,
{ "limit": 20, "page": 1, "sort": "random" },
);
res = await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
page: "2",
query: "foo",
sort: "random",
},
}),
createContext(),
// deno-lint-ignore no-explicit-any
) as any;
body = JSON.parse(res.body);
assert(res);
assertEquals(res.statusCode, 200);
assertEquals(
body.data?.options,
{ "limit": 20, "page": 1, "sort": "random" },
);
}
} finally {
await cleanupDatabase(database);
}
},
});
Deno.test({
name: "`/modules` unknow sort order",
async fn() {
try {
for (let i = 0; i < 5; i++) {
await database.saveModule({
name: `ltest${i}`,
description: "ltest repo",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
star_count: i,
type: "github",
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
}
assertEquals(
await handler(
createAPIGatewayProxyEventV2("GET", "/modules", {
queryStringParameters: {
sort: "foobar",
},
}),
createContext(),
),
{
body:
'{"success":false,"error":"the sort order must be one of stars, newest, oldest, random"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
},
);
} finally {
await cleanupDatabase(database);
}
},
}); | the_stack |
import { reportError } from 'app/client/models/AppModel';
import { ColumnRec, DocModel, TableRec, ViewSectionRec } from 'app/client/models/DocModel';
import { linkId, NoLink } from 'app/client/ui/selectBy';
import { getWidgetTypes, IWidgetType } from 'app/client/ui/widgetTypes';
import { bigPrimaryButton } from "app/client/ui2018/buttons";
import { colors, vars } from "app/client/ui2018/cssVars";
import { icon } from "app/client/ui2018/icons";
import { spinnerModal } from 'app/client/ui2018/modals';
import { isLongerThan, nativeCompare } from "app/common/gutil";
import { computed, Computed, Disposable, dom, domComputed, fromKo, IOption, select} from "grainjs";
import { makeTestId, Observable, onKeyDown, styled} from "grainjs";
import without = require('lodash/without');
import Popper from 'popper.js';
import { IOpenController, popupOpen, setPopupToCreateDom } from 'popweasel';
type TableId = number|'New Table'|null;
// Describes a widget selection.
export interface IPageWidget {
// The widget type
type: IWidgetType;
// The table (one of the listed tables or 'New Table')
table: TableId;
// Whether to summarize the table (not available for "New Table").
summarize: boolean;
// some of the listed columns to use to summarize the table.
columns: number[];
// link
link: string;
// the page widget section id (should be 0 for a to-be-saved new widget)
section: number;
}
// Creates a IPageWidget from a ViewSectionRec.
export function toPageWidget(section: ViewSectionRec): IPageWidget {
const link = linkId({
srcSectionRef: section.linkSrcSectionRef.peek(),
srcColRef: section.linkSrcColRef.peek(),
targetColRef: section.linkTargetColRef.peek()
});
return {
type: section.parentKey.peek() as IWidgetType,
table: section.table.peek().summarySourceTable.peek() || section.tableRef.peek(),
summarize: Boolean(section.table.peek().summarySourceTable.peek()),
columns: section.table.peek().columns.peek().peek()
.filter((col) => col.summarySourceCol.peek())
.map((col) => col.summarySourceCol.peek()),
link, section: section.id.peek()
};
}
export interface IOptions extends ISelectOptions {
// the initial selected value, we call the function when the popup get triggered
value?: () => IPageWidget;
// placement, directly passed to the underlying Popper library.
placement?: Popper.Placement;
}
const testId = makeTestId('test-wselect-');
// The picker disables some choices that do not make much sense. This function return the list of
// compatible types given the tableId and whether user is creating a new page or not.
function getCompatibleTypes(tableId: TableId, isNewPage: boolean|undefined): IWidgetType[] {
if (tableId !== 'New Table') {
return ['record', 'single', 'detail', 'chart', 'custom'];
} else if (isNewPage) {
// New view + new table means we'll be switching to the primary view.
return ['record'];
} else {
// The type 'chart' makes little sense when creating a new table.
return ['record', 'single', 'detail'];
}
}
// Whether table and type make for a valid selection whether the user is creating a new page or not.
function isValidSelection(table: TableId, type: IWidgetType, isNewPage: boolean|undefined) {
return table !== null && getCompatibleTypes(table, isNewPage).includes(type);
}
export type ISaveFunc = (val: IPageWidget) => Promise<void>;
// Delay in milliseconds, after a user click on the save btn, before we start showing a modal
// spinner. If saving completes before this time elapses (which is likely to happen for regular
// table) we don't show the modal spinner.
const DELAY_BEFORE_SPINNER_MS = 500;
// Attaches the page widget picker to elem to open on 'click' on the left.
export function attachPageWidgetPicker(elem: HTMLElement, docModel: DocModel, onSave: ISaveFunc,
options: IOptions = {}) {
// Overrides .placement, this is needed to enable the page widget to update position when user
// expand the `Group By` panel.
// TODO: remove .placement from the options of this method (note: breaking buildPageWidgetPicker
// into two steps, one for model creation and the other for building UI, seems promising. In
// particular listening to value.summarize to update popup position could be done directly in
// code).
options.placement = 'left';
const domCreator = (ctl: IOpenController) => buildPageWidgetPicker(ctl, docModel, onSave, options);
setPopupToCreateDom(elem, domCreator, {
placement: 'left',
trigger: ['click'],
attach: 'body',
boundaries: 'viewport'
});
}
// Open page widget widget picker on the right of element.
export function openPageWidgetPicker(elem: HTMLElement, docModel: DocModel, onSave: ISaveFunc,
options: IOptions = {}) {
popupOpen(elem, (ctl) => buildPageWidgetPicker(
ctl, docModel, onSave, options
), { placement: 'right' });
}
// Builds a picker to stick into the popup. Takes care of setting up the initial selected value and
// bind various events to the popup behaviours: close popup on save, gives focus to the picker,
// binds cancel and save to Escape and Enter keydown events. Also takes care of preventing the popup
// to overlay the trigger element (which could happen when the 'Group By' panel is expanded for the
// first time). When saving is taking time, show a modal spinner (see DELAY_BEFORE_SPINNER_MS).
export function buildPageWidgetPicker(
ctl: IOpenController,
docModel: DocModel,
onSave: ISaveFunc,
options: IOptions = {}) {
const tables = fromKo(docModel.allTables.getObservable());
const columns = fromKo(docModel.columns.createAllRowsModel('parentPos').getObservable());
// default value for when it is omitted
const defaultValue: IPageWidget = {
type: 'record',
table: null, // when creating a new widget, let's initially have no table selected
summarize: false,
columns: [],
link: NoLink,
section: 0,
};
// get initial value and setup state for the picker.
const initValue = options.value && options.value() || defaultValue;
const value: IWidgetValueObs = {
type: Observable.create(ctl, initValue.type),
table: Observable.create(ctl, initValue.table),
summarize: Observable.create(ctl, initValue.summarize),
columns: Observable.create(ctl, initValue.columns),
link: Observable.create(ctl, initValue.link),
section: Observable.create(ctl, initValue.section)
};
// calls onSave and closes the popup. Failure must be handled by the caller.
async function onSaveCB() {
ctl.close();
const type = value.type.get();
const savePromise = onSave({
type,
table: value.table.get(),
summarize: value.summarize.get(),
columns: sortedAs(value.columns.get(), columns.get().map((col) => col.id.peek())),
link: value.link.get(),
section: value.section.get(),
});
// If savePromise throws an error, before or after timeout, we let the error propagate as it
// should be handle by the caller.
if (await isLongerThan(savePromise, DELAY_BEFORE_SPINNER_MS)) {
const label = getWidgetTypes(type).label;
await spinnerModal(`Building ${label} widget`, savePromise);
}
}
// whether the current selection is valid
function isValid() {
return isValidSelection(value.table.get(), value.type.get(), options.isNewPage);
}
// Summarizing a table causes the 'Group By' panel to expand on the right. To prevent it from
// overlaying the trigger, we bind an update of the popup to it when it is on the left of the
// trigger.
// WARN: This does not work when the picker is triggered from a menu item because the trigger
// element does not exist anymore at this time so calling update will misplace the popup. However,
// this is not a problem at the time or writing because the picker is never placed at the left of
// a menu item (currently picker is only placed at the right of a menu item and at the left of a
// basic button).
if (options.placement && options.placement === 'left') {
ctl.autoDispose(value.summarize.addListener((val, old) => val && ctl.update()));
}
// dom
return cssPopupWrapper(
dom.create(PageWidgetSelect, value, tables, columns, onSaveCB, options),
// gives focus and binds keydown events
(elem: any) => { setTimeout(() => elem.focus(), 0); },
onKeyDown({
Escape: () => ctl.close(),
Enter: () => isValid() && onSaveCB()
})
);
}
// Same as IWidgetValue but with observable values
export type IWidgetValueObs = {
[P in keyof IPageWidget]: Observable<IPageWidget[P]>;
};
export interface ISelectOptions {
// the button's label
buttonLabel?: string;
// Indicates whether the section builder is in a new view
isNewPage?: boolean;
// A callback to provides the links that are available to a page widget. It is called any time the
// user changes in the selected page widget (type, table, summary ...) and we update the "SELECT
// BY" dropdown with the result list of options. The "SELECT BY" dropdown is hidden if omitted.
selectBy?: (val: IPageWidget) => Array<IOption<string>>;
}
// the list of widget types in the order they should be listed by the widget.
const sectionTypes: IWidgetType[] = [
'record', 'single', 'detail', 'chart', 'custom'
];
// Returns dom that let a user select a page widget. User can select a widget type (id: 'grid',
// 'card', ...), one of `tables` and optionally some of the `columns` of the selected table if she
// wants to generate a summary. Clicking the `Add ...` button trigger `onSave()`. Note: this is an
// internal method used by widgetPicker, it is only exposed for testing reason.
export class PageWidgetSelect extends Disposable {
// an observable holding the list of options of the `select by` dropdown
private _selectByOptions = this._options.selectBy ?
Computed.create(this, (use) => {
// TODO: it is unfortunate to have to convert from IWidgetValueObs to IWidgetValue. Maybe
// better to change this._value to be Observable<IWidgetValue> instead.
const val = {
type: use(this._value.type),
table: use(this._value.table),
summarize: use(this._value.summarize),
columns: use(this._value.columns),
// should not have a dependency on .link
link: this._value.link.get(),
section: use(this._value.section),
};
return this._options.selectBy!(val);
}) :
null;
private _isNewTableDisabled = Computed.create(this, this._value.type, (use, t) => !isValidSelection(
'New Table', t, this._options.isNewPage));
constructor(
private _value: IWidgetValueObs,
private _tables: Observable<TableRec[]>,
private _columns: Observable<ColumnRec[]>,
private _onSave: () => Promise<void>,
private _options: ISelectOptions = {}
) { super(); }
public buildDom() {
return cssContainer(
testId('container'),
cssBody(
cssPanel(
header('Select Widget'),
sectionTypes.map((value) => {
const {label, icon: iconName} = getWidgetTypes(value);
const disabled = computed(this._value.table, (use, tid) => this._isTypeDisabled(value, tid));
return cssEntry(
dom.autoDispose(disabled),
cssTypeIcon(iconName),
label,
dom.on('click', () => !disabled.get() && this._selectType(value)),
cssEntry.cls('-selected', (use) => use(this._value.type) === value),
cssEntry.cls('-disabled', disabled),
testId('type'),
);
}),
),
cssPanel(
testId('data'),
header('Select Data'),
cssEntry(
cssIcon('TypeTable'), 'New Table',
// prevent the selection of 'New Table' if it is disabled
dom.on('click', (ev) => !this._isNewTableDisabled.get() && this._selectTable('New Table')),
cssEntry.cls('-selected', (use) => use(this._value.table) === 'New Table'),
cssEntry.cls('-disabled', this._isNewTableDisabled),
testId('table')
),
dom.forEach(this._tables, (table) => dom('div',
cssEntryWrapper(
cssEntry(cssIcon('TypeTable'), cssLabel(dom.text(table.tableId)),
dom.on('click', () => this._selectTable(table.id())),
cssEntry.cls('-selected', (use) => use(this._value.table) === table.id()),
testId('table-label')
),
cssPivot(
cssBigIcon('Pivot'),
cssEntry.cls('-selected', (use) => use(this._value.summarize) && use(this._value.table) === table.id()),
dom.on('click', (ev, el) => this._selectPivot(table.id(), el as HTMLElement)),
testId('pivot'),
),
testId('table'),
)
)),
),
cssPanel(
header('Group by'),
dom.hide((use) => !use(this._value.summarize)),
domComputed(
(use) => use(this._columns)
.filter((col) => !col.isHiddenCol() && col.parentId() === use(this._value.table)),
(cols) => cols ?
dom.forEach(cols, (col) =>
cssEntry(cssIcon('FieldColumn'), cssFieldLabel(dom.text(col.label)),
dom.on('click', () => this._toggleColumnId(col.id())),
cssEntry.cls('-selected', (use) => use(this._value.columns).includes(col.id())),
testId('column')
)
) :
null
),
),
),
cssFooter(
cssFooterContent(
// If _selectByOptions exists and has more than then "NoLinkOption", show the selector.
dom.maybe((use) => this._selectByOptions && use(this._selectByOptions).length > 1, () => [
cssSmallLabel('SELECT BY'),
dom.update(cssSelect(this._value.link, this._selectByOptions!),
testId('selectby'))
]),
dom('div', {style: 'flex-grow: 1'}),
bigPrimaryButton(
// TODO: The button's label of the page widget picker should read 'Close' instead when
// there are no changes.
this._options.buttonLabel || 'Add to Page',
dom.prop('disabled', (use) => !isValidSelection(
use(this._value.table), use(this._value.type), this._options.isNewPage)
),
dom.on('click', () => this._onSave().catch(reportError)),
testId('addBtn'),
),
),
),
);
}
private _closeSummarizePanel() {
this._value.summarize.set(false);
this._value.columns.set([]);
}
private _openSummarizePanel() {
this._value.summarize.set(true);
}
private _selectType(t: IWidgetType) {
this._value.type.set(t);
}
private _selectTable(tid: TableId) {
if (tid !== this._value.table.get()) {
this._value.link.set(NoLink);
}
this._value.table.set(tid);
this._closeSummarizePanel();
}
private _isSelected(el: HTMLElement) {
return el.classList.contains(cssEntry.className + '-selected');
}
private _selectPivot(tid: TableId, pivotEl: HTMLElement) {
if (this._isSelected(pivotEl)) {
this._closeSummarizePanel();
} else {
if (tid !== this._value.table.get()) {
this._value.columns.set([]);
this._value.table.set(tid);
this._value.link.set(NoLink);
}
this._openSummarizePanel();
}
}
private _toggleColumnId(cid: number) {
const ids = this._value.columns.get();
const newIds = ids.includes(cid) ? without(ids, cid) : [...ids, cid];
this._value.columns.set(newIds);
}
private _isTypeDisabled(type: IWidgetType, table: TableId) {
if (table === null) {
return false;
}
return !getCompatibleTypes(table, this._options.isNewPage).includes(type);
}
}
function header(label: string) {
return cssHeader(dom('h4', label), testId('heading'));
}
const cssContainer = styled('div', `
--outline: 1px solid rgba(217,217,217,0.60);
max-height: 386px;
box-shadow: 0 2px 20px 0 rgba(38,38,51,0.20);
border-radius: 2px;
display: flex;
flex-direction: column;
user-select: none;
background-color: white;
`);
const cssPopupWrapper = styled('div', `
&:focus {
outline: none;
}
`);
const cssBody = styled('div', `
display: flex;
min-height: 0;
`);
// todo: try replace min-width / max-width
const cssPanel = styled('div', `
width: 224px;
font-size: ${vars.mediumFontSize};
overflow: auto;
padding-bottom: 18px;
&:nth-of-type(2n) {
background-color: ${colors.lightGrey};
outline: var(--outline);
}
`);
const cssHeader = styled('div', `
margin: 24px 0 24px 24px;
font-size: ${vars.mediumFontSize};
`);
const cssEntry = styled('div', `
padding: 0 0 0 24px;
height: 32px;
display: flex;
flex-direction: row;
flex: 1 1 0px;
align-items: center;
white-space: nowrap;
overflow: hidden;
&-selected {
background-color: ${colors.mediumGrey};
}
&-disabled {
color: ${colors.mediumGrey};
}
&-disabled&-selected {
background-color: inherit;
}
`);
const cssIcon = styled(icon, `
margin-right: 8px;
flex-shrink: 0;
--icon-color: ${colors.slate};
.${cssEntry.className}-disabled > & {
opacity: 0.2;
}
`);
const cssTypeIcon = styled(cssIcon, `
--icon-color: ${colors.lightGreen};
`);
const cssLabel = styled('span', `
text-overflow: ellipsis;
overflow: hidden;
`);
const cssFieldLabel = styled(cssLabel, `
padding-right: 8px;
`);
const cssEntryWrapper = styled('div', `
display: flex;
align-items: center;
`);
const cssPivot = styled(cssEntry, `
width: 48px;
padding-left: 8px;
flex: 0 0 auto;
`);
const cssBigIcon = styled(icon, `
width: 24px;
height: 24px;
background-color: ${colors.darkGreen};
`);
const cssFooter = styled('div', `
display: flex;
border-top: var(--outline);
`);
const cssFooterContent = styled('div', `
flex-grow: 1;
height: 65px;
display: flex;
flex-direction: row;
align-items: center;
padding: 0 24px 0 24px;
`);
const cssSmallLabel = styled('span', `
font-size: ${vars.xsmallFontSize};
margin-right: 8px;
`);
const cssSelect = styled(select, `
flex: 1 0 160px;
`);
// Returns a copy of array with its items sorted in the same order as they appear in other.
function sortedAs(array: number[], other: number[]) {
const order: {[id: number]: number} = {};
for (const [index, item] of other.entries()) {
order[item] = index;
}
return array.slice().sort((a, b) => nativeCompare(order[a], order[b]));
} | the_stack |
import React, {createRef, createContext, memo, useContext} from 'react';
import {mount} from 'enzyme';
import type {MutableRefObject} from 'react';
import type {Fiber} from 'react-reconciler';
import type {ReactWrapper} from 'enzyme';
import {Child, getFibersIndices, getFibersKeys} from './__shared__';
import {findChildFiber, ParentFiber, Parent} from '../src';
import {invariant} from '../src/invariant';
import type {ChildProps} from './__shared__';
// Refs.
const parentARef = createRef<ParentFiber>();
const parentBRef = createRef<ParentFiber>();
// Wrappers.
let wrapperA: ReactWrapper;
let wrapperB: ReactWrapper;
// Parent fibers.
let parentA: ParentFiber;
let parentB: ParentFiber;
// Mocks.
let child1Mocks: ChildProps;
let child2Mocks: ChildProps;
let child3Mocks: ChildProps;
let child4Mocks: ChildProps;
// Mount the components before each test.
beforeEach(() => {
// Children moks.
child1Mocks = {
id: '1',
onRender: jest.fn(),
onMount: jest.fn(),
onUnmount: jest.fn(),
stateRef: createRef(),
};
// Children moks.
child2Mocks = {
id: '2',
onRender: jest.fn(),
onMount: jest.fn(),
onUnmount: jest.fn(),
stateRef: createRef(),
};
// Children moks.
child3Mocks = {
id: '3',
onRender: jest.fn(),
onMount: jest.fn(),
onUnmount: jest.fn(),
stateRef: createRef(),
};
// Children moks.
child4Mocks = {
id: '4',
onRender: jest.fn(),
onMount: jest.fn(),
onUnmount: jest.fn(),
stateRef: createRef(),
};
// Mount the components.
wrapperA = mount(
<div>
<Parent parentRef={parentARef}>
<Child key="1" {...child1Mocks} />
<Child key="2" {...child2Mocks} />
</Parent>
</div>
);
wrapperB = mount(
<div>
<Parent parentRef={parentBRef}>
<Child key="3" {...child3Mocks} />
<Child key="4" {...child4Mocks} />
</Parent>
</div>
);
// Parents.
invariant(parentARef.current !== null && parentBRef.current !== null);
parentA = parentARef.current;
parentB = parentBRef.current;
});
describe('How the reparented child lifecycle works', () => {
test('Send a child', () => {
parentA.sendChild(parentB, '1', 0);
// Update the children.
wrapperA.setProps({
children: (
<Parent parentRef={parentARef}>
<Child key="2" {...child2Mocks} />
</Parent>
),
});
wrapperB.setProps({
children: (
<Parent parentRef={parentBRef}>
<Child key="1" {...child1Mocks} />
<Child key="3" {...child3Mocks} />
<Child key="4" {...child4Mocks} />
</Parent>
),
});
// Child 1 lifecycle.
expect(child1Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child1Mocks.onRender).toHaveBeenCalledTimes(2);
// Child 2 lifecycle.
expect(child2Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child2Mocks.onRender).toHaveBeenCalledTimes(2);
// Child 3 lifecycle.
expect(child3Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child3Mocks.onRender).toHaveBeenCalledTimes(2);
// Child 4 lifecycle.
expect(child4Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child4Mocks.onRender).toHaveBeenCalledTimes(2);
wrapperA.unmount();
// Child 1 lifecycle.
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 2 lifecycle.
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 3 lifecycle.
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 4 lifecycle.
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(0);
wrapperB.unmount();
// Child 1 lifecycle.
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 2 lifecycle.
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 3 lifecycle.
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 4 lifecycle.
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(1);
});
});
describe('How the state is maintained after reparenting', () => {
test('Send a child', () => {
// The state is generated using Math.random().
invariant(child1Mocks.stateRef !== undefined);
const randomlyCalculatedState = child1Mocks.stateRef.current;
// Send the child.
parentA.sendChild(parentB, '1', 0);
// Update the children.
wrapperA.setProps({
children: (
<Parent parentRef={parentARef}>
<Child key="2" {...child2Mocks} />
</Parent>
),
});
wrapperB.setProps({
children: (
<Parent parentRef={parentBRef}>
<Child key="1" {...child1Mocks} />
<Child key="3" {...child3Mocks} />
<Child key="4" {...child4Mocks} />
</Parent>
),
});
// The state is manteined.
expect(randomlyCalculatedState).toBe(child1Mocks.stateRef.current);
});
});
describe('Reparenting with context', () => {
test('The context is changed', () => {
// The the Context Consumer and Provider.
const Context = createContext<string>('');
const {Provider} = Context;
const Consumer = (props: {valueRef: MutableRefObject<string>}): null => {
const {valueRef} = props;
valueRef.current = useContext(Context);
return null;
};
// Context values.
const valueARef = createRef<string>() as MutableRefObject<string>;
const valueBRef = createRef<string>() as MutableRefObject<string>;
// Mount the components.
wrapperA = mount(
<div>
<Provider value="A">
<Parent parentRef={parentARef}>
<Consumer key="1" valueRef={valueARef} />
</Parent>
</Provider>
</div>
);
wrapperB = mount(
<div>
<Provider value="B">
<Parent parentRef={parentBRef}>
<Consumer key="2" valueRef={valueBRef} />
</Parent>
</Provider>
</div>
);
expect(valueARef.current).toBe('A');
expect(valueBRef.current).toBe('B');
parentA.sendChild(parentB, 0, 0);
// Update the children.
wrapperB.setProps({
children: (
<Provider value="B">
<Parent parentRef={parentBRef}>
<Consumer key="1" valueRef={valueARef} />
<Consumer key="2" valueRef={valueBRef} />
</Parent>
</Provider>
),
});
// The context is changed.
expect(valueARef.current).toBe('B');
expect(valueBRef.current).toBe('B');
});
test('The context is changed with memoization', () => {
// The the Context Consumer and Provider.
const Context = createContext<string>('');
const {Provider} = Context;
const MemoConsumer = memo(
(props: {valueRef: MutableRefObject<string>}): null => {
const {valueRef} = props;
valueRef.current = useContext(Context);
return null;
}
);
// Context values.
const valueARef = createRef<string>() as MutableRefObject<string>;
const valueBRef = createRef<string>() as MutableRefObject<string>;
// Mount the components.
wrapperA = mount(
<div>
<Provider value="A">
<Parent parentRef={parentARef}>
<MemoConsumer key="1" valueRef={valueARef} />
</Parent>
</Provider>
</div>
);
wrapperB = mount(
<div>
<Provider value="B">
<Parent parentRef={parentBRef}>
<MemoConsumer key="2" valueRef={valueBRef} />
</Parent>
</Provider>
</div>
);
expect(valueARef.current).toBe('A');
expect(valueBRef.current).toBe('B');
parentA.sendChild(parentB, 0, 0);
// Update the children.
wrapperB.setProps({
children: (
<Provider value="B">
<Parent parentRef={parentBRef}>
<MemoConsumer key="1" valueRef={valueARef} />
<MemoConsumer key="2" valueRef={valueBRef} />
</Parent>
</Provider>
),
});
// The context is changed.
expect(valueARef.current).toBe('B');
expect(valueBRef.current).toBe('B');
});
});
describe('Reparenting with React.memo', () => {
test('The Child is not re-rendered after reparenting', () => {
// Children moks.
child1Mocks = {
id: '1',
onRender: jest.fn(),
onMount: jest.fn(),
onUnmount: jest.fn(),
};
// Children moks.
child2Mocks = {
id: '2',
onRender: jest.fn(),
onMount: jest.fn(),
onUnmount: jest.fn(),
};
// Children moks.
child3Mocks = {
id: '3',
onRender: jest.fn(),
onMount: jest.fn(),
onUnmount: jest.fn(),
};
// Children moks.
child4Mocks = {
id: '4',
onRender: jest.fn(),
onMount: jest.fn(),
onUnmount: jest.fn(),
};
const MemoChild = React.memo(Child);
// Mount the components.
wrapperA = mount(
<div>
<Parent parentRef={parentARef}>
<MemoChild key="1" {...child1Mocks} />
<MemoChild key="2" {...child2Mocks} />
</Parent>
</div>
);
wrapperB = mount(
<div>
<Parent parentRef={parentBRef}>
<MemoChild key="3" {...child3Mocks} />
<MemoChild key="4" {...child4Mocks} />
</Parent>
</div>
);
// (type fixing).
invariant(parentARef.current !== null && parentBRef.current !== null);
// Parents.
parentA = parentARef.current;
parentB = parentBRef.current;
parentA.sendChild(parentB, '1', 0);
// Mount the components.
wrapperA.setProps({
children: (
<Parent parentRef={parentARef}>
<MemoChild key="2" {...child2Mocks} />
</Parent>
),
});
wrapperB.setProps({
children: (
<Parent parentRef={parentBRef}>
<MemoChild key="1" {...child1Mocks} />
<MemoChild key="3" {...child3Mocks} />
<MemoChild key="4" {...child4Mocks} />
</Parent>
),
});
// Child 1 lifecycle.
expect(child1Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child1Mocks.onRender).toHaveBeenCalledTimes(1);
// Child 2 lifecycle.
expect(child2Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child2Mocks.onRender).toHaveBeenCalledTimes(1);
// Child 3 lifecycle.
expect(child3Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child3Mocks.onRender).toHaveBeenCalledTimes(1);
// Child 4 lifecycle.
expect(child4Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child4Mocks.onRender).toHaveBeenCalledTimes(1);
});
});
describe('Some possible scenarios', () => {
test('Re-render A before reparenting', () => {
// Re-render.
wrapperA.setProps({
children: (
<Parent parentRef={parentARef}>
<Child key="1" {...child1Mocks} />
<Child key="2" {...child2Mocks} />
</Parent>
),
});
parentA.sendChild(parentB, '1', 0);
parentA.sendChild(parentB, '2', '4');
// Update the children.
wrapperA.setProps({
children: <Parent parentRef={parentARef}>{null}</Parent>,
});
wrapperB.setProps({
children: (
<Parent parentRef={parentBRef}>
<Child key="1" {...child1Mocks} />
<Child key="3" {...child3Mocks} />
<Child key="2" {...child2Mocks} />
<Child key="4" {...child4Mocks} />
</Parent>
),
});
const fiber = findChildFiber(parentB.getCurrent(), '2');
invariant(fiber !== null && fiber.alternate !== null);
// The fiber fields are updated.
expect(fiber.return).toBe(parentB.getCurrent());
expect(fiber.alternate.return).toBe(parentB.getCurrent().alternate);
// The indices are updated.
expect(getFibersIndices(parentA.getCurrent())).toEqual([]);
expect(getFibersIndices(parentB.getCurrent())).toEqual([0, 1, 2, 3]);
expect(getFibersIndices(parentB.getCurrent().alternate as Fiber)).toEqual([
0,
1,
2,
3,
]);
// The keys are in the correct order.
expect(getFibersKeys(parentA.getCurrent())).toEqual([]);
expect(getFibersKeys(parentB.getCurrent())).toEqual(['1', '3', '2', '4']);
expect(getFibersKeys(parentB.getCurrent().alternate as Fiber)).toEqual([
'1',
'3',
'2',
'4',
]);
// The children are in the correct order.
expect(
Array.from(wrapperA.getDOMNode().children).map((child) =>
child.getAttribute('id')
)
).toEqual([]);
expect(
Array.from(wrapperB.getDOMNode().children).map((child) =>
child.getAttribute('id')
)
).toEqual(['1', '3', '2', '4']);
// Child 1 lifecycle.
expect(child1Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child1Mocks.onRender).toHaveBeenCalledTimes(3);
// Child 2 lifecycle.
expect(child2Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child2Mocks.onRender).toHaveBeenCalledTimes(3);
// Child 3 lifecycle.
expect(child3Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child3Mocks.onRender).toHaveBeenCalledTimes(2);
// Child 4 lifecycle.
expect(child4Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child4Mocks.onRender).toHaveBeenCalledTimes(2);
wrapperA.unmount();
// Child 1 lifecycle.
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 2 lifecycle.
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 3 lifecycle.
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 4 lifecycle.
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(0);
wrapperB.unmount();
// Child 1 lifecycle.
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 2 lifecycle.
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 3 lifecycle.
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 4 lifecycle.
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(1);
});
test('Re-render A before reparenting, re-render A and B after reparenting', () => {
// Re-render.
wrapperA.setProps({
children: (
<Parent parentRef={parentARef}>
<Child key="1" {...child1Mocks} />
<Child key="2" {...child2Mocks} />
</Parent>
),
});
parentA.sendChild(parentB, '1', 0);
parentA.sendChild(parentB, '2', '4');
// Update the children.
wrapperA.setProps({
children: <Parent parentRef={parentARef}>{null}</Parent>,
});
wrapperB.setProps({
children: (
<Parent parentRef={parentBRef}>
<Child key="1" {...child1Mocks} />
<Child key="3" {...child3Mocks} />
<Child key="2" {...child2Mocks} />
<Child key="4" {...child4Mocks} />
</Parent>
),
});
// Re-render.
wrapperA.setProps({
children: <Parent parentRef={parentARef}>{null}</Parent>,
});
wrapperB.setProps({
children: (
<Parent parentRef={parentBRef}>
<Child key="1" {...child1Mocks} />
<Child key="3" {...child3Mocks} />
<Child key="2" {...child2Mocks} />
<Child key="4" {...child4Mocks} />
</Parent>
),
});
const fiber = findChildFiber(parentB.getCurrent(), '2');
invariant(fiber !== null && fiber.alternate !== null);
// The fiber fields are updated.
expect(fiber.return).toBe(parentB.getCurrent());
expect(fiber.alternate.return).toBe(parentB.getCurrent().alternate);
// The indices are updated.
expect(getFibersIndices(parentA.getCurrent())).toEqual([]);
expect(getFibersIndices(parentB.getCurrent())).toEqual([0, 1, 2, 3]);
expect(getFibersIndices(parentB.getCurrent().alternate as Fiber)).toEqual([
0,
1,
2,
3,
]);
// The keys are in the correct order.
expect(getFibersKeys(parentA.getCurrent())).toEqual([]);
expect(getFibersKeys(parentB.getCurrent())).toEqual(['1', '3', '2', '4']);
expect(getFibersKeys(parentB.getCurrent().alternate as Fiber)).toEqual([
'1',
'3',
'2',
'4',
]);
// The children are in the correct order.
expect(
Array.from(wrapperA.getDOMNode().children).map((child) =>
child.getAttribute('id')
)
).toEqual([]);
expect(
Array.from(wrapperB.getDOMNode().children).map((child) =>
child.getAttribute('id')
)
).toEqual(['1', '3', '2', '4']);
// Child 1 lifecycle.
expect(child1Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child1Mocks.onRender).toHaveBeenCalledTimes(4);
// Child 2 lifecycle.
expect(child2Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child2Mocks.onRender).toHaveBeenCalledTimes(4);
// Child 3 lifecycle.
expect(child3Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child3Mocks.onRender).toHaveBeenCalledTimes(3);
// Child 4 lifecycle.
expect(child4Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child4Mocks.onRender).toHaveBeenCalledTimes(3);
wrapperA.unmount();
// Child 1 lifecycle.
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 2 lifecycle.
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 3 lifecycle.
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 4 lifecycle.
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(0);
wrapperB.unmount();
// Child 1 lifecycle.
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 2 lifecycle.
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 3 lifecycle.
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 4 lifecycle.
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(1);
});
test('Re-render A before reparenting, add a new child', () => {
const child5Mocks = {
id: '5',
onRender: jest.fn(),
onMount: jest.fn(),
onUnmount: jest.fn(),
};
// Re-render.
wrapperA.setProps({
children: (
<Parent parentRef={parentARef}>
<Child key="1" {...child1Mocks} />
<Child key="2" {...child2Mocks} />
</Parent>
),
});
parentA.sendChild(parentB, '1', 0);
parentA.sendChild(parentB, '2', '4');
// Update the children.
wrapperA.setProps({
children: <Parent parentRef={parentARef}>{null}</Parent>,
});
wrapperB.setProps({
children: (
<Parent parentRef={parentBRef}>
<Child key="1" {...child1Mocks} />
<Child key="3" {...child3Mocks} />
<Child key="5" {...child5Mocks} />
<Child key="2" {...child2Mocks} />
<Child key="4" {...child4Mocks} />
</Parent>
),
});
const fiber = findChildFiber(parentB.getCurrent(), '2');
invariant(fiber !== null && fiber.alternate !== null);
// The fiber fields are updated.
expect(fiber.return).toBe(parentB.getCurrent());
expect(fiber.alternate.return).toBe(parentB.getCurrent().alternate);
// The indices are updated.
expect(getFibersIndices(parentA.getCurrent())).toEqual([]);
expect(getFibersIndices(parentB.getCurrent())).toEqual([0, 1, 2, 3, 4]);
expect(getFibersIndices(parentB.getCurrent().alternate as Fiber)).toEqual([
0,
1,
2,
3,
]);
// The keys are in the correct order.
expect(getFibersKeys(parentA.getCurrent())).toEqual([]);
expect(getFibersKeys(parentB.getCurrent())).toEqual([
'1',
'3',
'5',
'2',
'4',
]);
expect(getFibersKeys(parentB.getCurrent().alternate as Fiber)).toEqual([
'1',
'3',
'2',
'4',
]);
// The children are in the correct order.
expect(
Array.from(wrapperA.getDOMNode().children).map((child) =>
child.getAttribute('id')
)
).toEqual([]);
expect(
Array.from(wrapperB.getDOMNode().children).map((child) =>
child.getAttribute('id')
)
).toEqual(['1', '3', '5', '2', '4']);
// Child 1 lifecycle.
expect(child1Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child1Mocks.onRender).toHaveBeenCalledTimes(3);
// Child 2 lifecycle.
expect(child2Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child2Mocks.onRender).toHaveBeenCalledTimes(3);
// Child 3 lifecycle.
expect(child3Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child3Mocks.onRender).toHaveBeenCalledTimes(2);
// Child 4 lifecycle.
expect(child4Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child4Mocks.onRender).toHaveBeenCalledTimes(2);
// Child 5 lifecycle.
expect(child5Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child5Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child5Mocks.onRender).toHaveBeenCalledTimes(1);
wrapperA.unmount();
// Child 1 lifecycle.
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 2 lifecycle.
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 3 lifecycle.
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 4 lifecycle.
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(0);
wrapperB.unmount();
// Child 1 lifecycle.
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 2 lifecycle.
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 3 lifecycle.
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 4 lifecycle.
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(1);
});
test('Re-render A before reparenting, re-render A and B after reparenting, add a new child', () => {
const child5Mocks = {
id: '5',
onRender: jest.fn(),
onMount: jest.fn(),
onUnmount: jest.fn(),
};
// Re-render.
wrapperA.setProps({
children: (
<Parent parentRef={parentARef}>
<Child key="1" {...child1Mocks} />
<Child key="2" {...child2Mocks} />
</Parent>
),
});
parentA.sendChild(parentB, '1', 0);
parentA.sendChild(parentB, '2', '4');
// Update the children.
wrapperA.setProps({
children: <Parent parentRef={parentARef}>{null}</Parent>,
});
wrapperB.setProps({
children: (
<Parent parentRef={parentBRef}>
<Child key="1" {...child1Mocks} />
<Child key="3" {...child3Mocks} />
<Child key="5" {...child5Mocks} />
<Child key="2" {...child2Mocks} />
<Child key="4" {...child4Mocks} />
</Parent>
),
});
// Re-render.
wrapperA.setProps({
children: <Parent parentRef={parentARef}>{null}</Parent>,
});
wrapperB.setProps({
children: (
<Parent parentRef={parentBRef}>
<Child key="1" {...child1Mocks} />
<Child key="3" {...child3Mocks} />
<Child key="5" {...child5Mocks} />
<Child key="2" {...child2Mocks} />
<Child key="4" {...child4Mocks} />
</Parent>
),
});
const fiber = findChildFiber(parentB.getCurrent(), '2');
invariant(fiber !== null && fiber.alternate !== null);
// The fiber fields are updated.
expect(fiber.return).toBe(parentB.getCurrent());
expect(fiber.alternate.return).toBe(parentB.getCurrent().alternate);
// The indices are updated.
expect(getFibersIndices(parentA.getCurrent())).toEqual([]);
expect(getFibersIndices(parentB.getCurrent())).toEqual([0, 1, 2, 3, 4]);
expect(getFibersIndices(parentB.getCurrent().alternate as Fiber)).toEqual([
0,
1,
2,
3,
4,
]);
// The keys are in the correct order.
expect(getFibersKeys(parentA.getCurrent())).toEqual([]);
expect(getFibersKeys(parentB.getCurrent())).toEqual([
'1',
'3',
'5',
'2',
'4',
]);
expect(getFibersKeys(parentB.getCurrent().alternate as Fiber)).toEqual([
'1',
'3',
'5',
'2',
'4',
]);
// The children are in the correct order.
expect(
Array.from(wrapperA.getDOMNode().children).map((child) =>
child.getAttribute('id')
)
).toEqual([]);
expect(
Array.from(wrapperB.getDOMNode().children).map((child) =>
child.getAttribute('id')
)
).toEqual(['1', '3', '5', '2', '4']);
// Child 1 lifecycle.
expect(child1Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child1Mocks.onRender).toHaveBeenCalledTimes(4);
// Child 2 lifecycle.
expect(child2Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child2Mocks.onRender).toHaveBeenCalledTimes(4);
// Child 3 lifecycle.
expect(child3Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child3Mocks.onRender).toHaveBeenCalledTimes(3);
// Child 4 lifecycle.
expect(child4Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child4Mocks.onRender).toHaveBeenCalledTimes(3);
// Child 5 lifecycle.
expect(child5Mocks.onMount).toHaveBeenCalledTimes(1);
expect(child5Mocks.onUnmount).toHaveBeenCalledTimes(0);
expect(child5Mocks.onRender).toHaveBeenCalledTimes(2);
wrapperA.unmount();
// Child 1 lifecycle.
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 2 lifecycle.
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 3 lifecycle.
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(0);
// Child 4 lifecycle.
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(0);
wrapperB.unmount();
// Child 1 lifecycle.
expect(child1Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 2 lifecycle.
expect(child2Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 3 lifecycle.
expect(child3Mocks.onUnmount).toHaveBeenCalledTimes(1);
// Child 4 lifecycle.
expect(child4Mocks.onUnmount).toHaveBeenCalledTimes(1);
});
}); | the_stack |
import { createTransformer, Transformer } from '../src'
import { defineMacro, EnvContext } from '@typed-macro/core'
import { createMacroRemove } from '../../core/__tests__/macros'
describe('Transformer', () => {
const env: EnvContext = {
host: 'test',
packageManager: 'test',
projectPath: [''],
dev: true,
ssr: false,
}
let transformer: Transformer
beforeEach(() => {
transformer = createTransformer({})
})
it('should support set parser plugins', () => {
transformer = createTransformer({ parserPlugins: ['decimal'] })
const code = `let a = 0.3m`
expect(() => transformer.transform(code, '', env)).not.toThrowError()
})
it('should support add parser plugins', () => {
const code = `let a = 0.3m`
expect(() => transformer.transform(code, '', env)).toThrowError()
transformer.appendParserPlugins(['decimal'])
expect(() => transformer.transform(code, '', env)).not.toThrowError()
})
it('should support add macros', () => {
const macroA = defineMacro('macroA')
.withSignature('(): void')
.withHandler(({ path }) => path.remove())
const macroB = defineMacro('macroB')
.withSignature('(): void')
.withHandler(({ path }) => path.remove())
expect(() => transformer.appendMacros('macro', [macroA])).not.toThrowError()
expect(() => transformer.appendMacros('macro', [macroB])).not.toThrowError()
// throw error when macro duplicates
expect(() => transformer.appendMacros('macro', [macroA])).toThrowError()
})
it('should apply macros', () => {
transformer.appendMacros('macro', [createMacroRemove()])
expect(
transformer.transform(
`
import 'macro'
import { noop } from 'macro'
noop()
parseInt()
Math.floor(2)
`,
'test.ts',
env
)
).toMatchSnapshot()
expect(
transformer.transform(
`import * as m from 'macro'
m.noop()
m['noop']()
parseInt()
Math.floor(2)
`,
'test.ts',
env
)
).toMatchSnapshot()
expect(
transformer.transform(
`import { noop as n } from 'macro'
n()
parseInt()
Math.floor(2)
`,
'test.ts',
env
)
).toMatchSnapshot()
expect(transformer.transform(`noop()`, 'test.ts', env)).toBeUndefined()
})
it('should support variable shadow', () => {
transformer.appendMacros('macro', [createMacroRemove()])
expect(
transformer.transform(
`
import { noop as n } from 'macro'
import * as m from 'macro'
{
const n = () => {}
n()
}
n()
m.noop()
{
const m = { noop() {} }
m.noop()
}
`,
'test.ts',
env
)
).toMatchSnapshot()
})
it('should support nested macros', () => {
transformer.appendMacros('macro', [
defineMacro('reverse')
.withSignature('(s: string): string')
.withHandler(({ path, args }, { types }) => {
let content = 'default'
if (args.length > 0 && args[0].isStringLiteral()) {
content = args[0].node.value
}
path.replaceWith(
types.stringLiteral(content.split('').reverse().join(''))
)
}),
])
expect(
transformer.transform(
`
import { reverse } from 'macro'
console.log(reverse(reverse('hello world')))
`,
'test.ts',
env
)
).toMatchSnapshot()
})
it('should support helpers', () => {
transformer.appendMacros('macro', [
defineMacro('reverse')
.withSignature('(s: string): string')
// use generator function to disable auto macro expansion
/* eslint-disable require-yield */
.withHandler(function* ({ path, args }, { types, template }, helper) {
expect(helper.containsMacros(args)).toEqual([true])
expect(helper.containsMacros(args[0])).toEqual(true)
helper.prependToBody(template.statement.ast('console.log(1)'))
helper.prependToBody(
template.statements.ast(`console.log(2); console.log(3)`)
)
helper.appendToBody(template.statement.ast('console.log(4)'))
helper.appendToBody(
template.statements.ast(`console.log(5); console.log(6)`)
)
const importA = {
moduleName: 'some',
exportName: 'funcA',
}
const importB = {
moduleName: 'some',
namespaceName: 'funcB',
}
const importC = {
moduleName: 'some',
exportName: 'funcC',
localName: '_funcC',
}
const importD = {
moduleName: 'other',
}
const importE = {
moduleName: 'other',
defaultName: '_other',
}
const insertedImportA = helper.prependImports(importA)
const [insertedImportB, insertedImportC] = helper.prependImports([
importB,
importC,
])
const insertedImportD = helper.appendImports(importD)
const [insertedImportE] = helper.appendImports([importE])
expect(helper.appendImports([])).toEqual([])
expect(helper.findImported(importA)).toBe(insertedImportA)
expect(helper.findImported([importB])[0]).toBe(insertedImportB)
expect(helper.findImported(importC)).toBe(insertedImportC)
expect(helper.findImported([importD])[0]).toBe(insertedImportD)
expect(helper.findImported([importE])[0]).toBe(insertedImportE)
let content = 'default'
if (args.length > 0 && args[0].isStringLiteral()) {
content = args[0].node.value
}
path.replaceWith(
types.stringLiteral(content.split('').reverse().join(''))
)
}),
/* eslint-enable require-yield */
])
expect(
transformer.transform(
`
import { reverse } from 'macro'
console.log(reverse('' + reverse('hello world')))
console.log(reverse(reverse('hello world')))
`,
'test.ts',
env
)
).toMatchSnapshot()
})
it('should support yield', () => {
transformer.appendMacros('macro', [
defineMacro('test')
.withSignature('(): void')
.withHandler(function* (
{ path, args },
{ template },
{ appendToBody, appendImports }
) {
if (args.length) {
yield args // NodePath[]
yield appendImports({ moduleName: 'macro', exportName: 'test' }) // NodePath<ImportDeclaration>
yield appendToBody(template.statement.ast('test()')) // NodePath[]
yield undefined // nothing
yield [undefined] // nothing
}
path.replaceWith(template.statement.ast('console.log(1)'))
}),
])
expect(
transformer.transform(
`
import { test } from 'macro'
test(test())
`,
'test.ts',
env
)
).toMatchSnapshot()
})
it('should support traversal/transform state', () => {
transformer.appendMacros('macro', [
defineMacro('noop')
.withSignature('(): void')
.withHandler(({ path, state }) => {
const transformCount = (state.transform.get('count') || 0) as number
if (transformCount === 0) {
// test state
expect(state.transform.has('unknown')).toBe(false)
expect(state.transform.getOrSet('unknown', 0)).toBe(0)
expect(state.transform.getOrSet('unknown', 1)).toBe(0)
state.transform.delete('unknown')
expect(state.transform.has('unknown')).toBe(false)
}
if (transformCount > 2) {
path.remove()
return
}
state.transform.set('count', transformCount + 1)
expect(state.traversal.get('flag')).toBeUndefined()
state.traversal.set('flag', 0)
}),
])
expect(() =>
transformer.transform(
`
import { noop as n } from 'macro'
n()
`,
'test.ts',
env
)
).not.toThrowError()
})
it('should limit max traversal times', () => {
transformer = createTransformer({ maxTraversals: 3 })
let count = 0
transformer.appendMacros('macro', [
defineMacro('noop')
.withSignature('(): void')
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.withHandler((_) => {
count++
}),
])
expect(() =>
transformer.transform(
`
import { noop as n } from 'macro'
n()
`,
'test.ts',
env
)
).toThrowError()
expect(count > 2).toBe(true)
})
it('should throw error when call non-existed macro', () => {
transformer.appendMacros('macro', [])
expect(() =>
transformer.transform(
`
import { noop as n } from 'macro'
n()
`,
'test.ts',
env
)
).toThrowError()
expect(() =>
transformer.transform(
`
import m from 'macro'
m.noop()
`,
'test.ts',
env
)
).toThrowError()
})
it('should reject yield parent path', () => {
transformer.appendMacros('macro', [
defineMacro('test')
.withSignature('(): void')
.withHandler(function* ({ path, args }, { template }) {
yield args
if (args.length === 0) {
yield path.parentPath
}
path.replaceWith(template.statement.ast('console.log(1)'))
}),
])
expect(() =>
transformer.transform(
`
import { test } from 'macro'
test(test())
`,
'test.ts',
env
)
).toThrowError()
})
it('should re-throw errors with code position from macro handlers', () => {
transformer.appendMacros('macro', [
defineMacro('test')
.withSignature('(): void')
.withHandler(({ args, path }) => {
if (args.length) {
throw new Error('some error')
}
path.remove()
}),
])
expect(
(() => {
try {
transformer.transform(
`
import { test } from 'macro'
test(1)
`,
'test.ts',
env
)
} catch (e) {
return e
}
})()
).toMatchSnapshot()
})
}) | the_stack |
import { ComprModeType } from './compr-mode-type'
import { Context } from './context'
import { LoaderOptions, Library, Instance } from './seal'
import { Exception, SealError } from './exception'
import { MemoryPoolHandle } from './memory-pool-handle'
import { ParmsIdType, ParmsIdTypeConstructorOptions } from './parms-id-type'
import { VectorConstructorOptions } from './vector'
import { INVALID_CIPHER_CONSTRUCTOR_OPTIONS } from './constants'
export type CipherTextDependencyOptions = {
readonly Exception: Exception
readonly ComprModeType: ComprModeType
readonly ParmsIdType: ParmsIdTypeConstructorOptions
readonly MemoryPoolHandle: MemoryPoolHandle
readonly Vector: VectorConstructorOptions
}
export type CipherTextDependencies = {
({
Exception,
ComprModeType,
ParmsIdType,
MemoryPoolHandle,
Vector
}: CipherTextDependencyOptions): CipherTextConstructorOptions
}
export type CipherTextConstructorOptions = {
({
context,
parmsId,
sizeCapacity,
pool
}?: {
context?: Context
parmsId?: ParmsIdType
sizeCapacity?: number
pool?: MemoryPoolHandle
}): CipherText
}
export type CipherText = {
readonly instance: Instance
readonly unsafeInject: (instance: Instance) => void
readonly delete: () => void
readonly reserve: (context: Context, capacity: number) => void
readonly resize: (size: number) => void
readonly release: () => void
readonly coeffModulusSize: number
readonly polyModulusDegree: number
readonly size: number
readonly sizeCapacity: number
readonly isTransparent: boolean
readonly isNttForm: boolean
readonly parmsId: ParmsIdType
readonly scale: number
readonly setScale: (scale: number) => void
readonly pool: MemoryPoolHandle
readonly save: (compression?: ComprModeType) => string
readonly saveArray: (compression?: ComprModeType) => Uint8Array
readonly load: (context: Context, encoded: string) => void
readonly loadArray: (context: Context, array: Uint8Array) => void
readonly copy: (cipher: CipherText) => void
readonly clone: () => CipherText
readonly move: (cipher: CipherText) => void
}
const CipherTextConstructor =
(library: Library): CipherTextDependencies =>
({
Exception,
ComprModeType,
ParmsIdType,
MemoryPoolHandle,
Vector
}: CipherTextDependencyOptions): CipherTextConstructorOptions =>
({
context,
parmsId,
sizeCapacity,
pool = MemoryPoolHandle.global
} = {}): CipherText => {
// Static methods
const Constructor = library.Ciphertext
let _instance = construct({
context,
parmsId,
sizeCapacity,
pool
})
function construct({
context,
parmsId,
sizeCapacity,
pool = MemoryPoolHandle.global
}: {
context?: Context
parmsId?: ParmsIdType
sizeCapacity?: number
pool?: MemoryPoolHandle
}) {
try {
if (!context && !parmsId && sizeCapacity === undefined) {
return new Constructor(pool)
} else if (context && !parmsId && sizeCapacity === undefined) {
return new Constructor(context.instance, pool)
} else if (context && parmsId && sizeCapacity === undefined) {
return new Constructor(context.instance, parmsId.instance, pool)
} else if (context && parmsId && sizeCapacity !== undefined) {
return new Constructor(
context.instance,
parmsId.instance,
sizeCapacity,
pool
)
} else {
throw new Error(INVALID_CIPHER_CONSTRUCTOR_OPTIONS)
}
} catch (e) {
throw Exception.safe(e as SealError)
}
}
/**
* @implements CipherText
*/
/**
* @interface CipherText
*/
return {
/**
* Get the underlying WASM instance
*
* @private
* @readonly
* @name CipherText#instance
* @type {Instance}
*/
get instance() {
return _instance
},
/**
* Inject this object with a raw WASM instance. No type checking is performed.
*
* @private
* @function
* @name CipherText#unsafeInject
* @param {Instance} instance WASM instance
*/
unsafeInject(instance: Instance) {
if (_instance) {
_instance.delete()
_instance = undefined
}
_instance = instance
},
/**
* Delete the underlying WASM instance.
*
* Should be called before dereferencing this object to prevent the
* WASM heap from growing indefinitely.
* @function
* @name CipherText#delete
*/
delete() {
if (_instance) {
_instance.delete()
_instance = undefined
}
},
/**
* Allocates enough memory to accommodate the backing array of a ciphertext
* with given capacity. In addition to the capacity, the allocation size is
* determined by the current encryption parameters.
*
* @function
* @name CipherText#reserve
* @param {Context} context The SEAL Context
* @param {number} capacity The capacity to reserve
*/
reserve(context: Context, capacity: number) {
try {
return _instance.reserve(context.instance, capacity)
} catch (e) {
throw Exception.safe(e as SealError)
}
},
/**
* Resizes the CipherText to given size, reallocating if the capacity
* of the CipherText is too small.
*
* This function is mainly intended for internal use and is called
* automatically by functions such as Evaluator.multiply and
* Evaluator.relinearize. A normal user should never have a reason
* to manually resize a CipherText.
*
* @function
* @name CipherText#resize
* @param {number} size The new size
*/
resize(size: number) {
try {
return _instance.resize(size)
} catch (e) {
throw Exception.safe(e as SealError)
}
},
/**
* Resets the CipherText. This function releases any memory allocated
* by the CipherText, returning it to the memory pool. It also sets all
* encryption parameter specific size information to zero.
*
* @function
* @name CipherText#release
*/
release() {
_instance.release()
},
/**
* The number of primes in the coefficient modulus of the
* associated encryption parameters. This directly affects the
* allocation size of the CipherText.
*
* @readonly
* @name CipherText#coeffModulusSize
* @type {number}
*/
get coeffModulusSize() {
return _instance.coeffModulusSize()
},
/**
* The degree of the polynomial modulus of the associated
* encryption parameters. This directly affects the allocation size
* of the CipherText.
*
* @readonly
* @name CipherText#polyModulusDegree
* @type {number}
*/
get polyModulusDegree() {
return _instance.polyModulusDegree()
},
/**
* The size of the CipherText.
*
* @readonly
* @name CipherText#size
* @type {number}
*/
get size() {
return _instance.size()
},
/**
* The capacity of the allocation. This means the largest size
* of the CipherText that can be stored in the current allocation with
* the current encryption parameters.
*
* @readonly
* @name CipherText#sizeCapacity
* @type {number}
*/
get sizeCapacity() {
return _instance.sizeCapacity()
},
/**
* Whether the current CipherText is transparent, i.e. does not require
* a secret key to decrypt. In typical security models such transparent
* CipherTexts would not be considered to be valid. Starting from the second
* polynomial in the current CipherText, this function returns true if all
* following coefficients are identically zero. Otherwise, returns false.
*
* @readonly
* @name CipherText#isTransparent
* @type {boolean}
*/
get isTransparent() {
return _instance.isTransparent()
},
/**
* Whether the CipherText is in NTT form.
*
* @readonly
* @name CipherText#isNttForm
* @type {boolean}
*/
get isNttForm() {
return _instance.isNttForm()
},
/**
* The reference to parmsId.
* @see {@link EncryptionParameters} for more information about parmsId.
*
* @readonly
* @name CipherText#parmsId
* @type {ParmsIdType}
*/
get parmsId() {
const parms = ParmsIdType()
parms.inject(_instance.parmsId())
return parms
},
/**
* The reference to the scale. This is only needed when using the
* CKKS encryption scheme. The user should have little or no reason to ever
* change the scale by hand.
*
* @readonly
* @name CipherText#scale
* @type {number}
*/
get scale() {
return _instance.scale()
},
/**
* Sets the CipherText scale. This is only needed when using the
* CKKS encryption scheme. The user should have little or no reason to ever
* change the scale by hand.
*
* @function
* @name CipherText#setScale
* @param {number} scale The scale to set
*/
setScale(scale: number) {
_instance.setScale(scale)
},
/**
* The currently used MemoryPoolHandle.
*
* @readonly
* @name CipherText#pool
* @type {MemoryPoolHandle}
*/
get pool() {
return _instance.pool()
},
/**
* Save the CipherText to a base64 string
*
* @function
* @name CipherText#save
* @param {ComprModeType} [compression={@link ComprModeType.zstd}] The compression mode to use
* @returns {string} Base64 encoded string
*/
save(compression: ComprModeType = ComprModeType.zstd): string {
return _instance.saveToString(compression)
},
/**
* Save the CipherText as a binary Uint8Array
*
* @function
* @name CipherText#saveArray
* @param {ComprModeType} [compression={@link ComprModeType.zstd}] The compression mode to use
* @returns {Uint8Array} A byte array containing the CipherText in binary form
*/
saveArray(compression: ComprModeType = ComprModeType.zstd): Uint8Array {
const tempVect = Vector()
const instance = _instance.saveToArray(compression)
tempVect.unsafeInject(instance)
tempVect.setType('Uint8Array')
const tempArr = tempVect.toArray() as Uint8Array
tempVect.delete()
return tempArr
},
/**
* Load a CipherText from a base64 string
*
* @function
* @name CipherText#load
* @param {Context} context Encryption context to enforce
* @param {string} encoded Base64 encoded string
*/
load(context: Context, encoded: string) {
try {
_instance.loadFromString(context.instance, encoded)
} catch (e) {
throw Exception.safe(e as SealError)
}
},
/**
* Load a CipherText from an Uint8Array holding binary data
*
* @function
* @name CipherText#loadArray
* @param {Context} context Encryption context to enforce
* @param {Uint8Array} array TypedArray containing binary data
*/
loadArray(context: Context, array: Uint8Array) {
try {
_instance.loadFromArray(context.instance, array)
} catch (e) {
throw Exception.safe(e as SealError)
}
},
/**
* Copy an existing CipherText and overwrite this instance
*
* @function
* @name CipherText#copy
* @param {CipherText} cipher CipherText to copy
* @example
* const cipherTextA = seal.CipherText()
* // ... after encoding some data ...
* const cipherTextB = seal.CipherText()
* cipherTextB.copy(cipherTextA)
* // cipherTextB holds a copy of cipherTextA
*/
copy(cipher: CipherText) {
try {
_instance.copy(cipher.instance)
} catch (e) {
throw Exception.safe(e as SealError)
}
},
/**
* Clone and return a new instance of this CipherText
*
* @function
* @name CipherText#clone
* @returns {CipherText}
* @example
* const cipherTextA = seal.CipherText()
* // ... after encoding some data ...
* const cipherTextB = cipherTextA.clone()
* // cipherTextB holds a copy of cipherTextA
*/
clone(): CipherText {
try {
const clonedInstance = _instance.clone()
const cipher = CipherTextConstructor(library)({
Exception,
ComprModeType,
ParmsIdType,
MemoryPoolHandle,
Vector
})()
cipher.unsafeInject(clonedInstance)
return cipher
} catch (e) {
throw Exception.safe(e as SealError)
}
},
/**
* Move a CipherText into this one and delete the old reference
*
* @function
* @name CipherText#move
* @param {CipherText} cipher CipherText to move
* @example
* const cipherTextA = seal.CipherText()
* // ... after encoding some data ...
* const cipherTextB = seal.CipherText()
* cipherTextB.move(cipherTextA)
* // cipherTextB holds a the instance of cipherTextA.
* // cipherTextA no longer holds an instance
*/
move(cipher: CipherText) {
try {
_instance.move(cipher.instance)
// TODO: find optimization
// This method results in a copy instead of a real move.
// Therefore, we need to delete the old instance.
cipher.delete()
} catch (e) {
throw Exception.safe(e as SealError)
}
}
}
}
export const CipherTextInit = ({
loader
}: LoaderOptions): CipherTextDependencies => {
const library: Library = loader.library
return CipherTextConstructor(library)
} | the_stack |
* Copyright 2022, Yahoo Holdings Inc.
* Licensed under the terms of the MIT license. See accompanying LICENSE.md file for terms.
*/
import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
import config from 'ember-get-config';
// @ts-ignore
import { getAllApiErrMsg } from 'navi-core/utils/persistence-error';
import { A as arr } from '@ember/array';
import { computed, action } from '@ember/object';
import RSVP from 'rsvp';
import { capitalize } from 'lodash-es';
import { featureFlag } from 'navi-core/helpers/feature-flag';
import { tracked } from '@glimmer/tracking';
import { assert } from '@ember/debug';
import type StoreService from '@ember-data/store';
import type DeliveryRuleModel from 'navi-core/models/delivery-rule';
import type NaviNotificationService from 'navi-core/services/interfaces/navi-notifications';
import type UserService from 'navi-core/services/user';
import type DeliverableItemModel from 'navi-core/models/deliverable-item';
import type { RSVPMethodsObj } from 'navi-reports/consumers/delivery-rule';
import GsheetFormat from 'navi-core/models/gsheet';
const defaultFrequencies = ['day', 'week', 'month', 'quarter', 'year'];
const defaultFormats = ['csv'];
interface Args {
model: DeliverableItemModel;
isValidForSchedule?(): Promise<boolean>;
onDelete(DeliveryRule: DeliveryRuleModel, promise: RSVPMethodsObj): void;
onSave(DeliveryRule: DeliveryRuleModel, promise: RSVPMethodsObj): void;
onRevert(DeliveryRule: DeliveryRuleModel): void;
}
export default class ScheduleActionComponent extends Component<Args> {
/**
* @property {Service} store
*/
@service store!: StoreService;
/**
* @property {Service} user
*/
@service user!: UserService;
/**
* @property {Service} naviNotifications
*/
@service naviNotifications!: NaviNotificationService;
/**
* This property is set in the onOpen action to make sure
* that we don't fetch any data until the modal is opened
* @property {DS.Model} deliveryRule - deliveryRule for the current user
*/
@tracked deliveryRules: DeliveryRuleModel[] = [];
/**
* @property {DS.Model} currentDisplayedRule - Model that stores the values of the modal's fields
*/
@tracked currentDisplayedRule?: DeliveryRuleModel;
/**
* @property {string} notification - In modal notification text
*/
@tracked notification?: string[];
@tracked isSaving = false;
@tracked showModal = false;
@tracked errorWhileFetchingRules = false;
deliveryOptions = ['email', 'none'];
/**
* List of formats it makes sense to show 'overwrite file' toggle
* Good for cloud based formats
*/
overwriteableFormats = ['gsheet'];
rootURL = config.rootURL;
/**
* Promise resolving to whether item is valid to be scheduled
*/
get isValidForSchedule(): Promise<boolean> {
return this.args.isValidForSchedule?.() ?? Promise.resolve(true);
}
/**
* @property {Array} frequencies
*/
@computed('config.navi.schedule.frequencies')
get frequencies() {
return arr(config.navi.schedule?.frequencies || defaultFrequencies);
}
get modelType() {
//@ts-ignore
return this.args.model.constructor.modelName;
}
/**
* @property {Array} formats
*/
get formats() {
let formats = config.navi.schedule?.formats;
if (!formats) {
formats = defaultFormats.slice();
const supportedFormats = featureFlag('exportFileTypes');
if (Array.isArray(supportedFormats) && supportedFormats.length > 0) {
formats = [...formats, ...supportedFormats];
const uniqFormats = [...new Set(formats)];
formats = uniqFormats.sort(function (a, b) {
//Sort the index based on defaultFormat inputs
return defaultFormats.indexOf(b) - defaultFormats.indexOf(a);
});
}
}
return arr(formats);
}
/**
* @property {Boolean} isRuleValid
*/
get isRuleValid() {
assert('Rule is defined', this.currentDisplayedRule);
return this.currentDisplayedRule.validations.isValid;
}
/**
* @property {Boolean} disableSave
*/
get disableSave() {
if (this.isSaving) {
return true;
}
return !(this.currentDisplayedRule?.hasDirtyAttributes && this.isRuleValid);
}
/**
* @action addNewRule
*/
@action
addNewRule() {
this.currentDisplayedRule = this._createNewDeliveryRule();
this.deliveryRules = [...this.deliveryRules, this.currentDisplayedRule];
}
/**
* @method _createNewDeliveryRule
* @private
* @returns {DS.Model} - new delivery rule model
*/
_createNewDeliveryRule() {
let newRule = this.store.createRecord('delivery-rule', {
recipients: [],
format: { type: this.formats.firstObject },
deliveredItem: this.args.model,
owner: this.user.getUser(),
});
assert('Delivery Rules are defined', this.deliveryRules);
return newRule;
}
/**
* @action doSave
*/
@action
async doSave() {
let rule = this.currentDisplayedRule;
if (rule?.validations.isValid) {
try {
await new RSVP.Promise((resolve, reject) => {
assert('The Rule is defined', rule);
this.args.onSave(rule, { resolve, reject });
});
assert('The currentDisplayedRule is defined', rule);
this.naviNotifications.add({
title: `'${
rule.name !== undefined ? rule.defaultName : capitalize(rule.name)
}' schedule successfully saved!`,
style: 'success',
timeout: 'short',
});
} catch (errors) {
this.notification = getAllApiErrMsg(
errors.errors[0],
`There was an error updating your delivery settings for schedule '${
rule.name !== undefined ? capitalize(rule.name) : rule.defaultName
}'`
);
} finally {
this.isSaving = false;
}
} else {
this.isSaving = false;
}
}
/**
* @action doDelete
*/
@action
async doDelete(deliveryRule: DeliveryRuleModel) {
assert('The currentDisplayedRule is defined', deliveryRule);
const name = deliveryRule.name ? deliveryRule.name : deliveryRule.defaultName;
const deletePromise = new RSVP.Promise((resolve, reject) => {
this.args.onDelete(deliveryRule, { resolve, reject });
});
try {
await deletePromise;
if (deliveryRule === this.currentDisplayedRule) {
//Make sure there is no more local rule after deletion
this.currentDisplayedRule = undefined;
}
this.deliveryRules = this.deliveryRules.filter((rule) => rule !== deliveryRule);
//Add Page notification
this.naviNotifications.add({
title: `Delivery schedule '${name}' removed`,
style: 'success',
timeout: 'short',
});
} catch (e) {
this.notification = [`An error occurred while removing the delivery schedule '${name}'`];
}
}
/**
* @action onOpen
*/
@action
async onOpen() {
try {
this.deliveryRules = await this.args.model.deliveryRulesForUser;
if (this.deliveryRules) {
this.currentDisplayedRule = this.deliveryRules[0] ? this.deliveryRules[0] : undefined;
if (this.currentDisplayedRule) {
if (this.formats.length === 1) {
this.updateFormat(this.formats[0]);
}
}
}
} catch (e) {
this.errorWhileFetchingRules = true;
this.notification = [`An error occurred while fetching your schedule(s) for this ${this.modelType}.`];
}
}
/**
* @action updateRecipients
* @param {Array} recipients - list of email strings
*/
@action
updateRecipients(recipients: string[]) {
assert('The currentDisplayedRule is defined', this.currentDisplayedRule);
this.currentDisplayedRule.recipients = recipients;
}
/**
* @action updateFormat
* @param {String} type - format type
*/
@action
updateFormat(type: string) {
assert('The currentDisplayedRule is defined', this.currentDisplayedRule);
assert('The format is defined', this.currentDisplayedRule.format);
this.currentDisplayedRule.format.type = type;
}
@action
toggleOverwriteFile() {
assert('The currentDisplayedRule is defined', this.currentDisplayedRule);
assert(
'Must be a type that supports overwriteFile in order to toggle',
this.overwriteableFormats.includes(this.currentDisplayedRule.format.type)
);
const format = this.currentDisplayedRule.format as GsheetFormat; //currently only type that supports this, make more dynamic with new types
if (!format.options) {
format.options = { overwriteFile: false };
}
const newOverwrite = !format.options?.overwriteFile;
format.options.overwriteFile = newOverwrite;
this.currentDisplayedRule.format = format;
// eslint-disable-next-line no-self-assign
this.currentDisplayedRule = this.currentDisplayedRule;
}
/**
* @action closeModal
*/
@action
closeModal() {
// Avoid `calling set on destroyed object` error
if (!this.isDestroyed && !this.isDestroying) {
if (this.deliveryRules.filter((rule) => rule.hasDirtyAttributes).length > 0) {
if (confirm('You have unsaved changes on your schedule(s), are you sure you want to exit?')) {
this.isSaving = false;
this.showModal = false;
this.notification = undefined;
this.revertAll();
}
} else {
this.isSaving = false;
this.showModal = false;
this.notification = undefined;
this.revertAll();
}
}
}
/**
* @action closeNotification
*/
@action
closeNotification() {
this.notification = undefined;
}
/**
* @action revertAll
*/
@action
revertAll() {
this.deliveryRules?.forEach((rule) => this.args.onRevert(rule));
this.deliveryRules
.filter((rule) => rule.isNew)
.forEach(
(rule) =>
new RSVP.Promise((resolve, reject) => {
this.args.onDelete(rule, { resolve, reject });
})
);
}
} | the_stack |
import * as path from 'path';
import * as ts from 'typescript';
import * as builtin from './builtin';
import { Context } from './Context';
import * as emit from './emit';
import * as format from './format';
import * as literal from './literal';
import { Local } from './Local';
import { Locals } from './Locals';
import { Type } from './type';
import { parse } from '../parse';
let labelCounter = 0;
function mangle(moduleName: string, local: string) {
return moduleName + '_' + local;
}
function identifier(id: ts.Identifier): string {
return id.escapedText as string;
}
function getType(context: Context, node: ts.Node) {
const flags = context.tc.getTypeAtLocation(node).getFlags();
const primitives = {
[ts.TypeFlags.String]: Type.V8String,
[ts.TypeFlags.Number]: Type.Number,
[ts.TypeFlags.Boolean]: Type.Boolean,
};
return primitives[flags] || Type.V8Value;
}
function setType(context: Context, node: ts.Node, local: Local) {
local.setType(getType(context, node));
}
function compileArrayLiteral(
context: Context,
destination: Local,
{ elements }: ts.ArrayLiteralExpression,
) {
let tmp;
if (!destination.initialized) {
tmp = destination;
} else {
tmp = context.locals.symbol('arr_lit');
}
tmp.setType(Type.V8Array);
tmp.setCode(`Array::New(isolate, ${elements.length})`);
const init = context.locals.symbol('init');
elements.forEach((e, i) => {
compileNode(context, init, e);
context.emitStatement(`${tmp}->Set(${i}, ${init.getCode()})`);
});
if (tmp !== destination) {
destination.setType(Type.V8Array);
builtin.assign(context, destination, tmp);
}
}
function compileBlock(context: Context, block: ts.Block) {
block.statements.forEach((statement, i) => {
compileNode(
{
...context,
tco: i < block.statements.length - 1 ? {} : context.tco,
},
context.locals.symbol('block'),
statement,
);
});
}
function compileParameter(
context: Context,
p: ts.ParameterDeclaration,
n: number,
last: boolean,
tailCallArgument?: Local,
) {
if (
p.name.kind === ts.SyntaxKind.ObjectBindingPattern ||
p.name.kind === ts.SyntaxKind.ArrayBindingPattern
) {
throw new Error('Parameter destructuring not supported');
}
const id = identifier(p.name);
const mangled = mangle(context.moduleName, id);
if (!tailCallArgument) {
const safe = context.locals.register(mangled);
setType(context, p.name, safe);
const argn = context.locals.symbol('arg');
argn.setCode(`args[${n}]`);
builtin.assign(context, safe, argn);
} else {
const safe = context.locals.get(mangled);
setType(context, p.name, safe);
builtin.assign(context, safe, tailCallArgument);
}
}
function compileFunctionDeclaration(
context: Context,
fd: ts.FunctionDeclaration,
) {
const name = fd.name ? identifier(fd.name) : 'lambda';
const mangled =
name === 'main' ? 'jsc_main' : mangle(context.moduleName, name);
const safe = context.locals.register(mangled, Type.Function);
const safeName = safe.getCode();
safe.initialized = true;
const tcoLabel = `tail_recurse_${labelCounter++}`;
context.emit(`void ${mangled}(const FunctionCallbackInfo<Value>& args) {`);
context.emitStatement(
'Isolate* isolate = args.GetIsolate()',
context.depth + 1,
);
const childContext = {
...context,
depth: context.depth + 1,
// Body, parameters get new context
locals: context.locals.clone(),
// Copying might not allow for mutually tail-recursive functions?
tco: {
...context.tco,
[safeName]: { label: tcoLabel, parameters: fd.parameters },
},
};
if (fd.parameters) {
fd.parameters.forEach((p, i) => {
compileParameter(childContext, p, i, i === fd.parameters.length - 1);
});
}
context.emitLabel(tcoLabel);
if (fd.body) {
compileBlock(childContext, fd.body);
}
context.emit('}\n');
}
function compileCall(
context: Context,
destination: Local,
ce: ts.CallExpression,
) {
let tcoLabel;
let tcoParameters;
if (ce.expression.kind === ts.SyntaxKind.Identifier) {
const id = identifier(ce.expression as ts.Identifier);
const safe = context.locals.get(mangle(context.moduleName, id));
if (safe && context.tco[safe.getCode()]) {
const safeName = safe.getCode();
tcoLabel = context.tco[safeName].label;
tcoParameters = context.tco[safeName].parameters;
}
}
const args = ce.arguments.map((argument) => {
const arg = context.locals.symbol('arg');
const argName = arg.getCode();
compileNode(context, arg, argument);
// Force initialization before TCE
if (tcoLabel && !arg.initialized) {
const initializer = arg.getCode();
arg.setCode(argName);
context.emitAssign(arg, initializer);
}
return arg;
});
// Handle tail call elimination
if (ce.expression.kind === ts.SyntaxKind.Identifier) {
const id = identifier(ce.expression as ts.Identifier);
const mangled = mangle(context.moduleName, id);
const safe = context.locals.get(mangled);
if (safe) {
if (tcoLabel) {
args.forEach((arg, i) => {
compileParameter(
context,
tcoParameters[i],
i,
i === args.length - 1,
arg,
);
});
context.emitStatement(`goto ${tcoLabel}`);
context.emit('', 0);
destination.tce = true;
return;
}
}
}
const argArray = context.locals.symbol('args');
if (!tcoLabel && args.length) {
context.emitStatement(
`Local<Value> ${argArray.getCode()}[] = { ${args
.map((a) => a.getCode(Type.V8Value))
.join(', ')} }`,
);
}
const fn = context.locals.symbol('fn');
compileNode(context, fn, ce.expression);
const argArrayName = args.length ? argArray.getCode() : 0;
const v8f = fn.getCode(Type.V8Function);
const call = `${v8f}->Call(${v8f}, ${args.length}, ${argArrayName})`;
builtin.assign(context, destination, call);
context.emit('', 0);
}
// TODO: prototype lookup
function compilePropertyAccess(
context: Context,
destination: Local,
pae: ts.PropertyAccessExpression,
) {
const exp = context.locals.symbol('parent');
compileNode(context, exp, pae.expression);
const id = identifier(pae.name);
const tmp = context.locals.symbol('prop_access');
tmp.setCode(
`${exp.getCode(Type.V8Object)}->Get(${format.v8String(
literal.string(id),
Type.String,
)})`,
);
builtin.assign(context, destination, tmp);
}
function compileElementAccess(
context: Context,
destination: Local,
eae: ts.ElementAccessExpression,
) {
const exp = context.locals.symbol('parent');
compileNode(context, exp, eae.expression);
const arg = context.locals.symbol('arg');
compileNode(context, arg, eae.argumentExpression);
const tmp = context.locals.symbol('elem_access');
tmp.setCode(`${exp.getCode(Type.V8Object)}->Get(${arg.getCode()})`);
builtin.assign(context, destination, tmp);
}
function compileIdentifier(
context: Context,
destination: Local,
id: ts.Identifier,
) {
const global = 'isolate->GetCurrentContext()->Global()';
const tmp = context.locals.symbol('ident');
let name = identifier(id);
const mangled = mangle(context.moduleName, name);
const local = context.locals.get(mangled);
if (local) {
builtin.assign(context, destination, local, true);
return;
} else if (name === 'global') {
tmp.setCode(global);
} else {
tmp.setCode(
`${global}->Get(${format.v8String(literal.string(name), Type.String)})`,
);
}
builtin.assign(context, destination, tmp);
}
function compileReturn(context: Context, exp?: ts.Expression) {
if (!exp) {
context.emitStatement('return');
return;
}
const tmp = context.locals.symbol('ret');
compileNode(context, tmp, exp);
if (!tmp.tce) {
context.emitStatement(
`args.GetReturnValue().Set(${tmp.getCode(Type.V8Value)})`,
);
context.emitStatement('return');
}
}
function compileIf(
context: Context,
exp: ts.Expression,
thenStmt: ts.Statement,
elseStmt?: ts.Statement,
) {
context.emit('', 0);
const test = context.locals.symbol('if_test', Type.Boolean);
compileNode(context, test, exp);
context.emit(`if (${test.getCode(Type.Boolean)}) {`);
const c = { ...context, depth: context.depth + 1 };
compileNode(c, context.locals.symbol('then'), thenStmt);
if (elseStmt) {
context.emit('} else {');
compileNode(c, context.locals.symbol('else'), elseStmt);
}
context.emit('}\n');
}
function compilePostfixUnaryExpression(
context: Context,
destination: Local,
pue: ts.PostfixUnaryExpression,
) {
const lhs = context.locals.symbol('pue');
compileNode(context, lhs, pue.operand);
// In `f++`, previous value of f is returned
builtin.assign(context, destination, lhs);
const tmp = context.locals.symbol('pue_tmp');
switch (pue.operator) {
case ts.SyntaxKind.PlusPlusToken:
builtin.plus(context, tmp, lhs, 1);
break;
case ts.SyntaxKind.MinusMinusToken:
builtin.plus(context, tmp, lhs, -1);
break;
default:
throw new Error('Unsupported operator: ' + ts.SyntaxKind[pue.operator]);
break;
}
compileAssign(context, destination, pue.operand, tmp);
}
function compileAssign(
context: Context,
destination: Local,
left: ts.Node,
rhs: Local,
) {
let tmp;
if (left.kind === ts.SyntaxKind.Identifier) {
const id = identifier(left as ts.Identifier);
const mangled = mangle(context.moduleName, id);
tmp = context.locals.get(mangled);
if (tmp) {
builtin.assign(context, tmp, rhs);
builtin.assign(context, destination, tmp);
return;
} else {
// This is an easy case, but punting for now.
throw new Error('Unsupported global assignment');
}
} else if (left.kind === ts.SyntaxKind.ElementAccessExpression) {
const eae = left as ts.ElementAccessExpression;
const exp = context.locals.symbol('parent');
compileNode(context, exp, eae.expression);
const arg = context.locals.symbol('arg');
compileNode(context, arg, eae.argumentExpression);
context.emitStatement(
`${exp.getCode(Type.V8Object)}->Set(${arg.getCode()}, ${rhs.getCode(
Type.V8Value,
)})`,
);
return;
} else if (left.kind === ts.SyntaxKind.PropertyAccessExpression) {
const pae = left as ts.PropertyAccessExpression;
const exp = context.locals.symbol('parent');
compileNode(context, exp, pae.expression);
const id = identifier(pae.name);
context.emitStatement(
`${exp.getCode(Type.V8Object)}->Set(${format.v8String(
literal.string(id),
Type.String,
)}, ${rhs.getCode(Type.V8Value)})`,
);
return;
}
throw new Error(
'Unsupported lhs assignment node: ' + ts.SyntaxKind[left.kind],
);
}
function compileBinaryExpression(
context: Context,
destination: Local,
be: ts.BinaryExpression,
) {
// Assignment is a special case.
if (be.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
const rhs = context.locals.symbol('rhs');
compileNode(context, rhs, be.right);
compileAssign(context, destination, be.left, rhs);
return;
} else if (be.operatorToken.kind === ts.SyntaxKind.PlusEqualsToken) {
const rhs = context.locals.symbol('rhs');
compileNode(context, rhs, be.right);
const lhs = context.locals.symbol('lhs');
compileNode(context, lhs, be.left);
const tmp = context.locals.symbol('plus_eq');
builtin.plus(context, tmp, lhs, rhs);
compileAssign(context, destination, be.left, tmp);
return;
}
const lhs = context.locals.symbol('lhs');
compileNode(context, lhs, be.left);
const rhs = context.locals.symbol('rhs');
compileNode(context, rhs, be.right);
const tmp = context.locals.symbol('bin_exp');
switch (be.operatorToken.kind) {
case ts.SyntaxKind.LessThanToken:
builtin.lessThan(context, tmp, lhs, rhs);
break;
case ts.SyntaxKind.GreaterThanToken:
builtin.greaterThan(context, tmp, lhs, rhs);
break;
case ts.SyntaxKind.LessThanEqualsToken:
builtin.lessThanEquals(context, tmp, lhs, rhs);
break;
case ts.SyntaxKind.GreaterThanEqualsToken:
builtin.greaterThanEquals(context, tmp, lhs, rhs);
break;
case ts.SyntaxKind.ExclamationEqualsToken:
builtin.notEquals(context, tmp, lhs, rhs);
break;
case ts.SyntaxKind.EqualsEqualsToken:
builtin.equals(context, tmp, lhs, rhs);
break;
case ts.SyntaxKind.ExclamationEqualsEqualsToken:
builtin.strictNotEquals(context, tmp, lhs, rhs);
break;
case ts.SyntaxKind.EqualsEqualsEqualsToken:
builtin.strictEquals(context, tmp, lhs, rhs);
break;
case ts.SyntaxKind.AmpersandAmpersandToken:
builtin.and(context, tmp, lhs, rhs);
break;
case ts.SyntaxKind.PlusToken:
builtin.plus(context, tmp, lhs, rhs);
break;
case ts.SyntaxKind.AsteriskToken:
builtin.times(context, tmp, lhs, rhs);
break;
case ts.SyntaxKind.MinusToken:
builtin.minus(context, tmp, lhs, rhs);
break;
default:
throw new Error(
'Unsupported binary operator: ' + ts.SyntaxKind[be.operatorToken.kind],
);
break;
}
builtin.assign(context, destination, tmp);
}
function compileVariable(
context: Context,
destination: Local,
vd: ts.VariableDeclaration,
flags: ts.NodeFlags,
) {
if (
vd.name.kind === ts.SyntaxKind.ObjectBindingPattern ||
vd.name.kind === ts.SyntaxKind.ArrayBindingPattern
) {
throw new Error('Variable destructuring not supported');
}
const id = identifier(vd.name);
const safe = context.locals.register(mangle(context.moduleName, id));
destination = safe;
const initializer = context.locals.symbol('var_init');
if (vd.initializer) {
compileNode(context, initializer, vd.initializer);
const isConst = (flags & ts.NodeFlags.Const) === ts.NodeFlags.Const;
const isExplicit = vd.type;
// Cannot infer on types at declaration without a separate pass.
if (isConst || isExplicit) {
//setType(context, vd.type || vd.name, destination);
destination.setType(initializer.getType());
}
builtin.assign(context, destination, initializer);
}
}
function compileDo(
context: Context,
{ statement: body, expression: test }: ts.DoStatement,
) {
context.emit('do {');
const bodyContext = { ...context, depth: context.depth + 1 };
compileNode(bodyContext, context.locals.symbol('do'), body);
const tmp = context.locals.symbol('test', Type.Boolean);
compileNode(bodyContext, tmp, test);
context.emitStatement(`} while (${tmp.getCode()})`);
}
function compileWhile(
context: Context,
{ statement: body, expression: exp }: ts.WhileStatement,
) {
const test = context.locals.symbol('while_test', Type.Boolean);
compileNode(context, test, exp);
context.emit(`while (${test.getCode(Type.Boolean)}) {`);
const bodyContext = { ...context, depth: context.depth + 1 };
compileNode(bodyContext, context.locals.symbol('while'), body);
compileNode(bodyContext, test, exp);
context.emit('}');
}
function compileFor(
context: Context,
{ initializer, condition, incrementor, statement: body }: ts.ForStatement,
) {
const init = context.locals.symbol('init');
if (initializer) {
compileNode(context, init, initializer);
}
const cond = context.locals.symbol('cond');
if (condition) {
compileNode(context, cond, condition);
}
const start = `start_for_${labelCounter++}`;
const end = `end_for_${labelCounter++}`;
context.emitLabel(start);
const childContext = { ...context, depth: context.depth + 1 };
const tmp = context.locals.symbol('body');
compileNode(childContext, tmp, body);
if (incrementor) {
compileNode(childContext, context.locals.symbol('inc'), incrementor);
}
if (condition) {
compileNode(childContext, cond, condition);
childContext.emit('', 0);
childContext.emitStatement(
`if (!${cond.getCode(Type.Boolean)}) goto ${end}`,
);
}
context.emitStatement(`goto ${start}`);
if (condition) {
context.emitLabel(end);
}
}
function compileImport(context: Context, id: ts.ImportDeclaration) {
// TODO: validate import was exported
const t =
id.importClause &&
id.importClause.namedBindings &&
id.importClause.namedBindings.kind === ts.SyntaxKind.NamedImports
? id.importClause.namedBindings
: { elements: undefined };
if (t.elements) {
const { text } = id.moduleSpecifier as ts.StringLiteral;
const fileName = path.resolve(context.directory, text);
const program = parse(fileName);
const moduleContext = {
...context,
depth: 0,
locals: new Locals(),
moduleName: '',
tco: {},
};
compile(program, moduleContext);
t.elements.forEach((exportObject) => {
if (exportObject.propertyName) {
throw new Error(
"Unsupported import style: import { <> as <> } from '<>';",
);
}
const exportName = identifier(exportObject.name);
// Put the name the module will reference into context
const local = context.locals.register(
mangle(context.moduleName, exportName),
);
// Grab the location it will have been registered in the other module
const real = moduleContext.locals.get(
mangle(moduleContext.moduleName, exportName),
);
// Set the local lookup type & value to the real lookup value & type
local.setCode(real.getCode());
local.setType(real.getType());
local.initialized = true;
});
return;
}
throw new Error('Unsupported import style');
}
function compileNode(context: Context, destination: Local, node: ts.Node) {
switch (node.kind) {
case ts.SyntaxKind.FunctionDeclaration: {
const fd = node as ts.FunctionDeclaration;
compileFunctionDeclaration(context, fd);
break;
}
case ts.SyntaxKind.ExpressionStatement: {
const es = node as ts.ExpressionStatement;
compileNode(context, destination, es.expression);
break;
}
case ts.SyntaxKind.VariableStatement: {
const vs = node as ts.VariableStatement;
compileNode(
{
...context,
tco: {},
},
destination,
vs.declarationList,
);
break;
}
case ts.SyntaxKind.VariableDeclarationList: {
const dl = node as ts.VariableDeclarationList;
dl.declarations.forEach((d) => {
compileVariable(
{
...context,
tco: {},
},
context.locals.symbol('var'),
d,
dl.flags,
);
});
break;
}
case ts.SyntaxKind.BinaryExpression: {
const be = node as ts.BinaryExpression;
compileBinaryExpression(
{
...context,
tco: {},
},
destination,
be,
);
break;
}
case ts.SyntaxKind.PostfixUnaryExpression: {
const pue = node as ts.PostfixUnaryExpression;
compilePostfixUnaryExpression(
{
...context,
tco: {},
},
destination,
pue,
);
break;
}
case ts.SyntaxKind.CallExpression: {
const ce = node as ts.CallExpression;
compileCall(context, destination, ce);
break;
}
case ts.SyntaxKind.PropertyAccessExpression: {
const pae = node as ts.PropertyAccessExpression;
compilePropertyAccess(
{
...context,
tco: {},
},
destination,
pae,
);
break;
}
case ts.SyntaxKind.ElementAccessExpression: {
const eae = node as ts.ElementAccessExpression;
compileElementAccess(
{
...context,
tco: {},
},
destination,
eae,
);
break;
}
case ts.SyntaxKind.Identifier: {
const id = node as ts.Identifier;
compileIdentifier(
{
...context,
tco: {},
},
destination,
id,
);
break;
}
case ts.SyntaxKind.StringLiteral: {
const sl = node as ts.StringLiteral;
const local = context.locals.symbol('string', Type.String);
local.setCode(literal.string(sl.text));
builtin.assign(context, destination, local, true);
break;
}
case ts.SyntaxKind.NullKeyword: {
const local = context.locals.symbol('null', Type.V8Null);
local.setCode('Null(isolate)');
builtin.assign(context, destination, local, true);
break;
}
case ts.SyntaxKind.TrueKeyword: {
const local = context.locals.symbol('boolean', Type.Boolean);
local.setCode(true);
builtin.assign(context, destination, local, true);
break;
}
case ts.SyntaxKind.FalseKeyword: {
const local = context.locals.symbol('boolean', Type.Boolean);
local.setCode(false);
builtin.assign(context, destination, local, true);
break;
}
case ts.SyntaxKind.ArrayLiteralExpression: {
const ale = node as ts.ArrayLiteralExpression;
compileArrayLiteral(
{
...context,
tco: {},
},
destination,
ale,
);
break;
}
case ts.SyntaxKind.FirstLiteralToken:
case ts.SyntaxKind.NumericLiteral: {
const nl = node as ts.NumericLiteral;
const local = context.locals.symbol('num', Type.Number);
local.setCode(+nl.text);
builtin.assign(context, destination, local, true);
break;
}
case ts.SyntaxKind.DoStatement: {
const ds = node as ts.DoStatement;
compileDo(
{
...context,
tco: {},
},
ds,
);
break;
}
case ts.SyntaxKind.WhileStatement: {
const ws = node as ts.WhileStatement;
compileWhile(
{
...context,
tco: {},
},
ws,
);
break;
}
case ts.SyntaxKind.ForStatement: {
const fs = node as ts.ForStatement;
compileFor(
{
...context,
tco: {},
},
fs,
);
break;
}
case ts.SyntaxKind.ReturnStatement: {
const rs = node as ts.ReturnStatement;
compileReturn(context, rs.expression);
break;
}
case ts.SyntaxKind.IfStatement: {
const is = node as ts.IfStatement;
compileIf(context, is.expression, is.thenStatement, is.elseStatement);
break;
}
case ts.SyntaxKind.Block: {
const b = node as ts.Block;
compileBlock(context, b);
break;
}
case ts.SyntaxKind.ImportDeclaration: {
const id = node as ts.ImportDeclaration;
compileImport(
{
...context,
tco: {},
},
id,
);
break;
}
case ts.SyntaxKind.ExportDeclaration: {
// TODO: add export to exports list;
break;
}
case ts.SyntaxKind.EndOfFileToken:
break;
default:
throw new Error(
'Unsupported syntax element: ' + ts.SyntaxKind[node.kind],
);
}
}
export function compileSource(context: Context, ast: ts.SourceFile) {
const locals = new Locals();
ts.forEachChild(ast, (node) => {
compileNode(context, locals.symbol('source'), node);
});
}
function emitPrefix(buffer: string[]) {
emit.emit(buffer, 0, `#include "lib.cc"\n`);
}
function emitPostfix(buffer: string[]) {
emit.emit(
buffer,
0,
`void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "jsc_main", jsc_main);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n`,
);
}
export function compile(program: ts.Program, context?: Context) {
const isDependency = !!context;
const buffer = context ? context.buffer : [];
if (!isDependency) {
emitPrefix(buffer);
}
const tc = program.getTypeChecker();
program.getSourceFiles().forEach((source) => {
const { fileName } = source;
if (fileName.endsWith('.d.ts')) {
return;
}
const directory = path.dirname(fileName);
// TODO: mangle module name appropriately (e.g. replace('.', '_'), etc.)
const moduleName = path.basename(fileName, path.extname(fileName));
// May be wrong to recreate this on every source file? But for now
// getSourceFile only returns the entrypoint, not imports...
if (!context) {
context = {
buffer,
depth: 0,
directory,
emit(s: string, d?: number) {
emit.emit(this.buffer, d === undefined ? this.depth : d, s);
},
emitAssign(l: Local, s: string | null, d?: number) {
emit.assign(this.buffer, d === undefined ? this.depth : d, l, s);
},
emitStatement(s: string, d?: number) {
emit.statement(this.buffer, d === undefined ? this.depth : d, s);
},
emitLabel(s: string, d?: number) {
emit.label(this.buffer, d === undefined ? this.depth : d, s);
},
locals: new Locals(),
moduleName,
tc,
tco: {},
};
}
compileSource(context, source);
});
if (!isDependency) {
emitPostfix(buffer);
}
return buffer.join('\n');
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormProduct {
interface Header extends DevKit.Controls.IHeader {
/** Status of the product. */
StateCode: DevKit.Controls.OptionSet;
}
interface tab_FieldService_Sections {
tab_3_section_1: DevKit.Controls.Section;
tab_3_section_3: DevKit.Controls.Section;
tab_3_section_4: DevKit.Controls.Section;
}
interface tab_notes_Sections {
notes: DevKit.Controls.Section;
}
interface tab_price_list_items_Sections {
knowledgesection: DevKit.Controls.Section;
msdynsales_pricing_information: DevKit.Controls.Section;
price_list_items_section: DevKit.Controls.Section;
productsubstitute_items_section: DevKit.Controls.Section;
}
interface tab_product_details_Sections {
costs: DevKit.Controls.Section;
product_information: DevKit.Controls.Section;
}
interface tab_product_dynamic_properties_Sections {
product_dynamic_properties_section: DevKit.Controls.Section;
}
interface tab_productassocaition_items_Sections {
DynamicProperties: DevKit.Controls.Section;
productassocaition_items_section: DevKit.Controls.Section;
}
interface tab_FieldService extends DevKit.Controls.ITab {
Section: tab_FieldService_Sections;
}
interface tab_notes extends DevKit.Controls.ITab {
Section: tab_notes_Sections;
}
interface tab_price_list_items extends DevKit.Controls.ITab {
Section: tab_price_list_items_Sections;
}
interface tab_product_details extends DevKit.Controls.ITab {
Section: tab_product_details_Sections;
}
interface tab_product_dynamic_properties extends DevKit.Controls.ITab {
Section: tab_product_dynamic_properties_Sections;
}
interface tab_productassocaition_items extends DevKit.Controls.ITab {
Section: tab_productassocaition_items_Sections;
}
interface Tabs {
FieldService: tab_FieldService;
notes: tab_notes;
price_list_items: tab_price_list_items;
product_details: tab_product_details;
product_dynamic_properties: tab_product_dynamic_properties;
productassocaition_items: tab_productassocaition_items;
}
interface Body {
Tab: Tabs;
/** Current cost for the product item. Used in price calculations. */
CurrentCost: DevKit.Controls.Money;
/** Current cost for the product item. Used in price calculations. */
CurrentCost_1: DevKit.Controls.Money;
/** Default unit for the product. */
DefaultUoMId: DevKit.Controls.Lookup;
/** Default unit group for the product. */
DefaultUoMScheduleId: DevKit.Controls.Lookup;
/** Description of the product. */
Description: DevKit.Controls.String;
/** Specify whether a product is to be converted to a customer asset. When a product is used on a work order, the system will automatically convert it into a customer asset when the work order is closed. */
msdyn_ConvertToCustomerAsset: DevKit.Controls.Boolean;
/** Default vendor that supplies this product */
msdyn_DefaultVendor: DevKit.Controls.Lookup;
msdyn_FieldServiceProductType: DevKit.Controls.OptionSet;
/** Type the name for the product when used on a purchase order. */
msdyn_PurchaseName: DevKit.Controls.String;
/** Select whether the item is taxable. If an item is set as not taxable, it won't be taxable even on a taxable work order. */
msdyn_Taxable: DevKit.Controls.Boolean;
/** Shows the UPC Code for product. Used for bar code scanning. */
msdyn_UPCCode: DevKit.Controls.String;
/** Name of the product. */
Name: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
/** Specifies the parent product family hierarchy. */
ParentProductId: DevKit.Controls.Lookup;
/** Specifies the parent product family hierarchy. */
ParentProductId_1: DevKit.Controls.Lookup;
/** List price for the product item. Used in price calculations. */
Price: DevKit.Controls.Money;
/** Select the default price list for the product. */
PriceLevelId: DevKit.Controls.Lookup;
/** User-defined product ID. */
ProductNumber: DevKit.Controls.String;
/** Number of decimal places that can be used in monetary amounts for the product. */
QuantityDecimal: DevKit.Controls.Integer;
/** Standard cost for the product item. Used in price calculations. */
StandardCost: DevKit.Controls.Money;
/** Standard cost for the product item. Used in price calculations. */
StandardCost_1: DevKit.Controls.Money;
/** Select a category for the product. */
SubjectId: DevKit.Controls.Lookup;
/** Date from which this product is valid. */
ValidFromDate: DevKit.Controls.Date;
/** Date to which this product is valid. */
ValidToDate: DevKit.Controls.Date;
}
interface Navigation {
nav_msdyn_product_msdyn_agreementbookingproduct_Product: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_agreementbookingservice_Service: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_agreementinvoiceproduct_Product: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_customerasset_Product: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_fieldservicepricelistitem_ProductService: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_fieldservicesetting: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_incidenttypeproduct_Product: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_incidenttypeservice_Service: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_inventoryadjustmentproduct_Product: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_inventoryjournal_Product: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_productinventory_Product: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_purchaseorderproduct_Product: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_rmaproduct_Product: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_rtvproduct_Product: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_workorderproduct_Product: DevKit.Controls.NavigationItem,
nav_msdyn_product_msdyn_workorderservice_Service: DevKit.Controls.NavigationItem,
navAsyncOperations: DevKit.Controls.NavigationItem,
navComps: DevKit.Controls.NavigationItem,
navDocument: DevKit.Controls.NavigationItem,
navPrices: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem,
navProductBundles: DevKit.Controls.NavigationItem,
navSalesLit: DevKit.Controls.NavigationItem,
navSubs: DevKit.Controls.NavigationItem
}
interface Grid {
productassocaition_items: DevKit.Controls.Grid;
product_dynamic_properties: DevKit.Controls.Grid;
product_dynamic_properties_offline: DevKit.Controls.Grid;
Price_List_Items: DevKit.Controls.Grid;
productsubstitute_items: DevKit.Controls.Grid;
KnowledgeArticlesSubGrid: DevKit.Controls.Grid;
}
}
class FormProduct extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Product
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Product */
Body: DevKit.FormProduct.Body;
/** The Header section of form Product */
Header: DevKit.FormProduct.Header;
/** The Navigation of form Product */
Navigation: DevKit.FormProduct.Navigation;
/** The Grid of form Product */
Grid: DevKit.FormProduct.Grid;
}
namespace FormProduct_Project_Information {
interface Header extends DevKit.Controls.IHeader {
/** Status of the product. */
StateCode: DevKit.Controls.OptionSet;
}
interface tab_notes_Sections {
notes: DevKit.Controls.Section;
}
interface tab_price_list_items_Sections {
price_list_items_section: DevKit.Controls.Section;
productsubstitute_items_section: DevKit.Controls.Section;
}
interface tab_product_computed_fields_Sections {
tab_6_section_1: DevKit.Controls.Section;
tab_6_section_2: DevKit.Controls.Section;
}
interface tab_product_details_Sections {
costs: DevKit.Controls.Section;
product_information: DevKit.Controls.Section;
}
interface tab_product_dynamic_properties_Sections {
product_dynamic_properties_section: DevKit.Controls.Section;
}
interface tab_productassocaition_items_Sections {
DynamicProperties: DevKit.Controls.Section;
productassocaition_items_section: DevKit.Controls.Section;
}
interface tab_notes extends DevKit.Controls.ITab {
Section: tab_notes_Sections;
}
interface tab_price_list_items extends DevKit.Controls.ITab {
Section: tab_price_list_items_Sections;
}
interface tab_product_computed_fields extends DevKit.Controls.ITab {
Section: tab_product_computed_fields_Sections;
}
interface tab_product_details extends DevKit.Controls.ITab {
Section: tab_product_details_Sections;
}
interface tab_product_dynamic_properties extends DevKit.Controls.ITab {
Section: tab_product_dynamic_properties_Sections;
}
interface tab_productassocaition_items extends DevKit.Controls.ITab {
Section: tab_productassocaition_items_Sections;
}
interface Tabs {
notes: tab_notes;
price_list_items: tab_price_list_items;
product_computed_fields: tab_product_computed_fields;
product_details: tab_product_details;
product_dynamic_properties: tab_product_dynamic_properties;
productassocaition_items: tab_productassocaition_items;
}
interface Body {
Tab: Tabs;
/** Current cost for the product item. Used in price calculations. */
CurrentCost: DevKit.Controls.Money;
/** Default unit for the product. */
DefaultUoMId: DevKit.Controls.Lookup;
/** Default unit group for the product. */
DefaultUoMScheduleId: DevKit.Controls.Lookup;
/** Description of the product. */
Description: DevKit.Controls.String;
/** Name of the product. */
Name: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
/** Specifies the parent product family hierarchy. */
ParentProductId: DevKit.Controls.Lookup;
/** List price for the product item. Used in price calculations. */
Price: DevKit.Controls.Money;
/** Select the default price list for the product. */
PriceLevelId: DevKit.Controls.Lookup;
/** User-defined product ID. */
ProductNumber: DevKit.Controls.String;
/** Number of decimal places that can be used in monetary amounts for the product. */
QuantityDecimal: DevKit.Controls.Integer;
/** Standard cost for the product item. Used in price calculations. */
StandardCost: DevKit.Controls.Money;
/** Select a category for the product. */
SubjectId: DevKit.Controls.Lookup;
/** Date from which this product is valid. */
ValidFromDate: DevKit.Controls.Date;
/** Date to which this product is valid. */
ValidToDate: DevKit.Controls.Date;
}
interface Navigation {
navDocument: DevKit.Controls.NavigationItem,
navPrices: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
interface Grid {
productassocaition_items: DevKit.Controls.Grid;
product_dynamic_properties: DevKit.Controls.Grid;
Computed_Fields: DevKit.Controls.Grid;
Price_List_Items: DevKit.Controls.Grid;
productsubstitute_items: DevKit.Controls.Grid;
}
}
class FormProduct_Project_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Product_Project_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Product_Project_Information */
Body: DevKit.FormProduct_Project_Information.Body;
/** The Header section of form Product_Project_Information */
Header: DevKit.FormProduct_Project_Information.Header;
/** The Navigation of form Product_Project_Information */
Navigation: DevKit.FormProduct_Project_Information.Navigation;
/** The Grid of form Product_Project_Information */
Grid: DevKit.FormProduct_Project_Information.Grid;
}
namespace FormProduct_Quick_Create_FS_5x5 {
interface tab_tab_1_Sections {
tab_1_column_1_section_1: DevKit.Controls.Section;
tab_1_column_2_section_1: DevKit.Controls.Section;
tab_1_column_3_section_1: DevKit.Controls.Section;
}
interface tab_tab_1 extends DevKit.Controls.ITab {
Section: tab_tab_1_Sections;
}
interface Tabs {
tab_1: tab_tab_1;
}
interface Body {
Tab: Tabs;
/** Default unit for the product. */
DefaultUoMId: DevKit.Controls.Lookup;
/** Default unit group for the product. */
DefaultUoMScheduleId: DevKit.Controls.Lookup;
msdyn_FieldServiceProductType: DevKit.Controls.OptionSet;
/** Name of the product. */
Name: DevKit.Controls.String;
/** User-defined product ID. */
ProductNumber: DevKit.Controls.String;
}
}
class FormProduct_Quick_Create_FS_5x5 extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Product_Quick_Create_FS_5x5
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Product_Quick_Create_FS_5x5 */
Body: DevKit.FormProduct_Quick_Create_FS_5x5.Body;
}
namespace FormProduct_family_Quick_Create {
interface tab_tab_1_Sections {
tab_1_column_1_section_1: DevKit.Controls.Section;
tab_1_column_2_section_1: DevKit.Controls.Section;
}
interface tab_tab_1 extends DevKit.Controls.ITab {
Section: tab_tab_1_Sections;
}
interface Tabs {
tab_1: tab_tab_1;
}
interface Body {
Tab: Tabs;
/** Default unit for the product. */
DefaultUoMId: DevKit.Controls.Lookup;
/** Default unit group for the product. */
DefaultUoMScheduleId: DevKit.Controls.Lookup;
/** Name of the product. */
Name: DevKit.Controls.String;
/** Specifies the parent product family hierarchy. */
ParentProductId: DevKit.Controls.Lookup;
/** User-defined product ID. */
ProductNumber: DevKit.Controls.String;
/** Number of decimal places that can be used in monetary amounts for the product. */
QuantityDecimal: DevKit.Controls.Integer;
/** Date from which this product is valid. */
ValidFromDate: DevKit.Controls.Date;
/** Date to which this product is valid. */
ValidToDate: DevKit.Controls.Date;
}
}
class FormProduct_family_Quick_Create extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Product_family_Quick_Create
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Product_family_Quick_Create */
Body: DevKit.FormProduct_family_Quick_Create.Body;
}
namespace FormProduct_Quick_Create {
interface tab_tab_1_Sections {
tab_1_column_1_section_1: DevKit.Controls.Section;
tab_1_column_2_section_1: DevKit.Controls.Section;
tab_1_column_3_section_1: DevKit.Controls.Section;
}
interface tab_tab_1 extends DevKit.Controls.ITab {
Section: tab_tab_1_Sections;
}
interface Tabs {
tab_1: tab_tab_1;
}
interface Body {
Tab: Tabs;
/** Default unit for the product. */
DefaultUoMId: DevKit.Controls.Lookup;
/** Default unit group for the product. */
DefaultUoMScheduleId: DevKit.Controls.Lookup;
/** Description of the product. */
Description: DevKit.Controls.String;
/** Name of the product. */
Name: DevKit.Controls.String;
/** Specifies the parent product family hierarchy. */
ParentProductId: DevKit.Controls.Lookup;
/** User-defined product ID. */
ProductNumber: DevKit.Controls.String;
/** Number of decimal places that can be used in monetary amounts for the product. */
QuantityDecimal: DevKit.Controls.Integer;
/** Select a category for the product. */
SubjectId: DevKit.Controls.Lookup;
/** Date from which this product is valid. */
ValidFromDate: DevKit.Controls.Date;
/** Date to which this product is valid. */
ValidToDate: DevKit.Controls.Date;
}
}
class FormProduct_Quick_Create extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Product_Quick_Create
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Product_Quick_Create */
Body: DevKit.FormProduct_Quick_Create.Body;
}
class ProductApi {
/**
* DynamicsCrm.DevKit ProductApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the product. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the external party who created the record. */
CreatedByExternalParty: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the product. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Current cost for the product item. Used in price calculations. */
CurrentCost: DevKit.WebApi.MoneyValue;
/** Value of the Current Cost in base currency. */
CurrentCost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Default unit for the product. */
DefaultUoMId: DevKit.WebApi.LookupValue;
/** Default unit group for the product. */
DefaultUoMScheduleId: DevKit.WebApi.LookupValue;
/** Description of the product. */
Description: DevKit.WebApi.StringValue;
/** Internal Use Only */
DMTImportState: DevKit.WebApi.IntegerValue;
/** Shows the default image for the record. */
EntityImage: DevKit.WebApi.StringValue;
EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly;
EntityImage_URL: DevKit.WebApi.StringValueReadonly;
EntityImageId: DevKit.WebApi.GuidValueReadonly;
/** Exchange rate for the currency associated with the product with respect to the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Hierarchy path of the product. */
HierarchyPath: DevKit.WebApi.StringValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Information that specifies whether the product is a kit. */
IsKit: DevKit.WebApi.BooleanValue;
IsReparented: DevKit.WebApi.BooleanValue;
/** Information about whether the product is a stock item. */
IsStockItem: DevKit.WebApi.BooleanValue;
/** Unique identifier of the user who last modified the product. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the external party who modified the record. */
ModifiedByExternalParty: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who last modified the product. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Specify whether a product is to be converted to a customer asset. When a product is used on a work order, the system will automatically convert it into a customer asset when the work order is closed. */
msdyn_ConvertToCustomerAsset: DevKit.WebApi.BooleanValue;
/** Default vendor that supplies this product */
msdyn_DefaultVendor: DevKit.WebApi.LookupValue;
msdyn_FieldServiceProductType: DevKit.WebApi.OptionSetValue;
/** Type the name for the product when used on a purchase order. */
msdyn_PurchaseName: DevKit.WebApi.StringValue;
/** Select whether the item is taxable. If an item is set as not taxable, it won't be taxable even on a taxable work order. */
msdyn_Taxable: DevKit.WebApi.BooleanValue;
/** Select the transaction category for this product. */
msdyn_TransactionCategory: DevKit.WebApi.LookupValue;
/** Shows the UPC Code for product. Used for bar code scanning. */
msdyn_UPCCode: DevKit.WebApi.StringValue;
/** Name of the product. */
Name: DevKit.WebApi.StringValue;
/** Unique identifier for the organization */
OrganizationId: DevKit.WebApi.LookupValueReadonly;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Specifies the parent product family hierarchy. */
ParentProductId: DevKit.WebApi.LookupValue;
/** List price for the product item. Used in price calculations. */
Price: DevKit.WebApi.MoneyValue;
/** Value of the List Price in base currency. */
Price_Base: DevKit.WebApi.MoneyValueReadonly;
/** Select the default price list for the product. */
PriceLevelId: DevKit.WebApi.LookupValue;
/** Contains the id of the process associated with the entity. */
ProcessId: DevKit.WebApi.GuidValue;
/** Unique identifier of the product. */
ProductId: DevKit.WebApi.GuidValue;
/** User-defined product ID. */
ProductNumber: DevKit.WebApi.StringValue;
/** Product Structure. */
ProductStructure: DevKit.WebApi.OptionSetValue;
/** Type of product. */
ProductTypeCode: DevKit.WebApi.OptionSetValue;
/** URL for the Website associated with the product. */
ProductUrl: DevKit.WebApi.StringValue;
/** Number of decimal places that can be used in monetary amounts for the product. */
QuantityDecimal: DevKit.WebApi.IntegerValue;
/** Quantity of the product in stock. */
QuantityOnHand: DevKit.WebApi.DecimalValue;
/** Product size. */
Size: DevKit.WebApi.StringValue;
/** Contains the id of the stage where the entity is located. */
StageId: DevKit.WebApi.GuidValue;
/** Standard cost for the product item. Used in price calculations. */
StandardCost: DevKit.WebApi.MoneyValue;
/** Value of the Standard Cost in base currency. */
StandardCost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Status of the product. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the product. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Stock volume of the product. */
StockVolume: DevKit.WebApi.DecimalValue;
/** Stock weight of the product. */
StockWeight: DevKit.WebApi.DecimalValue;
/** Select a category for the product. */
SubjectId: DevKit.WebApi.LookupValue;
/** Name of the product's supplier. */
SupplierName: DevKit.WebApi.StringValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the currency associated with the product. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */
TraversedPath: DevKit.WebApi.StringValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Date from which this product is valid. */
ValidFromDate_DateOnly: DevKit.WebApi.DateOnlyValue;
/** Date to which this product is valid. */
ValidToDate_DateOnly: DevKit.WebApi.DateOnlyValue;
/** Unique identifier of vendor supplying the product. */
VendorID: DevKit.WebApi.StringValue;
/** Name of the product vendor. */
VendorName: DevKit.WebApi.StringValue;
/** Unique part identifier in vendor catalog of this product. */
VendorPartNumber: DevKit.WebApi.StringValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace Product {
enum msdyn_FieldServiceProductType {
/** 690970000 */
Inventory,
/** 690970001 */
Non_Inventory,
/** 690970002 */
Service
}
enum ProductStructure {
/** 1 */
Product,
/** 3 */
Product_Bundle,
/** 2 */
Product_Family
}
enum ProductTypeCode {
/** 4 */
Flat_Fees,
/** 2 */
Miscellaneous_Charges,
/** 1 */
Sales_Inventory,
/** 3 */
Services
}
enum StateCode {
/** 0 */
Active,
/** 2 */
Draft,
/** 1 */
Retired,
/** 3 */
Under_Revision
}
enum StatusCode {
/** 1 */
Active,
/** 0 */
Draft,
/** 2 */
Retired,
/** 3 */
Under_Revision
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Product','Product Quick Create FS 5x5','Project Information','Quick Create','Quick Create'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { ISearchMatch, ISearchProvider } from '@jupyterlab/documentsearch';
import { SpreadsheetEditorDocumentWidget } from './documentwidget';
import { Widget } from '@lumino/widgets';
import { DocumentWidget } from '@jupyterlab/docregistry';
import { SpreadsheetWidget } from './widget';
import { ISignal, Signal } from '@lumino/signaling';
import { JExcelElement } from 'jexcel';
export interface ICellCoordinates {
column: number;
row: number;
}
class CoordinatesSet {
protected _set: Set<string>;
constructor() {
this._set = new Set<string>();
}
protected _valueToString(value: ICellCoordinates): string {
if (typeof value === 'undefined') {
return value;
}
return value.column + '|' + value.row;
}
protected _stringToValue(value: string): ICellCoordinates {
if (typeof value === 'undefined') {
return value;
}
const parts = value.split('|');
if (parts.length !== 2) {
console.warn('A problem with stringToValue input detected!');
}
return {
column: parseInt(parts[0], 10),
row: parseInt(parts[1], 10)
};
}
add(value: ICellCoordinates): this {
this._set.add(this._valueToString(value));
return this;
}
delete(value: ICellCoordinates): boolean {
return this._set.delete(this._valueToString(value));
}
has(value: ICellCoordinates): boolean {
return this._set.has(this._valueToString(value));
}
values(): IterableIterator<ICellCoordinates> {
const iterator = this._set.values();
const stringToValue = this._stringToValue;
return {
[Symbol.iterator](): IterableIterator<ICellCoordinates> {
return this;
},
return(value: any): IteratorResult<ICellCoordinates> {
const returned = iterator.return(value);
return {
done: returned.done,
value: stringToValue(returned.value)
};
},
next() {
const next = iterator.next();
return {
done: next.done,
value: stringToValue(next.value)
};
},
throw() {
const thrown = iterator.throw();
return {
done: thrown.done,
value: stringToValue(thrown.value)
};
}
};
}
clear() {
return this._set.clear();
}
}
export class SpreadsheetSearchProvider
implements ISearchProvider<SpreadsheetEditorDocumentWidget> {
/**
* Report whether or not this provider has the ability to search on the given object
*/
static canSearchOn(
domain: Widget
): domain is SpreadsheetEditorDocumentWidget {
// check to see if the SpreadsheetSearchProvider can search on the
// first cell, false indicates another editor is present
return (
domain instanceof DocumentWidget &&
domain.content instanceof SpreadsheetWidget
);
}
private mostRecentSelectedCell: any;
get changed(): ISignal<this, void> {
return this._changed;
}
get currentMatchIndex() {
return this._currentMatchIndex;
}
readonly isReadOnly: boolean;
get matches(): ISearchMatch[] {
return this._matches;
}
endQuery(): Promise<void> {
this.backlightOff();
this._currentMatchIndex = null;
this._matches = [];
this._sheet.changed.disconnect(this._onSheetChanged, this);
return Promise.resolve(undefined);
}
private backlightOff() {
for (const matchCoords of this.backlitMatches.values()) {
const cell: HTMLElement = this._target.getCellFromCoords(
matchCoords.column,
matchCoords.row
);
cell.classList.remove('se-backlight');
}
this.backlitMatches.clear();
}
async endSearch(): Promise<void> {
// restore the selection
// eslint-disable-next-line eqeqeq
if (this._target.selectedCell == null && this.mostRecentSelectedCell) {
this._target.selectedCell = this.mostRecentSelectedCell;
}
return this.endQuery();
}
private getSelectedCellCoordinates(): ICellCoordinates {
const target = this._target;
const columns = target.getSelectedColumns();
const rows = target.getSelectedRows(true);
if (rows.length === 1 && columns.length === 1) {
return {
column: columns[0],
row: rows[0]
};
}
}
private _initialQueryCoodrs: ICellCoordinates;
getInitialQuery(searchTarget: SpreadsheetEditorDocumentWidget): any {
this._target = searchTarget.content.jexcel;
const coords = this.getSelectedCellCoordinates();
this._initialQueryCoodrs = coords;
if (coords) {
const value = this._target.getValueFromCoords(
coords.column,
coords.row,
false
);
if (value) {
return value;
}
}
return null;
}
async highlightNext(): Promise<ISearchMatch | undefined> {
if (this._currentMatchIndex + 1 < this.matches.length) {
this._currentMatchIndex += 1;
} else {
this._currentMatchIndex = 0;
}
const match = this.matches[this.currentMatchIndex];
if (!match) {
return;
}
this.highlight(match);
return match;
}
async highlightPrevious(): Promise<ISearchMatch | undefined> {
if (this._currentMatchIndex > 0) {
this._currentMatchIndex -= 1;
} else {
this._currentMatchIndex = this.matches.length - 1;
}
const match = this.matches[this.currentMatchIndex];
if (!match) {
return;
}
this.highlight(match);
return match;
}
highlight(match: ISearchMatch) {
this.backlightMatches();
// select the matched cell, which leads to a loss of "focus" (or rather jexcel eagerly intercepting events)
this._target.updateSelectionFromCoords(
match.column,
match.line,
match.column,
match.line,
null
);
// "regain" focus by erasing selection information (but keeping all the CSS) - this is a workaround (best avoided)
this.mostRecentSelectedCell = this._target.selectedCell;
this._target.selectedCell = null;
this._sheet.scrollCellIntoView({ row: match.line, column: match.column });
}
async replaceAllMatches(newText: string): Promise<boolean> {
for (let i = 0; i < this.matches.length; i++) {
this._currentMatchIndex = i;
await this.replaceCurrentMatch(newText, true);
}
this._matches = this.findMatches();
this.backlightMatches();
return true;
}
async replaceCurrentMatch(
newText: string,
isReplaceAll = false
): Promise<boolean> {
let replaceOccurred = false;
const match = this.matches[this.currentMatchIndex];
const cell = this._target.getValueFromCoords(
match.column,
match.line,
false
);
let index = -1;
let matchesInCell = 0;
const newValue = String(cell).replace(this._query, substring => {
index += 1;
matchesInCell += 1;
if (index === match.index) {
replaceOccurred = true;
return newText;
}
return substring;
});
let subsequentIndex = this.currentMatchIndex + 1;
while (subsequentIndex < this.matches.length) {
const subsequent = this.matches[subsequentIndex];
if (
subsequent.column === match.column &&
subsequent.line === match.line
) {
subsequent.index -= 1;
} else {
break;
}
subsequentIndex += 1;
}
this._target.setValueFromCoords(match.column, match.line, newValue, false);
if (!isReplaceAll && matchesInCell === 1) {
const matchCoords = { column: match.column, row: match.line };
const cell: HTMLElement = this._target.getCellFromCoords(
match.column,
match.line
);
cell.classList.remove('se-backlight');
this.backlitMatches.delete(matchCoords);
}
if (!isReplaceAll) {
await this.highlightNext();
}
return replaceOccurred;
}
private _onSheetChanged() {
// matches may need updating
this._matches = this.findMatches(false);
// update backlight
this.backlightOff();
this.backlightMatches();
this._changed.emit(undefined);
}
protected backlitMatches: CoordinatesSet;
/**
* Highlight n=1000 matches around the current match.
* The number of highlights is limited to prevent negative impact on the UX in huge notebooks.
*/
protected backlightMatches(n = 1000): void {
for (
let i = Math.max(0, this._currentMatchIndex - n / 2);
i < Math.min(this._currentMatchIndex + n / 2, this.matches.length);
i++
) {
const match = this.matches[i];
const matchCoord = {
column: match.column,
row: match.line
};
if (!this.backlitMatches.has(matchCoord)) {
const cell: HTMLElement = this._target.getCellFromCoords(
match.column,
match.line
);
cell.classList.add('se-backlight');
this.backlitMatches.add(matchCoord);
}
}
}
protected findMatches(highlightFirst = true): ISearchMatch[] {
const currentCellCoordinates = this._initialQueryCoodrs;
this._initialQueryCoodrs = null;
let currentMatchIndex = 0;
const matches: ISearchMatch[] = [];
const data = this._target.getData();
let rowNumber = 0;
let columnNumber = -1;
let index = 0;
let totalMatchIndex = 0;
for (const row of data) {
for (const cell of row) {
columnNumber += 1;
if (!cell) {
continue;
}
const matched = String(cell).match(this._query);
if (!matched) {
continue;
}
index = 0;
if (
// eslint-disable-next-line eqeqeq
currentCellCoordinates != null &&
currentCellCoordinates.row === rowNumber &&
currentCellCoordinates.column === columnNumber
) {
currentMatchIndex = totalMatchIndex;
}
for (const match of matched) {
matches.push({
line: rowNumber,
column: columnNumber,
index: index,
fragment: match,
text: match
});
index += 1;
totalMatchIndex += 1;
}
}
columnNumber = -1;
rowNumber += 1;
}
this._currentMatchIndex = currentMatchIndex;
this._matches = matches;
if (matches.length && highlightFirst) {
this.highlight(matches[this._currentMatchIndex]);
}
return matches;
}
constructor() {
this.backlitMatches = new CoordinatesSet();
}
async startQuery(
query: RegExp,
searchTarget: SpreadsheetEditorDocumentWidget
): Promise<ISearchMatch[]> {
if (!SpreadsheetSearchProvider.canSearchOn(searchTarget)) {
throw new Error('Cannot find Spreadsheet editor instance to search');
}
this._sheet = searchTarget.content;
this._query = query;
this._target = searchTarget.content.jexcel;
this._target.resetSelection(true);
this._target.el.blur();
this._sheet.changed.connect(this._onSheetChanged, this);
return this.findMatches();
}
private _changed = new Signal<this, void>(this);
private _target: JExcelElement;
private _sheet: SpreadsheetWidget;
private _query: RegExp;
private _matches: ISearchMatch[];
private _currentMatchIndex: number;
} | the_stack |
declare module 'rn-components-kit' {
import * as React from 'react';
import {
ViewStyle,
TextStyle,
TextProps,
Constructor,
ImageRequireSource,
NativeMethodsMixin,
TouchableOpacityProps,
} from 'react-native'
interface BadgeProps {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* Determines whether it is rendered as a dot without number in it
* default: true
*/
dot?: boolean;
/**
* Determines the dot's color
* default: '#F5222D'
*/
color?: string;
/**
* If you specify the count prop, you should set dot prop `false` as well (they are two exclusive modes).
* And in this case, this number would be rendered at the center of dot
* default: 0
*/
count?: number;
/**
* Max count to show. If count is greater than overflowCount, it will be displayed as `${overflowCount}+`
* default: 99
*/
overflowCount?: number;
/**
* Determines whether it should be shown when count is 0
* default: false
*/
showZero?: boolean;
/**
* If you are not satisfied with the dot's position (upper-right corner), you can adjust it through offsetX/offsetY
* default: 0
*/
offsetX?: number;
/**
* If you are not satisfied with the dot's position (upper-right corner), you can adjust it through offsetX/offsetY
* default: 0
*/
offsetY?: number;
}
export const Badge: React.SFC<BadgeProps>;
interface ButtonProps {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* Text to display in button
*/
text?: string;
/**
* Icon to display in button
*/
icon?: string;
/**
* Determines icon's direction in button is left or right
* default: true
*/
iconLeft?: boolean;
/**
* Button type
* default: 'default'
*/
type?: 'default' | 'primary' | 'success' | 'warning' | 'danger' | 'link';
/**
* Button size
* default: 'default'
*/
size?: 'small' | 'default' | 'large';
/**
* Button Shape
* default: 'default'
*/
shape?: 'default' | 'round' | 'square';
/**
* Block level button
* default: false
*/
block?: boolean;
/**
* Applies outline button style
* default: false
*/
outline?: boolean;
/**
* Applies link button style
* default: false
*/
link?: boolean;
}
interface ThemeConfig {
default?: string;
primary?: string;
warning?: string;
danger?: string;
success?: string;
}
interface SizeConfig {
fontSize?: number;
borderRadius?: number;
paddingHorizontal?: number;
paddingVertical?: number;
iconTextSpacing?: number;
}
interface Preset {
theme?: ThemeConfig;
small?: SizeConfig;
default?: SizeConfig;
large?: SizeConfig;
}
interface ButtonComponent<T> extends React.SFC<T> {
updatePreset: (preset: Preset) => void;
}
export const Button: ButtonComponent<ButtonProps & TouchableOpacityProps>;
interface CarouselProps {
/**
* Allow you to customize style
*/
style?: ViewStyle;
data?: any;
/**
* Determines the position when carousel first show
* default: 0
*/
initialIndex?: number;
/**
* Determines whether carousel can be dragged to slide to prev/next one
* default: true
*/
draggable?: boolean;
/**
* Determines whether caousel is in horizontal or vertical direction
* default: false
*/
vertical?: boolean;
/**
* The width of carousel (when carousel is horizontal mode, width and itemWidth must be set)
*/
width?: number;
/**
* The height of carousel (when carousel is vertical mode, height and itemHeight must be set)
*/
height?: number;
/**
* The width of each item in carousel (when carousel is horizontal mode, width and itemWidth must be set)
* default: 0
*/
itemWidth?: number;
/**
* The height of each item in carousel (when carousel is vertical mode, height and itemHeight must be set)
* default: 0
*/
itemHeight?: number;
/**
* When item's length is smaller than container, gap can be used to separate items
* default: 0
*/
gap?: number;
/**
* Determines whether carousel's loop mode is enabled
* default: false
*/
loop?: boolean;
/**
* When loop mode is enabled, there will be `cloneCount` copied elements placed
* at both sides of items
* default: 3
*/
cloneCount?: number;
/**
* When item's length is smaller than container, item would be adjusted to the center
* of carousel if centerModeEnabled is true. In this case, prev/current/next elements will
* be all in one screen
* default: false
*/
centerModeEnabled?: boolean;
/**
* Determines whether auto play mode is enabled
* default: false
*/
autoPlay?: boolean;
/**
* When auto play mode is enabled, it determines how long it takes between two scrolling animations (ms)
* default: 3000
*/
autoPlayDelay?: number;
/**
* Determines whether pagination module is shown in carousel
* default: false
*/
showPagination?: boolean;
/**
* Allow you to customize pagination's container style
*/
paginationStyle?: ViewStyle;
/**
* Allow you to customize pagination's dot style
*/
dotStyle?: ViewStyle;
/**
* Allow you to customize pagination's current dot style
*/
curDotStyle?: ViewStyle;
/**
* Allow you to customize pagination module
*/
renderPagination?: (info: {curIndex: number, total: number}) => React.ReactElement | null;
/**
* A callback will be triggered when carousel's scrollIndex changes
* default: () => {}
*/
onIndexChange?: (from: number, to: number) => void;
}
export class Carousel extends React.PureComponent<CarouselProps> {
/**
* Scrolls to prev element
*/
scrollToPrev(): void;
/**
* Scrolls to next element
*/
scrollToNext(): void;
/**
* Scrolls to the item at the specified index
*/
scrollToIndex(param: {index: number, animated: boolean}): void;
}
interface CheckBoxProps {
/**
* Allows you to customize style
*/
style?: ViewStyle;
/**
* Title of checkbox
*/
title: string;
/**
* Allows you to customize title's style
*/
titleStyle?: TextStyle;
/**
* Size of icon (or width and height for image, if you specify checkedImage/unCheckedImage)
* default: 20
*/
iconSize?: number;
/**
* Determines whether checkbox is available
*/
disabled?: boolean;
/**
* Flag for checking the icon
* default: false
*/
checked: boolean;
/**
* Checked icon (Icon Preset: https://github.com/SmallStoneSK/rn-components-kit/tree/master/packages/Icon)
* default: 'check-square-fill'
*/
checkedIconType?: string;
/**
* Color of checked icon
* default: '#1890FF'
*/
checkedIconColor?: string;
/**
* If you are not satisfied with icon preset, you can specify an image for checked icon
*/
checkedImage?: string | ImageRequireSource;
/**
* UnChecked icon (Icon Preset: https://github.com/SmallStoneSK/rn-components-kit/tree/master/packages/Icon)
* default: 'border'
*/
unCheckedIconType?: string;
/**
* Color of unChecked icon
* default: '#BFBFBF'
*/
unCheckedIconColor?: string;
/**
* If you are not satisfied with icon preset, you can specify an image for unChecked icon
*/
unCheckedImage?: string | ImageRequireSource;
/**
* Determines which animation is adpoted when checked value changes
* default: 'opacity'
*/
animationType?: 'none' | 'opacity' | 'size'
/**
* A callback will be triggered when checkbox is pressed
* default: () => {}
*/
onPress?: () => void;
}
export class CheckBox extends React.PureComponent<CheckBoxProps> {}
interface DeckSwiperProps<T> {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* Data source of cards
*/
data: T[];
/**
* Width of card (it is important to help calculate animation)
*/
cardWidth: number;
/**
* Height of card (it is important to help calculate animation)
*/
cardHeight: number;
/**
* Takes an item from data and renders it into the swiper
*/
renderCard: (params: {item: T, index: number}) => React.ReactElement | null;
/**
* When all cards are swiped, it will be called and returns bottom layer component
*/
renderBottom?: () => React.ReactElement | null;
/**
* A callback will be triggered when card is swiped left
* default: () => {}
*/
onSwipeLeft?: (from: number, to: number) => void;
/**
* A callback will be triggered when card is swiped right
* default: () => {}
*/
onSwipeRight?: (from: number, to: number) => void;
/**
* A callback will be triggered when you begin to drag SwipeOut
* default: () => {}
*/
onBeginDragging?: () => void;
/**
* A callback will be triggered when dragging operation ends
* default: () => {}
*/
onEndDragging?: () => void;
}
export class DeckSwiper<T> extends React.PureComponent<DeckSwiperProps<T>> {
/**
* Swipes to previous card
*/
prev: () => void;
/**
* Swipes to next card
*/
next: () => void;
}
interface DividerProps {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* Determines the divider's color
* default: '#DFDFDF'
*/
color?: string;
/**
* Determines the divider's orientation
* default: 'horizontal'
*/
orientation?: 'horizontal' | 'vertical';
/**
* Space between two sides on cross axis
* default: 0
*/
margin?: number;
/**
* Space inside two sides on main axis
* default: 0
*/
padding?: number;
}
export const Divider: React.SFC<DividerProps>;
interface IconProps {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* Determines the icon's color
* default: '#333'
*/
color?: string;
/**
* Determines the icon's size
* default: 15
*/
size?: number;
/**
* Icon type, integrated in Ant-Design Preset(https://ant.design/components/icon/)
*/
type: (
'check-circle' |
'ci' |
'dollar' |
'compass' |
'close-circle' |
'frown' |
'info-circle' |
'left-circle' |
'down-circle' |
'euro' |
'copyright' |
'minus-circle' |
'meh' |
'plus-circle' |
'play-circle' |
'question-circle' |
'pound' |
'right-circle' |
'smile' |
'trademark' |
'time-circle' |
'time-out' |
'earth' |
'yuan' |
'up-circle' |
'warning-circle' |
'sync' |
'transaction' |
'undo' |
'redo' |
'reload' |
'reload-time' |
'message' |
'dashboard' |
'issues-close' |
'poweroff' |
'logout' |
'pie-chart' |
'setting' |
'eye' |
'location' |
'edit-square' |
'export' |
'save' |
'import' |
'app-store' |
'close-square' |
'down-square' |
'layout' |
'left-square' |
'play-square' |
'control' |
'code-library' |
'detail' |
'minus-square' |
'plus-square' |
'right-square' |
'project' |
'wallet' |
'up-square' |
'calculator' |
'interation' |
'check-square' |
'border' |
'border-outer' |
'border-top' |
'border-bottom' |
'border-left' |
'border-right' |
'border-inner' |
'border-verticle' |
'border-horizontal' |
'radius-bottomleft' |
'radius-bottomright' |
'radius-upleft' |
'radius-upright' |
'radius-setting' |
'add-user' |
'delete-team' |
'delete-user' |
'addteam' |
'user' |
'team' |
'area-chart' |
'line-chart' |
'bar-chart' |
'point-map' |
'container' |
'database' |
'sever' |
'mobile' |
'tablet' |
'red-envelope' |
'book' |
'file-done' |
'reconciliation' |
'file--exception' |
'file-sync' |
'file-search' |
'solution' |
'file-protect' |
'file-add' |
'file-excel' |
'file-exclamation' |
'file-pdf' |
'file-image' |
'file-markdown' |
'file-unknown' |
'file-ppt' |
'file-word' |
'file' |
'file-zip' |
'file-text' |
'file-copy' |
'snippets' |
'audit' |
'diff' |
'batch-folding' |
'security-scan' |
'property-safety' |
'safety-certificate' |
'insurance' |
'alert' |
'delete' |
'hourglass' |
'bulb' |
'experiment' |
'bell' |
'trophy' |
'rest' |
'usb' |
'skin' |
'home' |
'bank' |
'filter' |
'funnel-plot' |
'like' |
'unlike' |
'unlock' |
'lock' |
'customer-service' |
'flag' |
'money-collect' |
'medicinebox' |
'shop' |
'rocket' |
'shopping' |
'folder' |
'folder-open' |
'folder-add' |
'deployment-unit' |
'account-book' |
'contacts' |
'carry-out' |
'calendar-check' |
'calendar' |
'scan' |
'select' |
'box-plot' |
'build' |
'sliders' |
'laptop' |
'barcode' |
'camera' |
'cluster' |
'gateway' |
'car' |
'printer' |
'read' |
'cloud-server' |
'cloud-upload' |
'cloud' |
'cloud-download' |
'cloud-sync' |
'video' |
'notification' |
'sound' |
'radar-chart' |
'qrcode' |
'fund' |
'image' |
'mail' |
'table' |
'id-card' |
'credit-card' |
'heart' |
'block' |
'error' |
'star' |
'gold' |
'heat-map' |
'wifi' |
'attachment' |
'edit' |
'key' |
'api' |
'disconnect' |
'highlight' |
'monitor' |
'link' |
'man' |
'percentage' |
'pushpin' |
'phone' |
'shake' |
'tag' |
'wrench' |
'tags' |
'scissor' |
'mr' |
'share' |
'branches' |
'fork' |
'shrink' |
'arrawsalt' |
'vertical-right' |
'vertical-left' |
'right' |
'left' |
'up' |
'down' |
'fullscreen' |
'fullscreen-exit' |
'doubleleft' |
'double-right' |
'arrowright' |
'arrowup' |
'arrowleft' |
'arrowdown' |
'upload' |
'colum-height' |
'vertical-align-botto' |
'vertical-align-middl' |
'totop' |
'vertical-align-top' |
'download' |
'sort-descending' |
'sort-ascending' |
'fall' |
'swap' |
'stock' |
'rise' |
'indent' |
'outdent' |
'menu' |
'unordered-list' |
'ordered-list' |
'align-right' |
'align-center' |
'align-left' |
'pic-center' |
'pic-right' |
'pic-left' |
'bold' |
'font-colors' |
'exclaimination' |
'font-size' |
'infomation' |
'line-height' |
'strikethrough' |
'underline' |
'number' |
'italic' |
'code' |
'column-width' |
'check' |
'ellipsis' |
'dash' |
'close' |
'enter' |
'line' |
'minus' |
'question' |
'rollback' |
'small-dash' |
'pause' |
'bg-colors' |
'crown' |
'drag' |
'desktop' |
'gift' |
'stop' |
'fire' |
'thunderbolt' |
'check-circle-fill' |
'left-circle-fill' |
'down-circle-fill' |
'minus-circle-fill' |
'close-circle-fill' |
'info-circle-fill' |
'up-circle-fill' |
'right-circle-fill' |
'plus-circle-fill' |
'question-circle-fill' |
'euro-circle-fill' |
'frown-fill' |
'copyright-circle-fil' |
'ci-circle-fill' |
'compass-fill' |
'dollar-circle-fill' |
'poweroff-circle-fill' |
'meh-fill' |
'play-circle-fill' |
'pound-circle-fill' |
'smile-fill' |
'stop-fill' |
'warning-circle-fill' |
'time-circle-fill' |
'trademark-circle-fil' |
'yuan-circle-fill' |
'heart-fill' |
'pie-chart-circle-fil' |
'dashboard-fill' |
'message-fill' |
'check-square-fill' |
'down-square-fill' |
'minus-square-fill' |
'close-square-fill' |
'code-library-fill' |
'left-square-fill' |
'play-square-fill' |
'up-square-fill' |
'right-square-fill' |
'plus-square-fill' |
'account-book-fill' |
'carry-out-fill' |
'calendar-fill' |
'calculator-fill' |
'interation-fill' |
'project-fill' |
'detail-fill' |
'save-fill' |
'wallet-fill' |
'control-fill' |
'layout-fill' |
'app-store-fill' |
'mobile-fill' |
'tablet-fill' |
'book-fill' |
'red-envelope-fill' |
'safety-certificate-fill' |
'property-safety-fill' |
'insurance-fill' |
'security-scan-fill' |
'file-exclamation-fil' |
'file-add-fill' |
'file-fill' |
'file-excel-fill' |
'file-markdown-fill' |
'file-text-fill' |
'file-ppt-fill' |
'file-unknown-fill' |
'file-word-fill' |
'file-zip-fill' |
'file-pdf-fill' |
'file-image-fill' |
'diff-fill' |
'file-copy-fill' |
'snippets-fill' |
'batch-folding-fill' |
'reconciliation-fill' |
'folder-add-fill' |
'folder-fill' |
'folder-open-fill' |
'database-fill' |
'container-fill' |
'sever-fill' |
'calendar-check-fill' |
'image-fill' |
'id-card-fill' |
'credit-card-fill' |
'fund-fill' |
'read-fill' |
'contacts-fill' |
'delete-fill' |
'notification-fill' |
'flag-fill' |
'money-collect-fill' |
'medicine-box-fill' |
'rest-fill' |
'shopping-fill' |
'skin-fill' |
'video-fill' |
'sound-fill' |
'bulb-fill' |
'bell-fill' |
'filter-fill' |
'fire-fill' |
'funnel-plot-fill' |
'gift-fill' |
'hourglass-fill' |
'home-fill' |
'trophy-fill' |
'location-fill' |
'cloud-fill' |
'customer-service-fill' |
'experiment-fill' |
'eye-fill' |
'like-fill' |
'lock-fill' |
'unlike-fill' |
'star-fill' |
'unlock-fill' |
'alert-fill' |
'api-fill' |
'highlight-fill' |
'phone-fill' |
'edit-fill' |
'pushpin-fill' |
'rocket-fill' |
'thunderbolt-fill' |
'tag-fill' |
'wrench-fill' |
'tags-fill' |
'bank-fill' |
'camera-fill' |
'error-fill' |
'crown-fill' |
'mail-fill' |
'car-fill' |
'printer-fill' |
'shop-fill' |
'setting-fill' |
'usb-fill' |
'golden-fill' |
'build-fill' |
'box-plot-fill' |
'sliders-fill' |
'alibaba' |
'alibabacloud' |
'ant-design' |
'ant-cloud' |
'behance' |
'google-plus' |
'medium' |
'google' |
'ie' |
'amazon' |
'slack' |
'alipay' |
'taobao' |
'zhihu' |
'html5' |
'linkedin' |
'yahoo' |
'facebook' |
'skype' |
'codesandbox' |
'chrome' |
'codepen' |
'aliwangwang' |
'apple' |
'android' |
'sketch' |
'gitlab' |
'dribbble' |
'instagram' |
'reddit' |
'windows' |
'yuque' |
'youtube' |
'gitlab-fill' |
'dropbox' |
'dingtalk' |
'android-fill' |
'apple-fill' |
'html5-fill' |
'windows-fill' |
'qq' |
'twitter' |
'skype-fill' |
'weibo' |
'yuque-fill' |
'youtube-fill' |
'yahoo-fill' |
'wechat-fill' |
'chrome-fill' |
'alipay-circle-fill' |
'aliwangwang-fill' |
'behance-circle-fill' |
'amazon-circle-fill' |
'codepen-circle-fill' |
'codesandbox-circle-fill' |
'dropbox-circle-fill' |
'github-fill' |
'dribbble-circle-fill' |
'google-plus-circle-fill' |
'medium-circle-fill' |
'qq-circle-fill' |
'ie-circle-fill' |
'google-circle-fill' |
'dingtalk-circle-fill' |
'sketch-circle-fill' |
'slack-circle-fill' |
'twitter-circle-fill' |
'taobao-circle-fill' |
'weibo-circle-fill' |
'zhihu-circle-fill' |
'reddit-circle-fill' |
'alipay-square-fill' |
'dingtalk-square-fill' |
'codesandbox-square-fill' |
'behance-square-fill' |
'amazon-square-fill' |
'codepen-square-fill' |
'dribbble-square-fill' |
'dropbox-square-fill' |
'facebook-fill' |
'google-plus-square-fill' |
'google-square-fill' |
'instagram-fill' |
'ie-square-fill' |
'medium-square-fill' |
'linkedin-fill' |
'qq-square-fill' |
'reddit-square-fill' |
'twitter-square-fill' |
'sketch-square-fill' |
'slack-square-fill' |
'taobao-square-fill' |
'weibo-square-fill' |
'zhihu-square-fill' |
'zoom-out' |
'apartment' |
'audio' |
'audio-fill' |
'robot' |
'zoom-in' |
'robot-fill' |
'bug-fill' |
'bug' |
'audio-static' |
'comment' |
'signal-fill' |
'verified' |
'shortcut-fill' |
'videocamera-add' |
'switch-user' |
'whatsapp' |
'appstore-add' |
'caret-down' |
'backward' |
'caret-up' |
'caret-right' |
'caret-left' |
'fast-backward' |
'forward' |
'fast-forward' |
'search' |
'retweet' |
'login' |
'step-backward' |
'step-forward' |
'swap-right' |
'swap-left' |
'woman' |
'plus' |
'eye-close-fill' |
'eye-close' |
'clear' |
'collapse' |
'expand' |
'delete-column' |
'merge-cells' |
'subnode' |
'rotate-left' |
'rotate-right' |
'insert-row-below' |
'insert-row-above' |
'solit-cells' |
'format-painter' |
'insert-row-right' |
'format-painter-fill' |
'insert-row-left' |
'translate' |
'delete-row' |
'sister-node'
);
}
export const Icon: React.SFC<IconProps>;
interface ProgressProps {
/**
* Allows you to customize style
*/
style?: ViewStyle;
/**
* Determine progress bar's type
* default: 'line'
*/
type?: 'line' | 'circle';
/**
* Current completion percentage
* default: 0
*/
percent?: number;
/**
* Status of progress
* default: 'normal'
*/
status?: 'normal' | 'active' | 'success' | 'fail';
/**
* Line width of progress bar
* default: 6
*/
lineWidth?: number;
/**
* Highlight color of progress bar
* default: '#40A9FF'
*/
color?: string;
/**
* Color of progress track
* default: '#EFEFEF'
*/
trackColor?: string;
/**
* Radius of circle (only works when type is 'circle')
* default: 50
*/
radius?: number;
/**
* Determines whether to display info area (percent tip and icon)
* default: true
*/
showInfo?: boolean;
/**
* Allows you to customize percent tip's style (only works when type is 'line')
*/
lineInfoTextStyle?: TextStyle;
/**
* Allows you to customize percent tip's style (only works when type is 'circle')
*/
circleInfoTextStyle?: TextStyle;
/**
* Progress will pass value to percentFormatter, and display its return value in info area
* default: value => `${value}%`
*/
percentFormatter?: (value: number) => string;
/**
* Allow you to fully customize info area
*/
renderInfo?: () => React.ReactElement;
}
export class Progress extends React.PureComponent<ProgressProps> {}
interface RadiosGroupProps {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* Default value to speficy which radio button is selected initially
*/
defaultValue?: any;
/**
* A callback will be triggered when selected value changes
*/
onValueChange?: (value: any) => void;
}
interface RadioButtonProps {
/**
* Allows you to customize style
*/
style?: ViewStyle;
/**
* According to value for comparison, to determine whether the selected
*/
value: any;
/**
* Title of radio button
*/
title: string;
/**
* Allows you to customize title's style
*/
titleStyle?: TextStyle;
/**
* Size of icon (or width and height for image, if you specify checkedImage/unCheckedImage)
* default: 20
*/
iconSize?: number;
/**
* Determines whether radio button is available
*/
disabled?: boolean;
/**
* Flag for checking the icon
* default: false
*/
checked?: boolean;
/**
* Checked icon (Icon Preset: https://github.com/SmallStoneSK/rn-components-kit/tree/master/packages/Icon)
* default: 'check-radio'
*/
checkedIconType?: string;
/**
* Color of checked icon
* default: '#1890FF'
*/
checkedIconColor?: string;
/**
* If you are not satisfied with icon preset, you can specify an image for checked icon
*/
checkedImage?: string | ImageRequireSource;
/**
* UnChecked icon (Icon Preset: https://github.com/SmallStoneSK/rn-components-kit/tree/master/packages/Icon)
* default: 'circle'
*/
unCheckedIconType?: string;
/**
* Color of unChecked icon
* default: '#BFBFBF'
*/
unCheckedIconColor?: string;
/**
* If you are not satisfied with icon preset, you can specify an image for unChecked icon
*/
unCheckedImage?: string | ImageRequireSource;
/**
* Determines which animation is adpoted when checked value changes
* default: 'size'
*/
animationType?: 'none' | 'opacity' | 'size'
/**
* A callback will be triggered when radio button is pressed
* default: () => {}
*/
onPress?: () => void;
}
export const Radio: {
Group: React.ComponentClass<RadiosGroupProps>,
Button: React.SFC<RadioButtonProps>
}
interface RatingProps {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* The granularity that Rating can step through values
* default: 1
*/
step?: 0.1 | 0.2 | 0.5 | 1;
/**
* Count of star
* default: 5
*/
total?: number;
/**
* Current count of active star
* default: 0
*/
value?: number;
/**
* Space between stars
* default: 4
*/
iconGap?: number;
/**
* Size of star icon
* default: 20
*/
iconSize?: number;
/**
* Determines whether value can be changed
* default: false
*/
disabled?: boolean;
/**
* Icon type when it is active
* default: 'star-fill'
*/
activeIconType?: string;
/**
* Icon color when it is active
* default: '#FADB14'
*/
activeIconColor?: string;
/**
* Icon type when it is inactive
* default: 'star-fill'
*/
inActiveIconType?: string;
/**
* Icon color when it is inactive
* default: '#E8E8E8'
*/
inActiveIconColor?: string;
/**
* A callback will be triggered when Rating's value changes
* default: () => {}
*/
onValueChange?: (value: number) => void;
}
export class Rating extends React.PureComponent<RatingProps> {}
interface ScrollPickerProps {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* Height of each item in ScrollPicker.Item
* default: 30
*/
itemHeight?: number;
/**
* A callback will be triggered when ScrollPicker.Item's selected value changes
* default: () => {}
*/
onValueChange?: (value: {[key: string]: any}) => void;
}
interface ScrollPickItemProps<T> {
/**
* A unique identifier in ScrollPicker
*/
id: string;
/**
* How much of the remaining space in the flex container
* default: 1
*/
flex?: number;
/**
* Data source of options
*/
data: T[];
/**
* Default value to speficy which option is selected initially (must be one of data)
* default: data[0]
*/
defaultValue?: T;
/**
* Allows you to customize content style
*/
renderItem: (params: {item: T, index: number}) => React.ReactElement;
}
class ScrollPickerItem<T> extends React.PureComponent<ScrollPickItemProps<T>> {}
export class ScrollPicker extends React.PureComponent<ScrollPickerProps> {
static Item: typeof ScrollPickerItem;
}
interface AvatarProps {
/**
* Allow you to customize avatar module's style (e.g. margin, backgroundColor)
*/
style?: ViewStyle;
/**
* The width and height of avatar
* default: 20
*/
size?: number;
/**
* The shape of avatar
* default: 'circle'
*/
shape?: 'circle' | 'square';
}
interface TitleProps {
/**
* Allow you to customize title block's style (e.g. margin, backgroundColor)
*/
style?: ViewStyle;
/**
* The width of title block (if undefined or null, default 100%)
*/
width?: number | string;
/**
* The height of title block
* default: 15
*/
height?: number;
}
interface ParagraphProps {
/**
* Allow you to customize paragraph module's style
*/
style?: ViewStyle;
/**
* The count of paragraph block lines
* default: 3
*/
rows?: number;
/**
* An array of each block's width (if undefined or null, default 100%)
* default: []
*/
widths?: Array<number|string>;
/**
* An array of each block's height (if undefined or null, default 15)
* default: []
*/
heights?: number[];
}
interface SkeletonProps {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* Show avatar placeholder
* default: true
*/
avatar?: boolean | AvatarProps;
/**
* Show title placeholder
* default: true
*/
title?: boolean | TitleProps;
/**
* Show paragraph placeholder
* default: true
*/
paragraph?: boolean | ParagraphProps;
}
export class Skeleton extends React.PureComponent<SkeletonProps> {}
interface withSkeletonOptions {
/**
* How long a loop animation lasts
* default: 1000
*/
duraion: number;
/**
* The minimum opacity value during animation
* default: 0.2
*/
minOpacity: number;
/**
* The maximum opacity value during animation
* default: 1
*/
maxOpacity: number;
}
export function withSkeleton (
options?: withSkeletonOptions
) : <P extends Object>(WrappedComponent: React.ComponentType<P>) => React.ComponentType<P & {opacity: number}>
interface SliderProps {
/**
* Allows you to customize style
*/
style?: ViewStyle;
/**
* The minimum value that thumb can slide to
* default: 0
*/
min?: number;
/**
* The maximum value that thumb can slide to
* default: 100
*/
max?: number;
/**
* The granularity the slider can step through values. (Must greater than 0, and be divided by (max - min))
* default: 1
*/
step?: number;
/**
* The initial value when first render slider
*/
defaultValue: number | number[];
/**
* Determines whether one or two thumbs in slider
* default: false
*/
multi?: boolean;
/**
* Determines whether slider is horizontal or vertical
* default: false
*/
vertical?: boolean;
/**
* Determines whether tooltip is shown
* default: true
*/
showTip?: 'never' | 'onTap' | 'always';
/**
* Allows you to customize tip's container style (e.g. size, backgroundColor)
*/
tipContainerStyle?: ViewStyle;
/**
* Allows you to customize tip's text style (e.g. fontSize, color)
*/
tipTextStyle?: TextStyle;
/**
* Color of track
* default: '#DDD'
*/
trackColor?: string;
/**
* Color of track's selected part
* default: '#40A9FF'
*/
selectedTrackColor?: string;
/**
* Allows you to customize thumb's style (e.g. color, size, shadow)
*/
thumbStyle?: ViewStyle;
/**
* Allows you to fully customize thumb module
*/
renderThumb?: () => React.ReactElement;
/**
* Slider will pass value to tipFormatter, and display its return value in tooltip
* default: value => value.toString();
*/
tipFormatter?: (value: number) => string;
/**
* A callback will be triggered when slider's value changes
* default: () => {}
*/
onValueChange?: (value: number) => void;
/**
* A callback will be triggered when slider starts to slider
* default: () => {}
*/
onBeginSliding?: () => void;
/**
* A callback will be triggered when slider ends to slider
* default: () => {}
*/
onEndSliding?: () => void;
}
export class Slider extends React.PureComponent<SliderProps> {}
interface BaseSpinProps {
/**
* Allows you to customize style
*/
style?: ViewStyle;
/**
* Zooming in/out scale of component
* default: 1
*/
scale?: number;
/**
* Duration of a looped animation
*/
duration?: number;
}
interface CommonSpinProps extends BaseSpinProps {
/**
* Color of elements inside component
* default: '#40A9FF'
*/
color?: string;
}
interface RainbowProps extends BaseSpinProps {
/**
* Five colors passed to rainbow
* default: ['#EA7671', '#81D2B4', '#A963B8', '#70ACF6', '#F4B860']
*/
colors?: string[];
}
interface WaveProps extends CommonSpinProps {
/**
* Type of wave
* default: 'rect'
*/
type?: 'rect' | 'dot';
}
export class Ladder extends React.PureComponent<CommonSpinProps> {}
export class Rainbow extends React.PureComponent<RainbowProps> {}
export class Wave extends React.PureComponent<WaveProps> {}
export class RollingCubes extends React.PureComponent<CommonSpinProps> {}
export class ChasingCircles extends React.PureComponent<CommonSpinProps> {}
export class Pulse extends React.PureComponent<CommonSpinProps> {}
export class FlippingCard extends React.PureComponent<CommonSpinProps> {}
interface SwipeOutOption {
/**
* Text to display in button
*/
title: string;
/**
* Background color of button
*/
color?: string;
/**
* Callback will be triggered when pressing the button
*/
onPress: () => void;
}
interface SwipeOutProps {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* The config for left hidden part. It supports followings:
* 1. function[() => React.ReactElement]: allows you to fully customize the hidden component
* 2. object[Option]: a pre-setted style for button, you need to specify title, color and onPress
* 3. array[Option[]]: multiple buttons
*/
left?: () => React.ReactElement | SwipeOutOption | SwipeOutOption[] | null;
/**
* The config for right hidden part (same to left)
*/
right?: () => React.ReactElement | SwipeOutOption | SwipeOutOption[] | null;
/**
* A callback will be triggered when you begin to drag SwipeOut
* default: () => {}
*/
onBeginDragging?: () => void;
/**
* A callback will be triggered when dragging operation ends
* default: () => {}
*/
onEndDragging?: () => void;
}
export class SwipeOut extends React.PureComponent<SwipeOutProps> {}
interface SwitchProps {
/**
* Allows you to customize style
*/
style?: ViewStyle;
/**
* Two types (cupertino for IOS and material for Android)
* default: 'cupertino'
*/
type?: 'cupertino' | 'material';
/**
* Determines whether switch is on when initial rendering
* default: false
*/
value?: boolean;
/**
* Determines whether switch is touchabled
* default: false
*/
disabled?: boolean;
/**
* Width of switch
* default: 40
*/
width?: number;
/**
* Height of switch's track
* default: 20
*/
height?: number;
/**
* Radius of thumb
* default: 8
*/
thumbRadius?: number;
/**
* Color of thumb
* default: '#FFF'
*/
thumbColor?: string;
/**
* Color of track when switch is "on" status
* default: '#79D472'
*/
trackOnColor?: string;
/**
* Color of track when switch is "off" status
* default: '#CCC'
*/
trackOffColor?: string;
/**
* A callback will be triggered when switch's status changes
* default: () => {}
*/
onValueChange?: (value: boolean) => void;
}
export class Switch extends React.PureComponent<SwitchProps> {}
interface TagProps {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* Text inside tag to display
*/
text: string;
/**
* Determines the tag's type (outline or solid)
* default: 'outline'
*/
type?: 'outline' | 'solid';
/**
* Determines the tag's color
* default: '#333'
*/
color?: string;
/**
* Determines the fontSize of tag's text
* default: 14
*/
fontSize?: number;
/**
* Padding value in the horizontal orientation
* default: 4
*/
paddingHorizontal?: number;
/**
* Padding value in the vertical orientation
* default: 1
*/
paddingVertical?: number;
/**
* Determines the border radius value of tag
* default: 3
*/
borderRadius?: number;
/**
* Color of tag's border. If it is not set, the default is the same as color
*/
borderColor?: string;
/**
* Determines whether an animation enabled when the tag is closed
* default: false
*/
animatedWhenDisappear?: boolean;
/**
* Determines how long the disappearing animation will take when tag is closed. (ms)
* default: 300
*/
animationDuration?: number;
/**
* Determines whether a tag can be closed
* default: false
*/
closable?: boolean;
/**
* A callback will be triggered when the tag is closed
*/
onClose?: (text: string) => void;
}
export class Tag extends React.PureComponent<TagProps> {}
class TextComponent extends React.Component<TextProps> {}
const TextBase: Constructor<NativeMethodsMixin> & typeof TextComponent;
export class Text extends TextBase {}
interface TooltipProps {
/**
* Allows you to customize style
*/
style?: ViewStyle;
/**
* Content to show when tooltip pressed. If it is a string, it will be wrapped within Text component. You can also pass a customized ReactElement
*/
popup: React.ReactElement | string;
/**
* Customized style for popup content's container
*/
popupContainerStyle?: ViewStyle;
/**
* Customized style for popup text (works only when popup is a string)
*/
popupTextStyle?: TextStyle;
/**
* Determines whether to show display pointer
* default: true
*/
showCaret?: boolean;
/**
* Background color of tooptip (also for caret if showCaret is true)
* default: 'rgba(0,0,0,.8)'
*/
backgroundColor?: string;
/**
* Background color of overlay (you can use rgba to control the opacity)
* default: 'rgba(0,0,0,.1)'
*/
overlayColor?: string;
/**
* Controls where to show tooltip
* default: 'bottom'
*/
placement?: 'top' | 'bottom';
/**
* A callback will be triggered when tooltip opens
*/
onOpen?: () => void;
/**
* A callback will be triggered when tooltip closes
*/
onClose?: () => void;
}
export class Tooltip extends React.PureComponent<TooltipProps> {
/**
* Normally, tooltip has taken over the work of opening/closing. But in some cases, you can also use this function to open tooltip
*/
open: () => void;
/**
* Normally, tooltip has taken over the work of opening/closing. But in some cases, you can also use this function to close tooltip
*/
close: () => void;
}
} | the_stack |
import React from 'react';
import {Disc, X} from 'react-feather';
import styled from '@emotion/styled';
import {formatDistance} from 'date-fns';
import {AnimatePresence, motion} from 'framer-motion';
import {toJS} from 'mobx';
import {observer} from 'mobx-react';
import TimeTicker from 'src/shared/components/TimeTicker';
import {PlayedTrack} from 'src/shared/store';
import {idTrack} from 'src/utils/dummyData';
import {Tags, tagsConfig} from './tags';
import {ThemeComponentProps, ThemeDescriptor} from '.';
const artToSrc = (d: Uint8Array | undefined) =>
d && d.length > 0
? `data:image/jpg;base64,${window.btoa(String.fromCharCode(...d))}`
: undefined;
type MotionDivProps = React.ComponentProps<typeof motion.div>;
type OrientedMotionDivProps = MotionDivProps & {
alignRight?: boolean;
};
const defaultColors = {
'--pt-np-primary-text': '#fff',
'--pt-np-primary-bg': 'rgba(0, 0, 0, 0.25)',
'--pt-np-empty-attrs-text': 'rgba(255, 255, 255, 0.6)',
'--pt-np-empty-art-bg': '#28272b',
'--pt-np-empty-art-icon': '#aaa',
};
const cssVar = (name: keyof typeof defaultColors) =>
`var(${name}, ${defaultColors[name]})`;
const MissingArtwork = styled((p: MotionDivProps) => (
<motion.div {...p}>
<Disc size="50%" />
</motion.div>
))`
display: flex;
align-items: center;
justify-content: center;
background: ${cssVar('--pt-np-empty-art-bg')};
color: ${cssVar('--pt-np-empty-art-icon')};
opacity: 1;
`;
type ArtworkProps = {alignRight?: boolean; animateIn: boolean} & (
| ({src: string} & React.ComponentProps<typeof motion.img>)
| ({src: undefined} & React.HTMLAttributes<HTMLImageElement>)
);
const BaseArtwork = ({animateIn, alignRight, ...p}: ArtworkProps) => {
const animation = {
initial: {
clipPath: !animateIn
? 'inset(0% 0% 0% 0%)'
: alignRight
? 'inset(0% 0% 0% 100%)'
: 'inset(0% 100% 0% 0%)',
},
animate: {
clipPath: 'inset(0% 0% 0% 0%)',
transitionEnd: {zIndex: 1},
},
exit: {
clipPath: 'inset(0% 0% 100% 0%)',
},
};
return p.src !== undefined ? (
<motion.img variants={animation} {...p} />
) : (
<MissingArtwork variants={animation} className={p.className} />
);
};
const Artwork = styled(BaseArtwork)<ArtworkProps & {size: string}>`
display: flex;
height: ${p => p.size};
width: ${p => p.size};
border-radius: 3px;
flex-shrink: 0;
`;
Artwork.defaultProps = {
className: 'track-artwork',
};
const Text = styled(motion.div)`
background: ${cssVar('--pt-np-primary-bg')};
padding: 0 0.28em;
border-radius: 1px;
display: inline-block;
margin-left: 0.25rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
`;
Text.defaultProps = {
variants: {
initial: {opacity: 0, x: -20},
animate: {opacity: 1, x: 0},
exit: {x: 0},
},
};
const Title = styled(Text)`
font-weight: 600;
font-size: 1.3em;
line-height: 1.4;
margin-bottom: 0.2em;
`;
Title.defaultProps = {
...Text.defaultProps,
className: 'metadata-title',
};
const Artist = styled(Text)`
font-size: 1.1em;
line-height: 1.3;
margin-bottom: 0.2em;
`;
Artist.defaultProps = {
...Text.defaultProps,
className: 'metadata-artist',
};
const Attributes = styled(({alignRight, ...p}: OrientedMotionDivProps) => {
const animation = {
animate: {
x: 0,
transition: {
when: 'beforeChildren',
staggerChildren: 0.2,
staggerDirection: alignRight ? -1 : 1,
},
},
};
return <motion.div variants={animation} {...p} />;
})`
display: flex;
font-size: 0.9em;
line-height: 1.4;
margin-top: 0.1em;
// Set nowrap to fix a layout bug that occurse when the element is FLIPed in
// pose during the animation.
white-space: nowrap;
`;
Attributes.defaultProps = {
className: 'metadata-attributes',
};
type IconProps = {
icon: React.ComponentType<React.ComponentProps<typeof Disc>>;
className?: string;
};
const Icon = styled((p: IconProps) => <p.icon className={p.className} size="1em" />)`
margin-right: 0.25em;
vertical-align: text-top;
`;
type AttributeProps = React.ComponentProps<typeof Text> & {
icon: IconProps['icon'];
text?: string;
};
const Attribute = ({icon, text, ...p}: AttributeProps) =>
text === '' || text === undefined ? null : (
<Text {...p}>
<Icon icon={icon} />
{text}
</Text>
);
const NoAttributes = styled((p: Omit<AttributeProps, 'text' | 'icon'>) => (
<Attribute text="No Release Metadata" icon={X} {...p} />
))`
color: ${cssVar('--pt-np-empty-attrs-text')};
`;
const MetadataWrapper = styled((p: OrientedMotionDivProps) => {
const variants = {
initial: {
clipPath: 'inset(0% 100% 0% 0%)',
},
animate: {
clipPath: 'inset(0% 0% 0% 0%)',
transition: {
staggerChildren: 0.2,
delayChildren: 0.15,
},
},
exit: {
clipPath: p.alignRight ? 'inset(0% 0% 0% 100%)' : 'inset(0% 100% 0% 0%)',
transition: {
duration: 0.2,
},
},
};
return <motion.div variants={variants} {...p} />;
})<{alignRight?: boolean}>`
display: flex;
flex: 1;
flex-direction: column;
align-items: ${p => (p.alignRight ? 'flex-end' : 'flex-start')};
`;
MetadataWrapper.defaultProps = {
className: 'track-metadata',
};
type FullMetadataProps = OrientedMotionDivProps & {
track: PlayedTrack['track'];
tags: Tags;
};
const FullMetadata = ({track, tags, ...p}: FullMetadataProps) => (
<MetadataWrapper {...p}>
<Title>{track.title}</Title>
<Artist>{track.artist?.name}</Artist>
<Attributes alignRight={p.alignRight}>
{tags.map(tag => {
const {icon, getter} = tagsConfig[tag];
const text = getter(track);
return <Attribute key={tag} className={`attribute-${tag}`} {...{icon, text}} />;
})}
{tags.map(t => tagsConfig[t].getter(track)).join('') === '' && tags.length > 0 && (
<NoAttributes key="no-field" />
)}
</Attributes>
</MetadataWrapper>
);
type BaseTrackProps = MotionDivProps & {
played: PlayedTrack;
alignRight?: boolean;
hideArtwork?: boolean;
/**
* Enables animation of the artwork
*/
firstPlayed?: boolean;
/**
* The list of tags to show on the 3rd row
*/
tags?: Tags;
/**
* The string used to mask ID tracks. Blank if ID masks are disabled
*/
idMask?: string;
};
const FullTrack = ({
played,
firstPlayed,
hideArtwork,
idMask,
...props
}: BaseTrackProps) => (
<TrackContainer {...props}>
{!hideArtwork && (
<Artwork
alignRight={props.alignRight}
animateIn={!!firstPlayed}
src={artToSrc(played.artwork)}
size="80px"
/>
)}
<FullMetadata
alignRight={props.alignRight}
track={played.metadataIncludes(idMask) ? idTrack : played.track}
tags={props.tags ?? []}
/>
</TrackContainer>
);
const TrackContainer = styled(motion.div)<{alignRight?: boolean}>`
display: inline-grid;
grid-gap: 0.5rem;
color: ${cssVar('--pt-np-primary-text')};
font-family: Ubuntu;
justify-content: ${p => (p.alignRight ? 'right' : 'left')};
grid-template-columns: ${p =>
p.alignRight
? 'minmax(0, max-content) max-content'
: 'max-content minmax(0, max-content)'};
> *:nth-child(1) {
grid-row: 1;
grid-column: ${p => (p.alignRight ? 2 : 1)};
}
> *:nth-child(2) {
grid-row: 1;
grid-column: ${p => (p.alignRight ? 1 : 2)};
}
`;
TrackContainer.defaultProps = {
animate: 'animate',
initial: 'initial',
exit: 'exit',
};
const MiniTitle = styled(Text)`
font-size: 0.85em;
font-weight: 600;
line-height: 1.2;
margin-bottom: 0.15em;
`;
const MiniArtist = styled(Text)`
font-size: 0.8em;
line-height: 1.2;
margin-bottom: 0.25em;
`;
const PlayedAt = styled(Text)`
font-size: 0.7em;
line-height: 1.3;
`;
const MiniTrack = ({played, hideArtwork, idMask, ...props}: BaseTrackProps) => {
const track = played.metadataIncludes(idMask) ? idTrack : played.track;
return (
<TrackContainer {...props}>
{!hideArtwork && (
<Artwork
animateIn
alignRight={props.alignRight}
src={artToSrc(played.artwork)}
size="50px"
/>
)}
<MetadataWrapper alignRight={props.alignRight}>
<MiniTitle>{track.title}</MiniTitle>
<MiniArtist>{track.artist?.name}</MiniArtist>
<PlayedAt>
<TimeTicker randomRange={[15, 30]}>
{() =>
played.playedAt && `${formatDistance(Date.now(), played.playedAt)} ago`
}
</TimeTicker>
</PlayedAt>
</MetadataWrapper>
</TrackContainer>
);
};
type TrackProps = BaseTrackProps & {mini?: boolean};
const Track = ({mini, ...props}: TrackProps) =>
mini ? <MiniTrack {...props} /> : <FullTrack {...props} />;
const CurrentTrack = ({played, ...p}: React.ComponentProps<typeof Track>) => (
<CurrentWrapper>
<AnimatePresence>
{played && <Track played={played} key={played.playedAt.toString()} {...p} />}
</AnimatePresence>
</CurrentWrapper>
);
CurrentTrack.defaultProps = {
variants: {
enter: {
x: 0,
transition: {
when: 'beforeChildren',
delay: 0.3,
},
},
},
};
type Props = ThemeComponentProps;
const ThemeModern: React.FC<Props> = observer(({appConfig, config, history}) =>
history.length === 0 ? null : (
<React.Fragment>
<CurrentTrack
style={toJS(config.colors)}
className="track-current"
alignRight={config.alignRight}
hideArtwork={config.hideArtwork}
tags={config.tags}
firstPlayed={history.length === 1}
idMask={config.maskId ? appConfig.idMarker : ''}
played={history[0]}
/>
{(config.historyCount ?? 0) > 0 && history.length > 1 && (
<RecentWrapper className="track-recents" style={toJS(config.colors)}>
<AnimatePresence>
{history
.slice(1, config.historyCount ? config.historyCount + 1 : 0)
.map(track => (
<Track
mini
layout
alignRight={config.alignRight}
hideArtwork={config.hideArtwork}
played={track}
idMask={config.maskId ? appConfig.idMarker : ''}
variants={{exit: {display: 'none'}}}
key={`${track.playedAt}-${track.track.id}`}
/>
))}
</AnimatePresence>
</RecentWrapper>
)}
</React.Fragment>
)
);
const RecentWrapper = styled('div')`
display: flex;
flex-direction: column;
margin-top: 2rem;
gap: 14px;
`;
const CurrentWrapper = styled('div')`
display: grid;
grid-template-columns: minmax(0, 1fr);
> * {
grid-column: 1;
grid-row: 1;
}
`;
export default {
label: 'Track List',
component: ThemeModern,
colors: defaultColors,
enabledConfigs: [
'alignRight',
'hideArtwork',
'historyCount',
'tags',
'maskId',
'colors',
],
} as ThemeDescriptor; | the_stack |
import React from 'react';
import 'jest-styled-components';
import 'jest-axe/extend-expect';
import 'regenerator-runtime/runtime';
import { render } from '@testing-library/react';
import { fireEvent } from '@testing-library/dom';
import { Grommet } from '../../Grommet';
import { Pagination } from '..';
const NUM_ITEMS = 237;
const STEP = 10;
const data = [];
for (let i = 0; i < 95; i += 1) {
data.push(`entry-${i}`);
}
describe('Pagination', () => {
test(`should display the correct last page based on items length
and step`, () => {
const { container, getByText } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} />
</Grommet>,
);
// default step is 10
const expectedPageCount = Math.ceil(NUM_ITEMS / 10);
const lastPageButton = getByText(expectedPageCount.toString());
expect(lastPageButton).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
test('should render correct numberEdgePages', () => {
const { container } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} numberEdgePages={3} page={10} />
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test('should render correct numberMiddlePages when odd', () => {
const { container } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} numberMiddlePages={5} page={10} />
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test('should render correct numberMiddlePages when even', () => {
const { container } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} numberMiddlePages={4} page={10} />
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test('should show correct page when "page" is provided ', () => {});
test(`should disable previous and next controls when numberItems
< step`, () => {
const { container } = render(
<Grommet>
<Pagination numberItems={10} step={20} />
</Grommet>,
);
const previousButtonDisabled = (
container.querySelector(
`[aria-label="Go to previous page"]`,
) as HTMLButtonElement
).hasAttribute('disabled');
const nextButtonDisabled = (
container.querySelector(
`[aria-label="Go to next page"]`,
) as HTMLButtonElement
).hasAttribute('disabled');
expect(previousButtonDisabled).toBeTruthy();
expect(nextButtonDisabled).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
test(`should disable previous and next controls when numberItems
=== step`, () => {
const { container } = render(
<Grommet>
<Pagination numberItems={20} step={20} />
</Grommet>,
);
const previousButtonDisabled = (
container.querySelector(
`[aria-label="Go to previous page"]`,
) as HTMLButtonElement
).hasAttribute('disabled');
const nextButtonDisabled = (
container.querySelector(
`[aria-label="Go to next page"]`,
) as HTMLButtonElement
).hasAttribute('disabled');
expect(previousButtonDisabled).toBeTruthy();
expect(nextButtonDisabled).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
test(`should disable previous and next controls when numberItems
=== 0`, () => {
const { container } = render(
<Grommet>
<Pagination numberItems={0} />
</Grommet>,
);
const previousButtonDisabled = (
container.querySelector(
`[aria-label="Go to previous page"]`,
) as HTMLButtonElement
).hasAttribute('disabled');
const nextButtonDisabled = (
container.querySelector(
`[aria-label="Go to next page"]`,
) as HTMLButtonElement
).hasAttribute('disabled');
expect(previousButtonDisabled).toBeTruthy();
expect(nextButtonDisabled).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
test(`should set page to last page if page prop > total possible
pages`, () => {
const numberItems = 500;
const step = 50;
const { container, getByText } = render(
<Grommet>
<Pagination numberItems={numberItems} step={step} page={700} />
</Grommet>,
);
const expectedPage = `${Math.ceil(numberItems / step)}`;
fireEvent.click(getByText(expectedPage));
const activePage = (
container.querySelector(`[aria-current="page"]`) as HTMLButtonElement
).innerHTML;
expect(activePage).toEqual(expectedPage);
expect(container.firstChild).toMatchSnapshot();
});
// how to not hard code so many values
test(`should allow user to control page via state with page +
onChange`, () => {
const onChange = jest.fn();
const { container, getByLabelText } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} page={1} onChange={onChange} />
</Grommet>,
);
const nextPageButton = getByLabelText('Go to next page');
fireEvent.click(nextPageButton);
// step is 10 by default, so startIndex/endIndex are based on that
expect(onChange).toBeCalledWith(
expect.objectContaining({ page: 2, startIndex: 10, endIndex: 20 }),
);
expect(container.firstChild).toMatchSnapshot();
});
test(`should display next page of results when "next" is
selected`, () => {
const onChange = jest.fn();
const { container, getByLabelText } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} onChange={onChange} />
</Grommet>,
);
const nextPageButton = getByLabelText('Go to next page');
// mouse click
fireEvent.click(nextPageButton);
expect(onChange).toBeCalledTimes(1);
expect(container.firstChild).toMatchSnapshot();
// keyboard enter
fireEvent.keyDown(nextPageButton, {
key: 'Enter',
keyCode: 13,
which: 13,
});
expect(onChange).toBeCalledTimes(1);
expect(container.firstChild).toMatchSnapshot();
});
test(`should display previous page of results when "previous" is
selected`, () => {
const onChange = jest.fn();
const { container, getByLabelText } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} page={3} onChange={onChange} />
</Grommet>,
);
const previousPageButton = getByLabelText('Go to previous page');
// mouse click
fireEvent.click(previousPageButton);
expect(onChange).toBeCalledTimes(1);
expect(container.firstChild).toMatchSnapshot();
// keyboard enter
fireEvent.keyDown(previousPageButton, {
key: 'Enter',
keyCode: 13,
which: 13,
});
expect(onChange).toBeCalledTimes(1);
expect(container.firstChild).toMatchSnapshot();
});
test(`should display page 'n' of results when "page n" is
selected`, () => {
const { container, getByText } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} />
</Grommet>,
);
const desiredPage = '2';
fireEvent.click(getByText(desiredPage));
const activePage = (
container.querySelector(`[aria-current="page"]`) as HTMLButtonElement
).innerHTML;
expect(activePage).toEqual(desiredPage);
expect(container.firstChild).toMatchSnapshot();
});
test(`should disable previous button if on first page`, () => {
const { container } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} />
</Grommet>,
);
const previousButtonDisabled = (
container.querySelector(
`[aria-label="Go to previous page"]`,
) as HTMLButtonElement
).hasAttribute('disabled');
expect(previousButtonDisabled).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
test(`should disable next button if on last page`, () => {
const lastPage = Math.ceil(NUM_ITEMS / STEP);
const { container } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} page={lastPage} />
</Grommet>,
);
const nextButtonDisabled = (
container.querySelector(
`[aria-label="Go to next page"]`,
) as HTMLButtonElement
).hasAttribute('disabled');
expect(nextButtonDisabled).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
test(`should set numberMiddlePages = 1 if user provides value < 1`, () => {
console.warn = jest.fn();
const { container } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} numberMiddlePages={0} />
</Grommet>,
);
expect(console.warn).toHaveBeenCalledTimes(1);
expect(container.firstChild).toMatchSnapshot();
});
test(`should apply custom theme`, () => {
const customTheme = {
pagination: {
container: {
extend: `background: red;`,
},
},
};
const { container } = render(
<Grommet theme={customTheme}>
<Pagination numberItems={NUM_ITEMS} />
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test(`should apply button kind style when referenced by a string`, () => {
const customTheme = {
button: {
default: {},
bright: {
color: 'text-strong',
border: {
color: 'skyblue',
width: '2px',
},
},
active: {
bright: {
background: {
color: '#CA9CEA',
},
border: {
color: 'transparent',
},
color: 'text',
},
},
},
pagination: {
button: 'bright',
},
};
const { container } = render(
<Grommet theme={customTheme}>
<Pagination numberItems={NUM_ITEMS} />
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test(`should apply size`, () => {
const { container } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} />
<Pagination numberItems={NUM_ITEMS} size="small" />
<Pagination numberItems={NUM_ITEMS} size="large" />
</Grommet>,
);
expect(container.firstChild).toMatchSnapshot();
});
test(`should change the page on prop change`, () => {
const { container, rerender } = render(
<Grommet>
<Pagination numberItems={NUM_ITEMS} page={1} />
</Grommet>,
);
expect(
(container.querySelector(`[aria-current="page"]`) as HTMLButtonElement)
.innerHTML,
).toBe('1');
rerender(
<Grommet>
<Pagination numberItems={NUM_ITEMS} page={2} />
</Grommet>,
);
expect(
(container.querySelector(`[aria-current="page"]`) as HTMLButtonElement)
.innerHTML,
).toBe('2');
expect(container.firstChild).toMatchSnapshot();
});
test(`should apply a11yTitle and aria-label`, () => {
const { container, getByLabelText } = render(
<Grommet>
<Pagination a11yTitle="pagination-test" numberItems={NUM_ITEMS} />
<Pagination aria-label="pagination-test-2" numberItems={NUM_ITEMS} />
</Grommet>,
);
expect(getByLabelText('pagination-test')).toBeTruthy();
expect(getByLabelText('pagination-test-2')).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
}); | the_stack |
import { IDisposable } from "../../core/types";
import { transformGeometry } from "../../geometry/Geometry.Functions";
import { planeGeometry } from "../../geometry/primitives/planeGeometry";
import { Blending } from "../../materials/Blending";
import { ShaderMaterial } from "../../materials/ShaderMaterial";
import { ceilPow2 } from "../../math/Functions";
import { makeMatrix3Concatenation, makeMatrix3Scale, makeMatrix3Translation } from "../../math/Matrix3.Functions";
import { Matrix4 } from "../../math/Matrix4";
import {
makeMatrix4Inverse,
makeMatrix4Orthographic,
makeMatrix4OrthographicSimple,
makeMatrix4Scale,
makeMatrix4Translation,
} from "../../math/Matrix4.Functions";
import { Vector2 } from "../../math/Vector2";
import { makeVector2FillHeight } from "../../math/Vector2.Functions";
import { Vector3 } from "../../math/Vector3";
import { isFirefox, isiOS, isMacOS } from "../../platform/Detection";
import { blendModeToBlendState } from "../../renderers/webgl/BlendState";
import { BufferGeometry, makeBufferGeometryFromGeometry } from "../../renderers/webgl/buffers/BufferGeometry";
import { ClearState } from "../../renderers/webgl/ClearState";
import { Attachment } from "../../renderers/webgl/framebuffers/Attachment";
import { Framebuffer } from "../../renderers/webgl/framebuffers/Framebuffer";
import { renderBufferGeometry } from "../../renderers/webgl/framebuffers/VirtualFramebuffer";
import { makeProgramFromShaderMaterial, Program } from "../../renderers/webgl/programs/Program";
import { RenderingContext } from "../../renderers/webgl/RenderingContext";
import { DataType } from "../../renderers/webgl/textures/DataType";
import { PixelFormat } from "../../renderers/webgl/textures/PixelFormat";
import { TexImage2D } from "../../renderers/webgl/textures/TexImage2D";
import { makeTexImage2DFromTexture } from "../../renderers/webgl/textures/TexImage2D.Functions";
import { TexParameters } from "../../renderers/webgl/textures/TexParameters";
import { TextureFilter } from "../../renderers/webgl/textures/TextureFilter";
import { TextureTarget } from "../../renderers/webgl/textures/TextureTarget";
import { TextureWrap } from "../../renderers/webgl/textures/TextureWrap";
import { fetchImage, isImageBitmapSupported } from "../../textures/loaders/Image";
import { Texture } from "../../textures/Texture";
import fragmentSource from "./fragment.glsl";
import { Layer } from "./Layer";
import vertexSource from "./vertex.glsl";
function releaseImage(image: ImageBitmap | HTMLImageElement | undefined): void {
if (isImageBitmapSupported() && image instanceof ImageBitmap) {
image.close();
}
// if HTMLImageElement do nothing, just ensure there are no references to it.
}
export class LayerImage implements IDisposable {
disposed = false;
renderId = -1;
constructor(
readonly url: string,
public texImage2D: TexImage2D,
public image: ImageBitmap | HTMLImageElement | undefined,
) {
// console.log(`layerImage.load: ${this.url}`);
}
dispose(): void {
if (!this.disposed) {
this.texImage2D.dispose();
releaseImage(this.image);
this.image = undefined;
this.disposed = true;
// console.log(`layerImage.dispose: ${this.url}`);
}
}
}
export type LayerImageMap = { [key: string]: LayerImage | undefined };
export type TexImage2DPromiseMap = { [key: string]: Promise<TexImage2D> | undefined };
export function makeColorMipmapAttachment(
context: RenderingContext,
size: Vector2,
dataType: DataType | undefined = undefined,
): TexImage2D {
const texParams = new TexParameters();
texParams.generateMipmaps = true;
texParams.anisotropyLevels = 1;
texParams.wrapS = TextureWrap.ClampToEdge;
texParams.wrapT = TextureWrap.ClampToEdge;
texParams.magFilter = TextureFilter.Linear;
texParams.minFilter = TextureFilter.LinearMipmapLinear;
return new TexImage2D(
context,
[size],
PixelFormat.RGBA,
dataType ?? DataType.UnsignedByte,
PixelFormat.RGBA,
TextureTarget.Texture2D,
texParams,
);
}
export class LayerCompositor {
context: RenderingContext;
layerImageCache: LayerImageMap = {};
texImage2DPromiseCache: TexImage2DPromiseMap = {};
#bufferGeometry: BufferGeometry;
#program: Program;
imageSize = new Vector2(0, 0);
zoomScale = 1.0; // no zoom
panPosition: Vector2 = new Vector2(0.5, 0.5); // center
#layers: Layer[] = [];
#layerVersion = 0;
#offlineLayerVersion = -1;
firstRender = true;
clearState = new ClearState(new Vector3(1, 1, 1), 0.0);
offscreenFramebuffer: Framebuffer | undefined;
offscreenSize = new Vector2(0, 0);
offscreenColorAttachment: TexImage2D | undefined;
renderId = 0;
autoDiscard = false;
constructor(canvas: HTMLCanvasElement) {
this.context = new RenderingContext(canvas, {
alpha: true,
antialias: false,
depth: false,
premultipliedAlpha: true,
stencil: false,
preserveDrawingBuffer: true,
});
this.context.canvasFramebuffer.devicePixelRatio = window.devicePixelRatio;
this.context.canvasFramebuffer.resize();
const plane = planeGeometry(1, 1, 1, 1);
transformGeometry(plane, makeMatrix4Translation(new Vector3(0.5, 0.5, 0.0)));
this.#bufferGeometry = makeBufferGeometryFromGeometry(this.context, plane);
this.#program = makeProgramFromShaderMaterial(this.context, new ShaderMaterial(vertexSource, fragmentSource));
}
snapshot(mimeFormat = "image/jpeg", quality = 1.0): string {
const canvas = this.context.canvasFramebuffer.canvas;
if (canvas instanceof HTMLCanvasElement) {
return canvas.toDataURL(mimeFormat, quality);
}
throw new Error("snapshot not supported");
}
set layers(layers: Layer[]) {
this.#layers = layers;
this.#layerVersion++;
}
updateOffscreen(): void {
// but to enable mipmaps (for filtering) we need it to be up-rounded to a power of 2 in width/height.
const offscreenSize = new Vector2(ceilPow2(this.imageSize.x), ceilPow2(this.imageSize.y));
if (this.offscreenFramebuffer === undefined || !this.offscreenSize.equals(offscreenSize)) {
// console.log("updating framebuffer");
if (this.offscreenFramebuffer !== undefined) {
this.offscreenFramebuffer.dispose();
this.offscreenFramebuffer = undefined;
}
this.offscreenColorAttachment = makeColorMipmapAttachment(this.context, offscreenSize);
this.offscreenFramebuffer = new Framebuffer(this.context);
this.offscreenFramebuffer.attach(Attachment.Color0, this.offscreenColorAttachment);
// frame buffer is pixel aligned with layer images.
// framebuffer view is [ (0,0)-(framebuffer.with, framebuffer.height) ].
this.offscreenSize.copy(offscreenSize);
}
}
loadTexImage2D(url: string, image: HTMLImageElement | ImageBitmap | undefined = undefined): Promise<TexImage2D> {
const layerImagePromise = this.texImage2DPromiseCache[url];
if (layerImagePromise !== undefined) {
console.log(`loading: ${url} (reusing promise)`);
return layerImagePromise;
}
return (this.texImage2DPromiseCache[url] = new Promise<TexImage2D>((resolve) => {
// check for texture in cache.
const layerImage = this.layerImageCache[url];
if (layerImage !== undefined) {
return resolve(layerImage.texImage2D);
}
function createTexture(compositor: LayerCompositor, image: HTMLImageElement | ImageBitmap): TexImage2D {
// console.log(image, key);
// create texture
const texture = new Texture(image);
texture.wrapS = TextureWrap.ClampToEdge;
texture.wrapT = TextureWrap.ClampToEdge;
texture.minFilter = TextureFilter.Nearest;
texture.generateMipmaps = false;
texture.anisotropicLevels = 1;
texture.name = url;
console.log(`loading: ${url}`);
// load texture onto the GPU
const texImage2D = makeTexImage2DFromTexture(compositor.context, texture);
delete compositor.texImage2DPromiseCache[url];
return (compositor.layerImageCache[url] = new LayerImage(url, texImage2D, image)).texImage2D;
}
if (image === undefined) {
fetchImage(url).then((image: HTMLImageElement | ImageBitmap) => {
return resolve(createTexture(this, image));
});
} else if (image instanceof HTMLImageElement || image instanceof ImageBitmap) {
return resolve(createTexture(this, image));
}
})).then((texImage2D) => {
delete this.texImage2DPromiseCache[url];
return texImage2D;
});
}
discardTexImage2D(url: string): boolean {
// check for texture in cache.
const layerImage = this.layerImageCache[url];
if (layerImage !== undefined) {
console.log(`discarding: ${url}`);
layerImage.dispose();
delete this.layerImageCache[url];
return true;
}
return false;
}
// ask how much memory is used
// set max size
// draw() - makes things fit with size of div assuming pixels are square
render(): void {
this.renderId++;
// console.log(`render id: ${this.renderId}`);
const canvasFramebuffer = this.context.canvasFramebuffer;
const canvasSize = canvasFramebuffer.size;
const canvasAspectRatio = canvasSize.width / canvasSize.height;
const canvasImageSize = makeVector2FillHeight(canvasSize, this.imageSize);
const canvasImageCenter = canvasImageSize.clone().multiplyByScalar(0.5);
if (this.zoomScale > 1.0) {
// convert from canvas space to image space
const imagePanPosition = this.panPosition
.clone()
.multiplyByScalar(this.imageSize.width / canvasImageSize.width)
.multiplyByScalar(this.context.canvasFramebuffer.devicePixelRatio);
const imageCanvasSize = canvasSize.clone().multiplyByScalar(this.imageSize.width / canvasImageSize.width);
// center pan
const imagePanOffset = imagePanPosition.clone().sub(imageCanvasSize.clone().multiplyByScalar(0.5));
// clamp to within image.
imagePanOffset.x = Math.sign(imagePanOffset.x) * Math.min(Math.abs(imagePanOffset.x), this.imageSize.x * 0.5);
imagePanOffset.y = Math.sign(imagePanOffset.y) * Math.min(Math.abs(imagePanOffset.y), this.imageSize.y * 0.5);
// convert back to
const canvasPanOffset = imagePanOffset.clone().multiplyByScalar(canvasImageSize.width / this.imageSize.width);
// ensure zoom is at point of contact, not center of screen.
const centeredCanvasPanOffset = canvasPanOffset.clone().multiplyByScalar(1 - 1 / this.zoomScale);
canvasImageCenter.add(centeredCanvasPanOffset);
}
const imageToCanvas = makeMatrix4OrthographicSimple(
canvasSize.height,
canvasImageCenter,
-1,
1,
this.zoomScale,
canvasAspectRatio,
);
/* console.log(
`Canvas Camera: height ( ${canvasSize.height} ), center ( ${scaledImageCenter.x}, ${scaledImageCenter.y} ) `,
);*/
const canvasToImage = makeMatrix4Inverse(imageToCanvas);
const planeToImage = makeMatrix4Scale(new Vector3(canvasImageSize.width, canvasImageSize.height, 1.0));
this.renderLayersToFramebuffer();
const layerUVScale = new Vector2(
this.imageSize.width / this.offscreenSize.width,
this.imageSize.height / this.offscreenSize.height,
);
const uvScale = makeMatrix3Scale(layerUVScale);
const uvTranslation = makeMatrix3Translation(
new Vector2(0, (this.offscreenSize.height - this.imageSize.height) / this.offscreenSize.height),
);
const uvToTexture = makeMatrix3Concatenation(uvTranslation, uvScale);
canvasFramebuffer.clearState = new ClearState(new Vector3(0, 0, 0), 0.0);
canvasFramebuffer.clear();
const offscreenColorAttachment = this.offscreenColorAttachment;
if (offscreenColorAttachment === undefined) {
return;
}
const uniforms = {
viewToScreen: imageToCanvas,
screenToView: canvasToImage,
worldToView: new Matrix4(),
localToWorld: planeToImage,
layerMap: offscreenColorAttachment,
uvToTexture: uvToTexture,
mipmapBias: 0.0,
convertToPremultipliedAlpha: 0,
};
const blendState = blendModeToBlendState(Blending.Over, true);
// console.log(`drawing layer #${index}: ${layer.url} at ${layer.offset.x}, ${layer.offset.y}`);
renderBufferGeometry(canvasFramebuffer, this.#program, uniforms, this.#bufferGeometry, undefined, blendState);
if (this.autoDiscard) {
for (const url in this.layerImageCache) {
const layerImage = this.layerImageCache[url];
if (layerImage !== undefined && layerImage.renderId < this.renderId) {
this.discardTexImage2D(url);
}
}
}
}
renderLayersToFramebuffer(): void {
this.updateOffscreen();
if (this.#offlineLayerVersion >= this.#layerVersion) {
return;
}
this.#offlineLayerVersion = this.#layerVersion;
const offscreenFramebuffer = this.offscreenFramebuffer;
if (offscreenFramebuffer === undefined) {
return;
}
// clear to black and full alpha.
offscreenFramebuffer.clearState = new ClearState(new Vector3(0, 0, 0), 0.0);
offscreenFramebuffer.clear();
const imageToOffscreen = makeMatrix4Orthographic(0, this.offscreenSize.width, 0, this.offscreenSize.height, -1, 1);
/* console.log(
`Canvas Camera: height ( ${this.offscreenSize.height} ), center ( ${offscreenCenter.x}, ${offscreenCenter.y} ) `,
);*/
const offscreenToImage = makeMatrix4Inverse(imageToOffscreen);
// Ben on 2020-10-31
// - does not understand why this is necessary.
// - this means it may be working around a bug, and thus this will break in the future.
// - the bug would be in chrome as it seems to be the inverse of the current query
const convertToPremultipliedAlpha = !(isMacOS() || isiOS() || isFirefox()) ? 0 : 1;
this.#layers.forEach((layer) => {
const layerImage = this.layerImageCache[layer.url];
if (layerImage !== undefined) {
layerImage.renderId = this.renderId;
}
const uniforms = {
viewToScreen: imageToOffscreen,
screenToView: offscreenToImage,
worldToView: new Matrix4(),
localToWorld: layer.planeToImage,
layerMap: layer.texImage2D,
uvToTexture: layer.uvToTexture,
mipmapBias: 0,
convertToPremultipliedAlpha,
};
const blendState = blendModeToBlendState(Blending.Over, true);
// console.log(`drawing layer #${index}: ${layer.url} at ${layer.offset.x}, ${layer.offset.y}`);
renderBufferGeometry(offscreenFramebuffer, this.#program, uniforms, this.#bufferGeometry, undefined, blendState);
});
// generate mipmaps.
const colorAttachment = this.offscreenColorAttachment;
if (colorAttachment !== undefined) {
colorAttachment.generateMipmaps();
}
}
} | the_stack |
import $ from 'mdui.jq/es/$';
import contains from 'mdui.jq/es/functions/contains';
import extend from 'mdui.jq/es/functions/extend';
import { JQ } from 'mdui.jq/es/JQ';
import 'mdui.jq/es/methods/addClass';
import 'mdui.jq/es/methods/attr';
import 'mdui.jq/es/methods/children';
import 'mdui.jq/es/methods/css';
import 'mdui.jq/es/methods/data';
import 'mdui.jq/es/methods/each';
import 'mdui.jq/es/methods/find';
import 'mdui.jq/es/methods/first';
import 'mdui.jq/es/methods/hasClass';
import 'mdui.jq/es/methods/height';
import 'mdui.jq/es/methods/is';
import 'mdui.jq/es/methods/on';
import 'mdui.jq/es/methods/parent';
import 'mdui.jq/es/methods/parents';
import 'mdui.jq/es/methods/removeClass';
import 'mdui.jq/es/methods/width';
import Selector from 'mdui.jq/es/types/Selector';
import mdui from '../../mdui';
import '../../jq_extends/methods/transformOrigin';
import '../../jq_extends/methods/transitionEnd';
import '../../jq_extends/static/throttle';
import { componentEvent } from '../../utils/componentEvent';
import { $document, $window } from '../../utils/dom';
declare module '../../interfaces/MduiStatic' {
interface MduiStatic {
/**
* Menu 组件
*
* 请通过 `new mdui.Menu()` 调用
*/
Menu: {
/**
* 实例化 Menu 组件
* @param anchorSelector 触发菜单的元素的 CSS 选择器、或 DOM 元素、或 JQ 对象
* @param menuSelector 菜单的 CSS 选择器、或 DOM 元素、或 JQ 对象
* @param options 配置参数
*/
new (
anchorSelector: Selector | HTMLElement | ArrayLike<HTMLElement>,
menuSelector: Selector | HTMLElement | ArrayLike<HTMLElement>,
options?: OPTIONS,
): Menu;
};
}
}
type OPTIONS = {
/**
* 菜单相对于触发它的元素的位置,默认为 `auto`。
* 取值范围包括:
* `top`: 菜单在触发它的元素的上方
* `bottom`: 菜单在触发它的元素的下方
* `center`: 菜单在窗口中垂直居中
* `auto`: 自动判断位置。优先级为:`bottom` > `top` > `center`
*/
position?: 'auto' | 'top' | 'bottom' | 'center';
/**
* 菜单与触发它的元素的对其方式,默认为 `auto`。
* 取值范围包括:
* `left`: 菜单与触发它的元素左对齐
* `right`: 菜单与触发它的元素右对齐
* `center`: 菜单在窗口中水平居中
* `auto`: 自动判断位置:优先级为:`left` > `right` > `center`
*/
align?: 'auto' | 'left' | 'right' | 'center';
/**
* 菜单与窗口边框至少保持多少间距,单位为 px,默认为 `16`
*/
gutter?: number;
/**
* 菜单的定位方式,默认为 `false`。
* 为 `true` 时,菜单使用 fixed 定位。在页面滚动时,菜单将保持在窗口固定位置,不随滚动条滚动。
* 为 `false` 时,菜单使用 absolute 定位。在页面滚动时,菜单将随着页面一起滚动。
*/
fixed?: boolean;
/**
* 菜单是否覆盖在触发它的元素的上面,默认为 `auto`
* 为 `true` 时,使菜单覆盖在触发它的元素的上面
* 为 `false` 时,使菜单不覆盖触发它的元素
* 为 `auto` 时,简单菜单覆盖触发它的元素。级联菜单不覆盖触发它的元素
*/
covered?: boolean | 'auto';
/**
* 子菜单的触发方式,默认为 `hover`
* 为 `click` 时,点击时触发子菜单
* 为 `hover` 时,鼠标悬浮时触发子菜单
*/
subMenuTrigger?: 'click' | 'hover';
/**
* 子菜单的触发延迟时间(单位:毫秒),只有在 `subMenuTrigger: hover` 时,这个参数才有效,默认为 `200`
*/
subMenuDelay?: number;
};
type EVENT = 'open' | 'opened' | 'close' | 'closed';
type STATE = 'opening' | 'opened' | 'closing' | 'closed';
const DEFAULT_OPTIONS: OPTIONS = {
position: 'auto',
align: 'auto',
gutter: 16,
fixed: false,
covered: 'auto',
subMenuTrigger: 'hover',
subMenuDelay: 200,
};
class Menu {
/**
* 触发菜单的元素的 JQ 对象
*/
public $anchor: JQ;
/**
* 菜单元素的 JQ 对象
*/
public $element: JQ;
/**
* 配置参数
*/
public options: OPTIONS = extend({}, DEFAULT_OPTIONS);
/**
* 当前菜单状态
*/
private state: STATE = 'closed';
/**
* 是否是级联菜单
*/
private isCascade: boolean;
/**
* 菜单是否覆盖在触发它的元素的上面
*/
private isCovered: boolean;
public constructor(
anchorSelector: Selector | HTMLElement | ArrayLike<HTMLElement>,
menuSelector: Selector | HTMLElement | ArrayLike<HTMLElement>,
options: OPTIONS = {},
) {
this.$anchor = $(anchorSelector).first();
this.$element = $(menuSelector).first();
// 触发菜单的元素 和 菜单必须是同级的元素,否则菜单可能不能定位
if (!this.$anchor.parent().is(this.$element.parent())) {
throw new Error('anchorSelector and menuSelector must be siblings');
}
extend(this.options, options);
// 是否是级联菜单
this.isCascade = this.$element.hasClass('mdui-menu-cascade');
// covered 参数处理
this.isCovered =
this.options.covered === 'auto' ? !this.isCascade : this.options.covered!;
// 点击触发菜单切换
this.$anchor.on('click', () => this.toggle());
// 点击菜单外面区域关闭菜单
$document.on('click touchstart', (event: Event) => {
const $target = $(event.target as HTMLElement);
if (
this.isOpen() &&
!$target.is(this.$element) &&
!contains(this.$element[0], $target[0]) &&
!$target.is(this.$anchor) &&
!contains(this.$anchor[0], $target[0])
) {
this.close();
}
});
// 点击不含子菜单的菜单条目关闭菜单
// eslint-disable-next-line @typescript-eslint/no-this-alias
const that = this;
$document.on('click', '.mdui-menu-item', function () {
const $item = $(this);
if (
!$item.find('.mdui-menu').length &&
$item.attr('disabled') === undefined
) {
that.close();
}
});
// 绑定点击或鼠标移入含子菜单的条目的事件
this.bindSubMenuEvent();
// 窗口大小变化时,重新调整菜单位置
$window.on(
'resize',
$.throttle(() => this.readjust(), 100),
);
}
/**
* 是否为打开状态
*/
private isOpen(): boolean {
return this.state === 'opening' || this.state === 'opened';
}
/**
* 触发组件事件
* @param name
*/
private triggerEvent(name: EVENT): void {
componentEvent(name, 'menu', this.$element, this);
}
/**
* 调整主菜单位置
*/
private readjust(): void {
let menuLeft;
let menuTop;
// 菜单位置和方向
let position: 'bottom' | 'top' | 'center';
let align: 'left' | 'right' | 'center';
// window 窗口的宽度和高度
const windowHeight = $window.height();
const windowWidth = $window.width();
// 配置参数
const gutter = this.options.gutter!;
const isCovered = this.isCovered;
const isFixed = this.options.fixed;
// 动画方向参数
let transformOriginX;
let transformOriginY;
// 菜单的原始宽度和高度
const menuWidth = this.$element.width();
const menuHeight = this.$element.height();
// 触发菜单的元素在窗口中的位置
const anchorRect = this.$anchor[0].getBoundingClientRect();
const anchorTop = anchorRect.top;
const anchorLeft = anchorRect.left;
const anchorHeight = anchorRect.height;
const anchorWidth = anchorRect.width;
const anchorBottom = windowHeight - anchorTop - anchorHeight;
const anchorRight = windowWidth - anchorLeft - anchorWidth;
// 触发元素相对其拥有定位属性的父元素的位置
const anchorOffsetTop = this.$anchor[0].offsetTop;
const anchorOffsetLeft = this.$anchor[0].offsetLeft;
// 自动判断菜单位置
if (this.options.position === 'auto') {
if (anchorBottom + (isCovered ? anchorHeight : 0) > menuHeight + gutter) {
// 判断下方是否放得下菜单
position = 'bottom';
} else if (
anchorTop + (isCovered ? anchorHeight : 0) >
menuHeight + gutter
) {
// 判断上方是否放得下菜单
position = 'top';
} else {
// 上下都放不下,居中显示
position = 'center';
}
} else {
position = this.options.position!;
}
// 自动判断菜单对齐方式
if (this.options.align === 'auto') {
if (anchorRight + anchorWidth > menuWidth + gutter) {
// 判断右侧是否放得下菜单
align = 'left';
} else if (anchorLeft + anchorWidth > menuWidth + gutter) {
// 判断左侧是否放得下菜单
align = 'right';
} else {
// 左右都放不下,居中显示
align = 'center';
}
} else {
align = this.options.align!;
}
// 设置菜单位置
if (position === 'bottom') {
transformOriginY = '0';
menuTop =
(isCovered ? 0 : anchorHeight) +
(isFixed ? anchorTop : anchorOffsetTop);
} else if (position === 'top') {
transformOriginY = '100%';
menuTop =
(isCovered ? anchorHeight : 0) +
(isFixed ? anchorTop - menuHeight : anchorOffsetTop - menuHeight);
} else {
transformOriginY = '50%';
// =====================在窗口中居中
// 显示的菜单的高度,简单菜单高度不超过窗口高度,若超过了则在菜单内部显示滚动条
// 级联菜单内部不允许出现滚动条
let menuHeightTemp = menuHeight;
// 简单菜单比窗口高时,限制菜单高度
if (!this.isCascade) {
if (menuHeight + gutter * 2 > windowHeight) {
menuHeightTemp = windowHeight - gutter * 2;
this.$element.height(menuHeightTemp);
}
}
menuTop =
(windowHeight - menuHeightTemp) / 2 +
(isFixed ? 0 : anchorOffsetTop - anchorTop);
}
this.$element.css('top', `${menuTop}px`);
// 设置菜单对齐方式
if (align === 'left') {
transformOriginX = '0';
menuLeft = isFixed ? anchorLeft : anchorOffsetLeft;
} else if (align === 'right') {
transformOriginX = '100%';
menuLeft = isFixed
? anchorLeft + anchorWidth - menuWidth
: anchorOffsetLeft + anchorWidth - menuWidth;
} else {
transformOriginX = '50%';
//=======================在窗口中居中
// 显示的菜单的宽度,菜单宽度不能超过窗口宽度
let menuWidthTemp = menuWidth;
// 菜单比窗口宽,限制菜单宽度
if (menuWidth + gutter * 2 > windowWidth) {
menuWidthTemp = windowWidth - gutter * 2;
this.$element.width(menuWidthTemp);
}
menuLeft =
(windowWidth - menuWidthTemp) / 2 +
(isFixed ? 0 : anchorOffsetLeft - anchorLeft);
}
this.$element.css('left', `${menuLeft}px`);
// 设置菜单动画方向
this.$element.transformOrigin(`${transformOriginX} ${transformOriginY}`);
}
/**
* 调整子菜单的位置
* @param $submenu
*/
private readjustSubmenu($submenu: JQ): void {
const $item = $submenu.parent('.mdui-menu-item');
let submenuTop;
let submenuLeft;
// 子菜单位置和方向
let position: 'top' | 'bottom';
let align: 'left' | 'right';
// window 窗口的宽度和高度
const windowHeight = $window.height();
const windowWidth = $window.width();
// 动画方向参数
let transformOriginX;
let transformOriginY;
// 子菜单的原始宽度和高度
const submenuWidth = $submenu.width();
const submenuHeight = $submenu.height();
// 触发子菜单的菜单项的宽度高度
const itemRect = $item[0].getBoundingClientRect();
const itemWidth = itemRect.width;
const itemHeight = itemRect.height;
const itemLeft = itemRect.left;
const itemTop = itemRect.top;
// 判断菜单上下位置
if (windowHeight - itemTop > submenuHeight) {
// 判断下方是否放得下菜单
position = 'bottom';
} else if (itemTop + itemHeight > submenuHeight) {
// 判断上方是否放得下菜单
position = 'top';
} else {
// 默认放在下方
position = 'bottom';
}
// 判断菜单左右位置
if (windowWidth - itemLeft - itemWidth > submenuWidth) {
// 判断右侧是否放得下菜单
align = 'left';
} else if (itemLeft > submenuWidth) {
// 判断左侧是否放得下菜单
align = 'right';
} else {
// 默认放在右侧
align = 'left';
}
// 设置菜单位置
if (position === 'bottom') {
transformOriginY = '0';
submenuTop = '0';
} else if (position === 'top') {
transformOriginY = '100%';
submenuTop = -submenuHeight + itemHeight;
}
$submenu.css('top', `${submenuTop}px`);
// 设置菜单对齐方式
if (align === 'left') {
transformOriginX = '0';
submenuLeft = itemWidth;
} else if (align === 'right') {
transformOriginX = '100%';
submenuLeft = -submenuWidth;
}
$submenu.css('left', `${submenuLeft}px`);
// 设置菜单动画方向
$submenu.transformOrigin(`${transformOriginX} ${transformOriginY}`);
}
/**
* 打开子菜单
* @param $submenu
*/
private openSubMenu($submenu: JQ): void {
this.readjustSubmenu($submenu);
$submenu
.addClass('mdui-menu-open')
.parent('.mdui-menu-item')
.addClass('mdui-menu-item-active');
}
/**
* 关闭子菜单,及其嵌套的子菜单
* @param $submenu
*/
private closeSubMenu($submenu: JQ): void {
// 关闭子菜单
$submenu
.removeClass('mdui-menu-open')
.addClass('mdui-menu-closing')
.transitionEnd(() => $submenu.removeClass('mdui-menu-closing'))
// 移除激活状态的样式
.parent('.mdui-menu-item')
.removeClass('mdui-menu-item-active');
// 循环关闭嵌套的子菜单
$submenu.find('.mdui-menu').each((_, menu) => {
const $subSubmenu = $(menu);
$subSubmenu
.removeClass('mdui-menu-open')
.addClass('mdui-menu-closing')
.transitionEnd(() => $subSubmenu.removeClass('mdui-menu-closing'))
.parent('.mdui-menu-item')
.removeClass('mdui-menu-item-active');
});
}
/**
* 切换子菜单状态
* @param $submenu
*/
private toggleSubMenu($submenu: JQ): void {
$submenu.hasClass('mdui-menu-open')
? this.closeSubMenu($submenu)
: this.openSubMenu($submenu);
}
/**
* 绑定子菜单事件
*/
private bindSubMenuEvent(): void {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const that = this;
// 点击打开子菜单
this.$element.on('click', '.mdui-menu-item', function (event) {
const $item = $(this as HTMLElement);
const $target = $(event.target as HTMLElement);
// 禁用状态菜单不操作
if ($item.attr('disabled') !== undefined) {
return;
}
// 没有点击在子菜单的菜单项上时,不操作(点在了子菜单的空白区域、或分隔线上)
if ($target.is('.mdui-menu') || $target.is('.mdui-divider')) {
return;
}
// 阻止冒泡,点击菜单项时只在最后一级的 mdui-menu-item 上生效,不向上冒泡
if (!$target.parents('.mdui-menu-item').first().is($item)) {
return;
}
// 当前菜单的子菜单
const $submenu = $item.children('.mdui-menu');
// 先关闭除当前子菜单外的所有同级子菜单
$item
.parent('.mdui-menu')
.children('.mdui-menu-item')
.each((_, item) => {
const $tmpSubmenu = $(item).children('.mdui-menu');
if (
$tmpSubmenu.length &&
(!$submenu.length || !$tmpSubmenu.is($submenu))
) {
that.closeSubMenu($tmpSubmenu);
}
});
// 切换当前子菜单
if ($submenu.length) {
that.toggleSubMenu($submenu);
}
});
if (this.options.subMenuTrigger === 'hover') {
// 临时存储 setTimeout 对象
let timeout: any = null;
let timeoutOpen: any = null;
this.$element.on(
'mouseover mouseout',
'.mdui-menu-item',
function (event) {
const $item = $(this as HTMLElement);
const eventType = event.type;
const $relatedTarget = $(
(event as MouseEvent).relatedTarget as HTMLElement,
);
// 禁用状态的菜单不操作
if ($item.attr('disabled') !== undefined) {
return;
}
// 用 mouseover 模拟 mouseenter
if (eventType === 'mouseover') {
if (
!$item.is($relatedTarget) &&
contains($item[0], $relatedTarget[0])
) {
return;
}
}
// 用 mouseout 模拟 mouseleave
else if (eventType === 'mouseout') {
if (
$item.is($relatedTarget) ||
contains($item[0], $relatedTarget[0])
) {
return;
}
}
// 当前菜单项下的子菜单,未必存在
const $submenu = $item.children('.mdui-menu');
// 鼠标移入菜单项时,显示菜单项下的子菜单
if (eventType === 'mouseover') {
if ($submenu.length) {
// 当前子菜单准备打开时,如果当前子菜单正准备着关闭,不用再关闭了
const tmpClose = $submenu.data('timeoutClose.mdui.menu');
if (tmpClose) {
clearTimeout(tmpClose);
}
// 如果当前子菜单已经打开,不操作
if ($submenu.hasClass('mdui-menu-open')) {
return;
}
// 当前子菜单准备打开时,其他准备打开的子菜单不用再打开了
clearTimeout(timeoutOpen);
// 准备打开当前子菜单
timeout = timeoutOpen = setTimeout(
() => that.openSubMenu($submenu),
that.options.subMenuDelay,
);
$submenu.data('timeoutOpen.mdui.menu', timeout);
}
}
// 鼠标移出菜单项时,关闭菜单项下的子菜单
else if (eventType === 'mouseout') {
if ($submenu.length) {
// 鼠标移出菜单项时,如果当前菜单项下的子菜单正准备打开,不用再打开了
const tmpOpen = $submenu.data('timeoutOpen.mdui.menu');
if (tmpOpen) {
clearTimeout(tmpOpen);
}
// 准备关闭当前子菜单
timeout = setTimeout(
() => that.closeSubMenu($submenu),
that.options.subMenuDelay,
);
$submenu.data('timeoutClose.mdui.menu', timeout);
}
}
},
);
}
}
/**
* 动画结束回调
*/
private transitionEnd(): void {
this.$element.removeClass('mdui-menu-closing');
if (this.state === 'opening') {
this.state = 'opened';
this.triggerEvent('opened');
}
if (this.state === 'closing') {
this.state = 'closed';
this.triggerEvent('closed');
// 关闭后,恢复菜单样式到默认状态,并恢复 fixed 定位
this.$element.css({
top: '',
left: '',
width: '',
position: 'fixed',
});
}
}
/**
* 切换菜单状态
*/
public toggle(): void {
this.isOpen() ? this.close() : this.open();
}
/**
* 打开菜单
*/
public open(): void {
if (this.isOpen()) {
return;
}
this.state = 'opening';
this.triggerEvent('open');
this.readjust();
this.$element
// 菜单隐藏状态使用使用 fixed 定位。
.css('position', this.options.fixed ? 'fixed' : 'absolute')
.addClass('mdui-menu-open')
.transitionEnd(() => this.transitionEnd());
}
/**
* 关闭菜单
*/
public close(): void {
if (!this.isOpen()) {
return;
}
this.state = 'closing';
this.triggerEvent('close');
// 菜单开始关闭时,关闭所有子菜单
this.$element.find('.mdui-menu').each((_, submenu) => {
this.closeSubMenu($(submenu));
});
this.$element
.removeClass('mdui-menu-open')
.addClass('mdui-menu-closing')
.transitionEnd(() => this.transitionEnd());
}
}
mdui.Menu = Menu; | the_stack |
import {CUSTOM_DRAG_TYPE, GENERIC_TYPE, NATIVE_DRAG_TYPES} from './constants';
import {DirectoryItem, DragItem, DropItem, FileItem, DragTypes as IDragTypes} from '@react-types/shared';
import {DroppableCollectionState} from '@react-stately/dnd';
import {getInteractionModality, useInteractionModality} from '@react-aria/interactions';
import {useId} from '@react-aria/utils';
const droppableCollectionIds = new WeakMap<DroppableCollectionState, string>();
export function useDroppableCollectionId(state: DroppableCollectionState) {
let id = useId();
droppableCollectionIds.set(state, id);
return id;
}
export function getDroppableCollectionId(state: DroppableCollectionState) {
let id = droppableCollectionIds.get(state);
if (!id) {
throw new Error('Droppable item outside a droppable collection');
}
return id;
}
export function getTypes(items: DragItem[]): Set<string> {
let types = new Set<string>();
for (let item of items) {
for (let type of Object.keys(item)) {
types.add(type);
}
}
return types;
}
function mapModality(modality: string) {
if (!modality) {
modality = 'virtual';
}
if (modality === 'pointer') {
modality = 'virtual';
}
if (modality === 'virtual' && 'ontouchstart' in window) {
modality = 'touch';
}
return modality;
}
export function useDragModality() {
return mapModality(useInteractionModality());
}
export function getDragModality() {
return mapModality(getInteractionModality());
}
export function writeToDataTransfer(dataTransfer: DataTransfer, items: DragItem[]) {
// The data transfer API doesn't support more than one item of a given type at once.
// In addition, only a small set of types are supported natively for transfer between applications.
// We allow for both multiple items, as well as multiple representations of a single item.
// In order to make our API work with the native API, we serialize all items to JSON and
// store as a single native item. We only need to do this if there is more than one item
// of the same type, or if an item has more than one representation. Otherwise the native
// API is sufficient.
//
// The DataTransferItemList API also theoretically supports adding files, which would enable
// dragging binary data out of the browser onto the user's desktop for example. Unfortunately,
// this does not currently work in any browser, so it is not currently supported by our API.
// See e.g. https://bugs.chromium.org/p/chromium/issues/detail?id=438479.
let groupedByType = new Map<string, string[]>();
let needsCustomData = false;
let customData = [];
for (let item of items) {
let types = Object.keys(item);
if (types.length > 1) {
needsCustomData = true;
}
let dataByType = {};
for (let type of types) {
let typeItems = groupedByType.get(type);
if (!typeItems) {
typeItems = [];
groupedByType.set(type, typeItems);
} else {
needsCustomData = true;
}
let data = item[type];
dataByType[type] = data;
typeItems.push(data);
}
customData.push(dataByType);
}
for (let [type, items] of groupedByType) {
if (NATIVE_DRAG_TYPES.has(type)) {
// Only one item of a given type can be set on a data transfer.
// Join all of the items together separated by newlines.
let data = items.join('\n');
dataTransfer.items.add(data, type);
} else {
// Set data to the first item so we have access to the list of types.
dataTransfer.items.add(items[0], type);
}
}
if (needsCustomData) {
let data = JSON.stringify(customData);
dataTransfer.items.add(data, CUSTOM_DRAG_TYPE);
}
}
export class DragTypes implements IDragTypes {
private types: Set<string>;
private includesUnknownTypes: boolean;
constructor(dataTransfer: DataTransfer) {
this.types = new Set<string>();
let hasFiles = false;
for (let item of dataTransfer.items) {
if (item.type !== CUSTOM_DRAG_TYPE) {
if (item.kind === 'file') {
hasFiles = true;
}
if (item.type) {
this.types.add(item.type);
} else {
// Files with unknown types or extensions that don't map to a known mime type
// are sometimes exposed as an empty string by the browser. Map to a generic
// mime type instead. Note that this could also be a directory as there's no
// way to determine if something is a file or directory until drop.
this.types.add(GENERIC_TYPE);
}
}
}
// In Safari, when dragging files, the dataTransfer.items list is empty, but dataTransfer.types contains "Files".
// Unfortunately, this doesn't tell us what types of files the user is dragging, so we need to assume that any
// type the user checks for is included. See https://bugs.webkit.org/show_bug.cgi?id=223517.
this.includesUnknownTypes = !hasFiles && dataTransfer.types.includes('Files');
}
has(type: string) {
if (this.includesUnknownTypes) {
return true;
}
return this.types.has(type);
}
}
export function readFromDataTransfer(dataTransfer: DataTransfer) {
let items: DropItem[] = [];
// If our custom drag type is available, use that. This is a JSON serialized
// representation of all items in the drag, set when there are multiple items
// of the same type, or an individual item has multiple representations.
let hasCustomType = false;
if (dataTransfer.types.includes(CUSTOM_DRAG_TYPE)) {
try {
let data = dataTransfer.getData(CUSTOM_DRAG_TYPE);
let parsed = JSON.parse(data);
for (let item of parsed) {
items.push({
kind: 'text',
types: new Set(Object.keys(item)),
getText: (type) => Promise.resolve(item[type])
});
}
hasCustomType = true;
} catch (e) {
// ignore
}
}
// Otherwise, map native drag items to items of a single representation.
if (!hasCustomType) {
let stringItems = new Map();
for (let item of dataTransfer.items) {
if (item.kind === 'string') {
// The data for all formats must be read here because the data transfer gets
// cleared out after the event handler finishes. If the item has an empty string
// as a type, the mime type is unknown. Map to a generic mime type instead.
stringItems.set(item.type || GENERIC_TYPE, dataTransfer.getData(item.type));
} else if (item.kind === 'file') {
// Despite the name, webkitGetAsEntry is also implemented in Firefox and Edge.
// In the future, we may use getAsFileSystemHandle instead, but that's currently
// only implemented in Chrome.
if (typeof item.webkitGetAsEntry === 'function') {
let entry: FileSystemEntry = item.webkitGetAsEntry();
if (!entry) {
// For some reason, Firefox includes an item with type image/png when copy
// and pasting any file or directory (no matter the type), but returns `null` for both
// item.getAsFile() and item.webkitGetAsEntry(). Safari works as expected. Ignore this
// item if this happens. See https://bugzilla.mozilla.org/show_bug.cgi?id=1699743.
// This was recently fixed in Chrome Canary: https://bugs.chromium.org/p/chromium/issues/detail?id=1175483.
continue;
}
if (entry.isFile) {
items.push(createFileItem(item.getAsFile()));
} else if (entry.isDirectory) {
items.push(createDirectoryItem(entry));
}
} else {
// Assume it's a file.
items.push(createFileItem(item.getAsFile()));
}
}
}
// All string items are different representations of the same item. There's no way to have
// multiple string items at once in the current DataTransfer API.
if (stringItems.size > 0) {
items.push({
kind: 'text',
types: new Set(stringItems.keys()),
getText: (type) => Promise.resolve(stringItems.get(type))
});
}
}
return items;
}
function blobToString(blob: Blob): Promise<string> {
if (typeof blob.text === 'function') {
return blob.text();
}
// Safari doesn't have the Blob#text() method yet...
return new Promise((resolve, reject) => {
let reader = new FileReader;
reader.onload = () => {
resolve(reader.result as string);
};
reader.onerror = reject;
reader.readAsText(blob);
});
}
function createFileItem(file: File): FileItem {
return {
kind: 'file',
type: file.type || GENERIC_TYPE,
name: file.name,
getText: () => blobToString(file),
getFile: () => Promise.resolve(file)
};
}
function createDirectoryItem(entry: any): DirectoryItem {
return {
kind: 'directory',
name: entry.name,
getEntries: () => getEntries(entry)
};
}
interface FileSystemFileEntry {
isFile: true,
isDirectory: false,
name: string,
file(successCallback: (file: File) => void, errorCallback?: (error: Error) => void): void
}
interface FileSystemDirectoryEntry {
isDirectory: true,
isFile: false,
name: string,
createReader(): FileSystemDirectoryReader
}
type FileSystemEntry = FileSystemFileEntry | FileSystemDirectoryEntry;
interface FileSystemDirectoryReader {
readEntries(successCallback: (entries: FileSystemEntry[]) => void, errorCallback?: (error: Error) => void): void
}
async function *getEntries(item: FileSystemDirectoryEntry): AsyncIterable<FileItem | DirectoryItem> {
let reader = item.createReader();
// We must call readEntries repeatedly because there may be a limit to the
// number of entries that are returned at once.
let entries: FileSystemEntry[];
do {
entries = await new Promise((resolve, reject) => {
reader.readEntries(resolve, reject);
});
for (let entry of entries) {
if (entry.isFile) {
let file = await getEntryFile(entry);
yield createFileItem(file);
} else if (entry.isDirectory) {
yield createDirectoryItem(entry);
}
}
} while (entries.length > 0);
}
function getEntryFile(entry: FileSystemFileEntry): Promise<File> {
return new Promise((resolve, reject) => entry.file(resolve, reject));
} | the_stack |
import mnemonicData from "./Opcodes.js";
import {hi, isByteReg, isWordReg, lo, toHexWord} from "z80-base";
import {Variant} from "./OpcodesTypes.js";
import * as path from "path";
import * as fs from "fs";
/**
* List of all flags that can be specified in an instruction.
*/
const FLAGS = new Set(["z", "nz", "c", "nc", "po", "pe", "p", "m"]);
// Byte-defining pseudo instructions.
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z54.htm
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z51.htm
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z59.htm
const PSEUDO_DEF_BYTES = new Set(["defb", "db", ".db", ".byte", "defm", "dm", ".dm", ".text", ".ascii", ".asciz"]);
// Word-defining pseudo instructions.
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z52.htm
const PSEUDO_DEF_WORDS = new Set(["defw", "dw", ".dw", ".word"]);
// Long-defining pseudo instructions.
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z53.htm
const PSEUDO_DEF_LONGS = new Set([".long"]);
// Instruction to assign a value to a symbol. We don't support the "set" variant
// because it clashes with the Z80 "set" instruction, and so requires extra
// parsing logic.
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z71.htm
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z72.htm
const PSEUDO_EQU = new Set(["equ", ".equ", "defl", "="]);
// Org-setting pseudo instructions.
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z50.htm
const PSEUDO_ORG = new Set(["org", ".org", ".loc"]);
// Alignment pseudo instructions.
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z57.htm
const PSEUDO_ALIGN = new Set(["align", ".align"]);
// Fill pseudo instructions.
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z56.htm
const PSEUDO_FILL = new Set(["defs", "ds", ".ds", ".block", ".blkb", "data"]);
// Pseudo instructions to start and end macro definitions.
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z64.htm#A
const PSEUDO_MACRO = new Set(["macro", ".macro"]);
const PSEUDO_ENDM = new Set(["endm", ".endm"]);
// Pseudo instructions for if/else/endif.
const PSEUDO_IF = new Set(["if", "cond", "#if"]);
const PSEUDO_ELSE = new Set(["else", "#else"]);
const PSEUDO_ENDIF = new Set(["endif", "endc", "#endif"]);
// End file instruction. Followed by optional entry address or label.
const PSEUDO_END = new Set(["end"]);
// Valid extensions for files in library directories. Use the same list as zasm.
const LIBRARY_EXTS = new Set([".s", ".ass", ".asm"]);
// Possible tags for macro parameters.
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z65.htm#A
const MACRO_TAGS = ["!", "#", "$", "%", "&", ".", ":", "?", "@", "\\", "^", "_", "|", "~"];
// Type of target we can handle.
type Target = "bin" | "rom";
/**
* Parse a single digit in the given base, or undefined if the digit does not
* belong to that base.
*/
function parseDigit(ch: string, base: number): number | undefined {
let value = ch >= '0' && ch <= '9' ? ch.charCodeAt(0) - 0x30
: ch >= 'A' && ch <= 'F' ? ch.charCodeAt(0) - 0x41 + 10
: ch >= 'a' && ch <= 'f' ? ch.charCodeAt(0) - 0x61 + 10
: undefined;
return value === undefined || value >= base ? undefined : value;
}
function isFlag(s: string): boolean {
return FLAGS.has(s.toLowerCase());
}
function isLegalIdentifierCharacter(ch: string, isFirst: boolean) {
return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '.' || ch == '_' ||
(!isFirst && (ch >= '0' && ch <= '9'));
}
// Whether the specified character counts as horizontal whitespace.
function isWhitespace(c: string): boolean {
return c === " " || c === "\t";
}
/**
* Get the fill byte for the specified target.
*/
function fillForTarget(target: Target): number {
switch (target) {
case "bin":
return 0x00;
case "rom":
return 0xFF;
}
}
// A reference to a symbol.
export class SymbolReference {
// Line number in listing.
public lineNumber: number;
public column: number;
constructor(lineNumber: number, column: number) {
this.lineNumber = lineNumber;
this.column = column;
}
}
// Information about a symbol (label, constant).
export class SymbolInfo {
public readonly name: string;
public value: number;
public definitions: SymbolReference[] = [];
public references: SymbolReference[] = [];
// If it has multiple definitions with different values.
public changesValue = false;
constructor(name: string, value: number) {
this.name = name;
this.value = value;
}
// Whether the specified point is in this reference.
public matches(ref: SymbolReference, lineNumber: number, column: number) {
return lineNumber === ref.lineNumber &&
column >= ref.column && column <= ref.column + this.name.length;
}
}
// Information about each file that was read. Note that we may have more than one of these
// objects for one physical file if the file is included more than once.
export class FileInfo {
public readonly pathname: string;
// File that included this file, or undefined if it's the top file.
public readonly parentFileInfo: FileInfo | undefined;
// Depth of include, with 0 meaning top level.
public readonly depth: number;
// Line number in listing, inclusive.
public beginLineNumber = 0;
// Line number in listing, exclusive.
public endLineNumber = 0;
// Files included by this file.
public readonly childFiles: FileInfo[] = [];
// Lines in listing that correspond to this file.
public readonly lineNumbers: number[] = [];
constructor(pathname: string, parentFileInfo: FileInfo | undefined) {
this.pathname = pathname;
this.parentFileInfo = parentFileInfo;
this.depth = parentFileInfo === undefined ? 0 : parentFileInfo.depth + 1;
if (parentFileInfo !== undefined) {
parentFileInfo.childFiles.push(this);
}
}
}
export class AssembledLine {
// Source of line.
public readonly fileInfo: FileInfo;
// Line number in original file, or undefined if it's a synthetic line.
public readonly lineNumber: number | undefined;
// Text of line.
public readonly line: string;
// Line number in the listing.
public listingLineNumber = 0;
// Address of this line.
public address = 0;
// Decoded opcodes and parameters:
public binary: number[] = [];
// Any error found in the line.
public error: string | undefined;
// The variant of the instruction, if any.
public variant: Variant | undefined;
// List of symbols defined or referenced on this line.
public readonly symbols: SymbolInfo[] = [];
// The next address, if it was explicitly specified.
private specifiedNextAddress: number | undefined;
constructor(fileInfo: FileInfo, lineNumber: number | undefined, line: string) {
this.fileInfo = fileInfo;
this.lineNumber = lineNumber;
this.line = line;
}
set nextAddress(nextAddress: number) {
this.specifiedNextAddress = nextAddress;
}
get nextAddress(): number {
// Return explicit if provided, otherwise compute.
return this.specifiedNextAddress ?? (this.address + this.binary.length);
}
}
// Read the lines of a file, or undefined if the file cannot be read.
export type FileReader = (pathname: string) => string[] | undefined;
export class SourceFile {
public readonly fileInfo: FileInfo;
public readonly assembledLines: AssembledLine[];
constructor(fileInfo: FileInfo, assembledLines: AssembledLine[]) {
this.fileInfo = fileInfo;
this.assembledLines = assembledLines;
}
}
/**
* Macro definition.
*/
class Macro {
public readonly name: string;
// Single-character tag, like "&", "\\", or "#".
public readonly tag: string;
// Parameter names, not including the tags.
public readonly params: string[];
// Line number of ".macro" in the listing.
public readonly macroListingLineNumber: number;
// Line number of ".endm" in the listing.
public readonly endmListingLineNumber: number;
// Lines of text, not including .macro or endm.
public readonly lines: string[];
constructor(name: string, tag: string, params: string[], macroListingLineNumber: number, endmListingLineNumber: number, lines: string[]) {
this.name = name;
this.tag = tag;
this.params = params;
this.macroListingLineNumber = macroListingLineNumber;
this.endmListingLineNumber = endmListingLineNumber;
this.lines = lines;
}
}
/**
* Scope for symbols.
*/
class Scope {
public readonly symbols = new Map<string, SymbolInfo>();
public readonly parent: Scope | undefined;
constructor(parent: Scope | undefined) {
this.parent = parent;
}
public get(identifier: string, propagateUp?: boolean): SymbolInfo | undefined {
let symbolInfo = this.symbols.get(identifier);
if (symbolInfo === undefined && propagateUp && this.parent !== undefined) {
symbolInfo = this.parent.get(identifier, propagateUp);
}
return symbolInfo;
}
public set(identifier: string, symbolInfo: SymbolInfo): void {
this.symbols.set(identifier, symbolInfo);
}
public remove(identifier: string): void {
this.symbols.delete(identifier);
}
}
/**
* Assembler.
*/
export class Asm {
// Interface for fetching a file's lines.
public readonly fileReader: FileReader;
// Index 0 is global scope, then one scope for each #local.
public readonly scopes: Scope[] = [new Scope(undefined)];
// All assembled lines.
public assembledLines: AssembledLine[] = [];
// Cache from full directory path to list of filenames in the directory.
private dirCache = new Map<string,string[]>();
// Map from macro name (lower case) to its definition.
public macros = new Map<string,Macro>();
// Entry point into program.
public entryPoint: number | undefined = undefined;
constructor(fileReader: FileReader) {
this.fileReader = fileReader;
}
public assembleFile(pathname: string): SourceFile | undefined {
// Load the top-level file. This array will grow as we include files and expand macros.
const sourceFile = this.loadSourceFile(pathname, undefined);
if (sourceFile === undefined) {
return undefined;
}
this.assembledLines = sourceFile.assembledLines;
// FIRST PASS. Expand include files and macros, assemble instructions so that each
// label knows where it'll be.
new Pass(this, 1).run();
// SECOND PASS. Patch up references and generate error messages for undefined symbols.
new Pass(this, 2).run();
// Fix up line numbers in FileInfo structures.
for (let lineNumber = 0; lineNumber < this.assembledLines.length; lineNumber++) {
const assembledLine = this.assembledLines[lineNumber];
assembledLine.fileInfo.lineNumbers.push(lineNumber);
}
// Fix up begin/end line numbers in FileInfo structures.
const computeBeginEndLineNumbers = (fileInfo: FileInfo) => {
if (fileInfo.lineNumbers.length === 0) {
throw new Error("File info for \"" + fileInfo.pathname + "\" has no lines");
}
fileInfo.beginLineNumber = fileInfo.lineNumbers[0];
fileInfo.endLineNumber = fileInfo.lineNumbers[fileInfo.lineNumbers.length - 1] + 1;
for (const child of fileInfo.childFiles) {
// Process children first.
computeBeginEndLineNumbers(child);
fileInfo.beginLineNumber = Math.min(fileInfo.beginLineNumber, child.beginLineNumber);
fileInfo.endLineNumber = Math.max(fileInfo.endLineNumber, child.endLineNumber);
}
};
computeBeginEndLineNumbers(sourceFile.fileInfo);
// Fill in symbols of each line.
for (const scope of this.scopes) {
for (const symbol of scope.symbols.values()) {
for (const reference of symbol.definitions) {
this.assembledLines[reference.lineNumber].symbols.push(symbol);
}
for (const reference of symbol.references) {
this.assembledLines[reference.lineNumber].symbols.push(symbol);
}
}
}
return sourceFile;
}
/**
* Load a source file as an array of AssembledLine objects, or undefined if the
* file can't be loaded.
*/
public loadSourceFile(pathname: string, parentFileInfo: FileInfo | undefined): SourceFile | undefined {
const lines = this.fileReader(pathname);
if (lines === undefined) {
return undefined;
}
const fileInfo = new FileInfo(pathname, parentFileInfo);
// Converted to assembled lines.
const assembledLines: AssembledLine[] = [];
for (let lineNumber = 0; lineNumber < lines.length; lineNumber++) {
assembledLines.push(new AssembledLine(fileInfo, lineNumber, lines[lineNumber]));
}
return new SourceFile(fileInfo, assembledLines);
}
/**
* Reads a directory, caching the results.
*
* @return a list of filenames in the directory, or undefined if an error occurs.
*/
public readDir(dir: string): string[] | undefined {
let filenames = this.dirCache.get(dir);
if (filenames == undefined) {
try {
filenames = fs.readdirSync(dir);
} catch (e) {
// Can't read dir.
return undefined;
}
this.dirCache.set(dir, filenames);
}
return filenames;
}
}
/**
* Represents a pass through all the files.
*/
class Pass {
public readonly asm: Asm;
public readonly passNumber: number;
// The current scope, local or global.
public currentScope: Scope;
// Number of scopes defined so far in this pass, including global (index 0).
public scopeCount = 1;
// Target type (bin, rom).
public target: Target = "bin";
// Number (in listing) of line we're assembling.
private listingLineNumber = 0;
// Number of library files we included.
public libraryIncludeCount = 0;
// Whether we've seen an "end" directive.
public sawEnd = false;
constructor(asm: Asm, passNumber: number) {
this.asm = asm;
this.passNumber = passNumber;
this.currentScope = this.asm.scopes[0];
}
/**
* Assembles the lines of the file. Returns a FileInfo object for this tree, or undefined
* if the file couldn't be read.
*
* @return the number of errors.
*/
public run(): number {
const before = Date.now();
let errorCount = 0;
// Assemble every line.
this.listingLineNumber = 0;
while (true) {
const assembledLine = this.getNextLine();
if (assembledLine === undefined) {
break;
}
new LineParser(this, assembledLine).assemble();
if (assembledLine.error !== undefined) {
errorCount++;
}
}
// Make sure our #local and #endlocal are balanced.
if (this.currentScope !== this.asm.scopes[0]) {
const lines = this.asm.assembledLines;
if (lines.length > 0 && lines[lines.length - 1].error === undefined) {
lines[lines.length - 1].error = "missing #endlocal";
}
}
const after = Date.now();
/*
console.log("Pass " + this.passNumber + " time: " + (after - before) +
", library includes: " + this.libraryIncludeCount +
", errors: " + errorCount);
*/
return errorCount;
}
/**
* Return the next line of the listing file, or undefined if there are no more.
*/
public getNextLine(): AssembledLine | undefined {
if (this.listingLineNumber < 0 || this.listingLineNumber >= this.asm.assembledLines.length) {
return undefined;
}
const listingLineNumber = this.listingLineNumber++;
const assembledLine = this.asm.assembledLines[listingLineNumber];
assembledLine.listingLineNumber = listingLineNumber;
assembledLine.address = listingLineNumber === 0 ? 0 : this.asm.assembledLines[listingLineNumber - 1].nextAddress;
return assembledLine;
}
/**
* Rewind or skip ahead to this location. This line will be parsed next.
*/
public setListingLineNumber(listingLineNumber: number): void {
this.listingLineNumber = listingLineNumber;
}
/**
* Insert the specified lines immediately after the line currently being assembled.
* @param assembledLines
*/
public insertLines(assembledLines: AssembledLine[]): void {
this.asm.assembledLines.splice(this.listingLineNumber, 0, ...assembledLines);
}
/**
* Return the scope for global symbols.
*/
public globals(): Scope {
return this.asm.scopes[0];
}
/**
* Return the scope for the innermost #local, which could just be the global scope.
*/
public locals(): Scope {
return this.currentScope;
}
/**
* Create a new scope, when we hit #local.
*/
public enterScope(): Scope {
if (this.passNumber === 1) {
this.currentScope = new Scope(this.currentScope);
this.asm.scopes.push(this.currentScope);
this.scopeCount++;
} else {
this.currentScope = this.asm.scopes[this.scopeCount++];
}
return this.currentScope;
}
/**
* Exit the current scope, when we hit #endlocal.
*
* @return whether successful. Might fail if we're already at the global scope.
*/
public leaveScope(): boolean {
const scope = this.currentScope.parent;
if (scope === undefined) {
return false;
}
this.currentScope = scope;
return true;
}
}
/**
* Parser for one single line.
*/
class LineParser {
private readonly pass: Pass;
private readonly assembledLine: AssembledLine;
// Full text of line being parsed.
private readonly line: string;
// Parsing index into the line.
private column: number = 0;
// Pointer to the token we just parsed.
private previousToken = 0;
constructor(pass: Pass, assembledLine: AssembledLine) {
this.pass = pass;
this.assembledLine = assembledLine;
this.line = assembledLine.line;
}
public assemble(): void {
// Convenience.
const thisAddress = this.assembledLine.address;
// Clear out anything we put in previous passes.
this.assembledLine.binary.length = 0;
if (this.pass.sawEnd) {
// Ignore all lines after "end".
return;
}
// What value to assign to the label we parse, if any.
let labelValue: number | undefined;
// Look for compiler directive.
if (this.line.trim().startsWith("#")) {
this.parseDirective();
return;
}
// Look for label in column 1.
let symbolColumn = 0;
let label = this.readIdentifier(false, false);
let labelIsGlobal = false;
if (label !== undefined) {
if (this.foundChar(':')) {
if (this.foundChar(':')) {
// Double colons indicate global symbols (not local to #local).
labelIsGlobal = true;
}
}
// By default assign it to current address, but can be overwritten
// by .equ below.
labelValue = thisAddress;
symbolColumn = this.previousToken;
}
this.skipWhitespace();
let mnemonic = this.readIdentifier(false, true);
if (mnemonic === undefined) {
// Special check for "=", which is the same as "defl".
const column = this.column;
if (this.foundChar("=")) {
mnemonic = "=";
this.previousToken = column;
}
}
if (mnemonic !== undefined && this.previousToken > 0) {
if (PSEUDO_DEF_BYTES.has(mnemonic)) {
while (true) {
const s = this.readString();
if (s !== undefined) {
const adjustOperator = this.foundOneOfChar(["+", "-", "&", "|", "^"]);
let adjustValue: number | undefined;
if (adjustOperator !== undefined) {
adjustValue = this.readExpression(true);
if (adjustValue === undefined) {
if (this.assembledLine.error === undefined) {
this.assembledLine.error = "bad adjustment value";
}
return;
}
}
for (let i = 0; i < s.length; i++) {
let value = s.charCodeAt(i);
if (i === s.length - 1 && adjustOperator !== undefined && adjustValue !== undefined) {
switch (adjustOperator) {
case "+":
value += adjustValue;
break;
case "-":
value -= adjustValue;
break;
case "&":
value &= adjustValue;
break;
case "|":
value |= adjustValue;
break;
case "^":
value ^= adjustValue;
break;
}
value = lo(value);
}
this.assembledLine.binary.push(value);
}
} else if (this.assembledLine.error !== undefined) {
// Error parsing string.
return;
} else {
// Try some pre-defined names. These are only valid here.
const s = this.parsePredefinedName();
if (s !== undefined) {
for (let i = 0; i < s.length; i++) {
this.assembledLine.binary.push(s.charCodeAt(i));
}
} else {
// Try a normal expression.
const value = this.readExpression(true);
if (value === undefined) {
if (this.assembledLine.error === undefined) {
this.assembledLine.error = "invalid " + mnemonic + " expression";
}
return;
}
this.assembledLine.binary.push(lo(value));
}
}
if (!this.foundChar(',')) {
break;
}
}
if (mnemonic === ".asciz") {
// Terminating nul.
this.assembledLine.binary.push(0);
}
} else if (PSEUDO_DEF_WORDS.has(mnemonic)) {
while (true) {
const value = this.readExpression(true);
if (value === undefined) {
if (this.assembledLine.error === undefined) {
this.assembledLine.error = "invalid " + mnemonic + " expression";
}
return;
}
this.assembledLine.binary.push(lo(value));
this.assembledLine.binary.push(hi(value));
if (!this.foundChar(',')) {
break;
}
}
} else if (PSEUDO_DEF_LONGS.has(mnemonic)) {
while (true) {
const value = this.readExpression(true);
if (value === undefined) {
if (this.assembledLine.error === undefined) {
this.assembledLine.error = "invalid " + mnemonic + " expression";
}
return;
}
this.assembledLine.binary.push(lo(value));
this.assembledLine.binary.push(hi(value));
this.assembledLine.binary.push(lo(value >> 16));
this.assembledLine.binary.push(hi(value >> 16));
if (!this.foundChar(',')) {
break;
}
}
} else if (PSEUDO_EQU.has(mnemonic)) {
const value = this.readExpression(true);
if (value === undefined) {
this.assembledLine.error = "bad value for constant";
} else if (label === undefined) {
this.assembledLine.error = "must have label for constant";
} else {
// Remember constant.
labelValue = value;
}
} else if (PSEUDO_ORG.has(mnemonic)) {
const startAddress = this.readExpression(true);
if (startAddress === undefined) {
this.assembledLine.error = "start address expected";
} else {
this.assembledLine.nextAddress = startAddress;
}
} else if (PSEUDO_ALIGN.has(mnemonic)) {
const align = this.readExpression(true);
if (align === undefined || align <= 0) {
this.assembledLine.error = "alignment value expected";
} else {
let fillChar: number | undefined;
if (this.foundChar(",")) {
const expr = this.readExpression(true);
if (expr === undefined) {
if (this.assembledLine.error === undefined) {
this.assembledLine.error = "error in fill byte";
}
return;
}
fillChar = expr;
}
if (fillChar === undefined) {
this.assembledLine.nextAddress = thisAddress + (align - thisAddress%align)%align;
} else {
fillChar = lo(fillChar);
let address = thisAddress;
while ((address % align) !== 0) {
this.assembledLine.binary.push(fillChar);
address++;
}
}
}
} else if (PSEUDO_FILL.has(mnemonic)) {
const length = this.readExpression(true);
if (length === undefined || length <= 0) {
this.assembledLine.error = "length value expected";
} else {
let fillChar: number | undefined;
if (this.foundChar(",")) {
const expr = this.readExpression(true);
if (expr === undefined) {
if (this.assembledLine.error === undefined) {
this.assembledLine.error = "error in fill byte";
}
return;
}
fillChar = expr;
}
if (fillChar === undefined) {
this.assembledLine.nextAddress = thisAddress + length;
} else {
fillChar = lo(fillChar);
for (let i = 0; i < length; i++) {
this.assembledLine.binary.push(fillChar);
}
}
}
} else if (PSEUDO_MACRO.has(mnemonic)) {
// Macro definition.
let name: string | undefined;
let tag: string;
if (label !== undefined) {
name = label;
label = undefined;
tag = "&";
} else {
name = this.readIdentifier(true, false);
if (name === undefined) {
this.assembledLine.error = "must specify name of macro";
return;
}
tag = "\\";
}
// Convert to lower case because all mnemonics are case-insensitive.
name = name.toLowerCase();
const macro = this.pass.asm.macros.get(name);
if (this.pass.passNumber > 1) {
// Skip macro definition.
if (macro === undefined) {
throw new Error("Macro \"" + name + "\" not found in pass " + this.pass.passNumber);
}
this.pass.setListingLineNumber(macro.endmListingLineNumber + 1);
return;
} else {
// Can't redefine macro.
if (macro !== undefined) {
this.assembledLine.error = "macro \"" + name + "\" already defined";
return;
}
// Parse parameters.
const params: string[] = [];
if (!this.isEndOfLine()) {
// See if the first parameter specifies a tag. It's okay to not have one.
tag = this.foundOneOfChar(MACRO_TAGS) ?? tag;
do {
const thisTag = this.foundOneOfChar(MACRO_TAGS) ?? tag;
if (thisTag !== tag) {
this.assembledLine.error = "Inconsistent tags in macro: " + tag + " and " + thisTag;
return;
}
const param = this.readIdentifier(true, false);
if (param === undefined) {
this.assembledLine.error = "expected macro parameter name";
return;
}
params.push(param);
} while (this.foundChar(","));
// Make sure there's no extra junk.
this.ensureEndOfLine();
}
// Eat rest of macro.
const macroListingLineNumber = this.assembledLine.listingLineNumber;
let endmListingLineNumber: number | undefined = undefined;
const lines: string[] = [];
while (true) {
const assembledLine = this.pass.getNextLine();
if (assembledLine === undefined) {
this.assembledLine.error = "macro has no endm";
break;
}
const lineParser = new LineParser(this.pass, assembledLine);
// TODO check to make sure macro doesn't contain a # directive, unless the tag is
// # and the directive is one of the param names.
lineParser.skipWhitespace();
const token = lineParser.readIdentifier(false, true);
if (token !== undefined && PSEUDO_ENDM.has(token)) {
endmListingLineNumber = assembledLine.listingLineNumber;
break;
}
lines.push(assembledLine.line);
}
if (endmListingLineNumber === undefined) {
// Error in macro. Try to recover.
endmListingLineNumber = macroListingLineNumber;
lines.splice(0, lines.length);
this.pass.setListingLineNumber(macroListingLineNumber + 1);
}
this.pass.asm.macros.set(name, new Macro(name, tag, params,
macroListingLineNumber, endmListingLineNumber, lines));
// Don't want to parse any more of the original macro line.
return;
}
} else if (PSEUDO_ENDM.has(mnemonic)) {
this.assembledLine.error = "endm outside of macro definition";
return;
} else if (PSEUDO_END.has(mnemonic)) {
// End of source file. See if there's an optional entry address or label.
this.skipWhitespace();
if (!this.isEndOfLine()) {
const value = this.readExpression(true);
if (value === undefined) {
if (this.assembledLine.error === undefined) {
this.assembledLine.error = "invalid expression for entry point";
}
return;
}
// See if it's changed.
if (this.pass.asm.entryPoint !== undefined && this.pass.asm.entryPoint !== value) {
if (this.assembledLine.error === undefined) {
this.assembledLine.error = "changing entry point from 0x" +
toHexWord(this.pass.asm.entryPoint) + " to 0x" +
toHexWord(value);
}
return;
}
this.pass.asm.entryPoint = value;
}
this.pass.sawEnd = true;
} else {
this.processOpCode(mnemonic);
}
}
// Make sure there's no extra junk.
this.ensureEndOfLine();
// If we're defining a new symbol, record it.
if (label !== undefined && labelValue !== undefined) {
const scope = labelIsGlobal ? this.pass.globals() : this.pass.locals();
let symbolInfo = scope.get(label);
if (symbolInfo !== undefined) {
// Check if value is changing.
if (symbolInfo.definitions.length > 0 && symbolInfo.value !== labelValue) {
symbolInfo.changesValue = true;
}
symbolInfo.value = labelValue;
} else {
symbolInfo = new SymbolInfo(label, labelValue);
scope.set(label, symbolInfo);
}
if (this.pass.passNumber === 1) {
symbolInfo.definitions.push(new SymbolReference(this.assembledLine.listingLineNumber, symbolColumn));
}
}
}
// Parse a pre-defined name, returning its value.
private parsePredefinedName(): string | undefined {
const name = this.readIdentifier(false, true);
if (name === undefined) {
return undefined;
}
let value;
// https://k1.spdns.de/Develop/Projects/zasm/Documentation/z54.htm
switch (name) {
case "__date__": {
const date = new Date();
value = date.getFullYear() + "-" + (date.getMonth() + 1).toString().padStart(2, "0") + "-" +
date.getDate().toString().padStart(2, "0");
break;
}
case "__time__": {
const date = new Date();
value = date.getHours().toString().padStart(2, "0") + ":" +
date.getMinutes().toString().padStart(2, "0") + ":" +
date.getSeconds().toString().padStart(2, "0");
break;
}
case "__file__":
value = this.assembledLine.fileInfo.pathname;
break;
case "__line__":
// Zero-based.
// The line number might be undefined if the line is synthetic.
value = (this.assembledLine.lineNumber ?? 0).toString();
break;
}
if (value === undefined) {
// Back up, it wasn't for us.
this.column = this.previousToken;
}
return value;
}
// Advance the parser to the end of the line.
private skipToEndOfLine(): void {
this.column = this.line.length;
}
// Whether we're at the end of the line. Assumes we've already skipped whitespace.
private isEndOfLine(): boolean {
return this.isChar(";") || this.column === this.line.length;
}
// Make sure there's no junk at the end of the line.
private ensureEndOfLine(): void {
// Check for comment.
if (this.isChar(';')) {
// Skip rest of line.
this.column = this.line.length;
}
if (this.column != this.line.length && this.assembledLine.error === undefined) {
this.assembledLine.error = "syntax error";
}
}
private parseDirective(): void {
this.skipWhitespace();
if (!this.foundChar('#')) {
// Logic error.
throw new Error("did not find # for directive");
}
const directive = this.readIdentifier(true, true);
if (directive === undefined || directive === "") {
this.assembledLine.error = "must specify directive after #";
return;
}
switch (directive) {
case "target":
const target = this.readIdentifier(false, true);
if (target === "bin" || target === "rom") {
this.pass.target = target;
} else {
if (target === undefined) {
this.assembledLine.error = "must specify target";
} else {
this.assembledLine.error = "unknown target " + target;
}
return;
}
break;
case "code":
const segmentName = this.readIdentifier(true, false);
if (segmentName === undefined) {
this.assembledLine.error = "segment name expected";
} else if (this.foundChar(',')) {
if (this.foundChar("*")) {
// Keep start address unchanged.
} else {
const startAddress = this.readExpression(true);
if (startAddress === undefined) {
this.assembledLine.error = "start address expected";
} else {
this.assembledLine.nextAddress = startAddress;
}
}
if (this.foundChar(',')) {
const length = this.readExpression(true);
if (length === undefined) {
this.assembledLine.error = "length expected";
}
}
}
break;
case "include": {
const previousColumn = this.column;
const token = this.readIdentifier(false, true);
if (token === "library") {
const dir = this.readString();
if (dir === undefined) {
this.assembledLine.error = "missing library directory";
} else if (this.pass.passNumber === 1) {
const libraryDir = path.resolve(path.dirname(this.assembledLine.fileInfo.pathname), dir);
const filenames = this.pass.asm.readDir(libraryDir);
if (filenames === undefined) {
this.assembledLine.error = "can't read directory \"" + libraryDir + "\"";
return;
}
for (const filename of filenames) {
let parsedPath = path.parse(filename);
if (LIBRARY_EXTS.has(parsedPath.ext)) {
const symbol = this.pass.globals().get(parsedPath.name);
if (symbol !== undefined && symbol.definitions.length === 0) {
// Found used but undefined symbol that matches a file in the library.
const includePathname = path.resolve(libraryDir, filename);
this.pass.insertLines([
new AssembledLine(this.assembledLine.fileInfo, undefined,
"#include \"" + includePathname + "\""),
new AssembledLine(this.assembledLine.fileInfo, undefined,
this.line),
]);
this.pass.libraryIncludeCount++;
break;
}
}
}
}
} else if (token !== undefined) {
this.assembledLine.error = "unknown identifier " + token;
} else {
this.column = previousColumn;
const filename = this.readString();
if (filename === undefined) {
this.assembledLine.error = "missing included filename";
} else if (this.pass.passNumber === 1) {
const includePathname = path.resolve(path.dirname(this.assembledLine.fileInfo.pathname), filename);
const sourceFile = this.pass.asm.loadSourceFile(includePathname, this.assembledLine.fileInfo);
if (sourceFile === undefined) {
this.assembledLine.error = "cannot read file " + includePathname;
} else {
// Insert the included lines right in our listing.
this.pass.insertLines(sourceFile.assembledLines);
}
}
}
break;
}
case "local":
this.pass.enterScope();
break;
case "endlocal":
// When we leave a scope, we must push symbols that are both references and undefined out
// to the outer scope, since that's where they might be defined.
const scope = this.pass.locals();
if (scope.parent === undefined) {
this.assembledLine.error = "#endlocal without #local";
} else {
for (const [identifier, symbol] of scope.symbols) {
if (symbol.references.length > 0 && symbol.definitions.length === 0) {
scope.remove(identifier);
// Merge with this symbol in the parent, if any.
const parentSymbol = scope.parent.get(identifier);
if (parentSymbol === undefined) {
scope.parent.set(identifier, symbol);
} else {
parentSymbol.references.splice(parentSymbol.references.length, 0, ...symbol.references);
}
}
}
this.pass.leaveScope();
}
break;
case "insert": {
// Must specify pathname as string.
const pathname = this.readString();
if (pathname === undefined) {
if (this.assembledLine.error === undefined) {
this.assembledLine.error = "must specify pathname of file to insert";
}
return;
}
// Pathname is relative to including file.
const resolvedPathname = path.resolve(path.dirname(this.assembledLine.fileInfo.pathname), pathname);
// Load the file.
let binary: Uint8Array;
try {
binary = fs.readFileSync(resolvedPathname);
} catch (e) {
this.assembledLine.error = "file \"" + resolvedPathname + "\" not found";
return;
}
this.assembledLine.binary.push(...binary);
break;
}
default:
this.assembledLine.error = "unknown directive #" + directive;
break;
}
// Make sure there's no extra junk.
this.ensureEndOfLine();
}
private processOpCode(mnemonic: string): void {
// See if we should expand a macro.
const macro = this.pass.asm.macros.get(mnemonic);
if (macro !== undefined) {
if (this.pass.passNumber > 1) {
if (this.assembledLine.listingLineNumber > macro.endmListingLineNumber) {
// Valid, used after definition. Skip macro call.
this.skipToEndOfLine();
return;
} else {
// Ignore, will probably be an error below.
}
} else {
// Pass 1, expand macro.
// Parse arguments.
const args: string[] = [];
if (!this.isEndOfLine()) {
do {
const begin = this.column;
while (this.column < this.line.length && !this.isChar(",") && !this.isChar(";")) {
if (this.isChar("\"") || this.isChar("'")) {
const str = this.readString();
if (str === undefined) {
// Error is already set.
return;
}
} else {
this.column++;
}
}
// Back up over trailing spaces.
while (this.column > begin && isWhitespace(this.line.charAt(this.column - 1))) {
this.column--;
}
const arg = this.line.substring(begin, this.column);
args.push(arg);
this.skipWhitespace();
} while (this.foundChar(","));
}
// Make sure we got the right number.
if (args.length < macro.params.length) {
// Give name of argument as hint to what to type next.
this.assembledLine.error = "macro missing \"" + macro.params[args.length] + "\" argument";
return;
}
if (args.length > macro.params.length) {
this.assembledLine.error = "macro got too many arguments (" + args.length +
" instead of " + macro.params.length + ")";
return;
}
const assembledLines = macro.lines.map((line) =>
new AssembledLine(this.assembledLine.fileInfo, undefined, this.performMacroSubstitutions(line, macro, args)));
this.pass.insertLines(assembledLines);
return;
}
}
const mnemonicInfo = mnemonicData.mnemonics[mnemonic];
if (mnemonicInfo !== undefined) {
const argStart = this.column;
let match = false;
for (const variant of mnemonicInfo.variants) {
// Map from something like "nn" to its value.
const args: any = {};
match = true;
for (const token of variant.tokens) {
if (token === "," || token === "(" || token === ")" || token === "+") {
if (!this.foundChar(token)) {
match = false;
}
} else if (token === "nn" || token === "nnnn" || token === "dd" || token === "offset") {
// Parse.
const value = this.readExpression(false);
if (value === undefined) {
match = false;
} else {
// Add value to binary.
if (args[token] !== undefined) {
throw new Error("duplicate arg: " + this.line);
}
args[token] = value;
}
} else if (parseDigit(token[0], 10) !== undefined) {
// If the token is a number, then we must parse an expression and
// compare the values. This is used for BIT, SET, RES, RST, IM, and one
// variant of OUT (OUT (C), 0).
const expectedValue = parseInt(token, 10);
const actualValue = this.readExpression(false);
if (expectedValue !== actualValue) {
match = false;
}
} else {
// Register or flag.
const identifier = this.readIdentifier(true, true);
if (identifier !== token) {
match = false;
}
}
if (!match) {
break;
}
}
if (match) {
// Make sure they're no extra garbage.
if (!this.isEndOfLine()) {
match = false;
}
}
if (match) {
this.assembledLine.binary = [];
for (const op of variant.opcode) {
if (typeof(op) === "string") {
const value = args[op];
if (value === undefined) {
throw new Error("arg " + op + " not found for " + this.line);
}
switch (op) {
case "nnnn":
this.assembledLine.binary.push(lo(value));
this.assembledLine.binary.push(hi(value));
break;
case "nn":
case "dd":
this.assembledLine.binary.push(lo(value));
break;
case "offset":
this.assembledLine.binary.push(lo(value - this.assembledLine.address - this.assembledLine.binary.length - 1));
break;
default:
throw new Error("Unknown arg type " + op);
}
} else {
this.assembledLine.binary.push(op);
}
}
this.assembledLine.variant = variant;
break;
} else {
// Reset reader.
this.column = argStart;
}
}
if (!match && this.assembledLine.error === undefined) {
this.assembledLine.error = "no variant found for " + mnemonic;
}
} else {
this.assembledLine.error = "unknown mnemonic: " + mnemonic;
}
}
/**
* Substitute macro parameters and expand {} expressions.
*/
private performMacroSubstitutions(line: string, macro: Macro, args: string[]): string {
const parts: string[] = [];
let i = 0;
while (i < line.length) {
const ch = line.charAt(i);
if (ch === macro.tag) {
const beginName = i + 1;
let endName = beginName;
while (endName < line.length && isLegalIdentifierCharacter(line.charAt(endName), endName === beginName)) {
endName++;
}
const name = line.substring(beginName, endName);
const argIndex = macro.params.indexOf(name);
if (argIndex >= 0) {
parts.push(args[argIndex]);
i = endName;
} else {
parts.push(ch);
i++;
}
} else {
parts.push(ch);
i++;
}
}
return parts.join("");
}
/**
* Reads a string like "abc", or undefined if didn't find a string.
* If found the beginning of a string but not the end, sets this.assembledLine.error
* and returns undefined.
*/
private readString(): string | undefined {
// Find beginning of string.
if (this.column === this.line.length || (this.line[this.column] !== '"' && this.line[this.column] !== "'")) {
return undefined;
}
const quoteChar = this.line[this.column];
this.column++;
// Find end of string.
const startIndex = this.column;
while (this.column < this.line.length && this.line[this.column] !== quoteChar) {
this.column++;
}
if (this.column === this.line.length) {
// No end quote.
this.assembledLine.error = "no end quote in string";
return undefined;
}
// Clip out string contents.
const value = this.line.substring(startIndex, this.column);
this.column++;
this.skipWhitespace();
return value;
}
/**
* Read an expression.
*
* @param canStartWithOpenParens whether to allow the expression to start with an open parenthesis.
*
* @return the value of the expression, or undefined if there was an error reading it.
*/
private readExpression(canStartWithOpenParens: boolean): number | undefined {
if (!canStartWithOpenParens && this.line[this.column] === '(') {
// Expressions can't start with an open parenthesis because that's ambiguous
// with dereferencing.
return undefined;
}
return this.readSum();
}
private readSum(): number | undefined {
let value = 0;
let sign = 1;
while (true) {
const subValue = this.readProduct();
if (subValue === undefined) {
return undefined;
}
value += sign * subValue;
if (this.foundChar('+')) {
sign = 1;
} else if (this.foundChar('-')) {
sign = -1;
} else {
break;
}
}
return value;
}
private readProduct(): number | undefined {
let value = 1;
let isMultiply = true;
while (true) {
const subValue = this.readLogic();
if (subValue === undefined) {
return undefined;
}
if (isMultiply) {
value *= subValue;
} else {
value /= subValue;
}
if (this.foundChar('*')) {
isMultiply = true;
} else if (this.foundChar('/')) {
isMultiply = false;
} else {
break;
}
}
return value;
}
private readLogic(): number | undefined {
let value = 0;
let op = "";
while (true) {
const subValue = this.readShift();
if (subValue === undefined) {
return undefined;
}
if (op === "&") {
value &= subValue;
} else if (op === "|") {
value |= subValue;
} else if (op === "^") {
value ^= subValue;
} else {
value = subValue;
}
const ch = this.foundOneOfChar(["&", "|", "^"]);
if (ch !== undefined) {
op = ch;
} else {
break;
}
}
return value;
}
private readShift(): number | undefined {
let value = 0;
let op = "";
while (true) {
const subValue = this.readMonadic();
if (subValue === undefined) {
return undefined;
}
if (op === "<<") {
value <<= subValue;
} else if (op === ">>") {
value >>= subValue;
} else {
value = subValue;
}
op = this.line.substr(this.column, 2);
if (op === "<<" || op === ">>") {
this.column += 2;
this.skipWhitespace();
} else {
break;
}
}
return value;
}
private readMonadic(): number | undefined {
const ch = this.foundOneOfChar(["+", "-", "~", "!"]);
if (ch !== undefined) {
const value = this.readMonadic();
if (value === undefined) {
return undefined;
}
switch (ch) {
case "+":
default:
return value;
case "-":
return -value;
case "~":
return ~value;
case "!":
return !value ? 1 : 0;
}
} else {
return this.readAtom();
}
}
private readAtom(): number | undefined {
const startIndex = this.column;
// Parenthesized expression.
if (this.foundChar('(')) {
const value = this.readExpression(true);
if (value === undefined || !this.foundChar(')')) {
return undefined;
}
return value;
}
// Try identifier.
const identifier = this.readIdentifier(false, false);
if (identifier !== undefined) {
// See if it's a built-in function.
if (this.foundChar("(")) {
const value = this.readExpression(true);
if (value === undefined) {
if (this.assembledLine.error === undefined) {
this.assembledLine.error = "missing expression for function call";
}
return undefined;
}
if (!this.foundChar(")")) {
if (this.assembledLine.error === undefined) {
this.assembledLine.error = "missing end parenthesis for function call";
}
return undefined;
}
switch (identifier) {
case "lo":
return lo(value);
case "hi":
return hi(value);
default:
this.assembledLine.error = "unknown function \"" + identifier + "\"";
return undefined;
}
}
// Must be symbol reference. Get address of identifier or value of constant.
// Local symbols can shadow global ones, and might not be defined yet, so only check
// the local scope in pass 1. In pass 2 the identifier must have been defined somewhere.
let symbolInfo = this.pass.locals().get(identifier, this.pass.passNumber !== 1);
if (symbolInfo === undefined) {
if (this.pass.passNumber === 1) {
// Record that this identifier was used so that we can include its file with
// library includes. We don't know whether it's a local or global symbol.
// Assume local and push it out in #endlocal.
symbolInfo = new SymbolInfo(identifier, 0);
this.pass.locals().set(identifier, symbolInfo);
} else {
throw new Error("Identifier " + identifier + " was not defined in pass 1");
}
}
if (this.pass.passNumber === 1) {
// TODO I don't like this, given that evaluating this expression might be speculative.
symbolInfo.references.push(new SymbolReference(this.assembledLine.listingLineNumber, startIndex));
} else if (symbolInfo.definitions.length === 0) {
this.assembledLine.error = "unknown identifier \"" + identifier + "\"";
return 0;
} else if (symbolInfo.definitions.length > 1 &&
symbolInfo.changesValue &&
symbolInfo.definitions[0].lineNumber >= this.assembledLine.listingLineNumber) {
this.assembledLine.error = "label \"" + identifier + "\" not yet defined here";
return 0;
}
return symbolInfo.value;
}
// Try literal character, like 'a'.
if (this.isChar("'")) {
if (this.column > this.line.length - 3 || this.line[this.column + 2] !== "'") {
// TODO invalid character constant, show error.
return undefined;
}
const value = this.line.charCodeAt(this.column + 1);
this.column += 3;
this.skipWhitespace();
return value;
}
// Try numeric literal.
let base = 10;
let sign = 1;
let gotDigit = false;
if (this.foundChar('-')) {
sign = -1;
}
// Hex numbers can start with $, like $FF.
if (this.foundChar('$')) {
if (this.column === this.line.length || parseDigit(this.line[this.column], 16) === undefined) {
// It's a reference to the current address, not a hex prefix.
return sign*this.assembledLine.address;
}
base = 16;
} else if (this.foundChar('%')) {
base = 2;
}
// Before we parse the number, we need to look ahead to see
// if it ends with H, like 0FFH.
if (base === 10) {
const beforeIndex = this.column;
while (this.column < this.line.length && parseDigit(this.line[this.column], 16) !== undefined) {
this.column++;
}
if (this.column < this.line.length && this.line[this.column].toUpperCase() === "H") {
base = 16;
}
this.column = beforeIndex;
}
// And again we need to look for B, like 010010101B. We can't fold this into the
// above look since a "B" is a legal hex number!
if (base === 10) {
const beforeIndex = this.column;
while (this.column < this.line.length && parseDigit(this.line[this.column], 2) !== undefined) {
this.column++;
}
if (this.column < this.line.length && this.line[this.column].toUpperCase() === "B" &&
// "B" can't be followed by hex digit, or it's not the final character.
(this.column === this.line.length || parseDigit(this.line[this.column + 1], 16) === undefined)) {
base = 2;
}
this.column = beforeIndex;
}
// Look for 0x or 0b prefix. Must do this after above checks so that we correctly
// mark "0B1H" as hex and not binary.
if (base === 10 && this.column + 2 < this.line.length && this.line[this.column] === '0') {
if (this.line[this.column + 1].toLowerCase() == 'x') {
base = 16;
this.column += 2;
} else if (this.line[this.column + 1].toLowerCase() == 'b' &&
// Must check next digit to distinguish from just "0B".
parseDigit(this.line[this.column + 2], 2) !== undefined) {
base = 2;
this.column += 2;
}
}
// Parse number.
let value = 0;
while (true) {
if (this.column == this.line.length) {
break;
}
const ch = this.line[this.column];
let chValue = parseDigit(ch, base);
if (chValue === undefined) {
break;
}
value = value * base + chValue;
gotDigit = true;
this.column++;
}
if (!gotDigit) {
// Didn't parse anything.
return undefined;
}
// Check for base suffix.
if (this.column < this.line.length) {
const baseChar = this.line[this.column].toUpperCase();
if (baseChar === "H") {
// Check for programmer errors.
if (base !== 16) {
throw new Error("found H at end of non-hex number: " + this.line.substring(startIndex, this.column + 1));
}
this.column++;
} else if (baseChar === "B") {
// Check for programmer errors.
if (base !== 2) {
throw new Error("found B at end of non-binary number: " + this.line.substring(startIndex, this.column + 1));
}
this.column++;
}
}
this.skipWhitespace();
return sign * value;
}
private skipWhitespace(): void {
while (this.column < this.line.length && isWhitespace(this.line[this.column])) {
this.column++;
}
}
private readIdentifier(allowRegister: boolean, toLowerCase: boolean): string | undefined {
const startIndex = this.column;
// Skip through the identifier.
while (this.column < this.line.length && isLegalIdentifierCharacter(this.line[this.column], this.column == startIndex)) {
this.column++;
}
if (this.column > startIndex) {
let identifier = this.line.substring(startIndex, this.column);
if (toLowerCase) {
identifier = identifier.toLowerCase();
}
// Special case to parse AF'.
if (allowRegister && identifier.toLowerCase() === "af" && this.foundChar("'")) {
identifier += "'";
}
if (!allowRegister && (isWordReg(identifier) || isByteReg(identifier) || isFlag(identifier))) {
// Register names can't be identifiers.
this.column = startIndex;
return undefined;
}
this.skipWhitespace();
this.previousToken = startIndex;
return identifier;
} else {
return undefined;
}
}
/**
* If the next character matches the parameter, skips it and subsequent whitespace and return true.
* Else returns false.
*/
private foundChar(ch: string): boolean {
if (this.isChar(ch)) {
this.column++;
this.skipWhitespace();
return true;
} else {
return false;
}
}
/**
* If any of the specified characters is next, it is skipped (and subsequent whitespace) and returned.
* Else undefined is returned.
*/
private foundOneOfChar(chars: string[]): string | undefined {
for (const ch of chars) {
if (this.foundChar(ch)) {
return ch;
}
}
return undefined;
}
// Whether the next character matches the parameter. Does not advance.
private isChar(ch: string): boolean {
return this.column < this.line.length && this.line[this.column] === ch;
}
} | the_stack |
import { discardPeriodicTasks, fakeAsync, flushMicrotasks, TestBed, tick, waitForAsync } from '@angular/core/testing';
import { AudioPlayerService } from './audio-player.service';
import { AssetsBackendApiService } from './assets-backend-api.service';
import { ContextService } from './context.service';
import { EventEmitter, NO_ERRORS_SCHEMA } from '@angular/core';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import * as howler from 'howler';
import { AudioTranslationManagerService } from 'pages/exploration-player-page/services/audio-translation-manager.service';
import { Subject } from 'rxjs';
import { Howl } from 'howler';
describe('AudioPlayerService', () => {
let audioPlayerService: AudioPlayerService;
let contextService: ContextService;
let assetsBackendApiService: AssetsBackendApiService;
let audioTranslationManagerService: AudioTranslationManagerService;
let successHandler: jasmine.Spy;
let failHandler: jasmine.Spy;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
AudioPlayerService,
ContextService,
AssetsBackendApiService,
],
schemas: [NO_ERRORS_SCHEMA]
});
}));
beforeEach(() => {
audioTranslationManagerService =
TestBed.inject(AudioTranslationManagerService);
audioPlayerService = TestBed.inject(AudioPlayerService);
contextService = TestBed.inject(ContextService);
assetsBackendApiService = TestBed.inject(AssetsBackendApiService);
spyOn(contextService, 'getExplorationId').and.returnValue('1');
successHandler = jasmine.createSpy('success');
failHandler = jasmine.createSpy('fail');
});
describe('when audio loads successfully', () => {
beforeEach(() => {
spyOn(howler, 'Howl').and.returnValue({
on: (evt: string, func: () => void) => {
if (evt === 'load') {
func();
}
},
stop: () => {
console.error('Howl.stop');
},
pause: () => {
console.error('Howl.pause');
},
playing: () => {
return false;
},
play: () => {
console.error('Howl.play');
return 2;
},
seek: (num?: number) => {
if (typeof num !== 'undefined') {
console.error('Howl.seek ', num);
return num;
}
return 10;
},
duration: () => {
return 30;
}
} as unknown as Howl);
spyOn(assetsBackendApiService, 'loadAudio').and.returnValue(
Promise.resolve({
data: new Blob(),
filename: 'test.mp3'
}));
});
it('should load track when user plays audio', fakeAsync(async() => {
audioPlayerService.loadAsync('test.mp3').then(
successHandler, failHandler);
flushMicrotasks();
expect(successHandler).toHaveBeenCalled();
expect(failHandler).not.toHaveBeenCalled();
}));
it('should not load track when a track has already been loaded',
fakeAsync(() => {
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
expect(assetsBackendApiService.loadAudio).toHaveBeenCalledTimes(1);
}));
it('should play audio when user clicks the play button', fakeAsync(() => {
spyOn(console, 'error');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.play();
tick(501);
discardPeriodicTasks();
// The play function of the Howl calss is called when the user clicks
// the play button. Since the Howl class is mocked, a cosole.error stmt
// is placed inside the play function and is tested if the console.error
// stmt inside it triggered.
expect(console.error).toHaveBeenCalledWith('Howl.play');
}));
it('should not play audio again when audio is already being played',
fakeAsync(() => {
spyOn(console, 'error');
spyOn(audioPlayerService, 'isPlaying').and.returnValue(true);
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.play();
discardPeriodicTasks();
// The play function of the Howl calss is called when the user clicks
// the play button. Since the Howl class is mocked, a cosole.error stmt
// is placed inside the play function and is tested if the console.error
// stmt inside it triggered.
expect(console.error).not.toHaveBeenCalledWith('Howl.play');
}));
it('should not pause track when audio is not being played',
fakeAsync(() => {
spyOn(audioPlayerService, 'isPlaying').and.returnValue(false);
spyOn(audioPlayerService, 'getCurrentTime');
let subjectNext = spyOn(Subject.prototype, 'next');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.pause();
expect(audioPlayerService.getCurrentTime).not.toHaveBeenCalled();
expect(subjectNext).toHaveBeenCalledTimes(1);
}));
it('should pause track when user clicks the \'Pause\' ' +
'button', fakeAsync(() => {
spyOn(audioPlayerService, 'isPlaying').and.returnValue(true);
let subjectNext = spyOn(Subject.prototype, 'next');
spyOn(audioPlayerService, 'getCurrentTime');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.pause();
expect(audioPlayerService.getCurrentTime).toHaveBeenCalled();
expect(subjectNext).toHaveBeenCalled();
}));
it('should stop playing track and reset the time when called',
fakeAsync(() => {
spyOn(audioPlayerService, 'setCurrentTime');
spyOn(console, 'error');
let subjectNext = spyOn(Subject.prototype, 'next');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.stop();
expect(console.error).toHaveBeenCalledWith('Howl.stop');
expect(audioPlayerService.setCurrentTime).toHaveBeenCalledWith(0);
expect(subjectNext).toHaveBeenCalledTimes(2);
}));
it('should rewind the track when user clicks the \'Rewind\' ' +
'button', fakeAsync(() => {
spyOn(console, 'error');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.rewind(5);
expect(console.error).toHaveBeenCalledWith('Howl.seek ', 5);
}));
it('should forward the track when user clicks the \'forward\'' +
' button', fakeAsync(() => {
spyOn(console, 'error');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.forward(5);
expect(console.error).toHaveBeenCalledWith('Howl.seek ', 15);
}));
it('should get the current time of the track when it is being played',
fakeAsync(() => {
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
expect(audioPlayerService.getCurrentTime()).toBe(10);
}));
it('should set the time when user clicks on the track', fakeAsync(() => {
spyOn(console, 'error');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.setCurrentTime(15);
expect(console.error).toHaveBeenCalledWith('Howl.seek ', 15);
}));
it('should set the time as track duration when user clicks on end ' +
'of the track', fakeAsync(() => {
spyOn(console, 'error');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.setCurrentTime(31);
expect(console.error).toHaveBeenCalledWith('Howl.seek ', 30);
}));
it('should set the time as 0 when user clicks on beginning ' +
'of the track', fakeAsync(() => {
spyOn(console, 'error');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.setCurrentTime(-1);
expect(console.error).toHaveBeenCalledWith('Howl.seek ', 0);
}));
it('should return duration of the track when called', fakeAsync(() => {
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
expect(audioPlayerService.getAudioDuration()).toBe(30);
}));
it('should return false when audio is not being played', fakeAsync(() => {
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
expect(audioPlayerService.isPlaying()).toBe(false);
}));
it('should return whether track is loaded', fakeAsync(() => {
expect(audioPlayerService.isTrackLoaded()).toBe(false);
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
expect(audioPlayerService.isTrackLoaded()).toBe(true);
audioPlayerService.clear();
expect(audioPlayerService.isTrackLoaded()).toBe(false);
}));
it('should clear track when called', fakeAsync(() => {
spyOn(audioPlayerService, 'isPlaying').and.callThrough();
spyOn(audioPlayerService, 'stop');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
expect(audioPlayerService.isTrackLoaded()).toBe(true);
audioPlayerService.clear();
expect(audioPlayerService.stop).not.toHaveBeenCalled();
expect(audioPlayerService.isTrackLoaded()).toBe(false);
}));
it('should stop and clear track when called', fakeAsync(() => {
spyOn(audioPlayerService, 'isPlaying').and.returnValue(true);
spyOn(audioPlayerService, 'stop');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
expect(audioPlayerService.isTrackLoaded()).toBe(true);
audioPlayerService.clear();
expect(audioPlayerService.stop).toHaveBeenCalled();
expect(audioPlayerService.isTrackLoaded()).toBe(false);
}));
});
describe('when track is not loaded', () => {
beforeEach(() => {
spyOn(howler, 'Howl').and.returnValue({
on: (evt: string, func: () => void) => {
if (evt === 'load') {
func();
}
},
seek: (num: number) => {
if (typeof num !== 'undefined') {
console.error('Howl.seek ', num);
return num;
}
console.error('Howl.seek');
return {};
},
stop: () => {
console.error('Howl.stop');
},
playing: () => {
return true;
}
} as unknown as Howl);
spyOn(assetsBackendApiService, 'loadAudio').and.returnValue(
Promise.resolve({
data: new Blob(),
filename: 'test.mp3'
}));
spyOn(console, 'error');
});
it('should not call Howl.stop when no audio is loaded', fakeAsync(() => {
spyOn(audioPlayerService, 'setCurrentTime');
let subjectNext = spyOn(Subject.prototype, 'next');
audioPlayerService.stop();
expect(console.error).not.toHaveBeenCalledWith('Howl.stop');
expect(audioPlayerService.setCurrentTime).not.toHaveBeenCalledWith(0);
expect(subjectNext).not.toHaveBeenCalledTimes(2);
}));
it('should not rewind track when no audio is loaded', fakeAsync(() => {
audioPlayerService.rewind(5);
expect(console.error).not.toHaveBeenCalled();
}));
it('should not rewind track when seek does not return an number',
fakeAsync(() => {
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.rewind(5);
expect(console.error).toHaveBeenCalledTimes(1);
expect(console.error).toHaveBeenCalledWith('Howl.seek');
}));
it('should not forward track when no audio is loaded', fakeAsync(() => {
audioPlayerService.forward(5);
expect(console.error).not.toHaveBeenCalled();
}));
it('should not foward track when seek does not return an number',
fakeAsync(() => {
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
audioPlayerService.forward(5);
expect(console.error).toHaveBeenCalledTimes(1);
expect(console.error).toHaveBeenCalledWith('Howl.seek');
}));
it('should not get the current time of track when no audio is' +
' loaded', () => {
expect(audioPlayerService.getCurrentTime()).toBe(0);
});
it('should not get the current time of track when seek does not ' +
'return an number', fakeAsync(() => {
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
expect(audioPlayerService.getCurrentTime()).toBe(0);
}));
it('should not forward track when no audio is loaded', fakeAsync(() => {
audioPlayerService.forward(5);
expect(console.error).not.toHaveBeenCalled();
}));
it('should not set time of the track when audio is not loaded', () => {
audioPlayerService.setCurrentTime(5);
expect(console.error).not.toHaveBeenCalled();
});
it('should return 0 duration when no audio is loaded', fakeAsync(() => {
expect(audioPlayerService.getAudioDuration()).toBe(0);
}));
it('should return whether audio is playing', fakeAsync(() => {
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
expect(audioPlayerService.isPlaying()).toBe(true);
}));
});
it('should clear secondary audio translations when audio ' +
'ends', fakeAsync(async() => {
spyOn(howler, 'Howl').and.returnValue({
on: (evt: string, func: () => void) => {
if (evt === 'end') {
func();
}
}
} as unknown as Howl);
spyOn(assetsBackendApiService, 'loadAudio').and.returnValue(
Promise.resolve({
data: new Blob(),
filename: 'test'
}));
spyOn(audioTranslationManagerService, 'clearSecondaryAudioTranslations');
audioPlayerService.loadAsync('test.mp3');
flushMicrotasks();
expect(audioTranslationManagerService.clearSecondaryAudioTranslations)
.toHaveBeenCalled();
}));
it('should display error when audio fails to load', fakeAsync(() => {
spyOn(assetsBackendApiService, 'loadAudio').and.returnValue(
Promise.reject('Error'));
spyOn(audioTranslationManagerService, 'clearSecondaryAudioTranslations');
audioPlayerService.loadAsync('test.mp3').then(
successHandler, failHandler);
flushMicrotasks();
expect(successHandler).not.toHaveBeenCalled();
expect(failHandler).toHaveBeenCalledWith('Error');
}));
it('should fetch event emitter for update in view', () => {
let mockEventEmitter = new EventEmitter();
expect(audioPlayerService.viewUpdate).toEqual(
mockEventEmitter);
});
it('should fetch event emitter for auto play audio', () => {
let mockEventEmitter = new EventEmitter();
expect(audioPlayerService.onAutoplayAudio).toEqual(
mockEventEmitter);
});
it('should return subject when audio stops playing', () => {
let mockSubject = new Subject<void>();
expect(audioPlayerService.onAudioStop).toEqual(
mockSubject);
});
}); | the_stack |
import { makeExecutableSchema } from '@graphql-tools/schema';
import { IResolverValidationOptions } from '@graphql-tools/utils';
import {
graphql,
ExecutionResult,
GraphQLDirective,
GraphQLError,
GraphQLResolveInfo,
GraphQLSchema,
} from 'graphql';
import { IRateLimiterOptions, RateLimiterMemory, RateLimiterRes } from 'rate-limiter-flexible';
import { rateLimitDirective, RateLimitArgs } from '../index';
const getDirective = (schema: GraphQLSchema, name = 'rateLimit'): GraphQLDirective => {
const directive = schema.getDirectives().find((directive) => directive.name == name);
expect(directive).toBeDefined();
// See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/41179
return directive!; // eslint-disable-line @typescript-eslint/no-non-null-assertion
};
const getError = (response: ExecutionResult): GraphQLError => {
const error = (response.errors || [])[0];
expect(error).toBeDefined();
return error;
};
describe('rateLimitDirective', () => {
it('creates custom named directive', () => {
const name = 'customRateLimit';
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective({
name,
});
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [rateLimitDirectiveTypeDefs, ``],
}),
);
expect(getDirective(schema, name)).toEqual(expect.objectContaining({ name }));
});
it('overrides limit argument default value', () => {
const defaultLimit = '30';
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective({
defaultLimit,
});
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [rateLimitDirectiveTypeDefs, ``],
}),
);
expect(getDirective(schema).args).toEqual(
expect.arrayContaining([expect.objectContaining({ name: 'limit', defaultValue: 30 })]),
);
});
it('overrides duration argument default value', () => {
const defaultDuration = '30';
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective({
defaultDuration,
});
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [rateLimitDirectiveTypeDefs, ``],
}),
);
expect(getDirective(schema).args).toEqual(
expect.arrayContaining([expect.objectContaining({ name: 'duration', defaultValue: 30 })]),
);
});
it('uses custom limiter class with keyPrefix option', async () => {
let ranConstructor = false;
const keyPrefix = 'custom';
class CustomRateLimiter extends RateLimiterMemory {
constructor(opts: IRateLimiterOptions) {
super(opts);
ranConstructor = true;
expect(opts.keyPrefix).toEqual(keyPrefix);
}
}
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective({
limiterClass: CustomRateLimiter,
limiterOptions: { keyPrefix },
});
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`type Query {
quote: String @rateLimit
}`,
],
}),
);
await graphql(schema, 'query { quote }');
expect(ranConstructor).toEqual(true);
});
describe('limiting', () => {
const resolvers = {
Query: {
books: () => [
{
title: 'A Game of Thrones',
author: 'George R. R. Martin',
},
{
title: 'The Hobbit',
author: 'J. R. R. Tolkien',
},
],
quote: () =>
'The future is something which everyone reaches at the rate of sixty minutes an hour, whatever he does, whoever he is. ― C.S. Lewis',
},
};
const resolverValidationOptions: IResolverValidationOptions = {
requireResolversToMatchSchema: 'ignore',
};
let limiterConsume;
beforeEach(() => {
limiterConsume = jest.spyOn(RateLimiterMemory.prototype, 'consume');
});
afterEach(() => {
limiterConsume.mockRestore();
});
it('a specific field', async () => {
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective();
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`type Query {
quote: String @rateLimit
}`,
],
resolvers,
resolverValidationOptions,
}),
);
const response = await graphql(schema, 'query { quote }');
expect(limiterConsume).toHaveBeenCalledTimes(1);
expect(limiterConsume).toHaveBeenCalledWith('Query.quote', 1);
expect(response).toMatchSnapshot();
});
it('a repeated object', async () => {
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective();
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`type Query {
books: [Book!]
}
type Book {
title: String @rateLimit
}`,
],
resolvers,
resolverValidationOptions,
}),
);
const response = await graphql(schema, 'query { books { title } }');
expect(limiterConsume).toHaveBeenCalledTimes(2);
expect(limiterConsume).toHaveBeenNthCalledWith(1, 'Book.title', 1);
expect(limiterConsume).toHaveBeenNthCalledWith(2, 'Book.title', 1);
expect(response).toMatchSnapshot();
});
it('each field of an object', async () => {
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective();
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`type Query @rateLimit {
books: [Book!]
quote: String
}
type Book {
title: String
}`,
],
resolvers,
resolverValidationOptions,
}),
);
const response = await graphql(schema, 'query { quote books { title } }');
expect(limiterConsume).toHaveBeenCalledTimes(2);
expect(limiterConsume).toHaveBeenCalledWith('Query.quote', 1);
expect(limiterConsume).toHaveBeenCalledWith('Query.books', 1);
expect(response).toMatchSnapshot();
});
it('overrides field of an object', async () => {
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective();
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`type Query {
books: [Book!]
}
type Book @rateLimit {
title: String
author: String @rateLimit(limit: 1)
}`,
],
resolvers,
resolverValidationOptions,
}),
);
const response = await graphql(schema, 'query { books { title author } }');
expect(limiterConsume).toHaveBeenCalledTimes(4);
expect(limiterConsume).toHaveBeenCalledWith('Book.title', 1);
expect(limiterConsume).toHaveBeenCalledWith('Book.author', 1);
const error = getError(response);
expect(error.message).toMatch(/Too many requests, please try again in \d+ seconds\./);
expect(error.path).toEqual(['books', expect.any(Number), 'author']);
});
it('reraises limiter error', async () => {
const message = 'Some error happened';
limiterConsume.mockImplementation(() => {
throw new Error(message);
});
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective();
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`type Query {
quote: String @rateLimit
}`,
],
resolvers,
resolverValidationOptions,
}),
);
const response = await graphql(schema, 'query { quote }');
expect(limiterConsume).toHaveBeenCalledTimes(1);
expect(limiterConsume).toHaveBeenCalledWith('Query.quote', 1);
const error = getError(response);
expect(error.message).toEqual(message);
expect(error.path).toEqual(['quote']);
});
it('uses custom async keyGenerator', async () => {
interface IContext {
ip: string;
}
const context: IContext = {
ip: '127.0 0.1',
};
const keyGenerator = jest.fn(
(
/* eslint-disable @typescript-eslint/no-unused-vars */
directiveArgs: RateLimitArgs,
obj: unknown,
args: { [key: string]: unknown },
context: IContext,
info: GraphQLResolveInfo,
/* eslint-enable @typescript-eslint/no-unused-vars */
) => {
// This could be sync, but that case is widely tested already so force this to return a Promise
return Promise.resolve(`${context.ip}:${info.parentType}.${info.fieldName}`);
},
);
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective({
keyGenerator,
});
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`type Query {
quote: String @rateLimit(limit: 10, duration: 300)
}`,
],
resolvers,
resolverValidationOptions,
}),
);
const response = await graphql(schema, 'query { quote }', undefined, context);
expect(keyGenerator).toHaveBeenCalledWith(
{ limit: 10, duration: 300 },
undefined,
{},
context,
expect.any(Object),
);
expect(limiterConsume).toHaveBeenCalledTimes(1);
expect(limiterConsume).toHaveBeenCalledWith('127.0 0.1:Query.quote', 1);
expect(response).toMatchSnapshot();
});
it('uses custom pointsCalculator', async () => {
const pointsCalculator = jest.fn(
(
/* eslint-disable @typescript-eslint/no-unused-vars */
directiveArgs: RateLimitArgs,
obj: unknown,
args: { [key: string]: unknown },
context: Record<string, unknown>,
info: GraphQLResolveInfo,
/* eslint-enable @typescript-eslint/no-unused-vars */
) => 2,
);
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective({
pointsCalculator,
});
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`type Query {
quote: String @rateLimit(limit: 10, duration: 300)
}`,
],
resolvers,
resolverValidationOptions,
}),
);
const response = await graphql(schema, 'query { quote }');
expect(pointsCalculator).toHaveBeenCalledWith(
{ limit: 10, duration: 300 },
undefined,
{},
undefined,
expect.any(Object),
);
expect(limiterConsume).toHaveBeenCalledTimes(1);
expect(limiterConsume).toHaveBeenCalledWith('Query.quote', 2);
expect(response).toMatchSnapshot();
});
it('skips consume on zero cost', async () => {
const pointsCalculator = jest.fn(
(
/* eslint-disable @typescript-eslint/no-unused-vars */
directiveArgs: RateLimitArgs,
obj: unknown,
args: { [key: string]: unknown },
context: Record<string, unknown>,
info: GraphQLResolveInfo,
/* eslint-enable @typescript-eslint/no-unused-vars */
) => 0,
);
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective({
pointsCalculator,
});
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`type Query {
quote: String @rateLimit
}`,
],
resolvers,
resolverValidationOptions,
}),
);
await graphql(schema, 'query { quote }');
expect(pointsCalculator).toHaveBeenCalled();
expect(limiterConsume).not.toHaveBeenCalled();
});
it('uses default onLimit', async () => {
limiterConsume
.mockResolvedValueOnce(<RateLimiterRes>{
msBeforeNext: 250,
remainingPoints: 0,
consumedPoints: 1,
isFirstInDuration: true,
})
.mockRejectedValue(<RateLimiterRes>{
msBeforeNext: 250,
remainingPoints: 0,
consumedPoints: 1,
isFirstInDuration: false,
});
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective();
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`type Query {
quote: String @rateLimit(limit: 1)
}`,
],
resolvers,
resolverValidationOptions,
}),
);
const response = await graphql(schema, 'query { firstQuote: quote secondQuote: quote }');
expect(limiterConsume).toHaveBeenCalledTimes(2);
expect(limiterConsume).toHaveBeenCalledWith('Query.quote', 1);
const error = getError(response);
expect(error.message).toMatch(/Too many requests, please try again in \d+ seconds\./);
expect(error.path).toEqual([expect.any(String)]);
});
it('uses custom onLimit', async () => {
const consumeResponse = <RateLimiterRes>{
msBeforeNext: 1250,
remainingPoints: 0,
consumedPoints: 10,
isFirstInDuration: false,
};
limiterConsume.mockRejectedValue(consumeResponse);
const onLimit = jest.fn(
(
/* eslint-disable @typescript-eslint/no-unused-vars */
resource: RateLimiterRes,
directiveArgs: RateLimitArgs,
obj: unknown,
args: { [key: string]: unknown },
context: Record<string, unknown>,
info: GraphQLResolveInfo,
/* eslint-enable @typescript-eslint/no-unused-vars */
) => 'So comes snow after fire, and even dragons have their endings. ― Bilbo Baggins',
);
const { rateLimitDirectiveTypeDefs, rateLimitDirectiveTransformer } = rateLimitDirective({
onLimit,
});
const schema = rateLimitDirectiveTransformer(
makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`type Query {
quote: String @rateLimit(limit: 10, duration: 300)
}`,
],
resolvers,
resolverValidationOptions,
}),
);
const response = await graphql(schema, 'query { quote }');
expect(limiterConsume).toHaveBeenCalledTimes(1);
expect(limiterConsume).toHaveBeenCalledWith('Query.quote', 1);
expect(onLimit).toHaveBeenCalledWith(
consumeResponse,
{ limit: 10, duration: 300 },
undefined,
{},
undefined,
expect.any(Object),
);
expect(response).toMatchSnapshot();
});
});
}); | the_stack |
import React, {
useState,
useRef,
useEffect,
useMemo,
useLayoutEffect,
} from "react";
import { EnvManagerComponent } from "@ui_types";
import { Client, Model } from "@core/types";
import * as g from "@core/lib/graph";
import { style } from "typestyle";
import * as ui from "@ui";
import { getValDisplay } from "@ui_lib/envs";
import {
getCurrentUserEntryKeysSet,
getInheritingEnvironmentIds,
getRawEnvWithAncestors,
} from "@core/lib/client";
type Props = {
undefinedPlaceholder?: React.ReactNode;
} & (
| {
type: "entry";
environmentId?: undefined;
}
| {
type: "entryVal";
canUpdate?: boolean;
environmentId: string;
}
);
const entryPlaceholder = "VARIABLE_NAME";
const cursorPositionByCellId: Record<
string,
{ selectionStart: number; selectionEnd: number }
> = {};
export const EntryFormCell: EnvManagerComponent<{}, Props> = (props) => {
const { graph, graphUpdatedAt } = props.core;
const currentUserId = props.ui.loadedAccountId!;
const org = g.getOrg(graph);
const envParent = graph[props.envParentId] as Model.EnvParent;
const cellId = props.type == "entry" ? "entry" : props.environmentId;
const autoCaps = useMemo(() => {
if (props.type != "entry") {
return false;
}
return envParent.settings.autoCaps ?? org.settings.envs.autoCaps;
}, [graphUpdatedAt, currentUserId, props.type, props.envParentId]);
const subEnvEntryAutocompleteOptions = useMemo(() => {
if (props.type == "entry" && props.isSub && props.parentEnvironmentId) {
const currentKeysSet = getCurrentUserEntryKeysSet(
props.core,
currentUserId,
props.allEnvironmentIds,
true
);
return Object.keys(
getRawEnvWithAncestors(
props.core,
{
envParentId: props.envParentId,
environmentId: props.parentEnvironmentId,
},
true
)
)
.filter((k) => !currentKeysSet.has(k))
.sort()
.map((entryKey) => ({
label: entryKey,
update: { entryKey },
searchText: entryKey,
}));
} else {
return [];
}
}, [
graphUpdatedAt,
props.core.pendingEnvUpdates.length,
props.type,
props.envParentId,
props.isSub && props.parentEnvironmentId,
]);
let val: string | undefined,
inheritsEnvironmentId: string | undefined,
isEmpty: boolean | undefined,
isUndefined: boolean | undefined;
const entryFormState = props.ui.envManager.entryForm;
if (props.type == "entry") {
val = entryFormState.entryKey;
} else if (props.type == "entryVal") {
const cell: Client.Env.EnvWithMetaCell | undefined =
entryFormState.vals[props.environmentId];
if (cell) {
({ val, inheritsEnvironmentId, isEmpty, isUndefined } = cell);
} else {
isUndefined = true;
}
}
const isEditing =
(props.type == "entry" && entryFormState.editingEntryKey) ||
(props.type == "entryVal" &&
props.environmentId == entryFormState.editingEnvironmentId);
const canUpdate =
props.type == "entry" || (props.environmentId && props.canUpdate);
const showInput = canUpdate && isEditing;
const showAutocomplete =
showInput &&
((props.type == "entryVal" && !val) ||
(props.type == "entry" && props.isSub));
const currentUpdate = {
val,
inheritsEnvironmentId,
isEmpty,
isUndefined,
} as Client.Env.EnvWithMetaCell;
const clickedToEdit = entryFormState.clickedToEdit;
const inputRef = useRef<HTMLTextAreaElement>(null);
const isMulti =
props.type == "entryVal" && props.editingMultiline && showInput;
const [lastCommitted, setLastCommitted] = useState<
string | Client.Env.EnvWithMetaCell
>();
useLayoutEffect(() => {
if (showInput && inputRef.current) {
inputRef.current.focus();
// ensure smooth toggling between single and multi-line mode while editing
if (clickedToEdit) {
inputRef.current.scrollTop = 0;
props.setEnvManagerState({ clickedToEdit: undefined });
if (!props.editingMultiline) {
inputRef.current.select();
}
}
}
}, [props.envParentId, showInput]);
// maintain cursor position while moving between
// single and multi-line mode
useLayoutEffect(() => {
if (showInput && inputRef.current && cursorPositionByCellId[cellId]) {
const { selectionStart, selectionEnd } = cursorPositionByCellId[cellId];
inputRef.current.setSelectionRange(selectionStart, selectionEnd);
}
});
useLayoutEffect(() => {
if (
props.type == "entry" &&
props.ui.envManager.submittedEntryKey &&
showInput &&
inputRef.current
) {
inputRef.current.focus();
}
}, [props.ui.envManager.submittedEntryKey]);
const cancel = () => {
if (props.type == "entry") {
props.setEntryFormState({
editingEntryKey: undefined,
editingEnvironmentId: undefined,
entryKey: lastCommitted as string,
});
} else if (props.type == "entryVal") {
props.setEntryFormState({
editingEntryKey: undefined,
editingEnvironmentId: undefined,
vals: {
...(entryFormState.vals ?? {}),
[props.environmentId]: lastCommitted as Client.Env.EnvWithMetaCell,
},
});
}
delete cursorPositionByCellId[cellId];
};
const commit = () => {
if (props.type == "entry") {
setLastCommitted(val ?? "");
} else if (props.type == "entryVal") {
setLastCommitted(currentUpdate);
}
delete cursorPositionByCellId[cellId];
};
const clearEditing = () => {
props.setEntryFormState({
editingEntryKey: undefined,
editingEnvironmentId: undefined,
});
};
const setEntry = (inputVal: string) => {
props.setEntryFormState({ entryKey: inputVal });
};
const submitEntry = (inputVal: string) => {
props.setEntryFormState({
...entryFormState,
entryKey: inputVal,
editingEntryKey: undefined,
editingEnvironmentId: undefined,
});
delete cursorPositionByCellId[cellId];
setLastCommitted(inputVal);
};
const setEntryVal = (update: Client.Env.EnvWithMetaCell) => {
if (!props.environmentId) {
return;
}
props.setEntryFormState({
vals: { ...entryFormState.vals, [props.environmentId]: update },
});
};
const submitEntryVal = (update: Client.Env.EnvWithMetaCell) => {
if (!props.environmentId) {
return;
}
props.setEntryFormState({
vals: { ...entryFormState.vals, [props.environmentId]: update },
editingEntryKey: undefined,
editingEnvironmentId: undefined,
});
delete cursorPositionByCellId[cellId];
setLastCommitted(update);
};
let cellContents: React.ReactNode[] = [];
let classNames: string[] = ["cell"];
classNames.push(
props.type == "entry" || (props.type == "entryVal" && props.canUpdate)
? "writable"
: "not-writable"
);
if (showInput) {
classNames.push("editing");
const inputProps = {
ref: inputRef as any,
spellCheck: false,
placeholder:
props.type == "entry"
? entryPlaceholder
: "Insert value or choose below.",
value: val || "",
onChange: (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => {
let inputVal = e.currentTarget.value;
if (autoCaps) {
inputVal = inputVal.toUpperCase();
}
if (inputVal != val) {
if (props.type == "entry") {
setEntry(inputVal);
} else if (props.type == "entryVal") {
setEntryVal({
val: inputVal,
isUndefined: typeof inputVal == "undefined" ? true : undefined,
isEmpty: inputVal === "" ? true : undefined,
} as Client.Env.EnvWithMetaCell);
}
}
if (inputRef.current) {
const { selectionStart, selectionEnd } = inputRef.current;
cursorPositionByCellId[cellId] = { selectionStart, selectionEnd };
}
},
onClick: (e: React.MouseEvent) => {
if (isEditing) {
e.stopPropagation();
}
},
onKeyDown: (e: React.KeyboardEvent) => {
if (e.key == "Enter" && !showAutocomplete && !e.shiftKey) {
e.preventDefault();
e.stopPropagation();
commit();
clearEditing();
} else if (e.key == "Escape") {
cancel();
} else if (inputRef.current) {
const { selectionStart, selectionEnd } = inputRef.current;
cursorPositionByCellId[cellId] = {
selectionStart,
selectionEnd,
};
}
},
onBlur: () => {
if (!showAutocomplete) {
commit();
}
},
};
cellContents.push(<textarea {...inputProps} />);
if (showAutocomplete) {
classNames.push("autocomplete-open");
if (props.isSub && props.type == "entry") {
cellContents.push(
<ui.CellAutocomplete
{...props}
initialSelected={{ entryKey: val }}
onSelect={({ entryKey }) => submitEntry(entryKey!)}
options={subEnvEntryAutocompleteOptions}
filter={(searchText) =>
!val || searchText.toLowerCase().indexOf(val.toLowerCase()) > -1
}
/>
);
} else if (props.environmentId) {
cellContents.push(
<ui.EnvCellAutocomplete
{...props}
initialSelected={currentUpdate}
onSelect={(update) => {
submitEntryVal(update);
}}
pendingInheritingEnvironmentIds={
props.isSub
? new Set<string>()
: getInheritingEnvironmentIds(props.core, {
...props,
newEntryVals: props.ui.envManager.entryForm.vals,
})
}
/>
);
}
}
} else {
let display: React.ReactNode;
const valDisplay = getValDisplay(val ?? "");
if (props.type == "entry") {
display = val || (
<small>{props.undefinedPlaceholder || entryPlaceholder}</small>
);
} else if (inheritsEnvironmentId) {
classNames.push("special");
classNames.push("inherits");
display = (
<span>
<small>inherits</small>
<label>
{g.getEnvironmentName(props.core.graph, inheritsEnvironmentId)}
</label>
</span>
);
} else if (isUndefined) {
classNames.push("special");
classNames.push("undefined");
const environment = props.core.graph[props.environmentId] as
| Model.Environment
| undefined;
const envName = environment
? g
.getEnvironmentName(props.core.graph, props.environmentId)
.toLowerCase()
: "local";
display = <small>{`Set ${envName} value (optional)`}</small>;
} else if (isEmpty) {
classNames.push("special");
classNames.push("empty");
display = <small>empty string</small>;
} else {
display = <span>{valDisplay}</span>;
}
cellContents.push(<span>{display}</span>);
}
return (
<div
id={[props.environmentId, entryFormState.entryKey]
.filter(Boolean)
.join("|")}
className={
classNames.join(" ") +
" " +
style({
width:
props.type == "entry" ? props.entryColWidth : props.valColWidth,
height: isMulti
? props.gridHeight - props.labelRowHeight
: props.envRowHeight,
})
}
onClick={() => {
if (!isEditing) {
props.setEntryFormState({
editingEntryKey: props.type == "entry" ? true : undefined,
editingEnvironmentId:
props.type == "entryVal" ? props.environmentId : undefined,
clickedToEdit: true,
});
}
}}
>
{cellContents}
</div>
);
}; | the_stack |
import { ARobotBehaviour } from './interpreter.aRobotBehaviour';
import { State } from './interpreter.state';
import * as C from './interpreter.constants';
import * as U from './interpreter.util';
export class RobotWeDoBehaviour extends ARobotBehaviour {
/*
* represents the state of connected wedo devices with the following
* structure: {<name of the device> { 1 : { tiltsensor : "0.0" }, 2 : {
* motionsensor : "4.0 }, batterylevel : "100", button : "false" }
*/
private btInterfaceFct;
private toDisplayFct;
private timers;
private wedo = {};
private tiltMode = {
UP: '3.0',
DOWN: '9.0',
BACK: '5.0',
FRONT: '7.0',
NO: '0.0',
};
constructor(btInterfaceFct: any, toDisplayFct: any) {
super();
this.btInterfaceFct = btInterfaceFct;
this.toDisplayFct = toDisplayFct;
this.timers = {};
this.timers['start'] = Date.now();
U.loggingEnabled(true, true);
}
public update(data) {
U.info('update type:' + data.type + ' state:' + data.state + ' sensor:' + data.sensor + ' actor:' + data.actuator);
if (data.target !== 'wedo') {
return;
}
switch (data.type) {
case 'connect':
if (data.state == 'connected') {
this.wedo[data.brickid] = {};
this.wedo[data.brickid]['brickname'] = data.brickname.replace(/\s/g, '').toUpperCase();
// for some reason we do not get the inital state of the button, so here it is hardcoded
this.wedo[data.brickid]['button'] = 'false';
} else if (data.state == 'disconnected') {
delete this.wedo[data.brickid];
}
break;
case 'didAddService':
let theWedoA = this.wedo[data.brickid];
if (data.state == 'connected') {
if (data.id && data.sensor) {
theWedoA[data.id] = {};
theWedoA[data.id][this.finalName(data.sensor)] = '';
} else if (data.id && data.actuator) {
theWedoA[data.id] = {};
theWedoA[data.id][this.finalName(data.actuator)] = '';
} else if (data.sensor) {
theWedoA[this.finalName(data.sensor)] = '';
} else {
theWedoA[this.finalName(data.actuator)] = '';
}
}
break;
case 'didRemoveService':
if (data.id) {
delete this.wedo[data.brickid][data.id];
} else if (data.sensor) {
delete this.wedo[data.brickid][this.finalName(data.sensor)];
} else {
delete this.wedo[data.brickid][this.finalName(data.actuator)];
}
break;
case 'update':
let theWedoU = this.wedo[data.brickid];
if (data.id) {
if (theWedoU[data.id] === undefined) {
theWedoU[data.id] = {};
}
theWedoU[data.id][this.finalName(data.sensor)] = data.state;
} else {
theWedoU[this.finalName(data.sensor)] = data.state;
}
break;
default:
// TODO think about what could happen here.
break;
}
U.info(this.wedo);
}
public getConnectedBricks() {
var brickids = [];
for (var brickid in this.wedo) {
if (this.wedo.hasOwnProperty(brickid)) {
brickids.push(brickid);
}
}
return brickids;
}
public getBrickIdByName(name) {
for (var brickid in this.wedo) {
if (this.wedo.hasOwnProperty(brickid)) {
if (this.wedo[brickid].brickname === name.toUpperCase()) {
return brickid;
}
}
}
return null;
}
public getBrickById(id) {
return this.wedo[id];
}
public clearDisplay() {
U.debug('clear display');
this.toDisplayFct({ clear: true });
}
public getSample(s: State, name: string, sensor: string, port: number, slot: string) {
var robotText = 'robot: ' + name + ', port: ' + port;
U.info(robotText + ' getsample called for ' + sensor);
var sensorName;
switch (sensor) {
case 'infrared':
sensorName = 'motionsensor';
break;
case 'gyro':
sensorName = 'tiltsensor';
break;
case 'buttons':
sensorName = 'button';
break;
case C.TIMER:
s.push(this.timerGet(port));
return;
default:
throw 'invalid get sample for ' + name + ' - ' + port + ' - ' + sensor + ' - ' + slot;
}
let wedoId = this.getBrickIdByName(name);
s.push(this.getSensorValue(wedoId, port, sensorName, slot));
}
private getSensorValue(wedoId, port, sensor, slot) {
let theWedo = this.wedo[wedoId];
let thePort = theWedo[port];
if (thePort === undefined) {
thePort = theWedo['1'] !== undefined ? theWedo['1'] : theWedo['2'];
}
let theSensor = thePort === undefined ? 'undefined' : thePort[sensor];
U.info('sensor object ' + (theSensor === undefined ? 'undefined' : theSensor.toString()));
switch (sensor) {
case 'tiltsensor':
if (slot === 'ANY') {
return parseInt(theSensor) !== parseInt(this.tiltMode.NO);
} else {
return parseInt(theSensor) === parseInt(this.tiltMode[slot]);
}
case 'motionsensor':
return parseInt(theSensor);
case 'button':
return theWedo.button === 'true';
}
}
private finalName(notNormalized: string): string {
if (notNormalized !== undefined) {
return notNormalized.replace(/\s/g, '').toLowerCase();
} else {
U.info('sensor name undefined');
return 'undefined';
}
}
public timerReset(port: number) {
this.timers[port] = Date.now();
U.debug('timerReset for ' + port);
}
public timerGet(port: number) {
const now = Date.now();
var startTime = this.timers[port];
if (startTime === undefined) {
startTime = this.timers['start'];
}
const delta = now - startTime;
U.debug('timerGet for ' + port + ' returned ' + delta);
return delta;
}
public ledOnAction(name: string, port: number, color: number) {
var brickid = this.getBrickIdByName(name);
const robotText = 'robot: ' + name + ', port: ' + port;
U.debug(robotText + ' led on color ' + color);
const cmd = { target: 'wedo', type: 'command', actuator: 'light', brickid: brickid, color: color };
this.btInterfaceFct(cmd);
}
public statusLightOffAction(name: string, port: number) {
var brickid = this.getBrickIdByName(name);
const robotText = 'robot: ' + name + ', port: ' + port;
U.debug(robotText + ' led off');
const cmd = { target: 'wedo', type: 'command', actuator: 'light', brickid: brickid, color: 0 };
this.btInterfaceFct(cmd);
}
public toneAction(name: string, frequency: number, duration: number) {
var brickid = this.getBrickIdByName(name); // TODO: better style
const robotText = 'robot: ' + name;
U.debug(robotText + ' piezo: ' + ', frequency: ' + frequency + ', duration: ' + duration);
const cmd = { target: 'wedo', type: 'command', actuator: 'piezo', brickid: brickid, frequency: Math.floor(frequency), duration: Math.floor(duration) };
this.btInterfaceFct(cmd);
return duration;
}
public motorOnAction(name: string, port: any, duration: number, speed: number): number {
var brickid = this.getBrickIdByName(name); // TODO: better style
const robotText = 'robot: ' + name + ', port: ' + port;
const durText = duration === undefined ? ' w.o. duration' : ' for ' + duration + ' msec';
U.debug(robotText + ' motor speed ' + speed + durText);
const cmd = {
target: 'wedo',
type: 'command',
actuator: 'motor',
brickid: brickid,
action: 'on',
id: port,
direction: speed < 0 ? 1 : 0,
power: Math.abs(speed),
};
this.btInterfaceFct(cmd);
return 0;
}
public motorStopAction(name: string, port: number) {
var brickid = this.getBrickIdByName(name); // TODO: better style
const robotText = 'robot: ' + name + ', port: ' + port;
U.debug(robotText + ' motor stop');
const cmd = { target: 'wedo', type: 'command', actuator: 'motor', brickid: brickid, action: 'stop', id: port };
this.btInterfaceFct(cmd);
}
public showTextAction(text: any, _mode: string): number {
const showText = '' + text;
U.debug('***** show "' + showText + '" *****');
this.toDisplayFct({ show: showText });
return 0;
}
public showImageAction(_text: any, _mode: string): number {
U.debug('***** show image not supported by WeDo *****');
return 0;
}
public displaySetBrightnessAction(_value: number): number {
return 0;
}
public displaySetPixelAction(_x: number, _y: number, _brightness: number): number {
return 0;
}
public writePinAction(_pin: any, _mode: string, _value: number): void {}
public close() {
var ids = this.getConnectedBricks();
for (let id in ids) {
if (ids.hasOwnProperty(id)) {
var name = this.getBrickById(ids[id]).brickname;
this.motorStopAction(name, 1);
this.motorStopAction(name, 2);
this.ledOnAction(name, 99, 3);
}
}
}
public encoderReset(_port: string): void {
throw new Error('Method not implemented.');
}
public gyroReset(_port: number): void {
throw new Error('Method not implemented.');
}
public lightAction(_mode: string, _color: string, _port: string): void {
throw new Error('Method not implemented.');
}
public playFileAction(_file: string): number {
throw new Error('Method not implemented.');
}
public _setVolumeAction(_volume: number): void {
throw new Error('Method not implemented.');
}
public _getVolumeAction(_s: State): void {
throw new Error('Method not implemented.');
}
public setLanguage(_language: string): void {
throw new Error('Method not implemented.');
}
public sayTextAction(_text: string, _speed: number, _pitch: number): number {
throw new Error('Method not implemented.');
}
public getMotorSpeed(_s: State, _name: string, _port: any): void {
throw new Error('Method not implemented.');
}
public setMotorSpeed(_name: string, _port: any, _speed: number): void {
throw new Error('Method not implemented.');
}
public driveStop(_name: string): void {
throw new Error('Method not implemented.');
}
public driveAction(_name: string, _direction: string, _speed: number, _distance: number): number {
throw new Error('Method not implemented.');
}
public curveAction(_name: string, _direction: string, _speedL: number, _speedR: number, _distance: number): number {
throw new Error('Method not implemented.');
}
public turnAction(_name: string, _direction: string, _speed: number, _angle: number): number {
throw new Error('Method not implemented.');
}
public showTextActionPosition(_text: any, _x: number, _y: number): void {
throw new Error('Method not implemented.');
}
public displaySetPixelBrightnessAction(_x: number, _y: number, _brightness: number): number {
throw new Error('Method not implemented.');
}
public displayGetPixelBrightnessAction(_s: State, _x: number, _y: number): void {
throw new Error('Method not implemented.');
}
public setVolumeAction(_volume: number): void {
throw new Error('Method not implemented.');
}
public getVolumeAction(_s: State): void {
throw new Error('Method not implemented.');
}
public debugAction(_value: any): void {
this.showTextAction('> ' + _value, undefined);
}
public assertAction(_msg: string, _left: any, _op: string, _right: any, _value: any): void {
if (!_value) {
this.showTextAction('> Assertion failed: ' + _msg + ' ' + _left + ' ' + _op + ' ' + _right, undefined);
}
}
} | the_stack |
'use strict';
/**
* TODO: Update functions to remove interaction with the VSCode editor, to allow for unit testing of functionality.
* TODO: Add function comments
* TODO: Use common support functions instead of repetitious calls to VSCode directly.
*/
import * as vscode from 'vscode';
import { ListType } from '../constants/list-type';
import * as common from './common';
import { LineObjectModel } from './line-object-model';
import { ListObjectModel } from './list-object-model';
export const numberedListRegex = /^( )*[0-9]+\.( )/;
export const alphabetListRegex = /^( )*[a-z]{1}\.( )/;
export const bulletedListRegex = /^( )*\-( )/;
export const numberedListWithIndentRegexTemplate = '^( ){{0}}[0-9]+\\.( )';
export const alphabetListWithIndentRegexTemplate = '^( ){{0}}[a-z]{1}\\.( )';
export const fixedBulletedListRegex = /^( )*\-( )$/;
export const fixedNumberedListWithIndentRegexTemplate = '^( ){{0}}[0-9]+\\.( )$';
export const fixedAlphabetListWithIndentRegexTemplate = '^( ){{0}}[a-z]{1}\\.( )$';
export const startAlphabet = 'a';
export const numberedListValue = '1';
export const tabPattern = ' ';
/**
* Creates a list(numbered or bulleted) in the vscode editor.
*/
export function insertList(editor: vscode.TextEditor, listType: ListType) {
const cursorPosition = editor.selection.active;
const lineText = editor.document.lineAt(cursorPosition.line).text;
const listObjectModel = createListObjectModel(editor);
let previousOuterNumbered =
listObjectModel.previousOuter != null && listType === ListType.Numbered
? listObjectModel.previousOuter.listNumber
: 0;
let previousNestedNumbered = startAlphabet.charCodeAt(0) - 1;
const endInnerListedLine =
listObjectModel.nextNested != null ? listObjectModel.nextNested.line : cursorPosition.line;
const indentCount = CountIndent(lineText);
let newNumberedLines = [];
if (indentCount > 0 && indentCount !== 4) {
newNumberedLines.push(
listType === ListType.Numbered
? ' '.repeat(indentCount) + '1. '
: ' '.repeat(indentCount) + '- '
);
insertEmptyList(editor, newNumberedLines.join('\n'));
common.setCursorPosition(editor, cursorPosition.line, newNumberedLines[0].length);
} else {
if (indentCount === 0) {
const newlineText = listType === ListType.Numbered ? ++previousOuterNumbered + '. ' : '- ';
newNumberedLines.push(newlineText);
} else {
const newlineText =
listType === ListType.Numbered
? tabPattern + String.fromCharCode(++previousNestedNumbered) + '. '
: tabPattern + '- ';
newNumberedLines.push(newlineText);
}
const updatedInnerListed = updateOrderedNumberedList(
editor,
cursorPosition.line + 1,
endInnerListedLine,
previousNestedNumbered,
tabPattern.length,
ListType.Alphabet
);
const updatedOuterListed = updateOrderedNumberedList(
editor,
endInnerListedLine + 1,
editor.document.lineCount - 1,
previousOuterNumbered,
0,
ListType.Numbered
);
newNumberedLines = newNumberedLines.concat(updatedInnerListed).concat(updatedOuterListed);
const endLine = cursorPosition.line + updatedInnerListed.length + updatedOuterListed.length;
const range: vscode.Range = new vscode.Range(
cursorPosition.line,
0,
endLine,
editor.document.lineAt(endLine).text.length
);
common.insertContentToEditor(editor, newNumberedLines.join('\n'), true, range);
common.setCursorPosition(editor, cursorPosition.line, newNumberedLines[0].length);
}
}
/**
* Created a number list from existing text.
*/
export function createNumberedListFromText(editor: vscode.TextEditor) {
const listObjectModel = createListObjectModel(editor);
const startSelected = editor.selection.start;
const endSelected = editor.selection.end;
let previousNestedListNumbered =
listObjectModel.previousNested != null
? listObjectModel.previousNested.listNumber
: startAlphabet.charCodeAt(0) - 1;
let previousNestedListType =
listObjectModel.previousNested != null
? listObjectModel.previousNested.listType
: ListType.Alphabet;
const numberedListLines = [];
const casetype = createNumberedListCaseType(editor, ListType.Numbered);
// Update selected text
for (let i = startSelected.line; i <= endSelected.line; i++) {
let lineText = editor.document.lineAt(i).text;
const indentCount = CountIndent(lineText);
const numberedListType = getListTypeOfNumberedList(lineText);
if (lineText.trim().length === 0) {
numberedListLines.push(lineText);
// previousOuterNumbered = 0;
previousNestedListNumbered = startAlphabet.charCodeAt(0) - 1;
previousNestedListType = ListType.Alphabet;
continue;
}
lineText = getTextOfNumberedList(lineText, numberedListType);
switch (casetype) {
case CaseType.TextType:
numberedListLines.push(lineText);
break;
case CaseType.UnIndentNestedType:
numberedListLines.push(numberedListValue + '. ' + lineText);
break;
case CaseType.IndentType:
if (indentCount === 0) {
numberedListLines.push(numberedListValue + '. ' + lineText);
previousNestedListNumbered = startAlphabet.charCodeAt(0) - 1;
previousNestedListType = ListType.Alphabet;
} else {
if (previousNestedListType === ListType.Numbered) {
numberedListLines.push(tabPattern + ++previousNestedListNumbered + '. ' + lineText);
} else if (previousNestedListType === ListType.Alphabet) {
numberedListLines.push(
tabPattern + String.fromCharCode(++previousNestedListNumbered) + '. ' + lineText
);
} else {
numberedListLines.push(tabPattern + lineText);
}
}
break;
}
}
if (casetype === CaseType.TextType) {
// previousOuterNumbered = 0;
previousNestedListNumbered = startAlphabet.charCodeAt(0) - 1;
previousNestedListType = ListType.Alphabet;
} else if (casetype === CaseType.UnIndentNestedType) {
previousNestedListNumbered = startAlphabet.charCodeAt(0) - 1;
previousNestedListType = ListType.Alphabet;
}
const newSelection = new vscode.Selection(
new vscode.Position(startSelected.line, 0),
new vscode.Position(endSelected.line, numberedListLines[numberedListLines.length - 1].length)
);
// const endInnerListedLine = listObjectModel.nextNested != null && CountIndent(editor.document.lineAt(endSelected.line).text) > 0 ? listObjectModel.nextNested.line : endSelected.line;
const endLine = endSelected.line;
const range = new vscode.Range(
new vscode.Position(startSelected.line, 0),
new vscode.Position(endLine, editor.document.lineAt(endLine).text.length)
);
common.insertContentToEditor(editor, numberedListLines.join('\n'), true, range);
editor.selection = newSelection;
}
export function updateOrderedNumberedList(
editor: vscode.TextEditor,
startLine: number,
endLine: number,
currentNumber: number,
indentCount: number,
listType: ListType
) {
const newNumberedLines = [];
for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++) {
const lineText = editor.document.lineAt(lineNumber).text;
if (lineText.trim() === '') {
break;
}
const lineTextIndentCount = CountIndent(lineText);
const lineTextListType = getListTypeOfNumberedList(lineText);
if (
lineTextIndentCount === indentCount &&
(lineTextListType === ListType.Numbered || lineTextListType === ListType.Alphabet)
) {
const newlineText =
' '.repeat(indentCount) +
(listType === ListType.Numbered ? '1' : '1') +
'. ' +
getTextOfNumberedList(lineText, lineTextListType);
newNumberedLines.push(newlineText);
} else {
newNumberedLines.push(lineText);
if (lineTextIndentCount === indentCount) {
currentNumber = listType === ListType.Numbered ? 0 : startAlphabet.charCodeAt(0) - 1;
}
}
}
return newNumberedLines;
}
export function updateNumberedList(
editor: vscode.TextEditor,
startLine: number,
endLine: number,
currentNumber: number,
indent: string,
isNested: boolean
) {
let lineNumber = startLine;
const newNumberedLines = [];
// Update only the numbered list which is the indent are the same
const regex = new RegExp(
numberedListWithIndentRegexTemplate.replace('{0}', indent.length.toString())
);
for (; lineNumber <= endLine; lineNumber++) {
let lineText = editor.document.lineAt(lineNumber).text;
if (lineText.trim() === '') {
break;
}
if (
getNumberedLineWithRegex(regex, lineText) > 0 ||
(isNested && editor.selection.start.line === lineNumber)
) {
lineText = lineText.substring(lineText.indexOf('.', 0) + 1, lineText.length).trim();
newNumberedLines.push(indent + numberedListValue + '. ' + lineText);
} else {
newNumberedLines.push(lineText);
}
}
return newNumberedLines;
}
/**
* Update the nested list of numbers.
* @param {vscode.TextEditor} editor - The document associated with this text editor.
* @param {number} startLine - Numbered list start the index of the line.
* @param {number} endLine - Numbered list end the index of the line.
* @param {number} currentLineCode - The current line of the number/alphabet number of the char code.
* @param {string} indent - Indent string.
* @param {enum} listType - Numbered list of types.
*/
export function updateNestedNumberedList(
editor: vscode.TextEditor,
startLine: number,
endLine: number,
currentLineCode: number,
indent: string,
listType: ListType
) {
const newNumberedLines = [];
for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++) {
const lineText = editor.document.lineAt(lineNumber).text;
if (lineText.trim() === '') {
break;
}
const lineListType = getListTypeOfNumberedList(lineText);
switch (listType) {
case ListType.Numbered:
if (lineListType === ListType.Numbered || lineListType === ListType.Alphabet) {
newNumberedLines.push(
indent + ++currentLineCode + '. ' + getTextOfNumberedList(lineText, lineListType)
);
} else {
newNumberedLines.push(lineText);
if (CountIndent(lineText) === indent.length) {
currentLineCode = 0;
}
}
break;
case ListType.Alphabet:
if (lineListType === ListType.Numbered || lineListType === ListType.Alphabet) {
newNumberedLines.push(
indent +
String.fromCharCode(++currentLineCode) +
'. ' +
getTextOfNumberedList(lineText, lineListType)
);
} else {
newNumberedLines.push(lineText);
if (CountIndent(lineText) === indent.length) {
currentLineCode = startAlphabet.charCodeAt(0) - 1;
}
}
break;
case ListType.Bulleted:
newNumberedLines.push(indent + '- ' + getTextOfNumberedList(lineText, lineListType));
break;
}
}
return newNumberedLines;
}
export function getNumberTextOfNumberedList(text: string, listType: ListType) {
switch (listType) {
case ListType.Numbered:
case ListType.Alphabet:
text = text.substring(0, text.indexOf('.')).trim();
break;
case ListType.Bulleted:
text = text.substring(0, text.indexOf('-')).trim();
break;
}
return text;
}
export function getTextOfNumberedList(text: string, listType: ListType) {
switch (listType) {
case ListType.Numbered:
case ListType.Alphabet:
text = text.substring(text.indexOf('.') + 2);
break;
case ListType.Bulleted:
text = text.substring(text.indexOf('-') + 2);
break;
case ListType.Other:
text = text.substring(CountIndent(text));
break;
}
return text;
}
export function getListTypeOfNumberedList(text: string) {
let listType;
if (numberedListRegex.test(text)) {
listType = ListType.Numbered;
} else if (alphabetListRegex.test(text)) {
listType = ListType.Alphabet;
} else if (bulletedListRegex.test(text)) {
listType = ListType.Bulleted;
} else {
listType = ListType.Other;
}
return listType;
}
export function updateNestedAlphabetList(
editor: vscode.TextEditor,
startLine: number,
endLine: number,
currentAlphabet: number,
indent: string
) {
let lineNumber = startLine;
const newAlphabetLines = [];
// const numberRegex = new RegExp(numberedListWithIndentRegexTemplate.replace("{0}", indent.length.toString()));
const alphabetRegex = new RegExp(
alphabetListWithIndentRegexTemplate.replace('{0}', indent.length.toString())
);
for (; lineNumber <= endLine; lineNumber++) {
let lineText = editor.document.lineAt(lineNumber).text;
if (lineText.trim() === '') {
break;
}
if (
getAlphabetLineWithRegex(alphabetRegex, lineText) > 0 ||
editor.selection.start.line === lineNumber
) {
lineText = lineText.substring(lineText.indexOf('.', 0) + 1, lineText.length).trim();
newAlphabetLines.push(indent + String.fromCharCode(++currentAlphabet) + '. ' + lineText);
} else {
newAlphabetLines.push(lineText);
}
}
return newAlphabetLines;
}
/**
* Creates a new bulleted list from the current selection.
* @param {vscode.TextEditor} editor - the current vscode active editor.
*/
export function createBulletedListFromText(editor: vscode.TextEditor) {
const startSelected = editor.selection.start;
const endSelected = editor.selection.end;
const numberedListLines = [];
const casetype = createNumberedListCaseType(editor, ListType.Bulleted);
for (let line = startSelected.line; line <= endSelected.line; line++) {
let lineText = editor.document.lineAt(line).text;
if (lineText.trim() === '') {
numberedListLines.push(lineText);
continue;
}
const indentCount = CountIndent(lineText);
const numberedListType = getListTypeOfNumberedList(lineText);
lineText = getTextOfNumberedList(lineText, numberedListType);
switch (casetype) {
case CaseType.TextType:
numberedListLines.push(lineText);
break;
case CaseType.UnIndentNestedType:
numberedListLines.push('- ' + lineText);
break;
case CaseType.IndentType:
if (indentCount === 0) {
numberedListLines.push('- ' + lineText);
} else {
numberedListLines.push(tabPattern + '- ' + lineText);
}
break;
}
}
/* if (casetype === CaseType.TextType || casetype === CaseType.UnIndentNestedType) {
} */
const newSelection = new vscode.Selection(
new vscode.Position(startSelected.line, 0),
new vscode.Position(endSelected.line, numberedListLines[numberedListLines.length - 1].length)
);
const endLine = endSelected.line;
const range = new vscode.Range(
new vscode.Position(startSelected.line, 0),
new vscode.Position(endLine, editor.document.lineAt(endLine).text.length)
);
common.insertContentToEditor(editor, numberedListLines.join('\n'), true, range);
editor.selection = newSelection;
}
export function checkEmptyLine(editor: vscode.TextEditor) {
const cursorPosition = editor.selection.active;
const selectedLine = editor.document.lineAt(cursorPosition);
return editor.selection.isEmpty && selectedLine.text.trim() === '';
}
export function checkEmptySelection(editor: vscode.TextEditor) {
for (let i = editor.selection.start.line; i <= editor.selection.end.line; i++) {
if (!editor.document.lineAt(i).isEmptyOrWhitespace) {
return false;
}
}
return true;
}
export function insertEmptyList(editor: vscode.TextEditor, list: string) {
const cursorPosition = editor.selection.active;
editor.edit(update => {
update.insert(cursorPosition.with(cursorPosition.line, 0), list);
});
}
export function isBulletedLine(text: string) {
return text.trim() !== '' && (text.trim() === '-' || text.substring(0, 2) === '- ');
}
/**
* Get the list line number.
* @param {vscode.TextEditor} editor - The document associated with this text editor.
* @param {number} line - A line number in [0, lineCount].
* @param {enum} listType - Numbered list of types.
* @param {number} start - The zero-based index number indicating the beginning of the substring.
*/
export function getListLineNumber(
editor: vscode.TextEditor,
line: number,
listType: ListType,
start?: number
) {
if (line > -1 && line < editor.document.lineCount) {
const text =
start == null
? editor.document.lineAt(line).text
: editor.document.lineAt(line).text.substring(start);
switch (listType) {
case ListType.Numbered:
return getNumberedLine(text);
case ListType.Alphabet:
return getAlphabetLine(text);
case ListType.Bulleted:
return getBulletedLine(text);
}
}
return -1;
}
export function getNumberedLine(text: string) {
const match = numberedListRegex.exec(text);
if (match != null) {
const numbered = match[0].split('.')[0];
return +numbered;
}
return -1;
}
export function getNumberedLineWithRegex(regex: RegExp, text: string) {
const match = regex.exec(text);
if (match != null) {
const numbered = match[0].split('.')[0];
return +numbered;
}
return -1;
}
export function getAlphabetLine(text: string) {
const match = alphabetListRegex.exec(text);
if (match != null) {
const alphabet = match[0].split('.')[0].trim();
return alphabet.charCodeAt(0) < 'z'.charCodeAt(0) ? alphabet.charCodeAt(0) : -1;
}
return -1;
}
export function getAlphabetLineWithRegex(regex: RegExp, text: string) {
const match = regex.exec(text);
if (match != null) {
const alphabet = match[0].split('.')[0].trim();
return alphabet.charCodeAt(0) < 'z'.charCodeAt(0) ? alphabet.charCodeAt(0) : -1;
}
return -1;
}
export function getBulletedLine(text: string) {
const match = bulletedListRegex.exec(text);
if (match != null) {
return '-'.charCodeAt(0);
}
return -1;
}
export function addIndent(line: string) {
const stringTrim = line.trim();
return line.substring(0, line.indexOf(stringTrim));
}
export function CountIndent(text: string) {
for (let i = 0; i < text.length; i++) {
if (text[i] !== ' ') {
return i;
}
}
return 0;
}
export function findCurrentNumberedListNextLine(editor: vscode.TextEditor, currentLine: number) {
const nextLine = 0;
if (currentLine >= editor.document.lineCount) {
return nextLine;
}
const indentCount = CountIndent(editor.document.lineAt(currentLine).text);
const regex = new RegExp(
numberedListWithIndentRegexTemplate.replace('{0}', indentCount.toString())
);
while (
++currentLine < editor.document.lineCount &&
editor.document.lineAt(currentLine).text.trim() !== ''
) {
const number = getNumberedLineWithRegex(regex, editor.document.lineAt(currentLine).text);
if (number > 0) {
return currentLine;
}
}
return nextLine;
}
export function findCurrentAlphabetListNextLine(editor: vscode.TextEditor, currentLine: number) {
const nextLine = 0;
if (currentLine >= editor.document.lineCount) {
return nextLine;
}
const indentCount = CountIndent(editor.document.lineAt(currentLine).text);
const regex = new RegExp(
alphabetListWithIndentRegexTemplate.replace('{0}', indentCount.toString())
);
while (
++currentLine < editor.document.lineCount &&
editor.document.lineAt(currentLine).text.trim() !== ''
) {
const number = getAlphabetLineWithRegex(regex, editor.document.lineAt(currentLine).text);
if (number > 0) {
return currentLine;
}
}
return nextLine;
}
export function findCurrentNumberedListLastLine(
editor: vscode.TextEditor,
currentLine: number,
indentAdjust?: number
) {
let lastLine = -1;
if (currentLine >= editor.document.lineCount) {
return lastLine;
}
let indentCount = CountIndent(editor.document.lineAt(currentLine).text);
if (indentAdjust != null) {
indentCount = indentCount - indentAdjust;
}
while (
++currentLine < editor.document.lineCount &&
editor.document.lineAt(currentLine).text.trim() !== ''
) {
const regex = new RegExp(
numberedListWithIndentRegexTemplate.replace('{0}', indentCount.toString())
);
const number = getNumberedLineWithRegex(regex, editor.document.lineAt(currentLine).text);
if (number > 0) {
lastLine = currentLine;
}
}
return lastLine;
}
export function findCurrentAlphabetListLastLine(editor: vscode.TextEditor, currentLine: number) {
if (currentLine >= editor.document.lineCount) {
return editor.document.lineCount - 1;
}
const indentCount = CountIndent(editor.document.lineAt(currentLine).text);
while (
currentLine < editor.document.lineCount &&
editor.document.lineAt(currentLine).text.trim() !== ''
) {
const regex = new RegExp(
alphabetListWithIndentRegexTemplate.replace('{0}', indentCount.toString())
);
if (
getAlphabetLineWithRegex(regex, editor.document.lineAt(currentLine).text) > 0 ||
editor.selection.start.line === currentLine
) {
currentLine++;
} else {
break;
}
}
return currentLine - 1;
}
// Find the previous number in current indent
export function findCurrentNumberedListPreviousNumber(
editor: vscode.TextEditor,
currentLine: number,
indentAdjust?: number
) {
let previousListNumbered = 0;
if (currentLine >= editor.document.lineCount) {
return previousListNumbered;
}
let indentCount = CountIndent(editor.document.lineAt(currentLine).text);
if (indentAdjust != null) {
indentCount = indentCount - indentAdjust;
}
const regex = new RegExp(
numberedListWithIndentRegexTemplate.replace('{0}', indentCount.toString())
);
while (--currentLine >= 0 && editor.document.lineAt(currentLine).text.trim() !== '') {
previousListNumbered = getNumberedLineWithRegex(
regex,
editor.document.lineAt(currentLine).text
);
previousListNumbered = previousListNumbered !== -1 ? previousListNumbered : 0;
if (previousListNumbered > 0) {
return previousListNumbered;
}
}
return previousListNumbered;
}
export function autolistAlpha(
editor: vscode.TextEditor,
cursorPosition: vscode.Position,
alphabet: number
) {
// Check numbered block
const lineNumber = cursorPosition.line;
const firstLine = editor.document
.lineAt(lineNumber)
.text.substring(cursorPosition.character, editor.document.lineAt(lineNumber).text.length);
const indentCount = CountIndent(editor.document.lineAt(lineNumber).text);
const indent = ' '.repeat(indentCount);
let alphabetLines = [];
// Add a new line
alphabetLines.push('\n' + indent + numberedListValue + '. ' + firstLine);
const listObjectModel = createListObjectModel(editor);
const endInnerListedLine =
listObjectModel.nextNested != null && indentCount > 0
? listObjectModel.nextNested.line
: lineNumber;
const previousOuterNumbered =
listObjectModel.previousOuter != null ? listObjectModel.previousOuter.listNumber : 0;
const updatedInnerListed = updateOrderedNumberedList(
editor,
lineNumber + 1,
endInnerListedLine,
alphabet,
indentCount,
ListType.Alphabet
);
const updatedOuterListed = updateOrderedNumberedList(
editor,
endInnerListedLine + 1,
editor.document.lineCount - 1,
previousOuterNumbered,
0,
ListType.Numbered
);
alphabetLines = alphabetLines.concat(updatedInnerListed).concat(updatedOuterListed);
const endLine = lineNumber + updatedInnerListed.length + updatedOuterListed.length;
// Replace editer's text and range assignment
const range: vscode.Range = new vscode.Range(
lineNumber,
cursorPosition.character,
endLine,
editor.document.lineAt(endLine).text.length
);
const replacementText = alphabetLines.join('\n');
common.insertContentToEditor(editor, replacementText, true, range);
// set cursor position
common.setCursorPosition(
editor,
lineNumber + 1,
String.fromCharCode(alphabet).toString().length + indentCount + 2
);
}
export function autolistNumbered(
editor: vscode.TextEditor,
cursorPosition: vscode.Position,
numbered: number
) {
// Check numbered block
const lineNumber = cursorPosition.line;
const firstLine = editor.document
.lineAt(cursorPosition.line)
.text.substring(
cursorPosition.character,
editor.document.lineAt(cursorPosition.line).text.length
);
const indentCount = CountIndent(editor.document.lineAt(cursorPosition.line).text);
const indent = ' '.repeat(indentCount);
let numberedLines = [];
// Add a new line
numberedLines.push('\n' + indent + numberedListValue + '. ' + firstLine);
const listObjectModel = createListObjectModel(editor);
const endInnerListedLine =
listObjectModel.nextNested != null && indentCount > 0
? listObjectModel.nextNested.line
: lineNumber;
let previousOuterNumbered = 0;
if (indentCount === 0) {
previousOuterNumbered = numbered;
} else if (listObjectModel.previousOuter != null) {
previousOuterNumbered = listObjectModel.previousOuter.listNumber;
}
const updatedInnerListed = updateOrderedNumberedList(
editor,
lineNumber + 1,
endInnerListedLine,
numbered,
indentCount,
ListType.Numbered
);
const updatedOuterListed = updateOrderedNumberedList(
editor,
endInnerListedLine + 1,
editor.document.lineCount - 1,
previousOuterNumbered,
0,
ListType.Numbered
);
numberedLines = numberedLines.concat(updatedInnerListed).concat(updatedOuterListed);
const endLine = lineNumber + updatedInnerListed.length + updatedOuterListed.length;
const range: vscode.Range = new vscode.Range(
cursorPosition.line,
cursorPosition.character,
endLine,
editor.document.lineAt(endLine).text.length
);
common.insertContentToEditor(editor, numberedLines.join('\n'), true, range);
// set cursor position
common.setCursorPosition(
editor,
cursorPosition.line + 1,
numbered.toString().length + indentCount + 2
);
}
export function nestedNumberedList(
editor: vscode.TextEditor,
cursorPosition: vscode.Position,
indentCount: number
) {
const previousLine = cursorPosition.line - 1;
const nextLine = cursorPosition.line + 1;
const previousInnerNumbered = getListLineNumber(
editor,
previousLine,
ListType.Numbered,
cursorPosition.character
);
const previousaphabet = getListLineNumber(
editor,
previousLine,
ListType.Alphabet,
cursorPosition.character
);
const nextnumbered = getListLineNumber(
editor,
nextLine,
ListType.Numbered,
cursorPosition.character
);
const nextalphabet = getListLineNumber(
editor,
nextLine,
ListType.Alphabet,
cursorPosition.character
);
const newIndentCount = CountIndent(tabPattern + editor.document.lineAt(cursorPosition.line).text);
let cursorIndex = (tabPattern + tabPattern.repeat(indentCount) + startAlphabet + '. ').length;
// When have next/previous inner number list
if (previousInnerNumbered > 0 || (previousaphabet <= 0 && nextnumbered > 0)) {
const listObjectModel = createListObjectModel(editor);
const previousOuterNumbered =
listObjectModel.previousOuter != null ? listObjectModel.previousOuter.listNumber : 0;
const numbered = previousInnerNumbered > 0 ? previousInnerNumbered : 0;
const endInnerListedLine =
listObjectModel.nextNested != null ? listObjectModel.nextNested.line : cursorPosition.line;
const endOuterListedLine =
listObjectModel.nextOuter != null ? listObjectModel.nextOuter.line : endInnerListedLine;
// Update inner numbered list
const updatedInnerListed = updateNestedNumberedList(
editor,
cursorPosition.line,
endInnerListedLine,
numbered,
tabPattern.repeat(newIndentCount / 4),
ListType.Numbered
);
const updatedOuterListed = updateOrderedNumberedList(
editor,
endInnerListedLine + 1,
endOuterListedLine,
previousOuterNumbered,
indentCount,
ListType.Numbered
);
const updatedListedText =
updatedInnerListed.concat(updatedOuterListed).length > 0
? updatedInnerListed.concat(updatedOuterListed).join('\n')
: '';
const range: vscode.Range = new vscode.Range(
cursorPosition.line,
0,
endOuterListedLine,
editor.document.lineAt(endOuterListedLine).text.length
);
common.insertContentToEditor(editor, updatedListedText, true, range);
cursorIndex =
updatedInnerListed.length > 0 ? updatedInnerListed[0].indexOf('. ') + 2 : cursorIndex;
} else if (previousaphabet > 0 || nextalphabet > 0) {
const listObjectModel = createListObjectModel(editor);
const previousOuterNumbered =
listObjectModel.previousOuter != null ? listObjectModel.previousOuter.listNumber : 0;
const alphabet = previousaphabet > 0 ? previousaphabet : startAlphabet.charCodeAt(0) - 1;
const endInnerListedLine =
listObjectModel.nextNested != null ? listObjectModel.nextNested.line : cursorPosition.line;
const endOuterListedLine =
listObjectModel.nextOuter != null ? listObjectModel.nextOuter.line : endInnerListedLine;
// Update inner alphabet list
const updatedInnerListed = updateNestedNumberedList(
editor,
cursorPosition.line,
endInnerListedLine,
alphabet,
tabPattern.repeat(newIndentCount / 4),
ListType.Alphabet
);
const updatedOuterListed = updateOrderedNumberedList(
editor,
endInnerListedLine + 1,
endOuterListedLine,
previousOuterNumbered,
indentCount,
ListType.Numbered
);
const updatedListedText =
updatedInnerListed.concat(updatedOuterListed).length > 0
? updatedInnerListed.concat(updatedOuterListed).join('\n')
: '';
const range: vscode.Range = new vscode.Range(
cursorPosition.line,
0,
endOuterListedLine,
editor.document.lineAt(endOuterListedLine).text.length
);
common.insertContentToEditor(editor, updatedListedText, true, range);
} else {
const lineText = editor.document.lineAt(cursorPosition.line).text;
const lineCount = CountIndent(lineText);
const listObjectModel = createListObjectModel(editor);
let previousOuterNumbered =
listObjectModel.previousOuter != null ? listObjectModel.previousOuter.listNumber : 0;
let previousOuterListType = ListType.Numbered;
let previousNestedNumbered =
listObjectModel.previousNested != null
? listObjectModel.previousNested.listNumber
: startAlphabet.charCodeAt(0) - 1;
let previousNestedListType =
listObjectModel.previousNested != null
? listObjectModel.previousNested.listType
: ListType.Alphabet;
let endInnerListedLine =
listObjectModel.nextNested != null ? listObjectModel.nextNested.line : cursorPosition.line;
let endOuterListedLine =
listObjectModel.nextOuter != null ? listObjectModel.nextOuter.line : endInnerListedLine;
let numberedListLines = [];
const lineTextListType = getListTypeOfNumberedList(lineText);
// const lineTextListNumbered = getNumberTextOfNumberedList(lineText, lineTextListType);
switch (lineTextListType) {
case ListType.Numbered:
case ListType.Alphabet:
let newNumber = numberedListValue;
if (lineCount === 0) {
newNumber = numberedListValue;
}
let newLineText =
' '.repeat(newIndentCount) +
newNumber +
'. ' +
getTextOfNumberedList(lineText, lineTextListType);
numberedListLines.push(newLineText);
break;
case ListType.Bulleted:
case ListType.Other:
newLineText =
' '.repeat(newIndentCount) +
getNumberTextOfNumberedList(lineText, lineTextListType) +
getTextOfNumberedList(lineText, lineTextListType);
if (lineCount === 0) {
previousNestedNumbered = startAlphabet.charCodeAt(0) - 1;
previousNestedListType = ListType.Alphabet;
}
break;
}
if (lineCount > 0) {
endOuterListedLine = endInnerListedLine;
previousOuterNumbered = previousNestedNumbered;
previousOuterListType = previousNestedListType;
endInnerListedLine = cursorPosition.line;
previousNestedNumbered = startAlphabet.charCodeAt(0) - 1;
previousNestedListType = ListType.Alphabet;
}
const updatedInnerListed = updateNestedNumberedList(
editor,
cursorPosition.line + 1,
endInnerListedLine,
previousNestedNumbered,
tabPattern.repeat(newIndentCount / 4),
previousNestedListType
);
const updatedOuterListed = updateOrderedNumberedList(
editor,
endInnerListedLine + 1,
endOuterListedLine,
previousOuterNumbered,
indentCount,
previousOuterListType
);
numberedListLines = numberedListLines.concat(updatedInnerListed.concat(updatedOuterListed));
cursorIndex = cursorPosition.character + numberedListLines[0].length - lineText.length;
const range: vscode.Range = new vscode.Range(
cursorPosition.line,
0,
endOuterListedLine,
editor.document.lineAt(endOuterListedLine).text.length
);
common.insertContentToEditor(editor, numberedListLines.join('\n'), true, range);
}
// set cursor position
common.setCursorPosition(editor, cursorPosition.line, cursorIndex > 0 ? cursorIndex : 0);
}
export function removeNestedListSingleLine(editor: vscode.TextEditor) {
const cursorPosition = editor.selection.active;
const startSelected = editor.selection.start;
const endSelected = editor.selection.end;
const text = editor.document.getText(
new vscode.Range(
cursorPosition.with(cursorPosition.line, 0),
cursorPosition.with(cursorPosition.line, endSelected.character)
)
);
const indentCount = CountIndent(editor.document.lineAt(cursorPosition.line).text);
const numberedRegex = new RegExp(
fixedNumberedListWithIndentRegexTemplate.replace('{0}', indentCount.toString())
);
const alphabetRegex = new RegExp(
fixedAlphabetListWithIndentRegexTemplate.replace('{0}', indentCount.toString())
);
// If it contain number or bullet list
if (fixedBulletedListRegex.exec(text) != null) {
if (indentCount >= 4) {
editor.edit(update => {
update.delete(
new vscode.Range(
cursorPosition.with(cursorPosition.line, 0),
cursorPosition.with(cursorPosition.line, 4)
)
);
});
} else if (indentCount < 4) {
editor.edit(update => {
update.delete(
new vscode.Range(
cursorPosition.with(cursorPosition.line, 0),
cursorPosition.with(cursorPosition.line, endSelected.character)
)
);
});
}
} else if (getNumberedLineWithRegex(numberedRegex, text) > 0) {
if (indentCount >= 4) {
const listObjectModel = createListObjectModel(editor);
const previousOuterNumbered =
listObjectModel.previousOuter != null ? listObjectModel.previousOuter.listNumber : 0;
let previousNestedNumbered = startAlphabet.charCodeAt(0) - 1;
let previousNestedListType = ListType.Alphabet;
if (cursorPosition.line < editor.document.lineCount - 1) {
const nextLineText = editor.document.lineAt(cursorPosition.line + 1).text;
const nextListType = getListTypeOfNumberedList(nextLineText);
if (CountIndent(nextLineText) === tabPattern.length && nextListType === ListType.Numbered) {
previousNestedListType = ListType.Numbered;
previousNestedNumbered = 0;
}
}
const endInnerListedLine =
listObjectModel.nextNested != null ? listObjectModel.nextNested.line : cursorPosition.line;
const endOuterListedLine =
listObjectModel.nextOuter != null ? listObjectModel.nextOuter.line : endInnerListedLine;
const updatedListed = updateNumberedList(
editor,
cursorPosition.line,
cursorPosition.line,
previousOuterNumbered,
tabPattern.repeat(indentCount / 4 - 1),
true
);
const updatedInnerListed = updateNestedNumberedList(
editor,
cursorPosition.line + 1,
endInnerListedLine,
previousNestedNumbered,
tabPattern.repeat(indentCount / 4),
previousNestedListType
);
const updatedOuterListed = updateOrderedNumberedList(
editor,
endInnerListedLine + 1,
endOuterListedLine,
previousOuterNumbered,
indentCount - tabPattern.length,
ListType.Numbered
);
const updatedListedText =
updatedListed.concat(updatedInnerListed).concat(updatedOuterListed).length > 0
? updatedListed.concat(updatedInnerListed).concat(updatedOuterListed).join('\n')
: '';
editor.edit(update => {
update.replace(
new vscode.Range(
cursorPosition.line,
0,
endOuterListedLine,
editor.document.lineAt(endOuterListedLine).text.length
),
updatedListedText
);
});
const cursorIndex =
updatedListed.length > 0
? updatedListed[0].indexOf('. ') + 2
: cursorPosition.character - indentCount;
common.setCursorPosition(editor, cursorPosition.line, cursorIndex);
} else if (indentCount < 4) {
let lineText = editor.document.lineAt(cursorPosition.line).text;
lineText = lineText.substring(lineText.indexOf('.', 0) + 1, lineText.length).trim();
let newNumberedLines = [lineText];
const updatedOuterListed = updateOrderedNumberedList(
editor,
cursorPosition.line + 1,
editor.document.lineCount - 1,
0,
0,
ListType.Numbered
);
newNumberedLines = newNumberedLines.concat(updatedOuterListed);
const endLine = cursorPosition.line + updatedOuterListed.length;
const range: vscode.Range = new vscode.Range(
cursorPosition.line,
0,
endLine,
editor.document.lineAt(endLine).text.length
);
common.insertContentToEditor(editor, newNumberedLines.join('\n'), true, range);
common.setSelectorPosition(editor, cursorPosition.line, 0, cursorPosition.line, 0);
}
} else if (getAlphabetLineWithRegex(alphabetRegex, text) > 0) {
if (indentCount >= 4) {
const listObjectModel = createListObjectModel(editor);
let lineText = editor.document.lineAt(cursorPosition.line).text;
lineText = lineText.substring(lineText.indexOf('.', 0) + 1, lineText.length).trim();
const previousOuterNumbered =
listObjectModel.previousOuter != null ? listObjectModel.previousOuter.listNumber : 0;
const endInnerListedLine =
listObjectModel.nextNested != null ? listObjectModel.nextNested.line : cursorPosition.line;
const endOuterListedLine =
listObjectModel.nextOuter != null ? listObjectModel.nextOuter.line : endInnerListedLine;
const updatedListed = updateNumberedList(
editor,
cursorPosition.line,
cursorPosition.line,
previousOuterNumbered,
tabPattern.repeat(indentCount / 4 - 1),
true
);
const updatedInnerListed = updateNestedNumberedList(
editor,
cursorPosition.line + 1,
endInnerListedLine,
startAlphabet.charCodeAt(0) - 1,
tabPattern.repeat(indentCount / 4),
ListType.Alphabet
);
const updatedOuterListed = updateOrderedNumberedList(
editor,
endInnerListedLine + 1,
endOuterListedLine,
previousOuterNumbered,
indentCount - 4,
ListType.Numbered
);
const updatedListedText =
updatedListed.concat(updatedInnerListed).concat(updatedOuterListed).length > 0
? updatedListed.concat(updatedInnerListed).concat(updatedOuterListed).join('\n')
: '';
editor.edit(update => {
update.replace(
new vscode.Range(
cursorPosition.line,
0,
endOuterListedLine,
editor.document.lineAt(endOuterListedLine).text.length
),
updatedListedText
);
});
const cursorIndex =
updatedListed.length > 0
? updatedListed[0].indexOf('. ') + 2
: cursorPosition.character - indentCount;
common.setCursorPosition(editor, cursorPosition.line, cursorIndex);
} else if (indentCount < 4) {
editor.edit(update => {
update.delete(
new vscode.Range(
cursorPosition.with(cursorPosition.line, 0),
cursorPosition.with(cursorPosition.line, endSelected.character)
)
);
});
}
} else {
// If selected text > 0
if (Math.abs(endSelected.character - startSelected.character) > 0) {
removeNestedListMultipleLine(editor);
} else if (startSelected.character !== 0) {
editor.edit(update => {
update.delete(
new vscode.Range(
cursorPosition.with(cursorPosition.line, startSelected.character - 1),
cursorPosition.with(cursorPosition.line, startSelected.character)
)
);
});
} else if (startSelected.character === 0) {
if (startSelected.line !== 0) {
const lineText = editor.document.lineAt(startSelected.line - 1).text;
// Replace editor's text
editor.edit(update => {
update.replace(
new vscode.Range(startSelected.line - 1, 0, endSelected.line, 0),
lineText
);
});
}
}
}
}
export function removeNestedListMultipleLine(editor: vscode.TextEditor) {
const startSelected = editor.selection.start;
const endSelected = editor.selection.end;
const numberedListLines = [];
const startLineNotSelectedText = editor.document
.lineAt(startSelected.line)
.text.substring(0, startSelected.character);
const endLineNotSelectedText = editor.document
.lineAt(endSelected.line)
.text.substring(endSelected.character);
if (startLineNotSelectedText.trim().length > 0 || endLineNotSelectedText.trim().length > 0) {
numberedListLines.push(endLineNotSelectedText);
}
const endLine = endSelected.line;
const range = new vscode.Range(
startSelected.line,
startSelected.character,
endLine,
editor.document.lineAt(endLine).text.length
);
common.insertContentToEditor(editor, numberedListLines.join('\n'), true, range);
common.setCursorPosition(editor, startSelected.line, startSelected.character);
}
export function createListObjectModel(editor: vscode.TextEditor) {
const startPosition = editor.selection.start;
const endPosition = editor.selection.end;
let startLine = startPosition.line;
const listObjectModel = new ListObjectModel();
let flag = true;
while (--startLine >= 0) {
const lineText = editor.document.lineAt(startLine).text;
const indentCount = CountIndent(lineText);
const listType = getListTypeOfNumberedList(lineText);
if (lineText.trim() === '') {
break;
}
if (indentCount === 0) {
if (listType === ListType.Numbered) {
listObjectModel.previousOuter = createLineObjectModel(editor, startLine);
}
break;
}
if (flag && indentCount === tabPattern.length) {
if (listType === ListType.Numbered || listType === ListType.Alphabet) {
listObjectModel.previousNested = createLineObjectModel(editor, startLine);
}
flag = false;
}
}
let endLine = endPosition.line;
flag = true;
while (++endLine < editor.document.lineCount) {
const lineText = editor.document.lineAt(endLine).text;
const indentCount = CountIndent(lineText);
if (lineText.trim() === '') {
listObjectModel.nextOuter = createLineObjectModel(editor, endLine - 1);
if (
flag &&
listObjectModel.nextNested == null &&
CountIndent(editor.document.lineAt(endLine - 1).text) > 0
) {
listObjectModel.nextNested = createLineObjectModel(editor, endLine - 1);
}
break;
} else if (endLine === editor.document.lineCount - 1) {
listObjectModel.nextOuter = createLineObjectModel(editor, endLine);
if (flag && listObjectModel.nextNested == null && indentCount > 0) {
listObjectModel.nextNested = createLineObjectModel(editor, endLine);
}
} else if (flag && indentCount === 0) {
if (CountIndent(editor.document.lineAt(endLine - 1).text) > 0) {
listObjectModel.nextNested = createLineObjectModel(editor, endLine - 1);
}
flag = false;
}
}
return listObjectModel;
}
export function createLineObjectModel(editor: vscode.TextEditor, line: number) {
if (line < 0 || line >= editor.document.lineCount) {
return null;
}
const lineText = editor.document.lineAt(line).text;
const indent = ' '.repeat(CountIndent(lineText));
const listType = getListTypeOfNumberedList(lineText);
const listNumber =
listType === ListType.Numbered
? +getNumberTextOfNumberedList(lineText, listType)
: getNumberTextOfNumberedList(lineText, listType).charCodeAt(0);
const listText = getTextOfNumberedList(lineText, listType);
return new LineObjectModel(line, indent, listType, listNumber, listText);
}
export function createNumberedListCaseType(editor: vscode.TextEditor, listType: ListType) {
const startSelectedLine = editor.selection.start.line;
const endSelectedLine = editor.selection.end.line;
let isUnIndentNestedType = true;
let isTextType = true;
for (let line = startSelectedLine; line <= endSelectedLine; line++) {
const lineText = editor.document.lineAt(line).text;
if (lineText.trim() === '') {
continue;
}
const lineCount = CountIndent(lineText);
const lineListType = getListTypeOfNumberedList(lineText);
switch (listType) {
case ListType.Bulleted:
if (lineCount > 0 || lineListType !== ListType.Bulleted) {
isTextType = false;
if (
(lineCount === 0 && lineListType !== ListType.Bulleted) ||
lineCount !== tabPattern.length ||
lineListType !== ListType.Bulleted
) {
isUnIndentNestedType = false;
line = endSelectedLine + 1;
}
}
break;
case ListType.Numbered:
if (lineCount > 0 || lineListType !== ListType.Numbered) {
isTextType = false;
if (
(lineCount === 0 && lineListType !== ListType.Numbered) ||
lineCount !== tabPattern.length ||
(lineListType !== ListType.Numbered && lineListType !== ListType.Alphabet)
) {
isUnIndentNestedType = false;
line = endSelectedLine + 1;
}
}
break;
}
}
let caseType = CaseType.IndentType;
if (isTextType) {
caseType = CaseType.TextType;
} else if (isUnIndentNestedType) {
caseType = CaseType.UnIndentNestedType;
}
return caseType;
}
export enum CaseType {
IndentType,
UnIndentNestedType,
TextType
} | the_stack |
import { EventStream } from '~/api/grpc/event-stream';
import { Filters, FilterEntry, FilterDirection } from '~/domain/filtering';
import { FlowFilter, Verdict } from '~backend/proto/flow/flow_pb';
import { filterEntries } from '~/testing/data';
// TODO: consider to move it to helper utils ~/testing/helpers
interface ExpectList {
srcPod?: string[];
dstPod?: string[];
srcIp?: string[];
dstIp?: string[];
srcIdentity?: number[];
dstIdentity?: number[];
srcFqdn?: string[];
dstFqdn?: string[];
srcLabel?: string[];
dstLabel?: string[];
srcService?: string[];
dstService?: string[];
httpStatus?: string[];
dnsQuery?: string[];
verdict?: Verdict[];
// TODO: couple of fields are skipped
}
const expectLists = (ff: FlowFilter, obj: ExpectList) => {
const srcPod = ff.getSourcePodList();
const dstPod = ff.getDestinationPodList();
const srcIp = ff.getSourceIpList();
const dstIp = ff.getDestinationIpList();
const srcIdentity = ff.getSourceIdentityList();
const dstIdentity = ff.getDestinationIdentityList();
const srcFqdn = ff.getSourceFqdnList();
const dstFqdn = ff.getDestinationFqdnList();
const srcLabel = ff.getSourceLabelList();
const dstLabel = ff.getDestinationLabelList();
const srcService = ff.getSourceServiceList();
const dstService = ff.getDestinationServiceList();
const httpStatus = ff.getHttpStatusCodeList();
const dnsQuery = ff.getDnsQueryList();
const verdict = ff.getVerdictList();
expect(srcPod.length).toBe(obj.srcPod?.length || 0);
obj.srcPod?.forEach(v => {
expect(srcPod.includes(v)).toBe(true);
});
expect(dstPod.length).toBe(obj.dstPod?.length || 0);
obj.dstPod?.forEach(v => {
expect(dstPod.includes(v)).toBe(true);
});
expect(srcIp.length).toBe(obj.srcIp?.length || 0);
obj.srcIp?.forEach(v => {
expect(srcIp.includes(v)).toBe(true);
});
expect(dstIp.length).toBe(obj.dstIp?.length || 0);
obj.dstIp?.forEach(v => {
expect(dstIp.includes(v)).toBe(true);
});
expect(srcIdentity.length).toBe(obj.srcIdentity?.length || 0);
obj.srcIdentity?.forEach(v => {
expect(srcIdentity.includes(v)).toBe(true);
});
expect(dstIdentity.length).toBe(obj.dstIdentity?.length || 0);
obj.dstIdentity?.forEach(v => {
expect(dstIdentity.includes(v)).toBe(true);
});
expect(srcFqdn.length).toBe(obj.srcFqdn?.length || 0);
obj.srcFqdn?.forEach(v => {
expect(srcFqdn.includes(v)).toBe(true);
});
expect(dstFqdn.length).toBe(obj.dstFqdn?.length || 0);
obj.dstFqdn?.forEach(v => {
expect(dstFqdn.includes(v)).toBe(true);
});
expect(srcLabel.length).toBe(obj.srcLabel?.length || 0);
obj.srcLabel?.forEach(v => {
expect(srcLabel.includes(v)).toBe(true);
});
expect(dstLabel.length).toBe(obj.dstLabel?.length || 0);
obj.dstLabel?.forEach(v => {
expect(dstLabel.includes(v)).toBe(true);
});
expect(srcService.length).toBe(obj.srcService?.length || 0);
obj.srcService?.forEach(v => {
expect(srcService.includes(v)).toBe(true);
});
expect(dstService.length).toBe(obj.dstService?.length || 0);
obj.dstService?.forEach(v => {
expect(dstService.includes(v)).toBe(true);
});
expect(httpStatus.length).toBe(obj.httpStatus?.length || 0);
obj.httpStatus?.forEach(v => {
expect(httpStatus.includes(v)).toBe(true);
});
expect(verdict.length).toBe(obj.verdict?.length || 0);
obj.verdict?.forEach(v => {
expect(verdict.includes(v)).toBe(true);
});
expect(dnsQuery.length).toBe(obj.dnsQuery?.length || 0);
obj.dnsQuery?.forEach(v => {
expect(dnsQuery.includes(v)).toBe(true);
});
};
describe('EventStream::buildFlowFilters', () => {
test('test 1 - no filter entries', () => {
const ns = 'random-namespace';
const filters = new Filters({
namespace: ns,
filters: [],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(2);
const [a, b] = wl;
// NOTE: by default, only traffic either from ns OR to ns is allowed
expectLists(a, { srcPod: [`${ns}/`] });
expectLists(b, { dstPod: [`${ns}/`] });
});
test('test 2 - fromLabelRegular', () => {
const ns = 'random-namespace';
const fe = filterEntries.fromLabelRegular!;
const filters = new Filters({
namespace: ns,
filters: [fe],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(2);
const [toInside, fromInside] = wl;
// NOTE: flows to current ns AND specified label...
expectLists(toInside, { dstPod: [`${ns}/`], srcLabel: [fe.query] });
// NOTE: ...OR flows from current ns AND specified label
expectLists(fromInside, { srcPod: [`${ns}/`], srcLabel: [fe.query] });
});
test('test 3 - toLabelRegular', () => {
const ns = 'random-namespace';
const fe = filterEntries.toLabelRegular!;
const filters = new Filters({
namespace: ns,
filters: [fe],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(2);
const [fromInside, toInside] = wl;
// NOTE: flows from current ns AND to specified label...
expectLists(fromInside, { srcPod: [`${ns}/`], dstLabel: [fe.query] });
// NOTE: ...OR flows to current ns AND to specified label
expectLists(toInside, { dstPod: [`${ns}/`], dstLabel: [fe.query] });
});
test('test 4 - bothLabelRegular', () => {
const ns = 'random-namespace';
const fe = filterEntries.bothLabelRegular!;
const filters = new Filters({
namespace: ns,
filters: [fe],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(4);
const [
toInsideFromLabel,
fromInsideFromLabel,
fromInsideToLabel,
toInsideToLabel,
] = wl;
// NOTE: flows to current ns AND from specified label...
expectLists(toInsideFromLabel, {
dstPod: [`${ns}/`],
srcLabel: [fe.query],
});
// NOTE: ...OR flows from current ns AND from specified label
expectLists(fromInsideFromLabel, {
srcPod: [`${ns}/`],
srcLabel: [fe.query],
});
// NOTE: ...OR flows from current ns AND to specified label...
expectLists(fromInsideToLabel, {
srcPod: [`${ns}/`],
dstLabel: [fe.query],
});
// NOTE: ...OR flows to current ns AND to specified label
expectLists(toInsideToLabel, { dstPod: [`${ns}/`], dstLabel: [fe.query] });
});
test('test 5 - from/toLabelRegular', () => {
const ns = 'random-namespace';
const fe = [filterEntries.fromLabelRegular!, filterEntries.toLabelRegular!];
const filters = new Filters({
namespace: ns,
filters: fe,
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(4);
const [
toInsideFromLabel,
fromInsideFromLabel,
fromInsideToLabel,
toInsideToLabel,
] = wl;
// NOTE: flows to current ns AND from specified label...
expectLists(toInsideFromLabel, {
dstPod: [`${ns}/`],
srcLabel: [fe[0].query],
});
// NOTE: ...OR flows from current ns AND from specified label
expectLists(fromInsideFromLabel, {
srcPod: [`${ns}/`],
srcLabel: [fe[0].query],
});
// NOTE: ...OR flows from current ns AND to specified label...
expectLists(fromInsideToLabel, {
srcPod: [`${ns}/`],
dstLabel: [fe[0].query],
});
// NOTE: ...OR flows to current ns AND to specified label
expectLists(toInsideToLabel, {
dstPod: [`${ns}/`],
dstLabel: [fe[0].query],
});
});
test('test 6 - fromDnsGoogle', () => {
const ns = 'random-namespace';
const fe = filterEntries.fromDnsGoogle!;
const filters = new Filters({
namespace: ns,
filters: [fe],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(2);
const [toInside, fromInside] = wl;
// NOTE: flows to current ns AND specified dns...
expectLists(toInside, { dstPod: [`${ns}/`], srcFqdn: [fe.query] });
// NOTE: ...OR flows from current ns AND specified dns
expectLists(fromInside, { srcPod: [`${ns}/`], srcFqdn: [fe.query] });
});
test('test 7 - toDnsGoogle', () => {
const ns = 'random-namespace';
const fe = filterEntries.toDnsGoogle!;
const filters = new Filters({
namespace: ns,
filters: [fe],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(2);
const [fromInside, toInside] = wl;
// NOTE: flows from current ns AND to specified dns...
expectLists(fromInside, { srcPod: [`${ns}/`], dstFqdn: [fe.query] });
// NOTE: ...OR flows to current ns AND to specified dns
expectLists(toInside, { dstPod: [`${ns}/`], dstFqdn: [fe.query] });
});
test('test 8 - bothDnsGoogle', () => {
const ns = 'random-namespace';
const fe = filterEntries.bothDnsGoogle!;
const filters = new Filters({
namespace: ns,
filters: [fe],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(4);
const [
toInsideFromLabel,
fromInsideFromLabel,
fromInsideToLabel,
toInsideToLabel,
] = wl;
// NOTE: flows to current ns AND from specified dns...
expectLists(toInsideFromLabel, {
dstPod: [`${ns}/`],
srcFqdn: [fe.query],
});
// NOTE: ...OR flows from current ns AND from specified dns
expectLists(fromInsideFromLabel, {
srcPod: [`${ns}/`],
srcFqdn: [fe.query],
});
// NOTE: ...OR flows from current ns AND to specified dns...
expectLists(fromInsideToLabel, {
srcPod: [`${ns}/`],
dstFqdn: [fe.query],
});
// NOTE: ...OR flows to current ns AND to specified dns
expectLists(toInsideToLabel, { dstPod: [`${ns}/`], dstFqdn: [fe.query] });
});
test('test 9 - from/toDnsGoogle', () => {
const ns = 'random-namespace';
const fe = [filterEntries.fromDnsGoogle!, filterEntries.toDnsGoogle!];
const filters = new Filters({
namespace: ns,
filters: fe,
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(4);
const [
toInsideFromLabel,
fromInsideFromLabel,
fromInsideToLabel,
toInsideToLabel,
] = wl;
// NOTE: flows to current ns AND from specified dns...
expectLists(toInsideFromLabel, {
dstPod: [`${ns}/`],
srcFqdn: [fe[0].query],
});
// NOTE: ...OR flows from current ns AND from specified dns
expectLists(fromInsideFromLabel, {
srcPod: [`${ns}/`],
srcFqdn: [fe[0].query],
});
// NOTE: ...OR flows from current ns AND to specified dns...
expectLists(fromInsideToLabel, {
srcPod: [`${ns}/`],
dstFqdn: [fe[0].query],
});
// NOTE: ...OR flows to current ns AND to specified dns
expectLists(toInsideToLabel, {
dstPod: [`${ns}/`],
dstFqdn: [fe[0].query],
});
});
test('test 10 - fromRandomIp', () => {
const ns = 'random-namespace';
const fe = filterEntries.fromIpRandom!;
const filters = new Filters({
namespace: ns,
filters: [fe],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(2);
const [toInside, fromInside] = wl;
// NOTE: flows to current ns AND specified ip...
expectLists(toInside, { dstPod: [`${ns}/`], srcIp: [fe.query] });
// NOTE: ...OR flows from current ns AND specified ip
expectLists(fromInside, { srcPod: [`${ns}/`], srcIp: [fe.query] });
});
test('test 11 - toRandomIp', () => {
const ns = 'random-namespace';
const fe = filterEntries.toIpRandom!;
const filters = new Filters({
namespace: ns,
filters: [fe],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(2);
const [fromInside, toInside] = wl;
// NOTE: flows from current ns AND to specified ip...
expectLists(fromInside, { srcPod: [`${ns}/`], dstIp: [fe.query] });
// NOTE: ...OR flows to current ns AND to specified ip
expectLists(toInside, { dstPod: [`${ns}/`], dstIp: [fe.query] });
});
test('test 12 - bothRandomIp', () => {
const ns = 'random-namespace';
const fe = filterEntries.bothIpRandom!;
const filters = new Filters({
namespace: ns,
filters: [fe],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(4);
const [
toInsideFromLabel,
fromInsideFromLabel,
fromInsideToLabel,
toInsideToLabel,
] = wl;
// NOTE: flows to current ns AND from specified ip...
expectLists(toInsideFromLabel, {
dstPod: [`${ns}/`],
srcIp: [fe.query],
});
// NOTE: ...OR flows from current ns AND from specified ip
expectLists(fromInsideFromLabel, {
srcPod: [`${ns}/`],
srcIp: [fe.query],
});
// NOTE: ...OR flows from current ns AND to specified ip...
expectLists(fromInsideToLabel, {
srcPod: [`${ns}/`],
dstIp: [fe.query],
});
// NOTE: ...OR flows to current ns AND to specified ip
expectLists(toInsideToLabel, { dstPod: [`${ns}/`], dstIp: [fe.query] });
});
test('test 13 - from/toRandomIp', () => {
const ns = 'random-namespace';
const fe = [filterEntries.fromIpRandom!, filterEntries.toIpRandom!];
const filters = new Filters({
namespace: ns,
filters: fe,
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(4);
const [
toInsideFromLabel,
fromInsideFromLabel,
fromInsideToLabel,
toInsideToLabel,
] = wl;
// NOTE: flows to current ns AND from specified ip...
expectLists(toInsideFromLabel, {
dstPod: [`${ns}/`],
srcIp: [fe[0].query],
});
// NOTE: ...OR flows from current ns AND from specified ip
expectLists(fromInsideFromLabel, {
srcPod: [`${ns}/`],
srcIp: [fe[0].query],
});
// NOTE: ...OR flows from current ns AND to specified ip...
expectLists(fromInsideToLabel, {
srcPod: [`${ns}/`],
dstIp: [fe[0].query],
});
// NOTE: ...OR flows to current ns AND to specified ip
expectLists(toInsideToLabel, { dstPod: [`${ns}/`], dstIp: [fe[0].query] });
});
const ns = 'crawler-namespace';
const ns1 = 'another-namespace';
const fe = FilterEntry.newPodSelector({
pod: 'crawler-12345',
namespace: ns,
});
test('test 14 - fromPod (same namespace)', () => {
const filters = new Filters({
namespace: ns,
filters: [fe.setDirection(FilterDirection.From)],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(2);
const [toInside, fromInside] = wl;
// NOTE: flows to current ns AND specified pod...
expectLists(toInside, {
dstPod: [`${ns}/`],
srcPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows from current ns AND specified pod
expectLists(fromInside, { srcPod: [`${ns}/${fe.query}`] });
});
test('test 15 - fromPod (different namespaces)', () => {
const filters = new Filters({
namespace: ns1,
filters: [fe.setDirection(FilterDirection.From)],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(2);
const [toInside, fromInside] = wl;
// NOTE: flows to current ns AND specified pod...
expectLists(toInside, {
dstPod: [`${ns1}/`],
srcPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows from current ns AND specified pod
expectLists(fromInside, {
srcPod: [`${ns}/${fe.query}`],
dstPod: [`${ns1}/`],
});
});
test('test 16 - toPod (same namespace)', () => {
const filters = new Filters({
namespace: ns,
filters: [fe.setDirection(FilterDirection.To)],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(2);
const [fromInside, toInside] = wl;
// NOTE: flows from current ns AND to specified pod...
expectLists(fromInside, {
srcPod: [`${ns}/`],
dstPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows to current ns AND to specified pod
expectLists(toInside, { dstPod: [`${ns}/${fe.query}`] });
});
test('test 17 - toPod (different namespaces)', () => {
const filters = new Filters({
namespace: ns1,
filters: [fe.setDirection(FilterDirection.To)],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(2);
const [fromInside, toInside] = wl;
// NOTE: flows from current ns AND to specified pod...
expectLists(fromInside, {
srcPod: [`${ns1}/`],
dstPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows to current ns AND to specified pod
expectLists(toInside, {
srcPod: [`${ns1}/`],
dstPod: [`${ns}/${fe.query}`],
});
});
test('test 18 - bothPod (same namespace)', () => {
const filters = new Filters({
namespace: ns,
filters: [fe],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(4);
const [
toInsideFromPod,
fromInsideFromPod,
fromInsideToPod,
toInsideToPod,
] = wl;
// NOTE: flows to current ns AND from specified pod...
expectLists(toInsideFromPod, {
dstPod: [`${ns}/`],
srcPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows from current ns AND from specified pod
expectLists(fromInsideFromPod, {
srcPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows from current ns AND to specified pod...
expectLists(fromInsideToPod, {
srcPod: [`${ns}/`],
dstPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows to current ns AND to specified pod
expectLists(toInsideToPod, { dstPod: [`${ns}/${fe.query}`] });
});
test('test 19 - bothPod (different namespace)', () => {
const filters = new Filters({
namespace: ns1,
filters: [fe],
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(4);
const [
toInsideFromPod,
fromInsideFromPod,
fromInsideToPod,
toInsideToPod,
] = wl;
// NOTE: flows to current ns AND from specified pod...
expectLists(toInsideFromPod, {
dstPod: [`${ns1}/`],
srcPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows from current ns AND from specified pod
expectLists(fromInsideFromPod, {
dstPod: [`${ns1}/`],
srcPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows from current ns AND to specified pod...
expectLists(fromInsideToPod, {
srcPod: [`${ns1}/`],
dstPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows to current ns AND to specified pod
expectLists(toInsideToPod, {
srcPod: [`${ns1}/`],
dstPod: [`${ns}/${fe.query}`],
});
});
test('test 19 - from/toPod (same namespace)', () => {
const fes = [
fe.setDirection(FilterDirection.From),
fe.setDirection(FilterDirection.To),
];
const filters = new Filters({
namespace: ns,
filters: fes,
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(4);
const [
toInsideFromPod,
fromInsideFromPod,
fromInsideToPod,
toInsideToPod,
] = wl;
// NOTE: flows to current ns AND from specified pod...
expectLists(toInsideFromPod, {
dstPod: [`${ns}/`],
srcPod: [`${ns}/${fes[0].query}`],
});
// NOTE: ...OR flows from current ns AND from specified pod
expectLists(fromInsideFromPod, {
srcPod: [`${ns}/${fes[0].query}`],
});
// NOTE: ...OR flows from current ns AND to specified pod...
expectLists(fromInsideToPod, {
srcPod: [`${ns}/`],
dstPod: [`${ns}/${fes[0].query}`],
});
// NOTE: ...OR flows to current ns AND to specified pod
expectLists(toInsideToPod, { dstPod: [`${ns}/${fes[0].query}`] });
});
test('test 20 - from/toPod (different namespace)', () => {
const fes = [
fe.setDirection(FilterDirection.From),
fe.setDirection(FilterDirection.To),
];
const filters = new Filters({
namespace: ns1,
filters: fes,
});
const [wl] = EventStream.buildFlowFilters(filters);
expect(wl.length).toBe(4);
const [
toInsideFromPod,
fromInsideFromPod,
fromInsideToPod,
toInsideToPod,
] = wl;
// NOTE: flows to current ns AND from specified pod...
expectLists(toInsideFromPod, {
dstPod: [`${ns1}/`],
srcPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows from current ns AND from specified pod
expectLists(fromInsideFromPod, {
dstPod: [`${ns1}/`],
srcPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows from current ns AND to specified pod...
expectLists(fromInsideToPod, {
srcPod: [`${ns1}/`],
dstPod: [`${ns}/${fe.query}`],
});
// NOTE: ...OR flows to current ns AND to specified pod
expectLists(toInsideToPod, {
srcPod: [`${ns1}/`],
dstPod: [`${ns}/${fe.query}`],
});
});
}); | the_stack |
import * as React from 'react';
import * as ReactDom from 'react-dom';
import * as strings from 'contentQueryStrings';
import { Version, Text, Log } from '@microsoft/sp-core-library';
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import { IPropertyPaneConfiguration, IPropertyPaneField } from "@microsoft/sp-property-pane";
import { IPropertyPaneTextFieldProps, PropertyPaneTextField } from "@microsoft/sp-property-pane";
import { IPropertyPaneChoiceGroupProps, PropertyPaneChoiceGroup } from "@microsoft/sp-property-pane";
import { } from "@microsoft/sp-webpart-base";
import { IPropertyPaneToggleProps, PropertyPaneToggle } from "@microsoft/sp-property-pane";
import { IPropertyPaneLabelProps, PropertyPaneLabel } from "@microsoft/sp-property-pane";
import { IPropertyPaneButtonProps, PropertyPaneButton, PropertyPaneButtonType } from "@microsoft/sp-property-pane";
import { update, get, isEmpty } from '@microsoft/sp-lodash-subset';
import { IDropdownOption, IPersonaProps, ITag } from 'office-ui-fabric-react';
import ContentQuery from './components/ContentQuery';
import { IContentQueryProps } from './components/IContentQueryProps';
import { IQuerySettings } from './components/IQuerySettings';
import { IContentQueryTemplateContext } from './components/IContentQueryTemplateContext';
import { IContentQueryWebPartProps } from './IContentQueryWebPartProps';
import { PropertyPaneAsyncDropdown } from '../../controls/PropertyPaneAsyncDropdown/PropertyPaneAsyncDropdown';
import { PropertyPaneQueryFilterPanel } from '../../controls/PropertyPaneQueryFilterPanel/PropertyPaneQueryFilterPanel';
import { PropertyPaneAsyncChecklist } from '../../controls/PropertyPaneAsyncChecklist/PropertyPaneAsyncChecklist';
import { PropertyPaneTextDialog } from '../../controls/PropertyPaneTextDialog/PropertyPaneTextDialog';
import { IQueryFilterField } from '../../controls/PropertyPaneQueryFilterPanel/components/QueryFilter/IQueryFilterField';
import { IChecklistItem } from '../../controls/PropertyPaneAsyncChecklist/components/AsyncChecklist/IChecklistItem';
import { ContentQueryService } from '../../common/services/ContentQueryService';
import { IContentQueryService } from '../../common/services/IContentQueryService';
import { ContentQueryConstants } from '../../common/constants/ContentQueryConstants';
import { IDynamicDataPropertyDefinition } from '@microsoft/sp-dynamic-data';
import { IDynamicDataCallables } from '@microsoft/sp-dynamic-data';
import { IDynamicItem } from '../../common/dataContracts/IDynamicItem';
import { ThemeProvider, ThemeChangedEventArgs, IReadonlyTheme } from '@microsoft/sp-component-base';
//import { Providers, SharePointProvider, TemplateHelper } from '@microsoft/mgt';
export default class ContentQueryWebPart
extends BaseClientSideWebPart<IContentQueryWebPartProps>
implements IDynamicDataCallables {
private readonly logSource = "ContentQueryWebPart.ts";
/***************************************************************************
* Dynamic Data private members
***************************************************************************/
private selectedItem: IDynamicItem;
/***************************************************************************
* Service used to perform REST calls
***************************************************************************/
private ContentQueryService: IContentQueryService;
/***************************************************************************
* Support for theme variants
***************************************************************************/
private _themeProvider: ThemeProvider;
private _themeVariant: IReadonlyTheme | undefined;
/***************************************************************************
* Custom ToolPart Property Panes
***************************************************************************/
private siteUrlDropdown: PropertyPaneAsyncDropdown;
private webUrlDropdown: PropertyPaneAsyncDropdown;
private listTitleDropdown: PropertyPaneAsyncDropdown;
private orderByDropdown: PropertyPaneAsyncDropdown;
private orderByDirectionChoiceGroup: IPropertyPaneField<IPropertyPaneChoiceGroupProps>;
private limitEnabledToggle: IPropertyPaneField<IPropertyPaneToggleProps>;
private itemLimitTextField: IPropertyPaneField<IPropertyPaneTextFieldProps>;
private recursiveEnabledToggle: IPropertyPaneField<IPropertyPaneToggleProps>;
private filtersPanel: PropertyPaneQueryFilterPanel;
private itemSelectorButton: IPropertyPaneField<IPropertyPaneButtonProps>;
private itemSelectorButtonDescriptionLabel: IPropertyPaneField<IPropertyPaneLabelProps>;
private viewFieldsChecklist: PropertyPaneAsyncChecklist;
private templateTextDialog: PropertyPaneTextDialog;
private templateUrlTextField: IPropertyPaneField<IPropertyPaneTextFieldProps>;
private externalScripts: IPropertyPaneField<IPropertyPaneTextFieldProps>;
/***************************************************************************
* Returns the WebPart's version
***************************************************************************/
protected get dataVersion(): Version {
return Version.parse('1.0.11');
}
/***************************************************************************
* Initializes the WebPart
***************************************************************************/
protected onInit(): Promise<void> {
// Consume the new ThemeProvider service
this._themeProvider = this.context.serviceScope.consume(ThemeProvider.serviceKey);
// If it exists, get the theme variant
this._themeVariant = this._themeProvider.tryGetTheme();
// Register a handler to be notified if the theme variant changes
this._themeProvider.themeChangedEvent.add(this, this._handleThemeChangedEvent);
return new Promise<void>((resolve, _reject) => {
this.ContentQueryService = new ContentQueryService(this.context, this.context.spHttpClient);
this.properties.webUrl = this.properties.siteUrl || this.properties.webUrl ? this.properties.webUrl : this.context.pageContext.web.absoluteUrl.toLocaleLowerCase().trim();
this.properties.siteUrl = this.properties.siteUrl ? this.properties.siteUrl : this.context.pageContext.site.absoluteUrl.toLowerCase().trim();
// Mark the dynamic data disabled
this.properties.itemSelectorEnabled = false;
// Mark the ID field as not forcibly added
this.properties.idFieldForciblyAdded = false;
// Register this web part as dynamic data source
this.context.dynamicDataSourceManager.initializeSource(this);
// Select a dummy item
this.selectedItem = { webUrl: '', listId: '', itemId: -1 };
resolve();
});
}
/***************************************************************************
* Renders the WebPart
***************************************************************************/
public render(): void {
let querySettings: IQuerySettings = {
webUrl: this.properties.webUrl,
listId: this.properties.listId,
limitEnabled: this.properties.limitEnabled,
itemLimit: this.properties.itemLimit,
recursiveEnabled: this.properties.recursiveEnabled,
orderBy: this.properties.orderBy,
orderByDirection: this.properties.orderByDirection,
filters: this.properties.filters,
viewFields: this.properties.viewFields,
};
// Enable MGT support only if required
if (this.properties.enableMGT)
{
// Add MGT dependencies
const MGT:any = require('@microsoft/mgt');
// We only need to re-register the SharePoint provider if we didn't register it before
if (MGT.Providers.globalProvider === undefined) {
// Register the SharePoint provider
MGT.Providers.globalProvider = new MGT.SharePointProvider(this.context);
}
// Make sure that the custom binding syntax is enabled
// we do this because we don't want the standard MGT template binding ( {{ }} ) to interfere with handlebars syntax
MGT.TemplateHelper.setBindingSyntax('[[', ']]');
}
const element: React.ReactElement<IContentQueryProps> = React.createElement(ContentQuery,
{
onLoadTemplate: this.loadTemplate.bind(this),
onLoadTemplateContext: this.loadTemplateContext.bind(this),
onSelectedItem: this.onSelectedItem.bind(this),
siteUrl: this.properties.siteUrl,
querySettings: querySettings,
templateText: this.properties.templateText,
templateUrl: this.properties.templateUrl,
wpContext: this.context,
externalScripts: this.properties.externalScripts ? this.properties.externalScripts.split('\n').filter((script) => { return (script && script.trim() != ''); }) : null,
strings: strings.contentQueryStrings,
stateKey: new Date().toString(),
themeVariant: this._themeVariant
}
);
ReactDom.render(element, this.domElement);
}
/***************************************************************************
* Loads the toolpart configuration
***************************************************************************/
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
let firstCascadingLevelDisabled = !this.properties.siteUrl;
let secondCascadingLevelDisabled = !this.properties.siteUrl || !this.properties.webUrl;
let thirdCascadingLevelDisabled = !this.properties.siteUrl || !this.properties.webUrl || !this.properties.listId;
// Creates a custom PropertyPaneAsyncDropdown for the siteUrl property
this.siteUrlDropdown = new PropertyPaneAsyncDropdown(ContentQueryConstants.propertySiteUrl, {
label: strings.SiteUrlFieldLabel,
loadingLabel: strings.SiteUrlFieldLoadingLabel,
errorLabelFormat: strings.SiteUrlFieldLoadingError,
loadOptions: this.loadSiteUrlOptions.bind(this),
onPropertyChange: this.onCustomPropertyPaneChange.bind(this),
selectedKey: this.properties.siteUrl || ""
});
// Creates a custom PropertyPaneAsyncDropdown for the webUrl property
this.webUrlDropdown = new PropertyPaneAsyncDropdown(ContentQueryConstants.propertyWebUrl, {
label: strings.WebUrlFieldLabel,
loadingLabel: strings.WebUrlFieldLoadingLabel,
errorLabelFormat: strings.WebUrlFieldLoadingError,
loadOptions: this.loadWebUrlOptions.bind(this),
onPropertyChange: this.onCustomPropertyPaneChange.bind(this),
selectedKey: this.properties.webUrl || "",
disabled: firstCascadingLevelDisabled
});
// Creates a custom PropertyPaneAsyncDropdown for the listId property
this.listTitleDropdown = new PropertyPaneAsyncDropdown(ContentQueryConstants.propertyListId, {
label: strings.ListTitleFieldLabel,
loadingLabel: strings.ListTitleFieldLoadingLabel,
errorLabelFormat: strings.ListTitleFieldLoadingError,
loadOptions: this.loadListTitleOptions.bind(this),
onPropertyChange: this.onCustomPropertyPaneChange.bind(this),
selectedKey: this.properties.listId || "",
disabled: secondCascadingLevelDisabled
});
// Creates a custom PropertyPaneAsyncDropdown for the orderBy property
this.orderByDropdown = new PropertyPaneAsyncDropdown(ContentQueryConstants.propertyOrderBy, {
label: strings.OrderByFieldLabel,
loadingLabel: strings.OrderByFieldLoadingLabel,
errorLabelFormat: strings.OrderByFieldLoadingError,
loadOptions: this.loadOrderByOptions.bind(this),
onPropertyChange: this.onCustomPropertyPaneChange.bind(this),
selectedKey: this.properties.orderBy || "",
disabled: thirdCascadingLevelDisabled
});
// Creates a custom PropertyPaneQueryFilterPanel for the filters property
this.filtersPanel = new PropertyPaneQueryFilterPanel(ContentQueryConstants.propertyFilters, {
filters: this.properties.filters,
loadFields: this.loadFilterFields.bind(this),
onLoadTaxonomyPickerSuggestions: this.loadTaxonomyPickerSuggestions.bind(this),
onLoadPeoplePickerSuggestions: this.loadPeoplePickerSuggestions.bind(this),
onPropertyChange: this.onCustomPropertyPaneChange.bind(this),
trimEmptyFiltersOnChange: true,
disabled: thirdCascadingLevelDisabled,
strings: strings.queryFilterPanelStrings
});
this.itemSelectorButton = PropertyPaneButton("", {
text: !this.properties.itemSelectorEnabled ? strings.ConfigureItemSelectorLabel : strings.ClearItemSelectorLabel,
buttonType: PropertyPaneButtonType.Normal,
onClick: this.toggleItemSelector.bind(this)
});
this.itemSelectorButtonDescriptionLabel = PropertyPaneLabel("", {
text: !this.properties.itemSelectorEnabled ? strings.ConfigureItemSelectorDescriptionLabel : strings.ClearItemSelectorDescriptionLabel
});
// Creates a custom PropertyPaneAsyncChecklist for the viewFields property
this.viewFieldsChecklist = new PropertyPaneAsyncChecklist(ContentQueryConstants.propertyViewFields, {
loadItems: this.loadViewFieldsChecklistItems.bind(this),
checkedItems: this.properties.viewFields,
onPropertyChange: this.onCustomPropertyPaneChange.bind(this),
disable: thirdCascadingLevelDisabled,
strings: strings.viewFieldsChecklistStrings
});
// Creates a custom PropertyPaneTextDialog for the templateText property
this.templateTextDialog = new PropertyPaneTextDialog(ContentQueryConstants.propertyTemplateText, {
dialogTextFieldValue: this.properties.templateText,
onPropertyChange: this.onCustomPropertyPaneChange.bind(this),
disabled: false,
strings: strings.templateTextStrings
});
// Creates a PropertyPaneChoiceGroup for the orderByDirection property
this.orderByDirectionChoiceGroup = PropertyPaneChoiceGroup(ContentQueryConstants.propertOrderByDirection, {
options: [
{ text: strings.ShowItemsAscending, key: 'asc', checked: !this.properties.orderByDirection || this.properties.orderByDirection == 'asc', disabled: secondCascadingLevelDisabled },
{ text: strings.ShowItemsDescending, key: 'desc', checked: this.properties.orderByDirection == 'desc', disabled: secondCascadingLevelDisabled }
]
});
// Creates a PropertyPaneTextField for the templateUrl property
this.templateUrlTextField = PropertyPaneTextField(ContentQueryConstants.propertyTemplateUrl, {
label: strings.TemplateUrlFieldLabel,
placeholder: strings.TemplateUrlPlaceholder,
deferredValidationTime: 500,
onGetErrorMessage: this.onTemplateUrlChange.bind(this)
});
// Creates a PropertyPaneToggle for the limitEnabled property
this.limitEnabledToggle = PropertyPaneToggle(ContentQueryConstants.propertyLimitEnabled, {
label: strings.LimitEnabledFieldLabel,
offText: 'Disabled',
onText: 'Enabled',
checked: this.properties.limitEnabled,
disabled: thirdCascadingLevelDisabled
});
// Creates a PropertyPaneTextField for the itemLimit property
this.itemLimitTextField = PropertyPaneTextField(ContentQueryConstants.propertyItemLimit, {
deferredValidationTime: 500,
placeholder: strings.ItemLimitPlaceholder,
disabled: !this.properties.limitEnabled || secondCascadingLevelDisabled,
onGetErrorMessage: this.onItemLimitChange.bind(this)
});
// Creates a PropertyPaneToggle for the limitEnabled property
this.recursiveEnabledToggle = PropertyPaneToggle(ContentQueryConstants.propertyRecursiveEnabled, {
label: strings.RecursiveEnabledFieldLabel,
offText: 'Disabled',
onText: 'Enabled',
checked: this.properties.recursiveEnabled,
disabled: thirdCascadingLevelDisabled
});
// Creates a PropertyPaneTextField for the externalScripts property
this.externalScripts = PropertyPaneTextField(ContentQueryConstants.propertyExternalScripts, {
label: strings.ExternalScriptsLabel,
deferredValidationTime: 500,
placeholder: strings.ExternalScriptsPlaceholder,
multiline: true,
rows: 5,
onGetErrorMessage: () => { return ''; }
});
return {
pages: [
{
header: { description: strings.WebPartDescription },
displayGroupsAsAccordion: true,
groups: [
{
groupName: strings.SourceGroupName,
groupFields: [
PropertyPaneLabel(ContentQueryConstants.propertySiteUrl, {
text: strings.SourcePageDescription
}),
this.siteUrlDropdown,
this.webUrlDropdown,
this.listTitleDropdown
]
},
{
groupName: strings.QueryGroupName,
groupFields: [
PropertyPaneLabel(ContentQueryConstants.propertyOrderBy, {
text: strings.QueryPageDescription
}),
this.orderByDropdown,
this.orderByDirectionChoiceGroup,
this.limitEnabledToggle,
this.itemLimitTextField,
this.recursiveEnabledToggle,
this.filtersPanel
]
},
{
groupName: strings.DisplayGroupName,
groupFields: [
PropertyPaneLabel(ContentQueryConstants.propertyViewFields, {
text: strings.DisplayPageDescription
}),
this.viewFieldsChecklist,
this.itemSelectorButton,
this.itemSelectorButtonDescriptionLabel,
this.templateTextDialog,
this.templateUrlTextField
]
},
{
groupName: strings.ExternalGroupName,
groupFields: [
PropertyPaneLabel(ContentQueryConstants.propertyExternalScripts, {
text: strings.ExternalPageDescription
}),
this.externalScripts,
PropertyPaneToggle("enableMGT", {
label: "Microsoft Graph Toolkit support",
checked: this.properties.enableMGT,
offText: "Disabled",
onText: "Enabled"
})
]
}
]
}
]
};
}
private toggleItemSelector(oldValue: boolean): any {
let viewFields: string[] = this.properties.viewFields;
console.log(viewFields);
// If the WebPart is not configured to render the Dynamic Data
if (!this.properties.itemSelectorEnabled) {
// Enable the dynamic data selector
this.properties.itemSelectorEnabled = true;
// Add the ID field if it is not already included in the list of selected fields
if (viewFields != null && viewFields.indexOf('ID') < 0) {
// Add the ID field
viewFields.push('ID');
// Mark the ID field as forcibly added
this.properties.idFieldForciblyAdded = true;
}
else if (viewFields == null) {
// Initialize the array of fields
viewFields = ['ID'];
// Mark the ID field as forcibly added
this.properties.idFieldForciblyAdded = true;
}
}
// If the Web Part is configured to render the Dynamic Data
else if (this.properties.itemSelectorEnabled) {
// Disable the dynamic data selector
this.properties.itemSelectorEnabled = false;
// If the ID field was forcibly added, try to remove it
if (this.properties.idFieldForciblyAdded) {
if (viewFields != null) {
let idFieldIndex = viewFields.indexOf('ID');
// If the ID field is in the list of view fields
if (idFieldIndex >= 0) {
// Remove the ID field
viewFields.splice(idFieldIndex);
// Mark the ID field as not forcibly added
this.properties.idFieldForciblyAdded = false;
}
}
}
}
// Refresh the view fields property
this.onCustomPropertyPaneChange(ContentQueryConstants.propertyViewFields, viewFields);
// Redraw the property pane
this.context.propertyPane.refresh();
console.log(this.properties);
}
/***************************************************************************
* Loads the HandleBars template from the specified url
***************************************************************************/
private loadTemplate(templateUrl: string): Promise<string> {
return this.ContentQueryService.getFileContent(templateUrl);
}
/***************************************************************************
* Loads the HandleBars context based on the specified query
***************************************************************************/
private loadTemplateContext(querySettings: IQuerySettings, callTimeStamp: number): Promise<IContentQueryTemplateContext> {
return this.ContentQueryService.getTemplateContext(querySettings, callTimeStamp);
}
/***************************************************************************
* Loads the dropdown options for the webUrl property
***************************************************************************/
private loadSiteUrlOptions(): Promise<IDropdownOption[]> {
return this.ContentQueryService.getSiteUrlOptions();
}
/***************************************************************************
* Loads the dropdown options for the webUrl property
***************************************************************************/
private loadWebUrlOptions(): Promise<IDropdownOption[]> {
return this.ContentQueryService.getWebUrlOptions(this.properties.siteUrl);
}
/***************************************************************************
* Loads the dropdown options for the listTitle property
***************************************************************************/
private loadListTitleOptions(): Promise<IDropdownOption[]> {
return this.ContentQueryService.getListTitleOptions(this.properties.webUrl);
}
/***************************************************************************
* Loads the dropdown options for the orderBy property
***************************************************************************/
private loadOrderByOptions(): Promise<IDropdownOption[]> {
return this.ContentQueryService.getOrderByOptions(this.properties.webUrl, this.properties.listId);
}
/***************************************************************************
* Loads the dropdown options for the listTitle property
***************************************************************************/
private loadFilterFields(): Promise<IQueryFilterField[]> {
return this.ContentQueryService.getFilterFields(this.properties.webUrl, this.properties.listId);
}
/***************************************************************************
* Loads the checklist items for the viewFields property
***************************************************************************/
private loadViewFieldsChecklistItems(): Promise<IChecklistItem[]> {
return this.ContentQueryService.getViewFieldsChecklistItems(this.properties.webUrl, this.properties.listId);
}
/***************************************************************************
* Returns the user suggestions based on the user entered picker input
* @param filterText : The filter specified by the user in the people picker
* @param currentPersonas : The IPersonaProps already selected in the people picker
* @param limitResults : The results limit if any
***************************************************************************/
private loadPeoplePickerSuggestions(filterText: string, currentPersonas: IPersonaProps[], limitResults?: number): Promise<IPersonaProps[]> {
return this.ContentQueryService.getPeoplePickerSuggestions(this.properties.webUrl, filterText, currentPersonas, limitResults);
}
/***************************************************************************
* Returns the taxonomy suggestions based on the user entered picker input
* @param field : The taxonomy field from which to load the terms from
* @param filterText : The filter specified by the user in the people picker
* @param currentPersonas : The IPersonaProps already selected in the people picker
* @param limitResults : The results limit if any
***************************************************************************/
private loadTaxonomyPickerSuggestions(field: IQueryFilterField, filterText: string, currentTerms: ITag[]): Promise<ITag[]> {
return this.ContentQueryService.getTaxonomyPickerSuggestions(this.properties.webUrl, this.properties.listId, field, filterText, currentTerms);
}
/***************************************************************************
* When a custom property pane updates
***************************************************************************/
private onCustomPropertyPaneChange(propertyPath: string, newValue: any): void {
Log.verbose(this.logSource, "WebPart property '" + propertyPath + "' has changed, refreshing WebPart...", this.context.serviceScope);
let rerenderTemplateTextDialog = false;
const oldValue = get(this.properties, propertyPath);
// Stores the new value in web part properties
update(this.properties, propertyPath, (): any => { return newValue; });
this.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue);
// Resets dependent property panes if needed
this.resetDependentPropertyPanes(propertyPath);
// If the viewfields have changed, update the default template text if it hasn't been altered by the user
if (propertyPath == ContentQueryConstants.propertyViewFields && !this.properties.hasDefaultTemplateBeenUpdated) {
let generatedTemplate = this.ContentQueryService.generateDefaultTemplate(newValue, this.properties.itemSelectorEnabled);
update(this.properties, ContentQueryConstants.propertyTemplateText, (): any => { return generatedTemplate; });
this.templateTextDialog.properties.dialogTextFieldValue = generatedTemplate;
rerenderTemplateTextDialog = true;
}
// If the templateText have changed, update the "hasDefaultTemplateBeenUpdated" to true so the WebPart doesn't override the user template after updating view fields
if (propertyPath == ContentQueryConstants.propertyTemplateText && !this.properties.hasDefaultTemplateBeenUpdated) {
update(this.properties, ContentQueryConstants.propertyhasDefaultTemplateBeenUpdated, (): any => { return true; });
}
// Refreshes the web part manually because custom fields don't update since sp-webpart-base@1.1.1
// https://github.com/SharePoint/sp-dev-docs/issues/594
if (!this.disableReactivePropertyChanges)
this.render();
if (rerenderTemplateTextDialog) {
this.templateTextDialog.render();
}
}
/***************************************************************************
* Validates the templateUrl property
***************************************************************************/
private onTemplateUrlChange(value: string): Promise<String> {
Log.verbose(this.logSource, "WebPart property 'templateUrl' has changed, refreshing WebPart...", this.context.serviceScope);
return new Promise<string>((resolve, reject) => {
// Doesn't raise any error if file is empty (otherwise error message will show on initial load...)
if (isEmpty(value)) {
resolve('');
}
// Resolves an error if the file isn't a valid .htm or .html file
else if (!this.ContentQueryService.isValidTemplateFile(value)) {
resolve(strings.ErrorTemplateExtension);
}
// Resolves an error if the file doesn't answer a simple head request
else {
this.ContentQueryService.ensureFileResolves(value).then((isFileResolving: boolean) => {
resolve('');
})
.catch((error) => {
resolve(Text.format(strings.ErrorTemplateResolve, error));
});
}
});
}
/***************************************************************************
* Validates the itemLimit property
***************************************************************************/
private onItemLimitChange(value: string): Promise<String> {
Log.verbose(this.logSource, "WebPart property 'itemLimit' has changed, refreshing WebPart...", this.context.serviceScope);
return new Promise<string>((resolve, reject) => {
// Resolves an error if the file isn't a valid number between 1 to 999
let parsedValue = parseInt(value);
let isNumeric = !isNaN(parsedValue) && isFinite(parsedValue);
let isValid = (isNumeric && parsedValue >= 1 && parsedValue <= 999) || isEmpty(value);
resolve(!isValid ? strings.ErrorItemLimit : '');
});
}
/***************************************************************************
* Resets dependent property panes if needed
***************************************************************************/
private resetDependentPropertyPanes(propertyPath: string): void {
if (propertyPath == ContentQueryConstants.propertySiteUrl) {
this.resetWebUrlPropertyPane();
this.resetListTitlePropertyPane();
this.resetOrderByPropertyPane();
this.resetFiltersPropertyPane();
this.resetViewFieldsPropertyPane();
}
else if (propertyPath == ContentQueryConstants.propertyWebUrl) {
this.resetListTitlePropertyPane();
this.resetOrderByPropertyPane();
this.resetFiltersPropertyPane();
this.resetViewFieldsPropertyPane();
}
else if (propertyPath == ContentQueryConstants.propertyListId) {
this.resetOrderByPropertyPane();
this.resetFiltersPropertyPane();
this.resetViewFieldsPropertyPane();
}
}
/***************************************************************************
* Resets the List Title property pane and re-renders it
***************************************************************************/
private resetWebUrlPropertyPane() {
Log.verbose(this.logSource, "Resetting 'webUrl' property...", this.context.serviceScope);
this.properties.webUrl = "";
this.ContentQueryService.clearCachedWebUrlOptions();
update(this.properties, ContentQueryConstants.propertyWebUrl, (): any => { return this.properties.webUrl; });
this.webUrlDropdown.properties.selectedKey = "";
this.webUrlDropdown.properties.disabled = isEmpty(this.properties.siteUrl);
this.webUrlDropdown.render();
}
/***************************************************************************
* Resets the List Title property pane and re-renders it
***************************************************************************/
private resetListTitlePropertyPane() {
Log.verbose(this.logSource, "Resetting 'listTitle' property...", this.context.serviceScope);
this.properties.listId = null;
this.ContentQueryService.clearCachedListTitleOptions();
update(this.properties, ContentQueryConstants.propertyListId, (): any => { return this.properties.listId; });
this.listTitleDropdown.properties.selectedKey = "";
this.listTitleDropdown.properties.disabled = isEmpty(this.properties.webUrl);
this.listTitleDropdown.render();
}
/***************************************************************************
* Resets the Filters property pane and re-renders it
***************************************************************************/
private resetOrderByPropertyPane() {
Log.verbose(this.logSource, "Resetting 'orderBy' property...", this.context.serviceScope);
this.properties.orderBy = null;
this.ContentQueryService.clearCachedOrderByOptions();
update(this.properties, ContentQueryConstants.propertyOrderBy, (): any => { return this.properties.orderBy; });
this.orderByDropdown.properties.selectedKey = "";
this.orderByDropdown.properties.disabled = isEmpty(this.properties.webUrl) || isEmpty(this.properties.listId);
this.orderByDropdown.render();
}
/***************************************************************************
* Resets the Filters property pane and re-renders it
***************************************************************************/
private resetFiltersPropertyPane() {
Log.verbose(this.logSource, "Resetting 'filters' property...", this.context.serviceScope);
this.properties.filters = null;
this.ContentQueryService.clearCachedFilterFields();
update(this.properties, ContentQueryConstants.propertyFilters, (): any => { return this.properties.filters; });
this.filtersPanel.properties.filters = null;
this.filtersPanel.properties.disabled = isEmpty(this.properties.webUrl) || isEmpty(this.properties.listId);
this.filtersPanel.render();
}
/***************************************************************************
* Resets the View Fields property pane and re-renders it
***************************************************************************/
private resetViewFieldsPropertyPane() {
Log.verbose(this.logSource, "Resetting 'viewFields' property...", this.context.serviceScope);
this.properties.viewFields = null;
this.ContentQueryService.clearCachedViewFields();
update(this.properties, ContentQueryConstants.propertyViewFields, (): any => { return this.properties.viewFields; });
this.viewFieldsChecklist.properties.checkedItems = null;
this.viewFieldsChecklist.properties.disable = isEmpty(this.properties.webUrl) || isEmpty(this.properties.listId);
this.viewFieldsChecklist.render();
}
/***************************************************************************
* Provides the source dynamic properties
***************************************************************************/
public getPropertyDefinitions(): ReadonlyArray<IDynamicDataPropertyDefinition> {
return [
{
id: 'selectedItem',
title: 'Selected Item'
}
];
}
/***************************************************************************
* Returns the value of the selected item for a Dynamic Data consumer
***************************************************************************/
public getPropertyValue(propertyId: string): IDynamicItem {
switch (propertyId) {
case 'selectedItem':
return this.selectedItem;
}
throw new Error('Unsupported property id');
}
/***************************************************************************
* Notifies to a Dynamic Data consumer that the selected item changed
***************************************************************************/
private onSelectedItem = (selectedItem: IDynamicItem): void => {
this.selectedItem = selectedItem;
// notify that the value has changed
this.context.dynamicDataSourceManager.notifyPropertyChanged('selectedItem');
}
/***************************************************************************
* Update the current theme variant reference and re-render.
*
* @param args The new theme
***************************************************************************/
private _handleThemeChangedEvent(args: ThemeChangedEventArgs): void {
this._themeVariant = args.theme;
this.render();
}
} | the_stack |
import { observable, IObservableArray, action } from 'mobx'
import { referenceOne, referenceMany } from '.'
import { moveItem } from 'mobx-utils'
const map = require('lodash/map')
const filter = require('lodash/filter')
const find = require('lodash/find')
const some = require('lodash/some')
const every = require('lodash/every')
const reduce = require('lodash/reduce')
const chunk = require('lodash/chunk')
const forEach = require('lodash/forEach')
const orderBy = require('lodash/orderBy')
/**
* Used in various Lodash functions such as `map`, `filter`..
*/
export interface IIteratee<T, M> {
(input: T, index: number): M
}
/**
* Indexed collection used for reusing models.
*/
export interface ICollection<T> {
/**
* The actual item map.
*/
items: IObservableArray<T>
/**
* Getter for the items length.
*/
length: number
/**
* Adds one or more models to the end of the collection.
*/
add(models: T | T[]): this
/**
* Multi-version of `create`.
*/
create(data: any[], createOpts?: ICollectionOptions<T>): T[]
/**
* Like `set`, but will add regardless of whether an id is present or not.
* This has the added risk of resulting multiple model instances if you don't make sure
* to update the existing model once you do have an id. The model id is what makes the whole
* one-instance-per-entity work.
*/
create(data: any, createOpts?: ICollectionOptions<T>): T
/**
* Gets items by ids.
*/
get(id: any[]): Array<T | undefined>
/**
* Gets a item by id.
*/
get(id: any): T | undefined
/**
* Same as the singular version, but with multiple.
*/
set<D>(
data?: D[],
setOpts?: ICollectionOptions<T>
): D extends undefined ? undefined : T[]
/**
* Adds a single item and maps it using the mapper in the options.
*/
set<D>(
data?: D,
setOpts?: ICollectionOptions<T>
): D extends undefined ? undefined : T
/**
* Clears the collection.
*/
clear(): this
/**
* Maps over the items.
*/
map<M>(iteratee: IIteratee<T, M>): M[]
/**
* Filters the items.
*/
filter(iteratee: IIteratee<T, boolean>): T[]
/**
* Determines if there are any items that match the predicate.
*/
some(iteratee: IIteratee<T, boolean>): boolean
/**
* Determines if all items match the predicate.
*/
every(iteratee: IIteratee<T, boolean>): boolean
/**
* Chunks the collection.
*/
chunk(size?: number): Array<Array<T>>
/**
* Reduces on the items.
*/
reduce<R>(iteratee: IIteratee<T, R>, seed?: R): R
/**
* Finds a particular item.
*/
find(iteratee: IIteratee<T, boolean>): T | undefined
/**
* Orders the items based on iteratees and orders.
*/
orderBy(
iteratees: Array<IIteratee<T, any> | Object | string>,
orders?: Array<boolean | string>
): T[]
/**
* Removes an item based on ID or the item itself.
*/
remove(modelOrId: T | string): this
/**
* Slices the array.
*/
slice(start?: number, end?: number): T[]
/**
* Moves an item from one index to another, using MobX's `move`.
*/
move(fromIndex: number, toIndex: number): this
/**
* Returns the item at the specified index.
*/
at(index: number): T | undefined
/**
* Runs a `forEach` over the items and returns the collection.
*/
forEach(iteratee: IIteratee<T, any>): this
/**
* Given a single or list of ids and a collection with models,
* returns the model(s) the IDs represent. If `field` is specified, it
* will be used instead of the source collection model ID.
* Only the first matching model per ID is returned.
* For "one/many-to-many" type references, use `referenceMany`.
*
* @param {Array<string>} ids
* @param {keyof T} field
*/
referenceOne<K extends keyof T>(id: ModelId): T | null
referenceOne<K extends keyof T>(ids: Array<ModelId>): Array<T>
referenceOne<K extends keyof T>(id: T[K], field?: keyof T): T | null
referenceOne<K extends keyof T>(ids: Array<T[K]>, field?: keyof T): Array<T>
referenceOne<K extends keyof T>(
ids: T[K] | Array<T[K]>,
field?: keyof T
): T | null | Array<T>
/**
* Given a single or list of ids and a collection with models,
* returns the models that match `field`.
* All matching models are returned and flattened.
* For "one-to-one" type references, use `referenceOne`.
*
* @param {Array<string>} ids
* @param {keyof T} field
*/
referenceMany<K extends keyof T>(
ids: T[K] | Array<T[K]>,
field: keyof T
): Array<T>
}
/**
* Called when the collection wants to add a new item.
*/
export interface ICreateFunc<T> {
(input: any, opts: ICollectionOptions<T>): T
}
/**
* Called when the collection wants to update an existing item.
*/
export interface IUpdateFunc<T> {
(existing: T, input: any, opts: ICollectionOptions<T>): T
}
/**
* Function used for getting the ID of a particular input.
*/
export interface IGetId<T> {
// Returned value will be stringified.
(obj: T, opts: ICollectionOptions<T>): any
}
/**
* Collection options.
*/
export interface ICollectionOptions<T> {
/**
* May be used by callbacks like `getModelId` and `getDataId`
*/
idAttribute?: string
/**
* Called when the collection wants to add a new item.
*/
create?: ICreateFunc<T>
/**
* Called when the collection wants to update an existing item with more data.
*/
update?: IUpdateFunc<T>
/**
* Used to get the ID of a model that was passed in. Whatever is returned from
* this should be coercible to a string, and is used for indexing.
*/
getModelId?: IGetId<T>
/**
* Used to get an ID from input data, used to determine whether to create
* or update.
*/
getDataId?: IGetId<any>
}
/**
* Default collection options.
*/
export const defaults: ICollectionOptions<any> = {
create: (input, opts) => input,
getDataId: (input: any, opts) => input[opts.idAttribute || 'id'],
getModelId: (existing, opts) => existing[opts.idAttribute || 'id'],
idAttribute: 'id',
update: (existing, input, opts) => Object.assign(existing, input)
}
/**
* Possible model IDs.
*/
export type ModelId = string | number | Date
/**
* Creates a collection.
*
* @type {T} The item type.
* @type {O} Additional options.
*/
export function collection<T>(opts?: ICollectionOptions<T>): ICollection<T> {
opts = Object.assign({}, defaults, opts)
// Holds the actual items.
const items: IObservableArray<T> = observable.array([], { deep: false })
const idMap = new Map<string, T>()
const self = {
items,
add: action(add),
get,
set: action(set),
create: action(create),
remove: action(remove),
clear: action(clear),
filter: bindLodashFunc(items, filter),
some: bindLodashFunc(items, some),
every: bindLodashFunc(items, every),
find: bindLodashFunc(items, find),
orderBy: bindLodashFunc(items, orderBy),
map: bindLodashFunc(items, map),
reduce: bindLodashFunc(items, reduce),
chunk: bindLodashFunc(items, chunk),
referenceOne: ((ids: any, field: any): any =>
(referenceOne as any)(self, ids, field)) as any,
referenceMany: ((ids: any, field: any): any =>
(referenceMany as any)(self, ids, field)) as any,
forEach: (iteratee: IIteratee<T, any>) => {
forEach(items, iteratee)
return self
},
at: (index: number) => items[index],
slice,
move,
get length() {
return items.length
}
}
function get(id: ModelId[]): Array<T | undefined>
function get(id: ModelId): T | undefined
function get(
id: ModelId | ModelId[]
): (T | undefined) | Array<T | undefined> {
/*tslint:disable-next-line*/
if (id === undefined || id === null) {
return undefined
}
if (Array.isArray(id)) {
return id.map(get) as T[]
}
const idAsString: string = id.toString()
const fromMap = idMap.get(idAsString)
if (fromMap) {
return fromMap
}
const found = items.find(item => {
const modelId = opts!.getModelId!(item, opts!)
if (!modelId) {
return false
}
return modelId.toString() === idAsString
})
if (found !== undefined) {
idMap.set(idAsString, found)
}
return found
}
function set(data?: any[], setOpts?: ICollectionOptions<T>): T[] | undefined
function set(data?: any, setOpts?: ICollectionOptions<T>): T | undefined
function set(
data?: any | any[],
setOpts?: ICollectionOptions<T>
): T | T[] | undefined {
setOpts = Object.assign({}, opts as any, setOpts)
if (!data) {
return undefined
}
if (Array.isArray(data)) {
return data.map(d => set(d, setOpts) as T)
}
let dataId = opts!.getDataId!(data, setOpts!)
if (dataId === undefined) {
return undefined
}
if (dataId === null) {
throw new TypeError(`${dataId} is not a valid ID`)
}
dataId = dataId.toString()
let existing = get(dataId as string)
if (existing) {
opts!.update!(existing, data, Object.assign({}, opts as any, setOpts))
return existing
}
const created = opts!.create!(data, Object.assign({}, opts as any, setOpts))
// If creating this object resulted in another object with the same ID being
// added, reuse it instead of adding this new one.
existing = get(dataId as string)
if (existing) {
opts!.update!(existing, data, Object.assign({}, opts as any, setOpts))
return existing
}
items.push(created)
idMap.set(dataId, created)
return created
}
function create(data: any[], createOpts?: ICollectionOptions<T>): T[]
function create(data: any, createOpts?: ICollectionOptions<T>): T
function create(
data: any[] | any,
createOpts?: ICollectionOptions<T>
): T[] | T {
if (Array.isArray(data)) {
return data.map(d => create(d, createOpts))
}
createOpts = Object.assign({}, opts as any, createOpts)
const dataId = createOpts!.getDataId!(data, createOpts!)
if (dataId !== undefined && dataId !== null) {
return set(data, createOpts) as any
}
const created = createOpts!.create!(data, createOpts!)
add(created)
return created
}
function add(models: T | T[]): ICollection<T> {
if (!Array.isArray(models)) {
return add([models])
}
// Filter out existing models.
models = models.filter(x => items.indexOf(x) === -1)
items.push(...models)
return self
}
function remove(modelOrId: T | ModelId): ICollection<T> {
const model =
typeof modelOrId === 'string' ||
typeof modelOrId === 'number' ||
modelOrId instanceof Date
? get(modelOrId)
: modelOrId
if (!model) {
return self
}
items.remove(model)
const modelId = opts!.getModelId!(model, opts!)
/* istanbul ignore else */
if (modelId !== null && modelId !== undefined) {
idMap.delete(modelId.toString())
}
return self
}
function clear(): ICollection<T> {
items.clear()
idMap.clear()
return self
}
function slice(start?: number, end?: number) {
return items.slice(start, end)
}
function move(fromIndex: number, toIndex: number) {
moveItem(items, fromIndex, toIndex)
return self
}
return self
}
/**
* Utility for binding lodash functions.
*/
function bindLodashFunc(items: IObservableArray<any>, func: any): any {
return (...args: any[]) => func(items, ...args)
} | the_stack |
import * as angular from 'angular';
import * as _ from "underscore";
import {VisualQueryPainterService} from '../../visual-query/transform-data/visual-query-table/visual-query-painter.service';
import {DOCUMENT} from '@angular/platform-browser';
import {Component, ElementRef, HostListener, Inject, Input} from "@angular/core";
export class ActiveResize {
resizeInProgress:boolean;
headerDiv:JQuery;
headerElem:HTMLElement;
initialHeaderWidth :number;
/**
* the id of the column we are resizing
*/
columnId:string;
/**
* the start x of the resize
*/
startX:number;
/**
* resize amount
* @type {number}
*/
diff:number = 0;
/**
* the actual width of the column
*/
width:number;
/**
* Min width acceptable for the column
*/
minColWidth?:number;
constructor(private document:any){
}
start(columnId:string, seperator:JQuery, startX:number, width:number, minColWidth?:number){
this.startX = startX;
this.columnId = columnId;
this.headerDiv = seperator.parent();
this.headerElem = this.headerDiv.get(0);
this.initialHeaderWidth = this.headerElem.offsetWidth;;
this.minColWidth = minColWidth;
this.width = width;
this.headerDiv.css("z-index", "1"); //to hide other columns behind the one being resized
this.document.body.style.cursor = "col-resize";
this.diff = 0;
this.resizeInProgress = true;
}
resize(endX:number){
this.diff = endX - this.startX;
let updatedWith = this.initialHeaderWidth + this.diff;
this.width = updatedWith < this.minColWidth ? this.minColWidth : updatedWith;
this.headerElem.style.width = this.width + "px";
}
getWidth(){
return this.width;
}
stop() :number {
this.headerDiv.css("z-index", "unset");
document.body.style.cursor = null;
this.resizeInProgress = false;
this.minColWidth = undefined;
return this.getWidth();
}
isResizing(){
return this.resizeInProgress;
}
}
export class FattableOptions {
tableContainerId:string
headers: any[]
rows: any[]
minColumnWidth: number = 50
maxColumnWidth: number = 300;
rowHeight: number = 27;
headerHeight: number = 40;
headerPadding: number = 5;
padding: number = 50;
firstColumnPaddingLeft: number = 24;
headerFontFamily = "Roboto, \"Helvetica Neue\", sans-serif"
headerFontSize = "13px"
headerFontWeight = "500"
rowFontFamily = "sans-serif"
rowFontSize = "13px"
rowFontWeight = "normal"
setupRefreshDebounce:number = 300
public constructor(init?: Partial<FattableOptions>) {
Object.assign(this, init);
}
headerText(header: any) {
if(typeof header == "string"){
return header;
}
else {
return header.displayName;
}
}
cellText (row: any, column: any) {
if(typeof column =="string") {
return row[column];
}
else {
return row[column.displayName];
}
}
fillCell (cellDiv: any, data: any) {
cellDiv.innerHTML = _.escape(data.value);
}
getCellSync (i: any, j: any) {
const displayName = this.headerText(this.headers[j]) //.displayName;
const row = this.rows[i];
if (row === undefined) {
//occurs when filtering table
return undefined;
}
return {
"value": row[displayName]
}
}
fillHeader(headerDiv: any, header: any) {
headerDiv.innerHTML = _.escape(header.value);
}
getHeaderSync(j: any) {
return this.headerText(this.headers[j]);// this.headers[j].displayName;
}
}
@Component({
selector:"fattable",
template:`<div style="width:700px;height:500px;" ></div>`
})
export class FattableComponent {
ATTR_DATA_COLUMN_ID = "data-column-id";
activeResize:ActiveResize;
@Input()
options:FattableOptions;
optionDefaults: FattableOptions = new FattableOptions();
scrollXY: number[] = [];
table:fattable.TableView;
tableData:fattable.SyncTableModel = new fattable.SyncTableModel();
painter:fattable.Painter =new fattable.Painter();
settings:FattableOptions;
columnWidths:number[]
selector:string;
constructor(private ele:ElementRef, @Inject(DOCUMENT) private document: any){
this.activeResize = new ActiveResize(this.document)
}
setupTable(){
this.settings = new FattableOptions(this.options);
//add the array of column widths to the settings to populate
this.columnWidths = [];
this.populateHeaders();
this.setupPainter();
this.setupTableData();
this.createTable();
}
ngOnInit() {
this.setupTable();
}
/**
* populate the Headers with data from the settings
* @param settings
* @param {fattable.TableModel} tableData
*/
private populateHeaders(){
const headers = this.settings.headers;
const rows = this.settings.rows;
this.tableData.columnHeaders = [];
const headerContext = this.get2dContext(this.settings.headerFontWeight + " " + this.settings.headerFontSize + " " + this.settings.headerFontFamily);
const rowContext = this.get2dContext(this.settings.rowFontWeight + " " + this.settings.rowFontSize + " " + this.settings.rowFontFamily);
_.each(this.settings.headers, (column) =>{
const headerText = this.settings.headerText(column);
const headerTextWidth = headerContext.measureText(headerText).width;
const longestColumnText = _.reduce(rows, (previousMax, row) =>{
const cellText = this.settings.cellText(row, column);
const cellTextLength = cellText === undefined || cellText === null ? 0 : cellText.length;
return previousMax.length < cellTextLength ? cellText : previousMax;
}, "");
const columnTextWidth = rowContext.measureText(longestColumnText).width;
this.columnWidths.push(Math.min(this.settings.maxColumnWidth, Math.max(this.settings.minColumnWidth, headerTextWidth, columnTextWidth)) + this.settings.padding);
this.tableData.columnHeaders.push(headerText);
});
}
private get2dContext(font: any) {
const canvas = this.document.createElement("canvas");
this.document.createDocumentFragment().appendChild(canvas);
const context = canvas.getContext("2d");
context.font = font;
return context;
}
/**
* setup the painter
* @param {fattable.Painter} painter
*/
private setupPainter(){
let mousedown = (separator: JQuery, e: JQueryEventObject) => {
e.preventDefault(); //prevent default action of selecting text
const columnId = this.getColumnId(separator);
let start = 0, diff = 0, newWidth = this.settings.minColumnWidth;
if (e.pageX) {
start = e.pageX;
} else if (e.clientX) {
start = e.clientX;
}
this.activeResize.start(columnId,separator,start,newWidth,this.settings.minColumnWidth);
}
this.painter.setupHeader = (div:Element) => {
// console.log("setupHeader");
let separator = jQuery('<div class="header-separator"></div>')
let heading = jQuery('<div class="header-value ui-grid-header-cell-title"></div>')
// div.insertAdjacentHTML("afterend",heading)
let headerDiv =jQuery(div);
separator.on("mousedown", event => mousedown(separator, event));
headerDiv.append(heading).append(separator);
}
this.painter.fillCell = (div:any, data:any) =>{
if (data === undefined) {
return;
}
if (data.columnId === 0) {
div.className = " first-column ";
}
div.style.fontSize = this.settings.rowFontSize;
div.style.fontFamily = this.settings.rowFontFamily;
div.className += "layout-column layout-align-center-start ";
if (data["rowId"] % 2 === 0) {
div.className += " even ";
}
else {
div.className += " odd ";
}
this.settings.fillCell(div, data);
};
this.painter.fillHeader = (div: any, header: any) =>{
// console.log('fill header', header);
div.style.fontSize = this.settings.headerFontSize;
div.style.fontFamily = this.settings.headerFontFamily;
div.style.fontWeight = this.settings.headerFontWeight;
const children = jQuery(div).children();
this.setColumnId(children.last(), header.id);
const valueDiv = children.first();
valueDiv.css("width", (this.table.columnWidths[header.id] - this.settings.headerPadding - 2) + "px"); //leave 2 pixels for column separator
const valueSpan = valueDiv.get(0);
this.settings.fillHeader(valueSpan, header);
};
}
setupTableData(){
this.tableData.getCellSync = (i: any, j: any) => {
let data :any = this.settings.getCellSync(i, j);
if (data !== undefined) {
//add row id so that we can add odd/even classes to rows
data.rowId = i;
data.columnId = j;
}
return data;
};
this.tableData.getHeaderSync = (j: number) =>{
const header = this.settings.getHeaderSync(j);
return {
value: header,
id: j
};
};
}
@HostListener('document:mousemove', ['$event'])
onMouseMove(e:MouseEvent) {
if(this.activeResize.isResizing()) {
let end = 0;
if (e.pageX) {
end = e.pageX;
} else if (e.clientX) {
end = e.clientX;
}
this.activeResize.resize(end);
}
}
@HostListener('document:mouseup', ['$event'])
onMouseUp(e:MouseEvent) {
// document.body.onmousemove = document.body.onmouseup = null;
if(this.activeResize.isResizing()) {
let columnId = this.activeResize.columnId;
let newWidth = this.activeResize.stop();
this.resizeColumn(columnId, newWidth);
}
}
private resizeColumn(columnId: string, columnWidth: number) {
const x = this.scrollXY[0];
const y = this.scrollXY[1];
// console.log('resize to new width', columnWidth);
this.table.columnWidths[columnId] = columnWidth;
const columnOffset = _.reduce((this.table.columnWidths as number[]), function (memo, width) {
memo.push(memo[memo.length - 1] + width);
return memo;
}, [0]);
// console.log('columnWidths, columnOffset', columnWidths, columnOffset);
this.table.columnOffset = columnOffset;
// this.table.W = columnOffset[columnOffset.length - 1];
this.table.setup();
// console.log('displaying cells', scrolledCellX, scrolledCellY);
// this.table.scroll.setScrollXY(x, y); //table.setup() scrolls to 0,0, here we scroll back to were we were while resizing column
}
createTable() {
if(this.settings.tableContainerId == undefined){
this.settings.tableContainerId = _.uniqueId("fattable-");
}
this.ele.nativeElement.id = this.settings.tableContainerId
this.selector = "#" + this.settings.tableContainerId;
const parameters = {
"container": this.selector,
"model": this.tableData,
"nbRows": this.settings.rows.length,
"rowHeight": this.settings.rowHeight,
"headerHeight": this.settings.headerHeight,
"painter": this.painter,
"columnWidths": this.columnWidths
};
let onScroll = (x: number, y: number) =>{
this.scrollXY[0] = x;
this.scrollXY[1] = y;
}
this.table = fattable(parameters);
this.table.onScroll = onScroll;
this.table.setup();
}
private getColumnId(separatorSpan: JQuery) {
return separatorSpan.attr(this.ATTR_DATA_COLUMN_ID);
}
private setColumnId(separatorSpan: JQuery, id: string) {
separatorSpan.attr(this.ATTR_DATA_COLUMN_ID, id);
}
private registerEvents(){
const eventId = "resize.fattable." + this.settings.tableContainerId;
jQuery( this.getWindow()).unbind(eventId);
jQuery( this.getWindow()).on(eventId, () =>{
_.debounce(this.setupTable, this.settings.setupRefreshDebounce)
});
jQuery(this.selector).on('$destroy', ()=> {
jQuery(this.getWindow()).unbind(eventId);
});
}
private getWindow(){
return window;
}
} | the_stack |
import { RequestUtil } from "mesosphere-shared-reactjs";
import { request } from "@dcos/http-service";
import Config from "#SRC/js/config/Config";
import getFixtureResponses from "#SRC/js/utils/getFixtureResponses";
import PrivatePluginsConfig from "../../PrivatePluginsConfig";
import * as ActionTypes from "../constants/ActionTypes";
import SDK from "PluginSDK";
function isFile(value) {
return value instanceof File;
}
const SecretActions = {
fetchSealStatus(storeName) {
RequestUtil.json({
url: `${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/seal-status/${storeName}`,
success(response) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_SEAL_STATUS_SUCCESS,
data: response,
});
},
error(xhr) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_SEAL_STATUS_ERROR,
data: RequestUtil.getErrorFromXHR(xhr),
});
},
});
},
fetchSecret(storeName, secretPath) {
const url = `${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/secret/${storeName}/${secretPath}`;
request(url, {
headers: { Accept: "*/*" },
responseType: "text",
}).subscribe({
next: ({ response, responseHeaders }) => {
let data;
const contentType = responseHeaders["content-type"];
if (contentType === "application/json") {
data = JSON.parse(response);
} else {
// File based secret
try {
data = new File(response.split("\n"), "secret");
} catch (e) {
// Some browsers don't support the file api, we leave the data empty
data = null;
}
}
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_SECRET_SUCCESS,
data,
storeName,
secretPath,
contentType,
});
},
error: (event) => {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_SECRET_ERROR,
data: event,
storeName,
secretPath,
});
},
});
},
createSecret(storeName, path, value) {
const encodedPath = encodeURIComponent(path);
const body = isFile(value)
? value
: JSON.stringify({ path: encodedPath, value });
request(
`${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/secret/${storeName}/${path}`,
{
headers: {
Accept: "application/json",
"Content-Type": isFile(value)
? "application/octet-stream"
: "application/json",
},
method: "PUT",
body,
}
).subscribe({
next: (event) => {
const data = JSON.parse(event.response);
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_CREATE_SECRET_SUCCESS,
data,
});
},
error: (event) => {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_CREATE_SECRET_ERROR,
data: event,
});
},
});
},
updateSecret(storeName, path, value) {
const encodedPath = encodeURIComponent(path);
const body = isFile(value)
? value
: JSON.stringify({ path: encodedPath, value });
request(
`${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/secret/${storeName}/${path}`,
{
headers: {
Accept: "application/json",
"Content-Type": isFile(value)
? "application/octet-stream"
: "application/json",
},
method: "PATCH",
body,
}
).subscribe({
next: (event) => {
let data;
try {
data = JSON.parse(event.response);
} catch (exception) {
data = event.response;
}
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_UPDATE_SECRET_SUCCESS,
data,
});
},
error: (event) => {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_UPDATE_SECRET_ERROR,
data: event,
});
},
});
},
deleteSecret(storeName, secretPath) {
RequestUtil.json({
url: `${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/secret/${storeName}/${secretPath}`,
method: "DELETE",
success(response) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_DELETE_SECRET_SUCCESS,
data: response,
});
},
error(xhr) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_DELETE_SECRET_ERROR,
data: RequestUtil.getErrorFromXHR(xhr),
});
},
});
},
fetchSecrets(storeName, secretPath = "") {
RequestUtil.json({
url: `${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/secret/${storeName}/${secretPath}?list=true`,
success(response) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_SECRETS_SUCCESS,
data: response,
});
},
error(xhr) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_SECRETS_ERROR,
data: xhr,
});
},
});
},
revokeSecret(storeName, secretPath) {
RequestUtil.json({
url: `${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/revoke/${storeName}/${secretPath}`,
method: "PUT",
success(response) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_REVOKE_SECRET_SUCCESS,
data: response,
});
},
error(xhr) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_REVOKE_SECRET_ERROR,
data: RequestUtil.getErrorFromXHR(xhr),
});
},
});
},
renewSecret(storeName, secretPath, durationObject) {
RequestUtil.json({
url: `${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/renew/${storeName}/${secretPath}`,
method: "PUT",
data: durationObject,
success(response) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_RENEW_SECRET_SUCCESS,
data: response,
});
},
error(xhr) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_RENEW_SECRET_ERROR,
data: RequestUtil.getErrorFromXHR(xhr),
});
},
});
},
fetchStores() {
RequestUtil.json({
url: `${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/store`,
success(response) {
SDK.dispatch({
type: ActionTypes.REQUEST_ALL_STORES_SUCCESS,
data: response.array,
});
},
error(xhr) {
SDK.dispatch({
type: ActionTypes.REQUEST_ALL_STORES_ERROR,
data: RequestUtil.getErrorFromXHR(xhr),
});
},
});
},
fetchStore(storeName) {
RequestUtil.json({
url: `${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/store/${storeName}`,
success(response) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_BACKEND_SUCCESS,
data: response,
});
},
error(xhr) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_BACKEND_ERROR,
data: RequestUtil.getErrorFromXHR(xhr),
});
},
});
},
createStore(storeName, storeObject) {
RequestUtil.json({
url: `${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/store/${storeName}`,
method: "PUT",
data: storeObject,
success(response) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_BACKEND_CREATE_SUCCESS,
data: response,
});
},
error(xhr) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_BACKEND_CREATE_ERROR,
data: RequestUtil.getErrorFromXHR(xhr),
});
},
});
},
deleteStore(storeName, storeObject) {
RequestUtil.json({
url: `${Config.rootUrl}${PrivatePluginsConfig.secretsAPIPrefix}/store/${storeName}`,
method: "DELETE",
data: storeObject,
success(response) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_BACKEND_DELETE_SUCCESS,
data: response,
});
},
error(xhr) {
SDK.dispatch({
type: ActionTypes.REQUEST_STORE_BACKEND_DELETE_ERROR,
data: RequestUtil.getErrorFromXHR(xhr),
});
},
});
},
};
if (Config.useFixtures) {
const methodFixtureMapping = {
fetchSealStatus: import(
/* storeSealStatus */ "../../../tests/_fixtures/secrets/store-seal-status.json"
),
fetchSecret: import(
/* secret */ "../../../tests/_fixtures/secrets/secret.json"
),
createSecret: import(
/* secret */ "../../../tests/_fixtures/secrets/secret.json"
),
deleteSecret: import(
/* secret */ "../../../tests/_fixtures/secrets/secret.json"
),
fetchSecrets: import(
/* secrets */ "../../../tests/_fixtures/secrets/secrets.json"
),
fetchStores: import(
/* stores */ "../../../tests/_fixtures/secrets/stores.json"
),
fetchStore: import(
/* backend */ "../../../tests/_fixtures/secrets/backend.json"
),
};
if (!window.actionTypes) {
window.actionTypes = {};
}
if (!window.actionTypes.SecretActions) {
window.actionTypes.SecretActions = {};
}
Promise.all(
Object.keys(methodFixtureMapping).map(
(method) => methodFixtureMapping[method]
)
).then((responses) => {
window.actionTypes.SecretActions = Object.assign(
getFixtureResponses(methodFixtureMapping, responses),
{
deleteSecret: {
event: "success",
success: { response: "Secret deleted." },
},
revokeSecret: {
event: "success",
success: { response: "Secret revoked." },
},
renewSecret: {
event: "success",
success: { response: "Secret renewed." },
},
createStore: {
event: "success",
success: { response: "Backend created." },
},
deleteStore: {
event: "success",
success: { response: "Backend deleted." },
},
}
);
Object.keys(window.actionTypes.SecretActions).forEach((method) => {
SecretActions[method] = RequestUtil.stubRequest(
SecretActions,
"SecretActions",
method
);
});
});
}
export default SecretActions; | the_stack |
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as fabricNetwork from 'fabric-network';
import { SmartContractUtil } from './ts-smart-contract-util';
import { User } from 'fabric-client';
import * as path from 'path';
chai.use(chaiAsPromised);
const expect = chai.expect;
const ARIUM_WALLET_PATH = path.join(__dirname, '../', '../', 'apps', 'manufacturer', 'vehiclemanufacture_fabric', 'wallet');
const VDA_WALLET_PATH = '';
const PRINCE_WALLET_PATH = '';
const ARIUM_CONNECTION_PATH = path.join(__dirname, '../', '../', 'apps', 'manufacturer', 'vehiclemanufacture_fabric', 'local_connection.json');
const VDA_CONNECTION_PATH = '';
const PRINCE_CONNECTION_PATH = '';
describe('org.acme.vehicle_network.vehicles-vehicle-manufacture-chaincode@0.1.0' , () => {
let discoveryAsLocalhost: boolean;
let discoveryEnabled: boolean;
let connectionProfile: any;
const ariumGateways: Map<string, fabricNetwork.Gateway> = new Map();
let ca: any;
let adminUser: User;
let ariumWallet: fabricNetwork.FileSystemWallet;
let vdaWallet: fabricNetwork.FileSystemWallet;
let princeWallet: fabricNetwork.FileSystemWallet;
before(async () => {
connectionProfile = await SmartContractUtil.getConnectionProfile(ARIUM_CONNECTION_PATH);
});
beforeEach(async function() {
this.timeout(100000);
discoveryAsLocalhost = SmartContractUtil.hasLocalhostURLs(connectionProfile);
discoveryEnabled = false;
const ariumUsers = ['reports', 'orders', 'production', 'telematics', 'registrar'];
ariumWallet = new fabricNetwork.FileSystemWallet(ARIUM_WALLET_PATH);
for (const identity of ariumUsers) {
const gateway = await SmartContractUtil.createGateway(
connectionProfile,
identity,
ariumWallet,
{discoveryAsLocalhost, discoveryEnabled},
);
ariumGateways.set(identity, gateway);
}
});
afterEach(async () => {
ariumGateways.forEach((g) => g.disconnect());
ariumGateways.clear();
});
describe('#placeOrder', () => {
let specialIdentity;
beforeEach(async () => {
specialIdentity = 'orders';
});
it('should successfully call', async () => {
const ordererId: string = 'EXAMPLE';
const vehicleDetails = {makeId: 'Arium'};
const options = {};
const args: string[] = [ ordererId, JSON.stringify(vehicleDetails), JSON.stringify(options)];
const gateway = ariumGateways.get(specialIdentity);
const response: any = await SmartContractUtil.submitTransaction(
'org.acme.vehicle_network.vehicles', 'placeOrder', args, gateway,
);
expect(response.class).to.equal('org.acme.vehicle_network.assets.Order');
expect(response.ordererId).to.equal(ordererId);
expect(response.orderStatus).to.equal(0);
expect(response.options).to.deep.equal(options);
expect(response.vehicleDetails).to.deep.equal(vehicleDetails);
const createdOrder: any = await SmartContractUtil.evaluateTransaction(
'org.acme.vehicle_network.vehicles', 'getOrder', [response.id], gateway,
);
expect(createdOrder.class).to.equal('org.acme.vehicle_network.assets.Order');
expect(createdOrder.ordererId).to.equal(ordererId);
expect(createdOrder.orderStatus).to.equal(0);
expect(createdOrder.options).to.deep.equal(options);
expect(createdOrder.vehicleDetails).to.deep.equal(vehicleDetails);
}).timeout(10000);
it('should receive a contract event', async () => {
const gateway = ariumGateways.get(specialIdentity);
const contract = (await gateway.getNetwork('vehiclemanufacture'))
.getContract('vehicle-manufacture-chaincode');
let eventTriggered = false;
await contract.addContractListener('PLACE_ORDER', 'PLACE_ORDER', async (err, event) => {
eventTriggered = true;
console.log(event);
}, {replay: false});
const ordererId: string = 'EXAMPLE';
const vehicleDetails = {makeId: 'Arium'};
const options = {};
const args: string[] = [ ordererId, JSON.stringify(vehicleDetails), JSON.stringify(options)];
await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'placeOrder', args, gateway);
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('Event not triggered'));
}, 25000);
const interval = setInterval(() => {
if (eventTriggered) {
clearInterval(interval);
clearTimeout(timeout);
resolve();
}
}, 100);
});
expect(eventTriggered).to.equal(true);
}).timeout(30000);
it('should throw if called by a participant without ORDER_CREATE', async () => {
const identity = 'registrar';
const gateway = ariumGateways.get(identity);
const ordererId: string = 'EXAMPLE';
const vehicleDetails = {makeId: 'Arium'};
const options = {};
const args: string[] = [ ordererId, JSON.stringify(vehicleDetails), JSON.stringify(options)];
await expect(SmartContractUtil.submitTransaction(
'org.acme.vehicle_network.vehicles',
'placeOrder',
args,
gateway,
)).to.be.rejectedWith('Only callers with role order.create can place orders');
}).timeout(2000);
it('should throw if participant orgId and vehicle makeId do not match', async () => {
const gateway = ariumGateways.get(specialIdentity);
const ordererId: string = 'example';
const vehicleDetails = {makeId: 'anotherManufacturer'};
const options = {};
const args: string[] = [ ordererId, JSON.stringify(vehicleDetails), JSON.stringify(options)];
await expect(SmartContractUtil.submitTransaction(
'org.acme.vehicle_network.vehicles',
'placeOrder',
args,
gateway,
)).to.be.rejectedWith('Callers may only create orders in their organisation');
}).timeout(2000);
});
describe('#getOrders', () => {
let specialIdentity;
beforeEach(async () => {
specialIdentity = 'orders';
});
it('should successfully call', async () => {
const gateway = ariumGateways.get(specialIdentity);
const args: string[] = [];
const response: Buffer = await SmartContractUtil.submitTransaction(
'org.acme.vehicle_network.vehicles',
'getOrders',
args,
gateway,
);
}).timeout(10000);
});
// describe('#getOrder', () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const orderId: string = 'EXAMPLE';
// const args: string[] = [ orderId];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'getOrder', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#getOrderHistory', () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const orderId: string = 'EXAMPLE';
// const args: string[] = [ orderId];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'getOrderHistory', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#scheduleForManufacture', () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const orderId: string = 'EXAMPLE';
// const args: string[] = [ orderId];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'scheduleOrderForManufacture', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#registerVehicleForOrder', () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const orderId: string = 'EXAMPLE';
// const vin: string = 'EXAMPLE';
// const args: string[] = [ orderId, vin];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'registerVehicleForOrder', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#assignOwnershipForOrder', () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const orderId: string = 'EXAMPLE';
// const args: string[] = [ orderId];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'assignOwnershipForOrder', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#deliverOrder', () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const orderId: string = 'EXAMPLE';
// const args: string[] = [ orderId];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'deliverOrder', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#getVehicles', () => {
// it('should successfully call', async () => {
// // TODO: Update with parameters of transaction
// const args: string[] = [];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'getVehicles', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#getVehicle', () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const vin: string = 'EXAMPLE';
// const args: string[] = [ vin];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'getVehicle', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#createPolicy', () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const vin: string = 'EXAMPLE';
// const holderId: string = 'EXAMPLE';
// const policyType: number = 0;
// const endDate: number = 0;
// const args: string[] = [ vin, holderId, policyType.toString(), endDate.toString()];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'createPolicy', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#getPolicies', () => {
// it('should successfully call', async () => {
// // TODO: Update with parameters of transaction
// const args: string[] = [];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'getPolicies', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#getPolicy', () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const policyId: string = 'EXAMPLE';
// const args: string[] = [ policyId];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'getPolicy', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#addUsageEvent', () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const vin: string = 'EXAMPLE';
// const eventType: number = 0;
// const acceleration: number = 0;
// const airTemperature: number = 0;
// const engineTemperature: number = 0;
// const lightLevel: number = 0;
// const pitch: number = 0;
// const roll: number = 0;
// const args: string[] = [ vin, eventType.toString(), acceleration.toString(), airTemperature.toString(), engineTemperature.toString(), lightLevel.toString(), pitch.toString(), roll.toString()];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'addUsageEvent', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#getUsageEvents', () => {
// it('should successfully call', async () => {
// // TODO: Update with parameters of transaction
// const args: string[] = [];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'getUsageEvents', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#getVehicleEvents', () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const vin: string = 'EXAMPLE';
// const args: string[] = [ vin];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'getVehicleEvents', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
// describe('#getPolicyEvents', async () => {
// it('should successfully call', async () => {
// // TODO: populate transaction parameters
// const policyId: string = 'EXAMPLE';
// const args: string[] = [ policyId];
// const response: Buffer = await SmartContractUtil.submitTransaction('org.acme.vehicle_network.vehicles', 'getPolicyEvents', args, gateway);
// // submitTransaction returns buffer of transcation return value
// // TODO: Update with return value of transaction
// assert.equal(true, true);
// // assert.equal(JSON.parse(response.toString()), undefined);
// }).timeout(10000);
// });
}); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [lookoutmetrics](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonlookoutformetrics.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Lookoutmetrics extends PolicyStatement {
public servicePrefix = 'lookoutmetrics';
/**
* Statement provider for service [lookoutmetrics](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonlookoutformetrics.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 activate an anomaly detector
*
* Access Level: Write
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_ActivateAnomalyDetector.html
*/
public toActivateAnomalyDetector() {
return this.to('ActivateAnomalyDetector');
}
/**
* Grants permission to run a backtest with an anomaly detector
*
* Access Level: Write
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_BackTestAnomalyDetector.html
*/
public toBackTestAnomalyDetector() {
return this.to('BackTestAnomalyDetector');
}
/**
* Grants permission to create an alert for an anomaly detector
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_CreateAlert.html
*/
public toCreateAlert() {
return this.to('CreateAlert');
}
/**
* Grants permission to create an anomaly detector
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_CreateAnomalyDetector.html
*/
public toCreateAnomalyDetector() {
return this.to('CreateAnomalyDetector');
}
/**
* Grants permission to create a dataset
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_CreateMetricSet.html
*/
public toCreateMetricSet() {
return this.to('CreateMetricSet');
}
/**
* Grants permission to delete an alert
*
* Access Level: Write
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_DeleteAlert.html
*/
public toDeleteAlert() {
return this.to('DeleteAlert');
}
/**
* Grants permission to delete an anomaly detector
*
* Access Level: Write
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_DeleteAnomalyDetector.html
*/
public toDeleteAnomalyDetector() {
return this.to('DeleteAnomalyDetector');
}
/**
* Grants permission to get details about an alert
*
* Access Level: Read
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_DescribeAlert.html
*/
public toDescribeAlert() {
return this.to('DescribeAlert');
}
/**
* Grants permission to get information about an anomaly detection job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_DescribeAnomalyDetectionExecutions.html
*/
public toDescribeAnomalyDetectionExecutions() {
return this.to('DescribeAnomalyDetectionExecutions');
}
/**
* Grants permission to get details about an anomaly detector
*
* Access Level: Read
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_DescribeAnomalyDetector.html
*/
public toDescribeAnomalyDetector() {
return this.to('DescribeAnomalyDetector');
}
/**
* Grants permission to get details about a dataset
*
* Access Level: Read
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_DescribeMetricSet.html
*/
public toDescribeMetricSet() {
return this.to('DescribeMetricSet');
}
/**
* Grants permission to get details about a group of affected metrics
*
* Access Level: Read
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_GetAnomalyGroup.html
*/
public toGetAnomalyGroup() {
return this.to('GetAnomalyGroup');
}
/**
* Grants permission to get data quality metrics for an anomaly detector
*
* Access Level: Read
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_GetDataQualityMetrics.html
*/
public toGetDataQualityMetrics() {
return this.to('GetDataQualityMetrics');
}
/**
* Grants permission to get feedback on affected metrics for an anomaly group
*
* Access Level: Read
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_GetFeedback.html
*/
public toGetFeedback() {
return this.to('GetFeedback');
}
/**
* Grants permission to get a selection of sample records from an Amazon S3 datasource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_GetSampleData.html
*/
public toGetSampleData() {
return this.to('GetSampleData');
}
/**
* Grants permission to get a list of alerts for a detector
*
* Access Level: List
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_ListAlerts.html
*/
public toListAlerts() {
return this.to('ListAlerts');
}
/**
* Grants permission to get a list of anomaly detectors
*
* Access Level: List
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_ListAnomalyDetectors.html
*/
public toListAnomalyDetectors() {
return this.to('ListAnomalyDetectors');
}
/**
* Grants permission to get a list of anomaly groups
*
* Access Level: List
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_ListAnomalyGroupSummaries.html
*/
public toListAnomalyGroupSummaries() {
return this.to('ListAnomalyGroupSummaries');
}
/**
* Grants permission to get a list of affected metrics for a measure in an anomaly group
*
* Access Level: List
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_ListAnomalyGroupTimeSeries.html
*/
public toListAnomalyGroupTimeSeries() {
return this.to('ListAnomalyGroupTimeSeries');
}
/**
* Grants permission to get a list of datasets
*
* Access Level: List
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_ListMetricSets.html
*/
public toListMetricSets() {
return this.to('ListMetricSets');
}
/**
* Grants permission to get a list of tags for a detector, dataset, or alert
*
* Access Level: Read
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to add feedback for an affected metric in an anomaly group
*
* Access Level: Write
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_PutFeedback.html
*/
public toPutFeedback() {
return this.to('PutFeedback');
}
/**
* Grants permission to add tags to a detector, dataset, or alert
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to remove tags from a detector, dataset, or alert
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update an anomaly detector
*
* Access Level: Write
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_UpdateAnomalyDetector.html
*/
public toUpdateAnomalyDetector() {
return this.to('UpdateAnomalyDetector');
}
/**
* Grants permission to update a dataset
*
* Access Level: Write
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_UpdateMetricSet.html
*/
public toUpdateMetricSet() {
return this.to('UpdateMetricSet');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"ActivateAnomalyDetector",
"BackTestAnomalyDetector",
"CreateAlert",
"CreateAnomalyDetector",
"CreateMetricSet",
"DeleteAlert",
"DeleteAnomalyDetector",
"PutFeedback",
"UpdateAnomalyDetector",
"UpdateMetricSet"
],
"Read": [
"DescribeAlert",
"DescribeAnomalyDetectionExecutions",
"DescribeAnomalyDetector",
"DescribeMetricSet",
"GetAnomalyGroup",
"GetDataQualityMetrics",
"GetFeedback",
"GetSampleData",
"ListTagsForResource"
],
"List": [
"ListAlerts",
"ListAnomalyDetectors",
"ListAnomalyGroupSummaries",
"ListAnomalyGroupTimeSeries",
"ListMetricSets"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type AnomalyDetector to the statement
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_AnomalyDetectorSummary.html
*
* @param anomalyDetectorName - Identifier for the anomalyDetectorName.
* @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 onAnomalyDetector(anomalyDetectorName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:lookoutmetrics:${Region}:${Account}:AnomalyDetector:${AnomalyDetectorName}';
arn = arn.replace('${AnomalyDetectorName}', anomalyDetectorName);
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 MetricSet to the statement
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_MetricSetSummary.html
*
* @param anomalyDetectorName - Identifier for the anomalyDetectorName.
* @param metricSetName - Identifier for the metricSetName.
* @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 onMetricSet(anomalyDetectorName: string, metricSetName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:lookoutmetrics:${Region}:${Account}:MetricSet/${AnomalyDetectorName}/${MetricSetName}';
arn = arn.replace('${AnomalyDetectorName}', anomalyDetectorName);
arn = arn.replace('${MetricSetName}', metricSetName);
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 Alert to the statement
*
* https://docs.aws.amazon.com/lookoutmetrics/latest/api/API_AlertSummary.html
*
* @param alertName - Identifier for the alertName.
* @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 onAlert(alertName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:lookoutmetrics:${Region}:${Account}:Alert:${AlertName}';
arn = arn.replace('${AlertName}', alertName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import m from 'mithril';
import classnames from 'classnames';
import PopperJS, { Boundary } from 'popper.js';
import { Classes, IAttrs, Style, safeCall, getClosest, elementIsOrContains } from '../../_shared';
import { AbstractComponent } from '../abstract-component';
import { IOverlayableAttrs, Overlay } from '../overlay';
import { PopoverInteraction, PopoverPosition } from './popoverTypes';
export interface IPopoverAttrs extends IOverlayableAttrs, IAttrs {
/**
* Set the bounding box.
* see <a href="https://popper.js.org/popper-documentation.html#modifiers..preventOverflow">Here</a> for more details
* @default 'window'
*/
boundariesEl?: Boundary | Element;
/** Close the popover on inner content click */
closeOnContentClick?: boolean;
/** Inner content */
content: m.Children;
/** Initial open when in uncontrolled mode */
defaultIsOpen?: boolean;
/**
* Toggles arrow visiblity
* @default true
*/
hasArrow?: boolean;
/**
* Duration of close delay on hover interaction
* @default 100
*/
hoverCloseDelay?: number;
/**
* Duration of open delay on hover interaction
* @default 0
*/
hoverOpenDelay?: number;
/**
* Trigger interaction to toggle visiblity
* @default 'click'
*/
interactionType?: PopoverInteraction;
/**
* Toggles visibility;
* Specifying this attr will place the Popover in controlled mode
* and will invoke the `onInteraction` callback for each open/close state change
*/
isOpen?: boolean;
/**
* Options to pass to the PopperJS instance;
* see <a href="https://popper.js.org/popper-documentation.html#modifiers">HERE</a> for more details
*/
modifiers?: PopperJS.Modifiers;
/**
* Position relative to trigger element
* @default 'bottom'
*/
position?: PopoverPosition;
/** Callback invoked in controlled mode when a popover action will modify the open state */
onInteraction?: (nextOpenState: boolean, e: Event) => void;
/**
* Toggles visibilty when trigger is keyboard focused;
* Only works when interactionType is hover or hover-trigger
*/
openOnTriggerFocus?: boolean;
/** Overlay HTML container class */
overlayClass?: string;
/** Overlay HTML container styles */
overlayStyle?: Style;
/** Trigger element */
trigger: m.Vnode<any, any>;
}
export interface IPopoverTriggerAttrs extends IAttrs {
onclick?(e: Event): void;
onmouseenter?(e: MouseEvent): void;
onmouseleave?(e: MouseEvent): void;
onfocus?(e: Event): void;
onblur?(e: Event): void;
[htmlAttrs: string]: any;
}
export class Popover extends AbstractComponent<IPopoverAttrs> {
private isOpen: boolean;
private popper?: PopperJS & { options?: PopperJS.PopperOptions };
private trigger: m.VnodeDOM<IPopoverTriggerAttrs>;
public getDefaultAttrs() {
return {
boundariesEl: 'window',
restoreFocus: false,
hasBackdrop: false,
hoverCloseDelay: 100,
hoverOpenDelay: 0,
interactionType: 'click',
position: 'bottom',
hasArrow: true
} as IPopoverAttrs;
}
public oninit(vnode: m.Vnode<IPopoverAttrs>) {
super.oninit(vnode);
const { isOpen, defaultIsOpen } = this.attrs;
this.isOpen = isOpen != null ? isOpen : defaultIsOpen != null ? defaultIsOpen : false;
}
public onbeforeupdate(vnode: m.Vnode<IPopoverAttrs>, old: m.VnodeDOM<IPopoverAttrs>) {
super.onbeforeupdate(vnode, old);
const isOpen = vnode.attrs.isOpen;
const wasOpen = old.attrs.isOpen;
if (isOpen && !wasOpen) {
this.isOpen = true;
} else if (!isOpen && wasOpen) {
this.isOpen = false;
}
}
public onupdate() {
if (this.popper) {
this.popper.options.placement = this.attrs.position as PopperJS.Placement;
this.popper.scheduleUpdate();
}
}
public onremove() {
this.destroyPopper();
}
public view() {
const {
class: className,
style,
content,
hasArrow,
trigger,
interactionType,
inline,
backdropClass,
overlayClass,
overlayStyle
} = this.attrs;
this.trigger = trigger as m.VnodeDOM;
this.setTriggerAttrs();
const innerContent = m('', {
class: classnames(Classes.POPOVER, className),
onclick: this.handlePopoverClick,
onmouseenter: this.handleTriggerMouseEnter,
onmouseleave: this.handleTriggerMouseLeave,
style
}, [
hasArrow && m(`.${Classes.POPOVER_ARROW}`),
m(`.${Classes.POPOVER_CONTENT}`, content)
]);
return m.fragment({}, [
this.trigger,
m(Overlay, {
restoreFocus: this.isClickInteraction(),
...this.attrs as IOverlayableAttrs,
backdropClass: classnames(Classes.POPOVER_BACKDROP, backdropClass),
class: overlayClass,
closeOnOutsideClick: interactionType !== 'click-trigger',
content: innerContent,
inline,
isOpen: this.isOpen,
onClose: this.handleOverlayClose,
onOpened: this.handleOpened,
onClosed: this.handleClosed,
style: overlayStyle
})
]);
}
private handleOpened = (contentEl: HTMLElement) => {
if (!this.popper && contentEl) {
const popoverEl = contentEl.querySelector(`.${Classes.POPOVER}`)!;
this.createPopper(popoverEl as HTMLElement);
safeCall(this.attrs.onOpened, contentEl);
}
}
private handleClosed = () => {
this.destroyPopper();
safeCall(this.attrs.onClosed);
}
private handleOverlayClose = (e: Event) => {
const target = e.target as HTMLElement;
const isTriggerClick = elementIsOrContains(this.trigger.dom as HTMLElement, target);
if (!isTriggerClick || e instanceof KeyboardEvent) {
this.isControlled ? this.handleInteraction(e) : this.isOpen = false;
}
}
private createPopper(el: HTMLElement) {
const { position, hasArrow, boundariesEl, modifiers } = this.attrs;
const options = {
placement: position,
modifiers: {
arrow: {
enabled: hasArrow,
element: `.${Classes.POPOVER_ARROW}`
},
offset: {
enabled: hasArrow,
fn: (data) => this.getContentOffset(data, el)
},
preventOverflow: {
enabled: true,
boundariesElement: boundariesEl,
padding: 0
},
...modifiers
}
} as PopperJS.PopperOptions;
this.popper = new PopperJS(
this.trigger.dom,
el,
options
);
}
private destroyPopper() {
if (this.popper) {
this.popper.destroy();
this.popper = undefined;
}
}
private setTriggerAttrs() {
const isControlled = this.isControlled;
if (!this.trigger.attrs) {
this.trigger.attrs = {};
}
const triggerAttrs = this.trigger.attrs;
if (this.isOpen) {
triggerAttrs.class = classnames(
triggerAttrs.className || triggerAttrs.class,
Classes.ACTIVE,
Classes.POPOVER_TRIGGER_ACTIVE
);
} else triggerAttrs.class = triggerAttrs.className || triggerAttrs.class || '';
const triggerEvents = {
onmouseenter: triggerAttrs.onmouseenter,
onmouseleave: triggerAttrs.onmouseleave,
onfocus: triggerAttrs.onfocus,
onblur: triggerAttrs.onblur,
onclick: triggerAttrs.onclick
};
if (this.isClickInteraction()) {
triggerAttrs.onclick = (e: Event) => {
isControlled ? this.handleInteraction(e) : this.handleTriggerClick();
safeCall(triggerEvents.onclick);
};
} else {
triggerAttrs.onmouseenter = (e: MouseEvent) => {
isControlled ? this.handleInteraction(e) : this.handleTriggerMouseEnter(e);
safeCall(triggerEvents.onmouseenter);
};
triggerAttrs.onmouseleave = (e: MouseEvent) => {
isControlled ? this.handleInteraction(e) : this.handleTriggerMouseLeave(e);
safeCall(triggerEvents.onmouseleave);
};
triggerAttrs.onfocus = (e: FocusEvent) => {
isControlled ? this.handleInteraction(e) : this.handleTriggerFocus(e);
safeCall(triggerEvents.onfocus);
};
triggerAttrs.onblur = (e: FocusEvent) => {
isControlled ? this.handleInteraction(e) : this.handleTriggerBlur(e);
safeCall(triggerEvents.onblur);
};
}
}
private handleInteraction(e: Event) {
safeCall(this.attrs.onInteraction, !this.isOpen, e);
}
private handlePopoverClick = (e: Event) => {
const target = e.target as HTMLElement;
const hasDimiss = getClosest(target, `.${Classes.POPOVER_DISSMISS}`) != null;
if (this.attrs.closeOnContentClick || hasDimiss) {
this.isControlled ? this.handleInteraction(e) : this.isOpen = false;
} else (e as any).redraw = false;
}
private handleTriggerClick() {
this.isOpen = !this.isOpen;
}
private handleTriggerFocus(e: FocusEvent) {
if (this.attrs.openOnTriggerFocus) {
this.handleTriggerMouseEnter(e as any);
} else (e as any).redraw = false;
}
private handleTriggerBlur(e: FocusEvent) {
if (this.attrs.openOnTriggerFocus) {
this.handleTriggerMouseLeave(e as any);
} else (e as any).redraw = false;
}
private handleTriggerMouseEnter = (e: MouseEvent) => {
const { hoverOpenDelay, interactionType } = this.attrs;
if (interactionType !== 'hover-trigger') {
this.clearTimeouts();
}
if (!this.isOpen && this.isHoverInteraction()) {
if (hoverOpenDelay! > 0) {
this.setTimeout(() => {
this.isOpen = true;
m.redraw();
}, hoverOpenDelay);
} else {
this.isOpen = true;
m.redraw();
}
}
(e as any).redraw = false;
}
private handleTriggerMouseLeave = (e: MouseEvent) => {
const { hoverCloseDelay } = this.attrs;
this.clearTimeouts();
if (this.isOpen && this.isHoverInteraction()) {
if (hoverCloseDelay! > 0) {
this.setTimeout(() => {
this.isOpen = false;
m.redraw();
}, hoverCloseDelay);
} else {
this.isOpen = false;
m.redraw();
}
}
(e as any).redraw = false;
}
private isHoverInteraction() {
const interactionType = this.attrs.interactionType;
return interactionType === 'hover' || interactionType === 'hover-trigger';
}
private isClickInteraction() {
const interactionType = this.attrs.interactionType;
return interactionType === 'click' || interactionType === 'click-trigger';
}
private get isControlled() {
return this.attrs.isOpen != null;
}
private getContentOffset = (data: PopperJS.Data, containerEl: HTMLElement) => {
if (!this.attrs.hasArrow) {
return data;
}
const placement = data.placement;
const isHorizontal = placement.includes('left') || placement.includes('right');
const position = isHorizontal ? 'left' : 'top';
const arrowSize = (containerEl.children[0] as HTMLElement).clientHeight + 1;
const offset = placement.includes('top') || placement.includes('left') ? -arrowSize : arrowSize;
data.offsets.popper[position] += offset;
return data;
}
} | the_stack |
import React, { ReactType } from 'react'
import { Dispatch } from 'redux'
import { connect } from 'react-redux'
import {
Text,
FlatList,
ListRenderItemInfo,
Dimensions,
TouchableWithoutFeedback,
View,
Clipboard,
Platform
} from 'react-native'
import { NavigationScreenProps, SafeAreaView } from 'react-navigation'
import ActionSheet from 'react-native-actionsheet'
import Toast from 'react-native-easy-toast'
import Textile, { IUser, Thread, FeedItemType } from '@textile/react-native-sdk'
import moment from 'moment'
import {
TextileHeaderButtons,
Item as TextileHeaderButtonsItem
} from '../../Components/HeaderButtons'
import KeyboardResponsiveContainer from '../../Components/KeyboardResponsiveContainer'
import InviteContactModal from '../../Components/InviteContactModal'
import Photo from '../../Components/photo'
import ProcessingImage from '../../Components/ProcessingImage'
import Message from '../../Components/message'
import Join from '../../Components/join'
import { Item } from '../../features/group/models'
import { RootState, RootAction } from '../../Redux/Types'
import { groupItems } from '../../features/group/selectors'
import { groupActions } from '../../features/group'
import UIActions from '../../Redux/UIRedux'
import GroupsActions from '../../Redux/GroupsRedux'
import { CommentData } from '../../Components/comments'
import { color } from '../../styles'
import { accountSelectors } from '../../features/account'
import RenameGroupModal from '../../Containers/RenameGroupModal'
import PhotosKeyboard from '../../Components/PhotosKeyboard'
const momentSpec: moment.CalendarSpec = {
sameDay: 'LT',
nextDay: '[Tomorrow] LT',
nextWeek: 'MMM DD LT',
lastDay: 'MMM DD LT',
lastWeek: 'MMM DD LT',
sameElse: 'MMM DD LT'
}
const screenWidth = Dimensions.get('screen').width
const contStyle = Platform.OS === 'ios' ? { flex: 1, paddingBottom: 40 } : {}
interface StateProps {
threadId: string
items: ReadonlyArray<Item>
groupName: string
initiator: string
selfAddress: string
renaming: boolean
canInvite: boolean
liking: ReadonlyArray<string>
removing: ReadonlyArray<string>
}
interface DispatchProps {
refresh: () => void
addPhotoLike: (block: string) => void
navigateToComments: (photoId: string) => void
leaveThread: () => void
retryShare: (key: string) => void
cancelShare: (key: string) => void
remove: (blockId: string) => void
}
interface NavProps {
threadId: string
groupName: string
showThreadActionSheet: () => void
// Needed to ensure the gallery closes before back navigation
destroyKeyboard: () => void
}
type Props = StateProps & DispatchProps & NavigationScreenProps<NavProps>
interface State {
showInviteContactModal: boolean
showRenameGroupModal: boolean
// The current selected block (message/photo). For use in the block action sheet
selected?: {
blockId: string
isCopyable: boolean
canRemove: boolean
text?: string
}
destroyKeyboard: boolean
}
class Group extends React.PureComponent<Props, State> {
static navigationOptions = ({
navigation
}: NavigationScreenProps<NavProps>) => {
// const openDrawer = navigation.getParam('openDrawer')
// const addContact = navigation.getParam('addContact')
const groupName = navigation.getParam('groupName')
const showThreadActionSheet = navigation.getParam('showThreadActionSheet')
const back = () => {
const destroyKeyboard = navigation.getParam('destroyKeyboard')
if (destroyKeyboard) {
destroyKeyboard()
}
navigation.goBack()
}
const headerLeft = (
<TextileHeaderButtons left={true}>
<TextileHeaderButtonsItem
title="Back"
iconName="arrow-left"
onPress={back}
/>
</TextileHeaderButtons>
)
const headerRight = (
<TextileHeaderButtons>
<TextileHeaderButtonsItem
title="More"
iconName="more-vertical"
onPress={showThreadActionSheet}
/>
</TextileHeaderButtons>
)
return {
headerLeft,
headerTitle: groupName,
headerRight
}
}
// Action sheet to handle thread options like renaming the thread
threadActionSheet: any
// Action sheet to handle block options like removing (ignoring) a message
blockActionSheet: any
toast?: Toast
constructor(props: Props) {
super(props)
this.state = {
showInviteContactModal: false,
showRenameGroupModal: false,
destroyKeyboard: false
}
}
componentDidMount() {
this.props.navigation.addListener('willFocus', this.onFocus)
this.props.navigation.setParams({
groupName: this.props.groupName,
showThreadActionSheet: this.showThreadActionSheet,
destroyKeyboard: this.destroyGalleryKeyboard
})
}
componentDidUpdate(prevProps: Props, prevState: State) {
if (this.state.selected && prevState.selected !== this.state.selected) {
this.blockActionSheet.show()
}
}
renderBlockActionSheet = () => {
const { selected } = this.state
if (!selected) return
const { canRemove, isCopyable } = selected
if (!canRemove && !isCopyable) return
// Block action sheet
const blockActionSheetOptions = [
...(canRemove ? ['Remove'] : []),
...(isCopyable ? ['Copy'] : []),
'Cancel'
]
const blockCancelButtonIndex = blockActionSheetOptions.indexOf('Cancel')
return (
<ActionSheet
ref={(o: any) => {
this.blockActionSheet = o
}}
title={'Options'}
options={blockActionSheetOptions}
cancelButtonIndex={blockCancelButtonIndex}
onPress={this.handleBlockActionSheetResponse}
/>
)
}
renderThreadActionSheet = () => {
// Thread action sheet
const threadActionSheetOptions = [
...(this.props.canInvite ? ['Invite Others'] : []),
...(this.props.selfAddress === this.props.initiator
? ['Rename Group']
: []),
'Leave Group',
'Cancel'
]
const threadCancelButtonIndex = threadActionSheetOptions.indexOf('Cancel')
return (
<ActionSheet
ref={(o: any) => {
this.threadActionSheet = o
}}
title={this.props.groupName + ' options'}
options={threadActionSheetOptions}
cancelButtonIndex={threadCancelButtonIndex}
onPress={this.handleThreadActionSheetResponse}
/>
)
}
render() {
const threadId = this.props.navigation.getParam('threadId')
// The rn-keyboard module caused some issues with Android vs iOS, this fixes it
// The rn-keyboard module caused some issues with Android vs iOS, this fixes it
return (
<View style={{ flex: 1, flexGrow: 1 }}>
<KeyboardResponsiveContainer style={contStyle} ios={false}>
<FlatList
style={{ flex: 1, backgroundColor: color.screen_primary }}
inverted={true}
data={this.props.items}
renderItem={this.renderRow}
keyExtractor={this.keyExtractor}
initialNumToRender={5}
windowSize={5}
onEndReachedThreshold={5}
maxToRenderPerBatch={5}
/>
<InviteContactModal
isVisible={this.state.showInviteContactModal}
cancel={this.hideInviteModal}
selectedThreadId={threadId}
selectedThreadName={this.props.groupName}
/>
{this.renderThreadActionSheet()}
{this.renderBlockActionSheet()}
<RenameGroupModal
isVisible={this.state.showRenameGroupModal}
threadId={threadId}
groupName={this.props.groupName}
cancel={this.cancelRenameGroup}
complete={this.completeRenameGroup}
/>
</KeyboardResponsiveContainer>
{!this.state.destroyKeyboard && (
<PhotosKeyboard threadId={this.props.threadId} />
)}
<Toast
ref={toast => {
this.toast = toast ? toast : undefined
}}
position="center"
/>
</View>
)
}
destroyGalleryKeyboard = () => {
this.setState({
destroyKeyboard: true
})
}
sameUserAgain = (user: IUser, previous?: Item): boolean => {
if (!previous) {
return false
}
switch (previous.type) {
case FeedItemType.Text: {
return user.address === previous.value.user.address
}
default: {
return false
}
}
}
keyExtractor = (item: Item) => {
switch (item.type) {
case 'addingMessage':
case 'addingPhoto':
return item.key
default:
return item.block
}
}
renderRow = ({ item, index }: ListRenderItemInfo<Item>) => {
switch (item.type) {
case FeedItemType.Files: {
const { value, syncStatus, block } = item
const { user, caption, date, data, files, likes, comments } = value
const isOwnPhoto = user.address === this.props.selfAddress
const canRemove = isOwnPhoto && !this.removing(block)
const hasLiked =
likes.findIndex(
likeInfo => likeInfo.user.address === this.props.selfAddress
) > -1 || this.liking(block)
const commentsData: ReadonlyArray<CommentData> = comments.map(
comment => {
const isOwnComment = user.address === comment.user.address
const isRemovingComment =
this.props.removing.indexOf(comment.id) !== -1
const canRemoveComment = isOwnComment && !isRemovingComment
return {
id: comment.id,
username: comment.user.name || '?',
body: comment.body,
onLongPress: this.configureBlockActionSheet(
comment.id,
canRemoveComment,
true,
comment.body
)
}
}
)
// Get full size image constraints
const def = screenWidth
const pinchWidth = !files.length
? def
: !files[0].links.large
? def
: files[0].links.large.meta.fields.width.numberValue
const pinchHeight = !files.length
? def
: !files[0].links.large
? def
: files[0].links.large.meta.fields.height.numberValue
const fileIndex =
files && files.length > 0 && files[0].index ? files[0].index : 0
return (
<Photo
avatar={user.avatar}
username={user.name.length > 0 ? user.name : 'unknown'}
message={caption.length > 0 ? caption : undefined}
time={moment(Textile.util.timestampToDate(date)).calendar(
undefined,
momentSpec
)}
photoId={data}
fileIndex={fileIndex}
syncStatus={syncStatus}
displayError={this.showToastWithMessage}
photoWidth={screenWidth}
hasLiked={hasLiked}
numberLikes={likes.length}
numberComments={comments.length}
onLike={this.onLike(block)}
onComment={this.onComment(block)}
comments={commentsData}
commentsDisplayMax={5}
onViewComments={this.onComment(block)}
pinchZoom={true}
pinchWidth={pinchWidth}
pinchHeight={pinchHeight}
onLongPress={
canRemove
? this.configureBlockActionSheet(item.block, true, false)
: undefined
}
/>
)
}
case 'addingPhoto': {
return (
<ProcessingImage
{...item.data}
/* tslint:disable-next-line */
retry={() => {
this.props.retryShare(item.key)
}}
/* tslint:disable-next-line */
cancel={() => {
this.props.cancelShare(item.key)
}}
/>
)
}
case FeedItemType.Text: {
const { user, body, date } = item.value
const isSameUser = this.sameUserAgain(user, this.props.items[index + 1])
const isOwnMessage = user.address === this.props.selfAddress
const canRemove = isOwnMessage && !this.removing(item.block)
const avatar = isSameUser ? undefined : user.avatar
return (
<TouchableWithoutFeedback
onLongPress={this.configureBlockActionSheet(
item.block,
canRemove,
true,
item.value.body
)}
>
<View>
<Message
avatar={avatar}
username={user.name || 'unknown'}
message={body}
// TODO: deal with pb Timestamp to JS Date!
time={moment(Textile.util.timestampToDate(date)).calendar(
undefined,
momentSpec
)}
isSameUser={isSameUser}
/>
</View>
</TouchableWithoutFeedback>
)
}
case FeedItemType.Leave:
case FeedItemType.Join: {
const { user, date } = item.value
const word = item.type === FeedItemType.Join ? 'joined' : 'left'
return (
<Join
avatar={user.avatar}
username={user.name || 'unknown'}
message={`${word} ${this.props.groupName}`}
time={moment(Textile.util.timestampToDate(date)).calendar(
undefined,
momentSpec
)}
/>
)
}
default:
return <Text>{`${item.type}`}</Text>
}
}
onFocus = () => {
this.props.refresh()
}
onLike = (block: string) => {
return () => this.props.addPhotoLike(block)
}
onComment = (target: string) => {
return () => this.props.navigateToComments(target)
}
showThreadActionSheet = () => {
this.threadActionSheet.show()
}
showBlockActionSheet = (
blockId: string,
canRemove: boolean,
isCopyable: boolean,
text?: string
) => {
this.setState({
selected: {
blockId,
canRemove,
isCopyable,
text
}
})
}
configureBlockActionSheet = (
blockId: string,
canRemove: boolean,
isCopyable: boolean,
text?: string
) => {
return () => {
return this.showBlockActionSheet(blockId, canRemove, isCopyable, text)
}
}
handleThreadActionSheetResponse = (index: number) => {
const actions = [
...(this.props.canInvite ? [this.showInviteModal] : []),
...(this.props.selfAddress === this.props.initiator
? [this.showRenameGroupModal]
: []),
this.props.leaveThread
]
if (index < actions.length) {
actions[index]()
}
}
handleBlockActionSheetResponse = (index: number) => {
const actions = [
...(this.state.selected && this.state.selected.canRemove
? [
() =>
this.state.selected &&
this.props.remove(this.state.selected.blockId)
]
: []),
...(this.state.selected && this.state.selected.isCopyable
? [
() => {
if (
this.state.selected &&
this.state.selected.text !== undefined
) {
Clipboard.setString(this.state.selected.text)
}
}
]
: [])
]
if (index < actions.length) {
actions[index]()
}
}
showInviteModal = () => {
this.setState({ showInviteContactModal: true })
}
hideInviteModal = () => {
this.setState({ showInviteContactModal: false })
}
showRenameGroupModal = () => {
this.setState({ showRenameGroupModal: true })
}
hideRenameGroupModal = () => {
this.setState({ showRenameGroupModal: false })
}
cancelRenameGroup = () => {
this.hideRenameGroupModal()
}
completeRenameGroup = () => {
this.hideRenameGroupModal()
// Update navigation params in case groupName changed
this.props.navigation.setParams({
groupName: this.props.groupName
})
}
liking = (blockId: string) => {
return this.props.liking.indexOf(blockId) !== -1
}
showToastWithMessage = (message: string) => {
return () => {
if (this.toast) {
this.toast.show(message, 3000)
}
}
}
removing = (blockId: string) => {
return this.props.removing.indexOf(blockId) !== -1
}
}
const mapStateToProps = (
state: RootState,
ownProps: NavigationScreenProps<NavProps>
): StateProps => {
const threadId = ownProps.navigation.getParam('threadId')
const items = groupItems(state.group, threadId)
const threadData = state.groups.threads[threadId]
const initiator = threadData ? threadData.initiator : ''
const sharing = threadData ? threadData.sharing : Thread.Sharing.NOT_SHARED
const canInvite = sharing !== Thread.Sharing.NOT_SHARED
const groupName = threadData ? threadData.name : 'Unknown'
const selfAddress = accountSelectors.getAddress(state.account) || ''
const renaming = Object.keys(state.group.renameGroup).indexOf(threadId) > -1
const liking = Object.keys(state.ui.likingPhotos)
const removing = Object.keys(state.group.ignore).filter(key => {
return state.group.ignore[key] !== {}
})
return {
threadId,
items,
groupName,
initiator,
selfAddress,
renaming,
canInvite,
liking,
removing
}
}
const mapDispatchToProps = (
dispatch: Dispatch<RootAction>,
ownProps: NavigationScreenProps<NavProps>
): DispatchProps => {
const threadId = ownProps.navigation.getParam('threadId')
return {
refresh: () =>
dispatch(groupActions.feed.refreshFeed.request({ id: threadId })),
addPhotoLike: (block: string) =>
dispatch(UIActions.addLike.request({ blockId: block })),
navigateToComments: (id: string) =>
dispatch(UIActions.navigateToCommentsRequest(id, threadId)),
leaveThread: () => dispatch(GroupsActions.removeThreadRequest(threadId)),
retryShare: (key: string) => {
dispatch(groupActions.addPhoto.retry(key))
},
cancelShare: (key: string) => {
dispatch(groupActions.addPhoto.cancelRequest(key))
},
remove: (blockId: string) => {
dispatch(groupActions.ignore.ignore.request(blockId))
}
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Group) | the_stack |
declare module 'gvis' {
export = gvis;
}
declare namespace gvis {
/**
* BaseApi Class for all future charts.
* @preferred
*/
export abstract class BaseApi {
protected version: string;
instanceIndex: number;
typeName: string;
container: any;
data: any;
render: any;
event: any;
layout: any;
language: any;
options: any;
constructor();
/**
* Set customized color by name for all ECharts based chart.
*
* @example Change color for series data.
* <pre>
* chart.setColorByName('Users', '#f00');
* chart.setColorByName('Series 1', '#f00');
* chart.setColorByName('Series 2', '#00ff00');
* chart.setColorByName('China', '#f0f');
* chart.setColorByName('Shanghai', '#aabbcc');
*
* </pre>
* @param {string} name [description]
* @param {string} color [description]
* @return {this} [description]
*/
setColorByName(name: string, color: string): this;
/**
* Return the customized color by name;
*
* @example Get current color for a series.
* <pre>
* console.assert(chart.getColorByName('Users'), '#f00');
* console.assert(chart.getColorByName('Series 1'), '#f00');
* console.assert(chart.getColorByName('Series 2'), '#00ff00');
* console.assert(chart.getColorByName('China'), '#f0f');
* console.assert(chart.getColorByName('Shanghai'), '#aabbcc');
* </pre>
* @param {string} name [description]
* @return {string} [description]
*/
getColorByName(name: string): string | undefined;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Data Base Class.
*
* Created on: Oct 5th, 2016
* Author: Xiaoke Huang
******************************************************************************/
/**
* Base Data Object Class for all Data object in the GVIS.
* @preferred
*/
export abstract class BaseData {
/**
* Store any additional data values within this field.
*/
extra: any;
/**
* This field can be used to return any error message for any data object.
*/
error: string;
constructor();
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: base event Class.
*
* Created on: Oct 24th, 2016
* Author: Xiaoke Huang
******************************************************************************/
/**
* Base Mouse Event Class. It represetns a single pointer.
* @preferred
*/
export class BaseMouseEvent {
altKey: boolean;
ctrlKey: boolean;
shiftKey: boolean;
/**
* Returns which mouse button was pressed when the mouse event was triggered
* 0 : The left mouse button
* 1 : The middle mouse button
* 2 : The right mouse button
* @type {number}
*/
button: number;
/**
* Returns which mouse buttons were pressed when the mouse event was triggered
* 1 : The left mouse button
* 2 : The right mouse button
* 4 : The middle mouse button
* 8 : The fourth mouse button (typically the "Browser Back" button)
* 16 : The fifth mouse button (typically the "Browser Forward" button)
* @type {number}
*/
buttons: number;
/**
* Returns which mouse button was pressed when the mouse event was triggered
* 1 : The left mouse button
* 2 : The middle mouse button
* 3 : The right mouse button
* @type {number}
*/
which: number;
/** @type {number} Returns a number that indicates how many times the mouse was clicked */
/** @type {number} Returns the horizontal coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered */
clientX: number;
/** @type {number} Returns the vertical coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered */
clientY: number;
/** @type {number} Returns the horizontal coordinate of the mouse pointer, relative to the screen, when an event was triggered */
/** @type {number} Returns the vertical coordinate of the mouse pointer, relative to the screen, when an event was triggered */
/** @type {number} Returns the horizontal coordinate of the mouse pointer, relative to the document, when the mouse event was triggered */
pageX: number;
/** @type {number} Returns the vertical coordinate of the mouse pointer, relative to the document, when the mouse event was triggered */
pageY: number;
/** @type {Object} Returns the element related to the element that triggered the mouse event */
relatedTarget: Object;
preventDefault: {
(): void;
};
constructor(event: any);
}
/**
* KeyBoard Base Event class. It represetns a single key press.
*/
export class BaseKeyboardEvent {
altKey: boolean;
ctrlKey: boolean;
shiftKey: boolean;
metaKey: boolean;
/** @type {string} Returns the Unicode character code of the key that triggered the onkeypress event */
charCode: string;
/** @type {string} Returns the key value of the key represented by the event */
key: string;
/** @type {number} Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event */
keyCode: number;
/** @type {number} Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event */
which: number;
/**
* Returns the location of a key on the keyboard or device
* 0 : represents a standard key (like "A")
* 1 : represents a left key (like the left CTRL key)
* 2 : represents a right key (like the right CTRL key)
* 3 : represents a key on the numeric keypad (like the number "2" on the right keyboard side)
* @type {number}
*/
location: number;
constructor(event: any);
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Base style class.
*
* Created on: Feb 17th, 2017
* Author: Xiaoke Huang
******************************************************************************/
/**
* The base chart setting except for graph chart.
*/
export interface ChartSetting {
render?: {
container: Object;
title?: {
text?: string;
subtext?: string;
};
legend?: {
show: boolean;
};
grid?: {
left?: number | string;
top?: number | string;
right?: number | string;
bottom?: number | string;
};
textStyle?: {
color?: string;
fontStyle?: string;
fontWeight?: string;
fontFamily?: string;
fontSize?: number;
};
xAxis?: {
name?: string;
nameLocation?: string;
nameGap?: number;
nameRotate?: number;
nameTextStyle?: {
color?: string;
fontStyle?: string;
fontWeight?: string;
fontFamily?: string;
fontSize?: number;
};
};
yAxis?: {
name?: string;
nameLocation?: string;
nameGap?: number;
nameRotate?: number;
nameTextStyle?: {
color?: string;
fontStyle?: string;
fontWeight?: string;
fontFamily?: string;
fontSize?: number;
};
};
[options: string]: any;
};
formatter?: {
tooltip?: {
(...args: any[]): string;
};
};
language?: {
selectedLanguage?: string;
localization?: {
[language: string]: {
vertex?: {
[type: string]: string | {
type?: string;
attrs: {
[attribute: string]: string | {
attr?: string;
values: {
[value: string]: string;
};
};
};
};
};
edge?: {
[type: string]: string | {
type?: string;
attrs: {
[attribute: string]: string | {
attr?: string;
values: {
[value: string]: string;
};
};
};
};
};
};
};
};
}
/**
* Base style class for all charts except the graph chart.
*/
export class BaseStyle {
defaultChartStyle: {
[styles: string]: any;
};
color: Color;
customizedColor: {
[keys: string]: string;
};
constructor();
/**
* Set customized color by name for all ECharts based chart.
* @param {string} name [description]
* @param {string} color [description]
* @return {this} [description]
*/
setColorByName(name: string, color: string): this;
/**
* Return the color by name;
* @param {string} name [description]
* @return {string} [description]
*/
getColorByName(name: string): string;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: GVIS library main interface.
*
* Created on: Oct 5th, 2016
* Author: Xiaoke Huang
******************************************************************************/
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Bar Chart Class
*
* Created on: Feb 15th, 2017
* Author: Xiaoke Huang
******************************************************************************/
export interface BarChartSetting extends ChartSetting {
formatter?: {
/**
* horizontal | vertical;
* @type {[type]}
*/
orient?: string;
/**
* xAxis label formatter
* @param {string} value of the tick.
* @param {number} index of the tick.
* @return {string} label of the tick.
*/
xAxis?: (value: string, index: number) => string;
/**
* yAxis label formatter
* @param {number} value of the tick.
* @param {number} index of the tick.
* @return {string} label of the tick.
*/
yAxis?: (value: number, index: number) => string;
tooltip?: (params: {
componentType: 'series';
seriesType: string;
seriesIndex: number;
seriesName: string;
name: string;
dataIndex: number;
data: Object;
value: any;
color: string;
percent: number;
}, ticket?: string, callback?: {
(ticket: string, html: string): void;
}) => string;
};
label?: {
show?: boolean;
position?: string;
};
language?: {
selectedLanguage?: string;
localization?: {
[language: string]: {
vertex?: {
[type: string]: string | {
type?: string;
attrs: {
[attribute: string]: string | {
attr?: string;
values: {
[value: string]: string;
};
};
};
};
};
edge?: {
[type: string]: string | {
type?: string;
attrs: {
[attribute: string]: string | {
attr?: string;
values: {
[value: string]: string;
};
};
};
};
};
};
};
};
}
export class BarChart extends BaseApi {
render: BarChartRender;
data: BarChartData;
event: BarChartEvent;
options: BarChartSetting;
/**
* Creates an instance of BarChart.
*
* @example Create an instance of BarChart by using a customized configuration.
* <pre>
* window.barchart = new gvis.BarChart({
* render: {
* container: document.getElementById("BarChart 1"),
* legend: {
* show: true
* },
* grid: {
* left: 250,
* right: 80
* },
* textStyle: {
* color: '#f00',
* fontStyle: 'italic',
* fontWeight: 'bolder',
* fontFamily: '"Courier New", Courier, monospace',
* fontSize: 20,
* }
* },
* formatter: {
* orient: 'horizontal',
* xAxis: function(v, i) {
* return `GET /vertex/value1 /value 2Test ${v}`;
* },
* yAxis: function(v, i) {
* return `${v} times/hour`;
* },
* tooltip: function(params, ticket) {
* console.log(params);
* return `${params}`;
* }
* },
* label: {
* show: true,
* position: 'right'
* }
* });
*
* barchart
* .addData(testData)
* .update();
* </pre>
*
* @param {BarChartSetting} options
* @memberof BarChart
*/
constructor(options: BarChartSetting);
/**
* Add a bar chart data
*
* @example Create a test data, and add it in barchart.
*
* <pre>
* var testData = [];
* for (var i=1; i<testN; i++) {
*
* testData.push({
* series: 'Count',
* x: i,
* y: +(testN + 2 * i * +Math.random()).toFixed(1)
* });
*
* testData2.push({
* series: 'Count',
* x: i,
* y: +(2 * i * +Math.random()).toFixed(1)
* });
*
* testData.push({
* series: 'Count'+i%2,
* x: i,
* y: +(testN - 2 * i * +Math.random()).toFixed(1)
* });
* }
*
* barchart
* .addData(testData)
* .update();
*
* // add new data points for every 1 second.
*
* setInterval(() => {
* var tmp = [];
* tmp.push({
* series: 'Count',
* x: testN,
* y: +(testN * Math.random()).toFixed(1)
* });
* barchart
* .addData(tmp)
* .update();
* testN += 1;
*
* if (testN >= 18) {
* clearInterval(window.tmp);
* }
* }, 1000);
* </pre>
*
* @param {BarChartDataPoint[]} data
* @returns {this}
*
* @memberOf BarChart
*/
addData(data: BarChartDataPoint[]): this;
/**
* Drop all data from the chart, and load the new data in the chart.
*
* @example reload all data of barchart.
* <pre>
* barchart.reloadData(testData).update();
* </pre>
* @param {BarChartDataPoint[]} data
* @returns {this}
*
* @memberOf BarChart
*/
reloadData(data: BarChartDataPoint[]): this;
/**
* Rerender the chart, it needs to be called for all the changes in the chart.
* @example update barchart.
* <pre>
* barchart.update();
* </pre>
* @returns {this}
*
* @memberOf BarChart
*/
update(): this;
/**
* Update the setting of labels for the bar in the chart.
* options:
* `show`:
* - `true`
* - `false`
* `position`:
* - `right`
* - `top`
* - `bottom`
* - `left`
*
* @example Update settings for labels of barchart
* <pre>
* barchart.updateLabel({
* show: true,
* position: top
* })
* .update();
* </pre>
* @param {{
* show?: boolean;
* position?: string;
* }} option
* @returns {this}
*
* @memberOf BarChart
*/
updateLabel(option: {
show?: boolean;
position?: string;
}): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Bar chart data module class.
*
* Created on: Feb 14th, 2017
* Author: Xiaoke Huang
******************************************************************************/
/**
* x is the category value. Such as Query Name
* y is the value. Such call times.
* series is the series value.
* info can be use for other information.
*/
export interface BarChartDataPoint {
series: string;
x: string;
y: number;
info?: {
[key: number]: any;
};
}
export class BarChartData {
private chart;
private inData;
private maxBarNumber;
private axisID;
constructor(parent: BaseApi);
/**
* add a bar data in the bar chart. Not allow duplicated x value for a single series data.
* @param {BarChartDataPoint} data [description]
* @return {this} [description]
*/
addData(data: BarChartDataPoint): this;
/**
* Set the max bar number. If the bar number is larger than max bar number. The smallest bar will be discard.
* @param {number} n [description]
* @return {this} [description]
*/
setMaxBarNumber(n: number): this;
getSeries(): string[];
/**
* It returns the max value of y in all series. It will be used for the feature of the y axis range.
* @return {number} [description]
*/
getYMax(): number;
/**
* It returns the min value of y in all series. It will be used for generate yAxis range.
* @return {number} [description]
*/
getYMin(): number;
getXMaxNumber(): number;
/**
* Get the largest series data x value array.
* @return {any[]} [description]
*/
getXAxisData(): any[];
/**
* change the major axis value series id. The bar order will be changed.
* @param {number} id [description]
* @return {this} [description]
*/
setAxisID(id: number): this;
/**
* get data points array by series name.
* @param {string} series [description]
* @return {BarChartDataPoint[]} [description]
*/
getData(series: string): BarChartDataPoint[];
/**
* get the y axis data for a series. It will return an array which match the getXAxisData format. Undefined will be used for non existed value.
* @param {string} series [description]
* @return {BarChartDataPoint[]} [description]
*/
getYAxisData(series: string): any[];
/**
* Clean the data by series name.
* @param {string} series [description]
* @return {BarChartDataPoint[]} [description]
*/
cleanSeriesData(series: string): BarChartDataPoint[];
/**
* Sort the y value by ascending order.
* @param {BarChartDataPoint} a [description]
* @param {BarChartDataPoint} b [description]
* @return {number} [description]
*/
private compare(a, b);
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Bar chart event module class.
*
* Created on: Feb 15th, 2017
* Author: Xiaoke Huang
******************************************************************************/
export interface BarChartEventHandlers {
[eventName: string]: {
(...args: any[]): void;
};
}
export interface EChartsMouseEvent {
componentType: string;
seriesType: string;
seriesIndex: number;
seriesName: string;
name: string;
dataIndex: number;
data: Object;
dataType: string;
value: number | number[];
color: string;
}
export class BarChartEvent {
private chart;
private defaultHandlers;
private handlers;
constructor(parent: BaseApi);
getEventsName(): string[];
/**
* get event callback instance by event Name;
* @param {BaseApi} eventName [description]
*/
getEventHandler(eventName: string): {
(...args: any[]): void;
};
setEventHandler(eventName: string, callback: {
(...args: any[]): void;
}): this;
}
/**
* ECharts Options Typings. Needs to get ECharts Typings.
*/
export interface EBarChartsOptions {
[option: string]: any;
}
export class BarChartRender {
private chart;
private engine;
private style;
private timer;
private timerTask;
private options;
constructor(parent: BaseApi);
private init();
/**
* init Events binding.
* @return {this} [description]
*/
private initEvents();
/**
* Refined user input chart options for echarts.
* @param {EBarChartsOptions} options [description]
* @return {any} [description]
*/
private refineUserOptions(options);
private initFormatter();
update(): this;
/**
* Update the basic settings. It will affect current cart directly.
* @return {this} [description]
*/
updateSettings(options?: EBarChartsOptions): this;
/**
* Redraw the line chart. It will create a new engine instance.
* @return {this} [description]
*/
redraw(): this;
/**
* Clear the line chart object.
*/
clear(): this;
updateLabelSetting(option: {
show?: boolean;
position?: string;
}): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: bar chart style module class.
*
* Created on: Feb 15th, 2017
* Author: Xiaoke Huang
******************************************************************************/
export class BarChartStyle extends BaseStyle {
private chart;
private defaultBarChartStyle;
label: {
[keys: string]: any;
};
constructor(parent: BaseApi);
getStyleOptions(): any;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Graph Chart Class
*
* Created on: Oct 6th, 2016
* Author: Xiaoke Huang
******************************************************************************/
export interface GraphChartSetting {
advanced?: {
maxNodeLimit?: number;
maxLinkLimit?: number;
hideArrorMinZoom?: number;
nodeToolTipSetting?: {
(inNode: GraphChartDataNode, coreNode?: any, chart?: BaseApi): any;
};
linkToolTipSetting?: {
(inLink: GraphChartDataLink, coreLink?: any, chart?: BaseApi): any;
};
nodeMenuContentsFunction?: {
(inNode: GraphChartDataNode, coreNode?: any, config?: any, returnDefaultContent?: {
(): any;
}): any;
};
linkMenuContentsFunction?: {
(inLink: GraphChartDataLink, coreLink?: any, config?: any, returnDefaultContent?: {
(): any;
}): any;
};
};
renderType?: string;
render?: any;
style?: {
node?: {
condition: string | {
(node: GraphChartDataNode, chart: BaseApi): boolean;
};
style: GraphStyle.GraphChartNodeStyleInterface;
}[];
link?: {
condition: string | {
(link: GraphChartDataLink, chart: BaseApi): boolean;
};
style: GraphStyle.GraphChartLinkStyleInterface;
}[];
};
icon?: {
[exType: string]: string;
};
graphSchema?: {
VertexTypes: {
Name: string;
}[];
EdgeTypes: {
Name: string;
}[];
};
nodeMenu?: {
buttons?: {
label: string;
callback: {
(node: GraphChartDataNode, chart: BaseApi): void;
};
}[];
enabled: boolean;
};
linkMenu?: {
buttons?: {
label: string;
callback: {
(link: GraphChartDataLink, chart: BaseApi): void;
};
}[];
enabled: boolean;
};
language?: {
selectedLanguage?: string;
localization?: {
[language: string]: {
vertex?: {
[type: string]: string | {
type?: string;
attrs: {
[attribute: string]: string | {
attr?: string;
values: {
[value: string]: string;
};
};
};
};
};
edge?: {
[type: string]: string | {
type?: string;
attrs: {
[attribute: string]: string | {
attr?: string;
values: {
[value: string]: string;
};
};
};
};
};
};
};
};
}
/**
* Graph Chart Visualization Object
* @preferred
*/
export class GraphChart extends BaseApi {
typeName: string;
container: any;
/**
* graph data object
* @type {GraphChartData}
*/
data: GraphChartData;
/**
* User to parse external data to exteranl graph.
* @type {GraphParser}
*/
parser: GraphParser;
/**
* Rendering engine object.
* @type {any}
*/
render: GraphChartRender;
/**
* Layout object for graph visualization.
* @type {GraphChartLayout}
*/
layout: GraphChartLayout;
/**
* Event object for graph visualization.
* @type {GraphChartEvent}
*/
event: GraphChartEvent;
/**
* global settings for graph chart.
* @type {GraphChartSetting}
*/
options: GraphChartSetting;
language: Localization;
style: any;
/**
* Creates an instance of GraphChart by using GraphChartSetting.
*
* @example Create a graph chart instance.
* <pre>
* // import { GraphChart } from 'gvis';
* // const GraphChart = require('gvis').GraphChart;
*
* var chart = new GraphChart({
* advanced: {
* maxNodeLimit: 5000,
* maxLinkLimit: 10000
* },
* render: {
* assetsUrlBase: '/dist/assets',
* advanced: {
* showFPS: true
* },
* container: document.getElementById('GraphChart'),
* },
* icon: {
* 'UserCard': 'BankCard1',
* 'IdCard': 'idCard'
* },
* style: {
* node: [{
* condition: 'type === "p_order" || id === "TID-00000000000000000100" || id.indexOf("User") !== -1',
* style: {
* radius: 100,
* }
* },{
* condition: (node, chart) => {
* return node.exType === "Txn" && node.exID.indexOf("1909") !== -1;
* },
* style: {
* radius: 200,
* icon: 'Open Disconnector',
* display: 'rectangle',
* aspectRatio: 0.35
* }
* }],
* link: [{
* condition: 'type === "prodOrder"',
* style: {
* radius: 20,
* }
* },
* {
* condition: 'type === "prodOrder"',
* style: {
* fillColor: '#000000'
* }
* },
* ]
* },
* language: {
* selectedLanguage: 'zh',
* localization: {
* 'zh': {
* vertex: {
* 'built-in-translate': {
* attrs: {
* 'menu': {
* values: {
* 'Set as Start Vertex': '设置为出发点',
* 'Set as End Vertex': '设置为终止点',
* 'View Statistics Information': '查看统计信息'
* }
* }
* }
* },
* 'Txn': {
* type: '交易',
* attrs: {
* 'acct_date': {
* attr: '注册时间',
* values: {
* '20150023': '2015年1月23号',
* '20150313': '2015年4月13号'
* }
* },
* 'trans_type': {
* values: {
* 'A': '非法交易',
* 'B': '黑交易',
* 'C': '白交易',
* 'D': '未知交易'
* }
* },
* 'self': '交易流水号',
* 'merchant': '商户号',
* 'merchant_order': '商户订单号'
* }
* },
* 'Sid': {
* attrs: {
* 'id': 'ID',
* 'type': 'Sid类型'
* }
* }
* },
* edge: {
* 'built-in-translate': {
* attrs: {
* 'menu': {
* values: {
* 'View Statistics Information': '查看统计信息'
* }
* }
* }
* },
* 'Sid_User': {
* type: '使用中',
* attrs: {
* 'txn_time': {
* attr: '交易时间',
* values: {
* '13:42:06': '13点42分06秒'
* }
* }
* }
* }
* }
* }
* }
* },
* nodeMenu: {
* enabled: true,
* buttons: [{
* label: 'Set as Start Vertex',
* callback: function (node, chart) {
* console.log('start vertex menu click: ', node, ' ', chart);
* }
* },
* {
* label: 'Set as End Vertex',
* callback: function (node, chart) {
* console.log('end vertex menu click: ', node, ' ', chart);
* }
* },
* {
* label: 'View Statistics Information',
* callback: function (node, chart) {
* console.log('View Statistics Information Node menu click: ', node, ' ', chart);
* }
* }
* ]
* },
* linkMenu: {
* enabled: true,
* buttons: [{
* label: 'View Statistics Information',
* callback: function (link, chart) {
* console.log('View Statistics Information Link menu click: ', link, ' ', chart);
* }
* }]
* }
* })
*
* </pre>
* @param {GraphChartSetting} options
*/
constructor(options: GraphChartSetting);
/**
* redraw the chart in graphics level.
*
* @returns {this}
* @memberof GraphChart
*/
paint(): this;
/**
* Rerender the graph chart.
*
* @returns {this}
* @memberof GraphChart
*/
update(): this;
/**
* Sync the coordinate of dynamic layout between render data and internal data.
*
* @returns {this}
* @memberof GraphChart
*/
updateCoordinate(): this;
/**
* Add sub graph.
*
* @example Add a sub graph.
* <pre>
* var graph = JSON Object;
* chart.addData(graph, 'gquery');
* chart.addData(graph, 'gquery', 'extend');
* chart.addData(graph, 'ksubgraph', 'defaults');
* chart.addData(graph, 'ksubgraph', 'extend', {
* node: 'extend',
* link: 'overwrite'
* });
* chart.addData(graph, 'gquery', undefined, {
* node: undefined,
* link: 'extend'
* });
* chart.addData(graph, 'gquery', 'extend', {
* node: 'extend',
* link: 'extend'
* });
* </pre>
*
* @param {any} externalData [description]
* @param {any} externalDataType
* It is used to specify the graph format of the external data. Base on this filed, the corresponding parser is used to parse external data into external graph. A list of built in parser:
* - `static` no parser. Use original data object.
* - `gquery` use for standard gquery output.
* - `ksubgraph` use for ksubgraph output.
* - `pta` use for pta output.
* - `gpr` use for gpr output.
* - `restpp` use for restpp standard api output.
* - `gst` use for graph studio output.
*
* @param {string} nodeOption = `extend` [description]
* Add node base on option. Check out the utils module for detailed information for option.
* Example for adding a node A with an existing node B: two nodes A and B.
* - `defaults` : Merge A and B, if there are same field, use values from A;
* - `extend` : Merge A and B, if there are same field, use values from B;
* - `overwrite` : Use values from B overwrite the same fields of A;
*
* @param {AddLinkOption} linkOption [description]
* Add link base on option, and add link's source and target base on option.
* Example for adding an link L1 = `A_`->`B_`: There is a link L2 = A->B is existed. `A_` and A point to a same node,
* `B_` and B point to a same node. But attributes, styles, others of them may different.
*
* Link option.link (not handle source and target nodes):
* - `defaults` : Merge L1 and L2, if there are same field, use values from L1;
* - `extend` : Merge L1 and L2, if there are same field, use values from L2;
* - `overwrite` : Use values from L2 overwrite the same fields of L2;
*
* Link option.node (handle source and target nodes)
* This options is used for handling existed source or target node, such as `A_`(new) and A(old). The option is same as addNode APIs:
* - `defaults` : Merge `A_` and A, if there are same field, use values from A;
* - `extend` : Merge `A_` and A, if there are same field, use values from `A_`;
* - `overwrite` : Use values from `A_` overwrite the same fields of A;
*
* @return {this} [description]
*/
addData(externalData: any, externalDataType?: string, nodeOption?: string, linkOption?: AddLinkOption): this;
/**
* drop a sub graph base on the json object's format.
*
* @example Drop a sub graph.
* <pre>
* var graph = JSON Object;
* chart.dropData(graph, 'gquery');
* chart.dropData(graph, 'ksubgraph');
* chart.dropData(graph, 'gpr');
* chart.dropData(graph, 'gst');
* ...
* </pre>
*
* @param {*} externalData
* @param {string} externalDataType
* It is used to specify the graph format of the external data. Base on this filed, the corresponding parser is used to parse external data into external graph. A list of built in parser:
* - `static` no parser. Use original data object.
* - `gquery` use for standard gquery output.
* - `ksubgraph` use for ksubgraph output.
* - `pta` use for pta output.
* - `gpr` use for gpr output.
* - `restpp` use for restpp standard api output.
* - `gst` use for graph studio output.
*
* @returns {this}
*/
dropData(externalData: any, externalDataType?: string): this;
/**
* reload new graph in the graph visualization without clean the internal index.
*
* @example Reload a new graph.
*
* <pre>
* var graph = JSON Object;
* chart.reloadData(graph, 'gquery');
* chart.reloadData(graph, 'gpr');
* chart.reloadData(graph, 'restpp');
* ...
*
* </pre>
*
* @param {any} externalData [description]
* @param {any} externalDataType
* It is used to specify the graph format of the external data. Base on this filed, the corresponding parser is used to parse external data into external graph. A list of built in parser:
* - `static` no parser. Use original data object.
* - `gquery` use for standard gquery output.
* - `ksubgraph` use for ksubgraph output.
* - `pta` use for pta output.
* - `gpr` use for gpr output.
* - `restpp` use for restpp standard api output.
* - `gst` use for graph studio output.
*
* @return {this} [description]
*/
reloadData(externalData: any, externalDataType?: string): this;
/**
* delete the old graph visualization, and recreate a new graph visualization by using the new graph.
*
* @example Reset a new graph.
*
* <pre>
* var graph = JSON Object;
* chart.resetData(graph, 'gquery');
* chart.resetData(graph, 'gpr');
* chart.resetData(graph, 'restpp');
* ...
*
* </pre>
*
* @param {*} externalData
* @param {string} externalDataType
* It is used to specify the graph format of the external data. Base on this filed, the corresponding parser is used to parse external data into ext ernal graph. A list of built in parser:
* - `static` no parser. Use original data object.
* - `gquery` use for standard gquery output.
* - `ksubgraph` use for ksubgraph output.
* - `pta` use for pta output.
* - `gpr` use for gpr output.
* - `restpp` use for restpp standard api output.
* - `gst` use for graph studio output.
*
* @returns {this}
*/
resetData(externalData: any, externalDataType?: string): this;
/**
* Reset layout and redarw everything in the viewport.
*
* @example Redraw a graph.
* <pre>
* var graph = JSON Object;
* chart
* .addData(graph)
* .runLayout('force')
* .update();
*
* chart.redraw();
* </pre>
* @return {this} [description]
*/
redraw(): this;
/**
* drop a node by external type and id.
*
* @example Drop nodes.
* <pre>
* // Drop current selected nodes
* chart.getSelection().nodes.forEach(n => {
* chart.dropNode(n.exType, n.exID, true);
* })
*
* // Drop a taget node.
* chart.dropNode('Txn', '001', false);
*
* // Drop the first node in graph.
* var node = chart.getNodes()[0];
* chart.dropNode(node.exType, node.exID);
* </pre>
* @param {[type]} ExternalNode [description]
* @param {boolean} option dropping node will drop related links. While we drop links, we use option
* to determine whether or not we drop the isolated nodes:
* - `true`: drop isolated nodes
* - `false`: do not drop isolated nodes.
* @return {DroppedItems} The nodes dropped. The first one is the target dropping node.
*/
dropNode(exType: string, exID: string, option?: boolean): DroppedItems;
/**
* drop a link by external type, source, target.
*
* @example Drop Links
* <pre>
* // Drop current selected links
* chart.getSelection().links.forEach(l => {
* chart.dropLink(l.exType, l.source.exType, l.source.exID, l.target.exType, l.target.exID);
* })
*
* // Drop the first link in the graph
* var link = chart.getLinks()[0];
* chart.dropLink(link.exType, link.source.exType, link.source.exID, link.target.exType, link.target.exID);
*
* // Drop the last link in the graph, and remove the target or source nodes if it is isolated nodes.
* var links = chart.getLinks();
* var link = links.pop();
* chart.dropLink(link.exType, link.source.exType, link.source.exID, link.target.exType, link.target.exID, false);
* </pre>
*
* @param {string} exType link external type
* @param {string} sourceExType source node external type
* @param {string} sourceExID source node external id
* @param {string} targetExType target node external type
* @param {string} targetExID target node external id
* @param {[type]} option It is sed to determine if you want to drop isolated nodes:
* - `true`: don't remove any nodes from graph while dropping links.
* - `false`: do remove source and target nodes of this link, if the node is isolated. And use the same option for dropping other related nodes and links.
* @return {DroppedItems} [description]
*/
dropLink(exType: string, sourceExType: string, sourceExID: string, targetExType: string, targetExID: string, option?: boolean): DroppedItems;
/**
* Closes a node. Hide target node's neighbor nodes which only connetect with target.
*
* @example Close 1 step neighborhood of a target node.
* <pre>
* var node = chart.getSelection().nodes[0];
* chart
* .closeNode(node.exType, node.exID)
* .update();
* </pre>
*
* @param {string} exType [description]
* @param {string} exID [description]
* @return {this} [description]
*/
closeNode(exType: string, exID: string): this;
/**
* Collapse a node. Hide target node, and all its neighbor nodes.
*
* @example Collapse the target node.
* <pre>
* var node = chart.getSelection().nodes[0];
* chart
* .collapseNode(node.exType, node.exID)
* .update();
* </pre>
* @param {string} exType [description]
* @param {string} exID [description]
* @return {this} [description]
*/
collapseNode(exType: string, exID: string): this;
/**
* Expands a visible node. Show all one step neighbor nodes of target node.
*
* @example Expand 1 step neighborhood of a target node.
* <pre>
* var node = chart.getSelection().nodes[0];
*
* chart
* .expandNode(node.exType, node.exID)
* .update();
* </pre>
* @param {string} exType [description]
* @param {string} exID [description]
* @return {this} [description]
*/
expandNode(exType: string, exID: string): this;
/**
* hide a node.
*
* @example Hide current selected nodes.
* <pre>
* var nodes = chart.getSelection().nodes;
*
* nodes.forEach(n => {
* chart.hideNode(n.exType, n.exID)
* })
*
* chart.update();
*
* </pre>
* @param {string} exType [description]
* @param {string} exID [description]
* @return {this} [description]
*/
hideNode(exType: string, exID: string): this;
/**
* show an hidden node.
*
* @example Show a hidden node.
* <pre>
* var node = chart.getNodes()[0];
* chart.hideNode(n.exType, n.exID);
* chart.showNode(n.exType, n.exID)
*
* chart.update();
*
* </pre>
* @param {string} exType [description]
* @param {string} exID [description]
* @return {this} [description]
*/
showNode(exType: string, exID: string): this;
/**
* Fixates a node in place.
*
* @example Lock a node, and fixates it to [0, 0];
* <pre>
* var node = chart.getNodes()[0];
*
* chart.lockNode(node, 0, 0).paint();
* </pre>
* @param {GraphChartDataNode} node
* @param {number} [x]
* @param {number} [y]
* @returns {this}
* @memberof GraphChart
*/
lockNode(node: GraphChartDataNode, x?: number, y?: number): this;
/**
* Unfixates a node and allows it to be repositioned by the layout algorithms.
*
* @example ublock a node;
* <pre>
* var node = chart.getNodes()[0];
*
* chart.unlockNode(node);
* </pre>
* @param {GraphChartDataNode} node
* @returns {this}
* @memberof GraphChart
*/
unlockNode(node: GraphChartDataNode): this;
/**
* Lowlight a node base on external type, and external ID.
*
* @example Lowlight all nodes.
* <pre>
* var nodes = chart.getNodes();
*
* nodes.forEach(n => {
* chart.lowlightNode(n.exType, n.exID)
* })
*
* chart.update();
*
* </pre>
* @param {string} exType [description]
* @param {string} exID [description]
* @return {this} [description]
*/
lowlightNode(exType: string, exID: string): this;
/**
* UnLowlight a node base on external type, and external ID.
*
* @example UnLowlight all nodes.
* <pre>
* var nodes = chart.getNodes();
*
* nodes.forEach(n => {
* chart.unLowlightNode(n.exType, n.exID)
* })
*
* chart.update();
*
* </pre>
* @param {string} exType [description]
* @param {string} exID [description]
* @return {this} [description]
*/
unLowlightNode(exType: string, exID: string): this;
/**
* Lowlight a link base on edge type, source, and target.
*
* @example Lowlight all links.
* <pre>
* var links = chart.getLinks();
*
* links.forEach(l => {
* chart.lowlightLink(l.exType, l.source.exType, l.source.exID, l.target.exType, l.target.exID);
* })
*
* chart.update();
*
* </pre>
* @param {string} exType [description]
* @param {string} sourceExType [description]
* @param {string} sourceExID [description]
* @param {string} targetExType [description]
* @param {string} targetExID [description]
* @return {this} [description]
*/
lowlightLink(exType: string, sourceExType: string, sourceExID: string, targetExType: string, targetExID: string): this;
/**
* Un Lowlight a link base on edge type, source, and target.
*
* @example UnLowlight all links.
* <pre>
* var links = chart.getLinks();
*
* links.forEach(l => {
* chart.unLowlightLink(l.exType, l.source.exType, l.source.exID, l.target.exType, l.target.exID);
* })
*
* chart.update();
*
* </pre>
* @param {string} exType [description]
* @param {string} sourceExType [description]
* @param {string} sourceExID [description]
* @param {string} targetExType [description]
* @param {string} targetExID [description]
* @return {this} [description]
*/
unLowlightLink(exType: string, sourceExType: string, sourceExID: string, targetExType: string, targetExID: string): this;
/**
* Clear current visualization viewport.
*
* @example Clear the current visualization.
* <pre>
* chart.clear();
* </pre>
*
* @return {this} [description]
*/
clear(): this;
/**
* Export current graph viewport to a file.
*
* @example Export visualization result as a certain format.
* <pre>
* chart.export('screenshot');
* chart.export('screenshot1', 'pdf');
* chart.export('screenshot2', 'png');
* chart.export('screenshot3', 'jpg');
* chart.export('data', 'csv');
* ...
*
* </pre>
*
* @param {string} name output file name which is not include extension.
* @param {string} type [description] value supports:
* - `pdf`
* - `png`
* - `jpg`
* - `pdf`
* - `csv`
* @return {this} [description]
*/
export(name: string, type?: string): this;
/**
* get nodes APIs.
*
* @example Get nodes data object in graph visualization.
* <pre>
* // Get all nodes.
* var nodes = chart.getNodes();
* console.log(`There are ${nodes.length} nodes in visualization.`);
*
* // Get all `type` nodes.
* var nodes = chart.getNodes('Person');
* console.log(`There are ${nodes.length} "Person" nodes in visualization.`);
*
* // Get a person node of which name is 'Joe'.
* var node = chart.getNodes('Person', 'Joe');
*
* </pre>
* @param {string} exType external node type.
* @param {string} exID external node id.
*
* 1. If no parameters input, return all nodes as array. Returns [] for an empty graph.
* 2. If only exType input, returns all nodes with this type. Returns [] for not type exist.
* 3. If both exType, exID are inputed, return the target node. Return undefined for not exist node.
* @return {GraphChartDataNode | GraphChartDataNode[]} [description]
*/
getNodes(exType?: string, exID?: string): GraphChartDataNode | GraphChartDataNode[];
/**
*
* Get all 1-step neighbors of a target node.
*
* @example Get selected node's 1 step neighborhood.
* <pre>
* let node = chart.getSelection().nodes[0];
* chart.getNeighbors(node);
*
* </pre>
* @param {GraphChartDataNode} node
* @returns {{
* all: GraphChartDataNode[],
* in: GraphChartDataNode[],
* out: GraphChartDataNode[]
* }}
* @memberof GraphChart
*/
getNeighbors(node: GraphChartDataNode): {
all: GraphChartDataNode[];
in: GraphChartDataNode[];
out: GraphChartDataNode[];
};
/**
* get links APIs.
*
* @example Get links data object in graph visualization.
* <pre>
* // Get all links.
* var links = chart.getLinks();
* console.log(`There are ${links.length} links in visualization.`);
*
* // Get all `type` links.
* var links = chart.getLinks('Connected');
* console.log(`There are ${links.length} "Connected" links in visualization.`);
*
* // Get a "Connected" link between Person Joe and Person Shawn
* var node = chart.getLinks('Connected', 'Person', 'Joe', 'Person', 'Shawn');
*
* </pre>
*
* @param {string} exType external link type
* @param {string} sourceExType source node external type
* @param {string} sourceExID source node exteranl id
* @param {string} targetExType target node exteranl type
* @param {string} targetExID target node external id
*
* 1. If no parameters is inputed, return all links as array. Returns [] for an empty graph.
* 2. If only exType is inputed, returns all links with this type. Returns [] for not type exist.
* 3. If exType, sourceType, sourceID are inputed, returns all links from the source node.
* 4. If input all parameters, return the target link. Return undefined for not exist link.
* @return {GraphChartDataLink | GraphChartDataLink[]} [description]
*/
getLinks(exType?: string, sourceExType?: string, sourceExID?: string, targetExType?: string, targetExID?: string): GraphChartDataLink | GraphChartDataLink[];
/**
* return all nodes and links in array
*
* @example Get graph.
* <pre>
* var graph = chart.getData();
*
* console.log(`There are ${graph.nodes.length} nodes.`);
* console.log(`There are ${graph.links.length} links.`);
* </pre>
*/
getData(): {
nodes: GraphChartDataNode | GraphChartDataNode[];
links: GraphChartDataLink | GraphChartDataLink[];
};
/**
* Get current selected nodes and links.
*
* @example Get selected subgraph.
* <pre>
* var graph = chart.getSelection();
*
* console.log(`${graph.nodes.length} nodes are selected.`);
* console.log(`${graph.links.length} links are selected.`);
* </pre>
*
* @returns {{ nodes: GraphChartDataNode[], links: GraphChartDataLink[] }}
*/
getSelection(): {
nodes: GraphChartDataNode[];
links: GraphChartDataLink[];
};
/**
* Set selected nodes and links.
*
* @example Set selected nodes and links.
*
* <pre>
* // select all nodes and links.
* var nodes = chart.getNodes();
* var links = chart.getLinks();
*
* chart.setSelection([...nodes, ...links]);
*
* // select the root node.
* chart.setSelection([chart.getRoot()]);
* chart.setSelection(chart.getRoots());
*
* // select the all 'Connected' links.
* chart.setSelection(chart.getLinks('Connected'));
*
* </pre>
*
* @param {((GraphChartDataNode | GraphChartDataLink)[])} selected
* @returns {this}
* @memberof GraphChart
*/
setSelection(selected: (GraphChartDataNode | GraphChartDataLink)[]): this;
/**
* unselect all elements.
*
* @example Unselecte all elements.
* <pre>
* chart.unselectAllElements();
* var graph = chart.getSelection();
*
* console.assert(graph.nodes.length === 0);
* console.assert(graph.links.length === 0);
* </pre>
* @returns {this}
*/
unselectAllElements(): this;
/**
* Export legend related information and label selection information.
*
* @example export the legend object.
* <pre>
* var legendObj = chart.exportLegends();
*
* console.log(`There are ${legendObj.nodes.length} different type of nodes.`);
* console.log(`There are ${legendObj.links.length} different type of links.`);
* </pre>
*
* @returns {{
* nodes: {
* type: string;
* icon: any;
* color: string;
* labels: {
* attributeName: string;
* isSelected: boolean;
* }[];
* }[];
* links: {
* type: string;
* color: string;
* labels: {
* attributeName: string;
* isSelected: boolean;
* }[];
* }[];
* }}
*/
exportLegends(): {
nodes: {
type: string;
icon: any;
color: string;
labels: {
attributeName: string;
isSelected: boolean;
}[];
}[];
links: {
type: string;
color: string;
labels: {
attributeName: string;
isSelected: boolean;
}[];
}[];
};
/**
* Customize an event call back behavior in visualization.
* @example Binding event handler.
*
* <pre>
* chart.on('onKeyPress', (nodes, links, event, chartObject) => {
* // Do something here. event call back.
* })
*
* chart.on('onSelectionChange', (nodes, links, chartObject) => {
* // Do something here. event call back.
* })
*
* chart.on('onClick', (item) => {
* // Do something here. event call back.
* // Example:
* if (item.isNode) {
* console.log(`Node ${item.exType} ${item.exID} is clicked.`);
* } else if (item.isLink) {
* cpmsole.log(`Link ${item.id} is clicked.`);
* }
* })
*
* chart.on('onDoubleClick', (item) => {
* // Do something here for double click event.
* })
*
* chart.on('onRightClick', (item) => {
* // Do something here for right click event.
* })
*
* chart.on('onExceedLimit', (nodes, links, chart) => {
* // Do something here to handle the graph size is larger than the limitation.
* })
* </pre>
*
* @param {string} event
* Current supported events and their call back function interfaces are shown as follow:
*
* - `onKeyPress` : { (nodes: GraphChartDataNode[], links: GraphChartDataLink[], event: BaseKeyboardEvent, chart: GraphChart): void };
* - `onChartUpdate` : { (chart: GraphChart): void };
* - `onSelectionChange` : { (nodes: GraphChartDataNode[], links: GraphChartDataLink[], chart: GraphChart): void };
* - `onClick` : { (item: GraphChartDataNode | GraphChartDataLink, event: BaseMouseEvent, chart: GraphChart): void };
* - `onDoubleClick` : { (item: GraphChartDataNode | GraphChartDataLink, event: BaseMouseEvent, chart: GraphChart): void };
* - `onHoverChange` : { (item: GraphChartDataNode | GraphChartDataLink, event: BaseMouseEvent, chart: GraphChart): void };
* - `onPositionChange` : { (event: BaseMouseEvent, chart: GraphChart): void };
* - `onRightClick` : { (item: GraphChartDataNode | GraphChartDataLink, event: BaseMouseEvent, chart: GraphChart): void };
* - `onExceedLimit` : { (nodes: GraphChartDataNode[], links: GraphChartDataLink[], chart: GraphChart): void };
* @param {void }} callback event call back function.
* @return {this} chart object
*/
on(event: string, callback: {
(item?: GraphChartDataNode | GraphChartDataLink, nodes?: GraphChartDataNode[], links?: GraphChartDataLink[], keyboardEvent?: BaseKeyboardEvent, mouseEvent?: BaseMouseEvent, chart?: GraphChart): void;
}): this;
/**
* Removes an event listener by event name
*
* @example unBinding event handler.
*
* <pre>
* chart.off('onKeyPress')l;
* chart.off('onSelectionChange');
* chart.off('onClick');
* chart.off('onDoubleClick');
* chart.off('onHoverChange');
* chart.off('onRightClick');
*
* ...
* </pre>
* @param {string} event Current supported events:
* - `onKeyPress`
* - `onChartUpdate`
* - `onSelectionChange`
* - `onClick`
* - `onDoubleClick`
* - `onHoverChange`
* - `onPositionChange`
* - `onRightClick`
* @return {this} [description]
*/
off(event: string): this;
/**
* Customize node tool tip GraphStyle. callback function returns html string to display in passed nodes info popup
* @param {function} callback [description]
* @return {this} [description]
*/
/**
* Customize link tool tip GraphStyle. callback function returns html string to display in passed links info popup.
* @param {function} callback [description]
* @return {this} [description]
*/
/**
* Show labels of a target node.
*
* @example Show labels of nodes.
* <pre>
* // show 'type' in labels for all nodes.
* var nodes = chart.getNodes();
* nodes.forEach(n => {
* chart.showNodeLabels(n.exType, exID, ['type']);
* })
*
* chart.update();
*
*
* // show 'id' and 'type' in labels for all current selected nodes.
* var nodes = chart.getSelection().nodes;
* nodes.forEach(n => {
* chart.showNodeLabels(n.exType, n.exID, ['type', 'id']);
* })
*
* ...
* </pre>
* @param {string} exType node external type
* @param {string} exID node external id
* @param {string[]} labels a list of labels which want to be shown.
* @return {this} [description]
*/
showNodeLabels(exType: string, exID: string, labels: string[]): this;
/**
* Show labels of nodes with one kind of type.
*
* @example Show labels of nodes by type.
* <pre>
* // show 'type' in labels for all 'Person' nodes.
* chart
* .showNodeLabelsByType('Person', ['type']);
* .update()
*
* // show 'id' and 'type' in labels for all nodes.
* chart.exportLegends().nodes.map(n => n.type).forEach(t => {
* chart.showNodeLabelsByType(t, ['id', 'type'])
* });
* chart.update();
* ...
* </pre>
*
* @param {string} exType node external type
* @param {string[]} labels the labels want to be shown
* @return {this} [description]
*/
showNodeLabelsByType(exType: string, labels: string[]): this;
/**
* hide a target node's labels
*
* @example Hide labels of nodes
* <pre>
* // Hide 'id' and 'type' in labels of the node Person Joe.
* chart.hideNodeLabels('Person', 'Joe', ['id', 'type']).update();
*
* // Hide 'id' and 'type' for all nodes.
* chart.getNodes().forEach(n => {
* chart.hideNodeLabels(n.exType, n.exID, ['id', 'type']);
* })
*
* chart.update();
* </pre>
* @param {string} exType node external type
* @param {string} exID node external id
* @param {string[]} labels a list of labels which want to be hidden.
* @return {this} [description]
*/
hideNodeLabels(exType: string, exID: string, labels: string[]): this;
/**
* hide labels of node with one kind of type.
*
* @example Hide labels of nodes by type
* <pre>
* // Hide 'id' and 'type' in labels of the node Person.
* chart.hideNodeLabelsByType('Person', ['id', 'type']).update();
*
* // Hide 'id' and 'type' for all nodes.
* chart.exportLegends().nodes.map(n => n.type).forEach(t => {
* chart.hideNodeLabelsByType(t, ['id', 'type']);
* })
*
* chart.update();
* </pre>
*
* @param {string} exType node exteranl type
* @param {string[]} labels a list of labels that want to be hidden.
* @return {this} [description]
*/
hideNodeLabelsByType(exType: string, labels: string[]): this;
/**
* Hide all nodes' labels.
*
* @example Hide labels of nodes by type
* <pre>
* chart.hideAllNodeLabels().update();
* </pre>
* @return {this} [description]
*/
hideAllNodeLabels(): this;
/**
* Show a target links's label
*
* @example Show link labels.
* <pre>
* // Show a link's 'type' in label
* chart
* .showLinkLabels('Connected', 'Person', 'Joe', 'Person', 'Joe', ['type'])
* .update();
*
* // Show all links' 'type' in label.
* chart
* .getLinks().forEach(l => {
* chart.showLinkLabels(l.exType, l.source.exType, l.source.exID, l.target.exType, l.target.exID, ['type']);
* })
*
* chart.update();
* </pre>
* @param {string} exType link external type
* @param {string} sourceExType source node external type
* @param {string} sourceExID source node exteranl id
* @param {string} targetExType target node external type
* @param {string} targetExID target node external id
* @param {string[]} labels a list of labels that want to be shwon. such as ['type', 'time']
* @return {this} [description]
*/
showLinkLabels(exType: string, sourceExType: string, sourceExID: string, targetExType: string, targetExID: string, labels: string[]): this;
/**
* show links with a same type
*
* @example Show links' labels.
* <pre>
* // Show label 'type' of 'Connected' links.
* chart
* .showLinkLabelsByType('Connected', ['type'])
* .update();
*
* </pre>
*
* @param {string} exType link external type
* @param {string[]} labels [description]
* @return {this} [description]
*/
showLinkLabelsByType(exType: string, labels: string[]): this;
/**
* hide a target link.
*
* @example Hide link labels.
* <pre>
* // Hide a link's 'type' in label
* chart
* .hideLinkLabels('Connected', 'Person', 'Joe', 'Person', 'Joe', ['type'])
* .update();
*
* // Hide all links' 'type' in label.
* chart
* .getLinks().forEach(l => {
* chart.hideLinkLabels(l.exType, l.source.exType, l.source.exID, l.target.exType, l.target.exID, ['type']);
* })
*
* chart.update();
* </pre>
* @param {string} exType [description]
* @param {string} sourceExType [description]
* @param {string} sourceExID [description]
* @param {string} targetExType [description]
* @param {string} targetExID [description]
* @param {string[]} labels [description]
* @return {this} [description]
*/
hideLinkLabels(exType: string, sourceExType: string, sourceExID: string, targetExType: string, targetExID: string, labels: string[]): this;
/**
* hide links' label with a same type
*
* @example Hide links' labels.
* <pre>
* // Hide label 'type' of 'Connected' links.
* chart
* .hideLinkLabelsByType('Connected', ['type'])
* .update();
*
* </pre>
* @param {string} exType [description]
* @param {string[]} labels [description]
* @return {this} [description]
*/
hideLinkLabelsByType(exType: string, labels: string[]): this;
/**
* hide all links labels.
* @example Hide all links label
* <pre>
* chart.hideAllLinkLabels().update();
* </pre>
* @return {this} [description]
*/
hideAllLinkLabels(): this;
/**
* Zoom in the view. ( x2 );
*
* @example zoom in the view.
* <pre>
* chart.zoomIn().update();
* </pre>
*
* @return {this} [description]
*/
zoomIn(): this;
/**
* Zoom out the view port. ( /2 );
*
* @example zoom out the view.
* <pre>
* chart.zoomOut().update();
* </pre>
*
* @return {this} [description]
*/
zoomOut(): this;
/**
* Auto fit current graph in the view.
*
* @example autoFit the view.
* <pre>
* chart.autoFit().update();
* </pre>
*
* @return {this} [description]
*/
autoFit(): this;
/**
* Auto center a group of nodes.
*
* @example Center the selected nodes.
* <pre>
* var nodes = chart.getSelection().nodes;
* chart.scrollIntoView(nodes)
* </pre>
*
* @return {this} [description]
*/
scrollIntoView(nodes?: GraphChartDataNode[]): this;
/**
* Auto fit selected nodes and their 1-step neightborhood nodes.
*
* @example Center the view.
* <pre>
* chart.centerView()
* </pre>
*
* @return {this} [description]
*/
centerView(): this;
/**
* Call when the container size has been changed to update the chart.
*
* @example Resize the viewport
* <pre>
* document.on('resize', () => {
* chart.updateSize();
* })
* </pre>
*
* @return {this} [description]
*/
updateSize(): this;
/**
* enable/disable fullscreen of visualization.
*
* @example Enable/
* <pre>
* // Enable Fullscreen.
* chart.fullscreen(true);
*
* // Disable Fullscreen.
* chart.fullscreen(false);
* </pre>
*
* @param {boolean} isFullscreen true: fullscreen, false: normal model.
* @return {this} [description]
*/
fullscreen(isFullscreen: boolean): this;
/**
* change the default layout. Once set layout does not run the layout. It will affect the behavoir of runLayout() API.
*
* @example set graph layout
* <pre>
* chart.setLayout('default').runLayout();
* chart.setLayout('force').runLayout();
* chart.setLayout('hierarchy').runLayout();
* chart.setLayout('tree').runLayout();
* chart.setLayout('circle').runLayout();
* chart.setLayout('sphere').runLayout();
* chart.setLayout('random').runLayout();
* chart.setLayout('static').runLayout();
* </pre>
*
* @param {string} layoutName [description]
* Current default supported layout:
* - `default`
* - `force`
* - `hierarchy`
* - `tree`
* - `circle`
* - `sphere`
* - `random`
* - `static`
* @return {this} [description]
*/
setLayout(layoutName: string): this;
/**
* Add a customized layout algorithm. The layoutName must be not existed. The callback function provide graph object and chart object as input. Change node.x and node.y in graph.nodes array.
*
* @example add layout `sphere`
* <pre>
* // add a customized layout called mySphere
* chart.addLayout('mySphere', function(graph, theChart) {
* let N = graph.nodes.length;
* let radius = 2 * N * 30 / Math.PI;
*
* graph.nodes.forEach((node, i) => {
* let position = Utils.rotate(0, 0, 0, radius, i / N * 360);
* node.x = position[0];
* node.y = position[1];
* });
* })
*
* chart.setLayout('mySphere').runLayout();
* chart.runLayout('mySphere');
* </pre>
* @param {string} layoutName [description]
* @param { (graph: { nodes: GraphChartDataNode[], links: GraphChartDataLink[] }, chart: BaseApi): void }
* callback customized function for layout algorithm.
* @return {this} [description]
*/
addLayout(layoutName: string, callback: {
(graph: {
nodes: GraphChartDataNode[];
links: GraphChartDataLink[];
}, chart: BaseApi): void;
}): this;
/**
* overwrite an existed layout.
*
* @example Overwrite a layout.
*
* <pre>
* // Overwrite the mySphere layout.
* chart.overwriteLayout('mySphere', function(graph, theChart) {
* // Here for new layout algorithm.
* let N = graph.nodes.length;
* let radius = 2 * N * 30 / Math.PI;
*
* graph.nodes.forEach((node, i) => {
* let position = Utils.rotate(0, 0, 0, radius, i / N * 360);
* node.x = position[0];
* node.y = position[1];
* });
* })
*
* chart.runLayout();
* </pre>
*
* @param {string} layoutName
* @param {{
* (graph: {
* nodes: GraphChartDataNode[],
* links: GraphChartDataLink[]
* },
* chart: BaseApi): void
* }} callback
* @returns {this}
*
*/
overwriteLayout(layoutName: string, callback: {
(graph: {
nodes: GraphChartDataNode[];
links: GraphChartDataLink[];
}, chart: BaseApi): void;
}): this;
/**
* run a layout by using a layout name. And set the layout to be selected layout. This function will update and autoFit by default.
* If there is not input, the current selected layout will be used, or the default (`force`) will be used.
* Current default supported layout:
* - `default`
* - `force`
* - `hierarchy`
* - `tree`
* - `circle`
* - `sphere`
* - `random`
* - `static`
*
* @example run a layout for visualization
* <pre>
* chart.runLayout('force');
* chart.runLayout('tree');
* chart.runLayout('sphere');
* chart.runLayout('random');
*
* ...
* </pre>
* @param {string} layoutName
* @return {this} [description] can not be used with update();
*/
runLayout(layoutName?: string, autoFit?: boolean): this;
/**
* add an new external data parser. The parser can not be added, if the name is already added.
* After add parser, the parser can be used in addData API.
*
* @example add a parser function for graph visualization.
* <pre>
* var graph = JSON String;
* chart.addParser('JSON', (externalData) => {
* var graph = JSON.parse(externalData);
*
* return graph;
* })
*
* chart.addData(graph, 'JSON').update();
* </pre>
* @param {string} parserName [description]
* @param {ExternalGraph }} callback [description]
* @return {this} [description]
*/
addParser(parserName: string, callback: {
(externalData: any): ExternalGraph;
}): this;
/**
* Get a parser function by a parser name.
*
* @example Get a parser function by name.
*
* <pre>
* // highlight the new coming nodes;
*
* var graph = JSON String;
* var parser = chart.getParser('JSON');
* var parsedGraph = parser(graph);
*
* chart.addData(parsedGraph, 'static');
*
* chart.getNodes().forEach(n => {
* chart.lowlightNode(n.exType, n.exID);
* });
*
* parsedGraph.nodes.forEach(n => {
* chart.unLowlightNode(n.exType, n.exID);
* })
*
* chart.update();
* </pre>
* @param {string} parserName
* @returns {{ (externalData: any): ExternalGraph }}
*/
getParser(parserName: string): {
(externalData: any): ExternalGraph;
};
/**
* Update an existed parser. Warning message will be submited, if the target parser is not existed.
*
* @example Update static parser
*
* <pre>
* var graph = JSON String;
*
* chart.updateParser('static', (externalData) => {
* var parsedGraph = JSON.parse(externalData);
* return chart.getParser('pta')(parsedGraph);
* })
*
* chart.addData(graph, 'static').update();
* </pre>
* @param {string} parserName [description]
* @param {ExternalGraph }} callback [description]
* @return {this} [description]
*/
updateParser(parserName: string, callback: {
(externalData: any): ExternalGraph;
}): this;
/**
* Update visualization setting. Have not finished yet.
* @param {any} options [description]
* @return {this} [description]
*/
updateSettings(options: {
area?: any;
node?: any;
link?: any;
}): this;
/**
* Set the target node to be The first item in the root node lists. In most of the case, the layout needs a single root node. You can use getRoot() to get current root node.
*
* @example Set the root node.
*
* <pre>
* // Run tree layout by setting the first selected node as root node.
* var node = chart.getSelection().nodes[0];
* chart.setRoot(node.exType, node.exID);
*
* chart.runLayout('tree');
* </pre>
* @param {string} exType target node external type
* @param {string} exID target node external id
* @return {this} [description]
*/
setRoot(exType: string, exID: string): this;
/**
* Get the single root node.
*
* @example Get the first root node.
*
* <pre>
* var root = chart.getRoot();
*
* console.assert(root.isNode)
* </pre>
* @return {GraphChartDataNode} Return the first node in the root node list.
*/
getRoot(): GraphChartDataNode;
/**
* add a target node in the root node list.
*
* @example add a node in root node list.
*
* <pre>
* var node = chart.getSelection().nodes[0];
* chart.addRoot(node.exType, node.exID);
* chart.runLayout('tree');
* </pre>
*
* @param {string} exType node external id
* @param {string} exID node external type
* @return {this} [description]
*/
addRoot(exType: string, exID: string): this;
/**
* get the root node list.
*
* @example Get all nodes in root node list.
*
* <pre>
* var nodes = chart.getRoots();
* </pre>
* @return {GraphChartDataNode[]} [description]
*/
getRoots(): GraphChartDataNode[];
/**
* clean current root node list.
*
* @example Clear all nodes in root node list.
*
* <pre>
* chart.cleanRoots();
* console.assert(chart.layout.roots.length === 0)
* </pre>
* @return {this} [description]
*/
cleanRoots(): this;
/**
* Translate a list of nodes base on current selectedLanguage, and localization settings.
*
* @example Get all translated nodes.
* <pre>
* chart.translateNodes(chart.getNodes());
* </pre>
* @param {[type]} nodes The list of nodes, such as the result of getNodes(), getSelectedNodes, etc..
* @return {GraphChartDataNode[]} [description]
*/
translateNodes(nodes: GraphChartDataNode[]): GraphChartDataNode[];
/**
* Translate a list of links base on current selectedLanguage, and localization settings.
*
* @example Get all translated links.
* <pre>
* chart.translateLinks(chart.getLinks());
* </pre>
* @param {[type]} links The list of links, such as the result of getLinks(), getSelectedLinks(), etc..
* @return {GraphChartDataLink[]} [description]
*/
translateLinks(links: GraphChartDataLink[]): GraphChartDataLink[];
/**
* get the vertex translation base on the input values.
* Translate type, if only type is inputed. Translate attribute, if type and attribute are inputed. Translate value, if all arguments are inputed.
* It will translate the value for specific input based on the vertex type and attribute.
*
* @example Translate information for a node.
* <pre>
* var chart = new GraphChart({
* render: {
* assetsUrlBase: '/dist/assets',
* container: document.getElementById('GraphChart'),
* },
* language: {
* selectedLanguage: 'zh',
* localization: {
* 'zh': {
* vertex: {
* 'Person': {
* type: '用户',
* attrs: {
* 'lastName': '姓',
* 'gender': {
* attr: '性别',
* value: {
* '0': '男',
* '1': '女'
* }
* }
* }
* }
* }
* }
* }
* }
* });
*
* var node = {
* exType: 'Person',
* exID: 'Shawn',
* attrs: {
* lastName: 'Huang',
* gender: '0'
* }
* };
*
* console.assert(chart.translateForNode(node.exType), '用户');
* console.assert(chart.translateForNode(node.exType, 'lastName'), '姓');
* console.assert(chart.translateForNode(node.exType, 'gender'), '性别');
* console.assert(chart.translateForNode(node.exType, 'gender', node.attrs.gender), '男');
* console.assert(chart.translateForNode('Person', 'gender', '1'), '女');
*
* ...
* </pre>
* @param {string} type Vertex type
* @param {string} attribute Vertex attribute
* @param {string} value Vertex value
* @return {string} the translated value
*/
translateForNode(vertexType: string, attribute?: string, value?: string): string;
/**
* get the edge translation base on the input values.
* Translate type, if only type is inputed. Translate attribute, if type and attribute are inputed. Translate value, if all arguments are inputed.
* It will translate the value for specific input based on the edge type and attribute.
*
* @example translate the information of links base on a predefined configuration.
* <pre>
* var chart = new GraphChart({
* render: {
* assetsUrlBase: '/dist/assets',
* container: document.getElementById('GraphChart'),
* },
* language: {
* selectedLanguage: 'zh',
* localization: {
* 'zh': {
* edge: {
* 'Connected': {
* type: '朋友',
* attrs: {
* 'lastName': '姓',
* 'gender': {
* attr: '性别',
* value: {
* '0': '男',
* '1': '女'
* }
* }
* }
* }
* }
* }
* }
* }
* });
* var link = {
* exType: 'Connected',
* source: {
* exType: 'Person',
* exID: 'Shawn'
* },
* target: {
* exType: 'Person',
* exID: 'Joe'
* },
* attrs: {
* lastName: 'Huang',
* gender: '0'
* }
* };
*
* console.assert(chart.translateForLink(link.exType), '朋友');
* console.assert(chart.translateForLink(link.exType, 'lastName'), '姓');
* console.assert(chart.translateForLink(link.exType, 'gender'), '性别');
* console.assert(chart.translateForLink(link.exType, 'gender', link.attrs.gender), '男');
* console.assert(chart.translateForLink('Person', 'gender', '1'), '女');
*
* </pre>
* @param {string} type Edge type
* @param {string} attribute Edge attribute
* @param {string} value Edge value
* @return {string} the translated value
*/
translateForLink(edgeType: string, attribute?: string, value?: string): string;
/**
* hide menu action. Hide current menu of graph visualization either node menu or link menu.
*
* @example hide all menu.
* <pre>
* chart.hideMenu();
* </pre>
* @return {this} [description]
*/
hideMenu(): this;
/**
* Set icon for a type.
*
* @example Set icon for a certain vertex type.
* <pre>
* chart.setIcon('Person', 'user');
* chart.setIcon('Person', 'Address1');
* chart.setIcon('Person', 'icon_001');
* chart.setIcon('Person', 'icon_225');
*
* chart.update();
* </pre>
*
* @param {string} type
* @param {string} icon
*/
setIcon(type: string, icon: string): this;
/**
* Set color for a type.
*
* @example Set color for a certain vertex or edge type.
* <pre>
* chart.setColor('Person', '#fff');
* chart.setColor('Person', '#abc');
* chart.setColor('Person', '#f00');
* chart.setColor('Connected', '#00ff00');
*
* chart.update();
* @param {string} type
* @param {string} color
*/
setColor(type: string, color: string): this;
/**
* Add pre defined style for nodes.
* @example add preNode style
* <pre>
*
* var preNodeStyles = [
* {
* condition: 'type === "p_order" || id === "TID-00000000000000000100" || id.indexOf("User") !== -1',
* style: {
* radius: 100,
* }
* },
* {
* condition: (node, chart) => { return node.exType === "p_order"}',
* style: {
* fillColor: '#000000',
* display: 'rectangle'
* }
* },
* {
* condition: 'type === "stocking"',
* style: {
* radius: 100,
* lineColor: '#222222',
* lineWidth: 15
* }
* },
* {
* condition: 'attrs["cert_type"] !== undefined && attrs["cert_type"].indexOf("07") !== -1',
* style: {
* radius: 100,
* lineColor: '#222222',
* lineWidth: 15
* }
* }
* ];
*
* preNodeStyles.forEach(style => {
* chart.addNodePreStyle(style);
* })
*
* </pre>
*
* @param {({
* condition: string | { (node: GraphChartDataNode, chart: BaseApi): boolean };
* style: {
* [key: string]: any;
* };
* })} preStyle
* @returns {this}
* @memberof GraphChart
*/
addNodePreStyle(preStyle: {
condition: string | {
(node: GraphChartDataNode, chart: BaseApi): boolean;
};
style: {
[key: string]: any;
};
}): this;
/**
* Add pre defined style for links.
*
* @example Same as `addNodePreStyle`.
*
* @param {{
* condition: string | { (link: GraphChartDataLink, chart: BaseApi): boolean };
* style: {
* [key: string]: any;
* };
* }} preStyle
* @returns {this}
*/
addLinkPreStyle(preStyle: {
condition: string | {
(link: GraphChartDataLink, chart: BaseApi): boolean;
};
style: {
[key: string]: any;
};
}): this;
/**
* get nodes by expression conditon.
*
* @example Get nodes by expression.
* <pre>
* chart.getNodesByExpression('node.attrs["fee"] > "9" && type === "Product"');
* chart.getNodesByExpression('true');
* chart.getNodesByExpression('type === "Person"');
* chart.getNodesByExpression('node.attrs["lastName"] === "Huang"');
* chart.getNodesByExpression('type === "p_order" || id === "TID-00000000000000000100" || id.indexOf("User") !== -1');
*
* </pre>
*
* @param {string} condition
* @returns
*/
getNodesByExpression(condition: string): any;
/**
* get links by expression condition.
*
* @example Get links by expression.
* <pre>
* chart.getLinksByExpression('link.attrs["fee"] > "9" && type === "Connected"');
* chart.getLinksByExpression('true');
* chart.getLinksByExpression('type === "Connected"');
* chart.getLinksByExpression('link.attrs["value"] === "certainValue"');
* chart.getLinksByExpression('type === "Connected" || link.source.id === "TID-00000000000000000100" || link.target.id.indexOf("User") !== -1');
*
* </pre>
* @param {string} condition
* @returns
() */
getLinksByExpression(condition: string): any;
/**
* Get rendering related info for a node.
*
* offsetRadius: the pixel numbers of the radius of the node relative to the container. Affected by css transform.
* offsetX: the pixel numbers to the left of the container. Affected by css transform.
* offsetY: the pixel numbers to the top of the container. Affected by css transform.
* offsetBounds: the pixel coordiates of top-left point and bottom-right point of the bounding in the container.
* zoom: the zoom level in graphcarht.
* zindex: zindex in the graph visualization. The hovered node is always shown as MAX zindex.
*
* The client offsetLeft and offsetTop can be got as follow:
* @example Example
*
* <pre>
*
* var node = chart.getSelection().nodes[0];
* var shape = chart.getNodeShape(node);
*
* var element = chart.container, viewportLeft = shape.offsetX, viewportTop = shape.offsetY;
* while (element) {
* viewportLeft += a.offsetLeft;
* viewportTop += a.offsetTop;
* element = element.offsetParent;
* }
*
* return {viewportLeft, viewportTop};
*
* </pre>
* @param {GraphChartDataNode} node
* @returns {{
* offsetRadius: number;
* offsetX: number;
* offsetY: number;
* offsetBounds: {
* x0: number,
* x1: number,
* y0: number,
* y1: number
* };
* zoom: number;
* zindex: number;
* }}
* @memberof GraphChart
*/
getNodeShape(node: GraphChartDataNode): {
offsetRadius: number;
offsetX: number;
offsetY: number;
offsetBounds: {
x0: number;
x1: number;
y0: number;
y1: number;
};
zoom: number;
zindex: number;
};
/**
* Get rendering related info for a link.
*
* offsetRadius: the pixel numbers of the radius of the node relative to the container. Affected by css transform. This may not be accurate if the pixel is smaller than 1.
* offsetPointsX: the x-coordinate of the points for rendering the link relative to the container in pxiels.
* offsetPointsY: the y-coordinate of the points for rendering the link relative to the container in pxiels.
* offsetBounds: the pixel coordiates of top-left point and bottom-right point of the bounding in the container.
* zoom: the zoom level in graphcarht.
*
* @param {GraphChartDataLink} link
* @returns {{
* offsetRadius: number;
* offsetPointsX: number[];
* offsetPointsY: number[];
* offsetBounds: {
* x0: number,
* x1: number,
* y0: number,
* y1: number
* };
* zoom: number;
* }}
* @memberof GraphChart
*/
getLinkShape(link: GraphChartDataLink): {
offsetRadius: number;
offsetPointsX: number[];
offsetPointsY: number[];
offsetBounds: {
x0: number;
x1: number;
y0: number;
y1: number;
};
zoom: number;
};
/**
* set nodes draggable. Needs call update to apply to the chart.
* draggable is ture: Draggable.
* draggable is false: Non-Draggable.
*
* @example Disable dragging for selected nodes.
* <pre>
* var nodes = chart.getSelection().nodes;
* chart
* .setNodesDraggable(nodes, false)
* .update();
*
* </pre>
* @param {GraphChartDataNode[]} nodes
* @param {boolean} [draggable=true]
* @returns {this}
* @memberof GraphChart
*/
setNodesDraggable(nodes: GraphChartDataNode[], draggable?: boolean): this;
/**
* set invisible of nodes.
*
* @example show a group of nodes. hide a group of nodes.
* <pre>
* // hide selected nodes;
* var nodes = chart.getSelection().nodes;
* chart.setNodesInvisible(nodes);
*
* // show all invisible nodes
* var nodes = chart.getNodes().filter(n => {
* return n.styles.isInvisible;
* });
* chart.setNodesInvisible(nodes, false);
*
* </pre>
*
* @param {GraphChartDataNode[]} nodes
* @param {boolean} [invisible=true]
* @returns {this}
* @memberof GraphChart
*/
setNodesInvisible(nodes: GraphChartDataNode[], invisible?: boolean): this;
/**
* set invisible of link.
*
* @example show a group of nodes. hide a group of links.
* <pre>
* // hide selected links;
* var links = chart.getSelection().links;
* chart.setLinksInvisible(links);
*
* // show all invisible links
* var links = chart.getLinks().filter(l => {
* return l.styles.isInvisible;
* });
* chart.setLinksInvisible(links, false);
*
* </pre>
*
* @param {GraphChartDataLink[]} links
* @param {boolean} [invisible=true]
* @returns {this}
* @memberof GraphChart
*/
setLinksInvisible(links: GraphChartDataLink[], invisible?: boolean): this;
/**
* Clear graph and add a graph contains random N nodes and 2*N links for performance test.
* @param {[type]} NumOfNodes = 500 [description]
*/
runStressTest(NumOfNodes?: number): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: graph chart data class.
*
* Created on: Oct 6th, 2016
* Author: Xiaoke Huang
******************************************************************************/
export interface ExternalGraph {
nodes: ExternalNode[];
links: ExternalLink[];
}
/**
* Graph data structure for graph chart.
* @preferred
*/
export class GraphChartData extends ItemsData {
private chart;
/**
* Internal graph data object.
* @type {GraphDataInternalData}
*/
private inData;
constructor(parent?: BaseApi);
/**
* Initial data object and internal index.
* @return {boolean}
*/
private initData();
/**
* Reset interal data object, then load new graph.
* @param {[type]} externalGraph external node array and link array.
* @param {any = {}} options [description]
* @return {this} [description]
*/
resetGraph(externalGraph: ExternalGraph, options?: any): this;
/**
* reload new graph. Keep using the previous location (x, y) of nodes.
* @param {[type]} externalGraph external node array and link array.
* @param {any = {}} options [description]
* @return {this} [description]
*/
reloadGraph(externalGraph: ExternalGraph, options?: any): this;
/**
* Add a new graph in current internal graph object.
* @param {ExternalGraph} externalGraph [description]
* @param {any = {}} options [description]
* @return {this} [description]
*/
addGraph(externalGraph: ExternalGraph, options?: {
node: string;
link: AddLinkOption;
}): this;
/**
* Drop a sub graph.
*
* @param {ExternalGraph} externalGraph
* @returns {this}
*
* @memberof GraphChartData
*/
dropGraph(externalGraph: ExternalGraph): this;
/**
* Add node base on option. Check out the utils module for detailed information for option.
* Example for adding an existing node : two nodes A and B. [option](A, B)
* defaults : Merge A and B, if there are same field, use values from A;
* extend : Merge A and B, if there are same field, use values from B;
* overwrite : Use values from B overwrite the same fields of A;
*
* @param {ExternalNode} node [description]
* @param {[type]} option = 'extend' defaults | extend | overwrite
* @return {GraphChartDataNode} [description]
*/
addNode(node: ExternalNode, option?: string): GraphChartDataNode;
/**
* Example for adding an existing link : two nodes A and B. [option](A, B)
* defaults : Merge A and B, if there are same field, use values from A;
* extend : Merge A and B, if there are same field, use values from B;
* overwrite : Use values from B overwrite the same fields of A;
*
* @param {ExternalLink} link external link object
* @param {AddLinkOption} option link/node: defaults | extend | overwrite
* @return {GraphChartDataLink} [description]
*/
addLink(link: ExternalLink, option?: AddLinkOption): GraphChartDataLink;
getInternalData(): GraphDataInternalData;
getData(): {
nodes: GraphChartDataNode | GraphChartDataNode[];
links: GraphChartDataLink | GraphChartDataLink[];
};
getNodes(exType?: string, exID?: string): GraphChartDataNode | GraphChartDataNode[];
getLinks(exType?: string, sourceExType?: string, sourceExID?: string, targetExType?: string, targetExID?: string): GraphChartDataLink | GraphChartDataLink[];
/**
* Drop node API.
* @param {string} exType [description]
* @param {string} exID [description]
* @param {[type]} option = false [description]
* @return {DroppedItems} [description]
*/
dropNode(exType: string, exID: string, option?: boolean): DroppedItems;
/**
* Drop a link by external source, target, type.
* @param {string} exType [description]
* @param {string} sourceExType [description]
* @param {string} sourceExID [description]
* @param {string} targetExType [description]
* @param {string} targetExID [description]
* @param {boolean} option while dropping links, option is used to determine whether or not we drop isolated nodes.
* - true: we don't remove any nodes from graph while dropping links.
* - false: we do remove source and target nodes of this link, if the node is isloated. And use the same option for dropping other related nodes and links.
* @return {DroppedItems} [description]
*/
dropLink(exType: string, sourceExType: string, sourceExID: string, targetExType: string, targetExID: string, option?: boolean): DroppedItems;
/**
* Drop all nodes and links of the internal graph data object. But it will keep the idSet. It is different with initData().
* @return {DroppedItems} [description]
*/
dropAll(): DroppedItems;
getNeighbors(exType: string, exID: string): {
all: GraphChartDataNode[];
in: GraphChartDataNode[];
out: GraphChartDataNode[];
};
setSelection(selected: (GraphChartDataNode | GraphChartDataLink)[]): this;
getSelectedNodes(): GraphChartDataNode[];
/**
* return selected Links and both source and target selected links.
* @return {GraphChartDataLink[]} [description]
*/
getSelectedLinks(): GraphChartDataLink[];
getNodeLegends(): string[];
getLinkLegends(): string[];
getNodeAttributes(): {
type: string;
icon: any;
color: string;
labels: {
attributeName: string;
isSelected: boolean;
}[];
}[];
getLinkAttributes(): {
type: string;
color: string;
labels: {
attributeName: string;
isSelected: boolean;
}[];
}[];
/**
* evaluate node by expression. The condition supports the javascript syntax.
*
* @param {GraphChartDataNode} inNode
* @param {(string | { (node: GraphChartDataNode, chart: BaseApi): boolean })} condition
* @returns {boolean}
* @memberof GraphChartData
*/
evaluateNodeExpression(inNode: GraphChartDataNode, condition: string | {
(node: GraphChartDataNode, chart: BaseApi): boolean;
}): boolean;
/**
* apply a style config for a node data object.
* @param {GraphChartDataNode} inNode [description]
* @param {any} style the external style config.
* @return {this} [description]
*/
applyNodeStyle(inNode: GraphChartDataNode, style: any): this;
/**
* Evaluate link by external expression. The condition supports javascript syntax.
*
*
* @param {GraphChartDataLink} inLink
* @param {(string | { (link: GraphChartDataLink, chart: BaseApi): boolean })} condition
* @returns {boolean}
* @memberof GraphChartData
*/
evaluateLinkExpression(inLink: GraphChartDataLink, condition: string | {
(link: GraphChartDataLink, chart: BaseApi): boolean;
}): boolean;
/**
* apply a style config for a link data object.
* @param {GraphChartDataLink} inLink [description]
* @param {any} style the external style config
* @return {this} [description]
*/
applyLinkStyle(inLink: GraphChartDataLink, style: any): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: graph chart id mapping class.
*
* Created on: Oct 10th, 2016
* Author: Xiaoke Huang
******************************************************************************/
/**
* ID set class for mapping external ID+Type to internal ID for graph node/link.
*/
export class GraphDataIDSet {
private static nodeIDConcChar;
private static linkIDConcChar;
/**
* This field is used for generating internal id index for external node id.
* @type {number}
*/
private nodesIDCount;
/**
* This field is use for generating internal type index for external node type.
* @type {number}
*/
private nodesTypeCount;
/**
* This field is used for maping link type from external type to internal type index.
* @type {number}
*/
private linksTypeCount;
/**
* Internal and external id mapping object. Id translation is using this object.
*/
private idMap;
constructor();
/**
* register an external node in id map for internal node id.
* @param {string} exType [description]
* @param {string} exID [description]
* @return {string} [description]
*/
registerExternalNode(exType: string, exID: string): string;
/**
* Check if a external node is mapped in idMap.
* @param {string} exType [description]
* @param {string} exID [description]
* @return {string} if exist, return internalID, else return undefined;
*/
checkExternalNode(exType: string, exID: string): string;
registerExternalLink(exType: string, sourceExType: string, sourceExID: string, targetExType: string, targetExID: string): string;
checkExternalLink(exType: string, sourceExType: string, sourceExID: string, targetExType: string, targetExID: string): string;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: graph chart internal graph data class.
*
* Created on: Oct 10th, 2016
* Author: Xiaoke Huang
******************************************************************************/
export interface DroppedItems {
target?: GraphChartDataNode | GraphChartDataLink;
nodes: GraphChartDataNode[];
links: GraphChartDataLink[];
}
/**
* Internal graph data object.
*/
export class GraphDataInternalData {
/**
* Mapper for external id+type to internal id for node and link.
* @type {GraphDataIDSet}
*/
private idSet;
/**
* The main data array for storing node and link objects.
*/
array: {
nodes: GraphChartDataNode[];
links: GraphChartDataLink[];
};
/**
* Internal indices for nodes and links in graph.
*/
index: {
nodes: {
[nodeInternalID: string]: GraphChartDataNode;
};
links: {
[linkInternalID: string]: GraphChartDataLink;
};
};
/**
* These indices refer from node to their neighboring nodes and related links.
*/
neighbors: {
in: {
[toID: string]: {
[fromID: string]: {
[linkID: string]: GraphChartDataLink;
};
};
};
out: {
[fromID: string]: {
[toID: string]: {
[linkID: string]: GraphChartDataLink;
};
};
};
all: {
[nodeID: string]: {
[nodeID: string]: {
[linkID: string]: GraphChartDataLink;
};
};
};
inCount: {
[toID: string]: number;
};
outCount: {
[fromID: string]: number;
};
allCount: {
[nodeID: string]: number;
};
};
constructor();
private init();
/**
* inject a new link in internal graph data.
* - b. If the new link is not exist.
* - b1. Add link to index.
* - b2. Add link to array.
* - b3. Update neighbors.
* @param {ExternalLink} link [description]
* @return {GraphChartDataLink} [description]
*/
private injectNewLink(link);
getIDSet(): GraphDataIDSet;
/**
* @param {string} inID
* @return {boolean}
*/
isNodeExist(inID: string): boolean;
/**
* get nodes by a array of internal id.
* @param {string[]} ids [description]
* @return {GraphChartDataNode[]} [description]
*/
getNodes(ids: string[]): GraphChartDataNode[];
getNodeByInternalID(inID: string): GraphChartDataNode;
getNodeByExternalTypeID(type: string, id: string): GraphChartDataNode;
/**
* Add an external node in internal data object.
* Example for adding an existing node: two nodes A and B. [option](A, B)
* defaults : Merge A and B, if there are same field, use values from A;
* extend : Merge A and B, if there are same field, use values from B;
* overwrite : Use values from B overwrite the same fields of A;
*
* 1. IdSet mapping.
* 2. Handle the case that node is in aggregated node.
* 3. Add node in data.
* - 1. add node in index;
* - 2. add node in array;
* - 3. add node in neighbors;
* @param {ExternalNode} node External Node
* @param {string} option Option for adding node. defaults | extend | overwrite
* @return {GraphChartDataNode} Added the internal GraphChartDataNode object.
*/
addNode(node: ExternalNode, option: string): GraphChartDataNode;
/**
* Drop a node by internal id from the internal data object.
* @param {string} id internal id.
* @param {boolean} option ture: drop isolated nodes, false: do not drop isolated nodes.
* dropping node will drop related links. While we drop links, we use option
* to determine whether or not we drop the isolated nodes.
* @return {DroppedItems} The nodes dropped. The first one is the target dropping node.
*/
dropNode(id: string, option: boolean): DroppedItems;
/**
* @param {string} inID internalID of the target link
* @return {boolean}
*/
isLinkExist(inID: string): boolean;
getLinks(ids: string[]): GraphChartDataLink[];
getLinkByInternalID(inID: string): GraphChartDataLink;
getLinkByExternalTypeID(exType: string, sourceExType: string, sourceExID: string, targetExType: string, targetExID: string): GraphChartDataLink;
/**
* Add an external link in internal data object.
* 1. Check existing of the new link in aggregated node.
* - a. If the link belongs to aggregated node, then update aggregated node contained link list, and create virtual link.
* - a1 : If link.source and link.target are both in aggregated nodes.
* - a2 : If link.source or link.target is in aggregated node.
* - a3 : If neighber of source or target is in aggregated node.
*
* 2. Add non-existed source/target node base on option.node.
* 3. Add link to index. Needs to check reverse link for direceted/undirected links.
* 4. if link is a new link, add it to array.
* - a. Update neighbors for target and source nodes.
*
* @param {ExternalLink} link [description]
* @param {AddLinkOption} option { link: defaults | extend | overwrite, node: defaults | extend | overwrite}
* @return {GraphChartDataLink} [description]
*/
addLink(link: ExternalLink, option: AddLinkOption): GraphChartDataLink;
/**
* Drop a link by internal id.
* @param {string} id internal id.
* @param {boolean} option while dropping links, option is used to determine whether or not we drop isolated nodes.
* true: we don't remove any nodes from graph while dropping links.
* false: we do remove source and target nodes of this link, if the node is isloated. And use the same option for dropping other related nodes and links.
* @return {DroppedItems} [description]
*/
dropLink(id: string, option: boolean): DroppedItems;
getNeighbors(id: string): {
all: GraphChartDataNode[];
in: GraphChartDataNode[];
out: GraphChartDataNode[];
};
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Define link object for graph chart.
*
* Created on: Oct 6th, 2016
* Author: Xiaoke Huang
******************************************************************************/
export interface ExternalLink {
source: {
id: string;
type: string;
};
target: {
id: string;
type: string;
};
type: string;
directed?: boolean;
attrs?: {
[key: string]: string | number | boolean | Object;
};
styles?: {
[key: string]: string | number | Object;
};
others?: any;
labels?: any;
}
/**
* AddLinkOption interface.
* It is used to determine how handle the nodes and link for a added link.
* `defaults` | `extend` | `overwrite`
* If a node or link exists:
* `defaults`: keep using old values for any existed field, use new values for non existed field
* `extend`: Merge new values with old values, prefer using new values for duplicated fields.
* `overwrite`: descard all old values. Use new values instead.
*/
export interface AddLinkOption {
link?: string;
node?: string;
}
/**
* Graph chart link object.
* @preferred
*/
export class GraphChartDataLink extends ItemsDataLink {
/**
* source node object;
* @type {GraphChartDataNode}
*/
source: GraphChartDataNode;
/**
* target node object;
* @type {GraphChartDataNode}
*/
target: GraphChartDataNode;
/**
* external link type
* @type {string}
*/
exType: string;
/**
* Indicate directed or undirected type link;
* @type {boolean}
*/
directed: boolean;
/**
* Style object for graph link object.
*/
styles: GraphStyle.GraphChartLinkStyles;
/**
* label object to determine which label needs to be shown in visualization.
*/
labels: {
[attrName: string]: boolean;
};
private pointsX;
readonly x: number[];
private pointsY;
readonly y: number[];
/**
* This field is used for storing middle reuslt from several algorithms which need to be shown in visualization or affect layout.
* @type {any}
*/
others: any;
isLink: boolean;
/**
* An internal link object.
* @param {string} internalID internalID by registerExternalLink;
* @param {ExternalLink} exLink external link data object
* @param {GraphChartDataNode} source internal source node object
* @param {GraphChartDataNode} target internal target node object
*/
constructor(internalID: string, exLink: ExternalLink, source: GraphChartDataNode, target: GraphChartDataNode);
/**
* Merge external node. Prefer external node values.
* @param {ExternalNode} exNode [description]
* @return {this} [description]
*/
extendLink(exLink: ExternalLink): this;
/**
* Merge external Link. Prefer old Link values.
* @param {ExternalLink} exLink [description]
* @return {this} [description]
*/
defaultsLink(exLink: ExternalLink): this;
/**
* Assign external Link values to old Links.
* @param {ExternalLink} exLink [description]
* @return {this} [description]
*/
overwriteLink(exLink: ExternalLink): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Define node data object class for graph chart.
*
* Created on: Oct 6th, 2016
* Author: Xiaoke Huang
******************************************************************************/
export interface ExternalNode {
id: string;
type: string;
attrs?: {
[key: string]: string | number | boolean | Object;
};
styles?: {
[key: string]: string | number | Object;
};
others?: any;
labels?: any;
x?: number;
y?: number;
}
/**
* Graph chrt node object.
* @preferred
*/
export class GraphChartDataNode extends ItemsDataNode {
/**
* node external id. It is mapped to internal id index. id index + type index = interal id
* @type {string}
*/
exID: string;
/**
* node external type. It is mapped to internal type index.
* @type {string}
*/
exType: string;
/**
* Style object for graph node object.
*/
attrs: {
[attrName: string]: number | string | boolean | Object;
};
/**
* Style object for graph node object.
*/
styles: GraphStyle.GraphChartNodeStyles;
/**
* label object to determine which label needs to be shown in visualization.
*/
labels: {
[attrName: string]: boolean;
};
/**
* External x value.
* @type {number}
*/
exX: number;
/**
* Exteranl y value.
* @type {number}
*/
exY: number;
/**
* Layout x position
* @type {number}
*/
x: number;
/**
* Layout y position
* @type {number}
*/
y: number;
/**
* This field is used for storing middle reuslt from several algorithms which need to be shown in visualization or affect layout.
* @type {any}
*/
others: any;
isNode: boolean;
constructor(internalID: string, exNode: ExternalNode);
/**
* Merge external node. Prefer external node values.
* @param {ExternalNode} exNode [description]
* @return {this} [description]
*/
extendNode(exNode: ExternalNode): this;
/**
* Merge external node. Prefer old node values.
* @param {ExternalNode} exNode [description]
* @return {this} [description]
*/
defaultsNode(exNode: ExternalNode): this;
/**
* Assign external node values to old nodes.
* @param {ExternalNode} exNode [description]
* @return {this} [description]
*/
overwriteNode(exNode: ExternalNode): this;
}
export class GraphChartEvent {
private chart;
private defaultHandlers;
handlers: {
onKeyPress: {
(nodes: GraphChartDataNode[], links: GraphChartDataLink[], event: BaseKeyboardEvent, chart: BaseApi): void;
};
onChartUpdate: {
(chart: BaseApi): void;
};
onDataUpdated: {
(chart: BaseApi): void;
};
onSelectionChange: {
(nodes: GraphChartDataNode[], links: GraphChartDataLink[], chart: BaseApi): void;
};
onClick: {
(item: GraphChartDataNode | GraphChartDataLink, event: BaseMouseEvent, chart: BaseApi): void;
};
onDoubleClick: {
(item: GraphChartDataNode | GraphChartDataLink, event: BaseMouseEvent, chart: BaseApi): void;
};
onHoverChange: {
(item: GraphChartDataNode | GraphChartDataLink, event: BaseMouseEvent, chart: BaseApi): void;
};
onPositionChange: {
(event: BaseMouseEvent, chart: BaseApi): void;
};
onRightClick: {
(item: GraphChartDataNode | GraphChartDataLink, event: BaseMouseEvent, chart: BaseApi): void;
};
onPointerDown: {
(item: GraphChartDataNode | GraphChartDataLink, event: BaseMouseEvent, chart: BaseApi): void;
};
onPointerUp: {
(item: GraphChartDataNode | GraphChartDataLink, event: BaseMouseEvent, chart: BaseApi): void;
};
onPointerDrag: {
(item: GraphChartDataNode | GraphChartDataLink, event: BaseMouseEvent, chart: BaseApi): void;
};
onExceedLimit: {
(nodes: GraphChartDataNode[], links: GraphChartDataLink[], chart: BaseApi): void;
};
[event: string]: any;
};
constructor(parent?: BaseApi);
private setDefaultHandlers();
/**
* Set an event handler base on name.
* @param {string} eventName [description]
* @param {void}} callback [description]
* @return {this} [description]
*/
setEventHandler(eventName: string, callback: {
(...args: any[]): void;
}): this;
/**
* Set an event to use the default handler.
* @param {string} eventName [description]
* @return {this} [description]
*/
defaultEventHandler(eventName: string): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: GVIS library layout module class.
*
* Created on: Oct 25th, 2016
* Author: Xiaoke Huang
******************************************************************************/
export class GraphChartLayout {
private chart;
private currentNodeRadius;
private treeLayoutHorizontalScale;
private treeLayoutVerticalScale;
currentLayout: string;
private isLockedUpdateAsyncPositionOfNodesLock;
private defaultLayouts;
private layouts;
/**
* Root node array.
* The first node in array will be used as root node in single root layout.
* @type {GraphChartDataNode[]}
*/
private roots;
constructor(parent: BaseApi);
/**
* Scale tree layout.
*
* @param {number} horizontalScale
* @param {number} verticalScale
* @memberof GraphChartLayout
*/
scaleTreeLayout(horizontalScale: number, verticalScale: number): void;
private setDefaultLayout();
private createBFSTreeArray(options);
private iterateTree(parents, result, nodes, graph);
/**
* Update the inNode x and x position from core node.
*/
updateSyncPositionOfNodes(): this;
updateSyncPositionOfNodeByInternalID(id: string): this;
updateSyncPositionOfLinkByInternalID(id: string): this;
/**
* Since layouts are async process. Need to call the function to update the position for layout.
* @param {number} delay million second for get updated position of each nodes.
* @return {this} [description]
*/
updateAsyncPositionOfNodes(delay?: number): this;
clear(): this;
/**
* It will be mainly used for reset the dynamic layout, since in some case, it takes too long to be converged.
*
* @returns {this}
*
* @memberOf GraphChartLayout
*/
resetLayout(): this;
runLayout(layoutName?: string): this;
setLayout(layoutName: string): this;
addLayout(layoutName: string, callback: {
(graph: {
nodes: GraphChartDataNode[];
links: GraphChartDataLink[];
}, chart: BaseApi): void;
}): this;
overwriteLayout(layoutName: string, callback: {
(graph: {
nodes: GraphChartDataNode[];
links: GraphChartDataLink[];
}, chart: BaseApi): void;
}): this;
setRoot(exType: string, exID: string): this;
/**
* get single root node.
* @return {GraphChartDataNode} [description]
*/
getRoot(): GraphChartDataNode;
/**
* Get all root nodes.
* @return {GraphChartDataNode[]} [description]
*/
getRoots(): GraphChartDataNode[];
/**
* add a root node in root node array.
* @param {string} exType [description]
* @param {string} exID [description]
* @return {this} [description]
*/
addRoot(exType: string, exID: string): this;
/**
* Return current layout name.
*/
getLayouts(): string[];
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: GVIS canvas rendering engine module class.
*
* Created on: Oct 14th, 2016
* Author: Xiaoke Huang
******************************************************************************/
export class GraphChartRenderCanvas extends GraphChartRenderEngineBase {
private chart;
core: any;
color: Color;
icons: ICON;
private zoom;
private otherOptions;
private canvasOptions;
constructor(options: any, chart: BaseApi);
private initOptions(options);
/**
* Initalize event handler for rendering engine.
*/
private initEventHandler();
private initOtherOptions(options);
getCore(): any;
replaceData(internalData: any): this;
addFocusNode(id: string): this;
clearFocus(): this;
collapseNode(id: string): this;
expandNode(id: string): this;
private initNodeLabelSetting(node);
private initNodeRenderSetting(node);
private initNodeItemsSetting(node);
private initLinkLabelSetting(link);
private initLinkRenderSetting(link);
private initLinkItemsSetting(link);
private nodeToolTipSetting(inNode, node, chart);
private linkToolTipSetting(inLink, link, chart);
private nodeMenuContentsFunction(data, coreNode?, targetOption?, defaultContentsFunction?);
private linkMenuContentsFunction(data, coreLink?, targetOption?, defaultContentsFunction?);
updateAreaSettings(settings: any): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: GVIS library render module class.
*
* Created on: Oct 14th, 2016
* Author: Xiaoke Huang
******************************************************************************/
export class GraphChartRender {
private chart;
engine: GraphChartRenderEngineBase;
private zoomLevel;
private exportType;
private maxNodeLimit;
private maxLinkLimit;
private defaultMaxNodeLimit;
private defaultMaxLinkLimit;
private preStyle;
/** built in icons mapping. This will be extend by outside options. */
private icons;
private defaultOptions;
style: BaseStyle;
constructor(parent?: BaseApi);
/**
* Does immediate repaint.
*
* @returns {this}
* @memberof GraphChartRender
*/
paint(): this;
/**
* render graph.
* @return {this} [description]
*/
update(): this;
updateCoordinate(): this;
/**
* reset layout and redarw everything in the viewport.
* @return {this} [description]
*/
redraw(): this;
closeNode(exType: string, exID: string): void;
collapseNode(exType: string, exID: string): void;
expandNode(exType: string, exID: string): void;
hideNode(exType: string, exID: string): void;
showNode(exType: string, exID: string): void;
setNodesInvisible(nodes: GraphChartDataNode[], invisible?: boolean): this;
setLinksInvisible(links: GraphChartDataLink[], invisible?: boolean): this;
zoom(level: number): number;
zoomIn(): this;
zoomOut(): this;
fullscreen(isFullscreen: boolean): this;
autoFit(): this;
/**
* center current visualization base on selected node. We scroll in to the view of all the selected nodes, and their 1-step neighborhood. This logic can be changed.
* @return {this} [description]
*/
centerView(): this;
export(name: string, type: string): this;
private downloadFile(filename, text);
/**
* Unselect all elements in visualization.
* @return {this} [description]
*/
unselectAllElements(): this;
showNodeLabels(exType: string, exID: string, labels: string[]): this;
showNodeLabelsByType(exType: string, labels: string[]): this;
hideNodeLabels(exType: string, exID: string, labels: string[]): this;
hideNodeLabelsByType(exType: string, labels: string[]): this;
hideAllNodeLabels(): this;
showLinkLabels(exType: string, sourceExType: string, sourceExID: string, targetExType: string, targetExID: string, labels: string[]): this;
showLinkLabelsByType(exType: string, labels: string[]): this;
hideLinkLabels(exType: string, sourceExType: string, sourceExID: string, targetExType: string, targetExID: string, labels: string[]): this;
hideLinkLabelsByType(exType: string, labels: string[]): this;
hideAllLinkLabels(): this;
updateAreaSettings(options: any): this;
hideMenu(): this;
updateSize(): this;
setIcon(type: string, icon: string): void;
addPreStyle(style: {
target: string;
obj: {
condition: string | {
(node: GraphChartDataNode, chart: BaseApi): boolean;
} | {
(link: GraphChartDataLink, chart: BaseApi): boolean;
};
style: {
[key: string]: any;
};
};
}): void;
/**
* Fixates a node in place.
*
* @param {string} id
* @param {number} x
* @param {number} y
* @returns {this}
* @memberof GraphChartRender
*/
lockNode(id: string, x: number, y: number): this;
/**
* Unfixates a node and allows it to be repositioned by the layout algorithms.
*
* @param {string} id
* @returns {this}
* @memberof GraphChartRender
*/
unlockNode(id: string): this;
/**
* Return the shape related information of a target node.
*
* @param {string} id
* @returns {{
* offsetRadius: number;
* offsetX: number;
* offsetY: number;
* offsetBounds: {
* x0: number,
* x1: number,
* y0: number,
* y1: number
* };
* zoom: number;
* zindex: number;
* }}
* @memberof GraphChartRender
*/
getNodeShape(id: string): {
offsetRadius: number;
offsetX: number;
offsetY: number;
offsetBounds: {
x0: number;
x1: number;
y0: number;
y1: number;
};
zoom: number;
zindex: number;
};
/**
* Return the shape related information of a target link.
*
* @param {string} id
* @returns {{
* offsetRadius: number;
* offsetPointsX: number;
* offsetPointsY: number;
* offsetBounds: {
* x0: number,
* x1: number,
* y0: number,
* y1: number
* };
* zoom: number;
* }}
* @memberof GraphChartRender
*/
getLinkShape(id: string): {
offsetRadius: number;
offsetPointsX: number[];
offsetPointsY: number[];
offsetBounds: {
x0: number;
x1: number;
y0: number;
y1: number;
};
zoom: number;
};
scrollIntoView(ids: string[]): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: GVIS library render engine base class.
*
* Created on: Oct 12th, 2016
* Author: Xiaoke Huang
******************************************************************************/
export abstract class GraphChartRenderEngineBase {
renderType: string;
core: any;
color: any;
constructor(type: string);
replaceData(data: any): this;
getCore(): any;
updateAreaSettings(settings: any): this;
}
/******************************************************************************
* Copyright (c) 2018, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: GVIS geo render module class.
*
* Created on: Mar 28th, 2018
* Author: Renchu Song
******************************************************************************/
export interface GeoInternalElement {
attrs: {
[attrName: string]: any;
};
icon?: string;
id: string;
exType: string;
imageSlicing: [number, number, number, number];
opacity: number;
scaleWithZoom: boolean;
showAtZoom: number;
hideAtZoom: number;
}
export interface GeoInternalNode extends GeoInternalElement {
exId: string;
display: string;
fillColor: string;
bounds: {
x1: number;
x0: number;
y1: number;
y0: number;
};
aspectRatio: number;
radius: number;
links: GeoInternalLink[];
x: number;
y: number;
}
export interface GeoInternalLink extends GeoInternalElement {
lineColor: string;
lineWidth: number;
from: GeoInternalNode;
to: GeoInternalNode;
directed: boolean;
iconRadius: number;
arrowSize: number;
}
export interface HeatPoint {
x: number;
y: number;
weight?: number;
}
export class GeoCore {
geoMap: any;
heatmapLayer: any;
contourLineLayer: any;
graphLayer: any;
icons: ICON;
private heatmapData;
private heatPointDefaultRadius;
private heatPointDefaultWeight;
private contourXRange;
private contourYRange;
private contourValues;
private thresholds;
private fillRange;
private colors;
private range;
private internalNodesMap;
private internalLinksMap;
private internalNodesArray;
private internalLinksArray;
private distanceBetweenEdgeArrows;
private showNodeTooltip;
private showLinkTooltip;
private showNodeLabel;
private showLinkLabel;
private nodeCallbackFunctions;
private linkCallbackFunctions;
private nodeToolTipCallback;
private linkToolTipCallback;
private nodeLabelCallback;
private linkLabelCallback;
private dragCallback;
zoom(zoomLevel?: number): void;
resetLayout(): void;
updateSettings(options?: any): void;
/**
* Paint the heatmap, contour line layer and graph correspondingly.
*
* @memberof GeoCore
*/
paintNow(): void;
/**
* Update the dafault configs of heatmap layer.
*
* @param {number} defaultRadius
* @param {number} defaultWeight
* @memberof GeoCore
*/
updateHeatmapConfigs(defaultRadius: number, defaultWeight: number): void;
/**
* Update the heatmap data.
*
* @param {HeatPoint[]} [heatMap]
* @memberof GeoCore
*/
updateHeatmapData(heatMap?: HeatPoint[]): void;
/**
* Paint the heatmap layer.
*
* @memberof GeoCore
*/
paintHeatMap(): void;
/**
* Update the depicting configs of contour line layer.
*
* @param {boolean} fillRange
* @memberof GeoCore
*/
updateContourLineConfigs(fillRange: boolean): void;
/**
* Update the contour lines data.
*
* @param {number[][]} [contourData]
* @param {number[]} [thresholds]
* @param {ContourColor[]} [colors]
* @param {{ x0: number, y0: number, x1: number, y1: number }} [range]
* @returns
* @memberof GeoCore
*/
updateContourLineData(contourData?: number[][], thresholds?: number[], colors?: string[], range?: {
x0: number;
y0: number;
x1: number;
y1: number;
}): void;
/**
* Paint the contour line layer.
*
* @memberof GeoCore
*/
paintContourLines(): void;
/**
* Update graph rendering configs.
*
* @param {{
* distanceBetweenEdgeArrows?: number,
* showNodeTooltip?: boolean,
* showLinkTooltip?: boolean,
* nodeToolTipCallback?: (node: GeoInternalNode) => string,
* linkToolTipCallback?: (link: GeoInternalLink) => string,
* showNodeLabel?: boolean,
* showLinkLabel?: boolean,
* nodeLabelCallback?: (node: GeoInternalNode) => string,
* linkLabelCallback?: (link: GeoInternalLink) => string
* }} config
* @memberof GeoCore
*/
updateGraphConfigs(config: {
distanceBetweenEdgeArrows?: number;
showNodeTooltip?: boolean;
showLinkTooltip?: boolean;
nodeToolTipCallback?: (node: GeoInternalNode) => string;
linkToolTipCallback?: (link: GeoInternalLink) => string;
showNodeLabel?: boolean;
showLinkLabel?: boolean;
nodeLabelCallback?: (node: GeoInternalNode) => string;
linkLabelCallback?: (link: GeoInternalLink) => string;
dragCallback?: (lat: number, long: number) => void;
}): void;
addNodeListener(eventType: string, callback: (node: GeoInternalNode) => any): void;
addLinkListener(eventType: string, callback: (link: GeoInternalLink) => any): void;
nodes(): GeoInternalNode[];
getNode(id: string): GeoInternalNode;
links(): GeoInternalLink[];
getLink(id: string): GeoInternalLink;
replaceData(internalData: {
nodes: GraphChartDataNode[];
links: GraphChartDataLink[];
}): void;
circle: {
latitude: number;
longitude: number;
radius: number;
iconString: string;
iconSize: number;
};
/**
* Paint the graph layer.
*
* @memberof GeoCore
*/
paintGraph(circle?: {
latitude: number;
longitude: number;
radius: number;
iconString: string;
iconSize: number;
}): void;
/**
* Rotate vector for radian.
*
* @private
* @param {[number, number]} vec
* @param {number} rad
* @returns {[number, number]}
* @memberof GeoCore
*/
private rotate(vec, rad);
}
export class GraphChartRenderGeo extends GraphChartRenderEngineBase {
private chart;
core: GeoCore;
color: Color;
icons: ICON;
private zoom;
private canvasOptions;
constructor(options: any, chart: BaseApi);
private initOptions(options);
/**
* Initalize event handler for rendering engine.
*/
private initEventHandler();
getCore(): any;
collapseNode(id: string): this;
expandNode(id: string): this;
private initNodeLabelSetting(node);
private initNodeRenderSetting(node);
private initNodeItemsSetting(node);
private initLinkLabelSetting(link);
private initLinkItemsSetting(link);
private nodeToolTipSetting(inNode, node, chart);
private linkToolTipSetting(inLink, link, chart);
private nodeMenuContentsFunction(data, coreNode?, targetOption?, defaultContentsFunction?);
private linkMenuContentsFunction(data, coreLink?, targetOption?, defaultContentsFunction?);
updateAreaSettings(settings: any): this;
replaceData(internalData: any): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: GVIS svg render module class.
*
* Created on: Oct 12th, 2016
* Author: Xiaoke Huang
******************************************************************************/
export class GraphChartRenderSVG extends GraphChartRenderEngineBase {
constructor(options: any);
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: GVIS webgl render module class.
*
* Created on: Oct 12th, 2016
* Author: Xiaoke Huang
******************************************************************************/
export class GraphChartRenderWebgl extends GraphChartRenderEngineBase {
constructor(options: any);
}
/**
* GVIS library Graph Chart Style Module.
*/
export module GraphStyle {
/**
* Node style interface.
*/
interface GraphChartNodeStyleInterface {
/** The ID of one or more auras to which the node belongs. Nodes with the same aura ID will be visually grouped together. */
aura?: string;
/** Cursor to show when node is hovered. */
cursor?: string;
/** Valid values: circle (default), text, roundtext, droplet, rectangle, customShape */
display?: string;
fillColor?: string;
icon?: string;
lineColor?: string;
lineDash?: Array<number>;
lineWidth?: number;
/** Node opacity. */
opacity?: number;
/** @type {number} Node radius */
radius?: number;
shadowBlur?: number;
shadowColor?: string;
shadowOffsetX?: number;
shadowOffsetY?: number;
draggable?: boolean;
[more: string]: any;
}
/**
* Link style interface
*/
interface GraphChartLinkStyleInterface {
cursor?: string;
/** null or 'U', 'D', 'L', 'R' */
direction?: string;
fillColor?: string;
length?: number;
lineDash?: Array<number>;
/** Specifies the width of the line rendered for this link. */
radius?: number;
shadowBlur?: number;
shadowColor?: string;
shadowOffsetX?: number;
shadowOffsetY?: number;
/** @type {number} specifies the force directed layout. */
strength?: number;
[more: string]: any;
}
/**
* Defailt event flag for items(both link and node) in graph chart.
*/
interface GraphChartItemStyleFlagInterface {
isInvisible?: boolean;
isExpanded?: boolean;
isHovered?: boolean;
isLowlighted?: boolean;
isLocked?: boolean;
isSelected?: boolean;
[more: string]: any;
}
/**
* visualization area setting.
* @type {[type]}
*/
let defualtAreaStyle: any;
/**
* default node base style in graph chart
* @type {GraphChartNodeStyleInterface}
*/
let defaultNodeBaseStyle: GraphChartNodeStyleInterface;
/**
* Detail link base style in graph chart
* @type {GraphChartLinkStyleInterface}
*/
let defaultLinkBaseStyle: GraphChartLinkStyleInterface;
/**
* The node style object in graph chart.
*/
class GraphChartNodeStyles implements GraphChartItemStyleFlagInterface {
base: GraphChartNodeStyleInterface;
isHovered: boolean;
hovered: GraphChartNodeStyleInterface;
isSelected: boolean;
selected: GraphChartNodeStyleInterface;
isLowlighted: boolean;
lowlighted: GraphChartNodeStyleInterface;
isLocked: boolean;
locked: GraphChartNodeStyleInterface;
isExpanded: boolean;
expanded: GraphChartNodeStyleInterface;
isInvisible: boolean;
invisible: GraphChartNodeStyleInterface;
constructor(newStyles: any);
}
/**
* The link style object for graph chart.
*/
class GraphChartLinkStyles implements GraphChartItemStyleFlagInterface {
base: GraphChartLinkStyleInterface;
isHovered: boolean;
hovered: GraphChartNodeStyleInterface;
isSelected: boolean;
selected: GraphChartNodeStyleInterface;
isLowlighted: boolean;
lowlighted: GraphChartNodeStyleInterface;
isInvisible: boolean;
invisible: GraphChartNodeStyleInterface;
constructor(newStyles: any);
}
let defaultNodeStyle: GraphChartNodeStyles;
let defaultLinkStyle: GraphChartLinkStyles;
let virtualRootNode: {
id: string;
exID: string;
exType: string;
};
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: All chart item data object class.
*
* Created on: Oct 6th, 2016
* Author: Xiaoke Huang
******************************************************************************/
/**
* Data object which can be binded with a visual item.
* @preferred
*/
export class ItemsData extends BaseData {
constructor();
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Define base class of all links object.
*
* Created on: Oct 6th, 2016
* Author: Xiaoke Huang
******************************************************************************/
/**
* Base link object.
* @preferred
*/
export class ItemsDataLink extends ItemsData {
/**
* The unique indentifier of the link
* @type {string}
*/
id: string;
/**
* id of the source node which is the node where the link originates.
* @type {string}
*/
from: string;
/**
* id of the target node.
* @type {string}
*/
to: string;
/**
* Attribute object of the link.
* @type {Object}
*/
attrs: {
[key: string]: number | string | boolean | Object;
};
/**
* visualization style of the link object.
* @type {Object}
*/
styles: Object;
/**
* This filed can be used to provide multiple classes for styling.
* Such as className = "classA classB classN";
* @type {string}
*/
className: string;
constructor(internalID: string, sourceID: string, targetID: string);
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Define base class of all nodes object.
*
* Created on: Oct 6th, 2016
* Author: Xiaoke Huang
******************************************************************************/
/**
* Base node object.
* @preferred
*/
export class ItemsDataNode extends ItemsData {
/**
* node id which is the unique identifier of the node;
* @type {string}
*/
id: string;
/**
* This filed can be used to provide multiple classes for styling.
* Such as className = "classA classB classN";
* @type {string}
*/
className: string;
/**
* attribute object for a node data object.
* @type {Object}
*/
attrs: Object;
/**
* visualization style of the node object.
* @type {Object}
*/
styles: Object;
constructor(internalID: string);
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Line Chart Class
*
* Created on: Feb 2nd, 2017
* Author: Xiaoke Huang
******************************************************************************/
/**
* LineChart Setting typings.
*/
export interface LineChartSetting extends ChartSetting {
renderType?: string;
data?: {
/**
* It will be used to control the x axis range. If the "range" is set, the min and max will be disabled. The max will be set implicitly as 'dataMax', the min will be set to the 'dataMax' - range;
* If min or max is set, it will use the new value as min or max. The default min and max value is 'dataMin' and 'dataMax' which indicates the minimum value and maximum value this axis.
* This is designed for data zoom bar. If the default is set, it will be used for adding non exist point as the value of y.
* The two non-existed points will be added, as "range min" and the smallest x value.
*
*/
xAxis?: {
range?: number;
min?: number;
max?: number;
default?: number;
};
yAxis?: {
min?: number;
max?: number;
};
/** @type {number} If sample points are more than maxNumber, the oldest data points will be discard. */
maxNumber?: number;
};
formatter?: {
/**
* xAxis label formatter
* @param {number} value of the tick.
* @param {number} index of the tick.
* @return {string} label of the tick.
*/
xAxis?: (value: number, index: number) => string;
/**
* yAxis label formatter
* @param {number} value of the tick.
* @param {number} index of the tick.
* @return {string} label of the tick.
*/
yAxis?: (value: number, index: number) => string;
tooltip?: (params: {
componentType: 'series';
seriesType: string;
seriesIndex: number;
seriesName: string;
name: string;
dataIndex: number;
data: Object;
value: any;
color: string;
percent: number;
}, ticket?: string, callback?: {
(ticket: string, html: string): void;
}) => string;
};
}
/**
* Line Chart Class
* @preferred
*/
export class LineChart extends BaseApi {
render: LineChartRender;
data: LineChartData;
event: LineChartEvent;
/**
* Render type : 'time' for time series data. 'value' for normal data.
* @type {LineChartSetting}
*/
options: LineChartSetting;
/**
* Create an instance of LineChart.
*
* @example Create an instance of LineChart.
* <pre>
*
* window.linechart = new gvis.LineChart({
* renderType: 'time',
* render: {
* container: document.getElementById("LineChart1"),
* legend: {
* show: true
* },
* textStyle: {
* fontStyle: 'italic',
* fontWeight: 'bolder',
* fontFamily: '"Courier New", Courier, monospace',
* fontSize: 12,
* },
* dataZoom: {
* show: true,
* top: 0,
* bottom: 0,
* handleSize: '20%'
* },
* title: {
* text: 'Memory Usage',
* subtext: 'Test subtext'
* }
* },
* data: {
* xAxis: {
* range: 1000 * 60 * 20
* },
* yAxis: {
* min: 0
* }
* },
* formatter: {
* tooltip: function(data) {
* return 'Customized tooltip base on data';
* }
* }
* });
*
* linechart
* .addData(testData)
* .update();
* </pre>
* @param {LineChartSetting} options
* @memberof LineChart
*/
constructor(options: LineChartSetting);
/**
* Add data points in linechart.
*
* @example Add a test dataset in linechart
*
* <pre>
*
* window.testData = [];
* var testNow = new Date();
* var testN = 100;
*
* for (var i=0; i<testN; i++) {
* testNow = +new Date(testNow - 1000);
*
* testData.push({
* series: 'name',
* x: testNow,
* y: testN - 2 * i * +Math.random().toFixed(1)
* });
*
* testData.push({
* series: 'name'+i%2,
* x: testNow,
* y: testN - 2 * i * +Math.random().toFixed(1)
* });
* }
*
* linechart
* .addData(testData)
* .update();
*
* // Dynamiclly add new data points.
* window.lineInt = setInterval(() => {
* var testData = [];
* testN += 5 * Math.random();
*
* testN = +testN.toFixed(1);
*
* testData.push({
* series: 'name',
* x: + new Date(),
* y: testN
* });
*
* testData.push({
* series: 'name0',
* x: + new Date(),
* y: +(testN * (1 + 0.2 * Math.random())).toFixed(1)
* });
*
* testData.push({
* series: 'name1',
* x: + new Date(),
* y: +(testN * (1 + 0.2 * Math.random())).toFixed(1)
* });
*
* linechart
* .addData(testData)
* .update();
*
* if (testN > 250) {
* clearInterval(window.lineInt);
* }
* }, 1000);
* </pre>
*
* @param {SeriesDataPoint[]} data
* @returns {this}
* @memberof LineChart
*/
addData(data: SeriesDataPoint[]): this;
update(): this;
reloadData(data: SeriesDataPoint[]): this;
/**
* Customize an event callback function.
* Currently supported events:
* - `dataZoom`
* - `legendselectchanged`
* The detial of callback function interfaces can be found in linechart.event module.
*
* @example binding legendselectchanged event.
* <pre>
* linechart.on('legendselectchanged', function(event, chart) {
* console.log(chart === linechart);
* console.log(event);
* });
* </pre>
* @param {string} eventName [description]
* @param {void }} callback [description]
* @return {this} [description]
*/
on(eventName: string, callback: {
(event: any, chart?: LineChart): void;
}): this;
/**
* Update the linechart settings.
*
* @example Update settings for linechart.
*
* <pre>
* var newOptions = {
* [anyKey: string]: any;
* };
*
* linechart.updateSettings(newOptions);
* linechart.update();
*
* </pre>
*
* @param {*} [options]
* @returns {this}
* @memberof LineChart
*/
updateSettings(options?: any): this;
/**
* Zoom in the line chart by X Axis by start index and end index. The index 0-100 indicates 0% - 100%
*
* @example zoom X axis.
* <pre>
* linechart.zoomX(0, 100);
* linechart.zoomX(90, 100);
* linechart.zoomX(50, 55);
* linechart.zoomX(10, 12);
* linechart.zoomX(11, 34);
* </pre>
* @param {number} start [description]
* @param {number} end [description]
* @return {this} [description]
*/
zoomX(start: number, end: number): this;
/**
* Contrl the legend of line chart. If "select" is undefined, Toggle the target legend. If "select" is true, select target legend. If "select" is false, unselect target legend.
*
* @example Togglelegned for linechart2 base on linechart event.
* <pre>
* linechart.on('legendselectchanged', function (event, chart) {
* console.log(chart === linechart);
* console.log(event);
*
* for (var name in event.selected) {
* linechart2.toggleLegend(name, event.selected[name]);
* }
* });
* </pre>
* @param {string} series name [description]
* @param {boolean} select [description]
* @return {this} [description]
*/
toggleLegend(name: string, select?: boolean): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Line chart data module class.
*
* Created on: Feb 2nd, 2017
* Author: Xiaoke Huang
******************************************************************************/
export interface SeriesDataPoint {
series: string;
x: number;
y: number;
info?: {
[key: string]: any;
};
}
export class LineChartData {
private chart;
private inData;
private maxNumber;
constructor(parent: BaseApi);
/**
* add data.
* @param {SeriesDataPoint} data [description]
* @return {this} [description]
*/
addData(data: SeriesDataPoint): this;
/**
* get data points array by series name.
* @param {string} series [description]
* @return {SeriesDataPoint[]} [description]
*/
getData(series: string): SeriesDataPoint[];
/**
* get the series name in string array.
* @return {string[]} [description]
*/
getSeries(): string[];
/**
* Clean the data by series name.
* @param {string} series [description]
* @return {SeriesDataPoint[]} [description]
*/
cleanSeriesData(series: string): SeriesDataPoint[];
/**
* cb It will return the value that use to compare items. 0 is equal. -1 is a > b. 1 is a < b.
* @param {SeriesDataPoint} a [description]
* @param {SeriesDataPoint} b [description]
* @return {number} [description]
*/
private compare(a, b);
/**
* It returns the max value of x in all series. It will be used for the feature of the x axis range.
* @return {number} [description]
*/
getXMax(): number;
/**
* It returns the min value of x in all series. It will be used for generate xAxis range.
* @return {number} [description]
*/
getXMin(): number;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Line chart event module class.
*
* Created on: Feb 10th, 2017
* Author: Xiaoke Huang
******************************************************************************/
export interface LineChartEventHandlers {
dataZoom: {
(event: {
type: 'datazoom';
start: number;
end: number;
startValue?: number;
endValue?: number;
}, chart: BaseApi): string | void;
};
legendselectchanged: {
(event: {
type: 'legendselectchanged';
name: string;
selected: Object;
}, chart: BaseApi): string | void;
};
[events: string]: {
(event: any, chart: BaseApi): string | void;
};
}
export class LineChartEvent {
private chart;
private defaultHandlers;
handlers: LineChartEventHandlers;
constructor(parent: BaseApi);
getEventsName(): string[];
/**
* get event callback instance by event Name;
* @param {BaseApi} eventName [description]
*/
getEventHandler(eventName: string): {
(event: any, chart?: BaseApi): void;
};
setEventHandler(eventName: string, callback: {
(event: any, chart?: BaseApi): void;
}): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Line chart render module class.
*
* Created on: Feb 2nd, 2017
* Author: Xiaoke Huang
******************************************************************************/
/**
* Line chart render class.
*/
export class LineChartRender {
private chart;
private engine;
private style;
private defaultOptions;
constructor(parent: BaseApi);
update(): this;
updateSettings(options?: any): this;
redraw(): this;
updateXAxisRange(start: number, end: number): this;
legendSelect(name: string, select?: boolean): this;
legendToggle(name: string): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Line chart render engine module class.
*
* Created on: Feb 6th, 2017
* Author: Xiaoke Huang
******************************************************************************/
/**
* ECharts Options Typings. Needs to get ECharts Typings.
*/
export interface ELineChartsOptions {
[option: string]: any;
}
export class LineChartRenderEngine {
private chart;
private options;
private timer;
private timerTask;
core: any;
constructor(parent: BaseApi, options: ELineChartsOptions);
/**
* refine user input chart options for echarts.
* @param {ELineChartsOptions} options [description]
* @return {any} [description]
*/
private refineUserOptions(options);
/**
* Init the core object of echarts. And binding the resize event with window.
* @return {this} [description]
*/
private init();
/**
* init the formatter base on options. It needs to be called before updateSetting.
* @return {this} [description]
*/
private initFormatter();
/**
* init Events binding.
* @return {this} [description]
*/
private initEvents();
/**
* Redraw the line chart. It will create a new core instance.
* @return {this} [description]
*/
redraw(): this;
/**
* Clear the line chart object.
*/
clear(): this;
/**
* Update the basic settings. It will affect current cart directly.
* @return {this} [description]
*/
updateSettings(options?: ELineChartsOptions): this;
/**
* update x Axis Range and update the line chart.
* @param {number} start [description]
* @param {number} end [description]
* @return {this} [description]
*/
updateXAxisRange(start: number, end: number): this;
/**
* Unbinds event-handling function.
* @param {string} eventName [description]
* @param {any} callbackInstance [description]
* @return {this} [description]
*/
offEvent(eventName: string, callbackInstance: any): this;
/**
* Binds event-handling function.
* @param {string} eventname [description]
* @param {any} callbackInstance [description]
* @return {this} [description]
*/
onEvent(eventname: string, callbackInstance: any): this;
/**
* Update the line chart rendering which includes all the changes through echarts.setOptions.
* @return {this} [description]
*/
update(): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Line chart style module class.
*
* Created on: Feb 2nd, 2017
* Author: Xiaoke Huang
******************************************************************************/
export class LineChartStyle extends BaseStyle {
private chart;
private defaultLineChartStyle;
constructor(parent: BaseApi);
getStyleOptions(): any;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Pie Chart Class
*
* Created on: Feb 17th, 2017
* Author: Xiaoke Huang
******************************************************************************/
export interface PieChartSetting extends ChartSetting {
name?: string;
formatter?: {
/**
* itemName for data item name, dataValue for data value, percentage for percentage. color for the item color.
* @type {[type]}
*/
tooltip?: {
(itemName?: string, dataValue?: number, percentage?: number, color?: string): string;
};
label?: {
(itemName?: string, dataValue?: number, percentage?: number, color?: string): string;
};
};
}
export interface PieChartDataPoint {
name: string;
value: number;
}
export class PieChart extends BaseApi {
render: PieChartRender;
event: PieChartEvent;
data: PieChartDataPoint[];
options: PieChartSetting;
/**
* Creates an instance of PieChart.
*
* @example Create an instance of PieChart by using a customized configuration.
* <pre>
* window.piechart = new gvis.PieChart({
* name: 'Something',
* render: {
* container: document.getElementById("piechart1"),
* legend: {
* show: true
* },
* textStyle: {
* fontStyle: 'italic',
* fontWeight: 'bolder',
* fontFamily: '"Courier New", Courier, monospace',
* fontSize: 12,
* }
* },
* formatter:{
* tooltip: function(itemName, dataValue, percentage, color) {
* return `<span style="color: ${color}">[${itemName}] : ${dataValue} (${percentage.toFixed(0)}%)</span>`;
* }
* }
* });
*
* var piechart = window.piechart;
* </pre>
*
* @param {PieChartSetting} options
* @memberof PieChart
*/
constructor(options: PieChartSetting);
/**
* Add data pints in the piechart.
*
* @example add data in piechart.
* <pre>
* window.testData = [];
* testData2 = [];
* var testN = 5;
*
* for (var i=1; i<testN; i++) {
*
* testData.push({
* name: 'Part ' + i,
* value: +(testN + 2 * i * +Math.random()).toFixed(1)
* });
*
* testData2.push({
* name: 'Usage ' + i,
* value: +(testN * Math.random() * Math.random()).toFixed(1)
* });
*
* // testData.push({
* // name: 'Part ' + i,
* // value: +(testN + 2 * i * +Math.random()).toFixed(1)
* // });
* }
*
* piechart
* .addData(testData)
* .update();
*
* // Dynamicly add data in piechart.
* setInterval(() => {
* var tmp = [];
*
* tmp.push({
* series: 'Count',
* name: 'Part ' + testN,
* value: +(testN + 2 * i * +Math.random()).toFixed(1)
* });
*
* piechart
* .addData(tmp)
* .update();
*
* testN += 1;
*
* if (testN >= 10) {
* clearInterval(window.pietmp);
* }
* }, 1000);
* </pre>
*
* @param {PieChartDataPoint[]} data
* @returns {this}
* @memberof PieChart
*/
addData(data: PieChartDataPoint[]): this;
/**
* reload the data in piechart. The previous data will be deleted from piechart.
*
* @example reload data in piechart.
*
* <pre>
* piechart.reload(testData).update();
* </pre>
*
* @param {PieChartDataPoint[]} data
* @returns {this}
* @memberof PieChart
*/
reloadData(data: PieChartDataPoint[]): this;
/**
* render the updates of piechart.
*
* @example update the piechart
* <pre>
* piechart.update();
* </pre>
* @returns {this}
* @memberof PieChart
*/
update(): this;
/**
* binding event callback by name.
*
* @example Binding pieselectchanged event
* <pre>
* piechart.on('pieselectchanged', (data, chart) => {
* console.log('Changed information : ', data);
* console.assert(chart === piechart);
* })
*
* </pre>
* @param {string} eventName [description]
* Currently supported events:
* - `pieselectchanged`
*
* @param {string}} callback [description]
*/
on(eventName: string, callback: {
(event: {
type: string;
seriesId: string;
name: string;
selected: {
[itemName: string]: boolean;
};
}, chart: BaseApi): string;
}): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: Pie chart event module class.
*
* Created on: Feb 17th, 2017
* Author: Xiaoke Huang
******************************************************************************/
export interface PieChartEventHandlers {
pieselectchanged: {
(event: {
type: string;
seriesId: string;
name: string;
selected: {
[itemName: string]: boolean;
};
}, chart: BaseApi): string;
};
[eventName: string]: {
(...args: any[]): void;
};
}
export class PieChartEvent {
private chart;
private defaultHandlers;
private handlers;
constructor(parent: BaseApi);
getEventsName(): string[];
/**
* get event callback instance by event Name;
* @param {BaseApi} eventName [description]
*/
getEventHandler(eventName: string): {
(...args: any[]): void;
};
setEventHandler(eventName: string, callback: {
(...args: any[]): void;
}): this;
}
/**
* ECharts Options Typings. Needs to get ECharts Typings.
*/
export interface EPieChartsOptions {
[option: string]: any;
}
export class PieChartRender {
private chart;
private engine;
private style;
private timer;
private timerTask;
private options;
constructor(parent: BaseApi);
private init();
/**
* init Events binding.
* @return {this} [description]
*/
private initEvents();
private initFormatter();
/**
* Update the basic settings. It will affect current cart directly.
* @return {this} [description]
*/
updateSettings(options?: EPieChartsOptions): this;
private refineUserOptions(options);
update(): this;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: pie chart style module class.
*
* Created on: Feb 17th, 2017
* Author: Xiaoke Huang
******************************************************************************/
export class PieChartStyle extends BaseStyle {
private chart;
private defaultPieChartStyle;
dataConfig: {
[keys: string]: any;
};
constructor(parent: BaseApi);
getStyleOptions(): any;
}
/**
* Color class for GVIS.
*/
export class Color {
private static c10;
private static c10a;
private static c10b;
private static c10c;
private static c10d;
private static c10e;
private static c20;
private static c30;
private static c40;
private static c50;
private static c60;
/**
* current color schema color string.
* @type {string}
*/
private colorSchema;
/**
* color array which is parsed from colorSchema.
* @type {string[]}
*/
private colorArray;
/**
* key is the type, it will be mapped to a index value or a color string.
* Index will be used to get the color string in colorArray, by colorArray[index % colorArray.length];
* Color string will be used as color.
*/
private colorMap;
private parseColorSchema(schema);
constructor(theme?: string);
/**
* Initialize color for a list of types.
* @param {string[]} types the list of types, example: ['Company', 'Car', 'Member']
* @return {this} [description]
*/
initialization(types: string[]): this;
/**
* get color for a type. Dunamically update the colorMap while getting color.
* @type {string} id for the color.
* @return {string} color string.
*/
getColor(type: string): string;
/**
* Customize a color for a type, it will override the index color.
* @type {string}
* @color {string}
* @return {this}
*/
setColor(type: string, color: string): this;
/**
* Change the color shcema theme. It will change color schema and color array after set a acceptable theme.
* @theme {string} Names of schema: 'c10', 'c10a', 'c10b', 'c10c', 'c10d', 'c10e', 'c20', 'c30', 'c40', 'c50', 'c60'
* @return {this}
*/
setColorTheme(theme: string): this;
/**
* Change the color schema for the color Array.
* @schema {string}
* @return {this}
*/
setColorSchema(schema: string): this;
/**
* Reset the color map object. Does not change the color schema or color array.
* @return {this}
*/
reset(): this;
/**
* use to generate random RGB color string. The random color could be duplicated.
* @return {string} random RGB color string.
*/
randomColor(): string;
/**
* use to return the privagte memeber color array. It will retrun an array contains currently used colors.
* @return {string[]} [description]
*/
getColorArray(): string[];
}
/**
* Exception class for handler all the exception in GVIS library.
* function GExceptionExample() {
* try {
* throw new GException(1000, 'customized error message');
* } catch (e) {
* console.log(r.toString);
* }
* }
*/
export class GException {
/**
* Exception status
* @type {number}
*/
status: number;
/**
* Exception customized message. By default is empty.
* @type {string}
*/
body: string;
/**
* Current error type which is defiend in ErrorStatus object. A status shows undefined if one status is not defined
* @type {string}
*/
errorType: string;
/**
* Error message which contains all the error information. Use this field for console.error output.
* @type {string}
*/
error: string;
/**
* @param {number} exception status code
* @param {string} customized message.
*/
constructor(status: number, body?: string);
toString(): string;
}
export const builtinIcons: {
[iconName: string]: any;
};
export const otherIcons: {
[iconName: string]: {
fileName: string;
size?: [number, number];
padding?: [number, number, number, number];
};
};
/**
* ICON class for gvis visualization icon framework.
*/
export class ICON {
private icons;
baseURL: string;
constructor(baseURL?: string);
/**
* add icon for visualization..
* @param {[type]} iconName The name of the icon which will be used in node GraphStyle.base.icon
* @param {[type]} fileName icon image name.
* @param {[number, number, number, number]} padding [top, right, buttom, left] percentage of the icon which will be shown. default value is [0.2, 0.2, 0.2, 0.2]
* @param {[number, number]} size [width, height] of the icon image in pixel. Default value is [512, 512].
* @param {[boolean]} overwrite Determiner whether or not overwirte existed icon in the object. Defualt is false
* @return {this} [description]
*/
addIcon(iconName: string, fileName: string, padding?: [number, number, number, number], size?: [number, number], overwrite?: boolean): this;
/**
* Get Icon by iconName. If icon name does not exist, return {}.
* @param {[type]} iconName [description]
*/
getIcon(iconName: string): {
image: string;
/** @type {[type]} [top, right, buttom, left] */
padding: [number, number, number, number];
/** @type {[type]} [left, top, width, height]*/
imageSlicing: [number, number, number, number];
};
}
/**
* Localization module for gvis library.
*/
export class Localization {
private localization;
private selectedLanguage;
constructor(language: {
selectedLanguage?: string;
localization?: {
[language: string]: {
vertex?: {
[type: string]: string | {
type?: string;
attrs: {
[attribute: string]: string | {
attr?: string;
values: {
[value: string]: string;
};
};
};
};
};
edge?: {
[type: string]: string | {
type?: string;
attrs: {
[attribute: string]: string | {
attr?: string;
values: {
[value: string]: string;
};
};
};
};
};
};
};
});
/**
* Set current selected language. if the selectedLanguage is not found, selectedLanguage set to be undefined.
* @param {[type]} selectedLanguage existed language name.
* @return {this} [description]
*/
setSelectedLanguage(selectedLanguage: string): this;
/**
* get the vertex translation base on the input values.
* Translate type, if only type is inputed. Translate attribute, if type and attribute are inputed. Translate value, if all arguments are inputed.
* It will translate the value for specific input based on the vertex type and attribute.
* @param {string} type Vertex type
* @param {string} attribute Vertex attribute
* @param {string} value Vertex value
* @return {string} the translated value
*/
getVertexString(type: string, attribute?: string, value?: string): string;
/**
* get the edge translation base on the input values.
* Translate type, if only type is inputed. Translate attribute, if type and attribute are inputed. Translate value, if all arguments are inputed.
* It will translate the value for specific input based on the edge type and attribute.
* @param {string} type Edge type
* @param {string} attribute Edge attribute
* @param {string} value Edge value
* @return {string} the translated value
*/
getEdgeString(type: string, attribute?: string, value?: string): string;
translateOneNode(node: GraphChartDataNode): any;
translateOneLink(link: GraphChartDataLink): any;
}
/******************************************************************************
* Copyright (c) 2017, TigerGraph Inc.
* All rights reserved.
* Project: GVIS
* Brief: GVIS library External Graph Parser Module.
*
* Created on: Oct 27th, 2016
* Author: Xiaoke Huang
******************************************************************************/
/**
* parser format standard class.
* @type {[type]}
*/
export class GraphParserFormat {
gquery: {
isNode: {
(obj: any): boolean;
};
isLink: {
(obj: any): boolean;
};
parseNode: {
(obj: any): ExternalNode;
};
parseLink: {
(obj: any): ExternalLink | ExternalLink[];
};
};
pta: {
isNode: {
(obj: any): boolean;
};
isLink: {
(obj: any): boolean;
};
parseNode: {
(obj: any): ExternalNode;
};
parseLink: {
(obj: any): ExternalLink | ExternalLink[];
};
};
ksubgraph: {
isNode: {
(obj: any): boolean;
};
isLink: {
(obj: any): boolean;
};
parseNode: {
(obj: any): ExternalNode;
};
parseLink: {
(obj: any): ExternalLink;
};
};
gpr: {
isNode: {
(obj: any): boolean;
};
isLink: {
(obj: any): boolean;
};
parseNode: {
(obj: any): ExternalNode;
};
parseLink: {
(obj: any): ExternalLink;
};
};
restpp: {
isNode: {
(obj: any): boolean;
};
isLink: {
(obj: any): boolean;
};
parseNode: {
(obj: any): ExternalNode;
};
parseLink: {
(obj: any): ExternalLink;
};
};
gst: {
isNode: {
(obj: any): boolean;
};
isLink: {
(obj: any): boolean;
};
parseNode: {
(obj: any): ExternalNode;
};
parseLink: {
(obj: any): ExternalLink;
};
};
constructor();
private initGQueryFormat();
private initPTAFormat();
private initKSubGraphFormat();
private initGPRFormat();
private initRestppFormat();
private initGSTFormat();
/**
* convert gpe topology attribute standard output to json object.
* @example
* <pre>
* 'type:2|od_et4:2|od_et5:1|name(0):site12|formula_order(0):2|useAmount(1):6000.000000|' =>
* { name: 'site12', 'formula_order': '2', 'useAmount': '6000.000000'}
* Split by '|', then for each item parse /(.*)\(\d*\):(.*)$/. In this case, 'type', 'od_et4', 'od_et5' are not parsed.
* </pre>
* @param {string} attrString [description]
*/
private gpeTopologyAttributesOutputToJSON(attrString);
}
/**
* Graph parser class.
*/
export class GraphParser {
chart: BaseApi;
parsers: {
[parserName: string]: {
(externalData: any): ExternalGraph;
};
};
private parserFormat;
constructor(parent: BaseApi);
/**
* recursively parsing obj to get external graph elements, such as nodes and links. Then add external graph elements in to targetGraph base on the format setting.
* @param {any} obj raw input. It is an random json object, which may contains graph elements.
* @param {ExternalGraph} targetGraph The output graph. It is the graph in visualization format.
* @param {ExternalLink }; }} format This is the format object which contians 4 functions:
* isNode: { (obj: any): boolean }; Check if an obj is a node.
* isLink: { (obj: any): boolean }; Check if an obj is a link.
* parseNode: { (obj: any): ExternalNode }; Parser function for a node.
* parseLink: { (obj: any): ExternalLink }; Parser function for a link.
*/
private recursivelyGetExternalElement(obj, targetGraph, format);
/**
* Add a parser function by name. Then we can use it by getParser('parserName');
* @param {string} parserName [description]
* @param {ExternalGraph }} callback [description]
* @return {this} [description]
*/
addParser(parserName: string, callback: {
(externalData: any): ExternalGraph;
}): this;
/**
* Update a parser function by name. Then we use the updated parser function by getParser('parserName');
* @param {string} parserName [description]
* @param {ExternalGraph }} callback [description]
* @return {this} [description]
*/
updateParser(parserName: string, callback: {
(externalData: any): ExternalGraph;
}): this;
/**
* Get the target parser function by name.
* @param {any} parserName [description]
* @return {ExternalGraph} [description]
*/
getParser(parserName: string): {
(externalData: any): ExternalGraph;
};
}
/**
* Array parser class. Need to be implemented for LineChart, once we have time.
*/
export class ArrayParser {
}
/**
* GVIS library Utility Module.
*/
export module Utils {
/**
* Download a uri in to a file.
* @param {[type]} uri [description]
* @param {[type]} name [description]
*/
function downloadURI(uri: string, name: string): void;
/**
* Convert GRB hexColor '#ffffff'code and alpha 1 to 'rgba(255, 255, 255, 1)'.
* @param {string} hexColor hex color code.
* @param {[type]} alpha The opacity of the color.
* @return {string} The converted color object string for canvas rendering engine.
*/
function rgbToRgba(hexColor: string, alpha?: string): string;
/**
* Calcualte coordinates for a point after rotate certain degree.
* @cx {number} rotate origin x
* @cy {number} rotate origin y
* @x {number} x of point
* @y {number} y of point
* @degree {number} degree of the rotation, range: [-180, 180]
*/
function rotate(cx: number, cy: number, x: number, y: number, degree: number): [number, number];
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are **not** supported.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'user': 'fred' };
* var other = { 'user': 'fred' };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value: Object, other: Object): boolean;
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep<T>(obj: T): T;
/**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/
function clone<T>(obj: T): T;
/**
* Creates a new array concatenating `array` with any additional arrays
* and/or values.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to concatenate.
* @param {...*} [values] The values to concatenate.
* @returns {Array} Returns the new concatenated array.
* @example
*
* var array = [1];
* var other = _.concat(array, 2, [3], [[4]]);
*
* console.log(other);
* // => [1, 2, 3, [4]]
*
* console.log(array);
* // => [1]
*/
function concat<T>(...values: (T | T[])[]): T[];
/**
* Assigns own enumerable properties of source object(s) to the destination object for all destination
* properties that resolve to undefined. Once a property is set, additional values of the same property are
* ignored.
*
* Note: This method mutates object.
*
* @param object The destination object.
* @param sources The source objects.
* @return The destination object.
*/
function defaults<T>(target: T, ...sources: any[]): any;
/**
* This method is like _.defaults except that it recursively assigns default properties.
* @param object The destination object.
* @param sources The source objects.
* @return Returns object.
*/
function defaultsDeep<T>(target: T, ...sources: any[]): any;
/**
* Recursively merges own and inherited enumerable properties of source
* objects into the destination object, skipping source properties that resolve
* to `undefined`. Array and plain object properties are merged recursively.
* Other objects and value types are overridden by assignment. Source objects
* are applied from left to right. Subsequent sources overwrite property
* assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var users = {
* 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
* };
*
* var ages = {
* 'data': [{ 'age': 36 }, { 'age': 40 }]
* };
*
* _.merge(users, ages);
* // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
*/
function extend<T>(destiation: T, ...sources: any[]): any;
/**
* assign handles unassigned but the others will skip it.
* This method is like `_.assign` except that it iterates over own and
* inherited source properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* function Bar() {
* this.d = 4;
* }
*
* Foo.prototype.c = 3;
* Bar.prototype.e = 5;
*
* _.assignIn({ 'a': 1 }, new Foo, new Bar);
* // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }
*/
function assignIn<T>(destiation: T, ...source: any[]): any;
/**
* Removes elements from array corresponding to the given indexes and returns an array of the removed elements.
* Indexes may be specified as an array of indexes or as individual arguments.
*
* Note: Unlike _.at, this method mutates array.
*
* @param array The array to modify.
* @param indexes The indexes of elements to remove, specified as individual indexes or arrays of indexes.
* @return Returns the new array of removed elements.
*/
function pullAt<T>(array: T[], indexes: number | number[]): T[];
/**
* Gets a random element from `collection`.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*/
function sample<T>(collection: T[], index?: number): any;
function loadCSSIfNotAlreadyLoaded(pathToCSS: string): void;
/**
* Insert a new data in a sorted array in O(Nlog(N)) time base on sort callback funtion.
* @type {T}
*/
function binaryInsert<T>(data: T, array: T[], callback: (a: T, b: T) => number, startVal?: number, endVal?: number): void;
}
} | the_stack |
/*!
* @author electricessence / https://github.com/electricessence/
* Original: http://linqjs.codeplex.com/
* Licensing: MIT https://github.com/electricessence/TypeScript.NET/blob/master/LICENSE.md
*/
import {areEqual as areEqualValues, compare as compareValues} from "../System/Compare";
import {copy} from "../System/Collections/Array/copy";
import * as Arrays from "../System/Collections/Array/Compare";
import * as enumUtil from "../System/Collections/Enumeration/Enumerator";
import {
isEnumerable,
isEnumerator,
isIterator,
throwIfEndless
} from "../System/Collections/Enumeration/Enumerator";
import {EmptyEnumerator} from "../System/Collections/Enumeration/EmptyEnumerator";
import {Type} from "../System/Types";
import {Integer} from "../System/Integer";
import {Functions as BaseFunctions} from "../System/Functions";
import {ArrayEnumerator} from "../System/Collections/Enumeration/ArrayEnumerator";
import {EnumeratorBase} from "../System/Collections/Enumeration/EnumeratorBase";
import {Dictionary} from "../System/Collections/Dictionaries/Dictionary";
import {Queue} from "../System/Collections/Queue";
import {dispose, using} from "../System/Disposable/dispose";
import {DisposableBase} from "../System/Disposable/DisposableBase";
import {UnsupportedEnumerableException} from "../System/Collections/Enumeration/UnsupportedEnumerableException";
import {ObjectDisposedException} from "../System/Disposable/ObjectDisposedException";
import {KeySortedContext} from "../System/Collections/Sorting/KeySortedContext";
import {ArgumentNullException} from "../System/Exceptions/ArgumentNullException";
import {ArgumentOutOfRangeException} from "../System/Exceptions/ArgumentOutOfRangeException";
import {IEnumerator} from "../System/Collections/Enumeration/IEnumerator";
import {IEnumerable} from "../System/Collections/Enumeration/IEnumerable";
import {
Action,
ActionWithIndex,
Closure,
Comparison,
EqualityComparison,
HashSelector,
PredicateWithIndex,
Selector,
SelectorWithIndex
} from "../System/FunctionTypes";
import {IDictionary, IMap} from "../System/Collections/Dictionaries/IDictionary";
import {Comparable} from "../System/IComparable";
import {IComparer} from "../System/IComparer";
import {IKeyValuePair} from "../System/KeyValuePair";
import {Order} from "../System/Collections/Sorting/Order";
import {EnumerableAction} from "./EnumerableAction";
import {IndexEnumerator} from "../System/Collections/Enumeration/IndexEnumerator";
import {Primitive} from "../System/Primitive";
import {IteratorEnumerator} from "../System/Collections/Enumeration/IteratorEnumerator";
import {ForEachEnumerable} from "../System/Collections/Enumeration/ForEachEnumerable";
import {initialize} from "../System/Collections/Array/initialize";
import {Random} from "../System/Random";
import {
InfiniteEnumerator,
InfiniteValueFactory
} from "../System/Collections/Enumeration/InfiniteEnumerator";
import __extendsImport from "../extends";
import {LazyList} from "../System/Collections/LazyList";
import disposeSingle = dispose.single;
// noinspection JSUnusedLocalSymbols
const __extends = __extendsImport;
// #region Local Constants.
const INVALID_DEFAULT:any = {}; // create a private unique instance for referencing.
const VOID0:undefined = void 0;
const NULL:any = null;
function BREAK():EnumerableAction
{
return EnumerableAction.Break;
}
function RETURN():EnumerableAction
{
return EnumerableAction.Return;
}
function isNotNullOrUndefined(e:any):boolean
{
return e!=null;
}
// Leave internal to avoid accidental overwriting.
class LinqFunctions
extends BaseFunctions
{
// noinspection JSMethodCanBeStatic
Greater<T>(a:T, b:T)
{
return a>b ? a : b;
}
// noinspection JSMethodCanBeStatic
Lesser<T>(a:T, b:T)
{
return a<b ? a : b;
}
}
const Functions = Object.freeze(new LinqFunctions());
// For re-use as a factory.
function getEmptyEnumerator():IEnumerator<any>
{
return EmptyEnumerator;
}
// #endregion
/*
* NOTE: About InfiniteEnumerable<T> and Enumerable<T>.
* There may seem like there's extra overrides here and they may seem unnecessary.
* But after closer inspection you'll see the type chain is retained and
* infinite enumerables are prevented from having features that finite ones have.
*
* I'm not sure if it's the best option to just use overrides, but it honors the typing properly.
*/
export class InfiniteLinqEnumerable<T>
extends DisposableBase
{
constructor(
protected _enumeratorFactory:() => IEnumerator<T>,
finalizer?:Closure | null)
{
super("InfiniteLinqEnumerable", finalizer);
this._isEndless = true;
}
protected _isEndless:boolean | undefined;
get isEndless():boolean | undefined
{
return this._isEndless;
}
// #region IEnumerable<T> Implementation...
getEnumerator():IEnumerator<T>
{
this.throwIfDisposed();
return this._enumeratorFactory();
}
// #endregion
// #region IDisposable override...
protected _onDispose():void
{
super._onDispose(); // Just in case.
(<any>this)._enumeratorFactory = null;
}
// #endregion
// Return a default (unfiltered) enumerable.
asEnumerable():this
{
const _ = this;
_.throwIfDisposed();
return <any> new InfiniteLinqEnumerable<T>(() => _.getEnumerator());
}
/**
* Similar to forEach, but executes an action for each time a value is enumerated.
* If the action explicitly returns false or 0 (EnumerationAction.Break), the enumeration will complete.
* If it returns a 2 (EnumerationAction.Skip) it will move on to the next item.
* This also automatically handles disposing the enumerator.
* @param action
* @param initializer
* @param isEndless Special case where isEndless can be null in order to negate inheritance.
* @param onComplete Executes just before the enumerator releases when there is no more entries.
* @returns {any}
*/
doAction(
action:ActionWithIndex<T> | PredicateWithIndex<T> | SelectorWithIndex<T, number> | SelectorWithIndex<T, EnumerableAction>,
initializer:Closure | null,
isEndless:true,
onComplete?:Action<number>):InfiniteLinqEnumerable<T>
doAction(
action:ActionWithIndex<T> | PredicateWithIndex<T> | SelectorWithIndex<T, number> | SelectorWithIndex<T, EnumerableAction>,
initializer?:Closure | null,
isEndless?:boolean | null | undefined,
onComplete?:Action<number>):LinqEnumerable<T>
doAction(
action:ActionWithIndex<T> | PredicateWithIndex<T> | SelectorWithIndex<T, number> | SelectorWithIndex<T, EnumerableAction>,
initializer?:Closure | null,
isEndless:boolean | null | undefined = this.isEndless,
onComplete?:Action<number>):LinqEnumerable<T>
{
const _ = this;
_.throwIfDisposed();
const isE:boolean | undefined = isEndless || undefined; // In case it's null.
if(!action)
throw new ArgumentNullException("action");
return <any> new LinqEnumerable<T>(
() =>
{
let enumerator:IEnumerator<T>;
let index:number = 0;
return new EnumeratorBase<T>(
() =>
{
throwIfDisposed(!action);
if(initializer) initializer();
index = 0;
enumerator = _.getEnumerator();
// May need a way to propagate isEndless
},
(yielder) =>
{
throwIfDisposed(!action);
while(enumerator.moveNext())
{
let c = enumerator.current!;
let actionResult = <any>action(c, index++);
if(actionResult===false || actionResult===EnumerableAction.Break)
return yielder.yieldBreak();
if(actionResult!==EnumerableAction.Skip) // || !== 2
return yielder.yieldReturn(c);
// If actionResult===2, then a signal for skip is received.
}
if(onComplete) onComplete(index);
return false;
},
() =>
{
if(enumerator) enumerator.dispose();
},
isE
);
},
// Using a finalizer value reduces the chance of a circular reference
// since we could simply reference the enumeration and check e.wasDisposed.
() =>
{
action = NULL;
},
isE
);
}
force():void
{
this.throwIfDisposed();
this.doAction(BREAK)
.getEnumerator()
.moveNext();
}
// #region Indexing/Paging methods.
skip(count:number):this
{
const _ = this;
_.throwIfDisposed();
if(!isFinite(count)) // +Infinity equals skip all so return empty.
return <any> new InfiniteLinqEnumerable<T>(getEmptyEnumerator);
Integer.assert(count, "count");
return this.where((element, index) => index>=count);
}
take(count:number):FiniteEnumerable<T>
{
if(!(count>0)) // Out of bounds? Empty.
return Enumerable.empty<T>();
const _ = this;
_.throwIfDisposed();
if(!isFinite(count))
throw new ArgumentOutOfRangeException('count', count, 'Must be finite.');
Integer.assert(count, "count");
// Once action returns false, the enumeration will stop.
return <any> _.doAction((element, index) => index<count, null, false);
}
// #region Single Value Return...
elementAt(index:number):T
{
const v = this.elementAtOrDefault(index, INVALID_DEFAULT);
if(v===INVALID_DEFAULT) throw new ArgumentOutOfRangeException('index', index, "is greater than or equal to the number of elements in source");
return <T>v;
}
elementAtOrDefault(index:number):T | undefined
elementAtOrDefault(index:number, defaultValue:T):T
elementAtOrDefault(index:number, defaultValue?:T):T | undefined
{
const _ = this;
_.throwIfDisposed();
Integer.assertZeroOrGreater(index, 'index');
const n:number = index;
return using(
this.getEnumerator(),
e =>
{
let i = 0;
while(e.moveNext())
{
if(i==n) return e.current;
i++;
}
return defaultValue;
});
}
/* Note: Unlike previous implementations, you could pass a predicate into these methods.
* But since under the hood it ends up calling .where(predicate) anyway,
* it may be better to remove this to allow for a cleaner signature/override.
* JavaScript/TypeScript does not easily allow for a strict method interface like C#.
* Having to write extra override logic is error prone and confusing to the consumer.
* Removing the predicate here may also cause the consumer of this method to think more about how they structure their query.
* The end all difference is that the user must declare .where(predicate) before .first(), .single(), or .last().
* Otherwise there would need to be much more code to handle these cases (.first(predicate), etc);
* */
first():T
{
const v = this.firstOrDefault(INVALID_DEFAULT);
if(v===INVALID_DEFAULT) throw new Error("first:The sequence is empty.");
return <T>v;
}
firstOrDefault():T | undefined
firstOrDefault(defaultValue:T):T
firstOrDefault(defaultValue?:T):T | undefined
{
const _ = this;
_.throwIfDisposed();
return using(
this.getEnumerator(),
e => e.moveNext() ? e.current : defaultValue
);
}
single():T
{
const _ = this;
_.throwIfDisposed();
return <T>using(
this.getEnumerator(),
e =>
{
if(e.moveNext())
{
let value = e.current;
if(!e.moveNext()) return value;
throw new Error("single:sequence contains more than one element.");
}
throw new Error("single:The sequence is empty.");
}
);
}
singleOrDefault():T | undefined
singleOrDefault(defaultValue:T):T
singleOrDefault(defaultValue?:T):T | undefined
{
const _ = this;
_.throwIfDisposed();
return using(
this.getEnumerator(),
e =>
{
if(e.moveNext())
{
let value = e.current;
if(!e.moveNext()) return value;
}
return defaultValue;
}
);
}
any():boolean
{
const _ = this;
_.throwIfDisposed();
return using(
this.getEnumerator(),
e => e.moveNext()
);
}
isEmpty():boolean
{
return !this.any();
}
// #endregion
// #region Projection and Filtering Methods
traverseDepthFirst(
childrenSelector:(element:T) => ForEachEnumerable<T> | null | undefined):LinqEnumerable<T>;
traverseDepthFirst<TNode>(
childrenSelector:(element:T | TNode) => ForEachEnumerable<TNode> | null | undefined):LinqEnumerable<TNode>;
traverseDepthFirst<TResult>(
childrenSelector:(element:T) => ForEachEnumerable<T> | null | undefined,
resultSelector:SelectorWithIndex<T, TResult>):LinqEnumerable<TResult>;
traverseDepthFirst<TNode, TResult>(
childrenSelector:(element:T | TNode) => ForEachEnumerable<TNode> | null | undefined,
resultSelector:SelectorWithIndex<T, TResult>):LinqEnumerable<TResult>;
traverseDepthFirst<TNode>(
childrenSelector:(element:T | TNode) => ForEachEnumerable<TNode> | null | undefined,
resultSelector:(
element:TNode,
nestLevel:number) => any = <any>Functions.Identity):LinqEnumerable<any>
{
const _ = this;
let disposed = !_.throwIfDisposed();
const isEndless = _._isEndless; // Is endless is not affirmative if false.
return new LinqEnumerable<any>(
() =>
{
// Dev Note: May want to consider using an actual stack and not an array.
let enumeratorStack:IEnumerator<any>[];
let enumerator:IEnumerator<any>;
let len:number; // Avoid using push/pop since they query .length every time and can be slower.
return new EnumeratorBase<T>(
() =>
{
throwIfDisposed(disposed);
enumerator = _.getEnumerator();
enumeratorStack = [];
len = 0;
},
(yielder) =>
{
throwIfDisposed(disposed);
while(true)
{
if(enumerator.moveNext())
{
let value = resultSelector(<TNode>enumerator.current, len);
enumeratorStack[len++] = enumerator;
let c = childrenSelector(<T | TNode>enumerator.current);
let e = !Type.isString(c) && Enumerable.fromAny(c);
enumerator = e ? e.getEnumerator() : EmptyEnumerator;
return yielder.yieldReturn(value);
}
if(len==0) return false;
enumerator.dispose();
enumerator = enumeratorStack[--len];
enumeratorStack.length = len;
}
},
() =>
{
try
{
if(enumerator) enumerator.dispose();
}
finally
{
if(enumeratorStack)
{
dispose.these.noCopy(enumeratorStack);
enumeratorStack.length = 0;
enumeratorStack = NULL;
}
}
},
isEndless
);
},
() =>
{
disposed = true;
},
isEndless
);
}
flatten<TFlat>():InfiniteLinqEnumerable<TFlat>
flatten():InfiniteLinqEnumerable<any>
flatten():InfiniteLinqEnumerable<any>
{
return this.selectMany(entry =>
{
let e = !Type.isString(entry) && Enumerable.fromAny(entry);
return e ? e.flatten() : [entry];
});
}
pairwise<TSelect>(
selector:(
previous:T, current:T,
index:number) => TSelect):InfiniteLinqEnumerable<TSelect>
{
const _ = this;
_.throwIfDisposed();
if(!selector)
throw new ArgumentNullException("selector");
let previous:T;
return this.select<TSelect>((value, i) =>
{
const result:any = i ? selector(previous!, value, i) : NULL;
previous = value;
return result;
}).skip(1);
}
scan(func:(previous:T, current:T, index:number) => T, seed?:T):this
{
const _ = this;
_.throwIfDisposed();
if(!func)
throw new ArgumentNullException("func");
return <this>(
seed===VOID0
? this.select((value, i) => seed = i ? func(seed!, value, i) : value)
: this.select((value, i) => seed = func(seed!, value, i))
);
}
// #endregion
select<TResult>(selector:SelectorWithIndex<T, TResult>):InfiniteLinqEnumerable<TResult>
{
return this._filterSelected(selector);
}
map<TResult>(selector:SelectorWithIndex<T, TResult>):InfiniteLinqEnumerable<TResult>
{
return this._filterSelected(selector);
}
/*
public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TCollection>> collectionSelector,
Func<TSource, TCollection, TResult> resultSelector)
*/
protected _selectMany<TElement, TResult>(
collectionSelector:SelectorWithIndex<T, ForEachEnumerable<TElement> | null | undefined>,
resultSelector?:(collection:T, element:TElement) => TResult):LinqEnumerable<TResult>
{
const _ = this;
_.throwIfDisposed();
if(!collectionSelector)
throw new ArgumentNullException("collectionSelector");
const isEndless = _._isEndless; // Do second enumeration, it will be indeterminate if false.
if(!resultSelector)
resultSelector = (a:T, b:any) => <TResult>b;
return new LinqEnumerable<TResult>(
() =>
{
let enumerator:IEnumerator<T>;
let middleEnumerator:IEnumerator<any> | null | undefined;
let index:number = 0;
return new EnumeratorBase<TResult>(
() =>
{
throwIfDisposed(!collectionSelector);
enumerator = _.getEnumerator();
middleEnumerator = VOID0;
index = 0;
},
(yielder) =>
{
throwIfDisposed(!collectionSelector);
// Just started, and nothing to enumerate? End.
if(middleEnumerator===VOID0 && !enumerator.moveNext())
return false;
// moveNext has been called at least once...
do
{
// Initialize middle if there isn't one.
if(!middleEnumerator)
{
let middleSeq = collectionSelector(<T>enumerator.current, index++);
// Collection is null? Skip it...
if(!middleSeq)
continue;
middleEnumerator = enumUtil.from(middleSeq);
}
if(middleEnumerator.moveNext())
return yielder.yieldReturn(
resultSelector!(
<T>enumerator.current, <TElement>middleEnumerator.current
)
);
// else no more in this middle? Then clear and reset for next...
middleEnumerator.dispose();
middleEnumerator = null;
}
while(enumerator.moveNext());
return false;
},
() =>
{
if(enumerator) enumerator.dispose();
disposeSingle(middleEnumerator);
enumerator = NULL;
middleEnumerator = null;
},
isEndless
);
},
() =>
{
collectionSelector = NULL;
},
isEndless
);
}
selectMany<TResult>(
collectionSelector:SelectorWithIndex<T, ForEachEnumerable<TResult> | null | undefined>):InfiniteLinqEnumerable<TResult>;
selectMany<TElement, TResult>(
collectionSelector:SelectorWithIndex<T, ForEachEnumerable<TElement> | null | undefined>,
resultSelector:(collection:T, element:TElement) => TResult):InfiniteLinqEnumerable<TResult>;
selectMany<TResult>(
collectionSelector:SelectorWithIndex<T, ForEachEnumerable<any> | null | undefined>,
resultSelector?:(collection:T, element:any) => TResult):InfiniteLinqEnumerable<TResult>
{
return this._selectMany(collectionSelector, resultSelector);
}
protected _filterSelected(
selector?:SelectorWithIndex<T, T>,
filter?:PredicateWithIndex<T>):LinqEnumerable<T>
protected _filterSelected<TResult>(
selector:SelectorWithIndex<T, TResult>,
filter?:PredicateWithIndex<TResult>):LinqEnumerable<TResult>
protected _filterSelected(
selector:SelectorWithIndex<T, any> = <any>Functions.Identity,
filter?:PredicateWithIndex<any>):LinqEnumerable<any>
{
const _ = this;
let disposed = !_.throwIfDisposed();
if(!selector)
throw new ArgumentNullException("selector");
return new LinqEnumerable<any>(
() =>
{
let enumerator:IEnumerator<T>;
let index:number = 0;
return new EnumeratorBase<any>(
() =>
{
throwIfDisposed(!selector);
index = 0;
enumerator = _.getEnumerator();
},
(yielder) =>
{
throwIfDisposed(disposed);
while(enumerator.moveNext())
{
let i = index++;
let result = selector(enumerator.current!, i);
if(!filter || filter(result, i++))
return yielder.yieldReturn(result);
}
return false;
},
() =>
{
if(enumerator) enumerator.dispose();
},
_._isEndless
);
},
() =>
{
disposed = false;
},
_._isEndless
);
}
/**
* Returns selected values that are not null or undefined.
*/
choose():InfiniteLinqEnumerable<T>;
choose<TResult>(selector?:Selector<T, TResult>):InfiniteLinqEnumerable<TResult>
choose(selector:Selector<T, any> = Functions.Identity):InfiniteLinqEnumerable<any>
{
return this._filterSelected(selector, isNotNullOrUndefined);
}
where(predicate:PredicateWithIndex<T>):this
{
return <any>this._filterSelected(Functions.Identity, predicate);
}
filter(predicate:PredicateWithIndex<T>):this
{
return <any>this._filterSelected(Functions.Identity, predicate);
}
nonNull():this
{
return this.where(v => v!=null && v!=VOID0);
}
ofType<TType>(type:{ new (...params:any[]):TType }):InfiniteLinqEnumerable<TType>;
ofType<TType>(type:any):InfiniteLinqEnumerable<TType>
{
let typeName:string;
switch(<any>type)
{
case Number:
typeName = Type.NUMBER;
break;
case String:
typeName = Type.STRING;
break;
case Boolean:
typeName = Type.BOOLEAN;
break;
case Function:
typeName = Type.FUNCTION;
break;
default:
return <any> this
.where(x => x instanceof type);
}
return <any>this
.where(x => isNotNullOrUndefined(x) && typeof x===typeName);
}
except(
second:ForEachEnumerable<T>,
compareSelector?:HashSelector<T>):this
{
const _ = this;
let disposed = !_.throwIfDisposed();
const isEndless = _._isEndless;
return <any> new LinqEnumerable<T>(
() =>
{
let enumerator:IEnumerator<T>;
let keys:Dictionary<T, boolean>;
return new EnumeratorBase<T>(
() =>
{
throwIfDisposed(disposed);
enumerator = _.getEnumerator();
keys = new Dictionary<T, boolean>(compareSelector);
if(second)
enumUtil.forEach(second, key => { keys.addByKeyValue(key, true) });
},
(yielder) =>
{
throwIfDisposed(disposed);
while(enumerator.moveNext())
{
let current = <T>enumerator.current;
if(!keys.containsKey(current))
{
keys.addByKeyValue(current, true);
return yielder.yieldReturn(current);
}
}
return false;
},
() =>
{
if(enumerator) enumerator.dispose();
keys.clear();
},
isEndless
);
},
() =>
{
disposed = true;
},
isEndless
);
}
distinct(compareSelector?:HashSelector<T>):this
{
return this.except(NULL, compareSelector);
}
// [0,0,0,1,1,1,2,2,2,0,0,0,1,1] results in [0,1,2,0,1];
distinctUntilChanged(compareSelector:HashSelector<T> = <any>Functions.Identity):this
{
const _ = this;
let disposed = !_.throwIfDisposed();
const isEndless = _._isEndless;
return <any> new LinqEnumerable<T>(
() =>
{
let enumerator:IEnumerator<T>;
let compareKey:any;
let initial:boolean = true;
return new EnumeratorBase<T>(
() =>
{
throwIfDisposed(disposed);
enumerator = _.getEnumerator();
},
(yielder) =>
{
throwIfDisposed(disposed);
while(enumerator.moveNext())
{
let key = compareSelector(<T>enumerator.current);
if(initial)
{
initial = false;
}
else if(areEqualValues(compareKey, key))
{
continue;
}
compareKey = key;
return yielder.yieldReturn(enumerator.current);
}
return false;
},
() =>
{
if(enumerator) enumerator.dispose();
},
isEndless
);
},
() =>
{
disposed = true;
},
isEndless
);
}
/**
* Returns a single default value if empty.
* @param defaultValue
* @returns {Enumerable}
*/
defaultIfEmpty(defaultValue?:T):this
{
const _ = this;
const disposed:boolean = !_.throwIfDisposed();
const isEndless = _._isEndless;
return <any> new LinqEnumerable<T>(
() =>
{
let enumerator:IEnumerator<T>;
let isFirst:boolean;
return new EnumeratorBase<T>(
() =>
{
isFirst = true;
throwIfDisposed(disposed);
enumerator = _.getEnumerator();
},
(yielder) =>
{
throwIfDisposed(disposed);
if(enumerator.moveNext())
{
isFirst = false;
return yielder.yieldReturn(enumerator.current);
}
else if(isFirst)
{
isFirst = false;
return yielder.yieldReturn(defaultValue);
}
return false;
},
() =>
{
if(enumerator) enumerator.dispose();
enumerator = NULL;
},
isEndless
);
},
null,
isEndless
);
}
zip<TSecond, TResult>(
second:ForEachEnumerable<TSecond>,
resultSelector:(first:T, second:TSecond, index:number) => TResult):LinqEnumerable<TResult>
{
const _ = this;
_.throwIfDisposed();
return new LinqEnumerable<TResult>(
() =>
{
let firstEnumerator:IEnumerator<T>;
let secondEnumerator:IEnumerator<TSecond>;
let index:number = 0;
return new EnumeratorBase<TResult>(
() =>
{
index = 0;
firstEnumerator = _.getEnumerator();
secondEnumerator = enumUtil.from<TSecond>(second);
},
(yielder) => firstEnumerator.moveNext()
&& secondEnumerator.moveNext()
&& yielder.yieldReturn(resultSelector(<T>firstEnumerator.current, <TSecond>secondEnumerator.current, index++)),
() =>
{
if(firstEnumerator) firstEnumerator.dispose();
if(secondEnumerator) secondEnumerator.dispose();
firstEnumerator = NULL;
secondEnumerator = NULL;
}
);
}
);
}
zipMultiple<TSecond, TResult>(
second:ArrayLike<ForEachEnumerable<TSecond>>,
resultSelector:(first:T, second:TSecond, index:number) => TResult):LinqEnumerable<TResult>
{
const _ = this;
_.throwIfDisposed();
if(!second.length)
return Enumerable.empty<TResult>();
return new LinqEnumerable<TResult>(
() =>
{
let secondTemp:Queue<any>;
let firstEnumerator:IEnumerator<T>;
let secondEnumerator:IEnumerator<TSecond>;
let index:number = 0;
return new EnumeratorBase<TResult>(
() =>
{
secondTemp = new Queue<any>(second);
index = 0;
firstEnumerator = _.getEnumerator();
secondEnumerator = NULL;
},
(yielder) =>
{
if(firstEnumerator.moveNext())
{
while(true)
{
while(!secondEnumerator)
{
if(secondTemp.count)
{
let next = secondTemp.dequeue();
if(next) // In case by chance next is null, then try again.
secondEnumerator = enumUtil.from<TSecond>(next);
}
else
return yielder.yieldBreak();
}
if(secondEnumerator.moveNext())
return yielder.yieldReturn(
resultSelector(<T>firstEnumerator.current, <TSecond>secondEnumerator.current, index++)
);
secondEnumerator.dispose();
secondEnumerator = NULL;
}
}
return yielder.yieldBreak();
},
() =>
{
if(firstEnumerator) firstEnumerator.dispose();
if(secondEnumerator) secondEnumerator.dispose();
if(secondTemp) secondTemp.dispose();
firstEnumerator = NULL;
secondEnumerator = NULL;
secondTemp = NULL;
}
);
}
);
}
// #region Join Methods
join<TInner, TKey, TResult>(
inner:ForEachEnumerable<TInner>,
outerKeySelector:Selector<T, TKey>,
innerKeySelector:Selector<TInner, TKey>,
resultSelector:(outer:T, inner:TInner) => TResult,
compareSelector:HashSelector<TKey> = <any>Functions.Identity):LinqEnumerable<TResult>
{
const _ = this;
return new LinqEnumerable<TResult>(
() =>
{
let outerEnumerator:IEnumerator<T>;
let lookup:Lookup<TKey, TInner>;
let innerElements:TInner[] | null;
let innerCount:number = 0;
return new EnumeratorBase<TResult>(
() =>
{
outerEnumerator = _.getEnumerator();
lookup = Enumerable.from(inner)
.toLookup(innerKeySelector, Functions.Identity, compareSelector);
},
(yielder) =>
{
while(true)
{
if(innerElements)
{
let innerElement = innerElements[innerCount++];
if(innerElement!==VOID0)
return yielder.yieldReturn(resultSelector(<T>outerEnumerator.current, innerElement));
innerElements = null;
innerCount = 0;
}
if(outerEnumerator.moveNext())
{
let key = outerKeySelector(<T>outerEnumerator.current);
innerElements = lookup.get(key);
}
else
{
return yielder.yieldBreak();
}
}
},
() =>
{
if(outerEnumerator) outerEnumerator.dispose();
innerElements = null;
outerEnumerator = NULL;
lookup = NULL;
}
);
}
);
}
groupJoin<TInner, TKey, TResult>(
inner:ForEachEnumerable<TInner>,
outerKeySelector:Selector<T, TKey>,
innerKeySelector:Selector<TInner, TKey>,
resultSelector:(outer:T, inner:TInner[] | null) => TResult,
compareSelector:HashSelector<TKey> = <any>Functions.Identity):LinqEnumerable<TResult>
{
const _ = this;
return new LinqEnumerable<TResult>(
() =>
{
let enumerator:IEnumerator<T>;
let lookup:Lookup<TKey, TInner>;
return new EnumeratorBase<TResult>(
() =>
{
enumerator = _.getEnumerator();
lookup = Enumerable.from(inner)
.toLookup(innerKeySelector, Functions.Identity, compareSelector);
},
(yielder) =>
enumerator.moveNext()
&& yielder.yieldReturn(
resultSelector(
<T>enumerator.current,
lookup.get(outerKeySelector(<T>enumerator.current))
)
),
() =>
{
if(enumerator) enumerator.dispose();
enumerator = NULL;
lookup = NULL;
}
);
}
);
}
merge(enumerables:ArrayLike<ForEachEnumerable<T>>):this
{
const _ = this;
const isEndless = _._isEndless;
if(!enumerables || enumerables.length==0)
return _;
return <any> new LinqEnumerable<T>(
() =>
{
let enumerator:IEnumerator<T>;
let queue:Queue<ForEachEnumerable<T>>;
return new EnumeratorBase<T>(
() =>
{
// 1) First get our values...
enumerator = _.getEnumerator();
queue = new Queue<ForEachEnumerable<T>>(enumerables);
},
(yielder) =>
{
while(true)
{
while(!enumerator && queue.tryDequeue(value =>
{
enumerator = enumUtil.from<T>(value); // 4) Keep going and on to step 2. Else fall through to yieldBreak().
}))
{ }
if(enumerator && enumerator.moveNext()) // 2) Keep returning until done.
return yielder.yieldReturn(enumerator.current);
if(enumerator) // 3) Dispose and reset for next.
{
enumerator.dispose();
enumerator = NULL;
continue;
}
return yielder.yieldBreak();
}
},
() =>
{
if(enumerator) enumerator.dispose();
enumerator = NULL;
if(queue) queue.dispose();
queue = NULL;
},
isEndless
);
},
null,
isEndless
);
}
concat(...enumerables:Array<ForEachEnumerable<T>>):this
{
return this.merge(enumerables);
}
union(
second:ForEachEnumerable<T>,
compareSelector:HashSelector<T> = <any>Functions.Identity):this
{
const _ = this;
const isEndless = _._isEndless;
return <any> new LinqEnumerable<T>(
() =>
{
let firstEnumerator:IEnumerator<T>;
let secondEnumerator:IEnumerator<T>;
let keys:Dictionary<T, any>;
return new EnumeratorBase<T>(
() =>
{
firstEnumerator = _.getEnumerator();
keys = new Dictionary<T, any>(compareSelector); // Acting as a HashSet.
},
(yielder) =>
{
let current:T;
if(secondEnumerator===VOID0)
{
while(firstEnumerator.moveNext())
{
current = <T>firstEnumerator.current;
if(!keys.containsKey(current))
{
keys.addByKeyValue(current, null);
return yielder.yieldReturn(current);
}
}
secondEnumerator = enumUtil.from(second);
}
while(secondEnumerator.moveNext())
{
current = <T>secondEnumerator.current;
if(!keys.containsKey(current))
{
keys.addByKeyValue(current, null);
return yielder.yieldReturn(current);
}
}
return false;
},
() =>
{
if(firstEnumerator) firstEnumerator.dispose();
if(secondEnumerator) secondEnumerator.dispose();
firstEnumerator = NULL;
secondEnumerator = NULL;
},
isEndless
);
},
null,
isEndless
);
}
insertAt(index:number, other:ForEachEnumerable<T>):this
{
Integer.assertZeroOrGreater(index, 'index');
const n:number = index;
const _ = this;
_.throwIfDisposed();
const isEndless = _._isEndless;
return <any> new LinqEnumerable<T>(
() =>
{
let firstEnumerator:IEnumerator<T>;
let secondEnumerator:IEnumerator<T>;
let count:number = 0;
let isEnumerated:boolean = false;
return new EnumeratorBase<T>(
() =>
{
count = 0;
firstEnumerator = _.getEnumerator();
secondEnumerator = enumUtil.from<T>(other);
isEnumerated = false;
},
(yielder) =>
{
if(count==n)
{ // Inserting?
isEnumerated = true;
if(secondEnumerator.moveNext())
return yielder.yieldReturn(secondEnumerator.current);
}
if(firstEnumerator.moveNext())
{
count++;
return yielder.yieldReturn(firstEnumerator.current);
}
return !isEnumerated
&& secondEnumerator.moveNext()
&& yielder.yieldReturn(secondEnumerator.current);
},
() =>
{
if(firstEnumerator) firstEnumerator.dispose();
firstEnumerator = NULL;
if(secondEnumerator) secondEnumerator.dispose();
secondEnumerator = NULL;
},
isEndless
);
},
null,
isEndless
);
}
alternateMultiple(sequence:ForEachEnumerable<T>):this
{
const _ = this;
const isEndless = _._isEndless;
return <any> new LinqEnumerable<T>(
() =>
{
let buffer:T,
mode:EnumerableAction,
enumerator:IEnumerator<T>,
alternateEnumerator:IEnumerator<T>;
return new EnumeratorBase<T>(
() =>
{
// Instead of recalling getEnumerator every time, just reset the existing one.
alternateEnumerator = new ArrayEnumerator(
Enumerable.toArray<T>(sequence)
); // Freeze
enumerator = _.getEnumerator();
let hasAtLeastOne = enumerator.moveNext();
mode = hasAtLeastOne
? EnumerableAction.Return
: EnumerableAction.Break;
if(hasAtLeastOne)
buffer = <T>enumerator.current;
},
(yielder) =>
{
switch(mode)
{
case EnumerableAction.Break: // We're done?
return yielder.yieldBreak();
case EnumerableAction.Skip:
if(alternateEnumerator.moveNext())
return yielder.yieldReturn(alternateEnumerator.current);
alternateEnumerator.reset();
mode = EnumerableAction.Return;
break;
}
let latest = buffer;
// Set up the next round...
// Is there another one? Set the buffer and setup instruct for the next one to be the alternate.
let another = enumerator.moveNext();
mode = another
? EnumerableAction.Skip
: EnumerableAction.Break;
if(another)
buffer = <T>enumerator.current;
return yielder.yieldReturn(latest);
},
() =>
{
if(enumerator) enumerator.dispose();
if(alternateEnumerator) alternateEnumerator.dispose();
enumerator = NULL;
alternateEnumerator = NULL;
},
isEndless
);
},
null,
isEndless
);
}
alternateSingle(value:T):this
{
return this.alternateMultiple(Enumerable.make(value));
}
alternate(...sequence:T[]):this
{
return this.alternateMultiple(sequence);
}
// #region Error Handling
catchError(handler:(e:any) => void):this
{
const _ = this;
const disposed = !_.throwIfDisposed();
return <any> new LinqEnumerable<T>(
() =>
{
let enumerator:IEnumerator<T>;
return new EnumeratorBase<T>(
() =>
{
try
{
throwIfDisposed(disposed);
enumerator = _.getEnumerator();
}
catch(e)
{
// Don't init...
}
},
(yielder) =>
{
if(enumerator) try
{
throwIfDisposed(disposed);
if(enumerator.moveNext())
return yielder.yieldReturn(enumerator.current);
}
catch(e)
{
handler(e);
}
return false;
},
() =>
{
if(enumerator) enumerator.dispose();
enumerator = NULL;
}
);
}
);
}
finallyAction(action:Closure):this
{
const _ = this;
const disposed = !_.throwIfDisposed();
return <any> new LinqEnumerable<T>(
() =>
{
let enumerator:IEnumerator<T>;
return new EnumeratorBase<T>(
() =>
{
throwIfDisposed(disposed);
enumerator = _.getEnumerator();
},
(yielder) =>
{
throwIfDisposed(disposed);
return (enumerator.moveNext())
? yielder.yieldReturn(enumerator.current)
: false;
},
() =>
{
try
{
if(enumerator) enumerator.dispose();
enumerator = NULL;
}
finally
{
action();
}
}
);
}
);
}
// #endregion
buffer(size:number):InfiniteLinqEnumerable<T[]>
{
if(size<1 || !isFinite(size))
throw new Error("Invalid buffer size.");
Integer.assert(size, "size");
const _ = this;
const isEndless = _._isEndless;
let len:number;
return new LinqEnumerable<T[]>(
() =>
{
let enumerator:IEnumerator<T>;
return new EnumeratorBase<T[]>(
() =>
{
enumerator = _.getEnumerator();
},
(yielder) =>
{
let array:T[] = initialize<T>(size);
len = 0;
while(len<size && enumerator.moveNext())
{
array[len++] = <T>enumerator.current;
}
array.length = len;
return !!len && yielder.yieldReturn(array);
},
() =>
{
if(enumerator) enumerator.dispose();
enumerator = NULL;
},
isEndless
);
},
null,
isEndless
);
}
share():this
{
const _ = this;
_.throwIfDisposed();
let sharedEnumerator:IEnumerator<T>;
return <any> new LinqEnumerable<T>(
() =>
{
return sharedEnumerator || (sharedEnumerator = _.getEnumerator());
},
() =>
{
if(sharedEnumerator) sharedEnumerator.dispose();
sharedEnumerator = NULL;
},
_._isEndless
);
}
memoize():InfiniteLinqEnumerable<T>
{
let source = new LazyList(this);
return <this>(new InfiniteLinqEnumerable<T>(() => source.getEnumerator(), () =>
{
source.dispose();
source = <any>null
}));
}
}
/**
* Enumerable<T> is a wrapper class that allows more primitive enumerables to exhibit LINQ behavior.
*
* In C# Enumerable<T> is not an instance but has extensions for IEnumerable<T>.
* In this case, we use Enumerable<T> as the underlying class that is being chained.
*/
export class LinqEnumerable<T>
extends InfiniteLinqEnumerable<T>
{
constructor(
enumeratorFactory:() => IEnumerator<T>,
finalizer?:Closure | null,
isEndless?:boolean)
{
super(enumeratorFactory, finalizer);
this._isEndless = isEndless;
// @ts-ignore
this._disposableObjectName = "LinqEnumerable";
}
// Return a default (unfiltered) enumerable.
asEnumerable():this
{
const _ = this;
_.throwIfDisposed();
return <any> new LinqEnumerable<T>(() => _.getEnumerator());
}
// #region Indexing/Paging methods.
skipWhile(predicate:PredicateWithIndex<T>):LinqEnumerable<T>
{
this.throwIfDisposed();
return this.doAction(
(element:T, index:number) =>
predicate(element, index)
? EnumerableAction.Skip
: EnumerableAction.Return
);
}
takeWhile(predicate:PredicateWithIndex<T>):this
{
this.throwIfDisposed();
if(!predicate)
throw new ArgumentNullException('predicate');
return <any>this.doAction(
(element:T, index:number) =>
predicate(element, index)
? EnumerableAction.Return
: EnumerableAction.Break,
null,
null // We don't know the state if it is endless or not.
);
}
// Is like the inverse of take While with the ability to return the value identified by the predicate.
takeUntil(predicate:PredicateWithIndex<T>, includeUntilValue?:boolean):this
{
this.throwIfDisposed();
if(!predicate)
throw new ArgumentNullException('predicate');
if(!includeUntilValue)
return <any>this.doAction(
(element:T, index:number) =>
predicate(element, index)
? EnumerableAction.Break
: EnumerableAction.Return,
null,
null // We don't know the state if it is endless or not.
);
let found:boolean = false;
return <any>this.doAction(
(element:T, index:number) =>
{
if(found)
return EnumerableAction.Break;
found = predicate(element, index);
return EnumerableAction.Return;
},
() =>
{
found = false;
},
null // We don't know the state if it is endless or not.
);
}
// Since an infinite enumerable will always end up traversing breadth first, we have this only here for regular enumerable.
traverseBreadthFirst(
childrenSelector:(element:T) => ForEachEnumerable<T> | null | undefined):LinqEnumerable<T>;
traverseBreadthFirst<TNode>(
childrenSelector:(element:T | TNode) => ForEachEnumerable<TNode> | null | undefined):LinqEnumerable<TNode>;
traverseBreadthFirst<TResult>(
childrenSelector:(element:T) => ForEachEnumerable<T> | null | undefined,
resultSelector:SelectorWithIndex<T, TResult>):LinqEnumerable<TResult>;
traverseBreadthFirst<TNode, TResult>(
childrenSelector:(element:T | TNode) => ForEachEnumerable<TNode> | null | undefined,
resultSelector:SelectorWithIndex<T, TResult>):LinqEnumerable<TResult>;
traverseBreadthFirst<TNode>(
childrenSelector:(element:T | TNode) => ForEachEnumerable<TNode> | null | undefined,
resultSelector:(
element:TNode,
nestLevel:number) => any = Functions.Identity):LinqEnumerable<any>
{
const _ = this;
let disposed = !_.throwIfDisposed();
const isEndless = _._isEndless; // Is endless is not affirmative if false.
return new LinqEnumerable<any>(
() =>
{
let enumerator:IEnumerator<any>;
let nestLevel:number = 0;
let buffer:any[], len:number;
return new EnumeratorBase<any>(
() =>
{
throwIfDisposed(disposed);
enumerator = _.getEnumerator();
nestLevel = 0;
buffer = [];
len = 0;
},
(yielder) =>
{
throwIfDisposed(disposed);
while(true)
{
if(enumerator.moveNext())
{
buffer[len++] = enumerator.current;
return yielder.yieldReturn(resultSelector(enumerator.current, nestLevel));
}
if(!len)
return yielder.yieldBreak();
let next = Enumerable
.from(buffer)
.selectMany(childrenSelector);
if(!next.any())
{
return yielder.yieldBreak();
}
else
{
nestLevel++;
buffer = [];
len = 0;
enumerator.dispose();
enumerator = next.getEnumerator();
}
}
},
() =>
{
if(enumerator) enumerator.dispose();
enumerator = NULL;
buffer.length = 0;
},
isEndless
);
},
() =>
{
disposed = true;
},
isEndless
);
}
forEach(action:ActionWithIndex<T>, max?:number):number
forEach(action:PredicateWithIndex<T>, max?:number):number
forEach(action:ActionWithIndex<T> | PredicateWithIndex<T>, max:number = Infinity):number
{
const _ = this;
_.throwIfDisposed();
if(!action)
throw new ArgumentNullException("action");
throwIfEndless(_.isEndless);
/*
// It could be just as easy to do the following:
return enumUtil.forEach(_, action, max);
// But to be more active about checking for disposal, we use this instead:
*/
// Return value of action can be anything, but if it is (===) false then the enumUtil.forEach will discontinue.
return max>0 ? using(
_.getEnumerator(), e =>
{
throwIfEndless(!isFinite(max) && e.isEndless);
let i = 0;
// It is possible that subsequently 'action' could cause the enumeration to dispose, so we have to check each time.
while(max>i && _.throwIfDisposed() && e.moveNext())
{
if(action(<T>e.current, i++)===false)
break;
}
return i;
}
) : 0;
}
// #region Conversion Methods
toArray(predicate?:PredicateWithIndex<T>):T[]
{
return predicate
? this.where(predicate).toArray()
: this.copyTo([]);
}
copyTo(target:T[], index:number = 0, count:number = Infinity):T[]
{
this.throwIfDisposed();
if(!target) throw new ArgumentNullException("target");
Integer.assertZeroOrGreater(index);
// If not exposing an action that could cause dispose, then use enumUtil.forEach utility instead.
enumUtil.forEach<T>(this, (x, i) =>
{
target[i + index] = x
}, count);
return target;
}
toLookup<TKey, TValue>(
keySelector:SelectorWithIndex<T, TKey>,
elementSelector:SelectorWithIndex<T, TValue> = <any>Functions.Identity,
compareSelector:HashSelector<TKey> = <any>Functions.Identity):Lookup<TKey, TValue>
{
const dict:Dictionary<TKey, TValue[]> = new Dictionary<TKey, TValue[]>(compareSelector);
this.forEach(
(x, i) =>
{
let key = keySelector(x, i);
let element = elementSelector(x, i);
let array = dict.getValue(key);
if(array!==VOID0) array.push(element);
else dict.addByKeyValue(key, [element]);
}
);
return new Lookup<TKey, TValue>(dict);
}
toMap<TResult>(
keySelector:SelectorWithIndex<T, string | number | symbol>,
elementSelector:SelectorWithIndex<T, TResult>):IMap<TResult>
{
const obj:IMap<TResult> = {};
this.forEach((x, i) =>
{
//@ts-ignore
obj[keySelector(x, i)] = elementSelector(x, i);
});
return obj;
}
toDictionary<TKey, TValue>(
keySelector:SelectorWithIndex<T, TKey>,
elementSelector:SelectorWithIndex<T, TValue>,
compareSelector:HashSelector<TKey> = <any>Functions.Identity):IDictionary<TKey, TValue>
{
const dict:Dictionary<TKey, TValue> = new Dictionary<TKey, TValue>(compareSelector);
this.forEach((x, i) => dict.addByKeyValue(keySelector(x, i), elementSelector(x, i)));
return dict;
}
toJoinedString(separator:string = "", selector:Selector<T, string> = <any>Functions.Identity)
{
return this
.select(selector)
.toArray()
.join(separator);
}
// #endregion
takeExceptLast(count:number = 1):this
{
const _ = this;
if(!(count>0)) // Out of bounds?
return _;
if(!isFinite(count)) // +Infinity equals skip all so return empty.
return <any> Enumerable.empty<T>();
Integer.assert(count, "count");
const c = count;
return <any> new LinqEnumerable<T>(
() =>
{
let enumerator:IEnumerator<T>;
let q:Queue<T>;
return new EnumeratorBase<T>(
() =>
{
enumerator = _.getEnumerator();
q = new Queue<T>();
},
(yielder) =>
{
while(enumerator.moveNext())
{
// Add the next one to the queue.
q.enqueue(<T>enumerator.current);
// Did we reach our quota?
if(q.count>c)
// Okay then, start returning results.
return yielder.yieldReturn(q.dequeue());
}
return false;
},
() =>
{
if(enumerator) enumerator.dispose();
enumerator = NULL;
if(q) q.dispose();
q = NULL;
}
);
}
);
}
skipToLast(count:number):this
{
if(!(count>0)) // Out of bounds? Empty.
return <any> Enumerable.empty<T>();
const _ = this;
if(!isFinite(count)) // Infinity means return all.
return _;
Integer.assert(count, "count");
// This sets up the query so nothing is done until move next is called.
return <any> _.reverse()
.take(count)
.reverse();
}
// To help with type guarding.
select<TResult>(selector:SelectorWithIndex<T, TResult>):LinqEnumerable<TResult>
{
return <LinqEnumerable<TResult>>super.select(selector);
}
map<TResult>(selector:SelectorWithIndex<T, TResult>):LinqEnumerable<TResult>
{
return <LinqEnumerable<TResult>>super.select(selector);
}
selectMany<TResult>(
collectionSelector:SelectorWithIndex<T, ForEachEnumerable<TResult> | null | undefined>):LinqEnumerable<TResult>;
selectMany<TElement, TResult>(
collectionSelector:SelectorWithIndex<T, ForEachEnumerable<TElement> | null | undefined>,
resultSelector:(collection:T, element:TElement) => TResult):LinqEnumerable<TResult>;
selectMany<TResult>(
collectionSelector:SelectorWithIndex<T, ForEachEnumerable<any> | null | undefined>,
resultSelector?:(collection:T, element:any) => TResult):LinqEnumerable<TResult>
{
return this._selectMany(collectionSelector, resultSelector);
}
choose():LinqEnumerable<T>;
choose<TResult>(selector:SelectorWithIndex<T, TResult>):LinqEnumerable<TResult>
choose(selector:SelectorWithIndex<T, any> = Functions.Identity):LinqEnumerable<any>
{
return this._filterSelected(selector, isNotNullOrUndefined);
}
reverse():this
{
const _ = this;
let disposed = !_.throwIfDisposed();
throwIfEndless(_._isEndless); // Cannot reverse an endless collection...
return <any> new LinqEnumerable<T>(
() =>
{
let buffer:T[];
let index:number = 0;
return new EnumeratorBase<T>(
() =>
{
throwIfDisposed(disposed);
_.throwIfDisposed();
buffer = _.toArray();
index = buffer.length;
},
(yielder) => !!index && yielder.yieldReturn(buffer[--index]),
() =>
{
buffer.length = 0;
}
);
},
() =>
{
disposed = true;
}
);
}
shuffle():this
{
const _ = this;
let disposed = !_.throwIfDisposed();
throwIfEndless(_._isEndless); // Cannot shuffle an endless collection...
return <any> new LinqEnumerable<T>(
() =>
{
let buffer:T[];
let capacity:number;
let len:number;
return new EnumeratorBase<T>(
() =>
{
throwIfDisposed(disposed);
buffer = _.toArray();
capacity = len = buffer.length;
},
(yielder) =>
{
// Avoid using major array operations like .slice();
if(!len)
return yielder.yieldBreak();
let selectedIndex = Random.integer(len);
let selectedValue = buffer[selectedIndex];
buffer[selectedIndex] = buffer[--len]; // Take the last one and put it here.
buffer[len] = NULL; // clear possible reference.
if(len%32==0) // Shrink?
buffer.length = len;
return yielder.yieldReturn(selectedValue);
},
() =>
{
buffer.length = 0;
}
);
},
() =>
{
disposed = true;
}
);
}
count(predicate?:PredicateWithIndex<T>):number
{
let count:number = 0;
this.forEach(
predicate
? (x, i) =>
{
if(predicate(x, i)) ++count;
}
: () =>
{
++count;
}
);
return count;
}
// Akin to '.every' on an array.
all(predicate:PredicateWithIndex<T>):boolean
{
if(!predicate)
throw new ArgumentNullException("predicate");
let result = true;
this.forEach((x, i) =>
{
if(!predicate(x, i))
{
result = false;
return false; // break
}
});
return result;
}
// 'every' has been added here for parity/compatibility with an array.
every(predicate:PredicateWithIndex<T>):boolean
{
return this.all(predicate);
}
// Akin to '.some' on an array.
any(predicate?:PredicateWithIndex<T>):boolean
{
if(!predicate)
return super.any();
let result = false;
// Splitting the forEach up this way reduces iterative processing.
// forEach handles the generation and disposal of the enumerator.
this.forEach(
(x, i) =>
{
result = predicate(x, i); // false = not found and therefore it should continue. true = found and break;
return !result;
});
return result;
}
// 'some' has been added here for parity/compatibility with an array.
some(predicate?:PredicateWithIndex<T>):boolean
{
return this.any(predicate);
}
contains(value:T, compareSelector?:Selector<T, any>):boolean
{
if(compareSelector)
{
const s = compareSelector(value);
return this.any(v => areEqualValues(compareSelector(v), s));
}
return this.any(v => areEqualValues(v, value));
}
// Originally has an overload for a predicate,
// but that's a bad idea since this could be an enumeration of functions and therefore fail the intent.
// Better to chain a where statement first to be more explicit.
indexOf(value:T, compareSelector?:SelectorWithIndex<T, any>):number
{
let found:number = -1;
this.forEach(
compareSelector
? (element:T, i:number) =>
{
if(areEqualValues(compareSelector(element, i), compareSelector(value, i), true))
{
found = i;
return false;
}
}
: (element:T, i:number) =>
{
// Why? Because NaN doesn't equal NaN. :P
if(areEqualValues(element, value, true))
{
found = i;
return false;
}
});
return found;
}
lastIndexOf(value:T, compareSelector?:SelectorWithIndex<T, any>):number
{
let result:number = -1;
this.forEach(
compareSelector
? (element:T, i:number) =>
{
if(areEqualValues(compareSelector(element, i), compareSelector(value, i), true)) result
= i;
}
: (element:T, i:number) =>
{
if(areEqualValues(element, value, true)) result = i;
});
return result;
}
intersect(
second:ForEachEnumerable<T>,
compareSelector?:HashSelector<T>):this
{
const _ = this;
_.throwIfDisposed();
if(!second)
throw new ArgumentNullException("second");
const isEndless = _.isEndless;
return <any> new LinqEnumerable<T>(
() =>
{
let enumerator:IEnumerator<T>;
let keys:Dictionary<T, boolean>;
let outs:Dictionary<T, boolean>;
return new EnumeratorBase<T>(
() =>
{
throwIfDisposed(!second);
enumerator = _.getEnumerator();
keys = new Dictionary<T, boolean>(compareSelector);
outs = new Dictionary<T, boolean>(compareSelector);
enumUtil.forEach(second, key =>
{
keys.addByKeyValue(key, true);
});
},
(yielder) =>
{
while(enumerator.moveNext())
{
let current = <T>enumerator.current;
if(!outs.containsKey(current) && keys.containsKey(current))
{
outs.addByKeyValue(current, true);
return yielder.yieldReturn(current);
}
}
return yielder.yieldBreak();
},
() =>
{
if(enumerator) enumerator.dispose();
if(keys) enumerator.dispose();
if(outs) enumerator.dispose();
enumerator = NULL;
keys = NULL;
outs = NULL;
},
isEndless
);
},
() =>
{
second = NULL;
},
isEndless
);
}
sequenceEqual(
second:ForEachEnumerable<T>,
equalityComparer:EqualityComparison<T> = areEqualValues):boolean
{
this.throwIfDisposed();
return using(
this.getEnumerator(),
e1 => using(
enumUtil.from(second),
e2 =>
{
// if both are endless, this will never evaluate.
throwIfEndless(e1.isEndless && e2.isEndless);
while(e1.moveNext())
{
if(!e2.moveNext() || !equalityComparer(<T>e1.current, <T>e2.current))
return false;
}
return !e2.moveNext();
}
)
);
}
//isEquivalent(second:ForEachEnumerable<T>,
// equalityComparer:EqualityComparison<T> = valuesAreEqual):boolean
//{
// return this
// .orderBy(keySelector)
// .sequenceEqual(Enumerable.from(second).orderBy(keySelector))
//}
// #endregion
ofType<TType>(type:{ new (...params:any[]):TType }):LinqEnumerable<TType>;
ofType<TType>(type:any):LinqEnumerable<TType>
{
this.throwIfDisposed();
return <LinqEnumerable<TType>>super.ofType(type);
}
// #region Ordering Methods
orderBy<TKey extends Comparable>(keySelector:Selector<T, TKey> = <any>Functions.Identity):IOrderedEnumerable<T>
{
this.throwIfDisposed();
return new OrderedEnumerable<T, TKey>(this, keySelector, Order.Ascending);
}
orderUsing(comparison:Comparison<T>):IOrderedEnumerable<T>
{
this.throwIfDisposed();
return new OrderedEnumerable<T, any>(this, null, Order.Ascending, null, comparison);
}
orderUsingReversed(comparison:Comparison<T>):IOrderedEnumerable<T>
{
this.throwIfDisposed();
return new OrderedEnumerable<T, any>(this, null, Order.Descending, null, comparison);
}
orderByDescending<TKey extends Comparable>(keySelector:Selector<T, TKey> = <any>Functions.Identity):IOrderedEnumerable<T>
{
this.throwIfDisposed();
return new OrderedEnumerable<T, TKey>(this, keySelector, Order.Descending);
}
/*
weightedSample(weightSelector) {
weightSelector = Utils.createLambda(weightSelector);
var source = this;
return new LinqEnumerable<T>(() => {
var sortedByBound;
var totalWeight = 0;
return new EnumeratorBase<T>(
() => {
sortedByBound = source
.choose(function (x) {
var weight = weightSelector(x);
if (weight <= 0) return null; // ignore 0
totalWeight += weight;
return { value: x, bound: totalWeight }
})
.toArray();
},
() => {
if (sortedByBound.length > 0) {
var draw = (Math.random() * totalWeight) + 1;
var lower = -1;
var upper = sortedByBound.length;
while (upper - lower > 1) {
var index = ((lower + upper) / 2);
if (sortedByBound[index].bound >= draw) {
upper = index;
}
else {
lower = index;
}
}
return (<any>this).yieldReturn(sortedByBound[upper].value);
}
return (<any>this).yieldBreak();
},
Functions.Blank);
});
}
*/
// #endregion
buffer(size:number):LinqEnumerable<T[]>
{
return <LinqEnumerable<T[]>>super.buffer(size);
}
// #region Grouping Methods
// Originally contained a result selector (not common use), but this could be done simply by a select statement after.
groupBy<TKey>(keySelector:SelectorWithIndex<T, TKey>):LinqEnumerable<Grouping<TKey, T>>;
groupBy<TKey>(
keySelector:SelectorWithIndex<T, TKey>,
elementSelector:SelectorWithIndex<T, T>,
compareSelector?:HashSelector<TKey>):LinqEnumerable<Grouping<TKey, T>>;
groupBy<TKey, TElement>(
keySelector:SelectorWithIndex<T, TKey>,
elementSelector:SelectorWithIndex<T, TElement>,
compareSelector?:HashSelector<TKey>):LinqEnumerable<Grouping<TKey, TElement>>
groupBy<TKey, TElement>(
keySelector:SelectorWithIndex<T, TKey> | Selector<T, TKey>,
elementSelector?:SelectorWithIndex<T, TElement> | Selector<T, TElement>,
compareSelector?:HashSelector<TKey>):LinqEnumerable<Grouping<TKey, TElement>>
{
if(!elementSelector) elementSelector = <any>Functions.Identity; // Allow for 'null' and not just undefined.
return new LinqEnumerable<Grouping<TKey, TElement>>(
() => this
.toLookup(keySelector, elementSelector, compareSelector)
.getEnumerator()
);
}
partitionBy<TKey>(keySelector:Selector<T, TKey>):LinqEnumerable<Grouping<TKey, T>>;
partitionBy<TKey, TElement>(
keySelector:Selector<T, TKey>,
elementSelector?:Selector<T, TElement>,
resultSelector?:(key:TKey, element:TElement[]) => Grouping<TKey, TElement>,
compareSelector?:Selector<TKey, any>):LinqEnumerable<Grouping<TKey, TElement>>;
partitionBy<TKey, TElement>(
keySelector:Selector<T, TKey>,
elementSelector?:Selector<T, TElement>,
resultSelector:(key:TKey, element:TElement[]) => Grouping<TKey, TElement>
= (key:TKey, elements:TElement[]) => new Grouping<TKey, TElement>(key, elements),
compareSelector:Selector<TKey, any>
= <any>Functions.Identity):LinqEnumerable<Grouping<TKey, T>> | LinqEnumerable<Grouping<TKey, TElement>>
{
const _ = this;
if(!elementSelector) elementSelector = <any>Functions.Identity; // Allow for 'null' and not just undefined.
return new LinqEnumerable<Grouping<TKey, TElement>>(
() =>
{
let enumerator:IEnumerator<T>;
let key:TKey;
let compareKey:any;
let group:TElement[] | null;
let len:number;
return new EnumeratorBase<Grouping<TKey, TElement>>(
() =>
{
throwIfDisposed(!elementSelector);
enumerator = _.getEnumerator();
if(enumerator.moveNext())
{
let v = <T>enumerator.current;
key = keySelector(v);
compareKey = compareSelector(key);
group = [elementSelector!(v)];
len = 1;
}
else
group = null;
},
(yielder) =>
{
throwIfDisposed(!elementSelector);
if(!group)
return yielder.yieldBreak();
let hasNext:boolean, c:T;
while((hasNext = enumerator.moveNext()))
{
c = <T>enumerator.current;
if(areEqualValues(compareKey, compareSelector(keySelector(c))))
group[len++] = elementSelector!(c);
else
break;
}
let result:Grouping<TKey, TElement>
= resultSelector(key, group);
if(hasNext)
{
c = <T>enumerator.current;
key = keySelector(c);
compareKey = compareSelector(key);
group = [elementSelector!(c)];
len = 1;
}
else
{
group = null;
}
return yielder.yieldReturn(result);
},
() =>
{
if(enumerator) enumerator.dispose();
enumerator = NULL;
group = null;
}
);
},
() =>
{
elementSelector = NULL;
}
);
}
// #endregion
// #region Aggregate Methods
flatten<TFlat>():LinqEnumerable<TFlat>
flatten():LinqEnumerable<any>
flatten():LinqEnumerable<any>
{
return <any>super.flatten();
}
pairwise<TSelect>(
selector:(
previous:T, current:T,
index:number) => TSelect):LinqEnumerable<TSelect>
{
return <any>super.pairwise(selector);
}
aggregate(
reduction:(previous:T, current:T, index?:number) => T):T | undefined;
aggregate<U>(
reduction:(previous:U, current:T, index?:number) => U,
initialValue:U):U;
aggregate<U>(
reduction:(previous:U, current:T, index?:number) => U,
initialValue?:U):U | undefined
{
if(initialValue==VOID0)
{
this.forEach((value, i) =>
{
initialValue = i
? reduction(initialValue!, value, i)
: <any>value
});
} else {
this.forEach((value, i) =>
{
initialValue = reduction(initialValue!, value, i)
});
}
return initialValue;
}
reduce<T>(
reduction:(previous:T, current:T, index?:number) => T):T | undefined;
reduce<U>(
reduction:(previous:U, current:T, index?:number) => U,
initialValue:U):U;
/**
* Provided as an analog for array.reduce. Simply a shortcut for aggregate.
* @param reduction
* @param initialValue
*/
reduce<U>(
reduction:(previous:U, current:T, index?:number) => U,
initialValue?:U):U | undefined
{
//@ts-ignore
return this.aggregate(reduction, initialValue);
}
average(selector:SelectorWithIndex<T, number> = Type.numberOrNaN):number
{
let count = 0;
const sum = this.sum((e, i) =>
{
count++;
return selector(e, i);
});
return (isNaN(sum) || !count)
? NaN
: (sum/count);
}
// If using numbers, it may be useful to call .takeUntil(v=>v==Infinity,true) before calling max. See static versions for numbers.
max():T | undefined
{
return this.aggregate(Functions.Greater);
}
min():T | undefined
{
return this.aggregate(Functions.Lesser);
}
maxBy(keySelector:Selector<T, Primitive> = <any>Functions.Identity):T | undefined
{
return this.aggregate((a:T, b:T) => (keySelector(a)>keySelector(b)) ? a : b);
}
minBy(keySelector:Selector<T, Primitive> = <any>Functions.Identity):T | undefined
{
return this.aggregate((a:T, b:T) => (keySelector(a)<keySelector(b)) ? a : b);
}
// Addition... Only works with numerical enumerations.
sum(selector:SelectorWithIndex<T, number> = Type.numberOrNaN):number
{
let sum = 0;
// This allows for infinity math that doesn't destroy the other values.
let sumInfinite = 0; // Needs more investigation since we are really trying to retain signs.
this.forEach(
(x, i) =>
{
let value = selector(x, i);
if(isNaN(value))
{
sum = NaN;
return false;
}
if(isFinite(value))
sum += value;
else
sumInfinite +=
value>0 ? (+1) : (-1);
}
);
return isNaN(sum) ? NaN : (sumInfinite ? (sumInfinite*Infinity) : sum);
}
// Multiplication...
product(selector:SelectorWithIndex<T, number> = Type.numberOrNaN):number
{
let result = 1, exists:boolean = false;
this.forEach(
(x, i) =>
{
exists = true;
let value = selector(x, i);
if(isNaN(value))
{
result = NaN;
return false;
}
if(value==0)
{
result = 0; // Multiplying by zero will always end in zero.
return false;
}
// Multiplication can never recover from infinity and simply must retain signs.
// You could cancel out infinity with 1/infinity but no available representation exists.
result *= value;
}
);
return (exists && isNaN(result)) ? NaN : result;
}
/**
* Takes the first number and divides it by all following.
* @param selector
* @returns {number}
*/
quotient(selector:SelectorWithIndex<T, number> = Type.numberOrNaN):number
{
let count = 0;
let result:number = NaN;
this.forEach(
(x, i) =>
{
let value = selector(x, i);
count++;
if(count===1)
{
result = value;
}
else
{
if(isNaN(value) || value===0 || !isFinite(value))
{
result = NaN;
return false;
}
result /= value;
}
}
);
if(count===1)
result = NaN;
return result;
}
// #endregion
// #region Single Value Return...
last():T
{
const _ = this;
_.throwIfDisposed();
let value:T | undefined = VOID0;
let found:boolean = false;
_.forEach(
x =>
{
found = true;
value = x;
}
);
if(!found) throw new Error("last:No element satisfies the condition.");
return <any>value;
}
lastOrDefault():T | undefined
lastOrDefault(defaultValue:T):T
lastOrDefault(defaultValue?:T):T | undefined
{
const _ = this;
_.throwIfDisposed();
let value:T | undefined = VOID0;
let found:boolean = false;
_.forEach(
x =>
{
found = true;
value = x;
}
);
return (!found) ? defaultValue : value;
}
// #endregion
memoize():LinqEnumerable<T>
{
let source = new LazyList(this);
return <this>(new LinqEnumerable(() => source.getEnumerator(), () =>
{
source.dispose();
source = <any>null
}, this.isEndless));
}
throwWhenEmpty():NotEmptyEnumerable<T>
{
return <any>this.doAction(RETURN, null, this.isEndless, count =>
{
if(!count) throw "Collection is empty.";
});
}
}
export interface NotEmptyEnumerable<T> extends LinqEnumerable<T>
{
aggregate(
reduction:(previous:T, current:T, index?:number) => T):T;
reduce(
reduction:(previous:T, current:T, index?:number) => T):T;
max():T
min():T
maxBy(keySelector?:Selector<T, Primitive>):T
minBy(keySelector?:Selector<T, Primitive>):T
}
// Provided for type guarding.
export class FiniteEnumerable<T>
extends LinqEnumerable<T>
{
constructor(
enumeratorFactory:() => IEnumerator<T>,
finalizer?:Closure)
{
super(enumeratorFactory, finalizer, false);
// @ts-ignore
this._disposableObjectName = "FiniteEnumerable";
}
}
export interface IOrderedEnumerable<T> extends FiniteEnumerable<T>
{
thenBy(keySelector:(value:T) => any):IOrderedEnumerable<T>;
thenByDescending(keySelector:(value:T) => any):IOrderedEnumerable<T>;
thenUsing(comparison:Comparison<T>):IOrderedEnumerable<T>;
thenUsingReversed(comparison:Comparison<T>):IOrderedEnumerable<T>;
}
export class ArrayEnumerable<T>
extends FiniteEnumerable<T>
{
private _source:ArrayLike<T>;
constructor(source:ArrayLike<T>)
{
super(() =>
{
_.throwIfDisposed();
return new ArrayEnumerator<T>(() =>
{
_.throwIfDisposed("The underlying ArrayEnumerable was disposed.", "ArrayEnumerator");
return _._source; // Should never be null, but ArrayEnumerable if not disposed simply treats null as empty array.
});
});
const _ = this;
// @ts-ignore
this._disposableObjectName = "ArrayEnumerable";
this._source = source;
}
protected _onDispose():void
{
super._onDispose();
this._source = NULL;
}
get source():ArrayLike<T>
{
return this._source;
}
toArray():T[]
{
const _ = this;
_.throwIfDisposed();
return enumUtil.toArray(_._source);
}
asEnumerable():this
{
const _ = this;
_.throwIfDisposed();
return <any> new ArrayEnumerable<T>(this._source);
}
// Optimize forEach so that subsequent usage is optimized.
forEach(action:ActionWithIndex<T>, max?:number):number
forEach(action:PredicateWithIndex<T>, max?:number):number
forEach(action:ActionWithIndex<T> | PredicateWithIndex<T>, max:number = Infinity):number
{
const _ = this;
_.throwIfDisposed();
return enumUtil.forEach(_._source, action, max);
}
// These methods should ALWAYS check for array length before attempting anything.
any(predicate?:PredicateWithIndex<T>):boolean
{
const _ = this;
_.throwIfDisposed();
const source = _._source;
let len = source.length;
return !!len && (!predicate || super.any(predicate));
}
count(predicate?:PredicateWithIndex<T>):number
{
const _ = this;
_.throwIfDisposed();
const source = _._source, len = source.length;
return len && (predicate ? super.count(predicate) : len);
}
elementAtOrDefault(index:number):T | undefined
elementAtOrDefault(index:number, defaultValue:T):T
elementAtOrDefault(index:number, defaultValue?:T):T | undefined
{
const _ = this;
_.throwIfDisposed();
Integer.assertZeroOrGreater(index, 'index');
const source = _._source;
return index<source.length
? source[index]
: defaultValue;
}
last():T
{
const _ = this;
_.throwIfDisposed();
const source = _._source, len = source.length;
return (len)
? source[len - 1]
: super.last();
}
lastOrDefault():T | undefined
lastOrDefault(defaultValue:T):T
lastOrDefault(defaultValue?:T):T | undefined
{
const _ = this;
_.throwIfDisposed();
const source = _._source, len = source.length;
return len
? source[len - 1]
: defaultValue;
}
skip(count:number):this
{
const _ = this;
_.throwIfDisposed();
if(!(count>0))
return _;
return <any> new LinqEnumerable<T>(
() => new ArrayEnumerator<T>(() => _._source, count)
);
}
takeExceptLast(count:number = 1):this
{
const _ = this;
_.throwIfDisposed();
return <any> _.take(_._source.length - count);
}
skipToLast(count:number):this
{
const _ = this;
_.throwIfDisposed();
if(!(count>0))
return <any> Enumerable.empty<T>();
if(!isFinite(count))
return _;
const len = _._source
? _._source.length
: 0;
return <any> _.skip(len - count);
}
reverse():this
{
const _ = this;
let disposed = !_.throwIfDisposed();
return <any> new LinqEnumerable<T>(
() =>
{
_.throwIfDisposed();
return new IndexEnumerator<T>(
() =>
{
let s = _._source;
throwIfDisposed(disposed || !s);
return {
source: s,
pointer: (s.length - 1),
length: s.length,
step: -1
};
}
)
},
() =>
{
disposed = true;
}
);
}
memoize():this
{
return this.asEnumerable();
}
sequenceEqual(
second:ForEachEnumerable<T>,
equalityComparer:EqualityComparison<T> = areEqualValues):boolean
{
if(Type.isArrayLike(second))
return Arrays.areEqual(this.source, second, true, equalityComparer);
// noinspection SuspiciousInstanceOfGuard
if(second instanceof ArrayEnumerable)
return second.sequenceEqual(this.source, equalityComparer);
return super.sequenceEqual(second, equalityComparer);
}
toJoinedString(separator:string = "", selector:Selector<T, string> = <any>Functions.Identity)
{
const s = this._source;
return !selector && (s) instanceof (Array)
? (<Array<T>>s).join(separator)
: super.toJoinedString(separator, selector);
}
}
export class Grouping<TKey, TElement>
extends ArrayEnumerable<TElement>
{
constructor(private _groupKey:TKey, elements:TElement[])
{
super(elements);
// @ts-ignore
this._disposableObjectName = "Grouping";
}
get key():TKey
{
return this._groupKey;
}
}
export class Lookup<TKey, TElement>
{
constructor(private _dictionary:IDictionary<TKey, TElement[]>)
{
}
get count():number
{
return this._dictionary.count;
}
get(key:TKey):TElement[] | null
{
return this._dictionary.getValue(key) || null;
}
contains(key:TKey):boolean
{
return this._dictionary.containsKey(key);
}
getEnumerator():IEnumerator<Grouping<TKey, TElement>>
{
const _ = this;
let enumerator:IEnumerator<IKeyValuePair<TKey, TElement[]>>;
return new EnumeratorBase<Grouping<TKey, TElement>>(
() =>
{
enumerator = _._dictionary.getEnumerator();
},
(yielder) =>
{
if(!enumerator.moveNext())
return false;
let current = <IKeyValuePair<TKey, TElement[]>>enumerator.current;
return yielder.yieldReturn(new Grouping<TKey, TElement>(current.key, current.value));
},
() =>
{
if(enumerator) enumerator.dispose();
enumerator = NULL;
}
);
}
}
export class OrderedEnumerable<T, TOrderBy extends Comparable>
extends FiniteEnumerable<T>
{
constructor(
private source:IEnumerable<T>,
public keySelector:Selector<T, TOrderBy> | null,
public order:Order,
public parent?:OrderedEnumerable<T, any> | null,
public comparer:Comparison<T> = compareValues)
{
super(NULL);
throwIfEndless(source && source.isEndless);
// @ts-ignore
this._disposableObjectName = "OrderedEnumerable";
}
private createOrderedEnumerable(
keySelector:Selector<T, TOrderBy>,
order:Order):IOrderedEnumerable<T>
{
this.throwIfDisposed();
return new OrderedEnumerable<T, TOrderBy>(this.source, keySelector, order, this);
}
thenBy(keySelector:(value:T) => TOrderBy):IOrderedEnumerable<T>
{
return this.createOrderedEnumerable(keySelector, Order.Ascending);
}
thenUsing(comparison:Comparison<T>):IOrderedEnumerable<T>
{
return new OrderedEnumerable<T, any>(this.source, null, Order.Ascending, this, comparison);
}
thenByDescending(keySelector:(value:T) => TOrderBy):IOrderedEnumerable<T>
{
return this.createOrderedEnumerable(keySelector, Order.Descending);
}
thenUsingReversed(comparison:Comparison<T>):IOrderedEnumerable<T>
{
return new OrderedEnumerable<T, any>(this.source, null, Order.Descending, this, comparison);
}
getEnumerator():EnumeratorBase<T>
{
const _ = this;
_.throwIfDisposed();
let buffer:T[];
let indexes:number[];
let index:number = 0;
return new EnumeratorBase<T>(
() =>
{
_.throwIfDisposed();
index = 0;
buffer = Enumerable.toArray(_.source);
indexes = createSortContext(_)
.generateSortedIndexes(buffer);
},
(yielder) =>
{
_.throwIfDisposed();
return (index<indexes.length)
? yielder.yieldReturn(buffer[indexes[index++]])
: false;
},
() =>
{
if(buffer)
buffer.length = 0;
buffer = NULL;
if(indexes)
indexes.length = 0;
indexes = NULL;
},
false
);
}
protected _onDispose():void
{
const _:this = this;
super._onDispose();
_.source = NULL;
_.keySelector = NULL;
_.order = NULL;
_.parent = NULL;
}
}
// A private static helper for the weave function.
function nextEnumerator<T>(queue:Queue<IEnumerator<T>>, e:IEnumerator<T>):IEnumerator<T> | null
{
if(e)
{
if(e.moveNext())
{
queue.enqueue(e);
}
else
{
if(e) e.dispose();
return null;
}
}
return e;
}
/**
* Recursively builds a SortContext chain.
* @param orderedEnumerable
* @param currentContext
* @returns {any}
*/
function createSortContext<T, TOrderBy extends Comparable>(
orderedEnumerable:OrderedEnumerable<T, TOrderBy>,
currentContext:IComparer<T> | null = null):KeySortedContext<T, TOrderBy>
{
const context = new KeySortedContext<T, TOrderBy>(
currentContext,
orderedEnumerable.keySelector,
orderedEnumerable.order,
orderedEnumerable.comparer);
if(orderedEnumerable.parent)
return createSortContext(orderedEnumerable.parent, context);
return context;
}
// #region Helper Functions...
// This allows for the use of a boolean instead of calling this.throwIfDisposed()
// since there is a strong chance of introducing a circular reference.
function throwIfDisposed(disposed:true):true
//noinspection JSUnusedLocalSymbols
function throwIfDisposed(disposed:false):never
//noinspection JSUnusedLocalSymbols
function throwIfDisposed(disposed:boolean):true | never
//noinspection JSUnusedLocalSymbols
function throwIfDisposed(disposed:boolean):true | never
{
if(disposed) throw new ObjectDisposedException("Enumerable");
return true;
}
// #endregion
export function Enumerable<T>(
source:InfiniteValueFactory<T>):InfiniteLinqEnumerable<T>
export function Enumerable<T>(
source:ForEachEnumerable<T>,
...additional:Array<ForEachEnumerable<T>>):LinqEnumerable<T>
export function Enumerable<T>(
source:ForEachEnumerable<T> | InfiniteValueFactory<T>,
...additional:Array<ForEachEnumerable<T>>):LinqEnumerable<T>
{
return enumerableFrom(source, additional);
}
function enumerableFrom<T>(
source:ForEachEnumerable<T> | InfiniteValueFactory<T>,
additional?:Array<ForEachEnumerable<T>>):LinqEnumerable<T>
{
let e = Enumerable.fromAny<T>(<any>source);
if(!e) throw new UnsupportedEnumerableException();
return (additional && additional.length)
? <any>e.merge(additional)
: <any>e;
}
export module Enumerable
{
/**
* Universal method for converting a primitive enumerables into a LINQ enabled ones.
*
* Is not limited to TypeScript usages.
*/
export function from<T>(source:InfiniteValueFactory<T>):InfiniteLinqEnumerable<T>
export function from<T>(
source:ForEachEnumerable<T>,
...additional:Array<ForEachEnumerable<T>>):LinqEnumerable<T>
export function from<T>(
source:ForEachEnumerable<T> | InfiniteValueFactory<T>,
...additional:Array<ForEachEnumerable<T>>):LinqEnumerable<T>
{
return enumerableFrom(source, additional);
}
export function fromAny<T>(
source:InfiniteValueFactory<T>):InfiniteLinqEnumerable<T>
export function fromAny<T>(
source:ForEachEnumerable<T>):LinqEnumerable<T>
export function fromAny(
source:any):LinqEnumerable<any> | undefined
export function fromAny<T>(
source:ForEachEnumerable<T>,
defaultEnumerable:LinqEnumerable<T>):LinqEnumerable<T>
export function fromAny<T>(
source:any,
defaultEnumerable?:LinqEnumerable<T>):LinqEnumerable<T> | InfiniteLinqEnumerable<T> | undefined
{
if(Type.isObject(source) || Type.isString(source))
{
if(source instanceof InfiniteLinqEnumerable)
return source;
if(Type.isArrayLike<T>(source))
return new ArrayEnumerable<T>(source);
if(isEnumerable<T>(source))
return new LinqEnumerable<T>(
() => source.getEnumerator(),
null, source.isEndless);
if(isEnumerator<T>(source))
return new LinqEnumerable<T>(
() => source, null, source.isEndless);
if(isIterator<T>(source))
return fromAny(new IteratorEnumerator(source));
}
else if(Type.isFunction(source))
{
return new InfiniteLinqEnumerable<T>(
() => new InfiniteEnumerator<T>(source));
}
return defaultEnumerable;
}
export function fromThese<T>(sources:ForEachEnumerable<T>[]):LinqEnumerable<T>
{
switch(sources ? sources.length : 0)
{
case 0:
return empty<T>();
case 1:
// Allow for validation and throwing...
return enumerableFrom<T>(sources[0]);
default:
return empty<T>().merge(sources);
}
}
export function fromOrEmpty<T>(source:ForEachEnumerable<T>):LinqEnumerable<T>
{
return fromAny(source) || empty<T>();
}
/**
* Static helper for converting enumerables to an array.
* @param source
* @returns {any}
*/
export function toArray<T>(source:ForEachEnumerable<T>):T[]
{
// noinspection SuspiciousInstanceOfGuard
if(source instanceof LinqEnumerable)
return source.toArray();
return enumUtil.toArray(source);
}
export function _choice<T>(values:T[]):InfiniteLinqEnumerable<T>
{
return new InfiniteLinqEnumerable<T>(
() => new EnumeratorBase<T>(
null,
(yielder) =>
{
throwIfDisposed(!values);
return yielder.yieldReturn(Random.select.one(values));
},
true // Is endless!
),
() =>
{
values.length = 0;
values = NULL;
}
);
}
export function choice<T>(values:ArrayLike<T>):InfiniteLinqEnumerable<T>
{
let len = values && values.length;
// We could return empty if no length, but that would break the typing and produce unexpected results.
// Enforcing that there must be at least 1 choice is key.
if(!len || !isFinite(len))
throw new ArgumentOutOfRangeException('length', length);
return _choice(copy(values));
}
export function chooseFrom<T>(arg:T, ...args:T[]):InfiniteLinqEnumerable<T>
export function chooseFrom<T>(...args:T[]):InfiniteLinqEnumerable<T>
{
// We could return empty if no length, but that would break the typing and produce unexpected results.
// Enforcing that there must be at least 1 choice is key.
if(!args.length)
throw new ArgumentOutOfRangeException('length', length);
return _choice(args);
}
function _cycle<T>(values:T[]):InfiniteLinqEnumerable<T>
{
return new InfiniteLinqEnumerable<T>(
() =>
{
let index:number = 0;
return new EnumeratorBase<T>(
() =>
{
index = 0;
}, // Reinitialize the value just in case the enumerator is restarted.
(yielder) =>
{
throwIfDisposed(!values);
if(index>=values.length) index = 0;
return yielder.yieldReturn(values[index++]);
},
true // Is endless!
);
},
() =>
{
values.length = 0;
values = NULL;
}
);
}
export function cycle<T>(values:ArrayLike<T>):InfiniteLinqEnumerable<T>
{
let len = values && values.length;
// We could return empty if no length, but that would break the typing and produce unexpected results.
// Enforcing that there must be at least 1 choice is key.
if(!len || !isFinite(len))
throw new ArgumentOutOfRangeException('length', length);
// Make a copy to avoid modifying the collection as we go.
return _cycle(copy(values));
}
export function cycleThrough<T>(arg:T, ...args:T[]):InfiniteLinqEnumerable<T>
export function cycleThrough<T>(...args:T[]):InfiniteLinqEnumerable<T>
{
// We could return empty if no length, but that would break the typing and produce unexpected results.
// Enforcing that there must be at least 1 choice is key.
if(!args.length)
throw new ArgumentOutOfRangeException('length', length);
return _cycle(args);
}
export function empty<T>():FiniteEnumerable<T>
{
// Could be single export function instance, but for safety, we'll make a new one.
return new FiniteEnumerable<T>(getEmptyEnumerator);
}
export function repeat<T>(element:T):InfiniteLinqEnumerable<T>;
export function repeat<T>(element:T, count:number):FiniteEnumerable<T>;
export function repeat<T>(element:T, count:number = Infinity):LinqEnumerable<T>
{
if(!(count>0))
return Enumerable.empty<T>();
return isFinite(count) && Integer.assert(count, "count")
? new FiniteEnumerable<T>(
() =>
{
let c:number = count;
let index:number = 0;
return new EnumeratorBase<T>(
() => { index = 0; },
(yielder) => (index++<c) && yielder.yieldReturn(element),
null,
false
);
}
)
: new LinqEnumerable<T>(
() =>
new EnumeratorBase<T>(
null,
(yielder) => yielder.yieldReturn(element),
true // Is endless!
)
);
}
/**
* DEPRECATED This method began to not make sense in so many ways.
* @deprecated since version 4.2
* @param initializer
* @param finalizer
*/
// Note: this enumeration is endless but can be disposed/cancelled and finalized.
export function repeatWithFinalize<T>(
initializer:() => T,
finalizer:Closure):InfiniteLinqEnumerable<T>
export function repeatWithFinalize<T>(
initializer:() => T,
finalizer?:Action<T>):InfiniteLinqEnumerable<T>
export function repeatWithFinalize<T>(
initializer:() => T,
finalizer?:Action<T>):InfiniteLinqEnumerable<T>
{
if(!initializer)
throw new ArgumentNullException("initializer");
return new InfiniteLinqEnumerable<T>(
() =>
{
let element:T;
return new EnumeratorBase<T>(
() =>
{
if(initializer)
element = initializer();
},
(yielder) =>
{
return initializer
? yielder.yieldReturn(element)
: yielder.yieldBreak();
},
() =>
{
element = NULL;
if(finalizer) finalizer(element);
},
true // Is endless!
);
},
() =>
{
initializer = NULL;
finalizer = VOID0;
}
);
}
/**
* Creates an enumerable of one element.
* @param element
* @returns {FiniteEnumerable<T>}
*/
export function make<T>(element:T):FiniteEnumerable<T>
{
return repeat<T>(element, 1);
}
// start and step can be other than integer.
export function range(
start:number,
count:number,
step:number = 1):FiniteEnumerable<number>
{
if(!isFinite(start))
throw new ArgumentOutOfRangeException("start", start, "Must be a finite number.");
if(!(count>0))
return empty<number>();
if(!step)
throw new ArgumentOutOfRangeException("step", step, "Must be a valid value");
if(!isFinite(step))
throw new ArgumentOutOfRangeException("step", step, "Must be a finite number.");
Integer.assert(count, "count");
return new FiniteEnumerable<number>(
() =>
{
let value:number;
let c:number = count; // Force integer evaluation.
let index:number = 0;
return new EnumeratorBase<number>(
() =>
{
index = 0;
value = start;
},
(yielder) =>
{
let result:boolean =
index++<c
&& yielder.yieldReturn(value);
if(result && index<count)
value += step;
return result;
},
false
);
});
}
export function rangeDown(
start:number,
count:number,
step:number = 1):FiniteEnumerable<number>
{
step = Math.abs(step)* -1;
return range(start, count, step);
}
// step = -1 behaves the same as toNegativeInfinity;
export function toInfinity(
start:number = 0,
step:number = 1):InfiniteLinqEnumerable<number>
{
if(!isFinite(start))
throw new ArgumentOutOfRangeException("start", start, "Must be a finite number.");
if(!step)
throw new ArgumentOutOfRangeException("step", step, "Must be a valid value");
if(!isFinite(step))
throw new ArgumentOutOfRangeException("step", step, "Must be a finite number.");
return new InfiniteLinqEnumerable<number>(
() =>
{
let value:number;
return new EnumeratorBase<number>(
() =>
{
value = start;
},
(yielder) =>
{
let current:number = value;
value += step;
return yielder.yieldReturn(current);
},
true // Is endless!
);
}
);
}
export function toNegativeInfinity(
start:number = 0,
step:number = 1):InfiniteLinqEnumerable<number>
{
return toInfinity(start, -step);
}
export function rangeTo(
start:number,
to:number,
step:number = 1):FiniteEnumerable<number>
{
if(isNaN(to) || !isFinite(to))
throw new ArgumentOutOfRangeException("to", to, "Must be a finite number.");
if(step && !isFinite(step))
throw new ArgumentOutOfRangeException("step", step, "Must be a finite non-zero number.");
// This way we adjust for the delta from start and to so the user can say +/- step and it will work as expected.
step = Math.abs(step);
return new FiniteEnumerable<number>(
() =>
{
let value:number;
return new EnumeratorBase<number>(() => { value = start; },
start<to
? yielder =>
{
let result:boolean = value<=to && yielder.yieldReturn(value);
if(result)
value += step;
return result;
}
: yielder =>
{
let result:boolean = value>=to && yielder.yieldReturn(value);
if(result)
value -= step;
return result;
}
, false);
}
);
}
export function matches(
input:string, pattern:any,
flags:string = ""):FiniteEnumerable<RegExpExecArray>
{
if(input==null)
throw new ArgumentNullException("input");
const type = typeof input;
if(type!=Type.STRING)
throw new Error("Cannot exec RegExp matches of type '" + type + "'.");
if(pattern instanceof RegExp)
{
flags += (pattern.ignoreCase) ? "i" : "";
flags += (pattern.multiline) ? "m" : "";
pattern = pattern.source;
}
if(flags.indexOf("g")=== -1) flags += "g";
return new FiniteEnumerable<RegExpExecArray>(
() =>
{
let regex:RegExp;
return new EnumeratorBase<RegExpExecArray>(
() =>
{
regex = new RegExp(pattern, flags);
},
(yielder) =>
{
// Calling regex.exec consecutively on the same input uses the lastIndex to start the next match.
let match = regex.exec(input);
return match!=null
? yielder.yieldReturn(match)
: yielder.yieldBreak();
}
);
}
);
}
export function generate<T>(factory:() => T):InfiniteLinqEnumerable<T>;
export function generate<T>(factory:() => T, count:number):FiniteEnumerable<T>;
export function generate<T>(factory:(index:number) => T):InfiniteLinqEnumerable<T>;
export function generate<T>(factory:(index:number) => T, count:number):FiniteEnumerable<T>;
export function generate<T>(
factory:Function,
count:number = Infinity):InfiniteLinqEnumerable<T>
{
if(!factory)
throw new ArgumentNullException("factory");
if(isNaN(count) || count<=0)
return Enumerable.empty<T>();
return isFinite(count) && Integer.assert(count, "count")
? new FiniteEnumerable<T>(
() =>
{
let c:number = count;
let index:number = 0;
return new EnumeratorBase<T>(
() =>
{
index = 0;
},
(yielder) =>
{
throwIfDisposed(!factory);
let current:number = index++;
return current<c && yielder.yieldReturn(factory(current));
},
false
);
},
() =>
{
factory = NULL;
})
: new InfiniteLinqEnumerable<T>(
() =>
{
let index:number = 0;
return new EnumeratorBase<T>(
() =>
{
index = 0;
},
(yielder) =>
{
throwIfDisposed(!factory);
return yielder.yieldReturn(factory(index++));
},
true // Is endless!
);
},
() =>
{
factory = NULL;
});
}
export module random
{
export function floats(maxExclusive:number = 1):InfiniteLinqEnumerable<number>
{
return generate(Random.generate(maxExclusive));
}
export function integers(boundary:number, inclusive?:boolean):InfiniteLinqEnumerable<number>
{
return generate(Random.generate.integers(boundary, inclusive));
}
}
export function unfold<T>(
seed:T,
valueFactory:SelectorWithIndex<T, T>,
skipSeed:Boolean = false):InfiniteLinqEnumerable<T>
{
if(!valueFactory)
throw new ArgumentNullException("factory");
return new InfiniteLinqEnumerable<T>(
() =>
{
let index:number = 0;
let value:T;
let isFirst:boolean;
return new EnumeratorBase<T>(
() =>
{
index = 0;
value = seed;
isFirst = !skipSeed;
},
(yielder) =>
{
throwIfDisposed(!valueFactory);
let i = index++;
if(isFirst)
isFirst = false;
else
value = valueFactory(value, i);
return yielder.yieldReturn(value);
},
true // Is endless!
);
},
() =>
{
valueFactory = NULL;
}
);
}
export function forEach<T>(
e:ForEachEnumerable<T>,
action:ActionWithIndex<T>,
max?:number):number
export function forEach<T>(
e:ForEachEnumerable<T>,
action:PredicateWithIndex<T>,
max?:number):number
export function forEach<T>(
enumerable:ForEachEnumerable<T>,
action:ActionWithIndex<T> | PredicateWithIndex<T>,
max:number = Infinity):number
{
// Will properly dispose created enumerable.
// Will throw if enumerable is endless.
return enumUtil.forEach(enumerable, action, max);
}
export function map<T, TResult>(
enumerable:ForEachEnumerable<T>,
selector:SelectorWithIndex<T, TResult>):TResult[]
{
// Will properly dispose created enumerable.
// Will throw if enumerable is endless.
return enumUtil.map(enumerable, selector);
}
// Slightly optimized versions for numbers.
export function max(values:FiniteEnumerable<number>):number
{
const v = values
.takeUntil(v => v== +Infinity, true)
.aggregate(Functions.Greater);
return v===VOID0 ? NaN : v;
}
export function min(values:FiniteEnumerable<number>):number
{
const v = values
.takeUntil(v => v== -Infinity, true)
.aggregate(Functions.Lesser);
return v===VOID0 ? NaN : v;
}
/**
* Takes any set of collections of the same type and weaves them together.
* @param enumerables
* @returns {Enumerable<T>}
*/
export function weave<T>(
enumerables:ForEachEnumerable<ForEachEnumerable<T>>):LinqEnumerable<T>
{
if(!enumerables)
throw new ArgumentNullException('enumerables');
let disposed = false;
return new LinqEnumerable<T>(
() =>
{
let queue:Queue<IEnumerator<T>>;
let mainEnumerator:IEnumerator<ForEachEnumerable<T>> | null;
let index:number;
return new EnumeratorBase<T>(
() =>
{
throwIfDisposed(disposed);
index = 0;
queue = new Queue<IEnumerator<T>>();
mainEnumerator = enumUtil.from(enumerables);
},
(yielder) =>
{
throwIfDisposed(disposed);
let e:IEnumerator<T> | null = null;
// First pass...
if(mainEnumerator)
{
while(!e && mainEnumerator.moveNext())
{
let c = mainEnumerator.current;
e = nextEnumerator(queue, c ? enumUtil.from(c) : NULL);
}
if(!e)
mainEnumerator = null;
}
while(!e && queue.tryDequeue(value =>
{
e = nextEnumerator(queue, enumUtil.from<T>(value));
}))
{ }
return e
? yielder.yieldReturn(e.current)
: yielder.yieldBreak();
},
() =>
{
if(queue)
{
dispose.these.noCopy(queue.dump());
queue = NULL;
}
if(mainEnumerator) mainEnumerator.dispose();
mainEnumerator = null;
}
);
},
() =>
{
disposed = true;
}
);
}
}
export default Enumerable; | the_stack |
import { connectSlot, slot, defaultSlotConfig } from './../src/Slot'
import { TestChannel } from './TestChannel'
import { Transport } from './../src/Transport'
import { DEFAULT_PARAM } from './../src/Constants'
import { TransportRegistrationMessage } from './../src/Message'
const makeTestTransport = () => {
const channel = new TestChannel()
const transport = new Transport(channel)
channel.callConnected()
return { channel, transport }
}
describe('slot', () => {
it('should have a default config', () => {
const testSlot = slot()
if (!testSlot.config) {
throw new Error('testSlot should have a config')
}
expect(testSlot.config).toEqual(defaultSlotConfig)
})
it('should set config passed as argument', () => {
const config = { noBuffer: true }
const testSlot = slot(config)
if (!testSlot.config) {
throw new Error('testSlot should have a config')
}
expect(testSlot.config).toEqual(config)
})
})
describe('connectSlot', () => {
describe('without parameter', () => {
describe('trigger', () => {
it('should use default parameter', async () => {
const numberToString = connectSlot<number, string>('numberToString', [])
numberToString.on(DEFAULT_PARAM, num => `${num.toString()}`)
const res = await numberToString(56)
expect(res).toEqual('56')
})
})
describe('on', () => {
it('should use default parameter', async () => {
const numberToString = connectSlot<number, string>('numberToString', [])
numberToString.on(num => `${num.toString()}`)
const res = await numberToString(DEFAULT_PARAM, 56)
expect(res).toEqual('56')
})
})
})
describe('with no transports', () => {
it('should call a single local handler registered for a parameter', async () => {
const numberToString = connectSlot<number, string>('numberToString', [])
numberToString.on('a', num => `a${num.toString()}`)
const res = await numberToString('a', 56)
expect(res).toEqual('a56')
})
it('should call all handlers if there is more than one', async () => {
const broadcastBool = connectSlot<boolean>('broadcastBool', [])
const results: string[] = []
broadcastBool.on('a', b => { results.push(`1:${b}`) })
broadcastBool.on('a', b => { results.push(`2:${b}`) })
broadcastBool.on('a', b => { results.push(`3:${b}`) })
// Should not be called: different parameter
broadcastBool.on('b', b => { results.push(`4:${b}`) })
await broadcastBool('a', true)
expect(results).toEqual(['1:true', '2:true', '3:true'])
})
it('should allow subscribing to multiple parameters', async () => {
const broadcastBool = connectSlot<number>('broadcastBool', [])
let value = 0
broadcastBool.on('add', n => { value += n })
broadcastBool.on('remove', n => { value -= n })
await broadcastBool('add', 3)
expect(value).toEqual(3)
await broadcastBool('remove', 2)
expect(value).toEqual(1)
})
it('should allow to unregister handlers', async () => {
const broadcastBool = connectSlot<number>('broadcastBool', [])
let value = 0
const unsub = broadcastBool.on('add', n => { value += n })
broadcastBool.on('add', n => { value += n })
await broadcastBool('add', 3)
expect(value).toEqual(6) // 2 * 3
unsub()
await broadcastBool('add', 3)
expect(value).toEqual(9) // 6 + 1 * 3
})
it('should call lazy connect and disconnect with parameter', () => {
const broadcastBool = connectSlot<boolean>('broadcastBool', [])
const param = 'param'
const connect = jest.fn()
const disconnect = jest.fn()
broadcastBool.lazy(connect, disconnect)
const unsubscribe = broadcastBool.on(param, () => { })
expect(connect).toHaveBeenCalledWith(param)
expect(disconnect).not.toHaveBeenCalled()
unsubscribe()
expect(disconnect).toHaveBeenCalled()
})
})
describe('with local and remote handlers', () => {
it('should call both local handlers and remote handlers', async () => {
const { channel, transport } = makeTestTransport()
const broadcastBool = connectSlot<boolean>('broadcastBool', [transport])
let localCalled = false
broadcastBool.on(_b => { localCalled = true })
const triggerPromise = broadcastBool(true)
// Handlers should not be called until a remote handler is registered
await Promise.resolve()
expect(localCalled).toEqual(false)
channel.fakeReceive({
param: DEFAULT_PARAM,
slotName: 'broadcastBool',
type: 'handler_registered'
})
// setTimeout(0) to yield control to ts-event-bus internals,
// so that the call to handlers can be processed
await new Promise(resolve => setTimeout(resolve, 0))
// Once a remote handler is registered, both local and remote should be called
expect(localCalled).toEqual(true)
const request = channel.sendSpy.mock.calls[channel.sendSpy.mock.calls.length - 1][0]
expect(request).toMatchObject({
data: true,
param: DEFAULT_PARAM,
slotName: 'broadcastBool',
type: 'request'
})
// triggerPromise should resolve once a remote response is received
channel.fakeReceive({
data: null,
id: request.id,
param: DEFAULT_PARAM,
slotName: 'broadcastBool',
type: 'response'
})
await triggerPromise
})
describe('noBuffer', () => {
it('should call local handlers even if no remote handler is registered', async () => {
const { channel, transport } = makeTestTransport()
const broadcastBool = connectSlot<boolean>(
'broadcastBool',
[transport],
{ noBuffer: true }
)
let localCalled = false
broadcastBool.on(_b => { localCalled = true })
await broadcastBool(true)
// We should have called the trigger
expect(localCalled).toEqual(true)
const registrationMessage: TransportRegistrationMessage = {
param: DEFAULT_PARAM,
slotName: 'broadcastBool',
type: 'handler_registered'
}
channel.fakeReceive(registrationMessage)
await new Promise(resolve => setTimeout(resolve, 0))
// Remote should not have been called, as it was not registered
// at the time of the trigger.
const request = channel.sendSpy.mock.calls[0]
expect(request).toMatchObject(request)
})
})
describe('lazy', () => {
it('should call connect and disconnect', () => {
const param = 'param'
const { channel: channel1, transport: transport1 } = makeTestTransport()
const { channel: channel2, transport: transport2 } = makeTestTransport()
const broadcastBool = connectSlot<boolean>(
'broadcastBool',
[transport1, transport2]
)
const connect = jest.fn()
const disconnect = jest.fn()
broadcastBool.lazy(connect, disconnect)
// Simulate two remote connextions to the slot
channel1.fakeReceive({
type: 'handler_registered',
slotName: 'broadcastBool',
param
})
channel2.fakeReceive({
type: 'handler_registered',
slotName: 'broadcastBool',
param
})
// Connect should have been called once
expect(connect).toHaveBeenCalledWith(param)
// Disconnect should not have been called
expect(disconnect).not.toHaveBeenCalled()
// Disconnect first remote client
channel1.fakeReceive({
type: 'handler_unregistered',
slotName: 'broadcastBool',
param
})
// Disconnect should not have been called
expect(disconnect).not.toHaveBeenCalled()
// Disconnect second remote client
channel2.fakeReceive({
type: 'handler_unregistered',
slotName: 'broadcastBool',
param
})
// Disconnect should have been called once
expect(disconnect).toHaveBeenCalledWith(param)
})
it('should support multiple lazy calls', () => {
const { channel: channel1, transport: transport1 } = makeTestTransport()
const param = 'param'
const connect1 = jest.fn()
const disconnect1 = jest.fn()
const connect2 = jest.fn()
const disconnect2 = jest.fn()
const broadcastBool = connectSlot<boolean>(
'broadcastBool',
[transport1]
)
broadcastBool.lazy(connect1, disconnect1)
broadcastBool.lazy(connect2, disconnect2)
channel1.fakeReceive({
type: 'handler_registered',
slotName: 'broadcastBool',
param
})
// Connects should have been called once
expect(connect1).toHaveBeenCalledWith(param)
expect(connect2).toHaveBeenCalledWith(param)
channel1.fakeReceive({
type: 'handler_unregistered',
slotName: 'broadcastBool',
param
})
expect(disconnect1).toHaveBeenCalledWith(param)
expect(disconnect2).toHaveBeenCalledWith(param)
})
it('should call connect if transport was registered before lazy was called', () => {
const param = 'param'
const { channel: channel1, transport: transport1 } = makeTestTransport()
const broadcastBool = connectSlot<boolean>('broadcastBool', [transport1])
const connect = jest.fn()
// Register remote handler *before* calling lazy
channel1.fakeReceive({
type: 'handler_registered',
slotName: 'broadcastBool',
param
})
broadcastBool.lazy(connect, () => { })
expect(connect).toHaveBeenCalledWith(param, 0, [param])
})
})
})
}) | the_stack |
import {
Score_itf, Staff_itf, Measure_itf, Note_itf, Rest_itf, Slur_itf, Cresc_itf, Time_signature,
CLEF, ACCIDENTAL, ORDER_OF_ACCIDENTALS, NOTE_LENGTH,
note_name_to_staff_pos, get_median_staff_pos, chord_and_beam_staff, short_id, Tuplet_itf, ARTICULATION, BARLINE, BRACKET,
} from "./common"
import {CONFIG} from "./main"
const ARTICULATION_SYMBOL_LOOKUP : Record<string,number> = {
'>':ARTICULATION.ACCENT,
'^':ARTICULATION.MARCATO,
'.':ARTICULATION.STACCATO,
'-':ARTICULATION.TENUTO,
',':ARTICULATION.SPICCATO,
'?':ARTICULATION.FERMATA,
'+':ARTICULATION.TREMBLEMENT,
't':ARTICULATION.TRILL,
'o':ARTICULATION.FLAGEOLET,
'm':ARTICULATION.MORDENT,
's':ARTICULATION.TURN,
'v':ARTICULATION.UP_BOW,
'{':ARTICULATION.ARPEGGIATED
};
let ARTICULATION_SYMBOL = Object.fromEntries(Object.entries(ARTICULATION_SYMBOL_LOOKUP).map(x=>[x[1],x[0]]));
export function parse_txt(txt:string) : Score_itf{
txt = txt.replace(/[\n\r\t]/g,' ');
let swap_sp = ''/*FFFF*/ ; let swap_sp_re = new RegExp(swap_sp,'g');
let swap_qt = ''/*FFFE*/ ; let swap_qt_re = new RegExp(swap_qt,'g');
txt = txt.replace(/\\'/g,swap_qt);
txt = txt.split("'").map((x,i)=>(i%2)?x.replace(/ /g,swap_sp):x).join("'");
// console.log(txt);
txt = txt.split(';').filter((_,i)=>!(i%2)).join(' ');
let words = txt.split(' ').filter(x=>x.length).map(x=>x.replace(swap_sp_re,' ').replace(swap_qt_re,"'"));
// console.log(words);
let score : Score_itf = {
title:[],
instruments:[],
composer:[],
slurs:[],
measures:[],
crescs:[],
};
let measure : Measure_itf;
let staff : Staff_itf;
let note : Note_itf;
let rest : Rest_itf;
let slur : Slur_itf;
let cresc : Cresc_itf;
let i = 0;
let state : string[] = [];
let begin = 0;
let voice = 0;
let begin0 = 0;
let rest_hidden = false;
let tup_state : {id:string,mul:number,begin:number,dur:number,num:number,members:(Note_itf|Rest_itf)[]}[] = [];
function curr_state(s:string):boolean{
return state[state.length-1]==s;
}
function pop_short_state(){
let curr = state[state.length-1];
if (curr){
if (curr == "note" ){
state.pop();
if (note.tuplet && note.tuplet.display_duration === null){
note.tuplet.display_duration = note.duration;
// console.log(JSON.stringify(tup_state));
note.duration = Math.max(1,~~(note.duration*tup_state[tup_state.length-1].mul));
// note.duration = Math.round(note.duration*tup_state[tup_state.length-1].mul);
}
if (note.tuplet) tup_state[tup_state.length-1].members.push(note);
if (curr_state('grace') || state.includes('grace')){
// console.log(begin,note.duration);
if (!staff.grace[begin0]){
staff.grace[begin0] = {duration:0,barline:BARLINE.NONE,staves:[{
clef:staff.clef,
time_signature:[1,1],
key_signature:staff.key_signature,
notes:[],
grace:[],
rests:[],
voices:1,
beams:[],
}]};
}
staff.grace[begin0].staves[0].notes.push(note);
}else{
staff.notes.push(note);
}
measure.duration = Math.max(measure.duration,begin+note.duration);
if (!curr_state('chord')){
begin += note.duration;
}
}else if (curr == "rest"){
state.pop();
if (rest.tuplet && rest.tuplet.display_duration === null){
rest.tuplet.display_duration = rest.duration;
rest.duration = Math.max(1,~~(rest.duration*tup_state[tup_state.length-1].mul));
// rest.duration = Math.round(rest.duration*tup_state[tup_state.length-1].mul);
}
if (rest.tuplet && !rest_hidden) tup_state[tup_state.length-1].members.push(rest);
measure.duration = Math.max(measure.duration,begin+rest.duration);
begin += rest.duration;
if (!rest_hidden) staff.rests.push(rest);
}else if (curr == "title" || curr == "composer" || curr == "instruments" || curr == "tempo"){
state.pop();
}else if (curr == "slur"){
state.pop();
score.slurs.push(slur);
}else if (curr == "cresc"){
state.pop();
score.crescs.push(cresc);
}
}
}
function switch_state(s:string){
pop_short_state();
state.push(s);
}
function parse_dur(x:string):[number,boolean]{
if (x[x.length-1] == '.'){
return [96/Number(x.slice(0,-1)),true];
}else{
return [64/Number(x),false];
}
}
while (i < words.length){
let x:string = words[i];
if (x == 'end'){
pop_short_state();
if (curr_state("staff")){
compile_staff(staff);
measure.staves.push(staff);
}else if (curr_state("measure")){
// if (measure.duration){
score.measures.push(measure);
// }
}else if (curr_state("chord")){
if (state.includes('grace')){
begin += staff.grace[begin0].staves[0].notes[staff.grace[begin0].staves[0].notes.length-1].duration;
}else{
begin += staff.notes[staff.notes.length-1].duration;
}
}else if (curr_state("voice")){
voice ++;
begin = 0;
}else if (curr_state("grace")){
// console.log(JSON.stringify(staff.grace),begin);
staff.grace[begin0].duration = Math.max(staff.grace[begin0].duration,begin);
compile_staff(staff.grace[begin0].staves[0],-1);
begin = begin0;
}else if (curr_state("tuplet")){
let tup = tup_state.pop();
let sum = (tup.members[tup.members.length-1].begin-tup.begin) + tup.members[tup.members.length-1].duration;
let remain = tup.dur-sum;
for (let i = tup.members.length-1; i >= 0; i--){
if (tup.members[i].begin ==tup.members[tup.members.length-1].begin ){
tup.members[i].duration += remain;
}else{
break;
}
}
// console.log(remain,tup);
begin = tup.begin+tup.dur;
}
state.pop();
}else if (x == 'title'){
switch_state("title")
}else if (x == 'composer'){
switch_state("composer")
}else if (x == 'instruments'){
switch_state("instruments")
}else if (x == 'tempo'){
switch_state("tempo")
}else if (x == 'measure'){
switch_state("measure");
measure = {
duration: 0,
barline: BARLINE.SINGLE,
staves: [],
};
}else if (x == 'staff'){
switch_state("staff");
staff = {
clef:CLEF.TREBLE,
time_signature:[4,4],
key_signature:[0,0],
notes:[],
grace:[],
rests:[],
voices:1,
beams:[],
};
if (score.measures[score.measures.length-1]){
if (score.measures[score.measures.length-1].staves[measure.staves.length]){
let prev = score.measures[score.measures.length-1].staves[measure.staves.length];
staff.time_signature[0] = prev.time_signature[0];
staff.time_signature[1] = prev.time_signature[1];
staff.key_signature[0] = prev.key_signature[0];
staff.key_signature[1] = prev.key_signature[1];
staff.clef = prev.clef;
}
}
begin = 0;
voice = 0;
}else if (x == 'note'){
switch_state("note");
note = {
begin:null,
duration:null,
accidental:null,
modifier:false,
octave:null,
name:null,
voice:null,
staff_pos:null,
stem_dir:null,
prev_in_chord:null,
next_in_chord:null,
tuplet:null,
}
if (state[state.length-2] == 'grace' && staff.grace[begin0] && staff.grace[begin0].staves[0].notes.length){
let notes = staff.grace[begin0].staves[0].notes;
if (notes[notes.length-1]){
Object.assign(note,notes[notes.length-1]);
}
}else{
if (staff.notes[staff.notes.length-1]){
Object.assign(note,staff.notes[staff.notes.length-1]);
}
}
note.begin = begin;
note.accidental = null;
note.voice = voice;
if (note.id){
delete note.id;
}
if (note.lyric){
delete note.lyric;
}
if (note.articulation){
delete note.articulation;
}
if (note.cue){
delete note.cue;
}
if (state[state.length-2] != 'grace'){
let tup = tup_state[tup_state.length-1];
if (note.tuplet && tup){
if (note.tuplet.id != tup.id){
note.tuplet = {id:tup.id,display_duration:null,label:tup.num};
}
}else if (tup && !note.tuplet){
note.tuplet = {id:tup.id,display_duration:null,label:tup.num};
}else if (!tup && note.tuplet){
note.tuplet = null;
}
}else{
note.tuplet = null;
}
}else if (x == 'rest'){
switch_state("rest");
rest = {
begin:null,
duration:null,
voice:null,
tuplet:null,
};
rest_hidden = false;
if (staff.rests[staff.rests.length-1]){
Object.assign(rest,staff.rests[staff.rests.length-1]);
}
rest.begin = begin;
rest.voice = voice;
if (rest.cue){
delete rest.cue;
}
if (state[state.length-2] != 'grace'){
let tup = tup_state[tup_state.length-1];
if (rest.tuplet && tup){
if (rest.tuplet.id != tup.id){
rest.tuplet = {id:tup.id,display_duration:null,label:tup.num};
}
}else if (tup && !rest.tuplet){
rest.tuplet = {id:tup.id,display_duration:null,label:tup.num};
}else if (!tup && rest.tuplet){
rest.tuplet = null;
}
}else{
rest.tuplet = null;
}
}else if (x == 'chord'){
switch_state("chord");
}else if (x == 'grace'){
switch_state("grace");
begin0 = begin;
begin = 0;
}else if (x == 'tuplet'){
switch_state("tuplet");
tup_state.push({
id:short_id(),
mul:1,
begin:begin,
dur:0,
num:3,
members:[],
});
}else if (x == 'voice'){
switch_state("voice");
}else if (x == "slur"){
switch_state("slur");
slur = {
left:null,
right:null,
is_tie:false,
}
}else if (x == "tie"){
switch_state("slur");
slur = {
left:null,
right:null,
is_tie:true,
}
}else if (x == 'cresc'){
switch_state("cresc");
cresc = {
left:null,
right:null,
val_left:null,
val_right:null,
}
}else if (curr_state("measure")){
if (x.startsWith('|') || x.startsWith(':')){
if (x == '|'){
measure.barline = BARLINE.SINGLE;
}else if (x == '||'){
measure.barline = BARLINE.DOUBLE;
}else if (x == '|||'){
measure.barline = BARLINE.END;
}else if (x == '|:'){
measure.barline = BARLINE.REPEAT_BEGIN;
}else if (x == ':|'){
measure.barline = BARLINE.REPEAT_END;
}else if (x == ':|:'){
measure.barline = BARLINE.REPEAT_END_BEGIN;
}
}
}else if (curr_state("staff")){
if (x == 'G'){
staff.clef = CLEF.TREBLE;
}else if (x == 'F'){
staff.clef = CLEF.BASS;
}else if (x == 'Ca' || x == 'C'){
staff.clef = CLEF.ALTO;
}else if (x == 'Ct'){
staff.clef = CLEF.TENOR;
}else if (x == 'Cm'){
staff.clef = CLEF.MEZZO_SOPRANO;
}else if (x == 'Cs'){
staff.clef = CLEF.SOPRANO;
}else if (x == 'Cb'){
staff.clef = CLEF.BARITONE;
}else if (x == '~'){
staff.key_signature = [0,0];
}else if (x.startsWith('b')){
staff.key_signature = [ACCIDENTAL.FLAT,x.length];
}else if (x.startsWith('#')){
staff.key_signature = [ACCIDENTAL.SHARP,x.length];
}else if (x.includes('/')){
let s = x.split('/');
staff.time_signature = [Number(s[0]),Number(s[1])];
}
}else if (curr_state("note")){
if ((/^[A-Z].*/).test(x)){
note.name = x[0];
note.octave = Number(x.slice(1));
}else if (x[0] == 'd'){
let [dur,mod] = parse_dur(x.slice(1));
note.duration = dur;
note.modifier = mod;
if (note.tuplet) note.tuplet.display_duration = null;
}else if (x[0] == '$'){
note.id = x.slice(1);
}else if (x[0] == '#'){
note.accidental = ACCIDENTAL.SHARP;
}else if (x[0] == 'b'){
note.accidental = ACCIDENTAL.FLAT;
}else if (x[0] == '~'){
note.accidental = ACCIDENTAL.NATURAL;
}else if (x[0] == 'l'){
note.lyric = x.slice(1).replace(/(^')|('$)/g,'');
}else if (x[0] == 'a'){
if (ARTICULATION_SYMBOL_LOOKUP[x[1]]){
note.articulation = ARTICULATION_SYMBOL_LOOKUP[x[1]];
}else{
note.articulation = Number(x[1]);
}
if (x[2] == '|'){
note.articulation = -note.articulation;
}
}else if (x[0] == '|'){
note.cue = {position:0,data:x.slice(1).replace(/(^')|('$)/g,'')};
}else if (x[0] == '['){
note.cue = {position:-1,data:x.slice(1).replace(/(^')|('$)/g,'')};
}else if (x[0] == ']'){
note.cue = {position:1,data:x.slice(1).replace(/(^')|('$)/g,'')};
}
}else if (curr_state("rest")){
if (x[0] == 'd'){
let dur = 64/Number(x.slice(1));
rest.duration = dur;
if (rest.tuplet) rest.tuplet.display_duration = null;
}else if (x[0] == '|'){
rest.cue = {position:0,data:x.slice(1).replace(/(^')|('$)/g,'')};
}else if (x[0] == '['){
rest.cue = {position:-1,data:x.slice(1).replace(/(^')|('$)/g,'')};
}else if (x[0] == ']'){
rest.cue = {position:1,data:x.slice(1).replace(/(^')|('$)/g,'')};
}else if (x[0] == '-'){
rest_hidden = true;
}
}else if (curr_state("slur")){
if (x[0] == '$'){
if (slur.left == null){
slur.left = x.slice(1);
}else{
slur.right = x.slice(1);
}
}
}else if (curr_state("cresc")){
if (x[0] == '$'){
if (cresc.left == null){
cresc.left = x.slice(1);
}else{
cresc.right = x.slice(1);
}
}else{
if (cresc.val_left === null){
cresc.val_left = Number(x);
}else{
cresc.val_right = Number(x);
}
}
}else if (curr_state("tuplet")){
if (x[0] == 'd'){
let [a_,b_] = x.slice(1).split('/');
let a : number = parse_dur(a_)[0];
let b : number = parse_dur(b_)[0];
tup_state[tup_state.length-1].mul = a/b;
tup_state[tup_state.length-1].dur = a;
// console.log(a_,b_,a,b);
}else{
let n : number = Number(x);
tup_state[tup_state.length-1].num = n;
}
}else if (curr_state("title")){
score.title.push(x.replace(/(^')|('$)/g,''));
}else if (curr_state("composer")){
score.composer.push(x.replace(/(^')|('$)/g,''));
}else if (curr_state("instruments")){
if (x == '{'){
while (score.instruments[score.instruments.length-1] && score.instruments[score.instruments.length-1].connect_barlines.length < score.instruments[score.instruments.length-1].names.length) score.instruments[score.instruments.length-1].connect_barlines.push(false);
score.instruments.push({bracket:BRACKET.BRACE,names:[],connect_barlines:[]})
}else if (x == '['){
while (score.instruments[score.instruments.length-1] && score.instruments[score.instruments.length-1].connect_barlines.length < score.instruments[score.instruments.length-1].names.length) score.instruments[score.instruments.length-1].connect_barlines.push(false);
score.instruments.push({bracket:BRACKET.BRACKET,names:[],connect_barlines:[]})
}else if (x == '|'){
while (score.instruments[score.instruments.length-1] && score.instruments[score.instruments.length-1].connect_barlines.length < score.instruments[score.instruments.length-1].names.length) score.instruments[score.instruments.length-1].connect_barlines.push(false);
score.instruments.push({bracket:BRACKET.NONE,names:[],connect_barlines:[]})
}else if (x == '-'){
score.instruments[score.instruments.length-1].connect_barlines.push(true);
}else{
if (!score.instruments.length){
score.instruments.push({bracket:BRACKET.NONE,names:[],connect_barlines:[]})
}
let group = score.instruments[score.instruments.length-1];
if (group.connect_barlines.length < group.names.length){
group.connect_barlines.push(false);
}
group.names.push(x.replace(/(^')|('$)/g,''));
}
}else if (curr_state("tempo")){
if (!score.tempo){
score.tempo = {};
}
if (x[0] == 'd'){
let [dur,mod] = parse_dur(x.slice(1));
score.tempo.duration = dur;
score.tempo.modifier = mod;
}else if (x[0] == '='){
score.tempo.bpm = Number(x.slice(1));
}else{
score.tempo.text = x.replace(/(^')|('$)/g,'');
}
}
i++;
}
pop_short_state();
return score;
}
function compile_staff(
staff:Staff_itf, force_stem_dir:number=0
){
for (let i = 0; i < staff.notes.length; i++){
staff.voices = Math.max(staff.notes[i].voice+1,staff.voices);
}
for (let i = 0; i < staff.rests.length; i++){
staff.voices = Math.max(staff.rests[i].voice+1,staff.voices);
}
function get_beat_length(time_sig:Time_signature){
if (CONFIG.BEAM_POLICY == 0){
return 1;
}else if (CONFIG.BEAM_POLICY == 1){
return ~~(NOTE_LENGTH.WHOLE/time_sig[1]);
}else{
let beat_length = ~~(NOTE_LENGTH.WHOLE/time_sig[1]);
beat_length *= (time_sig[0]%2 || (time_sig[0] <= 2 && time_sig[1] > 2)) ? time_sig[0] : (time_sig[0]/2);
return beat_length;
}
}
let beat_length = get_beat_length(staff.time_signature);
function get_beat_idx(note:Note_itf) : number{
return ~~(note.begin/beat_length);
}
function get_notes_in_beat(beat_idx:number) : Note_itf[]{
let notes : Note_itf[] = [];
for (let m of staff.notes){
if (get_beat_idx(m) == beat_idx){
notes.push(m);
}
}
return notes;
}
function calc_stem_dir(note:Note_itf){
let notes_in_beat : Note_itf[];
if (note.duration < NOTE_LENGTH.QUARTER){
let beat_idx : number = get_beat_idx(note);
if (note.tuplet){
notes_in_beat = staff.notes.filter(x=>x.tuplet&&x.tuplet.id==note.tuplet.id);
}else{
// let s = Math.sign(note.duration-NOTE_LENGTH.QUARTER);
// notes_in_beat = get_notes_in_beat(beat_idx)//.filter(x=>Math.sign(x.duration-NOTE_LENGTH.QUARTER)==s);
notes_in_beat = get_notes_in_beat(beat_idx).filter(x=>x.duration<NOTE_LENGTH.QUARTER);
}
}else{
notes_in_beat=[];
for (let m of staff.notes){
if (m.begin == note.begin){
notes_in_beat.push(m);
}
}
}
let avg_line : number = notes_in_beat.reduce((acc:number,x:Note_itf):number=>(acc+x.staff_pos),0)/notes_in_beat.length;
if (avg_line < 4){
return 1;
}else{
return -1;
}
}
let [measure_acc, num_acc] = staff.key_signature;
let acc_names : string[] = ORDER_OF_ACCIDENTALS[measure_acc].slice(0,num_acc).split('');
let acc_history : Record<string,number> = {};
for (let i = 0; i < staff.notes.length; i++){
let note : Note_itf = staff.notes[i];
let note_bname = note.name;
let key = note_bname + '_' + note.octave;
if (note.accidental != null){
note.name = note_bname + (['b','','s'][note.accidental+1]);
acc_history[key] = note.accidental;
}else{
if (acc_history[key] === undefined){
if (acc_names.includes(note_bname)){
note.name = note_bname + (['b',null,'s'][measure_acc+1]);
acc_history[key] = measure_acc;
}else{
note.name = note_bname;
}
}else{
note.name = note_bname + ['b','','s'][acc_history[key]+1];
}
}
note.name += "_";
note.name += note.octave;
note.staff_pos = note_name_to_staff_pos(note.name,staff.clef);
}
for (let i = 0; i < staff.notes.length; i++){
let note = staff.notes[i];
let stem_dir :number;
if (staff.voices == 1){
stem_dir = force_stem_dir || calc_stem_dir(note);
}else{
stem_dir = note.voice % 2 ? 1 : -1;
}
note.stem_dir = stem_dir;
}
chord_and_beam_staff(staff,beat_length);
}
export function export_txt(score:Score_itf):string{
let o : string = "";
o += `title '${score.title.map(x=>x.replace(/'/g,"\\'")).join("' '")}'\n`;
if (score.composer){
o += `composer '${score.composer}'\n`;
}
if (score.tempo){
o += `tempo`
if (score.tempo.text){
o += ` '`+score.tempo.text.replace(/'/g,"\\'")+`'`;
}
if (score.tempo.duration){
if (score.tempo.modifier){
o += ' d'+(96/score.tempo.duration).toString()+'.';
}else{
o += ' d'+(64/score.tempo.duration).toString();
}
if (score.tempo.bpm){
o += ' ='+score.tempo.bpm;
}
}
o += '\n';
}
if (score.instruments.length){
o += 'instruments ';
for (let i = 0; i < score.instruments.length; i++){
o += ['','{','['][score.instruments[i].bracket] + ' ';
for (let j = 0; j < score.instruments[i].names.length; j++){
if (j && score.instruments[i].connect_barlines[j-1]){
o += ' - ';
}
o += `'${score.instruments[i].names[j].replace(/'/g,"\\'")}' `;
}
}
o += '\n';
}
for (let i = 0; i < score.measures.length; i++){
let measure = score.measures[i];
o += `measure`;
if (measure.barline == BARLINE.DOUBLE){
o += ` ||`;
}else if (measure.barline == BARLINE.REPEAT_BEGIN){
o += ` |:`;
}else if (measure.barline == BARLINE.REPEAT_END){
o += ` :|`;
}else if (measure.barline == BARLINE.END ){
o += ` |||`;
}else if (measure.barline == BARLINE.REPEAT_END_BEGIN){
o += ` :|:`;
}
o += `\n`;
for (let j = 0; j < measure.staves.length; j++){
let staff = measure.staves[j];
o += ` staff ${staff.clef==CLEF.TREBLE?'G':'F'} ${['b','','#'][staff.key_signature[0]+1].repeat(staff.key_signature[1])} ${staff.time_signature[0]}/${staff.time_signature[1]}\n`;
for (let k = 0; k < staff.voices; k++){
let items : [string,(Note_itf|Rest_itf|{begin:number,duration:number,[other_options: string]: any}),boolean][] = [];
for (let l = 0; l < staff.notes.length; l++){
if (staff.notes[l].voice == k){
items.push(['note',staff.notes[l],false]);
}
}
for (let l = 0; l < staff.rests.length; l++){
if (staff.rests[l].voice == k){
items.push(['rest',staff.rests[l],false]);
}
}
for (let l = 0; l < staff.grace.length; l++){
if (!staff.grace[l]){
continue;
}
let grace_item : [string,({begin:number,duration:number,[other_options: string]: any}),boolean] = ['grace',{begin:l-0.001,duration:staff.grace[l].duration,items:[]},false];
for (let m = 0; m < staff.grace[l].staves[0].notes.length; m++){
let n = staff.grace[l].staves[0].notes[m];
if (n.voice == k){
grace_item[1].items.push(['note',n,false]);
}
}
for (let m = 0; m < staff.grace[l].staves[0].rests.length; m++){
let n = staff.grace[l].staves[0].rests[m];
if (n.voice == k){
grace_item[1].items.push(['rest',n,false]);
}
}
grace_item[1].items.sort((a:{begin:number,duration:number,[other_options: string]: any},b:{begin:number,duration:number,[other_options: string]: any})=>(a[1].begin-b[1].begin));
if (grace_item[1].items.length)
items.push(grace_item);
}
items.sort((a,b)=>(a[1].begin-b[1].begin));
// console.log(items);
if (staff.voices>1) {o += ' voice\n';}
function do_items(items:[string,(Note_itf|Rest_itf|{begin:number,duration:number,[other_options: string]: any}),boolean][]){
for (let l = 0; l < items.length; l++){
let done = items[l][2];
if (done){
continue;
}
if (items[l][1].tuplet){
function count():string[]{
let begin = -1;
let real = 0;
let disp = 0;
for (let m = l; m < items.length; m++){
if (!items[m][1].tuplet || items[m][1].tuplet.id != items[l][1].tuplet.id){
break;
}
if (items[m][1].begin != begin){
begin = items[m][1].begin;
disp += items[m][1].tuplet.display_duration;
}
real = items[m][1].begin-items[l][1].begin + items[m][1].duration;
}
function to_str(n:number){
if (64/n == ~~(64/n)){
return (~~(64/n)).toString();
}else{
return (~~(96/n)).toString()+".";
}
}
let real_str : string = to_str(real);
let disp_str : string = to_str(disp);
return [real_str,disp_str];
}
let prev_tup_id : string = null;
for (let m = l-1; m>=0; m--){
let e = (items[m][1] as {tuplet:Tuplet_itf});
if (e.tuplet){
prev_tup_id = items[m][1].tuplet.id;
break;
}
}
if (!items[l-1] || prev_tup_id === null){
o += ` tuplet ${items[l][1].tuplet.label} d${count().join('/')}\n`;
}else if (prev_tup_id !== null && prev_tup_id != items[l][1].tuplet.id){
o += ` end\n tuplet ${items[l][1].tuplet.label} d${count().join('/')}\n`;
}
}else if (items[l-1] && items[l-1][1].tuplet){
let next_tup_id : string = null;
for (let m = l+1; m < items.length; m++){
let e = (items[m][1] as {tuplet:Tuplet_itf});
if (e.tuplet){
next_tup_id = items[m][1].tuplet.id;
break;
}
}
if (items[l-1][1].tuplet.id != next_tup_id){
o += ` end\n`;
}
}
if (items[l][0] == 'note'){
let e : Note_itf = (items[l][1] as Note_itf);
while (e.prev_in_chord !== null){
e = staff.notes[e.prev_in_chord];
}
let is_chord = e.next_in_chord !== null;
if (is_chord) o += ' chord\n';
do{
items.find(x=>(x[1]==e))[2] = true;
let s : string[] = ['note'];
s.push(e.name[0]+e.octave);
if (e.accidental !== null){
s.push(['b','~','#'][e.accidental+1]);
}
let dur = e.duration;
if (e.tuplet){
dur = e.tuplet.display_duration;
}
if (e.modifier){
s.push('d'+(96/dur).toString()+'.');
}else{
s.push('d'+(64/dur).toString());
}
if (e.articulation){
s.push('a'+(ARTICULATION_SYMBOL[e.articulation]??e.articulation));
}
if (e.cue){
s.push(`${['[','|',']'][e.cue.position+1]}'${e.cue.data.replace(/'/g,"\\'")}'` );
}
if (e.lyric){
s.push(`l'${e.lyric.replace(/'/g,"\\'")}'`);
}
let t = ' ';
if (is_chord) t += ' ';
t += s.join(' ');
if (e.id){
t = t.padEnd(50,' ')+' $'+e.id;
}
o += t + '\n';
e = staff.notes[e.next_in_chord];
}while(e);
if (is_chord) o += ' end\n';
}else if (items[l][0] == "rest"){
let e : Rest_itf = (items[l][1] as Rest_itf);
let dur = e.duration;
if (e.tuplet){
dur = e.tuplet.display_duration;
}
o += ` rest d${64/dur}`;
if (e.cue){
o += ` ${['[','|',']'][e.cue.position+1]}'${e.cue.data.replace(/'/g,"\\'")}'`;
}
o += '\n';
}else if (items[l][0] == "grace"){
o += ` grace\n`;
do_items((items[l][1] as {begin:number,duration:number,[other_options: string]: any}).items);
o += ` end\n`;
}else{}
}
if (items[items.length-1] && items[items.length-1][1].tuplet){
o += ` end\n`;
}
}
do_items(items);
if (staff.voices>1) {o += ' end\n';}
}
o += ` end\n`;
}
o += `end\n`;
}
for (let i = 0; i < score.slurs.length; i++){
let slur = score.slurs[i];
if (slur.is_tie){
o += `tie $${slur.left} $${slur.right}\n`;
}else{
o += `slur $${slur.left} $${slur.right}\n`;
}
}
for (let i = 0; i < score.crescs.length; i++){
let cresc = score.crescs[i];
o += `cresc ${cresc.val_left} ${cresc.val_right} $${cresc.left} $${cresc.right}\n`;
}
return o;
} | the_stack |
import {
JavaArrayList,
JavaBigDecimal,
JavaBigInteger,
JavaBoolean,
JavaByte,
JavaDate,
JavaDouble,
JavaFloat,
JavaHashMap,
JavaHashSet,
JavaInteger,
JavaLong,
JavaOptional,
JavaShort,
JavaString
} from "../../java-wrappers";
import { MarshallerProvider } from "../MarshallerProvider";
import { JavaBigIntegerMarshaller } from "../marshallers/JavaBigIntegerMarshaller";
import { JavaHashMapMarshaller } from "../marshallers/JavaHashMapMarshaller";
import { JavaByteMarshaller } from "../marshallers/JavaByteMarshaller";
import { JavaBigDecimalMarshaller } from "../marshallers/JavaBigDecimalMarshaller";
import { JavaStringMarshaller } from "../marshallers/JavaStringMarshaller";
import { JavaBooleanMarshaller } from "../marshallers/JavaBooleanMarshaller";
import { JavaShortMarshaller } from "../marshallers/JavaShortMarshaller";
import { JavaLongMarshaller } from "../marshallers/JavaLongMarshaller";
import { JavaIntegerMarshaller } from "../marshallers/JavaIntegerMarshaller";
import { JavaFloatMarshaller } from "../marshallers/JavaFloatMarshaller";
import { JavaDoubleMarshaller } from "../marshallers/JavaDoubleMarshaller";
import { DefaultMarshaller } from "../marshallers/DefaultMarshaller";
import { JavaWrapperUtils } from "../../java-wrappers/JavaWrapperUtils";
import { JavaType } from "../../java-wrappers/JavaType";
import * as JavaCollectionMarshaller from "../marshallers/JavaCollectionMarshaller";
import { JavaDateMarshaller } from "../marshallers/JavaDateMarshaller";
import { JavaOptionalMarshaller } from "../marshallers/JavaOptionalMarshaller";
describe("getForObject", () => {
test("without initialize, should return Error", () => {
const input = new JavaString("foo");
expect(() => MarshallerProvider.getForObject(input)).toThrowError();
});
describe("properly initialized", () => {
beforeEach(() => {
MarshallerProvider.initialize();
});
afterEach(() => {
// force reinitialization
(MarshallerProvider as any).initialized = false;
});
test("with JavaByte instance, should return JavaByteMarshaller instance", () => {
const input = new JavaByte("1");
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaByteMarshaller());
});
test("with JavaDouble instance, should return JavaDoubleMarshaller instance", () => {
const input = new JavaDouble("1.1");
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaDoubleMarshaller());
});
test("with JavaFloat instance, should return JavaFloatMarshaller instance", () => {
const input = new JavaFloat("1.1");
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaFloatMarshaller());
});
test("with JavaInteger instance, should return JavaIntegerMarshaller instance", () => {
const input = new JavaInteger("1");
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaIntegerMarshaller());
});
test("with JavaLong instance, should return JavaLongMarshaller instance", () => {
const input = new JavaLong("1");
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaLongMarshaller());
});
test("with JavaShort instance, should return JavaShortMarshaller instance", () => {
const input = new JavaShort("1");
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaShortMarshaller());
});
test("with JavaBoolean instance, should return JavaBooleanMarshaller instance", () => {
const input = new JavaBoolean(false);
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaBooleanMarshaller());
});
test("with JavaString instance, should return JavaStringMarshaller instance", () => {
const input = new JavaString("foo");
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaStringMarshaller());
});
test("with JavaDate instance, should return JavaDateMarshaller instance", () => {
const input = new JavaDate(new Date());
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaDateMarshaller());
});
test("with JavaBigDecimal instance, should return JavaBigDecimalMarshaller instance", () => {
const input = new JavaBigDecimal("1.1");
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaBigDecimalMarshaller());
});
test("with JavaBigInteger instance, should return JavaBigIntegerMarshaller instance", () => {
const input = new JavaBigInteger("1");
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaBigIntegerMarshaller());
});
test("with JavaArrayList instance, should return JavaArrayListMarshaller instance", () => {
const input = new JavaArrayList([1, 2, 3]);
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaCollectionMarshaller.JavaArrayListMarshaller());
});
test("with JavaHashSet instance, should return JavaHashSetMarshaller instance", () => {
const input = new JavaHashSet(new Set([1, 2, 3]));
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaCollectionMarshaller.JavaHashSetMarshaller());
});
test("with JavaHashMap instance, should return JavaHashMapMarshaller instance", () => {
const input = new JavaHashMap(new Map([["foo", "bar"]]));
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaHashMapMarshaller());
});
test("with JavaOptional instance, should return JavaOptionalMarshaller instance", () => {
const input = new JavaOptional<string>("str");
expect(MarshallerProvider.getForObject(input)).toEqual(new JavaOptionalMarshaller());
});
test("with input without fqcn, should return default marshaller", () => {
const input = {
foo: "bar",
bar: "foo"
};
expect(MarshallerProvider.getForObject(input)).toEqual(new DefaultMarshaller());
});
test("with input with a custom fqcn, should return default marshaller", () => {
const fqcn = "com.myapp.custom.pojo";
const input = {
_fqcn: fqcn,
foo: "bar",
bar: "foo"
};
// it is a custom pojo (i.e. no pre-defined marshaller)
expect(JavaWrapperUtils.isJavaType(fqcn)).toBeFalsy();
expect(MarshallerProvider.getForObject(input)).toEqual(new DefaultMarshaller());
});
test("with a Java type without marshaller, should throw error", () => {
// the only scenario it throws errors is when a Java-wrapped type has no marshaller associated.
// little trick to mess with internal state
const marshallers = (MarshallerProvider as any).marshallersByJavaType;
marshallers.delete(JavaType.STRING);
const input = new JavaString("foo");
expect(() => MarshallerProvider.getForObject(input)).toThrowError();
});
});
});
describe("getForFqcn", () => {
test("without initialize, should return Error", () => {
expect(() => MarshallerProvider.getForFqcn("anything")).toThrowError();
});
describe("properly initialized", () => {
beforeEach(() => {
MarshallerProvider.initialize();
});
afterEach(() => {
// force reinitialization
(MarshallerProvider as any).initialized = false;
});
test("with Java's Byte fqcn, should return JavaByteMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.BYTE)).toEqual(new JavaByteMarshaller());
});
test("with Java's Double fqcn, should return JavaDoubleMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.DOUBLE)).toEqual(new JavaDoubleMarshaller());
});
test("with Java's Float fqcn, should return JavaFloatMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.FLOAT)).toEqual(new JavaFloatMarshaller());
});
test("with Java's Integer fqcn, should return JavaIntegerMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.INTEGER)).toEqual(new JavaIntegerMarshaller());
});
test("with Java's Long fqcn, should return JavaLongMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.LONG)).toEqual(new JavaLongMarshaller());
});
test("with Java's Short fqcn, should return JavaShortMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.SHORT)).toEqual(new JavaShortMarshaller());
});
test("with Java's Boolean fqcn, should return JavaBooleanMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.BOOLEAN)).toEqual(new JavaBooleanMarshaller());
});
test("with Java's String fqcn, should return JavaStringMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.STRING)).toEqual(new JavaStringMarshaller());
});
test("with Java's Date fqcn, should return JavaDateMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.DATE)).toEqual(new JavaDateMarshaller());
});
test("with Java's BigDecimal fqcn, should return JavaBigDecimalMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.BIG_DECIMAL)).toEqual(new JavaBigDecimalMarshaller());
});
test("with Java's BigInteger fqcn, should return JavaBigIntegerMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.BIG_INTEGER)).toEqual(new JavaBigIntegerMarshaller());
});
test("with Java's ArrayList fqcn, should return JavaArrayListMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.ARRAY_LIST)).toEqual(
new JavaCollectionMarshaller.JavaArrayListMarshaller()
);
});
test("with Java's HashSet fqcn, should return JavaHashSetMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.HASH_SET)).toEqual(
new JavaCollectionMarshaller.JavaHashSetMarshaller()
);
});
test("with Java's HashMap fqcn, should return JavaHashMapMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.HASH_MAP)).toEqual(new JavaHashMapMarshaller());
});
test("with Java's Optional fqcn, should return JavaOptionalMarshaller instance", () => {
expect(MarshallerProvider.getForFqcn(JavaType.OPTIONAL)).toEqual(new JavaOptionalMarshaller());
});
test("with null fqcn, should return default marshaller", () => {
const fqcn = null as any;
expect(MarshallerProvider.getForFqcn(fqcn)).toEqual(new DefaultMarshaller());
});
test("with undefined fqcn, should return default marshaller", () => {
const fqcn = undefined as any;
expect(MarshallerProvider.getForFqcn(fqcn)).toEqual(new DefaultMarshaller());
});
test("with empty string, should return default marshaller", () => {
const fqcn = "";
expect(MarshallerProvider.getForFqcn(fqcn)).toEqual(new DefaultMarshaller());
});
test("with custom fqcn, should return default marshaller", () => {
const fqcn = "com.myapp.custom.pojo";
// it is a custom pojo (i.e. no pre-defined marshaller)
expect(JavaWrapperUtils.isJavaType(fqcn)).toBeFalsy();
expect(MarshallerProvider.getForFqcn(fqcn)).toEqual(new DefaultMarshaller());
});
});
});
describe("consistency validations", () => {
beforeEach(() => {
(MarshallerProvider as any).initialized = false; // force reinitialization
MarshallerProvider.initialize();
});
test("all Java types should have a marshaller associated", () => {
// this test is important to avoid developers to forget to add marshallers to new JavaTypes
const marshallers = (MarshallerProvider as any).marshallersByJavaType;
Object.keys(JavaType)
.map((k: keyof typeof JavaType) => JavaType[k])
.forEach(javaType => expect(marshallers.get(javaType)).toBeDefined());
});
});
describe("getForEnum", () => {
beforeEach(() => {
MarshallerProvider.initialize();
});
afterEach(() => {
// force reinitialization
(MarshallerProvider as any).initialized = false;
});
test("should return exactly the same enum marshaller object", () => {
const enumMarshaller = (MarshallerProvider as any).marshallersByJavaType.get(JavaType.ENUM);
expect(MarshallerProvider.getForEnum()).toStrictEqual(enumMarshaller);
});
}); | the_stack |
import { ready as cryptoReady, tcrypto } from '@tanker/crypto';
import { expect } from '@tanker/test-utils';
import makeUint8Array from '../../__tests__/makeUint8Array';
import {
serializeUserGroupCreationV1,
unserializeUserGroupCreationV1,
serializeUserGroupCreationV2,
unserializeUserGroupCreationV2,
serializeUserGroupCreationV3,
unserializeUserGroupCreationV3,
serializeUserGroupAdditionV1,
unserializeUserGroupAdditionV1,
serializeUserGroupAdditionV2,
unserializeUserGroupAdditionV2,
serializeUserGroupAdditionV3,
unserializeUserGroupAdditionV3,
serializeUserGroupRemoval,
unserializeUserGroupRemoval,
UserGroupCreationRecordV1,
} from '../Serialize';
describe('groups blocks', () => {
before(() => cryptoReady);
it('correctly serializes/deserializes a UserGroupCreation test vector', async () => {
const userGroupCreation = {
public_signature_key: makeUint8Array('pub sig key', tcrypto.SIGNATURE_PUBLIC_KEY_SIZE),
public_encryption_key: makeUint8Array('pub enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_signature_key: makeUint8Array('encrypted priv sig key', tcrypto.SEALED_SIGNATURE_PRIVATE_KEY_SIZE),
encrypted_group_private_encryption_keys_for_users: [
{
public_user_encryption_key: makeUint8Array('pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
{
public_user_encryption_key: makeUint8Array('second pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('second encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
],
self_signature: makeUint8Array('self signature', tcrypto.SIGNATURE_SIZE),
};
const payload = new Uint8Array([
// public signature key
0x70, 0x75, 0x62, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public encryption key
0x70, 0x75, 0x62, 0x20,
0x65, 0x6e, 0x63, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
// encrypted group private signature key
0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65,
0x64, 0x20, 0x70, 0x72, 0x69, 0x76, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b,
0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// varint
0x02,
// public user encryption key 1
0x70, 0x75, 0x62,
0x20, 0x75, 0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 1
0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74,
0x65, 0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69,
0x76, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00,
// public user encryption key 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x70, 0x75, 0x62, 0x20,
0x75, 0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 2
0x73, 0x65, 0x63,
0x6f, 0x6e, 0x64, 0x20, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65,
0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69, 0x76,
0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
// self signature
0x73, 0x65, 0x6c, 0x66, 0x20, 0x73, 0x69,
0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
expect(serializeUserGroupCreationV1(userGroupCreation)).to.deep.equal(payload);
expect(unserializeUserGroupCreationV1(payload)).to.deep.equal(userGroupCreation);
});
it('correctly serializes/deserializes a UserGroupCreationV2 test vector', async () => {
const userGroupCreation = {
public_signature_key: makeUint8Array('pub sig key', tcrypto.SIGNATURE_PUBLIC_KEY_SIZE),
public_encryption_key: makeUint8Array('pub enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_signature_key: makeUint8Array('encrypted priv sig key', tcrypto.SEALED_SIGNATURE_PRIVATE_KEY_SIZE),
encrypted_group_private_encryption_keys_for_users: [
{
user_id: makeUint8Array('user id', tcrypto.HASH_SIZE),
public_user_encryption_key: makeUint8Array('pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
{
user_id: makeUint8Array('second user id', tcrypto.HASH_SIZE),
public_user_encryption_key: makeUint8Array('second pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('second encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
],
encrypted_group_private_encryption_keys_for_provisional_users: [
{
app_provisional_user_public_signature_key: makeUint8Array('app provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_signature_key: makeUint8Array('tanker provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('provisional user encrypted group priv key', tcrypto.TWO_TIMES_SEALED_KEY_SIZE),
},
{
app_provisional_user_public_signature_key: makeUint8Array('2nd app provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_signature_key: makeUint8Array('2nd tanker provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('2nd provisional user encrypted group priv key', tcrypto.TWO_TIMES_SEALED_KEY_SIZE),
},
],
self_signature: makeUint8Array('self signature', tcrypto.SIGNATURE_SIZE),
};
const payload = new Uint8Array([
// public signature key
0x70, 0x75, 0x62, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public encryption key
0x70, 0x75, 0x62, 0x20, 0x65, 0x6e, 0x63, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private signature key
0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x20, 0x70, 0x72,
0x69, 0x76, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
// Varint
0x02,
// user ID 1
0x75, 0x73, 0x65, 0x72, 0x20, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public user encryption key 1
0x70, 0x75, 0x62, 0x20, 0x75, 0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 1
0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72,
0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// user ID 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x75, 0x73, 0x65, 0x72, 0x20,
0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public user encryption key 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x70, 0x75, 0x62, 0x20, 0x75,
0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x65, 0x6e, 0x63, 0x72, 0x79,
0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x70,
0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Varint
0x02,
// public app signature key 1
0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public tanker signature key 1
0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69,
0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b,
0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 1
0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20,
0x75, 0x73, 0x65, 0x72, 0x20, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74,
0x65, 0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69,
0x76, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// provisional user app signature key 2
0x32, 0x6e, 0x64, 0x20, 0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76,
0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20,
0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
// provisional user tanker signature key 2
0x32, 0x6e, 0x64, 0x20, 0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70,
0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73,
0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00,
// encrypted group private encryption key 2
0x32, 0x6e, 0x64, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x61, 0x6c, 0x20, 0x75, 0x73, 0x65, 0x72, 0x20, 0x65, 0x6e, 0x63,
0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70,
0x20, 0x70, 0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// self signature
0x73, 0x65, 0x6c, 0x66, 0x20, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75,
0x72, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
]);
expect(serializeUserGroupCreationV2(userGroupCreation)).to.deep.equal(payload);
expect(unserializeUserGroupCreationV2(payload)).to.deep.equal(userGroupCreation);
});
it('correctly serializes/deserializes a UserGroupCreationV3 test vector', async () => {
const userGroupCreation = {
public_signature_key: makeUint8Array('pub sig key', tcrypto.SIGNATURE_PUBLIC_KEY_SIZE),
public_encryption_key: makeUint8Array('pub enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_signature_key: makeUint8Array('encrypted priv sig key', tcrypto.SEALED_SIGNATURE_PRIVATE_KEY_SIZE),
encrypted_group_private_encryption_keys_for_users: [
{
user_id: makeUint8Array('user id', tcrypto.HASH_SIZE),
public_user_encryption_key: makeUint8Array('pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
{
user_id: makeUint8Array('second user id', tcrypto.HASH_SIZE),
public_user_encryption_key: makeUint8Array('second pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('second encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
],
encrypted_group_private_encryption_keys_for_provisional_users: [
{
app_provisional_user_public_signature_key: makeUint8Array('app provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_signature_key: makeUint8Array('tanker provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
app_provisional_user_public_encryption_key: makeUint8Array('app provisional enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_encryption_key: makeUint8Array('tanker provisional enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('provisional user encrypted group priv key', tcrypto.TWO_TIMES_SEALED_KEY_SIZE),
},
{
app_provisional_user_public_signature_key: makeUint8Array('2nd app provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_signature_key: makeUint8Array('2nd tanker provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
app_provisional_user_public_encryption_key: makeUint8Array('2nd app provisional enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_encryption_key: makeUint8Array('2nd tanker provisional enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('2nd provisional user encrypted group priv key', tcrypto.TWO_TIMES_SEALED_KEY_SIZE),
},
],
self_signature: makeUint8Array('self signature', tcrypto.SIGNATURE_SIZE),
};
const payload = new Uint8Array([
// public signature key
0x70, 0x75, 0x62, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public encryption key
0x70, 0x75, 0x62, 0x20, 0x65, 0x6e, 0x63, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private signature key
0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x20, 0x70, 0x72,
0x69, 0x76, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
// Varint
0x02,
// user ID 1
0x75, 0x73, 0x65, 0x72, 0x20, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public user encryption key 1
0x70, 0x75, 0x62, 0x20, 0x75, 0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 1
0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72,
0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// user ID 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x75, 0x73, 0x65, 0x72, 0x20,
0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public user encryption key 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x70, 0x75, 0x62, 0x20, 0x75,
0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x65, 0x6e, 0x63, 0x72, 0x79,
0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x70,
0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Varint
0x02,
// public app signature key 1
0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public tanker signature key 1
0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69,
0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b,
0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public app encryption key 1
0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x61, 0x6c, 0x20, 0x65, 0x6e, 0x63, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public tanker encryption key 1
0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69,
0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x65, 0x6e, 0x63, 0x20, 0x6b,
0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 1
0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20,
0x75, 0x73, 0x65, 0x72, 0x20, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74,
0x65, 0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69,
0x76, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// provisional user app signature key 2
0x32, 0x6e, 0x64, 0x20, 0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76,
0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20,
0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
// provisional user tanker signature key 2
0x32, 0x6e, 0x64, 0x20, 0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70,
0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73,
0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00,
// public app encryption key 2
0x32, 0x6e, 0x64, 0x20, 0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76,
0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x65, 0x6e, 0x63, 0x20,
0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
// public tanker encryption key 2
0x32, 0x6e, 0x64, 0x20, 0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70,
0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x65,
0x6e, 0x63, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00,
// encrypted group private encryption key 2
0x32, 0x6e, 0x64, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x61, 0x6c, 0x20, 0x75, 0x73, 0x65, 0x72, 0x20, 0x65, 0x6e, 0x63,
0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70,
0x20, 0x70, 0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// self signature
0x73, 0x65, 0x6c, 0x66, 0x20, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75,
0x72, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
]);
expect(serializeUserGroupCreationV3(userGroupCreation)).to.deep.equal(payload);
expect(unserializeUserGroupCreationV3(payload)).to.deep.equal(userGroupCreation);
});
describe('serializing invalid group creation block', () => {
let userGroupCreation: UserGroupCreationRecordV1;
beforeEach(() => {
userGroupCreation = {
public_signature_key: new Uint8Array(tcrypto.SIGNATURE_PUBLIC_KEY_SIZE),
public_encryption_key: new Uint8Array(tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_signature_key: new Uint8Array(tcrypto.SEALED_SIGNATURE_PRIVATE_KEY_SIZE),
encrypted_group_private_encryption_keys_for_users: [
{
public_user_encryption_key: new Uint8Array(tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: new Uint8Array(tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
],
self_signature: new Uint8Array(tcrypto.SIGNATURE_SIZE),
};
});
it('should serialize a valid a user group creation block', async () => {
expect(() => serializeUserGroupCreationV1(userGroupCreation)).not.to.throw();
});
const fields: Array<keyof UserGroupCreationRecordV1> = [
'public_signature_key',
'public_encryption_key',
'encrypted_group_private_signature_key',
'self_signature',
];
fields.forEach(field => {
it(`should throw when serializing a user group creation block with invalid ${field}`, async () => {
// @ts-expect-error fields only contains Uint8Array fields from UserGroupCreationRecordV1
userGroupCreation[field] = new Uint8Array(0);
expect(() => serializeUserGroupCreationV1(userGroupCreation)).to.throw();
});
});
it('should throw when serializing a user group creation block with invalid public_user_encryption_key', async () => {
userGroupCreation.encrypted_group_private_encryption_keys_for_users[0]!.public_user_encryption_key = new Uint8Array(0);
expect(() => serializeUserGroupCreationV1(userGroupCreation)).to.throw();
});
it('should throw when serializing a user group creation block with invalid encrypted_group_private_encryption_key', async () => {
userGroupCreation.encrypted_group_private_encryption_keys_for_users[0]!.encrypted_group_private_encryption_key = new Uint8Array(0);
expect(() => serializeUserGroupCreationV1(userGroupCreation)).to.throw();
});
});
it('correctly deserializes a UserGroupAdditionV1 test vector', async () => {
const userGroupAdd = {
group_id: makeUint8Array('group id', tcrypto.HASH_SIZE),
previous_group_block: makeUint8Array('prev group block', tcrypto.HASH_SIZE),
encrypted_group_private_encryption_keys_for_users: [
{
public_user_encryption_key: makeUint8Array('pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
{
public_user_encryption_key: makeUint8Array('second pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('second encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
],
self_signature_with_current_key: makeUint8Array('self signature', tcrypto.SIGNATURE_SIZE),
};
const payload = new Uint8Array([
// group id
0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// previous group block
0x70, 0x72, 0x65, 0x76, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x62,
0x6c, 0x6f, 0x63, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// varint
0x02,
// public user encryption key 1
0x70, 0x75, 0x62, 0x20, 0x75, 0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 1
0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72,
0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public user encryption key 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x70, 0x75, 0x62, 0x20, 0x75,
0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x65, 0x6e, 0x63, 0x72, 0x79,
0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x70,
0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// self signature
0x73, 0x65, 0x6c, 0x66, 0x20, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75,
0x72, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
]);
expect(serializeUserGroupAdditionV1(userGroupAdd)).to.deep.equal(payload);
expect(unserializeUserGroupAdditionV1(payload)).to.deep.equal(userGroupAdd);
});
it('correctly deserializes a UserGroupAdditionV2 test vector', async () => {
const userGroupAdd = {
group_id: makeUint8Array('group id', tcrypto.HASH_SIZE),
previous_group_block: makeUint8Array('prev group block', tcrypto.HASH_SIZE),
encrypted_group_private_encryption_keys_for_users: [
{
user_id: makeUint8Array('user id', tcrypto.HASH_SIZE),
public_user_encryption_key: makeUint8Array('pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
{
user_id: makeUint8Array('second user id', tcrypto.HASH_SIZE),
public_user_encryption_key: makeUint8Array('second pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('second encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
],
encrypted_group_private_encryption_keys_for_provisional_users: [
{
app_provisional_user_public_signature_key: makeUint8Array('app provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_signature_key: makeUint8Array('tanker provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('provisional encrypted group priv key', tcrypto.TWO_TIMES_SEALED_KEY_SIZE),
},
{
app_provisional_user_public_signature_key: makeUint8Array('2nd app provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_signature_key: makeUint8Array('2nd tanker provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('2nd provisional encrypted group priv key', tcrypto.TWO_TIMES_SEALED_KEY_SIZE),
},
],
self_signature_with_current_key: makeUint8Array('self signature', tcrypto.SIGNATURE_SIZE),
};
const payload = new Uint8Array([
// group id
0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// previous group block
0x70, 0x72, 0x65, 0x76, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x62,
0x6c, 0x6f, 0x63, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Varint
0x02,
// User ID 1
0x75, 0x73, 0x65, 0x72, 0x20, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public user encryption key 1
0x70, 0x75, 0x62, 0x20, 0x75, 0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 1
0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72,
0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// User ID 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x75, 0x73, 0x65, 0x72, 0x20,
0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public user encryption key 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x70, 0x75, 0x62, 0x20, 0x75,
0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x65, 0x6e, 0x63, 0x72, 0x79,
0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x70,
0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Varint
0x02,
// public app signature key 1
0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public tanker signature key 1
0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69,
0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b,
0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 1
0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20,
0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72,
0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// provisional user app signature key 2
0x32, 0x6e, 0x64, 0x20, 0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76,
0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20,
0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
// provisional user tanker signature key 2
0x32, 0x6e, 0x64, 0x20, 0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70,
0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73,
0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00,
// encrypted group private encryption key 2
0x32, 0x6e, 0x64, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x61, 0x6c, 0x20, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65,
0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69, 0x76,
0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// self signature
0x73, 0x65, 0x6c, 0x66, 0x20, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75,
0x72, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
]);
expect(serializeUserGroupAdditionV2(userGroupAdd)).to.deep.equal(payload);
expect(unserializeUserGroupAdditionV2(payload)).to.deep.equal(userGroupAdd);
});
it('correctly deserializes a UserGroupAdditionV3 test vector', async () => {
const userGroupAdd = {
group_id: makeUint8Array('group id', tcrypto.HASH_SIZE),
previous_group_block: makeUint8Array('prev group block', tcrypto.HASH_SIZE),
encrypted_group_private_encryption_keys_for_users: [
{
user_id: makeUint8Array('user id', tcrypto.HASH_SIZE),
public_user_encryption_key: makeUint8Array('pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
{
user_id: makeUint8Array('second user id', tcrypto.HASH_SIZE),
public_user_encryption_key: makeUint8Array('second pub user key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('second encrypted group priv key', tcrypto.SEALED_ENCRYPTION_PRIVATE_KEY_SIZE),
},
],
encrypted_group_private_encryption_keys_for_provisional_users: [
{
app_provisional_user_public_signature_key: makeUint8Array('app provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_signature_key: makeUint8Array('tanker provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
app_provisional_user_public_encryption_key: makeUint8Array('app provisional enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_encryption_key: makeUint8Array('tanker provisional enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('provisional encrypted group priv key', tcrypto.TWO_TIMES_SEALED_KEY_SIZE),
},
{
app_provisional_user_public_signature_key: makeUint8Array('2nd app provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_signature_key: makeUint8Array('2nd tanker provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
app_provisional_user_public_encryption_key: makeUint8Array('2nd app provisional enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_provisional_user_public_encryption_key: makeUint8Array('2nd tanker provisional enc key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
encrypted_group_private_encryption_key: makeUint8Array('2nd provisional encrypted group priv key', tcrypto.TWO_TIMES_SEALED_KEY_SIZE),
},
],
self_signature_with_current_key: makeUint8Array('self signature', tcrypto.SIGNATURE_SIZE),
};
const payload = new Uint8Array([
// group id
0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// previous group block
0x70, 0x72, 0x65, 0x76, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x62,
0x6c, 0x6f, 0x63, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Varint
0x02,
// User ID 1
0x75, 0x73, 0x65, 0x72, 0x20, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public user encryption key 1
0x70, 0x75, 0x62, 0x20, 0x75, 0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 1
0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72,
0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// User ID 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x75, 0x73, 0x65, 0x72, 0x20,
0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public user encryption key 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x70, 0x75, 0x62, 0x20, 0x75,
0x73, 0x65, 0x72, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 2
0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x65, 0x6e, 0x63, 0x72, 0x79,
0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x70,
0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Varint
0x02,
// public app signature key 1
0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public tanker signature key 1
0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69,
0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b,
0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public app encryption key 1
0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x61, 0x6c, 0x20, 0x65, 0x6e, 0x63, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public tanker encryption key 1
0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69,
0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x65, 0x6e, 0x63, 0x20, 0x6b,
0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// encrypted group private encryption key 1
0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20,
0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x20, 0x67, 0x72,
0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69, 0x76, 0x20, 0x6b, 0x65, 0x79,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// provisional user app signature key 2
0x32, 0x6e, 0x64, 0x20, 0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76,
0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20,
0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
// provisional user tanker signature key 2
0x32, 0x6e, 0x64, 0x20, 0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70,
0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73,
0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00,
// public app encryption key 2
0x32, 0x6e, 0x64, 0x20, 0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76,
0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x65, 0x6e, 0x63, 0x20,
0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
// public tanker encryption key 2
0x32, 0x6e, 0x64, 0x20, 0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70,
0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x65,
0x6e, 0x63, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00,
// encrypted group private encryption key 2
0x32, 0x6e, 0x64, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x61, 0x6c, 0x20, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65,
0x64, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x70, 0x72, 0x69, 0x76,
0x20, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// self signature
0x73, 0x65, 0x6c, 0x66, 0x20, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75,
0x72, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
]);
expect(serializeUserGroupAdditionV3(userGroupAdd)).to.deep.equal(payload);
expect(unserializeUserGroupAdditionV3(payload)).to.deep.equal(userGroupAdd);
});
const fields = [
'previous_group_block',
'self_signature_with_current_key',
];
fields.forEach(field => {
it(`should throw when serializing an user group addition block with invalid ${field}`, async () => {
const userGroupAdd = {
group_id: new Uint8Array(tcrypto.HASH_SIZE),
previous_group_block: new Uint8Array(tcrypto.HASH_SIZE),
self_signature_with_current_key: new Uint8Array(tcrypto.SIGNATURE_SIZE),
encrypted_group_private_encryption_keys_for_users: [],
};
expect(() => serializeUserGroupAdditionV1(userGroupAdd)).not.to.throw();
// @ts-expect-error fields only contains Uint8Array fields from userGroupAdd
userGroupAdd[field] = new Uint8Array(0);
expect(() => serializeUserGroupAdditionV1(userGroupAdd)).to.throw();
});
});
it('correctly deserializes a UserGroupRemoval test vector', async () => {
const userGroupRemoval = {
group_id: makeUint8Array('group id', tcrypto.HASH_SIZE),
members_to_remove: [
makeUint8Array('user id 1', tcrypto.HASH_SIZE),
makeUint8Array('user id 2', tcrypto.HASH_SIZE),
],
provisional_members_to_remove: [
{
app_signature_public_key: makeUint8Array('app provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_signature_public_key: makeUint8Array('tanker provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
},
{
app_signature_public_key: makeUint8Array('2nd app provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
tanker_signature_public_key: makeUint8Array('2nd tanker provisional sig key', tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE),
},
],
self_signature_with_current_key: makeUint8Array('self signature', tcrypto.SIGNATURE_SIZE),
};
const payload = new Uint8Array([
// group id
0x67, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// varint
0x02,
// User ID 1
0x75, 0x73, 0x65, 0x72, 0x20, 0x69, 0x64, 0x20, 0x31, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// User ID 2
0x75, 0x73, 0x65, 0x72, 0x20, 0x69, 0x64, 0x20, 0x32, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Varint
0x02,
// public app signature key 1
0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// public tanker signature key 1
0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69,
0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20, 0x6b,
0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// provisional user app signature key 2
0x32, 0x6e, 0x64, 0x20, 0x61, 0x70, 0x70, 0x20, 0x70, 0x72, 0x6f, 0x76,
0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73, 0x69, 0x67, 0x20,
0x6b, 0x65, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00,
// provisional user tanker signature key 2
0x32, 0x6e, 0x64, 0x20, 0x74, 0x61, 0x6e, 0x6b, 0x65, 0x72, 0x20, 0x70,
0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x73,
0x69, 0x67, 0x20, 0x6b, 0x65, 0x79, 0x00, 0x00,
// self signature
0x73, 0x65, 0x6c, 0x66, 0x20, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75,
0x72, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
]);
expect(serializeUserGroupRemoval(userGroupRemoval)).to.deep.equal(payload);
expect(unserializeUserGroupRemoval(payload)).to.deep.equal(userGroupRemoval);
});
}); | the_stack |
import { TreeItem, TreeModel, TreeNode, walkTree } from "app/client/models/TreeModel";
import { mouseDrag, MouseDragHandler, MouseDragStart } from "app/client/ui/mouseDrag";
import * as css from 'app/client/ui/TreeViewComponentCss';
import { Computed, dom, DomArg, Holder } from "grainjs";
import { Disposable, IDisposable, makeTestId, ObsArray, Observable, observable } from "grainjs";
import debounce = require('lodash/debounce');
import defaults = require("lodash/defaults");
import noop = require('lodash/noop');
// DropZone identifies a location where an item can be inserted
interface DropZone {
zone: 'above'|'below'|'within';
item: ItemModel;
// `locked` allows to lock the dropzone until the cursor leaves the current item. This is useful
// when the dropzone is not computed from the cursor position but rather is set to 'within' an
// item when the auto-expander's timeout expires (defined in `this._updateExpander(...)`). In such
// a case it would be nearly impossible for the user to properly drop the item without the
// lock. Because when she releases the mouse she is very likely to move cursor unintentionally
// which would update the dropZone to either 'above' or 'below' and would insert item in the
// desired position.
locked?: boolean;
}
// The view model for a TreeItem
interface ItemModel {
highlight: Observable<boolean>;
collapsed: Observable<boolean>;
dragged: Observable<boolean>;
// vertical distance in px the user is dragging the item
deltaY: Observable<number>;
// the px distance from the left side of the container to the label
offsetLeft: () => number;
treeItem: TreeItem;
headerElement: HTMLElement;
containerElement: HTMLElement;
handleElement: HTMLElement;
labelElement: HTMLElement;
offsetElement: HTMLElement;
arrowElement: HTMLElement;
}
// Whether item1 and item2 are models of the same item.
function eq(item1: ItemModel|"root", item2: ItemModel|"root") {
if (item1 === "root" && item2 === "root") {
return true;
}
if (item1 === "root" || item2 === "root") {
return false;
}
return item1.treeItem === item2.treeItem;
}
// Set when a drag starts.
interface Drag extends IDisposable {
startY: number;
item: ItemModel;
// a holder used to update the highlight surrounding the target's parent
highlightedBox: Holder<IDisposable>;
autoExpander: Holder<{item: ItemModel} & IDisposable>;
}
// The geometry of the target which is a visual artifact showing where the user can drop an item.
interface Target {
width: number;
top: number;
left: number;
}
export interface TreeViewOptions {
// the number of pixels used for indentation.
offset?: number;
expanderDelay?: number;
// the delay a user has to keep the mouse down on a item before dragging starts
dragStartDelay?: number;
isOpen?: Observable<boolean>;
selected: Observable<TreeItem|null>;
// When true turns readonly mode on, defaults to false.
isReadonly?: Observable<boolean>;
}
const testId = makeTestId('test-treeview-');
/**
* The TreeViewComponent is a component that can show hierarchical data. It supports collapsing
* children and dragging and dropping to move items in the tree.
*
* Hovering an item reveals a handle. User must then grab that handle to drag an item. During drag
* the handle slides vertically to follow cursor's motion. During drag, the component highlights
* visually where the user can drop the item by displaying a target (above or below) the targeted
* item and by highlighting its parent. In order to ensure data consistency, the component prevents
* dropping an item within its own children. If the cursor leaves the component during a drag, all
* such visual artifact (handle, target and target's parent) are hidden, but if the cursor re-enter
* the componet without releasing the mouse, they will show again allowing user to resume dragging.
*/
// note to self: in the future the model will be updated by the server, which could cause conflicts
// if the user is dragging at the same time. It could be simpler to freeze the model and to differ
// their resolution until after the drag terminates.
export class TreeViewComponent extends Disposable {
private readonly _options: Required<TreeViewOptions>;
private readonly _containerElement: Element;
private _drag: Holder<Drag> = Holder.create(this);
private _hoveredItem: ItemModel|"root" = "root";
private _dropZone: DropZone|null = null;
private readonly _hideTarget = observable(true);
private readonly _target = observable<Target>({width: 0, top: 0, left: 0});
private readonly _dragging = observable(false);
private readonly _isClosed: Computed<boolean>;
private _treeItemMap: Map<TreeItem, Element> = new Map();
private _childrenDom: Observable<Node>;
constructor(private _model: Observable<TreeModel>, options: TreeViewOptions) {
super();
this._options = defaults(options, {
offset: 10,
expanderDelay: 1000,
dragStartDelay: 1000,
isOpen: Observable.create(this, true),
isReadonly: Observable.create(this, false),
});
// While building dom we add listeners to the children of all tree nodes to watch for changes
// and call this._update. Hence, repeated calls to this._update is likely to add or remove
// listeners to the observable that triggered the udpate which is not supported by grainjs and
// could fail (possibly infinite loop). Debounce allows for several change to resolve to a
// single update.
this._update = debounce(this._update.bind(this), 0, {leading: false});
// build dom for the tree of children
this._childrenDom = observable(this._buildChildren(this._model.get().children()));
this.autoDispose(this._model.addListener(this._update, this));
this._isClosed = Computed.create(this, (use) => !use(this._options.isOpen));
this._containerElement = css.treeViewContainer(
// hides the drop zone and target when the cursor leaves the component
dom.on('mouseleave', () => {
this._setDropZone(null);
const drag = this._drag.get();
if (drag) {
drag.autoExpander.clear();
drag.item.handleElement.style.display = 'none';
}
}),
dom.on('mouseenter', () => {
const drag = this._drag.get();
if (drag) {
drag.item.handleElement.style.display = '';
}
}),
// it's important to insert drop zone indicator before children, otherwise it could prevent
// some mouse events to hit children's dom
this._buildTarget(),
// insert children
dom.domComputed(this._childrenDom),
css.treeViewContainer.cls('-close', this._isClosed),
css.treeViewContainer.cls('-dragging', this._dragging),
testId('container'),
);
}
public buildDom() { return this._containerElement; }
// Starts a drag.
private _startDrag(ev: MouseEvent) {
if (this._options.isReadonly.get()) { return null; }
if (this._isClosed.get()) { return null; }
this._hoveredItem = this._closestItem(ev.target as HTMLElement|null);
if (this._hoveredItem === "root") {
return null;
}
const drag = {
startY: ev.clientY - this._hoveredItem.headerElement.getBoundingClientRect().top,
item: this._hoveredItem,
highlightedBox: Holder.create(this),
autoExpander: Holder.create<IDisposable & {item: ItemModel }>(this),
dispose: () => {
drag.autoExpander.dispose();
drag.highlightedBox.dispose();
drag.item.dragged.set(false);
drag.item.handleElement.style.display = '';
drag.item.deltaY.set(0);
}
};
this._drag.autoDispose(drag);
this._hoveredItem.dragged.set(true);
this._dragging.set(true);
return {
onMove: (mouseEvent: MouseEvent) => this._onMouseMove(mouseEvent),
onStop: () => this._terminateDragging(),
};
}
// Terminates a drag.
private _terminateDragging() {
const drag = this._drag.get();
// Clearing the `drag` instance before moving the item allow to revert the style of the item
// being dragged before it gets removed from the model.
this._drag.clear();
if (drag && this._dropZone) {
this._moveTreeNode(drag.item, this._dropZone);
}
this._setDropZone(null);
this._hideTarget.set(true);
this._dragging.set(false);
}
// The target is an horizontal bar indicating where user can drop an item. It typically shows
// above or below any particular item to indicate where the dragged item would be inserted.
private _buildTarget() {
return css.target(
testId('target'),
// show only if a drop zone is set
dom.hide(this._hideTarget),
dom.style('width', (use) => use(this._target).width + 'px'),
dom.style('top', (use) => use(this._target).top + 'px'),
dom.style('left', (use) => use(this._target).left + 'px'),
);
}
// Update this._childrenDom with the content of the new tree. Its rebuilds entirely the tree of
// items and reuses dom from the old content for each item that were already part of the old
// tree. Then takes care of disposing dom for thoses items that were removed from the old tree.
private _update() {
this._childrenDom.set(this._buildChildren(this._model.get().children(), 0));
// Dispose all the items from this._treeItemMap that are not in the new tree. Note an item
// already takes care of removing itself from the this._treeItemMap on dispose (thanks to the
// dom.onDispose(() => this._treeItemMap.delete(treeItem)) in this._getOrCreateItem). First
// create a map with all the items from _treeItemMap (they may or may not be included in the new
// tree), then walk the new tree and remove all of its items from the map. Eventually, what
// remains in the map are the elements that need disposal.
const map = new Map(this._treeItemMap);
walkTree(this._model.get(), (treeItem) => map.delete(treeItem));
map.forEach((elem, key) => dom.domDispose(elem));
}
// Build list of children. For each child reuses item's dom if already exist and update the offset
// and the list of children. Also add a listener that calls this._update to children.
private _buildChildren(children: ObsArray<TreeItem>, level: number = 0) {
return css.itemChildren(
children.get().map(treeItem => {
const elem = this._getOrCreateItem(treeItem);
this._setOffset(elem, level);
const itemHeaderElem = elem.children[0];
const itemChildren = treeItem.children();
const arrowElement = dom.getData(elem, 'item').arrowElement;
if (itemChildren) {
const itemChildrenElem = this._buildChildren(treeItem.children()!, level + 1);
replaceChildren(elem, itemHeaderElem, itemChildrenElem);
dom.styleElem(arrowElement, 'visibility', itemChildren.get().length ? 'visible' : 'hidden');
} else {
replaceChildren(elem, itemHeaderElem);
dom.styleElem(arrowElement, 'visibility', 'hidden');
}
return elem;
}),
dom.autoDispose(children.addListener(this._update, this)),
);
}
// Get or create dom for treeItem.
private _getOrCreateItem(treeItem: TreeItem): Element {
let item = this._treeItemMap.get(treeItem);
if (!item) {
item = this._buildTreeItemDom(treeItem,
dom.onDispose(() => this._treeItemMap.delete(treeItem))
);
this._treeItemMap.set(treeItem, item);
}
return item;
}
private _setOffset(el: Element, level: number) {
const item = dom.getData(el, 'item') as ItemModel;
item.offsetElement.style.width = level * this._options.offset + "px";
}
private _buildTreeItemDom(treeItem: TreeItem, ...args: DomArg[]): Element {
const collapsed = observable(false);
const dragged = observable(false);
// vertical distance in px the user is dragging the item
const deltaY = observable(0);
const children = treeItem.children();
const offsetLeft = () =>
labelElement.getBoundingClientRect().left - this._containerElement.getBoundingClientRect().left;
const highlight = observable(false);
let headerElement: HTMLElement;
let labelElement: HTMLElement;
let handleElement: HTMLElement;
let offsetElement: HTMLElement;
let arrowElement: HTMLElement;
const containerElement = dom('div.itemContainer',
testId('itemContainer'),
dom.cls('collapsed', collapsed),
css.itemHeaderWrapper(
testId('itemHeaderWrapper'),
dom.cls('dragged', dragged),
css.itemHeaderWrapper.cls('-not-dragging', (use) => !use(this._dragging)),
headerElement = css.itemHeader(
testId('itemHeader'),
dom.cls('highlight', highlight),
dom.cls('selected', (use) => use(this._options.selected) === treeItem),
offsetElement = css.offset(testId('offset')),
arrowElement = css.arrow(
css.dropdown('Dropdown'),
testId('itemArrow'),
dom.style('transform', (use) => use(collapsed) ? 'rotate(-90deg)' : ''),
dom.on('click', (ev) => toggle(collapsed)),
// Let's prevent dragging to start when un-intentionally holding the mouse down on an arrow.
dom.on('mousedown', (ev) => ev.stopPropagation()),
),
labelElement = css.itemLabel(
testId('label'),
treeItem.buildDom(),
dom.style('top', (use) => use(deltaY) + 'px')
),
delayedMouseDrag(this._startDrag.bind(this), this._options.dragStartDelay),
),
css.itemLabelRight(
handleElement = css.centeredIcon('DragDrop',
dom.style('top', (use) => use(deltaY) + 'px'),
testId('handle'),
dom.hide(this._options.isReadonly),
),
mouseDrag((startEvent, elem) => this._startDrag(startEvent))),
),
...args
);
// Associates some of this item internals to the dom element. This is what makes possible to
// find which item user is currently pointing at using `const item =
// this._closestItem(ev.target);` where ev is a mouse event.
const itemModel = {
collapsed, dragged, children, treeItem, offsetLeft, highlight, deltaY,
headerElement,
containerElement,
handleElement,
labelElement,
offsetElement,
arrowElement,
} as ItemModel;
dom.dataElem(containerElement, 'item', itemModel);
return containerElement;
}
private _updateHandle(y: number) {
const drag = this._drag.get();
if (drag) {
drag.item.deltaY.set(y - drag.startY - drag.item.headerElement.getBoundingClientRect().top);
}
}
private _onMouseMove(ev: MouseEvent) {
if (!(ev.target instanceof HTMLElement)) {
return null;
}
const item = this._closestItem(ev.target);
if (item === "root") {
return;
}
// updates the expander when cursor is entering a new item while dragging
const drag = this._drag.get();
if (drag && !eq(this._hoveredItem, item)) {
this._updateExpander(drag, item);
}
this._hoveredItem = item;
this._updateHandle(ev.clientY);
// update the target, update the target's parent
const dropZone = this._getDropZone(ev.clientY);
this._setDropZone(dropZone);
}
// Set the drop zone and update the target and target's parent
private _setDropZone(dropZone: DropZone|null) {
// if there is a locked dropzone on the hovered item already set, do nothing (see
// `DropZone#locked` documentation at the begin of this file for more detail)
if (this._dropZone && this._dropZone.locked && eq(this._dropZone.item, this._hoveredItem)) {
return;
}
this._dropZone = dropZone;
this._updateTarget();
this._updateTargetParent();
}
// Update the target based on this._dropZone.
private _updateTarget() {
const dropZone = this._dropZone;
if (dropZone) {
const left = this._getDropZoneOffsetLeft(dropZone);
const width = this._getDropZoneRight(dropZone) - left;
const top = this._getDropZoneTop(dropZone);
this._target.set({width, left, top});
this._hideTarget.set(false);
} else {
this._hideTarget.set(true);
}
}
// compute the px distance between the left side of the container and the right side of the header
private _getDropZoneRight(dropZone: DropZone): number {
const headerRight = dropZone.item.headerElement.getBoundingClientRect().right;
const containerRight = this._containerElement.getBoundingClientRect().left;
return headerRight - containerRight;
}
// compute the px distance between the left side of the container and the drop zone
private _getDropZoneOffsetLeft(dropZone: DropZone): number {
// when target is 'within' the item we must add one level of indentation to the items left offset
return dropZone.item.offsetLeft() + (dropZone.zone === 'within' ? this._options.offset : 0);
}
// compute the px distance between the top of the container and the drop zone
private _getDropZoneTop(dropZone: DropZone): number {
const el = dropZone.item.headerElement;
// when crossing the border between 2 consecutive items A and B while dragging another item, in
// order to allow the target to remain steady between A and B we need to remove 2 px when
// dropzone is 'above', otherwise it causes the target to flicker.
return dropZone.zone === 'above' ? el.offsetTop - 2 : el.offsetTop + el.clientHeight;
}
// Turns off the highlight on the former parent, and turns it on the new parent.
private _updateTargetParent() {
const drag = this._drag.get();
if (!drag) {
return;
}
const newParent = this._dropZone ? this._getDropZoneParent(this._dropZone) : null;
if (newParent && newParent !== "root") {
drag.highlightedBox.autoDispose({dispose: () => newParent.highlight.set(false)});
newParent.highlight.set(true);
} else {
// setting holder to a dump value allows to dispose the previous value
drag.highlightedBox.autoDispose({dispose: noop});
}
}
private _getDropZone(mouseY: number): DropZone|null {
const item = this._hoveredItem;
const drag = this._drag.get();
if (!drag || item === "root") {
return null;
}
// let's not permit dropping above or below the dragged item
if (eq(drag.item, item)) {
return null;
}
// prevents dropping items into their own children
if (this._isInChildOf(item.containerElement, drag.item.containerElement)) {
return null;
}
const children = item.treeItem.children();
const rect = item.headerElement.getBoundingClientRect();
// if cursor is over the top half of the header set the drop zone to above this item
if ((mouseY - rect.top) <= rect.height / 2) {
return {zone: 'above', item};
}
// if cursor is over the bottom half of the header set the drop zone to below this item, unless
// the children are expanded in which case set the drop zone to 'within' this item.
if ((mouseY - rect.top) > rect.height / 2) {
if (!item.collapsed.get() && children && children.get().length) {
// set drop zone to above the first child only if the dragged item is not this item, because
// it is not allowed to drop item into their own children.
if (eq(item, drag.item)) {
return null;
}
return {zone: 'within', item};
} else {
return {zone: 'below', item};
}
}
return null;
}
// Returns whether `element` is nested in a child of `parent`. Both `el` and `parent` must be
// a child of this._containerElement.
private _isInChildOf(el: Element, parent: Element) {
while (el.parentElement
&& el.parentElement !== parent
&& el.parentElement !== this._containerElement // let's stop at the top element
) {
el = el.parentElement;
}
return el.parentElement === parent;
}
// Finds the closest ancestor with '.itemContainer' and returns the attached ItemModel. Returns
// "root" if none are found.
private _closestItem(element: HTMLElement|null): ItemModel|"root" {
if (element) {
let el: HTMLElement|null = element;
while (el && el !== this._containerElement) {
if (el.classList.contains('itemContainer')) {
return dom.getData(el, 'item');
}
el = el.parentElement;
}
}
return "root";
}
// Return the ItemModel of the item's parent or 'root' if parent is the root.
private _getParent(item: ItemModel): ItemModel|"root" {
return this._closestItem(item.containerElement.parentElement);
}
// Return the ItemModel of the dropZone's parent or 'root' if parent is the root.
private _getDropZoneParent(zone: DropZone): ItemModel|"root" {
return zone.zone === 'within' ? zone.item : this._getParent(zone.item);
}
// Returns the TreeNode associated with the item or the TreeModel if item is the root.
private _getTreeNode(item: ItemModel|"root"): TreeNode {
return item === "root" ? this._model.get() : item.treeItem;
}
// returns the item that is just after where zone is pointing to
private _getNextChild(zone: DropZone): TreeItem|undefined {
const children = this._getTreeNode(this._getDropZoneParent(zone)).children();
if (!children) {
return undefined;
}
switch (zone.zone) {
case "within": return children.get()[0];
case "above": return zone.item.treeItem;
case "below": return findNext(children.get(), zone.item.treeItem);
}
}
// trigger calls to TreeNode#insertBefore(...) and TreeNode#removeChild(...) to move draggedItem
// to where zone is pointing to.
private _moveTreeNode(draggedItem: ItemModel, zone: DropZone) {
const parentTo = this._getTreeNode(this._getDropZoneParent(zone));
const childrenTo = parentTo.children();
const nextChild = this._getNextChild(zone);
const parentFrom = this._getTreeNode(this._getParent(draggedItem));
if (!childrenTo) {
throw new Error('Should not be possible to drop into an item with `null` children');
}
if (parentTo === parentFrom) {
// if dropping an item below the above item, do nothing.
if (nextChild === draggedItem.treeItem) {
return;
}
// if dropping and item above the below item, do nothing.
if (findNext(childrenTo.get(), draggedItem.treeItem) === nextChild) {
return;
}
}
// call callbacks
parentTo.insertBefore(draggedItem.treeItem, nextChild || null);
}
// Shuts down the previous expander, and sets a new one for item if it is not the dragged item and
// it can be expanded (ie: it has collapsed children or it has empty list of children).
private _updateExpander(drag: Drag, item: ItemModel) {
const children = item.treeItem.children();
if (eq(drag.item, item) || !children || children.get().length && !item.collapsed.get()) {
drag.autoExpander.clear();
} else {
const callback = () => {
// Expanding the item needs some extra care. Because we could push the dragged item
// downwards in the view (if the dragged item is below the item to be expanded). In which
// case we must update `item.deltaY` to reflect the offset in order to prevent an offset
// between the handle (and the drag image) and the cursor. So let's first save the old pos of the item.
const oldItemTop = drag.item.headerElement.getBoundingClientRect().top;
// let's expand the item
item.collapsed.set(false);
// let's get the new pos for the dragged item, and get the diff
const newItemTop = drag.item.headerElement.getBoundingClientRect().top;
const offset = newItemTop - oldItemTop;
// let's reflect the offset on `item.deltaY`
drag.item.deltaY.set(drag.item.deltaY.get() - offset);
// then set the dropzone.
this._setDropZone({zone: 'within', item, locked: true});
};
const timeoutId = window.setTimeout(callback, this._options.expanderDelay);
const dispose = () => window.clearTimeout(timeoutId);
drag.autoExpander.autoDispose({item, dispose});
}
}
}
// returns the item next to item in children, or null.
function findNext(children: TreeItem[], item: TreeItem) {
return children.find((val, i, array) => Boolean(i) && array[i - 1] === item);
}
function toggle(obs: Observable<boolean>) {
obs.set(!obs.get());
}
export function addTreeView(model: Observable<TreeModel>, options: TreeViewOptions) {
return dom.create(TreeViewComponent, model, options);
}
// Starts dragging only when the user keeps the mouse down for a while. Also the cursor must not
// move until the timer expires. Implementation relies on `./mouseDrag` and a timer that will call
// `startDrag` only after a timer expires.
function delayedMouseDrag(startDrag: MouseDragStart, delay: number) {
return mouseDrag((startEvent, el) => {
// the drag handler is assigned when the timer expires
let handler: MouseDragHandler|null;
const timeoutId = setTimeout(() => handler = startDrag(startEvent, el), delay);
dom.onDisposeElem(el, () => clearTimeout(timeoutId));
function onMove(ev: MouseEvent) {
// Clears timeout if cursor moves before timer expires, ie: the startDrag won't be called.
handler ? handler.onMove(ev) : clearTimeout(timeoutId);
}
function onStop(ev: MouseEvent) {
handler ? handler.onStop(ev) : clearTimeout(timeoutId);
}
return {onMove, onStop};
});
}
// Replaces the children of elem with children.
function replaceChildren(elem: Element, ...children: Element[]) {
while (elem.firstChild) {
elem.removeChild(elem.firstChild);
}
for (const child of children) {
elem.appendChild(child);
}
} | the_stack |
export = bigInt;
export as namespace bigInt;
declare var bigInt: bigInt.BigIntegerStatic;
declare namespace bigInt {
type BigNumber = number | bigint | string | BigInteger;
interface BigIntegerStatic {
/**
* Equivalent to bigInt(0).
*/
(): BigInteger;
/**
* Parse a Javascript number into a bigInt.
*/
(number: number): BigInteger;
/**
* Parse a Javascript native bigint into a bigInt.
*/
(number: bigint): BigInteger;
/**
* Parse a string into a bigInt.
* Default base is 10.
* Default alphabet is "0123456789abcdefghijklmnopqrstuvwxyz".
* caseSensitive defaults to false.
*/
(string: string, base?: BigNumber, alphabet?: string, caseSensitive?: boolean): BigInteger;
/**
* no-op.
*/
(bigInt: BigInteger): BigInteger;
/**
* Constructs a bigInt from an array of digits in specified base.
* The optional isNegative flag will make the number negative.
*/
fromArray: (digits: BigNumber[], base?: BigNumber, isNegative?: boolean) => BigInteger;
/**
* Finds the greatest common denominator of a and b.
*/
gcd: (a: BigNumber, b: BigNumber) => BigInteger;
/**
* Returns true if x is a BigInteger, false otherwise.
*/
isInstance: (x: any) => x is BigInteger;
/**
* Finds the least common multiple of a and b.
*/
lcm: (a: BigNumber, b: BigNumber) => BigInteger;
/**
* Returns the largest of a and b.
*/
max: (a: BigNumber, b: BigNumber) => BigInteger;
/**
* Returns the smallest of a and b.
*/
min: (a: BigNumber, b: BigNumber) => BigInteger;
/**
* Equivalent to bigInt(-1).
*/
minusOne: BigInteger;
/**
* Equivalent to bigInt(1).
*/
one: BigInteger;
/**
* Returns a random number between min and max.
*/
randBetween: (min: BigNumber, max: BigNumber) => BigInteger;
/**
* Equivalent to bigInt(0).
*/
zero: BigInteger;
}
interface BigInteger {
/**
* Returns the absolute value of a bigInt.
*/
abs(): BigInteger;
/**
* Performs addition.
*/
add(number: BigNumber): BigInteger;
/**
* Performs the bitwise AND operation.
*/
and(number: BigNumber): BigInteger;
/**
* Returns the number of digits required to represent a bigInt in binary.
*/
bitLength(): BigInteger;
/**
* Performs a comparison between two numbers. If the numbers are equal, it returns 0.
* If the first number is greater, it returns 1. If the first number is lesser, it returns -1.
*/
compare(number: BigNumber): number;
/**
* Performs a comparison between the absolute value of two numbers.
*/
compareAbs(number: BigNumber): number;
/**
* Alias for the compare method.
*/
compareTo(number: BigNumber): number;
/**
* Performs integer division, disregarding the remainder.
*/
divide(number: BigNumber): BigInteger;
/**
* Performs division and returns an object with two properties: quotient and remainder.
* The sign of the remainder will match the sign of the dividend.
*/
divmod(number: BigNumber): { quotient: BigInteger, remainder: BigInteger };
/**
* Alias for the equals method.
*/
eq(number: BigNumber): boolean;
/**
* Checks if two numbers are equal.
*/
equals(number: BigNumber): boolean;
/**
* Alias for the greaterOrEquals method.
*/
geq(number: BigNumber): boolean;
/**
* Checks if the first number is greater than the second.
*/
greater(number: BigNumber): boolean;
/**
* Checks if the first number is greater than or equal to the second.
*/
greaterOrEquals(number: BigNumber): boolean;
/**
* Alias for the greater method.
*/
gt(number: BigNumber): boolean;
/**
* Returns true if the first number is divisible by the second number, false otherwise.
*/
isDivisibleBy(number: BigNumber): boolean;
/**
* Returns true if the number is even, false otherwise.
*/
isEven(): boolean;
/**
* Returns true if the number is negative, false otherwise.
* Returns false for 0 and true for -0.
*/
isNegative(): boolean;
/**
* Returns true if the number is odd, false otherwise.
*/
isOdd(): boolean;
/**
* Return true if the number is positive, false otherwise.
* Returns true for 0 and false for -0.
*/
isPositive(): boolean;
/**
* Returns true if the number is prime, false otherwise.
*/
isPrime(): boolean;
/**
* Returns true if the number is very likely to be prime, false otherwise.
*/
isProbablePrime(iterations?: number): boolean;
/**
* Returns true if the number is 1 or -1, false otherwise.
*/
isUnit(): boolean;
/**
* Return true if the number is 0 or -0, false otherwise.
*/
isZero(): boolean;
/**
* Alias for the lesserOrEquals method.
*/
leq(number: BigNumber): boolean;
/**
* Checks if the first number is lesser than the second.
*/
lesser(number: BigNumber): boolean;
/**
* Checks if the first number is less than or equal to the second.
*/
lesserOrEquals(number: BigNumber): boolean;
/**
* Alias for the lesser method.
*/
lt(number: BigNumber): boolean;
/**
* Alias for the subtract method.
*/
minus(number: BigNumber): BigInteger;
/**
* Performs division and returns the remainder, disregarding the quotient.
* The sign of the remainder will match the sign of the dividend.
*/
mod(number: BigNumber): BigInteger;
/**
* Finds the multiplicative inverse of the number modulo mod.
*/
modInv(number: BigNumber): BigInteger;
/**
* Takes the number to the power exp modulo mod.
*/
modPow(exp: BigNumber, mod: BigNumber): BigInteger;
/**
* Performs multiplication.
*/
multiply(number: BigNumber): BigInteger;
/**
* Reverses the sign of the number.
*/
negate(): BigInteger;
/**
* Alias for the notEquals method.
*/
neq(number: BigNumber): boolean;
/**
* Adds one to the number.
*/
next(): BigInteger;
/**
* Performs the bitwise NOT operation.
*/
not(): BigInteger;
/**
* Checks if two numbers are not equal.
*/
notEquals(number: BigNumber): boolean;
/**
* Performs the bitwise OR operation.
*/
or(number: BigNumber): BigInteger;
/**
* Alias for the divide method.
*/
over(number: BigNumber): BigInteger;
/**
* Alias for the add method.
*/
plus(number: BigNumber): BigInteger;
/**
* Performs exponentiation. If the exponent is less than 0, pow returns 0.
* bigInt.zero.pow(0) returns 1.
*/
pow(number: BigNumber): BigInteger;
/**
* Subtracts one from the number.
*/
prev(): BigInteger;
/**
* Alias for the mod method.
*/
remainder(number: BigNumber): BigInteger;
/**
* Shifts the number left by n places in its binary representation.
* If a negative number is provided, it will shift right.
*
* Throws an error if number is outside of the range [-9007199254740992, 9007199254740992].
*/
shiftLeft(number: BigNumber): BigInteger;
/**
* Shifts the number right by n places in its binary representation.
* If a negative number is provided, it will shift left.
*
* Throws an error if number is outside of the range [-9007199254740992, 9007199254740992].
*/
shiftRight(number: BigNumber): BigInteger;
/**
* Squares the number.
*/
square(): BigInteger;
/**
* Performs subtraction.
*/
subtract(number: BigNumber): BigInteger;
/**
* Alias for the multiply method.
*/
times(number: BigNumber): BigInteger;
/**
*
* Converts a bigInt to an object representing it as an array of integers module the given radix.
*/
toArray(radix: number): BaseArray;
/**
* Converts a bigInt into a native Javascript number. Loses precision for numbers outside the range.
*/
toJSNumber(): number;
/**
* Converts a bigInt to a string.
*/
toString(radix?: number, alphabet?: string): string;
/**
* Converts a bigInt to a string. This method is called behind the scenes in JSON.stringify.
*/
toJSON(): string;
/**
* Converts a bigInt to a native Javascript number. This override allows you to use native
* arithmetic operators without explicit conversion.
*/
valueOf(): number;
/**
* Performs the bitwise XOR operation.
*/
xor(number: BigNumber): BigInteger;
}
// Array constant accessors
interface BigIntegerStatic {
'-999': BigInteger;
'-998': BigInteger;
'-997': BigInteger;
'-996': BigInteger;
'-995': BigInteger;
'-994': BigInteger;
'-993': BigInteger;
'-992': BigInteger;
'-991': BigInteger;
'-990': BigInteger;
'-989': BigInteger;
'-988': BigInteger;
'-987': BigInteger;
'-986': BigInteger;
'-985': BigInteger;
'-984': BigInteger;
'-983': BigInteger;
'-982': BigInteger;
'-981': BigInteger;
'-980': BigInteger;
'-979': BigInteger;
'-978': BigInteger;
'-977': BigInteger;
'-976': BigInteger;
'-975': BigInteger;
'-974': BigInteger;
'-973': BigInteger;
'-972': BigInteger;
'-971': BigInteger;
'-970': BigInteger;
'-969': BigInteger;
'-968': BigInteger;
'-967': BigInteger;
'-966': BigInteger;
'-965': BigInteger;
'-964': BigInteger;
'-963': BigInteger;
'-962': BigInteger;
'-961': BigInteger;
'-960': BigInteger;
'-959': BigInteger;
'-958': BigInteger;
'-957': BigInteger;
'-956': BigInteger;
'-955': BigInteger;
'-954': BigInteger;
'-953': BigInteger;
'-952': BigInteger;
'-951': BigInteger;
'-950': BigInteger;
'-949': BigInteger;
'-948': BigInteger;
'-947': BigInteger;
'-946': BigInteger;
'-945': BigInteger;
'-944': BigInteger;
'-943': BigInteger;
'-942': BigInteger;
'-941': BigInteger;
'-940': BigInteger;
'-939': BigInteger;
'-938': BigInteger;
'-937': BigInteger;
'-936': BigInteger;
'-935': BigInteger;
'-934': BigInteger;
'-933': BigInteger;
'-932': BigInteger;
'-931': BigInteger;
'-930': BigInteger;
'-929': BigInteger;
'-928': BigInteger;
'-927': BigInteger;
'-926': BigInteger;
'-925': BigInteger;
'-924': BigInteger;
'-923': BigInteger;
'-922': BigInteger;
'-921': BigInteger;
'-920': BigInteger;
'-919': BigInteger;
'-918': BigInteger;
'-917': BigInteger;
'-916': BigInteger;
'-915': BigInteger;
'-914': BigInteger;
'-913': BigInteger;
'-912': BigInteger;
'-911': BigInteger;
'-910': BigInteger;
'-909': BigInteger;
'-908': BigInteger;
'-907': BigInteger;
'-906': BigInteger;
'-905': BigInteger;
'-904': BigInteger;
'-903': BigInteger;
'-902': BigInteger;
'-901': BigInteger;
'-900': BigInteger;
'-899': BigInteger;
'-898': BigInteger;
'-897': BigInteger;
'-896': BigInteger;
'-895': BigInteger;
'-894': BigInteger;
'-893': BigInteger;
'-892': BigInteger;
'-891': BigInteger;
'-890': BigInteger;
'-889': BigInteger;
'-888': BigInteger;
'-887': BigInteger;
'-886': BigInteger;
'-885': BigInteger;
'-884': BigInteger;
'-883': BigInteger;
'-882': BigInteger;
'-881': BigInteger;
'-880': BigInteger;
'-879': BigInteger;
'-878': BigInteger;
'-877': BigInteger;
'-876': BigInteger;
'-875': BigInteger;
'-874': BigInteger;
'-873': BigInteger;
'-872': BigInteger;
'-871': BigInteger;
'-870': BigInteger;
'-869': BigInteger;
'-868': BigInteger;
'-867': BigInteger;
'-866': BigInteger;
'-865': BigInteger;
'-864': BigInteger;
'-863': BigInteger;
'-862': BigInteger;
'-861': BigInteger;
'-860': BigInteger;
'-859': BigInteger;
'-858': BigInteger;
'-857': BigInteger;
'-856': BigInteger;
'-855': BigInteger;
'-854': BigInteger;
'-853': BigInteger;
'-852': BigInteger;
'-851': BigInteger;
'-850': BigInteger;
'-849': BigInteger;
'-848': BigInteger;
'-847': BigInteger;
'-846': BigInteger;
'-845': BigInteger;
'-844': BigInteger;
'-843': BigInteger;
'-842': BigInteger;
'-841': BigInteger;
'-840': BigInteger;
'-839': BigInteger;
'-838': BigInteger;
'-837': BigInteger;
'-836': BigInteger;
'-835': BigInteger;
'-834': BigInteger;
'-833': BigInteger;
'-832': BigInteger;
'-831': BigInteger;
'-830': BigInteger;
'-829': BigInteger;
'-828': BigInteger;
'-827': BigInteger;
'-826': BigInteger;
'-825': BigInteger;
'-824': BigInteger;
'-823': BigInteger;
'-822': BigInteger;
'-821': BigInteger;
'-820': BigInteger;
'-819': BigInteger;
'-818': BigInteger;
'-817': BigInteger;
'-816': BigInteger;
'-815': BigInteger;
'-814': BigInteger;
'-813': BigInteger;
'-812': BigInteger;
'-811': BigInteger;
'-810': BigInteger;
'-809': BigInteger;
'-808': BigInteger;
'-807': BigInteger;
'-806': BigInteger;
'-805': BigInteger;
'-804': BigInteger;
'-803': BigInteger;
'-802': BigInteger;
'-801': BigInteger;
'-800': BigInteger;
'-799': BigInteger;
'-798': BigInteger;
'-797': BigInteger;
'-796': BigInteger;
'-795': BigInteger;
'-794': BigInteger;
'-793': BigInteger;
'-792': BigInteger;
'-791': BigInteger;
'-790': BigInteger;
'-789': BigInteger;
'-788': BigInteger;
'-787': BigInteger;
'-786': BigInteger;
'-785': BigInteger;
'-784': BigInteger;
'-783': BigInteger;
'-782': BigInteger;
'-781': BigInteger;
'-780': BigInteger;
'-779': BigInteger;
'-778': BigInteger;
'-777': BigInteger;
'-776': BigInteger;
'-775': BigInteger;
'-774': BigInteger;
'-773': BigInteger;
'-772': BigInteger;
'-771': BigInteger;
'-770': BigInteger;
'-769': BigInteger;
'-768': BigInteger;
'-767': BigInteger;
'-766': BigInteger;
'-765': BigInteger;
'-764': BigInteger;
'-763': BigInteger;
'-762': BigInteger;
'-761': BigInteger;
'-760': BigInteger;
'-759': BigInteger;
'-758': BigInteger;
'-757': BigInteger;
'-756': BigInteger;
'-755': BigInteger;
'-754': BigInteger;
'-753': BigInteger;
'-752': BigInteger;
'-751': BigInteger;
'-750': BigInteger;
'-749': BigInteger;
'-748': BigInteger;
'-747': BigInteger;
'-746': BigInteger;
'-745': BigInteger;
'-744': BigInteger;
'-743': BigInteger;
'-742': BigInteger;
'-741': BigInteger;
'-740': BigInteger;
'-739': BigInteger;
'-738': BigInteger;
'-737': BigInteger;
'-736': BigInteger;
'-735': BigInteger;
'-734': BigInteger;
'-733': BigInteger;
'-732': BigInteger;
'-731': BigInteger;
'-730': BigInteger;
'-729': BigInteger;
'-728': BigInteger;
'-727': BigInteger;
'-726': BigInteger;
'-725': BigInteger;
'-724': BigInteger;
'-723': BigInteger;
'-722': BigInteger;
'-721': BigInteger;
'-720': BigInteger;
'-719': BigInteger;
'-718': BigInteger;
'-717': BigInteger;
'-716': BigInteger;
'-715': BigInteger;
'-714': BigInteger;
'-713': BigInteger;
'-712': BigInteger;
'-711': BigInteger;
'-710': BigInteger;
'-709': BigInteger;
'-708': BigInteger;
'-707': BigInteger;
'-706': BigInteger;
'-705': BigInteger;
'-704': BigInteger;
'-703': BigInteger;
'-702': BigInteger;
'-701': BigInteger;
'-700': BigInteger;
'-699': BigInteger;
'-698': BigInteger;
'-697': BigInteger;
'-696': BigInteger;
'-695': BigInteger;
'-694': BigInteger;
'-693': BigInteger;
'-692': BigInteger;
'-691': BigInteger;
'-690': BigInteger;
'-689': BigInteger;
'-688': BigInteger;
'-687': BigInteger;
'-686': BigInteger;
'-685': BigInteger;
'-684': BigInteger;
'-683': BigInteger;
'-682': BigInteger;
'-681': BigInteger;
'-680': BigInteger;
'-679': BigInteger;
'-678': BigInteger;
'-677': BigInteger;
'-676': BigInteger;
'-675': BigInteger;
'-674': BigInteger;
'-673': BigInteger;
'-672': BigInteger;
'-671': BigInteger;
'-670': BigInteger;
'-669': BigInteger;
'-668': BigInteger;
'-667': BigInteger;
'-666': BigInteger;
'-665': BigInteger;
'-664': BigInteger;
'-663': BigInteger;
'-662': BigInteger;
'-661': BigInteger;
'-660': BigInteger;
'-659': BigInteger;
'-658': BigInteger;
'-657': BigInteger;
'-656': BigInteger;
'-655': BigInteger;
'-654': BigInteger;
'-653': BigInteger;
'-652': BigInteger;
'-651': BigInteger;
'-650': BigInteger;
'-649': BigInteger;
'-648': BigInteger;
'-647': BigInteger;
'-646': BigInteger;
'-645': BigInteger;
'-644': BigInteger;
'-643': BigInteger;
'-642': BigInteger;
'-641': BigInteger;
'-640': BigInteger;
'-639': BigInteger;
'-638': BigInteger;
'-637': BigInteger;
'-636': BigInteger;
'-635': BigInteger;
'-634': BigInteger;
'-633': BigInteger;
'-632': BigInteger;
'-631': BigInteger;
'-630': BigInteger;
'-629': BigInteger;
'-628': BigInteger;
'-627': BigInteger;
'-626': BigInteger;
'-625': BigInteger;
'-624': BigInteger;
'-623': BigInteger;
'-622': BigInteger;
'-621': BigInteger;
'-620': BigInteger;
'-619': BigInteger;
'-618': BigInteger;
'-617': BigInteger;
'-616': BigInteger;
'-615': BigInteger;
'-614': BigInteger;
'-613': BigInteger;
'-612': BigInteger;
'-611': BigInteger;
'-610': BigInteger;
'-609': BigInteger;
'-608': BigInteger;
'-607': BigInteger;
'-606': BigInteger;
'-605': BigInteger;
'-604': BigInteger;
'-603': BigInteger;
'-602': BigInteger;
'-601': BigInteger;
'-600': BigInteger;
'-599': BigInteger;
'-598': BigInteger;
'-597': BigInteger;
'-596': BigInteger;
'-595': BigInteger;
'-594': BigInteger;
'-593': BigInteger;
'-592': BigInteger;
'-591': BigInteger;
'-590': BigInteger;
'-589': BigInteger;
'-588': BigInteger;
'-587': BigInteger;
'-586': BigInteger;
'-585': BigInteger;
'-584': BigInteger;
'-583': BigInteger;
'-582': BigInteger;
'-581': BigInteger;
'-580': BigInteger;
'-579': BigInteger;
'-578': BigInteger;
'-577': BigInteger;
'-576': BigInteger;
'-575': BigInteger;
'-574': BigInteger;
'-573': BigInteger;
'-572': BigInteger;
'-571': BigInteger;
'-570': BigInteger;
'-569': BigInteger;
'-568': BigInteger;
'-567': BigInteger;
'-566': BigInteger;
'-565': BigInteger;
'-564': BigInteger;
'-563': BigInteger;
'-562': BigInteger;
'-561': BigInteger;
'-560': BigInteger;
'-559': BigInteger;
'-558': BigInteger;
'-557': BigInteger;
'-556': BigInteger;
'-555': BigInteger;
'-554': BigInteger;
'-553': BigInteger;
'-552': BigInteger;
'-551': BigInteger;
'-550': BigInteger;
'-549': BigInteger;
'-548': BigInteger;
'-547': BigInteger;
'-546': BigInteger;
'-545': BigInteger;
'-544': BigInteger;
'-543': BigInteger;
'-542': BigInteger;
'-541': BigInteger;
'-540': BigInteger;
'-539': BigInteger;
'-538': BigInteger;
'-537': BigInteger;
'-536': BigInteger;
'-535': BigInteger;
'-534': BigInteger;
'-533': BigInteger;
'-532': BigInteger;
'-531': BigInteger;
'-530': BigInteger;
'-529': BigInteger;
'-528': BigInteger;
'-527': BigInteger;
'-526': BigInteger;
'-525': BigInteger;
'-524': BigInteger;
'-523': BigInteger;
'-522': BigInteger;
'-521': BigInteger;
'-520': BigInteger;
'-519': BigInteger;
'-518': BigInteger;
'-517': BigInteger;
'-516': BigInteger;
'-515': BigInteger;
'-514': BigInteger;
'-513': BigInteger;
'-512': BigInteger;
'-511': BigInteger;
'-510': BigInteger;
'-509': BigInteger;
'-508': BigInteger;
'-507': BigInteger;
'-506': BigInteger;
'-505': BigInteger;
'-504': BigInteger;
'-503': BigInteger;
'-502': BigInteger;
'-501': BigInteger;
'-500': BigInteger;
'-499': BigInteger;
'-498': BigInteger;
'-497': BigInteger;
'-496': BigInteger;
'-495': BigInteger;
'-494': BigInteger;
'-493': BigInteger;
'-492': BigInteger;
'-491': BigInteger;
'-490': BigInteger;
'-489': BigInteger;
'-488': BigInteger;
'-487': BigInteger;
'-486': BigInteger;
'-485': BigInteger;
'-484': BigInteger;
'-483': BigInteger;
'-482': BigInteger;
'-481': BigInteger;
'-480': BigInteger;
'-479': BigInteger;
'-478': BigInteger;
'-477': BigInteger;
'-476': BigInteger;
'-475': BigInteger;
'-474': BigInteger;
'-473': BigInteger;
'-472': BigInteger;
'-471': BigInteger;
'-470': BigInteger;
'-469': BigInteger;
'-468': BigInteger;
'-467': BigInteger;
'-466': BigInteger;
'-465': BigInteger;
'-464': BigInteger;
'-463': BigInteger;
'-462': BigInteger;
'-461': BigInteger;
'-460': BigInteger;
'-459': BigInteger;
'-458': BigInteger;
'-457': BigInteger;
'-456': BigInteger;
'-455': BigInteger;
'-454': BigInteger;
'-453': BigInteger;
'-452': BigInteger;
'-451': BigInteger;
'-450': BigInteger;
'-449': BigInteger;
'-448': BigInteger;
'-447': BigInteger;
'-446': BigInteger;
'-445': BigInteger;
'-444': BigInteger;
'-443': BigInteger;
'-442': BigInteger;
'-441': BigInteger;
'-440': BigInteger;
'-439': BigInteger;
'-438': BigInteger;
'-437': BigInteger;
'-436': BigInteger;
'-435': BigInteger;
'-434': BigInteger;
'-433': BigInteger;
'-432': BigInteger;
'-431': BigInteger;
'-430': BigInteger;
'-429': BigInteger;
'-428': BigInteger;
'-427': BigInteger;
'-426': BigInteger;
'-425': BigInteger;
'-424': BigInteger;
'-423': BigInteger;
'-422': BigInteger;
'-421': BigInteger;
'-420': BigInteger;
'-419': BigInteger;
'-418': BigInteger;
'-417': BigInteger;
'-416': BigInteger;
'-415': BigInteger;
'-414': BigInteger;
'-413': BigInteger;
'-412': BigInteger;
'-411': BigInteger;
'-410': BigInteger;
'-409': BigInteger;
'-408': BigInteger;
'-407': BigInteger;
'-406': BigInteger;
'-405': BigInteger;
'-404': BigInteger;
'-403': BigInteger;
'-402': BigInteger;
'-401': BigInteger;
'-400': BigInteger;
'-399': BigInteger;
'-398': BigInteger;
'-397': BigInteger;
'-396': BigInteger;
'-395': BigInteger;
'-394': BigInteger;
'-393': BigInteger;
'-392': BigInteger;
'-391': BigInteger;
'-390': BigInteger;
'-389': BigInteger;
'-388': BigInteger;
'-387': BigInteger;
'-386': BigInteger;
'-385': BigInteger;
'-384': BigInteger;
'-383': BigInteger;
'-382': BigInteger;
'-381': BigInteger;
'-380': BigInteger;
'-379': BigInteger;
'-378': BigInteger;
'-377': BigInteger;
'-376': BigInteger;
'-375': BigInteger;
'-374': BigInteger;
'-373': BigInteger;
'-372': BigInteger;
'-371': BigInteger;
'-370': BigInteger;
'-369': BigInteger;
'-368': BigInteger;
'-367': BigInteger;
'-366': BigInteger;
'-365': BigInteger;
'-364': BigInteger;
'-363': BigInteger;
'-362': BigInteger;
'-361': BigInteger;
'-360': BigInteger;
'-359': BigInteger;
'-358': BigInteger;
'-357': BigInteger;
'-356': BigInteger;
'-355': BigInteger;
'-354': BigInteger;
'-353': BigInteger;
'-352': BigInteger;
'-351': BigInteger;
'-350': BigInteger;
'-349': BigInteger;
'-348': BigInteger;
'-347': BigInteger;
'-346': BigInteger;
'-345': BigInteger;
'-344': BigInteger;
'-343': BigInteger;
'-342': BigInteger;
'-341': BigInteger;
'-340': BigInteger;
'-339': BigInteger;
'-338': BigInteger;
'-337': BigInteger;
'-336': BigInteger;
'-335': BigInteger;
'-334': BigInteger;
'-333': BigInteger;
'-332': BigInteger;
'-331': BigInteger;
'-330': BigInteger;
'-329': BigInteger;
'-328': BigInteger;
'-327': BigInteger;
'-326': BigInteger;
'-325': BigInteger;
'-324': BigInteger;
'-323': BigInteger;
'-322': BigInteger;
'-321': BigInteger;
'-320': BigInteger;
'-319': BigInteger;
'-318': BigInteger;
'-317': BigInteger;
'-316': BigInteger;
'-315': BigInteger;
'-314': BigInteger;
'-313': BigInteger;
'-312': BigInteger;
'-311': BigInteger;
'-310': BigInteger;
'-309': BigInteger;
'-308': BigInteger;
'-307': BigInteger;
'-306': BigInteger;
'-305': BigInteger;
'-304': BigInteger;
'-303': BigInteger;
'-302': BigInteger;
'-301': BigInteger;
'-300': BigInteger;
'-299': BigInteger;
'-298': BigInteger;
'-297': BigInteger;
'-296': BigInteger;
'-295': BigInteger;
'-294': BigInteger;
'-293': BigInteger;
'-292': BigInteger;
'-291': BigInteger;
'-290': BigInteger;
'-289': BigInteger;
'-288': BigInteger;
'-287': BigInteger;
'-286': BigInteger;
'-285': BigInteger;
'-284': BigInteger;
'-283': BigInteger;
'-282': BigInteger;
'-281': BigInteger;
'-280': BigInteger;
'-279': BigInteger;
'-278': BigInteger;
'-277': BigInteger;
'-276': BigInteger;
'-275': BigInteger;
'-274': BigInteger;
'-273': BigInteger;
'-272': BigInteger;
'-271': BigInteger;
'-270': BigInteger;
'-269': BigInteger;
'-268': BigInteger;
'-267': BigInteger;
'-266': BigInteger;
'-265': BigInteger;
'-264': BigInteger;
'-263': BigInteger;
'-262': BigInteger;
'-261': BigInteger;
'-260': BigInteger;
'-259': BigInteger;
'-258': BigInteger;
'-257': BigInteger;
'-256': BigInteger;
'-255': BigInteger;
'-254': BigInteger;
'-253': BigInteger;
'-252': BigInteger;
'-251': BigInteger;
'-250': BigInteger;
'-249': BigInteger;
'-248': BigInteger;
'-247': BigInteger;
'-246': BigInteger;
'-245': BigInteger;
'-244': BigInteger;
'-243': BigInteger;
'-242': BigInteger;
'-241': BigInteger;
'-240': BigInteger;
'-239': BigInteger;
'-238': BigInteger;
'-237': BigInteger;
'-236': BigInteger;
'-235': BigInteger;
'-234': BigInteger;
'-233': BigInteger;
'-232': BigInteger;
'-231': BigInteger;
'-230': BigInteger;
'-229': BigInteger;
'-228': BigInteger;
'-227': BigInteger;
'-226': BigInteger;
'-225': BigInteger;
'-224': BigInteger;
'-223': BigInteger;
'-222': BigInteger;
'-221': BigInteger;
'-220': BigInteger;
'-219': BigInteger;
'-218': BigInteger;
'-217': BigInteger;
'-216': BigInteger;
'-215': BigInteger;
'-214': BigInteger;
'-213': BigInteger;
'-212': BigInteger;
'-211': BigInteger;
'-210': BigInteger;
'-209': BigInteger;
'-208': BigInteger;
'-207': BigInteger;
'-206': BigInteger;
'-205': BigInteger;
'-204': BigInteger;
'-203': BigInteger;
'-202': BigInteger;
'-201': BigInteger;
'-200': BigInteger;
'-199': BigInteger;
'-198': BigInteger;
'-197': BigInteger;
'-196': BigInteger;
'-195': BigInteger;
'-194': BigInteger;
'-193': BigInteger;
'-192': BigInteger;
'-191': BigInteger;
'-190': BigInteger;
'-189': BigInteger;
'-188': BigInteger;
'-187': BigInteger;
'-186': BigInteger;
'-185': BigInteger;
'-184': BigInteger;
'-183': BigInteger;
'-182': BigInteger;
'-181': BigInteger;
'-180': BigInteger;
'-179': BigInteger;
'-178': BigInteger;
'-177': BigInteger;
'-176': BigInteger;
'-175': BigInteger;
'-174': BigInteger;
'-173': BigInteger;
'-172': BigInteger;
'-171': BigInteger;
'-170': BigInteger;
'-169': BigInteger;
'-168': BigInteger;
'-167': BigInteger;
'-166': BigInteger;
'-165': BigInteger;
'-164': BigInteger;
'-163': BigInteger;
'-162': BigInteger;
'-161': BigInteger;
'-160': BigInteger;
'-159': BigInteger;
'-158': BigInteger;
'-157': BigInteger;
'-156': BigInteger;
'-155': BigInteger;
'-154': BigInteger;
'-153': BigInteger;
'-152': BigInteger;
'-151': BigInteger;
'-150': BigInteger;
'-149': BigInteger;
'-148': BigInteger;
'-147': BigInteger;
'-146': BigInteger;
'-145': BigInteger;
'-144': BigInteger;
'-143': BigInteger;
'-142': BigInteger;
'-141': BigInteger;
'-140': BigInteger;
'-139': BigInteger;
'-138': BigInteger;
'-137': BigInteger;
'-136': BigInteger;
'-135': BigInteger;
'-134': BigInteger;
'-133': BigInteger;
'-132': BigInteger;
'-131': BigInteger;
'-130': BigInteger;
'-129': BigInteger;
'-128': BigInteger;
'-127': BigInteger;
'-126': BigInteger;
'-125': BigInteger;
'-124': BigInteger;
'-123': BigInteger;
'-122': BigInteger;
'-121': BigInteger;
'-120': BigInteger;
'-119': BigInteger;
'-118': BigInteger;
'-117': BigInteger;
'-116': BigInteger;
'-115': BigInteger;
'-114': BigInteger;
'-113': BigInteger;
'-112': BigInteger;
'-111': BigInteger;
'-110': BigInteger;
'-109': BigInteger;
'-108': BigInteger;
'-107': BigInteger;
'-106': BigInteger;
'-105': BigInteger;
'-104': BigInteger;
'-103': BigInteger;
'-102': BigInteger;
'-101': BigInteger;
'-100': BigInteger;
'-99': BigInteger;
'-98': BigInteger;
'-97': BigInteger;
'-96': BigInteger;
'-95': BigInteger;
'-94': BigInteger;
'-93': BigInteger;
'-92': BigInteger;
'-91': BigInteger;
'-90': BigInteger;
'-89': BigInteger;
'-88': BigInteger;
'-87': BigInteger;
'-86': BigInteger;
'-85': BigInteger;
'-84': BigInteger;
'-83': BigInteger;
'-82': BigInteger;
'-81': BigInteger;
'-80': BigInteger;
'-79': BigInteger;
'-78': BigInteger;
'-77': BigInteger;
'-76': BigInteger;
'-75': BigInteger;
'-74': BigInteger;
'-73': BigInteger;
'-72': BigInteger;
'-71': BigInteger;
'-70': BigInteger;
'-69': BigInteger;
'-68': BigInteger;
'-67': BigInteger;
'-66': BigInteger;
'-65': BigInteger;
'-64': BigInteger;
'-63': BigInteger;
'-62': BigInteger;
'-61': BigInteger;
'-60': BigInteger;
'-59': BigInteger;
'-58': BigInteger;
'-57': BigInteger;
'-56': BigInteger;
'-55': BigInteger;
'-54': BigInteger;
'-53': BigInteger;
'-52': BigInteger;
'-51': BigInteger;
'-50': BigInteger;
'-49': BigInteger;
'-48': BigInteger;
'-47': BigInteger;
'-46': BigInteger;
'-45': BigInteger;
'-44': BigInteger;
'-43': BigInteger;
'-42': BigInteger;
'-41': BigInteger;
'-40': BigInteger;
'-39': BigInteger;
'-38': BigInteger;
'-37': BigInteger;
'-36': BigInteger;
'-35': BigInteger;
'-34': BigInteger;
'-33': BigInteger;
'-32': BigInteger;
'-31': BigInteger;
'-30': BigInteger;
'-29': BigInteger;
'-28': BigInteger;
'-27': BigInteger;
'-26': BigInteger;
'-25': BigInteger;
'-24': BigInteger;
'-23': BigInteger;
'-22': BigInteger;
'-21': BigInteger;
'-20': BigInteger;
'-19': BigInteger;
'-18': BigInteger;
'-17': BigInteger;
'-16': BigInteger;
'-15': BigInteger;
'-14': BigInteger;
'-13': BigInteger;
'-12': BigInteger;
'-11': BigInteger;
'-10': BigInteger;
'-9': BigInteger;
'-8': BigInteger;
'-7': BigInteger;
'-6': BigInteger;
'-5': BigInteger;
'-4': BigInteger;
'-3': BigInteger;
'-2': BigInteger;
'-1': BigInteger;
'0': BigInteger;
'1': BigInteger;
'2': BigInteger;
'3': BigInteger;
'4': BigInteger;
'5': BigInteger;
'6': BigInteger;
'7': BigInteger;
'8': BigInteger;
'9': BigInteger;
'10': BigInteger;
'11': BigInteger;
'12': BigInteger;
'13': BigInteger;
'14': BigInteger;
'15': BigInteger;
'16': BigInteger;
'17': BigInteger;
'18': BigInteger;
'19': BigInteger;
'20': BigInteger;
'21': BigInteger;
'22': BigInteger;
'23': BigInteger;
'24': BigInteger;
'25': BigInteger;
'26': BigInteger;
'27': BigInteger;
'28': BigInteger;
'29': BigInteger;
'30': BigInteger;
'31': BigInteger;
'32': BigInteger;
'33': BigInteger;
'34': BigInteger;
'35': BigInteger;
'36': BigInteger;
'37': BigInteger;
'38': BigInteger;
'39': BigInteger;
'40': BigInteger;
'41': BigInteger;
'42': BigInteger;
'43': BigInteger;
'44': BigInteger;
'45': BigInteger;
'46': BigInteger;
'47': BigInteger;
'48': BigInteger;
'49': BigInteger;
'50': BigInteger;
'51': BigInteger;
'52': BigInteger;
'53': BigInteger;
'54': BigInteger;
'55': BigInteger;
'56': BigInteger;
'57': BigInteger;
'58': BigInteger;
'59': BigInteger;
'60': BigInteger;
'61': BigInteger;
'62': BigInteger;
'63': BigInteger;
'64': BigInteger;
'65': BigInteger;
'66': BigInteger;
'67': BigInteger;
'68': BigInteger;
'69': BigInteger;
'70': BigInteger;
'71': BigInteger;
'72': BigInteger;
'73': BigInteger;
'74': BigInteger;
'75': BigInteger;
'76': BigInteger;
'77': BigInteger;
'78': BigInteger;
'79': BigInteger;
'80': BigInteger;
'81': BigInteger;
'82': BigInteger;
'83': BigInteger;
'84': BigInteger;
'85': BigInteger;
'86': BigInteger;
'87': BigInteger;
'88': BigInteger;
'89': BigInteger;
'90': BigInteger;
'91': BigInteger;
'92': BigInteger;
'93': BigInteger;
'94': BigInteger;
'95': BigInteger;
'96': BigInteger;
'97': BigInteger;
'98': BigInteger;
'99': BigInteger;
'100': BigInteger;
'101': BigInteger;
'102': BigInteger;
'103': BigInteger;
'104': BigInteger;
'105': BigInteger;
'106': BigInteger;
'107': BigInteger;
'108': BigInteger;
'109': BigInteger;
'110': BigInteger;
'111': BigInteger;
'112': BigInteger;
'113': BigInteger;
'114': BigInteger;
'115': BigInteger;
'116': BigInteger;
'117': BigInteger;
'118': BigInteger;
'119': BigInteger;
'120': BigInteger;
'121': BigInteger;
'122': BigInteger;
'123': BigInteger;
'124': BigInteger;
'125': BigInteger;
'126': BigInteger;
'127': BigInteger;
'128': BigInteger;
'129': BigInteger;
'130': BigInteger;
'131': BigInteger;
'132': BigInteger;
'133': BigInteger;
'134': BigInteger;
'135': BigInteger;
'136': BigInteger;
'137': BigInteger;
'138': BigInteger;
'139': BigInteger;
'140': BigInteger;
'141': BigInteger;
'142': BigInteger;
'143': BigInteger;
'144': BigInteger;
'145': BigInteger;
'146': BigInteger;
'147': BigInteger;
'148': BigInteger;
'149': BigInteger;
'150': BigInteger;
'151': BigInteger;
'152': BigInteger;
'153': BigInteger;
'154': BigInteger;
'155': BigInteger;
'156': BigInteger;
'157': BigInteger;
'158': BigInteger;
'159': BigInteger;
'160': BigInteger;
'161': BigInteger;
'162': BigInteger;
'163': BigInteger;
'164': BigInteger;
'165': BigInteger;
'166': BigInteger;
'167': BigInteger;
'168': BigInteger;
'169': BigInteger;
'170': BigInteger;
'171': BigInteger;
'172': BigInteger;
'173': BigInteger;
'174': BigInteger;
'175': BigInteger;
'176': BigInteger;
'177': BigInteger;
'178': BigInteger;
'179': BigInteger;
'180': BigInteger;
'181': BigInteger;
'182': BigInteger;
'183': BigInteger;
'184': BigInteger;
'185': BigInteger;
'186': BigInteger;
'187': BigInteger;
'188': BigInteger;
'189': BigInteger;
'190': BigInteger;
'191': BigInteger;
'192': BigInteger;
'193': BigInteger;
'194': BigInteger;
'195': BigInteger;
'196': BigInteger;
'197': BigInteger;
'198': BigInteger;
'199': BigInteger;
'200': BigInteger;
'201': BigInteger;
'202': BigInteger;
'203': BigInteger;
'204': BigInteger;
'205': BigInteger;
'206': BigInteger;
'207': BigInteger;
'208': BigInteger;
'209': BigInteger;
'210': BigInteger;
'211': BigInteger;
'212': BigInteger;
'213': BigInteger;
'214': BigInteger;
'215': BigInteger;
'216': BigInteger;
'217': BigInteger;
'218': BigInteger;
'219': BigInteger;
'220': BigInteger;
'221': BigInteger;
'222': BigInteger;
'223': BigInteger;
'224': BigInteger;
'225': BigInteger;
'226': BigInteger;
'227': BigInteger;
'228': BigInteger;
'229': BigInteger;
'230': BigInteger;
'231': BigInteger;
'232': BigInteger;
'233': BigInteger;
'234': BigInteger;
'235': BigInteger;
'236': BigInteger;
'237': BigInteger;
'238': BigInteger;
'239': BigInteger;
'240': BigInteger;
'241': BigInteger;
'242': BigInteger;
'243': BigInteger;
'244': BigInteger;
'245': BigInteger;
'246': BigInteger;
'247': BigInteger;
'248': BigInteger;
'249': BigInteger;
'250': BigInteger;
'251': BigInteger;
'252': BigInteger;
'253': BigInteger;
'254': BigInteger;
'255': BigInteger;
'256': BigInteger;
'257': BigInteger;
'258': BigInteger;
'259': BigInteger;
'260': BigInteger;
'261': BigInteger;
'262': BigInteger;
'263': BigInteger;
'264': BigInteger;
'265': BigInteger;
'266': BigInteger;
'267': BigInteger;
'268': BigInteger;
'269': BigInteger;
'270': BigInteger;
'271': BigInteger;
'272': BigInteger;
'273': BigInteger;
'274': BigInteger;
'275': BigInteger;
'276': BigInteger;
'277': BigInteger;
'278': BigInteger;
'279': BigInteger;
'280': BigInteger;
'281': BigInteger;
'282': BigInteger;
'283': BigInteger;
'284': BigInteger;
'285': BigInteger;
'286': BigInteger;
'287': BigInteger;
'288': BigInteger;
'289': BigInteger;
'290': BigInteger;
'291': BigInteger;
'292': BigInteger;
'293': BigInteger;
'294': BigInteger;
'295': BigInteger;
'296': BigInteger;
'297': BigInteger;
'298': BigInteger;
'299': BigInteger;
'300': BigInteger;
'301': BigInteger;
'302': BigInteger;
'303': BigInteger;
'304': BigInteger;
'305': BigInteger;
'306': BigInteger;
'307': BigInteger;
'308': BigInteger;
'309': BigInteger;
'310': BigInteger;
'311': BigInteger;
'312': BigInteger;
'313': BigInteger;
'314': BigInteger;
'315': BigInteger;
'316': BigInteger;
'317': BigInteger;
'318': BigInteger;
'319': BigInteger;
'320': BigInteger;
'321': BigInteger;
'322': BigInteger;
'323': BigInteger;
'324': BigInteger;
'325': BigInteger;
'326': BigInteger;
'327': BigInteger;
'328': BigInteger;
'329': BigInteger;
'330': BigInteger;
'331': BigInteger;
'332': BigInteger;
'333': BigInteger;
'334': BigInteger;
'335': BigInteger;
'336': BigInteger;
'337': BigInteger;
'338': BigInteger;
'339': BigInteger;
'340': BigInteger;
'341': BigInteger;
'342': BigInteger;
'343': BigInteger;
'344': BigInteger;
'345': BigInteger;
'346': BigInteger;
'347': BigInteger;
'348': BigInteger;
'349': BigInteger;
'350': BigInteger;
'351': BigInteger;
'352': BigInteger;
'353': BigInteger;
'354': BigInteger;
'355': BigInteger;
'356': BigInteger;
'357': BigInteger;
'358': BigInteger;
'359': BigInteger;
'360': BigInteger;
'361': BigInteger;
'362': BigInteger;
'363': BigInteger;
'364': BigInteger;
'365': BigInteger;
'366': BigInteger;
'367': BigInteger;
'368': BigInteger;
'369': BigInteger;
'370': BigInteger;
'371': BigInteger;
'372': BigInteger;
'373': BigInteger;
'374': BigInteger;
'375': BigInteger;
'376': BigInteger;
'377': BigInteger;
'378': BigInteger;
'379': BigInteger;
'380': BigInteger;
'381': BigInteger;
'382': BigInteger;
'383': BigInteger;
'384': BigInteger;
'385': BigInteger;
'386': BigInteger;
'387': BigInteger;
'388': BigInteger;
'389': BigInteger;
'390': BigInteger;
'391': BigInteger;
'392': BigInteger;
'393': BigInteger;
'394': BigInteger;
'395': BigInteger;
'396': BigInteger;
'397': BigInteger;
'398': BigInteger;
'399': BigInteger;
'400': BigInteger;
'401': BigInteger;
'402': BigInteger;
'403': BigInteger;
'404': BigInteger;
'405': BigInteger;
'406': BigInteger;
'407': BigInteger;
'408': BigInteger;
'409': BigInteger;
'410': BigInteger;
'411': BigInteger;
'412': BigInteger;
'413': BigInteger;
'414': BigInteger;
'415': BigInteger;
'416': BigInteger;
'417': BigInteger;
'418': BigInteger;
'419': BigInteger;
'420': BigInteger;
'421': BigInteger;
'422': BigInteger;
'423': BigInteger;
'424': BigInteger;
'425': BigInteger;
'426': BigInteger;
'427': BigInteger;
'428': BigInteger;
'429': BigInteger;
'430': BigInteger;
'431': BigInteger;
'432': BigInteger;
'433': BigInteger;
'434': BigInteger;
'435': BigInteger;
'436': BigInteger;
'437': BigInteger;
'438': BigInteger;
'439': BigInteger;
'440': BigInteger;
'441': BigInteger;
'442': BigInteger;
'443': BigInteger;
'444': BigInteger;
'445': BigInteger;
'446': BigInteger;
'447': BigInteger;
'448': BigInteger;
'449': BigInteger;
'450': BigInteger;
'451': BigInteger;
'452': BigInteger;
'453': BigInteger;
'454': BigInteger;
'455': BigInteger;
'456': BigInteger;
'457': BigInteger;
'458': BigInteger;
'459': BigInteger;
'460': BigInteger;
'461': BigInteger;
'462': BigInteger;
'463': BigInteger;
'464': BigInteger;
'465': BigInteger;
'466': BigInteger;
'467': BigInteger;
'468': BigInteger;
'469': BigInteger;
'470': BigInteger;
'471': BigInteger;
'472': BigInteger;
'473': BigInteger;
'474': BigInteger;
'475': BigInteger;
'476': BigInteger;
'477': BigInteger;
'478': BigInteger;
'479': BigInteger;
'480': BigInteger;
'481': BigInteger;
'482': BigInteger;
'483': BigInteger;
'484': BigInteger;
'485': BigInteger;
'486': BigInteger;
'487': BigInteger;
'488': BigInteger;
'489': BigInteger;
'490': BigInteger;
'491': BigInteger;
'492': BigInteger;
'493': BigInteger;
'494': BigInteger;
'495': BigInteger;
'496': BigInteger;
'497': BigInteger;
'498': BigInteger;
'499': BigInteger;
'500': BigInteger;
'501': BigInteger;
'502': BigInteger;
'503': BigInteger;
'504': BigInteger;
'505': BigInteger;
'506': BigInteger;
'507': BigInteger;
'508': BigInteger;
'509': BigInteger;
'510': BigInteger;
'511': BigInteger;
'512': BigInteger;
'513': BigInteger;
'514': BigInteger;
'515': BigInteger;
'516': BigInteger;
'517': BigInteger;
'518': BigInteger;
'519': BigInteger;
'520': BigInteger;
'521': BigInteger;
'522': BigInteger;
'523': BigInteger;
'524': BigInteger;
'525': BigInteger;
'526': BigInteger;
'527': BigInteger;
'528': BigInteger;
'529': BigInteger;
'530': BigInteger;
'531': BigInteger;
'532': BigInteger;
'533': BigInteger;
'534': BigInteger;
'535': BigInteger;
'536': BigInteger;
'537': BigInteger;
'538': BigInteger;
'539': BigInteger;
'540': BigInteger;
'541': BigInteger;
'542': BigInteger;
'543': BigInteger;
'544': BigInteger;
'545': BigInteger;
'546': BigInteger;
'547': BigInteger;
'548': BigInteger;
'549': BigInteger;
'550': BigInteger;
'551': BigInteger;
'552': BigInteger;
'553': BigInteger;
'554': BigInteger;
'555': BigInteger;
'556': BigInteger;
'557': BigInteger;
'558': BigInteger;
'559': BigInteger;
'560': BigInteger;
'561': BigInteger;
'562': BigInteger;
'563': BigInteger;
'564': BigInteger;
'565': BigInteger;
'566': BigInteger;
'567': BigInteger;
'568': BigInteger;
'569': BigInteger;
'570': BigInteger;
'571': BigInteger;
'572': BigInteger;
'573': BigInteger;
'574': BigInteger;
'575': BigInteger;
'576': BigInteger;
'577': BigInteger;
'578': BigInteger;
'579': BigInteger;
'580': BigInteger;
'581': BigInteger;
'582': BigInteger;
'583': BigInteger;
'584': BigInteger;
'585': BigInteger;
'586': BigInteger;
'587': BigInteger;
'588': BigInteger;
'589': BigInteger;
'590': BigInteger;
'591': BigInteger;
'592': BigInteger;
'593': BigInteger;
'594': BigInteger;
'595': BigInteger;
'596': BigInteger;
'597': BigInteger;
'598': BigInteger;
'599': BigInteger;
'600': BigInteger;
'601': BigInteger;
'602': BigInteger;
'603': BigInteger;
'604': BigInteger;
'605': BigInteger;
'606': BigInteger;
'607': BigInteger;
'608': BigInteger;
'609': BigInteger;
'610': BigInteger;
'611': BigInteger;
'612': BigInteger;
'613': BigInteger;
'614': BigInteger;
'615': BigInteger;
'616': BigInteger;
'617': BigInteger;
'618': BigInteger;
'619': BigInteger;
'620': BigInteger;
'621': BigInteger;
'622': BigInteger;
'623': BigInteger;
'624': BigInteger;
'625': BigInteger;
'626': BigInteger;
'627': BigInteger;
'628': BigInteger;
'629': BigInteger;
'630': BigInteger;
'631': BigInteger;
'632': BigInteger;
'633': BigInteger;
'634': BigInteger;
'635': BigInteger;
'636': BigInteger;
'637': BigInteger;
'638': BigInteger;
'639': BigInteger;
'640': BigInteger;
'641': BigInteger;
'642': BigInteger;
'643': BigInteger;
'644': BigInteger;
'645': BigInteger;
'646': BigInteger;
'647': BigInteger;
'648': BigInteger;
'649': BigInteger;
'650': BigInteger;
'651': BigInteger;
'652': BigInteger;
'653': BigInteger;
'654': BigInteger;
'655': BigInteger;
'656': BigInteger;
'657': BigInteger;
'658': BigInteger;
'659': BigInteger;
'660': BigInteger;
'661': BigInteger;
'662': BigInteger;
'663': BigInteger;
'664': BigInteger;
'665': BigInteger;
'666': BigInteger;
'667': BigInteger;
'668': BigInteger;
'669': BigInteger;
'670': BigInteger;
'671': BigInteger;
'672': BigInteger;
'673': BigInteger;
'674': BigInteger;
'675': BigInteger;
'676': BigInteger;
'677': BigInteger;
'678': BigInteger;
'679': BigInteger;
'680': BigInteger;
'681': BigInteger;
'682': BigInteger;
'683': BigInteger;
'684': BigInteger;
'685': BigInteger;
'686': BigInteger;
'687': BigInteger;
'688': BigInteger;
'689': BigInteger;
'690': BigInteger;
'691': BigInteger;
'692': BigInteger;
'693': BigInteger;
'694': BigInteger;
'695': BigInteger;
'696': BigInteger;
'697': BigInteger;
'698': BigInteger;
'699': BigInteger;
'700': BigInteger;
'701': BigInteger;
'702': BigInteger;
'703': BigInteger;
'704': BigInteger;
'705': BigInteger;
'706': BigInteger;
'707': BigInteger;
'708': BigInteger;
'709': BigInteger;
'710': BigInteger;
'711': BigInteger;
'712': BigInteger;
'713': BigInteger;
'714': BigInteger;
'715': BigInteger;
'716': BigInteger;
'717': BigInteger;
'718': BigInteger;
'719': BigInteger;
'720': BigInteger;
'721': BigInteger;
'722': BigInteger;
'723': BigInteger;
'724': BigInteger;
'725': BigInteger;
'726': BigInteger;
'727': BigInteger;
'728': BigInteger;
'729': BigInteger;
'730': BigInteger;
'731': BigInteger;
'732': BigInteger;
'733': BigInteger;
'734': BigInteger;
'735': BigInteger;
'736': BigInteger;
'737': BigInteger;
'738': BigInteger;
'739': BigInteger;
'740': BigInteger;
'741': BigInteger;
'742': BigInteger;
'743': BigInteger;
'744': BigInteger;
'745': BigInteger;
'746': BigInteger;
'747': BigInteger;
'748': BigInteger;
'749': BigInteger;
'750': BigInteger;
'751': BigInteger;
'752': BigInteger;
'753': BigInteger;
'754': BigInteger;
'755': BigInteger;
'756': BigInteger;
'757': BigInteger;
'758': BigInteger;
'759': BigInteger;
'760': BigInteger;
'761': BigInteger;
'762': BigInteger;
'763': BigInteger;
'764': BigInteger;
'765': BigInteger;
'766': BigInteger;
'767': BigInteger;
'768': BigInteger;
'769': BigInteger;
'770': BigInteger;
'771': BigInteger;
'772': BigInteger;
'773': BigInteger;
'774': BigInteger;
'775': BigInteger;
'776': BigInteger;
'777': BigInteger;
'778': BigInteger;
'779': BigInteger;
'780': BigInteger;
'781': BigInteger;
'782': BigInteger;
'783': BigInteger;
'784': BigInteger;
'785': BigInteger;
'786': BigInteger;
'787': BigInteger;
'788': BigInteger;
'789': BigInteger;
'790': BigInteger;
'791': BigInteger;
'792': BigInteger;
'793': BigInteger;
'794': BigInteger;
'795': BigInteger;
'796': BigInteger;
'797': BigInteger;
'798': BigInteger;
'799': BigInteger;
'800': BigInteger;
'801': BigInteger;
'802': BigInteger;
'803': BigInteger;
'804': BigInteger;
'805': BigInteger;
'806': BigInteger;
'807': BigInteger;
'808': BigInteger;
'809': BigInteger;
'810': BigInteger;
'811': BigInteger;
'812': BigInteger;
'813': BigInteger;
'814': BigInteger;
'815': BigInteger;
'816': BigInteger;
'817': BigInteger;
'818': BigInteger;
'819': BigInteger;
'820': BigInteger;
'821': BigInteger;
'822': BigInteger;
'823': BigInteger;
'824': BigInteger;
'825': BigInteger;
'826': BigInteger;
'827': BigInteger;
'828': BigInteger;
'829': BigInteger;
'830': BigInteger;
'831': BigInteger;
'832': BigInteger;
'833': BigInteger;
'834': BigInteger;
'835': BigInteger;
'836': BigInteger;
'837': BigInteger;
'838': BigInteger;
'839': BigInteger;
'840': BigInteger;
'841': BigInteger;
'842': BigInteger;
'843': BigInteger;
'844': BigInteger;
'845': BigInteger;
'846': BigInteger;
'847': BigInteger;
'848': BigInteger;
'849': BigInteger;
'850': BigInteger;
'851': BigInteger;
'852': BigInteger;
'853': BigInteger;
'854': BigInteger;
'855': BigInteger;
'856': BigInteger;
'857': BigInteger;
'858': BigInteger;
'859': BigInteger;
'860': BigInteger;
'861': BigInteger;
'862': BigInteger;
'863': BigInteger;
'864': BigInteger;
'865': BigInteger;
'866': BigInteger;
'867': BigInteger;
'868': BigInteger;
'869': BigInteger;
'870': BigInteger;
'871': BigInteger;
'872': BigInteger;
'873': BigInteger;
'874': BigInteger;
'875': BigInteger;
'876': BigInteger;
'877': BigInteger;
'878': BigInteger;
'879': BigInteger;
'880': BigInteger;
'881': BigInteger;
'882': BigInteger;
'883': BigInteger;
'884': BigInteger;
'885': BigInteger;
'886': BigInteger;
'887': BigInteger;
'888': BigInteger;
'889': BigInteger;
'890': BigInteger;
'891': BigInteger;
'892': BigInteger;
'893': BigInteger;
'894': BigInteger;
'895': BigInteger;
'896': BigInteger;
'897': BigInteger;
'898': BigInteger;
'899': BigInteger;
'900': BigInteger;
'901': BigInteger;
'902': BigInteger;
'903': BigInteger;
'904': BigInteger;
'905': BigInteger;
'906': BigInteger;
'907': BigInteger;
'908': BigInteger;
'909': BigInteger;
'910': BigInteger;
'911': BigInteger;
'912': BigInteger;
'913': BigInteger;
'914': BigInteger;
'915': BigInteger;
'916': BigInteger;
'917': BigInteger;
'918': BigInteger;
'919': BigInteger;
'920': BigInteger;
'921': BigInteger;
'922': BigInteger;
'923': BigInteger;
'924': BigInteger;
'925': BigInteger;
'926': BigInteger;
'927': BigInteger;
'928': BigInteger;
'929': BigInteger;
'930': BigInteger;
'931': BigInteger;
'932': BigInteger;
'933': BigInteger;
'934': BigInteger;
'935': BigInteger;
'936': BigInteger;
'937': BigInteger;
'938': BigInteger;
'939': BigInteger;
'940': BigInteger;
'941': BigInteger;
'942': BigInteger;
'943': BigInteger;
'944': BigInteger;
'945': BigInteger;
'946': BigInteger;
'947': BigInteger;
'948': BigInteger;
'949': BigInteger;
'950': BigInteger;
'951': BigInteger;
'952': BigInteger;
'953': BigInteger;
'954': BigInteger;
'955': BigInteger;
'956': BigInteger;
'957': BigInteger;
'958': BigInteger;
'959': BigInteger;
'960': BigInteger;
'961': BigInteger;
'962': BigInteger;
'963': BigInteger;
'964': BigInteger;
'965': BigInteger;
'966': BigInteger;
'967': BigInteger;
'968': BigInteger;
'969': BigInteger;
'970': BigInteger;
'971': BigInteger;
'972': BigInteger;
'973': BigInteger;
'974': BigInteger;
'975': BigInteger;
'976': BigInteger;
'977': BigInteger;
'978': BigInteger;
'979': BigInteger;
'980': BigInteger;
'981': BigInteger;
'982': BigInteger;
'983': BigInteger;
'984': BigInteger;
'985': BigInteger;
'986': BigInteger;
'987': BigInteger;
'988': BigInteger;
'989': BigInteger;
'990': BigInteger;
'991': BigInteger;
'992': BigInteger;
'993': BigInteger;
'994': BigInteger;
'995': BigInteger;
'996': BigInteger;
'997': BigInteger;
'998': BigInteger;
'999': BigInteger;
}
interface BaseArray {
value: number[],
isNegative: boolean
}
} | the_stack |
import { docsUrl } from "gen/gocd_version";
import { MithrilComponent, MithrilViewComponent } from "jsx/mithril-component";
import _ from "lodash";
import m from "mithril";
import Stream from "mithril/stream";
import { ConfigRepo, ParseInfo } from "models/config_repos/types";
import { PluginInfo } from "models/shared/plugin_infos_new/plugin_info";
import { Anchor, ScrollManager } from "views/components/anchor/anchor";
import { Code } from "views/components/code";
import { CollapsiblePanel } from "views/components/collapsible_panel";
import { FlashMessage, MessageType } from "views/components/flash_message";
import { HeaderIcon } from "views/components/header_icon";
import { Delete, Edit, IconGroup, Refresh } from "views/components/icons";
import { KeyValuePair } from "views/components/key_value_pair";
import { Link } from "views/components/link";
import { ShowRulesWidget } from "views/components/rules/show_rules_widget";
import { RequiresPluginInfos } from "views/pages/page_operations";
import { allAttributes, resolveHumanReadableAttributes, userDefinedProperties } from "./config_repo_attribute_helper";
import { CRResult } from "./config_repo_result";
import { ConfigRepoVM, CRVMAware, WebhookUrlGenerator } from "./config_repo_view_model";
import styles from "./index.scss";
import { WebhookSuggestions } from "./webhook_suggestions";
interface CollectionAttrs extends RequiresPluginInfos {
models: Stream<ConfigRepoVM[]>;
flushEtag: () => void;
sm: ScrollManager;
urlGenerator: WebhookUrlGenerator;
}
interface SingleAttrs extends CRVMAware {
flushEtag: () => void;
pluginInfo?: PluginInfo;
sm: ScrollManager;
page: WebhookUrlGenerator;
}
class HeaderWidget extends MithrilViewComponent<SingleAttrs> {
private static readonly MAX_COMMIT_MSG_LENGTH: number = 84;
private static readonly MAX_USERNAME_AND_REVISION_LENGTH: number = 40;
view(vnode: m.Vnode<SingleAttrs>): m.Children | void | null {
const repo = vnode.attrs.vm.repo;
const materialUrl = repo.material().materialUrl();
return [
this.pluginIcon(vnode.attrs.pluginInfo),
<div class={styles.headerTitle}>
<h4 data-test-id="config-repo-header" class={styles.headerTitleText}>{repo.id()}</h4>
<span class={styles.headerTitleUrl}>{materialUrl}</span>
</div>,
<div>{this.latestCommitDetails(repo.lastParse()!)}</div>
];
}
private latestCommitDetails(lastParsedCommit: ParseInfo | null) {
let parseStatus: m.Children = "This config repository was never parsed";
if (lastParsedCommit && lastParsedCommit.latestParsedModification) {
const latestParsedModification = lastParsedCommit.latestParsedModification;
const comment = _.truncate(latestParsedModification.comment,
{length: HeaderWidget.MAX_COMMIT_MSG_LENGTH});
const username = _.truncate(latestParsedModification.username,
{length: HeaderWidget.MAX_USERNAME_AND_REVISION_LENGTH});
const revision = _.truncate(latestParsedModification.revision,
{length: HeaderWidget.MAX_USERNAME_AND_REVISION_LENGTH});
parseStatus = (
<div class={styles.commitInfo}>
<span class={styles.comment}>
{comment}
</span>
<div class={styles.committerInfo}>
<span class={styles.committer}>{username}</span> | {revision}</div>
</div>
);
}
return parseStatus;
}
private pluginIcon(pluginInfo?: PluginInfo) {
if (pluginInfo && pluginInfo.imageUrl) {
return <HeaderIcon name="Plugin Icon" imageUrl={pluginInfo.imageUrl}/>;
} else {
return <HeaderIcon name="Plugin does not have an icon"/>;
}
}
}
interface SectionHeaderAttrs {
title: m.Children;
image?: m.Children;
titleTestId?: string;
}
class SectionHeader extends MithrilViewComponent<SectionHeaderAttrs> {
view(vnode: m.Vnode<SectionHeaderAttrs>) {
return <h3 class={styles.sectionHeader} data-test-id={vnode.attrs.titleTestId}>
{vnode.attrs.image}
<span class={styles.sectionHeaderTitle}>{vnode.attrs.title}</span>
</h3>;
}
}
interface ActionsAttrs extends CRVMAware {
flushEtag: () => void;
inProgress: boolean;
configRepoHasErrors: boolean;
can_administer: boolean;
title: string;
}
class CRPanelActions extends MithrilViewComponent<ActionsAttrs> {
view(vnode: m.Vnode<ActionsAttrs>): m.Children {
const vm = vnode.attrs.vm;
let statusIcon;
if (vnode.attrs.inProgress) {
statusIcon = <span class={styles.configRepoUpdateInProgress} data-test-id="repo-update-in-progress-icon"/>;
} else if (!vnode.attrs.configRepoHasErrors) {
statusIcon = <span class={styles.configRepoSuccessState} data-test-id="repo-success-state"/>;
}
return [
statusIcon,
<IconGroup>
<Refresh data-test-id="config-repo-refresh"
title={vnode.attrs.title}
disabled={!vnode.attrs.can_administer}
onclick={(e: MouseEvent) => vm.reparseRepo(e).then(vnode.attrs.flushEtag)}/>
<Edit data-test-id="config-repo-edit" title={vnode.attrs.title} disabled={!vnode.attrs.can_administer} onclick={vm.showEditModal}/>
<Delete data-test-id="config-repo-delete" title={vnode.attrs.title} disabled={!vnode.attrs.can_administer} onclick={vm.showDeleteModal}/>
</IconGroup>];
}
}
interface WarningAttrs {
parseInfo: ParseInfo | null;
pluginInfo?: PluginInfo;
}
class MaybeWarning extends MithrilViewComponent<WarningAttrs> {
view(vnode: m.Vnode<WarningAttrs>) {
const parseInfo = vnode.attrs.parseInfo;
const pluginInfo = vnode.attrs.pluginInfo;
if (!pluginInfo) {
return <div class={styles.errorMessage}>
<FlashMessage type={MessageType.alert} message="This plugin is missing."/>
</div>;
} else {
if (_.isEmpty(parseInfo)) {
return <FlashMessage type={MessageType.info} message="This configuration repository has not been parsed yet."/>;
} else if (parseInfo && parseInfo.error() && !parseInfo.latestParsedModification) {
return <FlashMessage type={MessageType.alert}>
There was an error parsing this configuration repository:
<Code>{parseInfo.error()}</Code>
</FlashMessage>;
}
}
}
}
class ConfigRepoWidget extends MithrilComponent<SingleAttrs> {
expanded: Stream<boolean> = Stream();
oninit(vnode: m.Vnode<SingleAttrs, {}>) {
const {sm, vm, pluginInfo} = vnode.attrs;
const repo = vm.repo;
const parseInfo = repo.lastParse();
const linked = sm.getTarget() === repo.id();
// set the initial state of the collapsible panel; alternative to setting `expanded` attribute
// and, perhaps, more obvious that this is only matters for first load
this.expanded(linked || !pluginInfo || _.isEmpty(parseInfo) || !!parseInfo!.error());
}
view(vnode: m.Vnode<SingleAttrs>): m.Children | void | null {
const {sm, vm, page, pluginInfo} = vnode.attrs;
const repo = vm.repo;
const parseInfo = repo.lastParse()!;
const maybeWarning = <MaybeWarning parseInfo={parseInfo} pluginInfo={pluginInfo}/>;
const configRepoHasErrors = !pluginInfo || _.isEmpty(parseInfo) || !!parseInfo!.error();
const title = !repo.canAdminister() ? "You are not authorised to perform this action!" : "";
const auto = repo.material().attributes()!.autoUpdate();
return <Anchor id={repo.id()} sm={sm} onnavigate={() => this.expanded(true)}>
<CollapsiblePanel error={configRepoHasErrors}
header={<HeaderWidget {...vnode.attrs}/>}
dataTestId={"config-repo-details-panel"}
actions={<CRPanelActions configRepoHasErrors={configRepoHasErrors}
inProgress={repo.materialUpdateInProgress()}
can_administer={repo.canAdminister()}
flushEtag={vnode.attrs.flushEtag}
title={title}
vm={vm}/>}
vm={this}
tagColor={auto ? void 0 : "b"}
onexpand={() => vm.notify("expand")}>
{maybeWarning}
{this.webhookSuggestions(repo, page)}
{this.renderedConfigs(parseInfo, vm)}
{this.latestModificationDetails(parseInfo)}
{this.lastGoodModificationDetails(parseInfo)}
{this.configRepoMetaConfigDetails(repo.id(), repo.pluginId())}
{this.materialConfigDetails(repo)}
{this.userPropertiesDetails(repo)}
<ShowRulesWidget rules={repo.rules}/>
</CollapsiblePanel>
</Anchor>;
}
private renderedConfigs(parseInfo: ParseInfo | null, vm: ConfigRepoVM): m.Children {
if (parseInfo) {
if (this.expanded()) {
vm.notify("expand");
}
return <CRResult vm={vm} />;
}
}
private webhookSuggestions(repo: ConfigRepo, page: WebhookUrlGenerator) {
if (!repo.material().attributes()!.autoUpdate()) {
return <WebhookSuggestions repoId={repo.id()} page={page} />;
}
}
private lastGoodModificationDetails(parseInfo: ParseInfo | null): m.Children {
if (parseInfo && parseInfo.goodRevision() === parseInfo.latestRevision()) {
// it's redundant to print this when good === latest
return;
}
if (parseInfo && parseInfo.goodModification) {
const attrs = resolveHumanReadableAttributes(parseInfo.goodModification);
const checkIcon = <span class={styles.goodModificationIcon}
title={`Last parsed with revision ${parseInfo.goodModification.revision}`}/>;
return <div data-test-id="config-repo-good-modification-panel">
<SectionHeader title="Last known good commit currently being used" image={checkIcon}/>
<div class={styles.configRepoProperties}><KeyValuePair data={attrs}/></div>
</div>;
}
}
private latestModificationDetails(parseInfo: ParseInfo | null): m.Children {
if (parseInfo && parseInfo.latestParsedModification) {
const attrs = resolveHumanReadableAttributes(parseInfo.latestParsedModification);
let statusIcon = styles.goodModificationIcon;
if (parseInfo.error()) {
attrs.set("Error", <code class={styles.parseErrorText}>{parseInfo.error()}</code>);
statusIcon = styles.errorLastModificationIcon;
}
return <div data-test-id="config-repo-latest-modification-panel">
<SectionHeader title={"Latest commit in the repository"}
image={<span class={statusIcon}
title={`Last parsed with revision ${parseInfo.latestParsedModification.revision}`}/>}/>
<div class={styles.configRepoProperties}><KeyValuePair data={attrs}/></div>
</div>;
}
}
private configRepoMetaConfigDetails(id: string, pluginId: string) {
return <div data-test-id="config-repo-plugin-panel">
<SectionHeader title="Config Repository Configurations"/>
<div class={styles.configRepoProperties}>
<KeyValuePair data={new Map([["Name", id], ["Plugin Id", pluginId]])}/>
</div>
</div>;
}
private materialConfigDetails(repo: ConfigRepo) {
return <div data-test-id="config-repo-material-panel">
<SectionHeader title="Material"/>
<div class={styles.configRepoProperties}><KeyValuePair data={allAttributes(repo)}/></div>
</div>;
}
private userPropertiesDetails(repo: ConfigRepo) {
return <div data-test-id="config-repo-user-properties-panel">
<SectionHeader title="User-defined Properties"/>
<div class={styles.configRepoProperties}><KeyValuePair data={userDefinedProperties(repo)} whenEmpty={<em>No properties have been defined.</em>}/></div>
</div>;
}
}
export class ConfigReposWidget extends MithrilViewComponent<CollectionAttrs> {
public static helpText() {
return <ul>
<li>Click on "Add" to add a new config repository.</li>
<li>GoCD can utilize the pipeline definitions stored in an external source code repository (either in your application’s repository, or in a
separate repository).
</li>
<li>You can read more about config repositories from <Link target="_blank" href={docsUrl('advanced_usage/pipelines_as_code.html')}>here</Link>.
</li>
</ul>;
}
view(vnode: m.Vnode<CollectionAttrs>): m.Children | void | null {
const models = vnode.attrs.models();
const configRepoUrl = "/advanced_usage/pipelines_as_code.html";
const docLink = <span data-test-id="doc-link">
<Link href={docsUrl(configRepoUrl)} target="_blank" externalLinkIcon={true}>
Learn More
</Link>
</span>;
const scrollManager = vnode.attrs.sm;
if (scrollManager.hasTarget()) {
const target = scrollManager.getTarget();
const hasTarget = models.some((config) => config.repo.id() === target);
if (!hasTarget) {
const msg = `Either '${target}' config repository has not been set up or you are not authorized to view the same.`;
return <FlashMessage dataTestId="anchor-config-repo-not-present" type={MessageType.alert}>
{msg} {docLink}
</FlashMessage>;
}
}
if (!models.length) {
return [
<FlashMessage type={MessageType.info}>
Either no config repositories have been set up or you are not authorized to view the same. {docLink}
</FlashMessage>,
<div className={styles.tips}>
{ConfigReposWidget.helpText()}
</div>
];
}
return <div>
{models.map((vm: any) => {
const repo = vm.repo;
const pluginInfo = _.find(vnode.attrs.pluginInfos(), {id: repo.pluginId()});
return <ConfigRepoWidget key={repo.id()}
flushEtag={vnode.attrs.flushEtag}
vm={vm}
pluginInfo={pluginInfo}
page={vnode.attrs.urlGenerator}
sm={vnode.attrs.sm}/>;
})}
</div>;
}
} | the_stack |
import { ReactNode, MouseEvent } from 'react';
import {
BUY,
SELL,
CATEGORY_PARAM_NAME,
TAGS_PARAM_NAME,
} from 'modules/common/constants';
import {
MARKET_ID_PARAM_NAME,
RETURN_PARAM_NAME,
OUTCOME_ID_PARAM_NAME,
CREATE_MARKET_FORM_PARAM_NAME,
} from './routes/constants/param-names';
import { AnyAction } from 'redux';
import type { Getters, PayoutNumeratorValue } from '@augurproject/sdk';
import type { TransactionMetadataParams, EthersSigner } from '@augurproject/contract-dependencies-ethers';
import type { BigNumber } from 'utils/create-big-number';
import type { Template } from '@augurproject/templates';
import { JsonRpcProvider } from "ethers/providers";
export enum SizeTypes {
SMALL = 'small',
NORMAL = 'normal',
LARGE = 'large',
}
export interface TextLink {
text: string;
link?: string;
linkText?: string;
lighten?: boolean;
}
export interface TextObject {
title: string;
subheader: TextLink[];
}
export interface Alert {
id: string;
uniqueId: string;
toast: boolean;
title: string;
name: string;
description: string;
timestamp: number;
href: string;
action: any;
status: string;
seen: boolean;
level: string;
params: object;
}
export interface TimezoneDateObject {
formattedUtc: string;
formattedLocalShortDateTimeWithTimezone: string;
timestamp: number;
}
export interface DateFormattedObject {
value: Date;
formattedUtcShortTime: string;
formattedShortTime: string;
formattedLocalShortDate: string;
formattedLocalShortWithUtcOffset: string;
formattedLocalShortDateSecondary: string;
timestamp: number;
utcLocalOffset: number;
clockTimeLocal: string;
formattedLocalShortDateTimeWithTimezone: string;
formattedLocalShortDateTimeNoTimezone: string;
formattedSimpleData: string;
formattedUtcShortDate: string;
clockTimeUtc: string;
formattedUtc: string;
formattedShortUtc: string;
}
export interface ValueLabelPair {
label: string;
value: string | FormattedNumber;
useFull?: boolean;
}
export interface CoreStats {
availableFunds: ValueLabelPair;
frozenFunds: ValueLabelPair;
totalFunds: ValueLabelPair;
realizedPL: ValueLabelPair;
}
export interface MarketInfos {
[marketId: string]: Getters.Markets.MarketInfo;
}
export interface Outcomes extends Getters.Markets.MarketInfoOutcome {
name?: string;
}
export interface ConsensusFormatted extends PayoutNumeratorValue {
winningOutcome: string | null;
outcomeName: string | null;
}
export interface OutcomeFormatted extends Getters.Markets.MarketInfoOutcome {
marketId: string;
description: string;
lastPricePercent: FormattedNumber | null;
lastPrice: FormattedNumber | null;
volumeFormatted: FormattedNumber;
isTradeable: boolean;
}
export interface MarketData extends Getters.Markets.MarketInfo {
marketId: string;
marketStatus: string;
defaultSelectedOutcomeId: number;
minPriceBigNumber: BigNumber;
maxPriceBigNumber: BigNumber;
noShowBondAmountFormatted: FormattedNumber;
creationTimeFormatted: DateFormattedObject;
endTimeFormatted: DateFormattedObject;
reportingFeeRatePercent: FormattedNumber;
marketCreatorFeeRatePercent: FormattedNumber;
settlementFeePercent: FormattedNumber;
openInterestFormatted: FormattedNumber;
volumeFormatted: FormattedNumber;
unclaimedCreatorFeesFormatted: FormattedNumber;
marketCreatorFeesCollectedFormatted: FormattedNumber;
finalizationTimeFormatted: DateFormattedObject | null;
isArchived: boolean;
// TODO: add this to getter Getters.Markets.MarketInfo
// disputeInfo: object; this needs to get filled in on getter
consensusFormatted: ConsensusFormatted | null;
outcomesFormatted: OutcomeFormatted[];
isTemplate: boolean;
pending?: boolean;
status?: string;
hasPendingLiquidityOrders?: boolean;
}
export interface ForkingInfo {
forkEndTime: number;
forkAttoReputationGoal: BigNumber;
forkingMarket: string;
forkAttoThreshold: BigNumber;
isForkingMarketFinalized: boolean;
winningChildUniverseId?: string;
}
export interface Universe extends Getters.Universe.UniverseDetails {
disputeWindow: Getters.Universe.DisputeWindow;
forkingInfo?: ForkingInfo;
forkEndTime?: string;
timeframeData?: Getters.Platform.PlatformActivityStatsResult;
maxMarketEndTime?: number;
}
export interface UserReports {
markets?: {
[universeId: string]: string;
};
}
export interface FormattedNumber {
fullPrecision: number | string;
roundedValue: BigNumber;
roundedFormatted: string;
formatted: string;
formattedValue: number | string;
denomination: string;
minimized: string;
value: number;
rounded: number | string;
full: number | string;
percent: number | string;
}
export interface FormattedNumberOptions {
decimals?: number;
decimalsRounded?: number;
denomination?: Function;
roundUp?: boolean;
roundDown?: boolean;
positiveSign?: boolean;
zeroStyled?: boolean;
minimized?: boolean;
blankZero?: boolean;
bigUnitPostfix?: boolean;
removeComma?: boolean;
}
export interface CreateMarketData {
id?: string;
txParams: TransactionMetadataParams;
endTime: DateFormattedObject;
description: string;
hash: string;
pending: boolean;
recentlyTraded: DateFormattedObject;
creationTime: DateFormattedObject;
marketType: string;
pendingId: string;
orderBook?: Getters.Markets.OutcomeOrderBook;
}
export interface PendingQueue {
[queueName: string]: {
[pendingId: string]: {
status: string;
blockNumber: number;
hash: string;
parameters?: UIOrder | NewMarket;
data: CreateMarketData;
};
};
}
export interface PendingOrders {
[marketId: string]: UIOrder[];
}
export interface QuantityOrderBookOrder
extends Getters.Markets.MarketOrderBookOrder {
quantityScale: number;
percent: number;
mySize: string;
price: string;
cumulativeShares: string;
}
export interface QuantityOutcomeOrderBook {
spread: string | BigNumber | null;
bids: QuantityOrderBookOrder[];
asks: QuantityOrderBookOrder[];
}
export interface OutcomeTestTradingOrder {
[outcomeId: number]: TestTradingOrder[];
}
export interface TestTradingOrder {
disappear: boolean;
avgPrice: FormattedNumber;
cumulativeShares: string;
id: string;
mySize: string;
orderEstimate: BigNumber;
outcomeId: string;
outcomeName: string;
price: string;
quantity: string;
shares: string;
sharesEscrowed: FormattedNumber;
tokensEscrowed: FormattedNumber;
type: string;
unmatchedShares: FormattedNumber;
}
export interface OrderBooks {
[marketId: string]: Getters.Markets.MarketOrderBook;
}
export interface IndividualOutcomeOrderBook {
spread: string | BigNumber | null;
bids: Getters.Markets.MarketOrderBookOrder[];
asks: Getters.Markets.MarketOrderBookOrder[];
}
export interface MyPositionsSummary {
currentValue: FormattedNumber;
totalPercent: FormattedNumber;
totalReturns: FormattedNumber;
valueChange: FormattedNumber;
valueChange24Hr: FormattedNumber;
}
export interface Notification {
id: string;
type: string;
isImportant: boolean;
redIcon?: boolean;
isNew: boolean;
title: string;
buttonLabel: string;
buttonAction: ButtonActionType;
Template: ReactNode;
market: MarketData;
markets: string[];
claimReportingFees?: object;
totalProceeds?: number;
queueName?: string;
queueId?: string;
hideCheckbox?: boolean;
hideNotification?: boolean;
}
export interface OrderStatus {
orderId: string;
status: string;
marketId: string;
outcome: any;
orderTypeLabel: string;
}
export interface OrderCancellations {
[orderId: string]: { status: string };
}
export interface UIOrder {
id: string;
outcomeName: string;
outcomeId: number;
marketId: string;
amount: string;
price: string;
fullPrecisionAmount: string;
fullPrecisionPrice: string;
type: string;
orderEstimate?: string;
cumulativeShares?: number;
status?: string;
hash?: string;
numTicks: number;
minPrice: string;
creationTime?: DateFormattedObject;
blockNumber?: number;
}
export interface CreateLiquidityOrders {
marketId: string;
chunkOrders: boolean;
}
export interface LiquidityOrders {
[txParamHash: string]: {
[outcome: number]: LiquidityOrder[];
};
}
export interface LiquidityOrder {
id?: string;
outcome?: string; // TODO: need to be consistent with outcome naming and type
index?: number;
quantity: BigNumber;
price: BigNumber;
type: string;
orderEstimate: BigNumber;
outcomeName: string;
outcomeId: number;
status?: string;
hash?: string;
mySize?: string;
cumulativeShares?: string;
shares: string;
}
export interface NewMarketPropertiesValidations {
description?: string;
categories?: string[];
type?: string;
designatedReporterType?: string;
designatedReporterAddress?: string;
setEndTime?: string;
hour?: string;
minute?: string;
meridiem?: string;
outcomes?: string | string[];
settlementFee?: string;
affiliateFee?: string;
inputs?: NewMarketPropertiesValidations[];
}
export interface NewMarketPropertyValidations {
settlementFee?: string;
scalarDenomination?: string;
affiliateFee?: string;
inputs?: NewMarketPropertiesValidations[];
outcomes?: string | string[];
}
export interface DateTimeComponents {
endTime: number;
endTimeFormatted: DateFormattedObject;
setEndTime: number;
hour: string;
minute: string;
meridiem: string;
offsetName: string;
offset: number;
timezone: string;
}
export interface NewMarket {
uniqueId: string;
isValid: boolean;
validations: NewMarketPropertiesValidations | NewMarketPropertyValidations;
currentStep: number;
type: string;
outcomes: string[];
outcomesFormatted: OutcomeFormatted[];
scalarBigNum: string;
scalarDenomination: string;
description: string;
designatedReporterType: string;
designatedReporterAddress: string;
minPrice: string;
maxPrice: string;
endTime: number;
endTimeFormatted: DateFormattedObject;
setEndTime: number;
tickSize: number;
numTicks: number;
hour: string;
minute: string;
meridiem: string;
marketType: string;
detailsText: string;
navCategories: string[];
categories: string[];
settlementFee: number;
settlementFeePercent: FormattedNumber;
affiliateFee: number;
orderBook: { [outcome: number]: LiquidityOrder[] };
orderBookSorted: { [outcome: number]: LiquidityOrder[] };
minPriceBigNumber: BigNumber;
maxPriceBigNumber: BigNumber;
initialLiquidityDai: BigNumber;
initialLiquidityGas: BigNumber;
creationError: string;
offsetName: string;
offset: number;
timezone: string;
template: Template;
}
export interface LinkContent {
content: string;
link?: string;
}
export interface Draft {
uniqueId: string;
created: number;
updated: number;
isValid: boolean;
validations:
| NewMarketPropertiesValidations[]
| NewMarketPropertyValidations[];
currentStep: number;
type: string;
outcomes: string[];
scalarBigNum: string;
scalarDenomination: string;
description: string;
designatedReporterType: string;
designatedReporterAddress: string;
minPrice: string;
maxPrice: string;
endTime: number;
tickSize: string;
hour: string;
minute: string;
meridiem: string;
marketType: string;
detailsText: string;
categories: string[];
settlementFee: number;
affiliateFee: number;
orderBook: { [outcome: number]: LiquidityOrder[] };
orderBookSorted: { [outcome: number]: LiquidityOrder[] };
initialLiquidityDai: any; // TODO: big number type
initialLiquidityGas: any; // TODO: big number type
creationError: string;
template: Template;
}
export interface Drafts {
[uniqueId: string]: Draft;
}
export interface Analytics {
[id: string]: Analytic;
}
export interface Analytic {
type: string;
eventName: string;
payload: AnalyticPayload;
}
export interface AnalyticPayload {
addedTimestamp: number;
userAgent: string;
}
export interface MarketsList {
isSearching: boolean;
meta: {
filteredOutCount: number;
marketCount: number;
categories: object;
};
selectedCategories: string[];
selectedCategory: string;
marketCardFormat: string;
isSearchInPlace: boolean;
}
export interface DefaultOrderProperties {
orderPrice: string;
orderQuantity: string;
selectedNav: string;
}
export interface LoadReportingMarketsOptions {
limit: number;
offset: number;
userPortfolioAddress?: string;
sortByRepAmount?: boolean;
sortByDisputeRounds?: boolean;
search?: string;
reportingStates?: string[];
}
export interface ReportingListState {
[reportingState: string]: {
marketIds: string[];
params: Partial<LoadReportingMarketsOptions>;
isLoading: boolean;
};
}
export interface FilledOrders {
[account: string]: Getters.Trading.MarketTradingHistory;
}
export interface OpenOrders {
[account: string]: Getters.Trading.Orders;
}
export interface GasPriceInfo {
average: number;
fast: number;
safeLow: number;
userDefinedGasPrice: number;
}
export enum INVALID_OPTIONS {
Show = 'show',
Hide = 'hide',
}
export interface FilterSortOptions {
marketFilter: string;
sortBy: string;
maxFee: string;
maxLiquiditySpread: string;
includeInvalidMarkets: INVALID_OPTIONS;
transactionPeriod: string;
templateFilter: string;
marketTypeFilter: string;
limit: number;
offset: number;
}
export interface Favorite {
[marketId: string]: number;
}
export interface QueryEndpoints {
ethereum_node_http?: string;
ethereum_node_ws?: string;
[MARKET_ID_PARAM_NAME]?: string;
[OUTCOME_ID_PARAM_NAME]?: string;
[RETURN_PARAM_NAME]?: string;
[CATEGORY_PARAM_NAME]?: string;
[TAGS_PARAM_NAME]?: string;
[CREATE_MARKET_FORM_PARAM_NAME]?: string;
}
export interface Endpoints {
ethereumNodeHTTP: string;
ethereumNodeWS: string;
}
export interface Connection {
isConnected: boolean;
isReconnectionPaused: boolean;
canHotload: boolean;
}
export interface Category {
categoryName: string;
nonFinalizedOpenInterest: string;
openInterest: string;
tags: Array<string>;
}
export interface Blockchain {
currentBlockNumber: number;
lastSyncedBlockNumber: number;
blocksBehindCurrent: number;
percentSynced: string;
currentAugurTimestamp: number;
}
export interface AppStatus {
isMobile?: boolean;
isMobileSmall?: boolean;
isHelpMenuOpen: boolean;
ethToDaiRate: FormattedNumber;
repToDaiRate: FormattedNumber;
usdtToDaiRate: FormattedNumber;
usdcToDaiRate: FormattedNumber;
zeroXEnabled: boolean;
walletStatus: string;
}
export interface AuthStatus {
isLogged?: boolean;
restoredAccount?: boolean;
isConnectionTrayOpen?: boolean;
}
export interface AccountPositionAction {
marketId: string;
positionData: AccountPosition;
}
export interface AccountPosition {
[market: string]: {
tradingPositionsPerMarket?: Getters.Users.MarketTradingPosition;
tradingPositions: {
[outcomeId: number]: Getters.Users.TradingPosition;
};
};
}
export interface UnrealizedRevenue {
unrealizedRevenue24hChangePercent: string;
}
// TODO: to be provided by SDK the comes from user stats
export interface TimeframeData {
positions: number;
numberOfTrades: number;
marketsTraded: number;
marketsCreated: number;
successfulDisputes: number;
redeemedPositions: number;
}
export interface AccountBalances {
eth: string;
rep: string;
dai: string;
usdt: string;
usdc: string;
legacyRep: string;
attoRep: string;
legacyAttoRep?: string;
signerBalances: {
eth: string;
rep: string;
dai: string;
usdt: string;
usdc: string;
legacyRep: string;
}
}
export interface LoginAccountMeta {
accountType: string;
address: string;
signer: any | EthersSigner;
provider: JsonRpcProvider;
isWeb3: boolean;
profileImage?: string;
email?: string;
openWallet?: Function;
}
export interface LoginAccountSettings {
showInvalidMarketsBannerFeesOrLiquiditySpread?: boolean;
showInvalidMarketsBannerHideOrShow?: boolean;
templateFilter?: boolean;
maxFee?: boolean;
spread?: boolean;
marketTypeFilter?: boolean;
marketFilter?: string;
showInvalid?: boolean;
sortBy?: string;
limit?: number;
offset?: number;
}
export interface LoginAccount {
currentOnboardingStep: number;
address?: string;
mixedCaseAddress?: string;
meta?: LoginAccountMeta;
totalFrozenFunds?: string;
totalRealizedPL?: string;
totalOpenOrdersFrozenFunds?: string;
tradingPositionsTotal?: UnrealizedRevenue;
timeframeData?: TimeframeData;
tradingApproved?: boolean;
balances: AccountBalances;
reporting: Getters.Accounts.AccountReportingHistory;
settings?: LoginAccountSettings;
affiliate?: string;
}
export interface Web3 {
currentProvider: any;
}
export interface WindowApp extends Window {
app: object;
web3: Web3;
ethereum: {
selectedAddress;
networkVersion: string;
isMetaMask?: boolean;
on?: Function;
enable?: Function;
send?: Function;
};
localStorage: Storage;
integrationHelpers: any;
fm?: any;
torus?: any;
portis?: any;
showIndexedDbSize?: Function;
}
export type ButtonActionType = (
event: MouseEvent<HTMLButtonElement | HTMLAnchorElement>
) => void;
export type NodeStyleCallback = (
err: Error | string | null,
result?: any
) => void;
export type DataCallback = (result?: any) => void;
export interface BaseAction extends AnyAction {
type: string;
data?: any;
}
export interface EthereumWallet {
appId: string;
appIds: string[];
archived: boolean;
deleted: boolean;
sortIndex: number;
id: string;
type: string;
keys: { ethereumAddress: string };
}
export interface EdgeUiAccount {
signEthereumTransaction: Function;
getFirstWalletInfo: Function;
createCurrencyWallet: Function;
username: string;
}
export interface WalletObject {
address: string;
balance: string;
derivationPath: Array<number>;
serializedPath: string;
}
export interface Trade {
numShares: FormattedNumber;
limitPrice: FormattedNumber;
potentialDaiProfit: FormattedNumber;
potentialDaiLoss: FormattedNumber;
totalCost: FormattedNumber;
sharesFilled: FormattedNumber;
shareCost: FormattedNumber;
side: typeof BUY | typeof SELL;
orderShareProfit: FormattedNumber;
orderShareTradingFee: FormattedNumber;
numFills: number;
}
export interface PriceTimeSeriesData {
tokenVolume: number;
period: number;
open: number;
close: number;
low: number;
high: number;
volume: number;
shareVolume: number;
}
export interface MarketClaimablePositions {
markets: MarketData[];
totals: {
totalUnclaimedProfit: BigNumber;
totalUnclaimedProceeds: BigNumber;
totalFees: BigNumber;
};
positions: {
[marketId: string]: {
unclaimedProfit: string;
unclaimedProceeds: string;
fee: string;
};
};
}
export interface ClaimReportingOptions {
reportingParticipants: string[];
disputeWindows: string[];
estimateGas?: boolean;
disavowed?: boolean;
isForkingMarket?: boolean;
}
export interface MarketReportContracts {
marketId: string;
contracts: string[];
totalAmount: BigNumber;
marketObject: MarketData;
}
export interface marketsReportingCollection {
unclaimedRep: BigNumber;
marketContracts: MarketReportContracts[];
}
export interface MarketReportClaimableContracts {
claimableMarkets: marketsReportingCollection;
participationContracts: {
contracts: string[];
unclaimedDai: BigNumber;
unclaimedRep: BigNumber;
};
totalUnclaimedDai: BigNumber;
totalUnclaimedRep: BigNumber;
totalUnclaimedDaiFormatted: FormattedNumber;
totalUnclaimedRepFormatted: FormattedNumber;
}
export interface DisputeInputtedValues {
inputStakeValue: string;
inputToAttoRep: string;
}
export interface NavMenuItem {
route: string;
title: string;
requireLogin?: boolean;
disabled?: boolean;
showAlert?: boolean;
button?: boolean;
alternateStyle?: boolean;
}
export interface SortedGroup {
value: string;
label: string;
subGroup?: Array<SortedGroup>;
autoCompleteList?: Array<SortedGroup>;
}
export interface CategoryList {
[category: string]: [
{
[category: string]: [
{
[index: number]: string;
}
];
}
];
} | the_stack |
import { LogFileConnection } from 'common-utils/index.js';
import { log, logError, logger, logInfo, setWorkspaceBase, setWorkspaceFolders } from 'common-utils/log.js';
import { toFileUri, toUri } from 'common-utils/uriHelper.js';
import * as CSpell from 'cspell-lib';
import { CSpellSettingsWithSourceTrace, extractImportErrors, getDefaultSettings, Glob, refreshDictionaryCache } from 'cspell-lib';
import { interval, ReplaySubject, Subscription } from 'rxjs';
import { debounce, debounceTime, filter, mergeMap, take, tap } from 'rxjs/operators';
import { TextDocument } from 'vscode-languageserver-textdocument';
import {
CodeActionKind,
createConnection,
Diagnostic,
DidChangeConfigurationParams,
Disposable,
InitializeParams,
InitializeResult,
ProposedFeatures,
PublishDiagnosticsParams,
ServerCapabilities,
TextDocuments,
TextDocumentSyncKind,
} from 'vscode-languageserver/node';
import * as Api from './api';
import { createClientApi } from './clientApi';
import { onCodeActionHandler } from './codeActions';
import { calculateConfigTargets } from './config/configTargetsHelper';
import { ConfigWatcher } from './config/configWatcher';
import { CSpellUserSettings } from './config/cspellConfig';
import { DictionaryWatcher } from './config/dictionaryWatcher';
import {
correctBadSettings,
DocumentSettings,
isLanguageEnabled,
isUriAllowed,
isUriBlocked,
SettingsCspell,
stringifyPatterns,
} from './config/documentSettings';
import { TextDocumentUri } from './config/vscode.config';
import { createProgressNotifier } from './progressNotifier';
import { textToWords } from './utils';
import { defaultIsTextLikelyMinifiedOptions, isTextLikelyMinified } from './utils/analysis';
import { debounce as simpleDebounce } from './utils/debounce';
import * as Validator from './validator';
log('Starting Spell Checker Server');
type ServerNotificationApiHandlers = {
[key in keyof Api.ServerNotifyApi]: (p: Parameters<Api.ServerNotifyApi[key]>) => void | Promise<void>;
};
const tds = CSpell;
const defaultCheckLimit = Validator.defaultCheckLimit;
const overRideDefaults: CSpellUserSettings = {
id: 'Extension overrides',
patterns: [],
ignoreRegExpList: [],
};
// Turn off the spell checker by default. The setting files should have it set.
// This prevents the spell checker from running too soon.
const defaultSettings: CSpellUserSettings = {
...CSpell.mergeSettings(getDefaultSettings(), CSpell.getGlobalSettings(), overRideDefaults),
checkLimit: defaultCheckLimit,
enabled: false,
};
const defaultDebounceMs = 50;
// Refresh the dictionary cache every 1000ms.
const dictionaryRefreshRateMs = 1000;
export function run(): void {
// debounce buffer
const validationRequestStream = new ReplaySubject<TextDocument>(1);
const triggerUpdateConfig = new ReplaySubject<void>(1);
const triggerValidateAll = new ReplaySubject<void>(1);
const validationByDoc = new Map<string, Subscription>();
const blockValidation = new Map<string, number>();
let isValidationBusy = false;
const disposables: Disposable[] = [];
const dictionaryWatcher = new DictionaryWatcher();
disposables.push(dictionaryWatcher);
const blockedFiles = new Map<string, Api.BlockedFileReason>();
const configWatcher = new ConfigWatcher();
disposables.push(configWatcher);
const requestMethodApi: Api.ServerRequestApiHandlers = {
isSpellCheckEnabled: handleIsSpellCheckEnabled,
getConfigurationForDocument: handleGetConfigurationForDocument,
splitTextIntoWords: handleSplitTextIntoWords,
spellingSuggestions: handleSpellingSuggestions,
};
// Create a connection for the server. The connection uses Node's IPC as a transport
log('Create Connection');
const connection = createConnection(ProposedFeatures.all);
const documentSettings = new DocumentSettings(connection, defaultSettings);
const clientApi = createClientApi(connection);
const progressNotifier = createProgressNotifier(clientApi);
// Create a simple text document manager.
const documents = new TextDocuments(TextDocument);
connection.onInitialize((params: InitializeParams): InitializeResult => {
// Hook up the logger to the connection.
log('onInitialize');
setWorkspaceBase(params.rootUri ? params.rootUri : '');
const capabilities: ServerCapabilities = {
// Tell the client that the server works in FULL text document sync mode
textDocumentSync: {
openClose: true,
change: TextDocumentSyncKind.Incremental,
willSave: true,
save: { includeText: true },
},
codeActionProvider: {
codeActionKinds: [CodeActionKind.QuickFix],
},
};
return { capabilities };
});
// The settings have changed. Is sent on server activation as well.
connection.onDidChangeConfiguration(onConfigChange);
interface OnChangeParam extends DidChangeConfigurationParams {
settings: SettingsCspell;
}
function onDictionaryChange(eventType?: string, filename?: string) {
logInfo(`Dictionary Change ${eventType}`, filename);
triggerUpdateConfig.next(undefined);
}
function onConfigFileChange(eventType?: string, filename?: string) {
logInfo(`Config File Change ${eventType}`, filename);
handleConfigChange();
}
function onConfigChange(_change?: OnChangeParam) {
logInfo('Configuration Change');
handleConfigChange();
}
function handleConfigChange() {
triggerUpdateConfig.next(undefined);
updateLogLevel();
}
function updateActiveSettings() {
log('updateActiveSettings');
documentSettings.resetSettings();
dictionaryWatcher.clear();
blockedFiles.clear();
triggerValidateAll.next(undefined);
}
function getActiveSettings(doc: TextDocumentUri) {
return getActiveUriSettings(doc.uri);
}
function getActiveUriSettings(uri?: string) {
return _getActiveUriSettings(uri);
}
const _getActiveUriSettings = simpleDebounce(__getActiveUriSettings, 50);
function __getActiveUriSettings(uri?: string) {
// Give the dictionaries a chance to refresh if they need to.
log('getActiveUriSettings', uri);
refreshDictionaryCache(dictionaryRefreshRateMs);
return documentSettings.getUriSettings(uri || '');
}
function registerConfigurationFile([path]: [string]) {
documentSettings.registerConfigurationFile(path);
logInfo('Register Configuration File', path);
triggerUpdateConfig.next(undefined);
}
const serverNotificationApiHandlers: ServerNotificationApiHandlers = {
notifyConfigChange: () => onConfigChange(),
registerConfigurationFile: registerConfigurationFile,
};
Object.entries(serverNotificationApiHandlers).forEach(([method, fn]) => {
connection.onNotification(method, fn);
});
interface TextDocumentInfo {
uri?: string;
languageId?: string;
text?: string;
}
// Listen for event messages from the client.
disposables.push(dictionaryWatcher.listen(onDictionaryChange));
disposables.push(configWatcher.listen(onConfigFileChange));
async function handleIsSpellCheckEnabled(params: TextDocumentInfo): Promise<Api.IsSpellCheckEnabledResult> {
return _handleIsSpellCheckEnabled(params);
}
const _handleIsSpellCheckEnabled = simpleDebounce(
__handleIsSpellCheckEnabled,
50,
({ uri, languageId }) => `(${uri})::(${languageId})`
);
async function __handleIsSpellCheckEnabled(params: TextDocumentInfo): Promise<Api.IsSpellCheckEnabledResult> {
log('handleIsSpellCheckEnabled', params.uri);
const activeSettings = await getActiveUriSettings(params.uri);
return calcIncludeExcludeInfo(activeSettings, params);
}
async function handleGetConfigurationForDocument(
params: Api.GetConfigurationForDocumentRequest
): Promise<Api.GetConfigurationForDocumentResult> {
return _handleGetConfigurationForDocument(params);
}
const _handleGetConfigurationForDocument = simpleDebounce(__handleGetConfigurationForDocument, 100, (params) => JSON.stringify(params));
async function __handleGetConfigurationForDocument(
params: Api.GetConfigurationForDocumentRequest
): Promise<Api.GetConfigurationForDocumentResult> {
log('handleGetConfigurationForDocument', params.uri);
const { uri, workspaceConfig } = params;
const doc = uri && documents.get(uri);
const docSettings = stringifyPatterns((doc && (await getSettingsToUseForDocument(doc))) || undefined);
const activeSettings = await getActiveUriSettings(uri);
const settings = stringifyPatterns(activeSettings);
const configFiles = uri ? (await documentSettings.findCSpellConfigurationFilesForUri(uri)).map((uri) => uri.toString()) : [];
const configTargets = workspaceConfig ? calculateConfigTargets(settings, workspaceConfig) : [];
const ieInfo = await calcIncludeExcludeInfo(activeSettings, params);
return {
configFiles,
configTargets,
docSettings,
settings,
...ieInfo,
};
}
async function getExcludedBy(uri: string): Promise<Api.ExcludeRef[]> {
function globToString(g: Glob): string {
if (typeof g === 'string') return g;
return g.glob;
}
function extractGlobSourceUri(settings: CSpellSettingsWithSourceTrace): string | undefined {
const filename = settings.__importRef?.filename || settings.source?.filename;
return toFileUri(filename)?.toString();
}
const ex = await documentSettings.calcExcludedBy(uri);
return ex.map((ex) => ({
glob: globToString(ex.glob),
configUri: extractGlobSourceUri(ex.settings),
id: ex.settings.id,
name: ex.settings.name,
}));
}
function handleSplitTextIntoWords(text: string): Api.SplitTextIntoWordsResult {
return {
words: textToWords(text),
};
}
async function handleSpellingSuggestions(_params: TextDocumentInfo): Promise<Api.SpellingSuggestionsResult> {
return {};
}
// Register API Handlers
Object.entries(requestMethodApi).forEach(([name, fn]) => {
connection.onRequest(name, fn);
});
interface DocSettingPair {
doc: TextDocument;
settings: CSpellUserSettings;
}
// validate documents
const disposableValidate = validationRequestStream.pipe(filter((doc) => !validationByDoc.has(doc.uri))).subscribe((doc) => {
if (validationByDoc.has(doc.uri)) return;
const uri = doc.uri;
log('Register Document Handler:', uri);
if (isUriBlocked(uri)) {
validationByDoc.set(
doc.uri,
validationRequestStream
.pipe(
filter((doc) => uri === doc.uri),
take(1),
tap((doc) => progressNotifier.emitSpellCheckDocumentStep(doc, 'ignore')),
tap((doc) => log('Ignoring:', doc.uri))
)
.subscribe()
);
} else {
validationByDoc.set(
doc.uri,
validationRequestStream
.pipe(
filter((doc) => uri === doc.uri),
tap((doc) => progressNotifier.emitSpellCheckDocumentStep(doc, 'start')),
tap((doc) => log(`Request Validate: v${doc.version}`, doc.uri))
)
.pipe(
debounceTime(defaultDebounceMs),
mergeMap(async (doc) => ({ doc, settings: await getActiveSettings(doc) } as DocSettingPair)),
tap((dsp) => progressNotifier.emitSpellCheckDocumentStep(dsp.doc, 'settings determined')),
debounce((dsp) =>
interval(dsp.settings.spellCheckDelayMs || defaultDebounceMs).pipe(filter(() => !isValidationBusy))
),
filter((dsp) => !blockValidation.has(dsp.doc.uri)),
mergeMap(validateTextDocument)
)
.subscribe(sendDiagnostics)
);
}
});
function sendDiagnostics(result: ValidationResult) {
log(`Send Diagnostics v${result.version}`, result.uri);
const diags: Required<PublishDiagnosticsParams> = {
uri: result.uri,
version: result.version,
diagnostics: result.diagnostics,
};
connection.sendDiagnostics(diags);
}
const disposableTriggerUpdateConfigStream = triggerUpdateConfig
.pipe(
tap(() => log('Trigger Update Config')),
debounceTime(100),
tap(() => log('Update Config Triggered'))
)
.subscribe(() => {
updateActiveSettings();
});
const disposableTriggerValidateAll = triggerValidateAll.pipe(debounceTime(250)).subscribe(() => {
log('Validate all documents');
documents.all().forEach((doc) => validationRequestStream.next(doc));
});
async function shouldValidateDocument(textDocument: TextDocument, settings: CSpellUserSettings): Promise<boolean> {
const { uri, languageId } = textDocument;
return (
!!settings.enabled &&
isLanguageEnabled(languageId, settings) &&
!(await isUriExcluded(uri)) &&
!isBlocked(textDocument, settings)
);
}
function isBlocked(textDocument: TextDocument, settings: CSpellUserSettings): boolean {
const { uri } = textDocument;
const {
blockCheckingWhenLineLengthGreaterThan = defaultIsTextLikelyMinifiedOptions.blockCheckingWhenLineLengthGreaterThan,
blockCheckingWhenAverageChunkSizeGreaterThan = defaultIsTextLikelyMinifiedOptions.blockCheckingWhenAverageChunkSizeGreaterThan,
blockCheckingWhenTextChunkSizeGreaterThan = defaultIsTextLikelyMinifiedOptions.blockCheckingWhenTextChunkSizeGreaterThan,
} = settings;
if (blockedFiles.has(uri)) {
log(`File is blocked ${blockedFiles.get(uri)?.message}`, uri);
return true;
}
const isMiniReason = isTextLikelyMinified(textDocument.getText(), {
blockCheckingWhenAverageChunkSizeGreaterThan,
blockCheckingWhenLineLengthGreaterThan,
blockCheckingWhenTextChunkSizeGreaterThan,
});
if (isMiniReason) {
blockedFiles.set(uri, isMiniReason);
// connection.window.showInformationMessage(`File not spell checked:\n${isMiniReason}\n\"${uriToName(toUri(uri))}"`);
log(`File is blocked: ${isMiniReason.message}`, uri);
}
return !!isMiniReason;
}
async function calcIncludeExcludeInfo(
settings: Api.CSpellUserSettings,
params: TextDocumentInfo
): Promise<Api.IsSpellCheckEnabledResult> {
log('calcIncludeExcludeInfo', params.uri);
const { uri, languageId } = params;
const languageEnabled = languageId ? isLanguageEnabled(languageId, settings) : undefined;
const {
include: fileIsIncluded = true,
exclude: fileIsExcluded = false,
ignored: gitignored = undefined,
gitignoreInfo = undefined,
} = uri ? await calcFileIncludeExclude(uri) : {};
const blockedReason = uri ? blockedFiles.get(uri) : undefined;
const fileEnabled = fileIsIncluded && !fileIsExcluded && !gitignored && !blockedReason;
const excludedBy = fileIsExcluded && uri ? await getExcludedBy(uri) : undefined;
log('calcIncludeExcludeInfo done', params.uri);
return {
excludedBy,
fileEnabled,
fileIsExcluded,
fileIsIncluded,
languageEnabled,
gitignored,
gitignoreInfo,
blockedReason: uri ? blockedFiles.get(uri) : undefined,
};
}
async function isUriExcluded(uri: string): Promise<boolean> {
const ie = await calcFileIncludeExclude(uri);
return !ie.include || ie.exclude || !!ie.ignored;
}
function calcFileIncludeExclude(uri: string) {
return documentSettings.calcIncludeExclude(toUri(uri));
}
async function getBaseSettings(doc: TextDocument) {
const settings = await getActiveSettings(doc);
return { ...CSpell.mergeSettings(defaultSettings, settings), enabledLanguageIds: settings.enabledLanguageIds };
}
async function getSettingsToUseForDocument(doc: TextDocument) {
return tds.constructSettingsForText(await getBaseSettings(doc), doc.getText(), doc.languageId);
}
interface ValidationResult extends PublishDiagnosticsParams {
version: number;
}
function isStale(doc: TextDocument, writeLog = true): boolean {
const currDoc = documents.get(doc.uri);
const stale = currDoc?.version !== doc.version;
if (stale && writeLog) {
log(`validateTextDocument stale ${currDoc?.version} <> ${doc.version}:`, doc.uri);
}
return stale;
}
async function validateTextDocument(dsp: DocSettingPair): Promise<ValidationResult> {
async function validate(): Promise<ValidationResult> {
const { doc, settings } = dsp;
const { uri, version } = doc;
try {
if (!isUriAllowed(uri, settings.allowedSchemas)) {
const schema = uri.split(':')[0];
log(`Schema not allowed (${schema}), skipping:`, uri);
return { uri, version, diagnostics: [] };
}
if (isStale(doc)) {
return { uri, version, diagnostics: [] };
}
const shouldCheck = await shouldValidateDocument(doc, settings);
if (!shouldCheck) {
log('validateTextDocument skip:', uri);
return { uri, version, diagnostics: [] };
}
log(`getSettingsToUseForDocument start ${doc.version}`, uri);
const settingsToUse = await getSettingsToUseForDocument(doc);
log(`getSettingsToUseForDocument middle ${doc.version}`, uri);
configWatcher.processSettings(settingsToUse);
log(`getSettingsToUseForDocument done ${doc.version}`, uri);
if (isStale(doc)) {
return { uri, version, diagnostics: [] };
}
if (settingsToUse.enabled) {
logInfo(`Validate File: v${doc.version}`, uri);
log(`validateTextDocument start: v${doc.version}`, uri);
const settings = correctBadSettings(settingsToUse);
logProblemsWithSettings(settings);
dictionaryWatcher.processSettings(settings);
const diagnostics: Diagnostic[] = await Validator.validateTextDocument(doc, settings);
log(`validateTextDocument done: v${doc.version}`, uri);
return { uri, version, diagnostics };
}
} catch (e) {
logError(`validateTextDocument: ${JSON.stringify(e)}`);
}
return { uri, version, diagnostics: [] };
}
isValidationBusy = true;
progressNotifier.emitSpellCheckDocumentStep(dsp.doc, 'start validation');
const r = await validate();
progressNotifier.emitSpellCheckDocumentStep(dsp.doc, 'end validation', r.diagnostics.length);
isValidationBusy = false;
return r;
}
const knownErrors = new Set<string>();
function isString(s: string | undefined): s is string {
return !!s;
}
function logProblemsWithSettings(settings: CSpellUserSettings) {
function join(...s: (string | undefined)[]): string {
return s.filter((s) => !!s).join(' ');
}
const importErrors = extractImportErrors(settings);
importErrors.forEach((err) => {
const msg = err.error.toString();
const importedBy =
err.referencedBy
?.map((s) => s.filename)
.filter(isString)
.map((s) => '"' + s + '"') || [];
const fullImportBy = importedBy.length ? join(' imported by \n', ...importedBy) : '';
// const firstImportedBy = importedBy.length ? join('imported by', importedBy[0]) : '';
const warnMsg = join(msg, fullImportBy);
if (knownErrors.has(warnMsg)) return;
knownErrors.add(warnMsg);
connection.console.warn(warnMsg);
connection.window.showWarningMessage(join(msg, fullImportBy));
});
}
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
disposables.push(
// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent((event) => {
validationRequestStream.next(event.document);
}),
// We want to block validation during saving.
documents.onWillSave((event) => {
const { uri, version } = event.document;
log(`onWillSave: v${version}`, uri);
blockValidation.set(uri, version);
}),
// Enable validation once it is saved.
documents.onDidSave((event) => {
const { uri, version } = event.document;
log(`onDidSave: v${version}`, uri);
blockValidation.delete(uri);
validationRequestStream.next(event.document);
}),
// Remove subscriptions when a document closes.
documents.onDidClose((event) => {
const uri = event.document.uri;
const sub = validationByDoc.get(uri);
if (sub) {
validationByDoc.delete(uri);
sub.unsubscribe();
}
// A text document was closed we clear the diagnostics
connection.sendDiagnostics({ uri, diagnostics: [] });
})
);
async function updateLogLevel() {
try {
const results: string[] = await connection.workspace.getConfiguration([
{ section: 'cSpell.logLevel' },
{ section: 'cSpell.logFile' },
]);
const logLevel = results[0];
const logFile = results[1];
logger.level = logLevel;
updateLoggerConnection(logFile);
console.error('UpdateLogLevel: %o %s', [logLevel, logFile], process.cwd());
} catch (reject) {
logger.setConnection({ console, onExit: () => undefined });
const message = `Failed to get config: ${JSON.stringify(reject)}`;
logger.error(message);
}
fetchFolders();
}
function updateLoggerConnection(logFile: string | undefined) {
if (!logFile?.endsWith('.log')) {
logger.setConnection(connection);
return;
}
const oldConnection = logger.connection;
if (oldConnection instanceof LogFileConnection && oldConnection.filename === logFile) {
return;
}
logger.setConnection(new LogFileConnection(logFile));
if (oldConnection instanceof LogFileConnection) {
oldConnection.close();
}
}
async function fetchFolders() {
const folders = await connection.workspace.getWorkspaceFolders();
if (folders) {
setWorkspaceFolders(folders.map((f) => f.uri));
} else {
setWorkspaceFolders([]);
}
return folders || undefined;
}
connection.onCodeAction(onCodeActionHandler(documents, getBaseSettings, () => documentSettings.version, clientApi));
// Free up the validation streams on shutdown.
connection.onShutdown(() => {
disposables.forEach((d) => d.dispose());
disposables.length = 0;
disposableValidate.unsubscribe();
disposableTriggerUpdateConfigStream.unsubscribe();
disposableTriggerValidateAll.unsubscribe();
const toDispose = [...validationByDoc.values()];
validationByDoc.clear();
toDispose.forEach((sub) => sub.unsubscribe());
});
// Listen on the connection
connection.listen();
} | the_stack |
import React, { CSSProperties, MouseEventHandler, ReactNode, RefCallback } from "react";
import ReactDOM from "react-dom";
import classNames from "classnames";
import UIStore from "../../../stores/UIStore";
import { ChevronFace } from "../../structures/ContextMenu";
const InteractiveTooltipContainerId = "mx_InteractiveTooltip_Container";
// If the distance from tooltip to window edge is below this value, the tooltip
// will flip around to the other side of the target.
const MIN_SAFE_DISTANCE_TO_WINDOW_EDGE = 20;
function getOrCreateContainer(): HTMLElement {
let container = document.getElementById(InteractiveTooltipContainerId);
if (!container) {
container = document.createElement("div");
container.id = InteractiveTooltipContainerId;
document.body.appendChild(container);
}
return container;
}
interface IRect {
top: number;
right: number;
bottom: number;
left: number;
}
function isInRect(x: number, y: number, rect: IRect): boolean {
const { top, right, bottom, left } = rect;
return x >= left && x <= right && y >= top && y <= bottom;
}
/**
* Returns the positive slope of the diagonal of the rect.
*
* @param {DOMRect} rect
* @return {number}
*/
function getDiagonalSlope(rect: IRect): number {
const { top, right, bottom, left } = rect;
return (bottom - top) / (right - left);
}
function isInUpperLeftHalf(x: number, y: number, rect: IRect): boolean {
const { bottom, left } = rect;
// Negative slope because Y values grow downwards and for this case, the
// diagonal goes from larger to smaller Y values.
const diagonalSlope = getDiagonalSlope(rect) * -1;
return isInRect(x, y, rect) && (y <= bottom + diagonalSlope * (x - left));
}
function isInLowerRightHalf(x: number, y: number, rect: IRect): boolean {
const { bottom, left } = rect;
// Negative slope because Y values grow downwards and for this case, the
// diagonal goes from larger to smaller Y values.
const diagonalSlope = getDiagonalSlope(rect) * -1;
return isInRect(x, y, rect) && (y >= bottom + diagonalSlope * (x - left));
}
function isInUpperRightHalf(x: number, y: number, rect: IRect): boolean {
const { top, left } = rect;
// Positive slope because Y values grow downwards and for this case, the
// diagonal goes from smaller to larger Y values.
const diagonalSlope = getDiagonalSlope(rect) * 1;
return isInRect(x, y, rect) && (y <= top + diagonalSlope * (x - left));
}
function isInLowerLeftHalf(x: number, y: number, rect: IRect): boolean {
const { top, left } = rect;
// Positive slope because Y values grow downwards and for this case, the
// diagonal goes from smaller to larger Y values.
const diagonalSlope = getDiagonalSlope(rect) * 1;
return isInRect(x, y, rect) && (y >= top + diagonalSlope * (x - left));
}
export enum Direction {
Top,
Left,
Bottom,
Right,
}
// exported for tests
export function mouseWithinRegion(
x: number,
y: number,
direction: Direction,
targetRect: DOMRect,
contentRect: DOMRect,
): boolean {
// When moving the mouse from the target to the tooltip, we create a safe area
// that includes the tooltip, the target, and the trapezoid ABCD between them:
// ┌───────────┐
// │ │
// │ │
// A └───E───F───┘ B
// V
// ┌─┐
// │ │
// C└─┘D
//
// As long as the mouse remains inside the safe area, the tooltip will stay open.
const buffer = 50;
if (isInRect(x, y, targetRect)) {
return true;
}
switch (direction) {
case Direction.Left: {
const contentRectWithBuffer = {
top: contentRect.top - buffer,
right: contentRect.right,
bottom: contentRect.bottom + buffer,
left: contentRect.left - buffer,
};
const trapezoidTop = {
top: contentRect.top - buffer,
right: targetRect.right,
bottom: targetRect.top,
left: contentRect.right,
};
const trapezoidCenter = {
top: targetRect.top,
right: targetRect.left,
bottom: targetRect.bottom,
left: contentRect.right,
};
const trapezoidBottom = {
top: targetRect.bottom,
right: targetRect.right,
bottom: contentRect.bottom + buffer,
left: contentRect.right,
};
if (
isInRect(x, y, contentRectWithBuffer) ||
isInLowerLeftHalf(x, y, trapezoidTop) ||
isInRect(x, y, trapezoidCenter) ||
isInUpperLeftHalf(x, y, trapezoidBottom)
) {
return true;
}
break;
}
case Direction.Right: {
const contentRectWithBuffer = {
top: contentRect.top - buffer,
right: contentRect.right + buffer,
bottom: contentRect.bottom + buffer,
left: contentRect.left,
};
const trapezoidTop = {
top: contentRect.top - buffer,
right: contentRect.left,
bottom: targetRect.top,
left: targetRect.left,
};
const trapezoidCenter = {
top: targetRect.top,
right: contentRect.left,
bottom: targetRect.bottom,
left: targetRect.right,
};
const trapezoidBottom = {
top: targetRect.bottom,
right: contentRect.left,
bottom: contentRect.bottom + buffer,
left: targetRect.left,
};
if (
isInRect(x, y, contentRectWithBuffer) ||
isInLowerRightHalf(x, y, trapezoidTop) ||
isInRect(x, y, trapezoidCenter) ||
isInUpperRightHalf(x, y, trapezoidBottom)
) {
return true;
}
break;
}
case Direction.Top: {
const contentRectWithBuffer = {
top: contentRect.top - buffer,
right: contentRect.right + buffer,
bottom: contentRect.bottom,
left: contentRect.left - buffer,
};
const trapezoidLeft = {
top: contentRect.bottom,
right: targetRect.left,
bottom: targetRect.bottom,
left: contentRect.left - buffer,
};
const trapezoidCenter = {
top: contentRect.bottom,
right: targetRect.right,
bottom: targetRect.top,
left: targetRect.left,
};
const trapezoidRight = {
top: contentRect.bottom,
right: contentRect.right + buffer,
bottom: targetRect.bottom,
left: targetRect.right,
};
if (
isInRect(x, y, contentRectWithBuffer) ||
isInUpperRightHalf(x, y, trapezoidLeft) ||
isInRect(x, y, trapezoidCenter) ||
isInUpperLeftHalf(x, y, trapezoidRight)
) {
return true;
}
break;
}
case Direction.Bottom: {
const contentRectWithBuffer = {
top: contentRect.top,
right: contentRect.right + buffer,
bottom: contentRect.bottom + buffer,
left: contentRect.left - buffer,
};
const trapezoidLeft = {
top: targetRect.top,
right: targetRect.left,
bottom: contentRect.top,
left: contentRect.left - buffer,
};
const trapezoidCenter = {
top: targetRect.bottom,
right: targetRect.right,
bottom: contentRect.top,
left: targetRect.left,
};
const trapezoidRight = {
top: targetRect.top,
right: contentRect.right + buffer,
bottom: contentRect.top,
left: targetRect.right,
};
if (
isInRect(x, y, contentRectWithBuffer) ||
isInLowerRightHalf(x, y, trapezoidLeft) ||
isInRect(x, y, trapezoidCenter) ||
isInLowerLeftHalf(x, y, trapezoidRight)
) {
return true;
}
break;
}
}
return false;
}
interface IProps {
children(props: {
ref: RefCallback<HTMLElement>;
onMouseOver: MouseEventHandler;
}): ReactNode;
// Content to show in the tooltip
content: ReactNode;
direction?: Direction;
// Function to call when visibility of the tooltip changes
onVisibilityChange?(visible: boolean): void;
}
interface IState {
contentRect: DOMRect;
visible: boolean;
}
/*
* This style of tooltip takes a "target" element as its child and centers the
* tooltip along one edge of the target.
*/
export default class InteractiveTooltip extends React.Component<IProps, IState> {
private target: HTMLElement;
public static defaultProps = {
side: Direction.Top,
};
constructor(props, context) {
super(props, context);
this.state = {
contentRect: null,
visible: false,
};
}
componentDidUpdate() {
// Whenever this passthrough component updates, also render the tooltip
// in a separate DOM tree. This allows the tooltip content to participate
// the normal React rendering cycle: when this component re-renders, the
// tooltip content re-renders.
// Once we upgrade to React 16, this could be done a bit more naturally
// using the portals feature instead.
this.renderTooltip();
}
componentWillUnmount() {
document.removeEventListener("mousemove", this.onMouseMove);
}
private collectContentRect = (element: HTMLElement): void => {
// We don't need to clean up when unmounting, so ignore
if (!element) return;
this.setState({
contentRect: element.getBoundingClientRect(),
});
};
private collectTarget = (element: HTMLElement) => {
this.target = element;
};
private onLeftOfTarget(): boolean {
const { contentRect } = this.state;
const targetRect = this.target.getBoundingClientRect();
if (this.props.direction === Direction.Left) {
const targetLeft = targetRect.left + window.pageXOffset;
return !contentRect || (targetLeft - contentRect.width > MIN_SAFE_DISTANCE_TO_WINDOW_EDGE);
} else {
const targetRight = targetRect.right + window.pageXOffset;
const spaceOnRight = UIStore.instance.windowWidth - targetRight;
return !contentRect || (spaceOnRight - contentRect.width < MIN_SAFE_DISTANCE_TO_WINDOW_EDGE);
}
}
private aboveTarget(): boolean {
const { contentRect } = this.state;
const targetRect = this.target.getBoundingClientRect();
if (this.props.direction === Direction.Top) {
const targetTop = targetRect.top + window.pageYOffset;
return !contentRect || (targetTop - contentRect.height > MIN_SAFE_DISTANCE_TO_WINDOW_EDGE);
} else {
const targetBottom = targetRect.bottom + window.pageYOffset;
const spaceBelow = UIStore.instance.windowHeight - targetBottom;
return !contentRect || (spaceBelow - contentRect.height < MIN_SAFE_DISTANCE_TO_WINDOW_EDGE);
}
}
private get isOnTheSide(): boolean {
return this.props.direction === Direction.Left || this.props.direction === Direction.Right;
}
private onMouseMove = (ev: MouseEvent) => {
const { clientX: x, clientY: y } = ev;
const { contentRect } = this.state;
const targetRect = this.target.getBoundingClientRect();
let direction: Direction;
if (this.isOnTheSide) {
direction = this.onLeftOfTarget() ? Direction.Left : Direction.Right;
} else {
direction = this.aboveTarget() ? Direction.Top : Direction.Bottom;
}
if (!mouseWithinRegion(x, y, direction, targetRect, contentRect)) {
this.hideTooltip();
}
};
private onTargetMouseOver = (): void => {
this.showTooltip();
};
private showTooltip(): void {
// Don't enter visible state if we haven't collected the target yet
if (!this.target) return;
this.setState({
visible: true,
});
this.props.onVisibilityChange?.(true);
document.addEventListener("mousemove", this.onMouseMove);
}
public hideTooltip() {
this.setState({
visible: false,
});
this.props.onVisibilityChange?.(false);
document.removeEventListener("mousemove", this.onMouseMove);
}
private renderTooltip() {
const { contentRect, visible } = this.state;
if (!visible) {
ReactDOM.unmountComponentAtNode(getOrCreateContainer());
return null;
}
const targetRect = this.target.getBoundingClientRect();
// The window X and Y offsets are to adjust position when zoomed in to page
const targetLeft = targetRect.left + window.pageXOffset;
const targetRight = targetRect.right + window.pageXOffset;
const targetBottom = targetRect.bottom + window.pageYOffset;
const targetTop = targetRect.top + window.pageYOffset;
// Place the tooltip above the target by default. If we find that the
// tooltip content would extend past the safe area towards the window
// edge, flip around to below the target.
const position: Partial<IRect> = {};
let chevronFace: ChevronFace = null;
if (this.isOnTheSide) {
if (this.onLeftOfTarget()) {
position.left = targetLeft;
chevronFace = ChevronFace.Right;
} else {
position.left = targetRight;
chevronFace = ChevronFace.Left;
}
position.top = targetTop;
} else {
if (this.aboveTarget()) {
position.bottom = UIStore.instance.windowHeight - targetTop;
chevronFace = ChevronFace.Bottom;
} else {
position.top = targetBottom;
chevronFace = ChevronFace.Top;
}
// Center the tooltip horizontally with the target's center.
position.left = targetLeft + targetRect.width / 2;
}
const chevron = <div className={"mx_InteractiveTooltip_chevron_" + chevronFace} />;
const menuClasses = classNames({
'mx_InteractiveTooltip': true,
'mx_InteractiveTooltip_withChevron_top': chevronFace === ChevronFace.Top,
'mx_InteractiveTooltip_withChevron_left': chevronFace === ChevronFace.Left,
'mx_InteractiveTooltip_withChevron_right': chevronFace === ChevronFace.Right,
'mx_InteractiveTooltip_withChevron_bottom': chevronFace === ChevronFace.Bottom,
});
const menuStyle: CSSProperties = {};
if (contentRect && !this.isOnTheSide) {
menuStyle.left = `-${contentRect.width / 2}px`;
}
const tooltip = <div className="mx_InteractiveTooltip_wrapper" style={{ ...position }}>
<div className={menuClasses} style={menuStyle} ref={this.collectContentRect}>
{ chevron }
{ this.props.content }
</div>
</div>;
ReactDOM.render(tooltip, getOrCreateContainer());
}
render() {
return this.props.children({
ref: this.collectTarget,
onMouseOver: this.onTargetMouseOver,
});
}
} | the_stack |
import { strict as assert } from "assert";
import { SinonFakeTimers, useFakeTimers } from "sinon";
import { PromiseCache } from "../..";
describe("PromiseCache", () => {
describe("Basic Cache Mechanism", () => {
let pc: PromiseCache<number, string> | undefined;
it("addOrGet", async () => {
pc = new PromiseCache<number, string>();
const contains_WhenAbsent = pc.has(1);
assert.equal(contains_WhenAbsent, false);
const get_WhenAbsent = pc.get(1);
assert.equal(get_WhenAbsent, undefined);
assert.equal(await get_WhenAbsent, undefined);
const remove_WhenAbsent = pc.remove(1);
assert.equal(remove_WhenAbsent, false);
const addOrGet_WhenAbsent = await pc.addOrGet(
1,
async () => "one",
);
assert.equal(addOrGet_WhenAbsent, "one");
const contains_WhenPresent = pc.has(1);
assert.equal(contains_WhenPresent, true);
const get_WhenPresent = await pc.get(1);
assert.equal(get_WhenPresent, "one");
const addOrGet_WhenPresent = await pc.addOrGet(
1,
async () => { throw new Error(); },
);
assert.equal(addOrGet_WhenPresent, "one");
const remove_WhenPresent = pc.remove(1);
assert.equal(remove_WhenPresent, true);
const get_AfterRemove = pc.get(1);
assert.equal(get_AfterRemove, undefined);
const contains_AfterRemove = pc.has(1);
assert.equal(contains_AfterRemove, false);
});
it("addValueOrGet", async () => {
pc = new PromiseCache<number, string>();
const addValueOrGet_Result = await pc.addValueOrGet(
1,
"one",
);
assert.equal(addValueOrGet_Result, "one");
});
it("add", async () => {
pc = new PromiseCache<number, string>();
const add_WhenAbsent = pc.add(
1,
async () => "one",
);
assert.equal(add_WhenAbsent, true);
const add_WhenPresent = pc.add(
1,
async () => { throw new Error(); },
);
assert.equal(add_WhenPresent, false);
const get_AfterAdd = await pc.get(1);
assert.equal(get_AfterAdd, "one");
});
it("addValue", async () => {
pc = new PromiseCache<number, string>();
const addValue_Result = pc.addValue(
1,
"one",
);
assert.equal(addValue_Result, true);
const get_AfterAddValue = await pc.get(1);
assert.equal(get_AfterAddValue, "one");
});
});
describe("asyncFn behavior", () => {
// eslint-disable-next-line @typescript-eslint/promise-function-async
const thrower = (removeOnError: boolean): Promise<string> => {
throw new Error(removeOnError ? "remove" : "Don't remove");
};
const removeOnErrorByMessage = (error: Error) => error.message === "remove";
let pc: PromiseCache<number, string> | undefined;
it("asyncFn run immediately and only if key not set", () => {
pc = new PromiseCache<number, string>();
let callCount = 0;
const fn = async () => { ++callCount; return "hello!"; };
// fn runs immediately...
pc.add(1, fn);
assert.equal(callCount, 1);
// ...but not if the key is already set...
pc.add(1, fn);
assert.equal(callCount, 1);
// ...even if set by value
callCount = 0;
pc.addValue(2, "Some value");
pc.add(2, fn);
assert.equal(callCount, 0);
});
it("asyncFn throws: addOrGet, non-async, removeOnError=false", async () => {
pc = new PromiseCache<number, string>({
removeOnError: removeOnErrorByMessage,
});
// eslint-disable-next-line @typescript-eslint/promise-function-async
const asyncFn = () => thrower(false /* removeOnError */);
const addOrGet1 = pc.addOrGet(1, asyncFn);
await assert.rejects(addOrGet1);
const contains1 = pc.has(1);
assert.equal(contains1, true);
});
it("asyncFn throws: add, non-async, removeOnError=false", async () => {
pc = new PromiseCache<number, string>({
removeOnError: removeOnErrorByMessage,
});
// eslint-disable-next-line @typescript-eslint/promise-function-async
const asyncFn = () => thrower(false /* removeOnError */);
const add2 = pc.add(2, asyncFn);
assert.equal(add2, true);
const get2 = pc.get(2);
if (get2 === undefined) { assert.fail(); }
await assert.rejects(get2);
});
it("asyncFn throws: addOrGet, async, removeOnError=false", async () => {
pc = new PromiseCache<number, string>({
removeOnError: removeOnErrorByMessage,
});
const asyncFn = async () => thrower(false /* removeOnError */);
const p3 = pc.addOrGet(3, asyncFn);
await assert.rejects(p3);
const contains3 = pc.has(3);
assert.equal(contains3, true);
});
it("asyncFn throws: add, async, removeOnError=false", async () => {
pc = new PromiseCache<number, string>({
removeOnError: removeOnErrorByMessage,
});
const asyncFn = async () => thrower(false /* removeOnError */);
const add4 = pc.add(4, asyncFn);
assert.equal(add4, true);
const get4 = pc.get(4);
if (get4 === undefined) { assert.fail(); }
await assert.rejects(get4);
});
it("asyncFn throws: addOrGet, non-async, removeOnError=true", async () => {
pc = new PromiseCache<number, string>({
removeOnError: removeOnErrorByMessage,
});
// eslint-disable-next-line @typescript-eslint/promise-function-async
const asyncFn = () => thrower(true /* removeOnError */);
const p5 = pc.addOrGet(5, asyncFn);
const contains5a = pc.has(5);
assert.equal(contains5a, true, "Shouldn't be removed yet; hasn't run yet");
await assert.rejects(p5);
const contains5b = pc.has(5);
assert.equal(contains5b, false, "Should be removed after rejecting");
});
it("asyncFn throws: add, non-async, removeOnError=true", async () => {
pc = new PromiseCache<number, string>({
removeOnError: removeOnErrorByMessage,
});
// eslint-disable-next-line @typescript-eslint/promise-function-async
const asyncFn = () => thrower(true /* removeOnError */);
const add6 = pc.add(6, asyncFn);
assert.equal(add6, true);
const get6 = pc.get(6);
if (get6 === undefined) { assert.fail("Shouldn't be removed yet; hasn't run yet"); }
await assert.rejects(get6);
const contains6 = pc.has(6);
assert.equal(contains6, false, "Should be removed after rejecting");
});
it("asyncFn throws: addOrGet, async, removeOnError=true", async () => {
pc = new PromiseCache<number, string>({
removeOnError: removeOnErrorByMessage,
});
const asyncFn = async () => thrower(true /* removeOnError */);
const p7 = pc.addOrGet(7, asyncFn);
const contains7a = pc.has(7);
assert.equal(contains7a, true, "Shouldn't be removed yet; hasn't run yet");
await assert.rejects(p7);
const contains7b = pc.has(7);
assert.equal(contains7b, false, "Should be removed after rejecting");
});
it("asyncFn throws: add, async, removeOnError=true", async () => {
pc = new PromiseCache<number, string>({
removeOnError: removeOnErrorByMessage,
});
const asyncFn = async () => thrower(true /* removeOnError */);
const add8 = pc.add(8, asyncFn);
assert.equal(add8, true);
const get8 = pc.get(8);
if (get8 === undefined) { assert.fail("Shouldn't be removed yet; hasn't run yet"); }
await assert.rejects(get8);
const contains8 = pc.has(8);
assert.equal(contains8, false, "Should be removed after rejecting");
});
});
describe("Garbage Collection and Expiry", () => {
let clock: SinonFakeTimers;
let pc: PromiseCache<number, string> | undefined;
// Useful for debugging the tests
const enableLogging: boolean = false; // Set to true to see timing logs
function logClock(m) {
if (enableLogging) {
console.log(`${m} ${clock.now}`);
}
}
before(() => {
clock = useFakeTimers();
});
after(() => {
clock.restore();
});
it("absolute expiry", async () => {
pc = new PromiseCache<number, string>({
expiry: { policy: "absolute", durationMs: 15 },
});
pc.addValue(1, "one");
clock.tick(10);
assert.equal(pc.has(1), true);
await pc.addValueOrGet(1, "one");
clock.tick(10);
assert.equal(pc.has(1), false);
});
it("sliding expiry", async () => {
const expiration = 15;
pc = new PromiseCache<number, string>({
expiry: { policy: "sliding", durationMs: expiration },
});
const startTime = clock.now;
logClock("start");
// Each of these operations should reset the sliding expiry
pc.add(1, async () => "one");
clock.tick(10);
pc.addValue(1, "one");
clock.tick(10);
await pc.addOrGet(1, async () => "one");
clock.tick(10);
await pc.addValueOrGet(1, "one");
clock.tick(10);
await pc.get(1);
clock.tick(10);
const endTime = clock.now;
logClock("endtime");
// More than the initial expiry elapsed but the entry wasn't evicted
assert.equal(endTime - startTime > expiration, true);
assert.equal(pc.has(1), true);
clock.tick(expiration);
logClock("later");
assert.equal(pc.has(1), false);
});
});
}); | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* A Cloud TPU instance.
*
* To get more information about Node, see:
*
* * [API documentation](https://cloud.google.com/tpu/docs/reference/rest/v1/projects.locations.nodes)
* * How-to Guides
* * [Official Documentation](https://cloud.google.com/tpu/docs/)
*
* ## Example Usage
* ### TPU Node Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const available = gcp.tpu.getTensorflowVersions({});
* const tpu = new gcp.tpu.Node("tpu", {
* zone: "us-central1-b",
* acceleratorType: "v3-8",
* tensorflowVersion: available.then(available => available.versions?[0]),
* cidrBlock: "10.2.0.0/29",
* });
* ```
*
* ## Import
*
* Node can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:tpu/node:Node default projects/{{project}}/locations/{{zone}}/nodes/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:tpu/node:Node default {{project}}/{{zone}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:tpu/node:Node default {{zone}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:tpu/node:Node default {{name}}
* ```
*/
export class Node extends pulumi.CustomResource {
/**
* Get an existing Node 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?: NodeState, opts?: pulumi.CustomResourceOptions): Node {
return new Node(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:tpu/node:Node';
/**
* Returns true if the given object is an instance of Node. 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 Node {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Node.__pulumiType;
}
/**
* The type of hardware accelerators associated with this node.
*/
public readonly acceleratorType!: pulumi.Output<string>;
/**
* The CIDR block that the TPU node will use when selecting an IP
* address. This CIDR block must be a /29 block; the Compute Engine
* networks API forbids a smaller block, and using a larger block would
* be wasteful (a node can only consume one IP address).
* Errors will occur if the CIDR block has already been used for a
* currently existing TPU node, the CIDR block conflicts with any
* subnetworks in the user's provided network, or the provided network
* is peered with another network that is using that CIDR block.
*/
public readonly cidrBlock!: pulumi.Output<string>;
/**
* The user-supplied description of the TPU. Maximum of 512 characters.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* Resource labels to represent user provided metadata.
*/
public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* The immutable name of the TPU.
*/
public readonly name!: pulumi.Output<string>;
/**
* The name of a network to peer the TPU node to. It must be a
* preexisting Compute Engine network inside of the project on which
* this API has been activated. If none is provided, "default" will be
* used.
*/
public readonly network!: pulumi.Output<string>;
/**
* The network endpoints where TPU workers can be accessed and sent work. It is recommended that Tensorflow clients of the
* node first reach out to the first (index 0) entry.
*/
public /*out*/ readonly networkEndpoints!: pulumi.Output<outputs.tpu.NodeNetworkEndpoint[]>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* Sets the scheduling options for this TPU instance.
* Structure is documented below.
*/
public readonly schedulingConfig!: pulumi.Output<outputs.tpu.NodeSchedulingConfig | undefined>;
/**
* The service account used to run the tensor flow services within the node. To share resources, including Google Cloud
* Storage data, with the Tensorflow job running in the Node, this account must have permissions to that data.
*/
public /*out*/ readonly serviceAccount!: pulumi.Output<string>;
/**
* The version of Tensorflow running in the Node.
*/
public readonly tensorflowVersion!: pulumi.Output<string>;
/**
* Whether the VPC peering for the node is set up through Service Networking API.
* The VPC Peering should be set up before provisioning the node. If this field is set,
* cidrBlock field should not be specified. If the network that you want to peer the
* TPU Node to is a Shared VPC network, the node must be created with this this field enabled.
*/
public readonly useServiceNetworking!: pulumi.Output<boolean | undefined>;
/**
* The GCP location for the TPU. If it is not provided, the provider zone is used.
*/
public readonly zone!: pulumi.Output<string>;
/**
* Create a Node 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: NodeArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: NodeArgs | NodeState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as NodeState | undefined;
inputs["acceleratorType"] = state ? state.acceleratorType : undefined;
inputs["cidrBlock"] = state ? state.cidrBlock : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["network"] = state ? state.network : undefined;
inputs["networkEndpoints"] = state ? state.networkEndpoints : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["schedulingConfig"] = state ? state.schedulingConfig : undefined;
inputs["serviceAccount"] = state ? state.serviceAccount : undefined;
inputs["tensorflowVersion"] = state ? state.tensorflowVersion : undefined;
inputs["useServiceNetworking"] = state ? state.useServiceNetworking : undefined;
inputs["zone"] = state ? state.zone : undefined;
} else {
const args = argsOrState as NodeArgs | undefined;
if ((!args || args.acceleratorType === undefined) && !opts.urn) {
throw new Error("Missing required property 'acceleratorType'");
}
if ((!args || args.tensorflowVersion === undefined) && !opts.urn) {
throw new Error("Missing required property 'tensorflowVersion'");
}
inputs["acceleratorType"] = args ? args.acceleratorType : undefined;
inputs["cidrBlock"] = args ? args.cidrBlock : undefined;
inputs["description"] = args ? args.description : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["network"] = args ? args.network : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["schedulingConfig"] = args ? args.schedulingConfig : undefined;
inputs["tensorflowVersion"] = args ? args.tensorflowVersion : undefined;
inputs["useServiceNetworking"] = args ? args.useServiceNetworking : undefined;
inputs["zone"] = args ? args.zone : undefined;
inputs["networkEndpoints"] = undefined /*out*/;
inputs["serviceAccount"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Node.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Node resources.
*/
export interface NodeState {
/**
* The type of hardware accelerators associated with this node.
*/
acceleratorType?: pulumi.Input<string>;
/**
* The CIDR block that the TPU node will use when selecting an IP
* address. This CIDR block must be a /29 block; the Compute Engine
* networks API forbids a smaller block, and using a larger block would
* be wasteful (a node can only consume one IP address).
* Errors will occur if the CIDR block has already been used for a
* currently existing TPU node, the CIDR block conflicts with any
* subnetworks in the user's provided network, or the provided network
* is peered with another network that is using that CIDR block.
*/
cidrBlock?: pulumi.Input<string>;
/**
* The user-supplied description of the TPU. Maximum of 512 characters.
*/
description?: pulumi.Input<string>;
/**
* Resource labels to represent user provided metadata.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The immutable name of the TPU.
*/
name?: pulumi.Input<string>;
/**
* The name of a network to peer the TPU node to. It must be a
* preexisting Compute Engine network inside of the project on which
* this API has been activated. If none is provided, "default" will be
* used.
*/
network?: pulumi.Input<string>;
/**
* The network endpoints where TPU workers can be accessed and sent work. It is recommended that Tensorflow clients of the
* node first reach out to the first (index 0) entry.
*/
networkEndpoints?: pulumi.Input<pulumi.Input<inputs.tpu.NodeNetworkEndpoint>[]>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Sets the scheduling options for this TPU instance.
* Structure is documented below.
*/
schedulingConfig?: pulumi.Input<inputs.tpu.NodeSchedulingConfig>;
/**
* The service account used to run the tensor flow services within the node. To share resources, including Google Cloud
* Storage data, with the Tensorflow job running in the Node, this account must have permissions to that data.
*/
serviceAccount?: pulumi.Input<string>;
/**
* The version of Tensorflow running in the Node.
*/
tensorflowVersion?: pulumi.Input<string>;
/**
* Whether the VPC peering for the node is set up through Service Networking API.
* The VPC Peering should be set up before provisioning the node. If this field is set,
* cidrBlock field should not be specified. If the network that you want to peer the
* TPU Node to is a Shared VPC network, the node must be created with this this field enabled.
*/
useServiceNetworking?: pulumi.Input<boolean>;
/**
* The GCP location for the TPU. If it is not provided, the provider zone is used.
*/
zone?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Node resource.
*/
export interface NodeArgs {
/**
* The type of hardware accelerators associated with this node.
*/
acceleratorType: pulumi.Input<string>;
/**
* The CIDR block that the TPU node will use when selecting an IP
* address. This CIDR block must be a /29 block; the Compute Engine
* networks API forbids a smaller block, and using a larger block would
* be wasteful (a node can only consume one IP address).
* Errors will occur if the CIDR block has already been used for a
* currently existing TPU node, the CIDR block conflicts with any
* subnetworks in the user's provided network, or the provided network
* is peered with another network that is using that CIDR block.
*/
cidrBlock?: pulumi.Input<string>;
/**
* The user-supplied description of the TPU. Maximum of 512 characters.
*/
description?: pulumi.Input<string>;
/**
* Resource labels to represent user provided metadata.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The immutable name of the TPU.
*/
name?: pulumi.Input<string>;
/**
* The name of a network to peer the TPU node to. It must be a
* preexisting Compute Engine network inside of the project on which
* this API has been activated. If none is provided, "default" will be
* used.
*/
network?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Sets the scheduling options for this TPU instance.
* Structure is documented below.
*/
schedulingConfig?: pulumi.Input<inputs.tpu.NodeSchedulingConfig>;
/**
* The version of Tensorflow running in the Node.
*/
tensorflowVersion: pulumi.Input<string>;
/**
* Whether the VPC peering for the node is set up through Service Networking API.
* The VPC Peering should be set up before provisioning the node. If this field is set,
* cidrBlock field should not be specified. If the network that you want to peer the
* TPU Node to is a Shared VPC network, the node must be created with this this field enabled.
*/
useServiceNetworking?: pulumi.Input<boolean>;
/**
* The GCP location for the TPU. If it is not provided, the provider zone is used.
*/
zone?: pulumi.Input<string>;
} | the_stack |
import { GitProject } from "@atomist/automation-client/lib/project/git/GitProject";
import { InMemoryFile as InMemoryProjectFile } from "@atomist/automation-client/lib/project/mem/InMemoryFile";
import { InMemoryProject } from "@atomist/automation-client/lib/project/mem/InMemoryProject";
import * as projectUtils from "@atomist/automation-client/lib/project/util/projectUtils";
import * as assert from "power-assert";
import { KubernetesSyncOptions } from "../../../../lib/pack/k8s/config";
import {
matchSpec,
ProjectFileSpec,
sameObject,
syncResources,
} from "../../../../lib/pack/k8s/sync/application";
import { k8sSpecGlob } from "../../../../lib/pack/k8s/sync/diff";
describe("pack/k8s/sync/application", () => {
describe("sameObject", () => {
it("should return true for equivalent objects", () => {
[
[
{ kind: "Service", metadata: { name: "emmylou", namespace: "harris" } },
{ kind: "Service", metadata: { name: "emmylou", namespace: "harris" } },
],
[
{ kind: "ClusterRole", metadata: { name: "emmylou" } },
{ kind: "ClusterRole", metadata: { name: "emmylou" } },
],
].forEach(oo => {
assert(sameObject(oo[0], oo[1]));
assert(sameObject(oo[1], oo[0]));
});
});
it("should return false for non-equivalent objects", () => {
[
[
{ kind: "Service", metadata: { name: "emmylou", namespace: "harris" } },
{ kind: "Service", metadata: { name: "bettylou", namespace: "harris" } },
],
[
{ kind: "ClusterRole", metadata: { name: "emmylou" } },
{ kind: "ClusterRole", metadata: { name: "bettylou" } },
],
[
{ kind: "Service", metadata: { name: "emmylou", namespace: "harris" } },
{ kind: "Role", metadata: { name: "emmylou", namespace: "harris" } },
],
[
{ kind: "ClusterRoleBinding", metadata: { name: "emmylou" } },
{ kind: "ClusterRole", metadata: { name: "emmylou" } },
],
[
{ kind: "Service", metadata: { name: "emmylou", namespace: "harris" } },
{ kind: "ClusterRole", metadata: { name: "emmylou" } },
],
].forEach(oo => {
assert(!sameObject(oo[0], oo[1]));
assert(!sameObject(oo[1], oo[0]));
});
});
it("should return false for invalid objects", () => {
[
[{ kind: "Service", metadata: { name: "emmylou", namespace: "harris" } }, undefined],
[{ kind: "ClusterRole", metadata: { name: "emmylou" } }, { kind: "ClusterRole" }],
[
{ kind: "Service", metadata: { name: "emmylou", namespace: "harris" } },
{ metadata: { name: "emmylou", namespace: "harris" } },
],
[
{ kind: "ClusterRole", metadata: { name: "emmylou" } },
{ kind: "ClusterRole", metadata: {} },
],
].forEach(oo => {
assert(!sameObject(oo[0], oo[1]));
assert(!sameObject(oo[1], oo[0]));
});
});
});
describe("matchSpec", () => {
it("should find nothing", () => {
const sss = [
[],
[
{
file: new InMemoryProjectFile("svc.json", "{}"),
spec: {
apiVersion: "v1",
kind: "Service",
metadata: {
name: "lyle",
namespace: "lovett",
},
},
},
{
file: new InMemoryProjectFile("jondep.json", "{}"),
spec: {
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "jon",
namespace: "lovett",
},
},
},
{
file: new InMemoryProjectFile("dep.json", "{}"),
spec: {
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "lyle",
namespace: "alzado",
},
},
},
],
];
sss.forEach(ss => {
const s = {
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "lyle",
namespace: "lovett",
},
};
const m = matchSpec(s, ss);
assert(m === undefined);
});
});
it("should find the file spec", () => {
const s = {
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "lyle",
namespace: "lovett",
},
};
const ss: ProjectFileSpec[] = [
{
file: new InMemoryProjectFile("dep.json", "{}"),
spec: {
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "lyle",
namespace: "lovett",
},
},
},
];
const m = matchSpec(s, ss);
assert.deepStrictEqual(m, ss[0]);
});
it("should find the file spec with different apiVersion", () => {
const s = {
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "lyle",
namespace: "lovett",
},
};
const ss: ProjectFileSpec[] = [
{
file: new InMemoryProjectFile("dep.json", "{}"),
spec: {
apiVersion: "extensions/v1beta1",
kind: "Deployment",
metadata: {
name: "lyle",
namespace: "lovett",
},
},
},
];
const m = matchSpec(s, ss);
assert.deepStrictEqual(m, ss[0]);
});
it("should find the right file spec among several", () => {
const s = {
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "lyle",
namespace: "lovett",
},
};
const ss: ProjectFileSpec[] = [
{
file: new InMemoryProjectFile("svc.json", "{}"),
spec: {
apiVersion: "v1",
kind: "Service",
metadata: {
name: "lyle",
namespace: "lovett",
},
},
},
{
file: new InMemoryProjectFile("jondep.json", "{}"),
spec: {
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "jon",
namespace: "lovett",
},
},
},
{
file: new InMemoryProjectFile("dep.json", "{}"),
spec: {
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "lyle",
namespace: "lovett",
},
},
},
{
file: new InMemoryProjectFile("dep.json", "{}"),
spec: {
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "lyle",
namespace: "alzado",
},
},
},
];
const m = matchSpec(s, ss);
assert.deepStrictEqual(m, ss[2]);
});
});
describe("syncResources", () => {
it("should create spec files", async () => {
const p: GitProject = InMemoryProject.of() as any;
p.isClean = async () => false;
let commitMessage: string;
p.commit = async msg => {
commitMessage = msg;
return p;
};
let pushed = false;
p.push = async msg => {
pushed = true;
return p;
};
const a = {
image: "hub.tonina.com/black-angel/como-yo:3.58",
name: "tonina",
ns: "black-angel",
workspaceId: "T0N1N4",
};
const rs = [
{
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "tonina",
namespace: "black-angel",
},
},
{
apiVersion: "v1",
kind: "Service",
metadata: {
name: "tonina",
namespace: "black-angel",
},
},
{
apiVersion: "v1",
kind: "ServiceAccount",
metadata: {
name: "tonina",
namespace: "black-angel",
},
},
{
apiVersion: "v1",
kind: "Secret",
type: "Opaque",
metadata: {
name: "tonina",
namespace: "black-angel",
},
data: {
Track01: "w4FyYm9sIERlIExhIFZpZGE=",
Track02: "Q2FseXBzbyBCbHVlcw==",
},
},
];
const o: KubernetesSyncOptions = {
repo: {
owner: "tonina",
repo: "black-angel",
url: "https://github.com/tonina/black-angel",
},
specFormat: "json",
};
await syncResources(a, rs, "upsert", o)(p);
const eCommitMessage = `Update black-angel/tonina:3.58
[atomist:generated] [atomist:sync-commit=@atomist/sdm-pack-k8s]
`;
assert(commitMessage === eCommitMessage);
assert(pushed, "commit was not pushed");
assert((await p.totalFileCount()) === 4);
assert(p.fileExistsSync("70_black-angel_tonina_deployment.json"));
assert(p.fileExistsSync("50_black-angel_tonina_service.json"));
assert(p.fileExistsSync("20_black-angel_tonina_service-account.json"));
assert(p.fileExistsSync("60_black-angel_tonina_secret.json"));
const d = await (await p.getFile("70_black-angel_tonina_deployment.json")).getContent();
const de = `{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"name": "tonina",
"namespace": "black-angel"
}
}
`;
assert(d === de);
const s = await (await p.getFile("60_black-angel_tonina_secret.json")).getContent();
const se = `{
"apiVersion": "v1",
"data": {
"Track01": "w4FyYm9sIERlIExhIFZpZGE=",
"Track02": "Q2FseXBzbyBCbHVlcw=="
},
"kind": "Secret",
"metadata": {
"name": "tonina",
"namespace": "black-angel"
},
"type": "Opaque"
}
`;
assert(s === se);
});
it("should default to YAML", async () => {
const p: GitProject = InMemoryProject.of() as any;
p.isClean = async () => false;
let commitMessage: string;
p.commit = async msg => {
commitMessage = msg;
return p;
};
let pushed = false;
p.push = async msg => {
pushed = true;
return p;
};
const a = {
image: "hub.tonina.com/black-angel/como-yo:3.58",
name: "tonina",
ns: "black-angel",
workspaceId: "T0N1N4",
};
const rs = [
{
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "tonina",
namespace: "black-angel",
},
},
{
metadata: {
name: "tonina",
namespace: "black-angel",
},
kind: "Service",
apiVersion: "v1",
},
];
const o: KubernetesSyncOptions = {
repo: {
owner: "tonina",
repo: "black-angel",
url: "https://github.com/tonina/black-angel",
},
};
await syncResources(a, rs, "upsert", o)(p);
const eCommitMessage = `Update black-angel/tonina:3.58
[atomist:generated] [atomist:sync-commit=@atomist/sdm-pack-k8s]
`;
assert(commitMessage === eCommitMessage);
assert(pushed, "commit was not pushed");
assert((await p.totalFileCount()) === 2);
assert(p.fileExistsSync("70_black-angel_tonina_deployment.yaml"));
assert(p.fileExistsSync("50_black-angel_tonina_service.yaml"));
const d = await (await p.getFile("70_black-angel_tonina_deployment.yaml")).getContent();
const de = `apiVersion: apps/v1
kind: Deployment
metadata:
name: tonina
namespace: black-angel
`;
assert(d === de);
const s = await (await p.getFile("50_black-angel_tonina_service.yaml")).getContent();
const se = `apiVersion: v1
kind: Service
metadata:
name: tonina
namespace: black-angel
`;
assert(s === se);
});
it("should update spec files and avoid conflicts", async () => {
const depJson = JSON.stringify({
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "tonina",
namespace: "black-angel",
},
});
const saYaml = `apiVersion: v1
kind: ServiceAccount
metadata:
name: tonina
namespace: black-angel
`;
const p: GitProject = InMemoryProject.of(
{ path: "70_black-angel_tonina_deployment.json", content: depJson },
{ path: "50_black-angel_tonina_service.json", content: "{}\n" },
{ path: "19+black-angel+tonina+service-acct.yaml", content: saYaml },
) as any;
p.isClean = async () => false;
let commitMessage: string;
p.commit = async msg => {
commitMessage = msg;
return p;
};
let pushed = false;
p.push = async msg => {
pushed = true;
return p;
};
const a = {
image: "hub.tonina.com/black-angel/como-yo:3.5.8-20180406",
name: "tonina",
ns: "black-angel",
workspaceId: "T0N1N4",
};
const rs = [
{
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "tonina",
namespace: "black-angel",
labels: {
"atomist.com/workspaceId": "T0N1N4",
},
},
},
{
apiVersion: "v1",
kind: "Service",
metadata: {
name: "tonina",
namespace: "black-angel",
},
},
{
apiVersion: "networking.k8s.io/v1beta1",
kind: "Ingress",
metadata: {
name: "tonina",
namespace: "black-angel",
},
},
{
apiVersion: "v1",
kind: "ServiceAccount",
metadata: {
name: "tonina",
namespace: "black-angel",
labels: {
"atomist.com/workspaceId": "T0N1N4",
},
},
},
{
apiVersion: "v1",
kind: "Secret",
type: "Opaque",
metadata: {
name: "tonina",
namespace: "black-angel",
},
data: {
Track01: "w4FyYm9sIERlIExhIFZpZGE=",
Track02: "Q2FseXBzbyBCbHVlcw==",
},
},
];
const o: KubernetesSyncOptions = {
repo: {
owner: "tonina",
repo: "black-angel",
url: "https://github.com/tonina/black-angel",
},
secretKey: "10. Historia De Un Amor (feat. Javier Limón & Tali Rubinstein)",
specFormat: "json",
};
await syncResources(a, rs, "upsert", o)(p);
const eCommitMessage = `Update black-angel/tonina:3.5.8-20180406
[atomist:generated] [atomist:sync-commit=@atomist/sdm-pack-k8s]
`;
assert(commitMessage === eCommitMessage);
assert(pushed, "commit was not pushed");
assert((await p.totalFileCount()) === 6);
assert(p.fileExistsSync("70_black-angel_tonina_deployment.json"));
assert(p.fileExistsSync("50_black-angel_tonina_service.json"));
assert(p.fileExistsSync("80_black-angel_tonina_ingress.json"));
assert(p.fileExistsSync("19+black-angel+tonina+service-acct.yaml"));
const dep = JSON.parse(await p.getFile("70_black-angel_tonina_deployment.json").then(f => f.getContent()));
assert.deepStrictEqual(dep, rs[0]);
const s = await p.getFile("50_black-angel_tonina_service.json").then(f => f.getContent());
assert(s === "{}\n");
const sa = await p.getFile("19+black-angel+tonina+service-acct.yaml").then(f => f.getContent());
const sae = `apiVersion: v1
kind: ServiceAccount
metadata:
labels:
atomist.com/workspaceId: T0N1N4
name: tonina
namespace: black-angel
`;
assert(sa === sae);
let foundServiceSpec = false;
await projectUtils.doWithFiles(p, k8sSpecGlob, async f => {
if (/^50_black-angel_tonina_service_[a-f0-9]+\.json$/.test(f.path)) {
const c = await f.getContent();
const sv = JSON.parse(c);
assert.deepStrictEqual(sv, rs[1]);
foundServiceSpec = true;
}
});
assert(foundServiceSpec, "failed to find new service spec");
const sec = JSON.parse(await p.getFile("60_black-angel_tonina_secret.json").then(f => f.getContent()));
const sece = {
apiVersion: "v1",
kind: "Secret",
type: "Opaque",
metadata: {
name: "tonina",
namespace: "black-angel",
},
data: {
Track01: "pIVq/+dRdfzQk4QRFkcwneZwzyAl3RBJTLI5WvAqdLg=",
Track02: "ArfFf8S0cHOycteqW6w/hGU7dIUuRBsbnUXSJ+yK7BI=",
},
};
assert.deepStrictEqual(sec, sece);
});
it("should delete spec files", async () => {
const depJson = JSON.stringify({
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "tonina",
namespace: "black-angel",
},
});
const saYaml = `apiVersion: v1
kind: ServiceAccount
metadata:
name: tonina
namespace: black-angel
`;
const svcJson = JSON.stringify({
apiVersion: "v1",
kind: "Service",
metadata: {
name: "tonina",
namespace: "black-angel",
},
});
const p: GitProject = InMemoryProject.of(
{ path: "black-angel~tonina~deployment.json", content: depJson },
{ path: "black-angel-tonina-service.json", content: "{}\n" },
{ path: "black-angel-tonina-service-acct.yaml", content: saYaml },
{ path: "black-angel-tonina-svc.json", content: svcJson },
) as any;
p.isClean = async () => false;
let commitMessage: string;
p.commit = async msg => {
commitMessage = msg;
return p;
};
let pushed = false;
p.push = async msg => {
pushed = true;
return p;
};
const a = {
name: "tonina",
ns: "black-angel",
workspaceId: "T0N1N4",
};
const rs = [
{
apiVersion: "apps/v1",
kind: "Deployment",
metadata: {
name: "tonina",
namespace: "black-angel",
labels: {
"atomist.com/workspaceId": "T0N1N4",
},
},
},
{
apiVersion: "v1",
kind: "Service",
metadata: {
name: "tonina",
namespace: "black-angel",
},
},
{
apiVersion: "networking.k8s.io/v1beta1",
kind: "Ingress",
metadata: {
name: "tonina",
namespace: "black-angel",
},
},
{
apiVersion: "v1",
kind: "ServiceAccount",
metadata: {
name: "tonina",
namespace: "black-angel",
labels: {
"atomist.com/workspaceId": "T0N1N4",
},
},
},
];
const o = {
repo: {
owner: "tonina",
repo: "black-angel",
url: "https://github.com/tonina/black-angel",
},
};
await syncResources(a, rs, "delete", o)(p);
const eCommitMessage = `Delete black-angel/tonina
[atomist:generated] [atomist:sync-commit=@atomist/sdm-pack-k8s]
`;
assert(commitMessage === eCommitMessage);
assert(pushed, "commit was not pushed");
assert((await p.totalFileCount()) === 1);
assert(!p.fileExistsSync("black-angel~tonina~deployment.json"));
assert(p.fileExistsSync("black-angel-tonina-service.json"));
assert(!p.fileExistsSync("black-angel-tonina-ingress.json"));
assert(!p.fileExistsSync("black-angel-tonina-service-acct.yaml"));
assert(!p.fileExistsSync("black-angel-tonina-svc.yaml"));
const svc = await p.getFile("black-angel-tonina-service.json").then(f => f.getContent());
assert(svc === "{}\n");
});
});
}); | the_stack |
import test, { Test } from "tape-promise/tape";
import { v4 as internalIpV4 } from "internal-ip";
import { v4 as uuidv4 } from "uuid";
import http from "http";
import bodyParser from "body-parser";
import express from "express";
import { AddressInfo } from "net";
import { Containers, CordaTestLedger } from "@hyperledger/cactus-test-tooling";
import {
LogLevelDesc,
IListenOptions,
Servers,
} from "@hyperledger/cactus-common";
import {
SampleCordappEnum,
CordaConnectorContainer,
} from "@hyperledger/cactus-test-tooling";
import {
CordappDeploymentConfig,
DefaultApi as CordaApi,
DeployContractJarsV1Request,
FlowInvocationType,
InvokeContractV1Request,
JvmTypeKind,
} from "../../../main/typescript/generated/openapi/typescript-axios/index";
import { Configuration } from "@hyperledger/cactus-core-api";
import {
IPluginLedgerConnectorCordaOptions,
PluginLedgerConnectorCorda,
} from "../../../main/typescript/plugin-ledger-connector-corda";
import { K_CACTUS_CORDA_TOTAL_TX_COUNT } from "../../../main/typescript/prometheus-exporter/metrics";
const logLevel: LogLevelDesc = "TRACE";
test.skip("Tests are passing on the JVM side", async (t: Test) => {
test.onFailure(async () => {
await Containers.logDiagnostics({ logLevel });
});
const ledger = new CordaTestLedger({
imageName: "ghcr.io/hyperledger/cactus-corda-4-6-all-in-one-obligation",
imageVersion: "2021-03-19-feat-686",
// imageName: "caio",
// imageVersion: "latest",
logLevel,
});
t.ok(ledger, "CordaTestLedger instantaited OK");
test.onFinish(async () => {
await ledger.stop();
await ledger.destroy();
});
const ledgerContainer = await ledger.start();
t.ok(ledgerContainer, "CordaTestLedger container truthy post-start() OK");
const corDappsDirPartyA = await ledger.getCorDappsDirPartyA();
const corDappsDirPartyB = await ledger.getCorDappsDirPartyB();
t.comment(`corDappsDirPartyA=${corDappsDirPartyA}`);
t.comment(`corDappsDirPartyB=${corDappsDirPartyB}`);
await ledger.logDebugPorts();
const partyARpcPort = await ledger.getRpcAPublicPort();
const partyBRpcPort = await ledger.getRpcBPublicPort();
const jarFiles = await ledger.pullCordappJars(
SampleCordappEnum.BASIC_CORDAPP,
);
t.comment(`Fetched ${jarFiles.length} cordapp jars OK`);
const internalIpOrUndefined = await internalIpV4();
t.ok(internalIpOrUndefined, "Determined LAN IPv4 address successfully OK");
const internalIp = internalIpOrUndefined as string;
t.comment(`Internal IP (based on default gateway): ${internalIp}`);
// TODO: parse the gradle build files to extract the credentials?
const partyARpcUsername = "user1";
const partyARpcPassword = "password";
const partyBRpcUsername = partyARpcUsername;
const partyBRpcPassword = partyARpcPassword;
const springAppConfig = {
logging: {
level: {
root: "INFO",
"net.corda": "INFO",
"org.hyperledger.cactus": "DEBUG",
},
},
cactus: {
corda: {
node: { host: internalIp },
rpc: {
port: partyARpcPort,
username: partyARpcUsername,
password: partyARpcPassword,
},
},
},
};
const springApplicationJson = JSON.stringify(springAppConfig);
const envVarSpringAppJson = `SPRING_APPLICATION_JSON=${springApplicationJson}`;
t.comment(envVarSpringAppJson);
const connector = new CordaConnectorContainer({
logLevel,
imageName: "ghcr.io/hyperledger/cactus-connector-corda-server",
imageVersion: "2021-11-23--feat-1493",
envVars: [envVarSpringAppJson],
});
t.ok(CordaConnectorContainer, "CordaConnectorContainer instantiated OK");
test.onFinish(async () => {
try {
await connector.stop();
} finally {
await connector.destroy();
}
});
const connectorContainer = await connector.start();
t.ok(connectorContainer, "CordaConnectorContainer started OK");
await connector.logDebugPorts();
const apiUrl = await connector.getApiLocalhostUrl();
const config = new Configuration({ basePath: apiUrl });
const apiClient = new CordaApi(config);
const flowsRes1 = await apiClient.listFlowsV1();
t.ok(flowsRes1.status === 200, "flowsRes1.status === 200 OK");
t.ok(flowsRes1.data, "flowsRes1.data truthy OK");
t.ok(flowsRes1.data.flowNames, "flowsRes1.data.flowNames truthy OK");
t.comment(`apiClient.listFlowsV1() => ${JSON.stringify(flowsRes1.data)}`);
const flowNamesPreDeploy = flowsRes1.data.flowNames;
const sshConfig = await ledger.getSshConfig();
const hostKeyEntry = "not-used-right-now-so-this-does-not-matter... ;-(";
const cdcA: CordappDeploymentConfig = {
cordappDir: corDappsDirPartyA,
cordaNodeStartCmd: "supervisorctl start corda-a",
cordaJarPath:
"/samples-kotlin/Advanced/obligation-cordapp/build/nodes/ParticipantA/corda.jar",
nodeBaseDirPath:
"/samples-kotlin/Advanced/obligation-cordapp/build/nodes/ParticipantA/",
rpcCredentials: {
hostname: internalIp,
port: partyARpcPort,
username: partyARpcUsername,
password: partyARpcPassword,
},
sshCredentials: {
hostKeyEntry,
hostname: internalIp,
password: "root",
port: sshConfig.port as number,
username: sshConfig.username as string,
},
};
const cdcB: CordappDeploymentConfig = {
cordappDir: corDappsDirPartyB,
cordaNodeStartCmd: "supervisorctl start corda-b",
cordaJarPath:
"/samples-kotlin/Advanced/obligation-cordapp/build/nodes/ParticipantB/corda.jar",
nodeBaseDirPath:
"/samples-kotlin/Advanced/obligation-cordapp/build/nodes/ParticipantB/",
rpcCredentials: {
hostname: internalIp,
port: partyBRpcPort,
username: partyBRpcUsername,
password: partyBRpcPassword,
},
sshCredentials: {
hostKeyEntry,
hostname: internalIp,
password: "root",
port: sshConfig.port as number,
username: sshConfig.username as string,
},
};
const cordappDeploymentConfigs: CordappDeploymentConfig[] = [cdcA, cdcB];
const depReq: DeployContractJarsV1Request = {
jarFiles,
cordappDeploymentConfigs,
};
const depRes = await apiClient.deployContractJarsV1(depReq);
t.ok(depRes, "Jar deployment response truthy OK");
t.equal(depRes.status, 200, "Jar deployment status code === 200 OK");
t.ok(depRes.data, "Jar deployment response body truthy OK");
t.ok(depRes.data.deployedJarFiles, "Jar deployment body deployedJarFiles OK");
t.equal(
depRes.data.deployedJarFiles.length,
jarFiles.length,
"Deployed jar file count equals count in request OK",
);
const flowsRes2 = await apiClient.listFlowsV1();
t.ok(flowsRes2.status === 200, "flowsRes2.status === 200 OK");
t.comment(`apiClient.listFlowsV1() => ${JSON.stringify(flowsRes2.data)}`);
t.ok(flowsRes2.data, "flowsRes2.data truthy OK");
t.ok(flowsRes2.data.flowNames, "flowsRes2.data.flowNames truthy OK");
const flowNamesPostDeploy = flowsRes2.data.flowNames;
t.notDeepLooseEqual(
flowNamesPostDeploy,
flowNamesPreDeploy,
"New flows detected post Cordapp Jar deployment OK",
);
// let's see if this makes a difference and if yes, then we know that the issue
// is a race condition for sure
// await new Promise((r) => setTimeout(r, 120000));
t.comment("Fetching network map for Corda network...");
const networkMapRes = await apiClient.networkMapV1();
t.ok(networkMapRes, "networkMapRes truthy OK");
t.ok(networkMapRes.status, "networkMapRes.status truthy OK");
t.ok(networkMapRes.data, "networkMapRes.data truthy OK");
t.true(Array.isArray(networkMapRes.data), "networkMapRes.data isArray OK");
t.true(networkMapRes.data.length > 0, "networkMapRes.data not empty OK");
// const partyA = networkMapRes.data.find((it) =>
// it.legalIdentities.some((it2) => it2.name.organisation === "ParticipantA"),
// );
// const partyAPublicKey = partyA?.legalIdentities[0].owningKey;
const partyB = networkMapRes.data.find((it) =>
it.legalIdentities.some((it2) => it2.name.organisation === "ParticipantB"),
);
const partyBPublicKey = partyB?.legalIdentities[0].owningKey;
const req: InvokeContractV1Request = ({
timeoutMs: 60000,
flowFullClassName: "net.corda.samples.example.flows.ExampleFlow$Initiator",
flowInvocationType: FlowInvocationType.FlowDynamic,
params: [
{
jvmTypeKind: JvmTypeKind.Primitive,
jvmType: {
fqClassName: "java.lang.Integer",
},
primitiveValue: 42,
},
{
jvmTypeKind: JvmTypeKind.Reference,
jvmType: {
fqClassName: "net.corda.core.identity.Party",
},
jvmCtorArgs: [
{
jvmTypeKind: JvmTypeKind.Reference,
jvmType: {
fqClassName: "net.corda.core.identity.CordaX500Name",
},
jvmCtorArgs: [
{
jvmTypeKind: JvmTypeKind.Primitive,
jvmType: {
fqClassName: "java.lang.String",
},
primitiveValue: "ParticipantB",
},
{
jvmTypeKind: JvmTypeKind.Primitive,
jvmType: {
fqClassName: "java.lang.String",
},
primitiveValue: "New York",
},
{
jvmTypeKind: JvmTypeKind.Primitive,
jvmType: {
fqClassName: "java.lang.String",
},
primitiveValue: "US",
},
],
},
{
jvmTypeKind: JvmTypeKind.Reference,
jvmType: {
fqClassName:
"org.hyperledger.cactus.plugin.ledger.connector.corda.server.impl.PublicKeyImpl",
},
jvmCtorArgs: [
{
jvmTypeKind: JvmTypeKind.Primitive,
jvmType: {
fqClassName: "java.lang.String",
},
primitiveValue: partyBPublicKey?.algorithm,
},
{
jvmTypeKind: JvmTypeKind.Primitive,
jvmType: {
fqClassName: "java.lang.String",
},
primitiveValue: partyBPublicKey?.format,
},
{
jvmTypeKind: JvmTypeKind.Primitive,
jvmType: {
fqClassName: "java.lang.String",
},
primitiveValue: partyBPublicKey?.encoded,
},
],
},
],
},
],
} as unknown) as InvokeContractV1Request;
const res = await apiClient.invokeContractV1(req);
t.ok(res, "InvokeContractV1Request truthy OK");
t.equal(res.status, 200, "InvokeContractV1Request status code === 200 OK");
const pluginOptions: IPluginLedgerConnectorCordaOptions = {
instanceId: uuidv4(),
corDappsDir: corDappsDirPartyA,
sshConfigAdminShell: sshConfig,
};
const plugin = new PluginLedgerConnectorCorda(pluginOptions);
const expressApp = express();
expressApp.use(bodyParser.json({ limit: "250mb" }));
const server = http.createServer(expressApp);
const listenOptions: IListenOptions = {
hostname: "0.0.0.0",
port: 0,
server,
};
const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo;
test.onFinish(async () => await Servers.shutdown(server));
const { address, port } = addressInfo;
const apiHost = `http://${address}:${port}`;
t.comment(
`Metrics URL: ${apiHost}/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-corda/get-prometheus-exporter-metrics`,
);
const apiConfig = new Configuration({ basePath: apiHost });
const apiClient1 = new CordaApi(apiConfig);
await plugin.getOrCreateWebServices();
await plugin.registerWebServices(expressApp);
{
plugin.transact();
const promRes = await apiClient1.getPrometheusMetricsV1();
const promMetricsOutput =
"# HELP " +
K_CACTUS_CORDA_TOTAL_TX_COUNT +
" Total transactions executed\n" +
"# TYPE " +
K_CACTUS_CORDA_TOTAL_TX_COUNT +
" gauge\n" +
K_CACTUS_CORDA_TOTAL_TX_COUNT +
'{type="' +
K_CACTUS_CORDA_TOTAL_TX_COUNT +
'"} 1';
t.ok(promRes);
t.ok(promRes.data);
t.equal(promRes.status, 200);
t.true(
promRes.data.includes(promMetricsOutput),
"Total Transaction Count of 1 recorded as expected. RESULT OK",
);
// Executing transaction to increment the Total transaction count metrics
plugin.transact();
const promRes1 = await apiClient1.getPrometheusMetricsV1();
const promMetricsOutput1 =
"# HELP " +
K_CACTUS_CORDA_TOTAL_TX_COUNT +
" Total transactions executed\n" +
"# TYPE " +
K_CACTUS_CORDA_TOTAL_TX_COUNT +
" gauge\n" +
K_CACTUS_CORDA_TOTAL_TX_COUNT +
'{type="' +
K_CACTUS_CORDA_TOTAL_TX_COUNT +
'"} 2';
t.ok(promRes1);
t.ok(promRes1.data);
t.equal(promRes1.status, 200);
t.true(
promRes1.data.includes(promMetricsOutput1),
"Total Transaction Count of 2 recorded as expected. RESULT OK",
);
}
t.end();
}); | the_stack |
import { Server } from "http";
import { Server as SecureServer } from "https";
import { v4 as uuidv4 } from "uuid";
import { Express } from "express";
import { promisify } from "util";
import { Optional } from "typescript-optional";
import OAS from "../json/openapi.json";
import {
ICactusPlugin,
ICactusPluginOptions,
IPluginWebService,
IWebServiceEndpoint,
} from "@hyperledger/cactus-core-api";
import { PluginRegistry } from "@hyperledger/cactus-core";
import { PluginImportType } from "@hyperledger/cactus-core-api";
import {
Checks,
Logger,
LoggerProvider,
LogLevelDesc,
} from "@hyperledger/cactus-common";
import {
InitializeRequest as InitializeRequestBesuERC20,
NewContractRequest as NewContractRequestBesuERC20,
PluginHtlcEthBesuErc20,
WithdrawRequest as WithdrawRequestBesuERC20,
} from "@hyperledger/cactus-plugin-htlc-eth-besu-erc20";
import {
InitializeRequest as InitializeRequestBesu,
NewContractObj,
InvokeContractV1Response,
IPluginHtlcEthBesuOptions,
PluginFactoryHtlcEthBesu,
WithdrawReq,
} from "@hyperledger/cactus-plugin-htlc-eth-besu";
import { PluginLedgerConnectorBesu } from "@hyperledger/cactus-plugin-ledger-connector-besu";
import { OwnHTLCEndpoint } from "./web-services/own-htlc-endpoint";
import { CounterpartyHTLCEndpoint } from "./web-services/counterparty-htlc-endpoint";
import { WithdrawCounterpartyEndpoint } from "./web-services/withdraw-counterparty-endpoint";
import {
OwnHTLCRequest,
CounterpartyHTLCRequest,
WithdrawCounterpartyRequest,
HtlcPackage,
} from "./generated/openapi/typescript-axios";
export interface IPluginHTLCCoordinatorBesuOptions
extends ICactusPluginOptions {
pluginRegistry: PluginRegistry;
logLevel?: LogLevelDesc;
}
export class PluginHTLCCoordinatorBesu
implements ICactusPlugin, IPluginWebService {
private readonly instanceId: string;
private readonly log: Logger;
private readonly pluginRegistry: PluginRegistry;
private endpoints: IWebServiceEndpoint[] | undefined;
private httpServer: Server | SecureServer | null = null;
public static readonly CLASS_NAME = "PluginHTLCCoordinatorBesu";
public get className(): string {
return PluginHTLCCoordinatorBesu.CLASS_NAME;
}
constructor(public readonly options: IPluginHTLCCoordinatorBesuOptions) {
const fnTag = `${this.className}#constructor()`;
Checks.truthy(options, `${fnTag} arg options`);
Checks.truthy(options.instanceId, `${fnTag} options.instanceId`);
Checks.truthy(options.pluginRegistry, `${fnTag} options.pluginRegistry`);
const level = this.options.logLevel || "INFO";
const label = this.className;
this.log = LoggerProvider.getOrCreate({ level, label });
this.instanceId = options.instanceId;
this.pluginRegistry = options.pluginRegistry;
}
public getInstanceId(): string {
return this.instanceId;
}
public async onPluginInit(): Promise<unknown> {
return;
}
public getOpenApiSpec(): unknown {
return OAS;
}
public getPackageName(): string {
return `@hyperledger/cactus-plugin-htlc-coordinator-besu`;
}
public getHttpServer(): Optional<Server | SecureServer> {
return Optional.ofNullable(this.httpServer);
}
public async shutdown(): Promise<void> {
const serverMaybe = this.getHttpServer();
if (serverMaybe.isPresent()) {
const server = serverMaybe.get();
await promisify(server.close.bind(server))();
}
}
async registerWebServices(app: Express): Promise<IWebServiceEndpoint[]> {
const webServices = await this.getOrCreateWebServices();
await Promise.all(webServices.map((ws) => ws.registerExpress(app)));
return webServices;
}
public async getOrCreateWebServices(): Promise<IWebServiceEndpoint[]> {
if (Array.isArray(this.endpoints)) {
return this.endpoints;
}
const endpoints: IWebServiceEndpoint[] = [];
{
const endpoint = new OwnHTLCEndpoint({
pluginRegistry: this.pluginRegistry,
logLevel: this.options.logLevel,
});
endpoints.push(endpoint);
}
{
const endpoint = new CounterpartyHTLCEndpoint({
pluginRegistry: this.pluginRegistry,
logLevel: this.options.logLevel,
});
endpoints.push(endpoint);
}
{
const endpoint = new WithdrawCounterpartyEndpoint({
pluginRegistry: this.pluginRegistry,
logLevel: this.options.logLevel,
});
endpoints.push(endpoint);
}
return endpoints;
}
public async ownHTLC(
ownHTLCRequest: OwnHTLCRequest,
): Promise<InvokeContractV1Response> {
const fnTag = `${this.className}#ownHTLC()`;
const connector = this.pluginRegistry.plugins.find(
(plugin) => plugin.getInstanceId() == ownHTLCRequest.connectorInstanceId,
) as PluginLedgerConnectorBesu;
const keychainId = ownHTLCRequest.keychainId;
this.log.debug("Using keychain ID:", keychainId);
const pluginRegistry = this.options.pluginRegistry;
// pluginRegistry.add(connector);
switch (ownHTLCRequest.htlcPackage) {
case HtlcPackage.BesuErc20: {
const pluginHtlc = (this.pluginRegistry.plugins.find((plugin) => {
return (
plugin.getPackageName() ==
"@hyperledger/cactus-plugin-htlc-eth-besu-erc20" /*&&
((plugin as unknown) as PluginHtlcEthBesuErc20).getKeychainId() ==
ownHTLCRequest.keychainId*/
);
}) as unknown) as PluginHtlcEthBesuErc20;
const request: InitializeRequestBesuERC20 = {
connectorId: connector.getInstanceId(),
keychainId: ownHTLCRequest.keychainId,
constructorArgs: ownHTLCRequest.constructorArgs,
web3SigningCredential: ownHTLCRequest.web3SigningCredential,
gas: ownHTLCRequest.gas,
};
const res = await pluginHtlc.initialize(request);
if (
res.transactionReceipt?.status == true &&
res.transactionReceipt?.contractAddress != undefined
) {
const newContractRequest: NewContractRequestBesuERC20 = {
contractAddress: res.transactionReceipt?.contractAddress,
inputAmount: ownHTLCRequest.inputAmount,
outputAmount: ownHTLCRequest.outputAmount,
expiration: ownHTLCRequest.expiration,
hashLock: ownHTLCRequest.hashLock,
tokenAddress: ownHTLCRequest.tokenAddress,
receiver: ownHTLCRequest.receiver,
outputNetwork: ownHTLCRequest.outputNetwork,
outputAddress: ownHTLCRequest.outputAddress,
connectorId: connector.getInstanceId(),
keychainId: ownHTLCRequest.keychainId,
web3SigningCredential: ownHTLCRequest.web3SigningCredential,
gas: ownHTLCRequest.gas,
};
const res2 = await pluginHtlc.newContract(newContractRequest);
return res2;
}
}
case HtlcPackage.Besu: {
const pluginOptions: IPluginHtlcEthBesuOptions = {
instanceId: uuidv4(),
pluginRegistry,
};
const factoryHTLC = new PluginFactoryHtlcEthBesu({
pluginImportType: PluginImportType.Local,
});
const pluginHtlc = await factoryHTLC.create(pluginOptions);
const request: InitializeRequestBesu = {
connectorId: connector.getInstanceId(),
keychainId: ownHTLCRequest.keychainId,
constructorArgs: ownHTLCRequest.constructorArgs,
web3SigningCredential: ownHTLCRequest.web3SigningCredential,
gas: ownHTLCRequest.gas,
};
const res = await pluginHtlc.initialize(request);
if (
res.transactionReceipt?.status == true &&
res.transactionReceipt?.contractAddress != undefined
) {
const newContractRequest: NewContractObj = {
contractAddress: res.transactionReceipt?.contractAddress,
outputAmount: ownHTLCRequest.outputAmount,
expiration: ownHTLCRequest.expiration,
hashLock: ownHTLCRequest.hashLock,
receiver: ownHTLCRequest.receiver,
inputAmount: ownHTLCRequest.inputAmount,
outputNetwork: ownHTLCRequest.outputNetwork,
outputAddress: ownHTLCRequest.outputAddress,
connectorId: connector.getInstanceId(),
keychainId: ownHTLCRequest.keychainId,
web3SigningCredential: ownHTLCRequest.web3SigningCredential,
gas: ownHTLCRequest.gas,
};
const res2 = await pluginHtlc.newContract(newContractRequest);
return res2;
}
}
default: {
throw new Error(
`${fnTag} Unrecognized HTLC Package: ` +
`${ownHTLCRequest.htlcPackage} Supported ones are: ` +
`${Object.values(HtlcPackage).join(";")}`,
);
}
}
}
public async counterpartyHTLC(
counterpartyHTLCRequest: CounterpartyHTLCRequest,
): Promise<InvokeContractV1Response> {
const fnTag = `${this.className}#counterpartyHTLC()`;
const pluginRegistry = this.options.pluginRegistry;
switch (counterpartyHTLCRequest.htlcPackage) {
case HtlcPackage.BesuErc20: {
const pluginHtlc = (this.pluginRegistry.plugins.find((plugin) => {
return (
plugin.getPackageName() ==
"@hyperledger/cactus-plugin-htlc-eth-besu-erc20" /*&&
((plugin as unknown) as PluginHtlcEthBesuErc20).getKeychainId() ==
counterpartyHTLCRequest.keychainId*/
);
}) as unknown) as PluginHtlcEthBesuErc20;
const getSingleStatusReq = {
id: counterpartyHTLCRequest.htlcId,
web3SigningCredential: counterpartyHTLCRequest.web3SigningCredential,
connectorId: counterpartyHTLCRequest.connectorInstanceId,
keychainId: counterpartyHTLCRequest.keychainId,
};
const res = await pluginHtlc.getSingleStatus(getSingleStatusReq);
return res;
}
case HtlcPackage.Besu: {
const pluginOptions: IPluginHtlcEthBesuOptions = {
instanceId: uuidv4(),
pluginRegistry,
};
const factoryHTLC = new PluginFactoryHtlcEthBesu({
pluginImportType: PluginImportType.Local,
});
const pluginHtlc = await factoryHTLC.create(pluginOptions);
const getSingleStatusReq = {
id: counterpartyHTLCRequest.htlcId,
web3SigningCredential: counterpartyHTLCRequest.web3SigningCredential,
connectorId: counterpartyHTLCRequest.connectorInstanceId,
keychainId: counterpartyHTLCRequest.keychainId,
};
const res = await pluginHtlc.getSingleStatus(getSingleStatusReq);
return res;
}
default: {
throw new Error(
`${fnTag} Unrecognized HTLC Package: ` +
`${counterpartyHTLCRequest.htlcPackage} Supported ones are: ` +
`${Object.values(HtlcPackage).join(";")}`,
);
}
}
}
public async withdrawCounterparty(
withdrawCounterpartyRequest: WithdrawCounterpartyRequest,
): Promise<InvokeContractV1Response> {
const fnTag = `${this.className}#withdrawCounterparty()`;
// const connector = this.pluginRegistry.plugins.find(
// (plugin) =>
// plugin.getInstanceId() ==
// withdrawCounterpartyRequest.connectorInstanceId,
// ) as PluginLedgerConnectorBesu;
const pluginRegistry = this.options.pluginRegistry;
// pluginRegistry.add(connector);
switch (withdrawCounterpartyRequest.htlcPackage) {
case HtlcPackage.BesuErc20: {
const pluginHtlc = (this.pluginRegistry.plugins.find((plugin) => {
return (
plugin.getPackageName() ==
"@hyperledger/cactus-plugin-htlc-eth-besu-erc20" /*&&
((plugin as unknown) as PluginHtlcEthBesuErc20).getKeychainId() ==
withdrawCounterpartyRequest.keychainId*/
);
}) as unknown) as PluginHtlcEthBesuErc20;
const withdrawRequest: WithdrawRequestBesuERC20 = {
id: withdrawCounterpartyRequest.htlcId,
secret: withdrawCounterpartyRequest.secret,
web3SigningCredential:
withdrawCounterpartyRequest.web3SigningCredential,
connectorId: withdrawCounterpartyRequest.connectorInstanceId,
keychainId: withdrawCounterpartyRequest.keychainId,
};
const res = await pluginHtlc.withdraw(withdrawRequest);
return res;
}
case HtlcPackage.Besu: {
const pluginOptions: IPluginHtlcEthBesuOptions = {
instanceId: uuidv4(),
pluginRegistry,
};
const factoryHTLC = new PluginFactoryHtlcEthBesu({
pluginImportType: PluginImportType.Local,
});
const pluginHtlc = await factoryHTLC.create(pluginOptions);
const withdrawRequest: WithdrawReq = {
id: withdrawCounterpartyRequest.htlcId,
secret: withdrawCounterpartyRequest.secret,
web3SigningCredential:
withdrawCounterpartyRequest.web3SigningCredential,
connectorId: withdrawCounterpartyRequest.connectorInstanceId,
keychainId: withdrawCounterpartyRequest.keychainId,
};
const res2 = await pluginHtlc.withdraw(withdrawRequest);
return res2;
}
default: {
throw new Error(
`${fnTag} Unrecognized HTLC Package: ` +
`${withdrawCounterpartyRequest.htlcPackage} Supported ones are: ` +
`${Object.values(HtlcPackage).join(";")}`,
);
}
}
}
} | the_stack |
import { AuthorizationServerOptions } from "../../authorization_server";
import { isClientConfidential, OAuthClient } from "../../entities/client.entity";
import { OAuthScope } from "../../entities/scope.entity";
import { OAuthToken } from "../../entities/token.entity";
import { OAuthUser } from "../../entities/user.entity";
import { OAuthException } from "../../exceptions/oauth.exception";
import { OAuthTokenRepository } from "../../repositories/access_token.repository";
import { OAuthAuthCodeRepository } from "../../repositories/auth_code.repository";
import { OAuthClientRepository } from "../../repositories/client.repository";
import { OAuthScopeRepository } from "../../repositories/scope.repository";
import { ExtraAccessTokenFields, OAuthUserRepository } from "../../repositories/user.repository";
import { AuthorizationRequest } from "../../requests/authorization.request";
import { RequestInterface } from "../../requests/request";
import { BearerTokenResponse } from "../../responses/bearer_token.response";
import { ResponseInterface } from "../../responses/response";
import { arrayDiff } from "../../utils/array";
import { base64decode } from "../../utils/base64";
import { DateInterval } from "../../utils/date_interval";
import { JwtInterface } from "../../utils/jwt";
import { getSecondsUntil, roundToSeconds } from "../../utils/time";
import { GrantIdentifier, GrantInterface } from "./grant.interface";
export interface ITokenData {
iss: undefined;
sub: string | undefined;
aud: undefined;
exp: number;
nbf: number;
iat: number;
jti: string;
cid: string;
scope: string;
}
export abstract class AbstractGrant implements GrantInterface {
public readonly options: AuthorizationServerOptions = {
requiresPKCE: true,
notBeforeLeeway: 0,
tokenCID: "name",
};
protected readonly scopeDelimiterString = " ";
protected readonly supportedGrantTypes: GrantIdentifier[] = [
"client_credentials",
"authorization_code",
"refresh_token",
"password",
"implicit",
];
abstract readonly identifier: GrantIdentifier;
constructor(
protected readonly authCodeRepository: OAuthAuthCodeRepository,
protected readonly clientRepository: OAuthClientRepository,
protected readonly tokenRepository: OAuthTokenRepository,
protected readonly scopeRepository: OAuthScopeRepository,
protected readonly userRepository: OAuthUserRepository,
protected readonly jwt: JwtInterface,
) {}
async makeBearerTokenResponse(
client: OAuthClient,
accessToken: OAuthToken,
scopes: OAuthScope[] = [],
extraJwtFields: ExtraAccessTokenFields = {},
) {
const scope = scopes.map(scope => scope.name).join(this.scopeDelimiterString);
const encryptedAccessToken = await this.encryptAccessToken(client, accessToken, scopes, extraJwtFields);
let encryptedRefreshToken: string | undefined = undefined;
if (accessToken.refreshToken) {
encryptedRefreshToken = await this.encryptRefreshToken(client, accessToken, scopes);
}
const bearerTokenResponse = new BearerTokenResponse(accessToken);
bearerTokenResponse.body = {
token_type: "Bearer",
expires_in: getSecondsUntil(accessToken.accessTokenExpiresAt),
access_token: encryptedAccessToken,
refresh_token: encryptedRefreshToken,
scope,
};
return bearerTokenResponse;
}
protected encryptRefreshToken(client: OAuthClient, refreshToken: OAuthToken, scopes: OAuthScope[]) {
const expiresAtMs = refreshToken.refreshTokenExpiresAt?.getTime() ?? refreshToken.accessTokenExpiresAt.getTime();
return this.encrypt({
client_id: client.id,
access_token_id: refreshToken.accessToken,
refresh_token_id: refreshToken.refreshToken,
scope: scopes.map(scope => scope.name).join(this.scopeDelimiterString),
user_id: refreshToken.user?.id,
expire_time: Math.ceil(expiresAtMs / 1000),
// token_version: 1, // @todo token version?
});
}
protected encryptAccessToken(
client: OAuthClient,
accessToken: OAuthToken,
scopes: OAuthScope[],
extraJwtFields: ExtraAccessTokenFields,
) {
return this.encrypt(<ITokenData | any>{
// non standard claims
...extraJwtFields,
cid: client[this.options.tokenCID],
scope: scopes.map(scope => scope.name).join(this.scopeDelimiterString),
// standard claims
iss: undefined, // @see https://tools.ietf.org/html/rfc7519#section-4.1.1
sub: accessToken.user?.id, // @see https://tools.ietf.org/html/rfc7519#section-4.1.2
aud: undefined, // @see https://tools.ietf.org/html/rfc7519#section-4.1.3
exp: roundToSeconds(accessToken.accessTokenExpiresAt.getTime()), // @see https://tools.ietf.org/html/rfc7519#section-4.1.4
nbf: roundToSeconds(Date.now()) - this.options.notBeforeLeeway, // @see https://tools.ietf.org/html/rfc7519#section-4.1.5
iat: roundToSeconds(Date.now()), // @see https://tools.ietf.org/html/rfc7519#section-4.1.6
jti: accessToken.accessToken, // @see https://tools.ietf.org/html/rfc7519#section-4.1.7
});
}
protected async validateClient(request: RequestInterface): Promise<OAuthClient> {
const [clientId, clientSecret] = this.getClientCredentials(request);
const grantType = this.getGrantType(request);
const client = await this.clientRepository.getByIdentifier(clientId);
if (isClientConfidential(client) && !clientSecret) {
throw OAuthException.invalidClient("Confidential clients require client_secret.");
}
const userValidationSuccess = await this.clientRepository.isClientValid(grantType, client, clientSecret);
if (!userValidationSuccess) {
throw OAuthException.invalidClient();
}
if (grantType === "client_credentials") {
if (!client.secret || client.secret !== clientSecret) {
throw OAuthException.invalidClient("Invalid client_credentials");
}
}
return client;
}
protected getClientCredentials(request: RequestInterface): [string, string | undefined] {
const [basicAuthUser, basicAuthPass] = this.getBasicAuthCredentials(request);
let clientId = this.getRequestParameter("client_id", request, basicAuthUser);
if (!clientId) {
throw OAuthException.invalidRequest("client_id");
}
let clientSecret = this.getRequestParameter("client_secret", request, basicAuthPass);
if (Array.isArray(clientId) && clientId.length > 0) clientId = clientId[0];
if (Array.isArray(clientSecret) && clientSecret.length > 0) clientSecret = clientSecret[0];
return [clientId, clientSecret];
}
protected getBasicAuthCredentials(request: RequestInterface) {
if (!request.headers?.hasOwnProperty("authorization")) {
return [undefined, undefined];
}
const header = request.headers["authorization"];
if (!header || !header.startsWith("Basic ")) {
return [undefined, undefined];
}
const decoded = base64decode(header.substr(6, header.length));
if (!decoded.includes(":")) {
return [undefined, undefined];
}
return decoded.split(":");
}
protected async validateScopes(
scopes: undefined | string | string[] = [],
redirectUri?: string,
): Promise<OAuthScope[]> {
if (typeof scopes === "string") {
scopes = scopes.split(this.scopeDelimiterString);
}
if (!scopes || scopes.length === 0 || scopes[0] === "") {
return [];
}
const validScopes = await this.scopeRepository.getAllByIdentifiers(scopes);
const invalidScopes = arrayDiff(
scopes,
validScopes.map(scope => scope.name),
);
if (invalidScopes.length > 0) {
throw OAuthException.invalidScope(invalidScopes.join(", "), redirectUri);
}
return validScopes;
}
protected async issueAccessToken(
accessTokenTTL: DateInterval,
client: OAuthClient,
user?: OAuthUser | null,
scopes: OAuthScope[] = [],
): Promise<OAuthToken> {
const accessToken = await this.tokenRepository.issueToken(client, scopes, user);
accessToken.accessTokenExpiresAt = accessTokenTTL.getEndDate();
await this.tokenRepository.persist(accessToken);
return accessToken;
}
issueRefreshToken(accessToken: OAuthToken): Promise<OAuthToken> {
return this.tokenRepository.issueRefreshToken(accessToken);
}
private getGrantType(request: RequestInterface): GrantIdentifier {
const result =
this.getRequestParameter("grant_type", request) ?? this.getQueryStringParameter("grant_type", request);
if (!result || !this.supportedGrantTypes.includes(result)) {
throw OAuthException.invalidRequest("grant_type");
}
if (this.identifier !== result) {
throw OAuthException.invalidRequest("grant_type", "something went wrong"); // @todo remove the something went wrong
}
return result;
}
protected getRequestParameter(param: string, request: RequestInterface, defaultValue?: any) {
return request.body?.[param] ?? defaultValue;
}
protected getQueryStringParameter(param: string, request: RequestInterface, defaultValue?: any) {
return request.query?.[param] ?? defaultValue;
}
protected encrypt(unencryptedData: string | Buffer | Record<string, unknown>): Promise<string> {
return this.jwt.sign(unencryptedData);
}
protected async decrypt(encryptedData: string) {
return await this.jwt.verify(encryptedData);
}
validateAuthorizationRequest(_request: RequestInterface): Promise<AuthorizationRequest> {
throw new Error("Grant does not support the request");
}
canRespondToAccessTokenRequest(request: RequestInterface): boolean {
return this.getRequestParameter("grant_type", request) === this.identifier;
}
canRespondToAuthorizationRequest(_request: RequestInterface): boolean {
return false;
}
async completeAuthorizationRequest(_authorizationRequest: AuthorizationRequest): Promise<ResponseInterface> {
throw new Error("Grant does not support the request");
}
async respondToAccessTokenRequest(_req: RequestInterface, _accessTokenTTL: DateInterval): Promise<ResponseInterface> {
throw new Error("Grant does not support the request");
}
} | the_stack |
import * as d3 from "d3";
import { Dataset } from "../core/dataset";
import { AttributeToProjector, IAccessor, Projector, SimpleSelection } from "../core/interfaces";
import * as Scales from "../scales";
import { QuantitativeScale } from "../scales/quantitativeScale";
import * as Utils from "../utils";
import * as Drawers from "../drawers";
import { AreaSVGDrawer, makeAreaCanvasDrawStep } from "../drawers/areaDrawer";
import { ProxyDrawer } from "../drawers/drawer";
import { LineSVGDrawer, makeLineCanvasDrawStep } from "../drawers/lineDrawer";
import * as Plots from "./";
import { Line } from "./linePlot";
import { Plot } from "./plot";
export class Area<X> extends Line<X> {
private static _Y0_KEY = "y0";
private _lineDrawers: Utils.Map<Dataset, ProxyDrawer>;
private _constantBaselineValueProvider: () => number[];
/**
* An Area Plot draws a filled region (area) between Y and Y0.
*
* @constructor
*/
constructor() {
super();
this.addClass("area-plot");
this.y0(0); // default
this.attr("fill-opacity", 0.25);
this.attr("fill", new Scales.Color().range()[0]);
this._lineDrawers = new Utils.Map<Dataset, ProxyDrawer>();
}
public y(): Plots.ITransformableAccessorScaleBinding<number, number>;
public y(y: number | IAccessor<number>): this;
public y(y: number | IAccessor<number>, yScale: QuantitativeScale<number>): this;
public y(y?: number | IAccessor<number>, yScale?: QuantitativeScale<number>): any {
if (y == null) {
return super.y();
}
if (yScale == null) {
super.y(y);
} else {
super.y(y, yScale);
}
if (yScale != null) {
const y0 = this.y0().accessor;
if (y0 != null) {
this._bindProperty(Area._Y0_KEY, y0, yScale);
}
this._updateYScale();
}
return this;
}
/**
* Gets the AccessorScaleBinding for Y0.
*/
public y0(): Plots.IAccessorScaleBinding<number, number>;
/**
* Sets Y0 to a constant number or the result of an Accessor<number>.
* If a Scale has been set for Y, it will also be used to scale Y0.
*
* @param {number|Accessor<number>} y0
* @returns {Area} The calling Area Plot.
*/
public y0(y0: number | IAccessor<number>): this;
public y0(y0?: number | IAccessor<number>): any {
if (y0 == null) {
return this._propertyBindings.get(Area._Y0_KEY);
}
const yBinding = this.y();
const yScale = yBinding && yBinding.scale;
this._bindProperty(Area._Y0_KEY, y0, yScale);
this._updateYScale();
this.render();
return this;
}
protected _onDatasetUpdate() {
super._onDatasetUpdate();
this._updateYScale();
}
protected _addDataset(dataset: Dataset) {
this._lineDrawers.set(dataset, new Drawers.ProxyDrawer(
() => new LineSVGDrawer(),
(ctx) => new Drawers.CanvasDrawer(ctx, makeLineCanvasDrawStep(() => {
const xProjector = Plot._scaledAccessor(this.x());
const yProjector = Plot._scaledAccessor(this.y());
return this._d3LineFactory(dataset, xProjector, yProjector);
}),
)),
);
super._addDataset(dataset);
return this;
}
protected _createNodesForDataset(dataset: Dataset) {
super._createNodesForDataset(dataset);
const drawer = this._lineDrawers.get(dataset);
if (this.renderer() === "svg") {
drawer.useSVG(this._renderArea);
} else {
drawer.useCanvas(this._canvas);
}
return drawer;
}
protected _removeDatasetNodes(dataset: Dataset) {
super._removeDatasetNodes(dataset);
this._lineDrawers.get(dataset).remove();
}
protected _additionalPaint() {
const drawSteps = this._generateLineDrawSteps();
const dataToDraw = this._getDataToDraw();
this.datasets().forEach((dataset) => {
const appliedDrawSteps = Plot.applyDrawSteps(drawSteps, dataset);
this._lineDrawers.get(dataset).draw(dataToDraw.get(dataset), appliedDrawSteps);
});
}
private _generateLineDrawSteps() {
const drawSteps: Drawers.DrawStep[] = [];
if (this._animateOnNextRender()) {
const attrToProjector = this._generateLineAttrToProjector();
attrToProjector["d"] = this._constructLineProjector(Plot._scaledAccessor(this.x()), this._getResetYFunction());
drawSteps.push({ attrToProjector: attrToProjector, animator: this._getAnimator(Plots.Animator.RESET) });
}
drawSteps.push({
attrToProjector: this._generateLineAttrToProjector(),
animator: this._getAnimator(Plots.Animator.MAIN),
});
return drawSteps;
}
private _generateLineAttrToProjector() {
const lineAttrToProjector = this._getAttrToProjector();
lineAttrToProjector["d"] = this._constructLineProjector(Plot._scaledAccessor(this.x()), Plot._scaledAccessor(this.y()));
return lineAttrToProjector;
}
protected _createDrawer(dataset: Dataset) {
return new ProxyDrawer(
() => new AreaSVGDrawer(),
(ctx) => {
return new Drawers.CanvasDrawer(ctx, makeAreaCanvasDrawStep(
() => {
const [ xProjector, yProjector, y0Projector ] = this._coordinateProjectors();
const definedProjector = this._createDefinedProjector(xProjector, yProjector);
return this._createAreaGenerator(xProjector, yProjector, y0Projector, definedProjector, dataset);
},
() => {
const [ xProjector, yProjector ] = this._coordinateProjectors();
const definedProjector = this._createDefinedProjector(xProjector, yProjector);
return this._createTopLineGenerator(xProjector, yProjector, definedProjector, dataset);
},
));
},
);
}
protected _generateDrawSteps(): Drawers.DrawStep[] {
const drawSteps: Drawers.DrawStep[] = [];
if (this._animateOnNextRender()) {
const attrToProjector = this._getAttrToProjector();
attrToProjector["d"] = this._constructAreaProjector(
Plot._scaledAccessor(this.x()),
this._getResetYFunction(),
Plot._scaledAccessor(this.y0()),
);
drawSteps.push({ attrToProjector: attrToProjector, animator: this._getAnimator(Plots.Animator.RESET) });
}
drawSteps.push({
attrToProjector: this._getAttrToProjector(),
animator: this._getAnimator(Plots.Animator.MAIN),
});
return drawSteps;
}
protected _updateYScale() {
const extents = this.getExtentsForProperty("y0");
const extent = Utils.Array.flatten<number>(extents);
const uniqExtentVals = Utils.Array.uniq<number>(extent);
const constantBaseline = uniqExtentVals.length === 1 ? uniqExtentVals[0] : null;
const yBinding = this.y();
const yScale = <QuantitativeScale<number>> (yBinding && yBinding.scale);
if (yScale == null) {
return;
}
if (this._constantBaselineValueProvider != null) {
yScale.removePaddingExceptionsProvider(this._constantBaselineValueProvider);
this._constantBaselineValueProvider = null;
}
if (constantBaseline != null) {
this._constantBaselineValueProvider = () => [constantBaseline];
yScale.addPaddingExceptionsProvider(this._constantBaselineValueProvider);
}
}
protected _getResetYFunction() {
return Plot._scaledAccessor(this.y0());
}
protected _coordinateProjectors(): [Projector, Projector, Projector] {
return [
Plot._scaledAccessor(this.x()),
Plot._scaledAccessor(this.y()),
Plot._scaledAccessor(this.y0()),
];
}
protected _propertyProjectors(): AttributeToProjector {
const propertyToProjectors = super._propertyProjectors();
const [ xProject, yProjector, y0Projector ] = this._coordinateProjectors();
propertyToProjectors["d"] = this._constructAreaProjector(xProject, yProjector, y0Projector);
return propertyToProjectors;
}
public selections(datasets = this.datasets()): SimpleSelection<any> {
if (this.renderer() === "canvas") {
return d3.selectAll();
}
const allSelections = super.selections(datasets).nodes();
const lineDrawers = datasets.map((dataset) => this._lineDrawers.get(dataset))
.filter((drawer) => drawer != null);
lineDrawers.forEach((ld) => allSelections.push(...ld.getVisualPrimitives()));
return d3.selectAll(allSelections);
}
protected _constructAreaProjector(xProjector: Projector, yProjector: Projector, y0Projector: Projector) {
const definedProjector = this._createDefinedProjector(
Plot._scaledAccessor(this.x()),
Plot._scaledAccessor(this.y()),
);
return (datum: any[], index: number, dataset: Dataset) => {
const areaGenerator = this._createAreaGenerator(xProjector, yProjector, y0Projector, definedProjector, dataset);
return areaGenerator(datum);
};
}
private _createDefinedProjector(xProjector: Projector, yProjector: Projector) {
return (d: any, i: number, dataset: Dataset) => {
const positionX = xProjector(d, i, dataset);
const positionY = yProjector(d, i, dataset);
return Utils.Math.isValidNumber(positionX) && Utils.Math.isValidNumber(positionY);
};
}
private _createAreaGenerator(
xProjector: Projector,
yProjector: Projector,
y0Projector: Projector,
definedProjector: Projector,
dataset: Dataset,
) {
// just runtime error if user passes curveBundle to area plot
const curveFactory = this._getCurveFactory() as d3.CurveFactory;
const areaGenerator = d3.area()
.x((innerDatum, innerIndex) => xProjector(innerDatum, innerIndex, dataset))
.y1((innerDatum, innerIndex) => yProjector(innerDatum, innerIndex, dataset))
.y0((innerDatum, innerIndex) => y0Projector(innerDatum, innerIndex, dataset))
.curve(curveFactory)
.defined((innerDatum, innerIndex) => definedProjector(innerDatum, innerIndex, dataset));
return areaGenerator;
}
private _createTopLineGenerator(
xProjector: Projector,
yProjector: Projector,
definedProjector: Projector,
dataset: Dataset,
) {
const curveFactory = this._getCurveFactory() as d3.CurveFactory;
const areaGenerator = d3.line()
.x((innerDatum, innerIndex) => xProjector(innerDatum, innerIndex, dataset))
.y((innerDatum, innerIndex) => yProjector(innerDatum, innerIndex, dataset))
.curve(curveFactory)
.defined((innerDatum, innerIndex) => definedProjector(innerDatum, innerIndex, dataset));
return areaGenerator;
}
} | the_stack |
import {
Input,
OnDestroy,
OnInit,
Output,
NgZone,
Directive,
OnChanges,
SimpleChanges,
} from '@angular/core';
import {Observable} from 'rxjs';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
import {MapAnchorPoint} from '../map-anchor-point';
/**
* Default options for the Google Maps marker component. Displays a marker
* at the Googleplex.
*/
export const DEFAULT_MARKER_OPTIONS = {
position: {lat: 37.421995, lng: -122.084092},
};
/**
* Angular component that renders a Google Maps marker via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/marker
*/
@Directive({
selector: 'map-marker',
exportAs: 'mapMarker',
})
export class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint {
private _eventManager = new MapEventManager(this._ngZone);
/**
* Title of the marker.
* See: developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.title
*/
@Input()
set title(title: string) {
this._title = title;
}
private _title: string;
/**
* Position of the marker. See:
* developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.position
*/
@Input()
set position(position: google.maps.LatLngLiteral | google.maps.LatLng) {
this._position = position;
}
private _position: google.maps.LatLngLiteral | google.maps.LatLng;
/**
* Label for the marker.
* See: developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.label
*/
@Input()
set label(label: string | google.maps.MarkerLabel) {
this._label = label;
}
private _label: string | google.maps.MarkerLabel;
/**
* Whether the marker is clickable. See:
* developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.clickable
*/
@Input()
set clickable(clickable: boolean) {
this._clickable = clickable;
}
private _clickable: boolean;
/**
* Options used to configure the marker.
* See: developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions
*/
@Input()
set options(options: google.maps.MarkerOptions) {
this._options = options;
}
private _options: google.maps.MarkerOptions;
/**
* Icon to be used for the marker.
* See: https://developers.google.com/maps/documentation/javascript/reference/marker#Icon
*/
@Input()
set icon(icon: string | google.maps.Icon | google.maps.Symbol) {
this._icon = icon;
}
private _icon: string | google.maps.Icon | google.maps.Symbol;
/**
* Whether the marker is visible.
* See: developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.visible
*/
@Input()
set visible(value: boolean) {
this._visible = value;
}
private _visible: boolean;
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.animation_changed
*/
@Output() readonly animationChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('animation_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.click
*/
@Output() readonly mapClick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('click');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.clickable_changed
*/
@Output() readonly clickableChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('clickable_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.cursor_changed
*/
@Output() readonly cursorChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('cursor_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.dblclick
*/
@Output() readonly mapDblclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dblclick');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.drag
*/
@Output() readonly mapDrag: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('drag');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.dragend
*/
@Output() readonly mapDragend: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragend');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.draggable_changed
*/
@Output() readonly draggableChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('draggable_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.dragstart
*/
@Output() readonly mapDragstart: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragstart');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.flat_changed
*/
@Output() readonly flatChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('flat_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.icon_changed
*/
@Output() readonly iconChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('icon_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.mousedown
*/
@Output() readonly mapMousedown: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mousedown');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.mouseout
*/
@Output() readonly mapMouseout: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseout');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.mouseover
*/
@Output() readonly mapMouseover: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseover');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.mouseup
*/
@Output() readonly mapMouseup: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseup');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.position_changed
*/
@Output() readonly positionChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('position_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.rightclick
*/
@Output() readonly mapRightclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('rightclick');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.shape_changed
*/
@Output() readonly shapeChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('shape_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.title_changed
*/
@Output() readonly titleChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('title_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.visible_changed
*/
@Output() readonly visibleChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('visible_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.zindex_changed
*/
@Output() readonly zindexChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('zindex_changed');
/**
* The underlying google.maps.Marker object.
*
* See developers.google.com/maps/documentation/javascript/reference/marker#Marker
*/
marker?: google.maps.Marker;
constructor(private readonly _googleMap: GoogleMap, private _ngZone: NgZone) {}
ngOnInit() {
if (this._googleMap._isBrowser) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.marker = new google.maps.Marker(this._combineOptions());
});
this._assertInitialized();
this.marker.setMap(this._googleMap.googleMap!);
this._eventManager.setTarget(this.marker);
}
}
ngOnChanges(changes: SimpleChanges) {
const {marker, _title, _position, _label, _clickable, _icon, _visible} = this;
if (marker) {
if (changes['options']) {
marker.setOptions(this._combineOptions());
}
if (changes['title'] && _title !== undefined) {
marker.setTitle(_title);
}
if (changes['position'] && _position) {
marker.setPosition(_position);
}
if (changes['label'] && _label !== undefined) {
marker.setLabel(_label);
}
if (changes['clickable'] && _clickable !== undefined) {
marker.setClickable(_clickable);
}
if (changes['icon'] && _icon) {
marker.setIcon(_icon);
}
if (changes['visible'] && _visible !== undefined) {
marker.setVisible(_visible);
}
}
}
ngOnDestroy() {
this._eventManager.destroy();
if (this.marker) {
this.marker.setMap(null);
}
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getAnimation
*/
getAnimation(): google.maps.Animation | null {
this._assertInitialized();
return this.marker.getAnimation() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getClickable
*/
getClickable(): boolean {
this._assertInitialized();
return this.marker.getClickable();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getCursor
*/
getCursor(): string | null {
this._assertInitialized();
return this.marker.getCursor() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getDraggable
*/
getDraggable(): boolean {
this._assertInitialized();
return !!this.marker.getDraggable();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getIcon
*/
getIcon(): string | google.maps.Icon | google.maps.Symbol | null {
this._assertInitialized();
return this.marker.getIcon() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getLabel
*/
getLabel(): google.maps.MarkerLabel | null {
this._assertInitialized();
return this.marker.getLabel() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getOpacity
*/
getOpacity(): number | null {
this._assertInitialized();
return this.marker.getOpacity() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getPosition
*/
getPosition(): google.maps.LatLng | null {
this._assertInitialized();
return this.marker.getPosition() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getShape
*/
getShape(): google.maps.MarkerShape | null {
this._assertInitialized();
return this.marker.getShape() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getTitle
*/
getTitle(): string | null {
this._assertInitialized();
return this.marker.getTitle() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getVisible
*/
getVisible(): boolean {
this._assertInitialized();
return this.marker.getVisible();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getZIndex
*/
getZIndex(): number | null {
this._assertInitialized();
return this.marker.getZIndex() || null;
}
/** Gets the anchor point that can be used to attach other Google Maps objects. */
getAnchor(): google.maps.MVCObject {
this._assertInitialized();
return this.marker;
}
/** Creates a combined options object using the passed-in options and the individual inputs. */
private _combineOptions(): google.maps.MarkerOptions {
const options = this._options || DEFAULT_MARKER_OPTIONS;
return {
...options,
title: this._title || options.title,
position: this._position || options.position,
label: this._label || options.label,
clickable: this._clickable ?? options.clickable,
map: this._googleMap.googleMap,
icon: this._icon || options.icon,
visible: this._visible ?? options.visible,
};
}
private _assertInitialized(): asserts this is {marker: google.maps.Marker} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this._googleMap.googleMap) {
throw Error(
'Cannot access Google Map information before the API has been initialized. ' +
'Please wait for the API to load before trying to interact with it.',
);
}
if (!this.marker) {
throw Error(
'Cannot interact with a Google Map Marker before it has been ' +
'initialized. Please wait for the Marker to load before trying to interact with it.',
);
}
}
}
} | the_stack |
declare namespace AMap {
type EventCallback = (...args: any[]) => void;
type GenericEventCallback<T> = (res: T) => void;
/**
* 加载插件
* @param pluginNames
* @param ready
*/
function plugin(pluginNames: string[], ready?: () => void): void;
/**
* 加载服务
* @param serviceName
* @param ready
*/
function service(serviceName: string, ready?: () => void): void;
namespace event {
/**
* 注册DOM对象事件:给DOM对象注册事件,并返回eventListener。运行AMap.event.removeListener(eventListener)可以删除该事件的监听器。
* @param instance:需注册事件的DOM对象(必填)
* @param eventName:事件名称(必填)
* @param handler:事件功能函数(必填)
* @param context:事件上下文(可选,缺省时,handler中this指向参数instance引用的对象,否则this指向context引用的对象)
*/
const addDomListener: (instance: any, eventName: string, handler: EventCallback, context?: any) => EventListener;
/**
* 注册对象事件:给对象注册事件,并返回eventListener。运行AMap.event.removeListener(eventListener)可以删除该事件的监听器。
* @param instance:需注册事件的对象(必填)
* @param eventName:事件名称(必填)
* @param handler:事件功能函数(必填)
* @param context:事件上下文(可选,缺省时,handler中this指向参数instance引用的对象,否则this指向context引用的对象)
*/
const addListener: (instance: any, eventName: string, handler: EventCallback, context?: any) => EventListener;
/**
* 类似于addListener,但处理程序会在处理完第一个事件后将自已移除。
*/
const addListenerOnce: (instance: any, eventName: string, handler: EventCallback, context?: any) => EventListener;
/**
* 删除由上述 event.addDomListener 和 event.addListener 传回的指定侦听器。
*/
const removeListener: (listener: EventListener) => void;
/**
* 触发非DOM事件:触发非DOM事件eventName,extArgs将扩展到事件监听函数(handler)接受到的event参数中。如:在extArgs内写入{m:10,p:2},eventName监听函数(handler)可以接收到包含m,p两个key值的event对象。
*/
const trigger: (instance: any, eventName: string, extArgs: any) => void;
}
/**
* 此对象用于表示地图、覆盖物、叠加层上的各种鼠标事件返回,包含以下字段:
*/
interface MapsEventOptions {
lnglat: LngLat;
pixel: Pixel;
type: string;
target: any;
}
abstract class EventBindable {
on(eventName: string, callback: EventCallback): void;
off(eventName: string, callback: EventCallback): void;
}
/* --------------------------- 基础类 --------------------------- */
/* 参考地址:http://lbs.amap.com/api/javascript-api/reference/core */
/**
* 像素坐标,确定地图上的一个像素点。
*/
class Pixel {
/**
* 构造一个像素坐标对象。
*/
constructor(x: number, y: number);
/**
* 获得X方向像素坐标
*/
getX(): number;
/**
* 获得Y方向像素坐标
*/
getY(): number;
/**
* 当前像素坐标与传入像素坐标是否相等
*/
equals(point: Pixel): boolean;
/**
* 以字符串形式返回像素坐标对象
*/
toString(): string;
}
/**
* 地物对象的像素尺寸
*/
class Size {
/**
* 构造尺寸对象
* @param width 宽度,单位:像素
* @param height 高度,单位:像素
*/
constructor(width: number, height: number);
/**
* 获得宽度
*/
getWidth(): number;
/**
* 获得高度
*/
getHeight(): number;
/**
* 以字符串形式返回尺寸大小对象
*/
toString(): string;
}
/**
* 经纬度坐标,确定地图上的一个点
*/
class LngLat {
/**
* 构造一个地理坐标对象
* @param lng 经度
* @param lat 纬度
*/
constructor(lng: number, lat: number);
/**
* 当前经纬度坐标值经度移动w,纬度移动s,得到新的坐标。
*
* @param w 经度,向右移为正值,单位:米
* @param s 纬度,向上移为正值,单位:米
*/
offset(w: number, s: number): LngLat;
/**
* 计算当前经纬度和传入经纬度或者经纬度数组连线之间的地面距离,单位为米
*
* @param lnglat 传入的经纬度
*/
distance(lnglat: LngLat | [number, number]): number;
/**
* 获取经度值
*/
getLng(): number;
/**
* 获取纬度值
*/
getLat(): number;
/**
* 判断当前坐标对象与传入坐标对象是否相等
*
* @param lnglat 传入坐标对象
*/
equals(lnglat: LngLat): boolean;
/**
* LngLat对象以字符串的形式返回
*/
toString(): string;
}
/**
* 地物对象的经纬度矩形范围
*/
class Bounds {
/**
* 构造一个矩形范围
* @param southWest 西南角经纬度坐标
* @param northEast 东北角经纬度坐标
*/
constructor(southWest: LngLat, northEast: LngLat);
/**
* 判断指定点坐标是否在矩形范围内
* @param point 指定点
*/
contains(point: LngLat): boolean;
/**
* 获取当前Bounds的中心点经纬度坐标
*/
getCenter(): LngLat;
/**
* 获取西南角坐标
*/
getSouthWest(): LngLat;
/**
* 获取东北角坐标
*/
getNorthEast(): LngLat;
/**
* 以字符串形式返回地物对象的矩形范围
*/
toString(): string;
}
interface TileLayerOptions {
map: Map;
tileSize: number;
tileUrl: string;
errorUrl: string;
getTileUrl: (x: number, y: number, z: number) => string;
zIndex: number;
opacity: number;
zooms: number[];
detectRetina: boolean;
}
abstract class Layer extends EventBindable {
setOpacity(alpha: number): void;
show(): void;
hide(): void;
getTiles(): string[];
reload(): void;
setTileUrl(): void;
getZooms(): number[];
setzIndex(index: number): void;
setMap(map: Map): void;
}
class TileLayer extends Layer {
constructor(tileOpt?: {
map: Map,
tileSize?: number | undefined,
tileUrl?: string | undefined,
errorUrl?: string | undefined,
getTileUrl?: ((x: number, y: number, z: number) => string) | undefined,
zIndex?: number | undefined,
opacity?: number | undefined,
zooms?: number[] | undefined,
detectRetina?: boolean | undefined
});
}
namespace TileLayer {
abstract class MapTypeLayer extends Layer {
constructor(options?: {
map: Map,
zIndex?: number | undefined,
opacity?: number | undefined,
zooms?: number[] | undefined,
detectRetina?: boolean | undefined
});
}
class Satellite extends MapTypeLayer {
}
class RoadNet extends MapTypeLayer {
}
class Traffic extends MapTypeLayer {
constructor(options?: {
map: Map,
zIndex?: number | undefined,
opacity?: number | undefined,
zooms?: number[] | undefined,
detectRetina?: boolean | undefined,
autoRefresh?: boolean | undefined,
interval?: number | undefined
});
interval: number;
autoRefresh: boolean;
}
}
class IndoorMap {
constructor(opts: {
zIndex?: number | undefined,
opacity?: number | undefined,
cursor?: string | undefined,
hideFloorBar?: boolean | undefined,
alwaysShow?: boolean | undefined
});
showIndoorMap(indoorid: string, floor: number, shopid: string): void;
showFloor(floor: number, noMove: boolean): void;
setMap(map: Map): void;
show(): void;
hide(): void;
setzIndex(): void;
showFloorBar(): void;
hideFloorBar(): void;
setOpacity(alpha: number): void;
getOpacity(): number;
showLabels(): void;
hideLabels(): void;
getSelectedBuildingId(): string;
getSelectedBuilding(): string;
}
interface MapOptions {
view?: View2D | undefined;
layers?: TileLayer[] | undefined;
level?: number | undefined;
center?: LngLat | undefined;
labelzIndex?: number | undefined;
zooms?: number[] | undefined;
lang?: string | undefined;
cursor?: string | undefined;
crs?: string | undefined;
animateEnable?: boolean | undefined;
isHotspot?: boolean | undefined;
defaultLayer?: TileLayer | undefined;
rotateEnable?: boolean | undefined;
resizeEnable?: boolean | undefined;
showIndoorMap?: boolean | undefined;
indoorMap?: IndoorMap | undefined;
expandZoomRange?: boolean | undefined;
dragEnable?: boolean | undefined;
zoomEnable?: boolean | undefined;
doubleClickZoom?: boolean | undefined;
keyboardEnable?: boolean | undefined;
jogEnable?: boolean | undefined;
scrollWheel?: boolean | undefined;
touchZoom?: boolean | undefined;
mapStyle?: string | undefined;
features?: string[] | undefined;
}
class View2D {
constructor(opt: {
center?: LngLat | undefined,
rotation?: number | undefined,
zoom?: number | undefined,
crs?: 'EPSG3857'|'EPSG3395'|'EPSG4326' | undefined
});
/**
* To silence lint error, this class has to be exists.
*/
toString(): string;
}
class Map extends EventBindable {
constructor(mapDiv: string, opts?: MapOptions);
getZoom(): number;
getLayers(): TileLayer[];
getCenter(): LngLat;
getCity(callback: (result: {
provice: string,
city: string,
citycode: string,
district: string
}) => void): void;
getBounds(): Bounds;
getlabelzIndex(): number;
getLimitBounds(): Bounds;
getLang(): string;
getSize(): Size;
getRotation(): number;
getStatus(): any;
getDefaultCursor(): string;
getResolution(point: LngLat): number;
getScale(dpi: number): number;
setZoom(level: number): void;
setlabelzIndex(index: number): void;
setLayers(layers: TileLayer[]): void;
add(overlayers: any[]): void;
remove(overlayers: any[]): void;
getAllOverlays(type: string): Marker[] | Circle[] | Polygon[] | Polyline[];
setCenter(position: LngLat): void;
setZoomAndCenter(zoomLevel: number, center: LngLat): void;
setCity(city: string, callback: () => void): void;
setBounds(bound: Bounds): void;
setLimitBounds(bound: Bounds): void;
clearLimitBounds(): void;
setLang(lang: string): void;
setRotation(rotation: number): void;
setStatus(status: any): void;
setDefaultCursor(cursor: string): void;
zoomIn(): void;
zoomOut(): void;
panTo(position: LngLat): void;
panBy(x: number, y: number): void;
setFitView(overlayList?: any[]): void;
clearMap(): void;
destroy(): void;
plugin(name: string| string[], callback: () => void): void;
addControl(obj: any): void;
removeControl(obj: any): void;
clearInfoWindow(): void;
pixelToLngLat(pixel: Pixel, level: number): LngLat;
lnglatToPixel(lnglat: LngLat, level: number): Pixel;
containerToLngLat(pixel: Pixel, level: number): LngLat;
lngLatToContainer(lnglat: LngLat, level: number): Pixel;
setMapStyle(style: string): void;
getMapStyle(): string;
setFeatures(features: string[]): void;
getFeatures(): string[];
setDefaultLayer(layer: TileLayer): void;
}
class Icon {
constructor(options?: {
size?: Size | undefined,
imageOffset?: Pixel | undefined,
image?: string | undefined,
imageSize?: Size | undefined
});
getImageSize(): Size;
setImageSize(size: Size): void;
}
/**
* MarkerShape用于划定Marker的可点击区域范围。需要注意的是,在IE浏览器中图标透明区域默认为不触发事件,因此MarkerShape在IE中不起作用。
*/
class MarkerShape {
constructor(options: {
/**
*
* 可点击区域组成元素数组,存放图形的像素坐标等信息,该数组元素由type决定:
* - circle:coords格式为 [x1, y1, r],x1,y1为圆心像素坐标,r为圆半径
* - poly: coords格式为 [x1, y1, x2, y2 … xn, yn],各x,y表示多边形边界像素坐标
* - rect: coords格式为 [x1, y1, x2, y2],x1,y1为矩形左上角像素坐标,x2,y2为矩形右下角像素坐标
* Markshape的像素坐标是指相对于marker的左上角的像素坐标偏移量
*/
coords?: number[] | undefined,
/**
* 可点击区域类型,可选值:
* - circle:圆形
* - poly:多边形
* - rect:矩形
*/
type?: string | undefined
});
/**
* To silence lint error, this class has to be exists.
*/
toString(): string;
}
interface MarkerOptions {
map?: Map | undefined;
position?: LngLat | undefined;
offset?: Pixel | undefined;
icon?: string|Icon | undefined;
content?: string| HTMLElement | undefined;
topWhenClick?: boolean | undefined;
topWhenMouseOver?: boolean | undefined;
draggable?: boolean | undefined;
raiseOnDrag?: boolean | undefined;
cursor?: string | undefined;
visible?: boolean | undefined;
zIndex?: number | undefined;
angle?: number | undefined;
autoRotation?: boolean | undefined;
animation?: string | undefined;
shadow?: Icon | undefined;
title?: string | undefined;
clickable?: boolean | undefined;
shape?: MarkerShape | undefined;
extData?: any;
label?: { content: string, offset: Pixel } | undefined;
}
/**
* 点标记。
*/
class Marker extends EventBindable {
constructor(options?: MarkerOptions);
markOnAMAP(obj: {
name: string,
position: LngLat
}): void;
getOffset(): Pixel;
setOffset(offset: Pixel): void;
setAnimation(animate: string): void;
getAnimation(): string;
setClickable(clickable: boolean): void;
getClickable(): boolean;
getPosition(): LngLat;
setPosition(lnglat: LngLat): void;
setAngle(angle: number): void;
getAngle(): number;
setLabel(label: {
content?: string | undefined,
offset?: Pixel | undefined
}): void;
getLabel(): {
content?: string | undefined,
offset?: Pixel | undefined
};
setzIndex(index: number): void;
getIcon(): string|Icon;
setIcon(content: string|Icon): void;
setDraggable(draggable: boolean): void;
getDraggable(): boolean;
hide(): void;
show(): void;
setCursor(cursor: string): void;
setContent(content: string| HTMLElement): void;
getContent(): string;
moveAlong(lnglatlist: LngLat[], speed?: number, f?: (k: number) => number, circlable?: boolean): void;
moveTo(lnglat: LngLat, speed?: number, f?: (k: number) => number): void;
stopMove(): void;
setMap(map: Map): void;
getMap(): Map;
setTitle(title: string): void;
getTitle(): string;
setTop(isTop: boolean): void;
getTop(): boolean;
setShadow(icon: Icon): void;
getShadow(): Icon;
setShape(shape: MarkerShape): void;
getShape(): MarkerShape;
setExtData(ext: any): void;
getExtData(): any;
}
interface MarkerClustererOptions {
gridSize?: number | undefined;
minClusterSize?: number | undefined;
maxZoom?: number | undefined;
averageCenter?: boolean | undefined;
styles?: any[] | undefined;
renderCluserMarker?: ((obj: any) => void) | undefined;
zoomOnClick?: boolean | undefined;
}
/**
* 用于地图上加载大量点标记,提高地图的绘制和显示性能。
*/
class MarkerClusterer extends EventBindable {
constructor(map: Map, markers: Marker[], opt?: MarkerClustererOptions);
/**
* 添加一个需进行聚合的点标记
* @param marker
*/
addMarker(marker: Marker): void;
/**
* 删除一个聚合的点标记
* @param marker 点标记
*/
removeMarker(marker: Marker): void;
/**
* 获取聚合点的总数量
*/
getClustersCount(): number;
/**
* 获取聚合网格的像素大小
*/
getGridSize(): number;
/**
* 获取地图中点标记的最大聚合级别
*/
getMaxZoom(): number;
/**
* 获取单个聚合的最小数量
*/
getMinClusterSize(): number;
/**
* 获取聚合的样式风格集合
*/
getStyles(): any[];
/**
* 设置聚合网格的像素大小
* @param size
*/
setGridSize(size: number): void;
/**
* 设置地图中点标记的最大聚合级别
* @param zoom
*/
setMaxZoom(zoom: number): void;
/**
* 设置单个聚合的最小数量
* @param size
*/
setMinClusterSize(size: number): void;
/**
* 设置聚合的样式风格
* @param styles
*/
setStyles(styles: any[]): void;
/**
* 从地图上彻底清除所有聚合点标记
*/
clearMarkers(): void;
/**
* 设置将进行点聚合的地图对象
* @param map
*/
setMap(map: Map): void;
/**
* 设置将进行点聚合显示的点标记集合
* @param markers
*/
setMarkers(markers: Marker[]): void;
/**
* 获取该点聚合的地图对象
*/
getMap(): Map;
/**
* 获取该点聚合中的点标记集合
*/
getMarkers(): Marker[];
/**
* 添加一组需进行聚合的点标记
*/
addMarkers(markers: Marker[]): void;
/**
* 删除一组聚合的点标记
* @param markers
*/
removeMarkers(markers: Marker[]): void;
/**
* 获取单个聚合点位置是否是聚合内所有标记的平均中心
*/
isAverageCenter(): boolean;
/**
* 设置单个聚合点位置是否是聚合内所有标记的平均中心
* @param averageCenter
*/
setAverageCenter(averageCenter: boolean): void;
}
interface CircleOptions {
map: Map;
zIndex?: number | undefined;
center: LngLat;
radius?: number | undefined;
strokeColor?: string | undefined;
strokeOpacity?: number | undefined;
fillColor?: string | undefined;
fillOpacity?: string | undefined;
strokeStyle?: string | undefined;
extData?: any;
strokeDasharray?: number[] | undefined;
}
class Circle {
constructor(options?: CircleOptions);
setCenter(lnglat: LngLat): void;
getCenter(): LngLat;
getBounds(): Bounds;
setRadius(radius: number): void;
getRadius(): number;
setOptions(circleopt: CircleOptions): void;
getOptions(): CircleOptions;
hide(): void;
show(): void;
setMap(map: Map): void;
setExtData(ext: any): void;
getExtData(): any;
contains(point: LngLat): boolean;
}
interface PolygonOptions {
map?: Map | undefined;
zIndex?: number | undefined;
path?: LngLat[]|LngLat[][] | undefined;
strokeColor?: string | undefined;
strokeOpacity?: number | undefined;
strokeWeight?: number | undefined;
fillColor?: string | undefined;
fillOpacity?: number | undefined;
extData?: any;
strokeStyle?: string | undefined;
strokeDasharray?: number[] | undefined;
}
class Polygon extends EventBindable {
constructor(options?: PolygonOptions);
setPath(path: LngLat[]|LngLat[][]): void;
getPath(): LngLat[]|LngLat[][];
setOptions(opt: PolygonOptions): void;
getOptions(): PolygonOptions;
getBounds(): Bounds;
getArea(): number;
hide(): void;
show(): void;
setMap(map: Map): void;
setExtData(ext: any): void;
getExtData(): any;
contains(point: LngLat): boolean;
}
interface PolylineOptions {
map?: Map | undefined;
zIndex?: number | undefined;
geodesic?: boolean | undefined;
isOutline?: boolean | undefined;
outlineColor?: string | undefined;
path?: LngLat[] | undefined;
strokeColor?: string | undefined;
strokeOpacity?: number | undefined;
strokeWeight?: number | undefined;
strokeStyle?: string | undefined;
strokeDasharray?: number[] | undefined;
extData?: any;
}
class Polyline extends EventBindable {
constructor(options?: PolylineOptions);
setPath(path: LngLat[]): void;
getPath(): LngLat[];
setOptions(opt: PolylineOptions): void;
getOptions(): PolylineOptions;
getLength(): number;
getBounds(): Bounds;
hide(): void;
show(): void;
setMap(map: Map): void;
setExtData(ext: any): void;
getExtData(): any;
}
interface MapControl {
show(): void;
hide(): void;
}
class MapType implements MapControl {
constructor(options?: {
defaultType?: number | undefined;
showTraffic?: boolean | undefined;
showRoad?: boolean | undefined;
});
show(): void;
hide(): void;
}
class OverView extends EventBindable implements MapControl {
constructor(options?: {
tileLayer?: TileLayer[] | undefined,
isOpen?: boolean | undefined,
visible?: boolean | undefined
});
open(): void;
close(): void;
setTileLayer(layer: TileLayer): void;
getTileLayer(): TileLayer;
show(): void;
hide(): void;
}
class Scale extends EventBindable implements MapControl {
offset: Pixel;
position: string;
show(): void;
hide(): void;
}
class ToolBar extends EventBindable implements MapControl {
constructor(options?: {
offset?: Pixel | undefined,
position?: string | undefined,
ruler?: boolean | undefined,
noIpLocate?: boolean | undefined,
locate?: boolean | undefined,
liteStyle?: boolean | undefined,
direction?: boolean | undefined,
autoPosition?: boolean | undefined,
locationMarker?: Marker | undefined,
useNative?: boolean | undefined
});
getOffset(): Pixel;
setOffset(offset: Pixel): void;
hideRuler(): void;
showRuler(): void;
hideDirection(): void;
showDirection(): void;
hideLocation(): void;
showLocation(): void;
doLocation(): void;
getLocation(): { lng: number, lat: number };
show(): void;
hide(): void;
}
class InfoWindow extends EventBindable {
constructor(options?: {
isCustom?: boolean | undefined,
autoMove?: boolean | undefined,
closeWhenClickMap?: boolean | undefined,
content?: string | HTMLElement | undefined,
size?: Size | undefined,
offset?: Pixel | undefined,
position?: LngLat | undefined,
showShadow?: boolean | undefined
});
open(map: Map, pos: LngLat): void;
close(): void;
getIsOpen(): boolean;
setPosition(lnglat: LngLat): void;
getPosition(): LngLat;
setSize(size: Size): void;
getSize(): Size;
getContent(): string;
setContent(content: string|HTMLElement): void;
}
class AdvancedInfoWindow extends EventBindable {
constructor(options?: {
autoMove?: boolean | undefined,
closeWhenClickMap?: boolean | undefined,
content?: string|HTMLElement | undefined,
offset?: Pixel | undefined,
position?: LngLat | undefined,
panel?: string|HTMLElement | undefined,
searchRadius?: number | undefined,
placeSearch?: boolean | undefined,
driving?: boolean | undefined,
walking?: boolean | undefined,
transit?: boolean | undefined,
asOrigin?: boolean | undefined,
asDestination?: boolean | undefined
});
open(map: Map, pos: LngLat): void;
close(): void;
getIsOpen(): boolean;
setPosition(lnglat: LngLat): void;
getPosition(): LngLat;
setContent(content: string|HTMLElement): void;
getContent(): string;
}
class Geolocation extends EventBindable {
constructor(options: {
enableHighAccuracy?: boolean | undefined,
timeout?: number | undefined,
noIpLocate?: boolean | undefined,
maximumAge?: number | undefined,
convert?: boolean | undefined,
showButton?: boolean | undefined,
buttonDom?: string|HTMLElement | undefined,
buttonPosition?: string | undefined,
buttonOffset?: Pixel | undefined,
showMarker?: boolean | undefined,
markerOptions?: MarkerOptions | undefined,
showCircle?: boolean | undefined,
circleOptions?: CircleOptions | undefined,
panToLocation?: boolean | undefined,
zoomToAccuracy?: boolean | undefined,
useNative?: boolean | undefined
});
isSupported(): boolean;
getCurrentPosition(): void;
watchPosition(): number;
clearWatch(watchId: number): number;
}
interface GeolocationResult {
position: LngLat;
accuracy: number;
isConverted: boolean;
info: string;
}
interface GeolocationError {
info: string;
}
interface BusinessArea {
id: string;
name: string;
location: string;
}
interface Road {
id: string;
name: string;
distance: number;
location: LngLat;
direction: string;
}
interface Cross {
distance: number;
direction: string;
location: LngLat;
first_id: string;
first_name: string;
second_id: string;
second_name: string;
}
interface AddressComponent {
province: string;
city: string;
citycode: string;
district: string;
adcode: string;
township: string;
street: string;
streetNumber: string;
neighborhood: string;
neighborhoodType: string;
building: string;
buildingType: string;
businessAreas: BusinessArea[];
}
interface Geocode {
addressComponent: AddressComponent;
formattedAddress: string;
location: LngLat;
adcode: string;
level: string;
}
interface ReGeocode {
addressComponent: AddressComponent;
formattedAddress: string;
roads: Road[];
crosses: Cross[];
pois: ReGeocodePoi[];
}
interface ReGeocodePoi {
id: string;
name: string;
type: string;
tel: string;
distance: number;
direction: string;
address: string;
location: LngLat;
businessArea: string;
}
interface GeocodeResult {
info: string;
geocodes: LngLat[];
resultNum: number;
}
interface ReGeocodeResult {
info: string;
regeocode: ReGeocode;
}
class Geocoder {
constructor(opts?: {
city?: string | undefined,
radius?: number | undefined,
batch?: boolean | undefined,
extensions?: string | undefined
});
getLocation(address: string, callback?: (status?: string, result?: string | GeocodeResult) => void): void;
setCity(city: string): void;
getAddress(location: LngLat|LngLat[], callback: (status?: string, result?: string | ReGeocodeResult) => void): void;
}
/**
* 坐标转换结果
*/
interface ConvertorResult {
info: string;
locations: LngLat[];
}
/**
* 坐标转换
*/
function convertFrom(lnglat: LngLat | LngLat[] | [number, number], type: string, result: (status: string, result: ConvertorResult) => void): void;
interface Poi {
id: string;
name: string;
type: string;
location: LngLat;
address: string;
distance: number;
tel: string;
website: string;
pcode: string;
citycode: string;
adcode: string;
postcode: string;
pname: string;
cityname: string;
adname: string;
email: string;
entr_location: LngLat;
exit_location: LngLat;
groupbuy: boolean;
discount: boolean;
}
interface CitySearchResult {
city: string;
bounds: Bounds;
}
class CitySearch extends EventBindable {
getLocalCity(callback: (status: string, result: string | CitySearchResult) => void): void;
getCityByIp(ip: string, callback: (status: string, result: string | CitySearchResult) => void): void;
}
enum DrivingPolicy {
LEAST_TIME,
LEAST_FEE,
LEAST_DISTANCE,
REAL_TRAFFIC
}
interface ViaCity {
name: string;
citycode: string;
adcode: string;
districts: District[];
}
interface District {
name: string;
adcode: string;
}
interface TMC {
lcode: string;
distance: number;
status: string;
}
interface DriveStep {
start_location: LngLat;
end_location: LngLat;
instruction: string;
action: string;
assist_action: string;
orientation: string;
road: string;
distance: number;
tolls: number;
tolls_distance: number;
toll_road: string;
time: number;
path: LngLat[];
cities?: ViaCity[] | undefined;
tmcs?: TMC[] | undefined;
}
interface DriveRoute {
distance: number;
time: number;
policy: string;
tolls: number;
tolls_distance: number;
steps: DriveStep[];
}
interface DrivingResult {
info: string;
origin: LngLat;
destination: LngLat|Poi;
start: Poi;
waypoints: Poi;
taxi_cost: number;
routes: DriveRoute[];
}
class Driving extends EventBindable {
constructor(options?: {
policy?: DrivingPolicy | undefined,
extensions?: string | undefined,
map?: Map | undefined,
panel?: string|HTMLElement | undefined,
hideMarkers?: boolean | undefined,
showTraffic?: boolean | undefined
});
search(origin: LngLat, destination: LngLat, opts?: {
waypoints: LngLat[]
}, callback?: (status: string, result: string|DrivingResult) => void): void;
search(point: Array<{
keyword: string,
city: string
}>, callback: (status: string, result: string|DrivingResult) => void): void;
setPolicy(policy: DrivingPolicy): void;
setAvoidPolygons(path: LngLat[][]): void;
setAvoidRoad(road: string): void;
clearAvoidRoad(): void;
clearAvoidPolygons(): void;
getAvlidPolygons(): LngLat[][];
getAvoidRoad(): string;
clear(): void;
searchOnAMAP(obj: {
origin?: LngLat | undefined,
originName?: string | undefined,
destination?: LngLat | undefined,
destinationName?: string | undefined
}): void;
}
// 天气插件
interface WeatherLiveResult {
info: string;
province: string;
city: string;
adcode: string;
weather: string;
temperature: number;
windDirection: string;
windPower: number;
humidity: string;
reportTime: string;
}
interface Forecast {
date: string;
week: string;
dayWeather: string;
nightWeather: string;
dayTemp: number;
nightTemp: number;
dayWindDir: string;
nightWindDir: string;
dayWindPower: string;
nightWindPower: string;
}
interface WeatherForecastResult {
info: string;
province: string;
city: string;
adcode: string;
reportTime: string;
forecasts: Forecast[];
}
class Weather {
/**
* 查询实时天气信息
* @param district 支持城市名称/区域编码(如:“杭州市”/“330100”)
* @param callback 当请求成功时ErrorStatus为null,当请求不成功时ErrorStatus为Obj
*/
getLive(district: string, callback: (errorStatus: any, result: WeatherLiveResult) => void): void;
/**
* 查询四天预报天气,包括查询当天天气信息
* @param district 支持城市名称/区域编码(如:“杭州市”/“330100”)
* @param callback 当请求成功时ErrorStatus为null,当请求不成功时ErrorStatus为Obj
*/
getForecast(district: string, callback: (errorStatus: any, result: WeatherForecastResult) => void): void;
}
interface Tip {
name: string;
district: string;
adcode: string;
}
interface AutocompleteResult {
info: string;
count: number;
tips: Tip[];
}
class Autocomplete {
constructor(opts: {
type?: string | undefined,
city?: string | undefined,
datatype?: string | undefined,
citylimit?: boolean | undefined,
input?: string | undefined
});
search(keyword: string, callback: (status: string, result: string | AutocompleteResult) => void): void;
}
interface SelectChangeEvent {
type: string;
id: string;
marker: Marker;
listElement: HTMLLIElement;
data: Poi;
}
interface PoiList {
pois: Poi[];
pageIndex: number;
pageSize: number;
count: number;
}
interface CityInfo {
name: string;
citycode: string;
adcode: string;
count: number;
}
interface SearchResult {
info: string;
poiList: PoiList;
keywordList: string[];
cityList: CityInfo[];
}
interface Photo {
title: string;
url: string;
}
interface Content {
id: string;
name: string;
}
interface Discount {
title: string;
detail: string;
start_time: string;
end_time: string;
sold_num: string;
photos: Photo[];
url: string;
provider: string;
}
interface Groupbuy {
title: string;
type_code: string;
type: string;
detail: string;
stime: string;
etime: string;
count: number;
sold_num: number;
original_price: number;
groupbuy_price: number;
discount: number;
ticket_address: string;
ticket_tel: string;
photos: Photo[];
url: string;
provider: string;
}
class PlaceSearch {
constructor(opts: {
city?: string | undefined,
citylimit?: boolean | undefined,
children?: number | undefined,
type?: string | undefined,
lang?: string | undefined,
pageSize?: number | undefined,
pageIndex?: number | undefined,
extensions?: string | undefined,
map?: Map | undefined,
panel?: string|HTMLElement | undefined,
showCover?: boolean | undefined,
renderStyle?: string | undefined,
autoFitView?: boolean | undefined
});
search(keyword: string, callback: (status: string, result: string | SearchResult) => void): void;
searchNearBy(keyword: string, center: LngLat, radius: number, callback: (status: string, result: string|SearchResult) => void): void;
searchInBounds(keyword: string, bounds: Bounds|Polygon, callback: (status: string, result: string|SearchResult) => void): void;
getDetails(POIID: string, callback: (status: string, result: string|SearchResult) => void): void;
setType(type: string): void;
setCityLimit(p: boolean): void;
setPageIndex(pageIndex: number): void;
setPageSize(setPageSize: number): void;
setCity(city: string): void;
setLang(lang: string): string;
getLang(): string;
clear(): void;
poiOnAMAP(obj: any): void;
detailOnAMAP(obj: any): void;
}
interface DistrictSearchOptions {
level: string;
showbiz?: boolean | undefined;
extensions?: string | undefined;
subdistrict?: number | undefined;
}
interface DistrictSearchResult {
info: string;
districtList: District[];
}
interface District {
name: string;
center: LngLat;
citycode: string;
adcode: string;
level: string;
boundaries: LngLat[];
districtList: District[];
}
class DistrictSearch {
constructor(opts: DistrictSearchOptions);
search(keywords: string, callback?: (status: string, result: string| DistrictSearchResult) => void, opts?: DistrictSearchOptions): void;
setLevel(level: string): void;
setSubdistrict(district: number): void;
}
} | the_stack |
import * as Babel from "babel-standalone";
import { registerDialog } from "dialog-polyfill";
import { debounce, throttle } from "lodash";
import { monaco } from "./monaco";
import * as ts from "typescript";
import { StrictLevel, ViewType } from "./model";
import { decodeUrlData } from "./urls";
import protect from "loop-protect";
document.body.style.display = "block";
const DEFAULT_COMPILER_OPTIONS: monaco.languages.typescript.CompilerOptions = Object.freeze(
{
skipLibCheck: true,
inlineSourceMap: true,
allowJs: true,
// Without this, Chrome tries to issue an HTTP request for file.ts that fails.
inlineSources: true,
// ng2
experimentalDecorators: true,
emitDecoratorMetadata: true,
target: monaco.languages.typescript.ScriptTarget.ESNext ,
},
);
const STRICT_COMPILER_OPTIONS: monaco.languages.typescript.CompilerOptions = Object.freeze(
{
...DEFAULT_COMPILER_OPTIONS,
noImplicitAny: true,
noImplicitReturns: true,
noFallthroughCasesInSwitch: true,
strictNullChecks: true,
noUnusedLocals: true,
noUnusedParameters: true,
noImplicitThis: true,
alwaysStrict: true,
},
);
type WindowExports = Readonly<Window> & { [key: string]: {} };
const global = window as unknown as WindowExports;
Babel.registerPlugin(
"loopProtection",
protect(100, (line: unknown) => {
console.error(`Breaking out of potential infinite loop at line: ${line}`);
}),
);
export function compilerOptionsForViewType(type: ViewType, level: StrictLevel) {
let compilerOptions;
switch (level) {
case StrictLevel.STRICT:
compilerOptions = STRICT_COMPILER_OPTIONS;
break;
case StrictLevel.LOOSE:
case StrictLevel.NONE:
compilerOptions = DEFAULT_COMPILER_OPTIONS;
break;
default:
throw new Error(`Unexpected strictLevel: ${level}`);
}
switch (type) {
case ViewType.ES5:
return {
...compilerOptions,
inlineSourceMap: false,
target: monaco.languages.typescript.ScriptTarget.ES5,
};
case ViewType.ESNEXT:
return {
...compilerOptions,
inlineSourceMap: false,
target: monaco.languages.typescript.ScriptTarget.ESNext,
};
case ViewType.EDITOR_ONLY:
case ViewType.OUTPUT:
case ViewType.OUTPUT_ONLY:
return compilerOptions;
default:
throw new Error(`Unexpected viewType: ${type}`);
}
}
export function run(
deps = {
localStorage,
ga,
registerDialog,
document,
global,
monaco,
body: document.body,
editor: monaco.editor.create(document.getElementById("monaco-container")!, {
lineNumbersMinChars: 4,
}),
getById(id: string) {
return document.getElementById(id);
},
worker: new Worker("./url_worker.ts"),
},
) {
deps.registerDialog(deps.getById("settings"));
deps.registerDialog(deps.getById("share"));
deps.worker.addEventListener("message", ({ data }) => {
history.replaceState(undefined, "", data);
});
function update(immediate = true) {
deps.body.dataset["viewType"] = viewType.toString();
deps.editor.getDomNode()!.style.display = "none";
deps.editor.layout();
deps.editor.getDomNode()!.style.display = "block";
deps.monaco.languages.typescript.typescriptDefaults.setCompilerOptions(
compilerOptionsForViewType(viewType, strictLevel),
);
const oldModel = models.script.model;
switch (strictLevel) {
case StrictLevel.STRICT:
case StrictLevel.LOOSE:
models.script.model = tsModel;
deps.getById("ts-tab")!.textContent = "ts";
break;
case StrictLevel.NONE:
models.script.model = jsModel;
deps.getById("ts-tab")!.textContent = "js";
break;
}
if (oldModel != models.script.model) {
models.script.model.setValue(oldModel.getValue());
oldModel.setValue("");
}
if (currentTab == "script") {
deps.editor.setModel(models.script.model);
}
updateUrl();
if (immediate) {
updateOutputNow();
} else {
updateOutput();
}
}
function onViewChange(newType = viewType) {
viewType = Number(newType);
if (viewType == ViewType.ESNEXT || viewType == ViewType.ES5) {
switchTab("script", deps.getById("ts-tab")!);
}
deps.ga("send", "event", "settings", "changeViewType", ViewType[viewType]);
update();
}
deps.global["onViewChange"] = onViewChange;
function onStrictChange(level = strictLevel) {
strictLevel = Number(level);
deps.ga(
"send",
"event",
"settings",
"changeStrictLevel",
StrictLevel[strictLevel],
);
update();
}
deps.global["onStrictChange"] = onStrictChange;
function showSettings() {
(deps.getById("settings") as any).showModal();
}
deps.global["showSettings"] = showSettings;
function share() {
(deps.getById("share") as any).showModal();
}
deps.global["share"] = share;
let currentTab: "css" | "html" | "script" = "script";
function switchTab(tab: typeof currentTab, tabElement: HTMLElement) {
models[currentTab].state = deps.editor.saveViewState();
currentTab = tab;
for (const elem of Array.from(
deps.document.querySelectorAll("#tabbar > li"),
)) {
elem.classList.remove("current");
}
tabElement.classList.add("current");
const { model, state } = models[currentTab];
deps.editor.setModel(model);
deps.editor.restoreViewState(state!);
deps.editor.focus();
}
deps.global["switchTab"] = switchTab;
function onChangeColorScheme(scheme: string) {
monaco.editor.setTheme(scheme);
deps.document.body.dataset["scheme"] = scheme;
deps.localStorage.setItem("monaco-theme", scheme);
}
deps.global["onChangeColorScheme"] = onChangeColorScheme;
function saveLocalWichSettings(save: boolean) {
if (save) {
deps.ga("send", "event", "settings", "saveLocalWichSettings");
deps.localStorage.setItem(
"starter-template",
JSON.stringify({
viewType,
strictLevel,
scriptSource: models.script.model.getValue(),
cssSource: models.css.model.getValue(),
htmlSource: models.html.model.getValue(),
}),
);
} else {
deps.ga("send", "event", "settings", "clearLocalWichSettings");
deps.localStorage.removeItem("starter-template");
}
}
deps.global["saveLocalWichSettings"] = saveLocalWichSettings;
function newWich() {
deps.ga("send", "event", "action", "newWich", "fromSidebar");
window.open(location.toString().split("#")[0]);
}
deps.global["newWich"] = newWich;
function turnOnAutoRun() {
deps.localStorage.setItem("maybeCrashed", "false");
crashMessage.style.display = "none";
updateOutputNow();
}
deps.global["turnOnAutoRun"] = turnOnAutoRun;
function updateUrl() {
deps.worker.postMessage({
viewType,
strictLevel,
scriptSource: models.script.model.getValue(),
cssSource: models.css.model.getValue(),
htmlSource: models.html.model.getValue(),
});
}
let viewType: ViewType = ViewType.OUTPUT;
let strictLevel: StrictLevel = StrictLevel.STRICT;
function decodeUrl() {
const starterTemplate = deps.localStorage.getItem("starter-template");
const {
viewType: newViewType,
strictLevel: newStrictLevel,
scriptSource,
cssSource,
htmlSource,
} = decodeUrlData(
location.hash.substring(1),
starterTemplate ? JSON.parse(starterTemplate) : undefined,
);
viewType = newViewType;
strictLevel = newStrictLevel;
models.script.model.setValue(scriptSource);
models.css.model.setValue(cssSource);
models.html.model.setValue(htmlSource);
(deps.getById(
"view-type-select",
) as HTMLSelectElement).value = viewType.toString();
(deps.getById(
"strict-level-select",
) as HTMLSelectElement).value = strictLevel.toString();
let startState = "BLANK";
if (location.hash.length > 1) startState = "LOAD";
if (starterTemplate) startState = "TEMPLATE";
deps.ga("set", "page", "/");
deps.ga("send", "pageview", {
dimension1: startState,
metric1: scriptSource.length.toString(),
metric2: cssSource.length.toString(),
metric3: htmlSource.length.toString(),
metric4: location.hash.length.toString(),
});
deps.ga(
"send",
"timing",
"JS Dependencies",
"load",
Math.round(performance.now()),
);
update();
}
deps.monaco.editor.createModel(
"",
"typescript",
deps.monaco.Uri.file("main.ts"),
);
const jsModel = deps.monaco.editor.createModel(
"",
"javascript",
deps.monaco.Uri.file("main_raw.js"),
);
const tsModel = deps.monaco.editor.createModel(
"",
"typescript",
deps.monaco.Uri.file("main_raw.ts"),
);
const models = {
script: { model: tsModel, state: deps.editor.saveViewState() },
css: {
model: deps.monaco.editor.createModel(
"",
"css",
deps.monaco.Uri.file("style.css"),
),
state: deps.editor.saveViewState(),
},
html: {
model: deps.monaco.editor.createModel(
"",
"html",
deps.monaco.Uri.file("index.html"),
),
state: deps.editor.saveViewState(),
},
};
const outputFrame = deps.getById("output-iframe") as HTMLIFrameElement;
const outputText = deps.document.querySelector(
"#output > pre",
) as HTMLElement;
const crashMessage = deps.getById("crash-message")!;
async function updateOutputNow() {
if (viewType == ViewType.EDITOR_ONLY) return;
if (deps.localStorage.getItem("maybeCrashed") == "true") {
crashMessage.style.display = "block";
return;
}
let transpiledScript = "";
if (models.script.model.getValue() != "") {
const worker = await deps.monaco.languages.typescript.getTypeScriptWorker();
let client, o: ts.EmitOutput;
if (viewType == ViewType.OUTPUT || viewType == ViewType.OUTPUT_ONLY) {
client = await worker(models.script.model.uri);
o = await client.getEmitOutput(models.script.model.uri.toString());
transpiledScript = Babel.transform(o.outputFiles[0].text, {
plugins: ["loopProtection"],
}).code;
} else {
client = await worker(models.script.model.uri);
o = await client.getEmitOutput(models.script.model.uri.toString());
transpiledScript = o.outputFiles[0].text;
}
}
switch (viewType) {
case ViewType.OUTPUT:
case ViewType.OUTPUT_ONLY:
const scriptUrl = URL.createObjectURL(new Blob([transpiledScript]));
(outputFrame as any).srcdoc = `
<!doctype html>
<title>Output</title>
<style>
${models.css.model.getValue()}
</style>
<body>
${models.html.model.getValue()}
<script src="${scriptUrl}"></script>
</body>`;
if (models.script.model.getValue()) {
deps.localStorage.setItem("maybeCrashed", "true");
outputFrame.addEventListener("load", () => {
// Experimentally confirmed that 'load' is fired *after* script
// execution. Doesn't handle an infinite loop in a timeout or event,
// of course.
deps.localStorage.setItem("maybeCrashed", "false");
});
}
break;
case ViewType.ES5:
case ViewType.ESNEXT:
outputText.innerText = transpiledScript;
break;
}
}
let updateOutput = debounce(updateOutputNow, 1000, { maxWait: 3000 });
decodeUrl();
const resizeHandler = throttle(() => {
deps.editor.getDomNode()!.style.display = "none";
deps.editor.layout();
deps.editor.getDomNode()!.style.display = "block";
}, 1000);
window.addEventListener("resize", resizeHandler);
switchTab("script", deps.getById("ts-tab")!);
const theme = deps.localStorage.getItem("monaco-theme");
if (theme) {
onChangeColorScheme(theme);
(deps.getById("theme-select") as HTMLSelectElement).value = theme;
}
deps.editor.onDidChangeModelContent(updateUrl);
let updateEvent = deps.editor.onDidChangeModelContent(updateOutput);
let anyScript = true;
deps.editor.onDidChangeModelContent(() => {
if (anyScript != (models.script.model.getValue() != "")) {
anyScript = models.script.model.getValue() != "";
if (anyScript) {
updateOutput = debounce(updateOutputNow, 1000, { maxWait: 3000 });
} else {
updateOutput = debounce(updateOutputNow, 100, { maxWait: 100 });
}
updateEvent.dispose();
updateEvent = deps.editor.onDidChangeModelContent(updateOutput);
}
});
let overlayTimeout: number;
deps.body.addEventListener("keydown", e => {
if (e.key == "s" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
clearTimeout(overlayTimeout);
deps.getById("save-overlay")!.style.display = "block";
overlayTimeout = setTimeout(() => {
deps.getById("save-overlay")!.style.display = "none";
}, 3000) as any;
}
});
}
global["run"] = run; | the_stack |
import { AnyOS, LinuxOS } from './getos';
import { resolveConfig, ResolveConfigVariables } from './resolveConfig';
import debug from 'debug';
import * as semver from 'semver';
import { isNullOrUndefined } from './utils';
import { BaseDryMongoBinaryOptions, DryMongoBinary } from './DryMongoBinary';
import { URL } from 'url';
import { UnknownArchitectureError, UnknownPlatformError } from './errors';
const log = debug('MongoMS:MongoBinaryDownloadUrl');
export interface MongoBinaryDownloadUrlOpts {
version: NonNullable<BaseDryMongoBinaryOptions['version']>;
platform: string;
arch: NonNullable<BaseDryMongoBinaryOptions['arch']>;
os?: BaseDryMongoBinaryOptions['os'];
}
/**
* Download URL generator
*/
export class MongoBinaryDownloadUrl implements MongoBinaryDownloadUrlOpts {
platform: string;
arch: string;
version: string;
os?: AnyOS;
constructor(opts: MongoBinaryDownloadUrlOpts) {
this.version = opts.version;
this.platform = this.translatePlatform(opts.platform);
this.arch = MongoBinaryDownloadUrl.translateArch(opts.arch, this.platform);
this.os = opts.os;
}
/**
* Assemble the URL to download
* Calls all the necessary functions to determine the URL
*/
async getDownloadUrl(): Promise<string> {
const downloadUrl = resolveConfig(ResolveConfigVariables.DOWNLOAD_URL);
if (downloadUrl) {
log(`Using "${downloadUrl}" as the Download-URL`);
const url = new URL(downloadUrl); // check if this is an valid url
return url.toString();
}
const archive = await this.getArchiveName();
log(`Using "${archive}" as the Archive String`);
const mirror =
resolveConfig(ResolveConfigVariables.DOWNLOAD_MIRROR) ?? 'https://fastdl.mongodb.org';
log(`Using "${mirror}" as the mirror`);
const url = new URL(mirror);
// ensure that the "mirror" path ends with "/"
if (!url.pathname.endsWith('/')) {
url.pathname = url.pathname + '/';
}
// no extra "/" between "pathname" and "platfrom", because of the "if" statement above to ensure "url.pathname" to end with "/"
url.pathname = `${url.pathname}${this.platform}/${archive}`;
return url.toString();
}
/**
* Get the archive
*/
async getArchiveName(): Promise<string> {
const archive_name = resolveConfig(ResolveConfigVariables.ARCHIVE_NAME);
// double-"!" to not include falsy values
if (!!archive_name) {
return archive_name;
}
switch (this.platform) {
case 'osx':
return this.getArchiveNameOsx();
case 'win32':
case 'windows':
return this.getArchiveNameWin();
case 'linux':
return this.getArchiveNameLinux();
default:
throw new UnknownPlatformError(this.platform);
}
}
/**
* Get the archive for Windows
* (from: https://www.mongodb.org/dl/win32)
*/
getArchiveNameWin(): string {
let name = `mongodb-${this.platform}-${this.arch}`;
if (!isNullOrUndefined(semver.coerce(this.version))) {
if (semver.satisfies(this.version, '4.2.x')) {
name += '-2012plus';
} else if (semver.lt(this.version, '4.1.0')) {
name += '-2008plus-ssl';
}
}
name += `-${this.version}.zip`;
return name;
}
/**
* Get the archive for OSX (Mac)
* (from: https://www.mongodb.org/dl/osx)
*/
getArchiveNameOsx(): string {
let name = `mongodb-osx`;
const version = semver.coerce(this.version);
if (!isNullOrUndefined(version) && semver.gte(version, '3.2.0')) {
name += '-ssl';
}
if (isNullOrUndefined(version) || semver.gte(version, '4.2.0')) {
name = `mongodb-macos`; // somehow these files are not listed in https://www.mongodb.org/dl/osx
}
if (this.arch === 'arm64') {
log('getArchiveNameOsx: Arch is "arm64", using x64 binary');
this.arch = 'x86_64';
}
name += `-${this.arch}-${this.version}.tgz`;
return name;
}
/**
* Get the archive for Linux
* (from: https://www.mongodb.org/dl/linux)
*/
async getArchiveNameLinux(): Promise<string> {
let osString: string | undefined;
// the highest version for "i686" seems to be 3.3
if (this.arch !== 'i686') {
if (!this.os) {
this.os = (await DryMongoBinary.generateOptions()).os;
}
osString = this.getLinuxOSVersionString(this.os as LinuxOS);
}
// this is below, to allow overwriting the arch (like arm64 to aarch64)
let name = `mongodb-linux-${this.arch}`;
if (!!osString) {
name += `-${osString}`;
}
name += `-${this.version}.tgz`;
return name;
}
/**
* Get the version string (with distro)
* @param os LinuxOS Object
*/
getLinuxOSVersionString(os: LinuxOS): string {
if (regexHelper(/ubuntu/i, os)) {
return this.getUbuntuVersionString(os);
} else if (regexHelper(/amzn/i, os)) {
return this.getAmazonVersionString(os);
} else if (regexHelper(/suse/i, os)) {
return this.getSuseVersionString(os);
} else if (regexHelper(/(rhel|centos|scientific)/i, os)) {
return this.getRhelVersionString(os);
} else if (regexHelper(/fedora/i, os)) {
return this.getFedoraVersionString(os);
} else if (regexHelper(/debian/i, os)) {
return this.getDebianVersionString(os);
} else if (regexHelper(/alpine/i, os)) {
console.warn('There is no offical build of MongoDB for Alpine!');
// Match "arch", "archlinux", "manjaro", "manjarolinux", "arco", "arcolinux"
} else if (regexHelper(/(arch|manjaro|arco)(?:linux)?$/i, os)) {
console.warn(
`There is no official build of MongoDB for ArchLinux (${os.dist}). Falling back to Ubuntu 20.04 release.`
);
return this.getUbuntuVersionString({
os: 'linux',
dist: 'Ubuntu Linux',
release: '20.04',
});
} else if (regexHelper(/unknown/i, os)) {
// "unknown" is likely to happen if no release file / command could be found
console.warn(
'Couldnt parse dist information, please report this to https://github.com/nodkz/mongodb-memory-server/issues'
);
}
// warn for the fallback
console.warn(
`Unknown/unsupported linux "${os.dist}(${os.id_like?.join(
', '
)})". Falling back to legacy MongoDB build!`
);
return this.getLegacyVersionString();
}
/**
* Get the version string for Debian
* @param os LinuxOS Object
*/
getDebianVersionString(os: LinuxOS): string {
let name = 'debian';
const release: number = parseFloat(os.release);
if (release >= 10 || ['unstable', 'testing'].includes(os.release)) {
if (semver.lte(this.version, '4.2.0')) {
log(
`getDebianVersionString: requested version "${this.version}" not available for osrelease "${release}", using "92"`
);
name += '92';
} else {
name += '10';
}
} else if (release >= 9) {
name += '92';
} else if (release >= 8.1) {
name += '81';
} else if (release >= 7.1) {
name += '71';
}
return name;
}
/**
* Get the version string for Fedora
* @param os LinuxOS Object
*/
getFedoraVersionString(os: LinuxOS): string {
let name = 'rhel';
const fedoraVer: number = parseInt(os.release, 10);
// 34 onward dosnt have "compat-openssl10" anymore, and only build from 4.0.24 are available for "rhel80"
if (fedoraVer >= 34) {
name += '80';
}
if (fedoraVer < 34 && fedoraVer >= 19) {
name += '70';
}
if (fedoraVer < 19 && fedoraVer >= 12) {
name += '62';
}
if (fedoraVer < 12 && fedoraVer >= 6) {
name += '55';
}
return name;
}
/**
* Get the version string for Red Hat Enterprise Linux
* @param os LinuxOS Object
*/
// TODO: add tests for RHEL
getRhelVersionString(os: LinuxOS): string {
let name = 'rhel';
const { release } = os;
if (release) {
if (/^8/.test(release)) {
name += '80';
} else if (/^7/.test(release)) {
name += '70';
} else if (/^6/.test(release)) {
name += '62';
} else if (/^5/.test(release)) {
name += '55';
}
}
// fallback
if (name === 'rhel') {
log('getRhelVersionString: falling back to "70"');
// fallback to "70", because that is what currently is supporting 3.6 to 5.0 and should work with many
name += '70';
}
return name;
}
/**
* Get the version string for Amazon Distro
* @param os LinuxOS Object
*/
getAmazonVersionString(os: LinuxOS): string {
let name = 'amazon';
const release: number = parseInt(os.release, 10);
if (release >= 2 && release <= 3) {
name += '2';
}
// dont add anthing as fallback, because for "amazon 1", mongodb just uses "amazon"
return name;
}
/**
* Linux Fallback
* @param os LinuxOS Object
*/
getLegacyVersionString(): string {
return '';
}
/**
* Get the version string for Suse / OpenSuse
* @param os LinuxOS Object
*/
getSuseVersionString(os: LinuxOS): string {
const releaseMatch: RegExpMatchArray | null = os.release.match(/(^11|^12)/);
return releaseMatch ? `suse${releaseMatch[0]}` : '';
}
/**
* Get the version string for Ubuntu
* @param os LinuxOS Object
*/
getUbuntuVersionString(os: LinuxOS): string {
const ubuntuOS: LinuxOS = {
...os,
dist: 'ubuntu',
};
// "id_like" processing (version conversion) [this is an block to be collapsible]
{
if (/^linux\s?mint\s*$/i.test(os.dist)) {
const mintToUbuntuRelease: Record<number, string> = {
17: '14.04',
18: '16.04',
19: '18.04',
20: '20.04',
};
ubuntuOS.release =
mintToUbuntuRelease[parseInt(os.release.split('.')[0])] || mintToUbuntuRelease[20];
}
if (/^elementary\s?os\s*$/i.test(os.dist)) {
const elementaryToUbuntuRelease: Record<number, string> = {
3: '14.04',
4: '16.04',
5: '18.04',
6: '20.04',
};
// untangle elemenatary versioning from hell https://en.wikipedia.org/wiki/Elementary_OS#Development
const [elementaryMajor, elementaryMinor] = os.release.split('.').map((el) => parseInt(el));
const realMajor = elementaryMajor || elementaryMinor;
ubuntuOS.release = elementaryToUbuntuRelease[realMajor] || elementaryToUbuntuRelease[6];
}
}
const ubuntuYear: number = parseInt(ubuntuOS.release.split('.')[0], 10);
// this is, because currently mongodb only really provides arm64 binaries for "ubuntu1604"
if (this.arch === 'arm64') {
// this is because, before version 4.1.10, everything for "arm64" / "aarch64" were just "arm64" and for "ubuntu1604"
if (semver.satisfies(this.version, '<4.1.10')) {
this.arch = 'arm64';
return 'ubuntu1604';
}
if (semver.satisfies(this.version, '>=4.1.10')) {
// this is because mongodb changed since 4.1.0 to use "aarch64" instead of "arm64"
this.arch = 'aarch64';
// this is because since versions below "4.4.0" did not provide an binary for something like "20.04"
if (semver.satisfies(this.version, '<4.4.0')) {
return 'ubuntu1804';
}
return `ubuntu${ubuntuYear || 18}04`;
}
}
if (ubuntuOS.release === '14.10') {
return 'ubuntu1410-clang';
}
// there are no MongoDB 3.x binary distributions for ubuntu >= 18
// https://www.mongodb.org/dl/linux/x86_64-ubuntu1604
if (ubuntuYear >= 18 && semver.satisfies(this.version, '3.x.x')) {
log(
`getUbuntuVersionString: ubuntuYear is "${ubuntuYear}", which dosnt have an 3.x.x version, defaulting to "1604"`
);
return 'ubuntu1604';
}
// there are no MongoDB <=4.3.x binary distributions for ubuntu > 18
// https://www.mongodb.org/dl/linux/x86_64-ubuntu1804
if (ubuntuYear > 18 && semver.satisfies(this.version, '<=4.3.x')) {
log(
`getUbuntuVersionString: ubuntuYear is "${ubuntuYear}", which dosnt have an "<=4.3.x" version, defaulting to "1804"`
);
return 'ubuntu1804';
}
// the "04" version always exists for ubuntu, use that as default
return `ubuntu${ubuntuYear || 14}04`;
}
/**
* Translate input platform to mongodb useable platform
* @example
* darwin -> osx
* @param platform The Platform to translate
*/
translatePlatform(platform: string): string {
switch (platform) {
case 'darwin':
return 'osx';
case 'win32':
const version = semver.coerce(this.version);
if (isNullOrUndefined(version)) {
return 'windows';
}
return semver.gte(version, '4.3.0') ? 'windows' : 'win32';
case 'linux':
case 'elementary OS':
return 'linux';
case 'sunos':
return 'sunos5';
default:
throw new UnknownPlatformError(platform);
}
}
/**
* Translate input arch to mongodb useable arch
* @example
* x64 -> x86_64
* @param platform The Platform to translate
*/
static translateArch(arch: string, mongoPlatform: string): string {
switch (arch) {
case 'ia32':
if (mongoPlatform === 'linux') {
return 'i686';
} else if (mongoPlatform === 'win32') {
return 'i386';
}
throw new UnknownArchitectureError(arch, mongoPlatform);
case 'x64':
return 'x86_64';
case 'arm64':
return 'arm64';
default:
throw new UnknownArchitectureError(arch);
}
}
}
export default MongoBinaryDownloadUrl;
/**
* Helper function to reduce code / regex duplication
*/
function regexHelper(regex: RegExp, os: LinuxOS): boolean {
return (
regex.test(os.dist) ||
(!isNullOrUndefined(os.id_like) ? os.id_like.filter((v) => regex.test(v)).length >= 1 : false)
);
} | the_stack |
import { TypedDocumentNode } from "@graphql-typed-document-node/core";
import fastJson from "fast-json-stringify";
import genFn from "generate-function";
import {
ASTNode,
DocumentNode,
ExecutionResult,
FragmentDefinitionNode,
getOperationRootType,
GraphQLAbstractType,
GraphQLEnumType,
GraphQLError,
GraphQLFieldResolver,
GraphQLIsTypeOfFn,
GraphQLLeafType,
GraphQLList,
GraphQLObjectType,
GraphQLOutputType,
GraphQLResolveInfo,
GraphQLScalarSerializer,
GraphQLScalarType,
GraphQLSchema,
GraphQLType,
isAbstractType,
isLeafType,
isListType,
isNonNullType,
isObjectType,
isSpecifiedScalarType,
Kind,
locatedError,
TypeNameMetaFieldDef
} from "graphql";
import { ExecutionContext as GraphQLContext } from "graphql/execution/execute";
import { pathToArray } from "graphql/jsutils/Path";
import { FieldNode, OperationDefinitionNode } from "graphql/language/ast";
import { GraphQLTypeResolver } from "graphql/type/definition";
import {
addPath,
Arguments,
collectFields,
collectSubfields,
computeLocations,
FieldsAndNodes,
flattenPath,
getArgumentDefs,
JitFieldNode,
ObjectPath,
resolveFieldDef
} from "./ast";
import { GraphQLError as GraphqlJitError } from "./error";
import createInspect from "./inspect";
import { queryToJSONSchema } from "./json";
import { createNullTrimmer, NullTrimmer } from "./non-null";
import {
createResolveInfoThunk,
ResolveInfoEnricherInput
} from "./resolve-info";
import { Maybe } from "./types";
import {
CoercedVariableValues,
compileVariableParsing,
failToParseVariables
} from "./variables";
const inspect = createInspect();
export interface CompilerOptions {
customJSONSerializer: boolean;
// Disable builtin scalars and enum serialization
// which is responsible for coercion,
// only safe for use if the output is completely correct.
disableLeafSerialization: boolean;
// Disable capturing the stack trace of errors.
disablingCapturingStackErrors: boolean;
// Map of serializers to override
// the key should be the name passed to the Scalar or Enum type
customSerializers: { [key: string]: (v: any) => any };
resolverInfoEnricher?: (inp: ResolveInfoEnricherInput) => object;
}
interface ExecutionContext {
promiseCounter: number;
data: any;
errors: GraphQLError[];
nullErrors: GraphQLError[];
resolve?: () => void;
inspect: typeof inspect;
variables: { [key: string]: any };
context: any;
rootValue: any;
safeMap: typeof safeMap;
GraphQLError: typeof GraphqlJitError;
resolvers: { [key: string]: GraphQLFieldResolver<any, any, any> };
trimmer: NullTrimmer;
serializers: {
[key: string]: (
c: ExecutionContext,
v: any,
onError: (c: ExecutionContext, msg: string) => void
) => any;
};
typeResolvers: { [key: string]: GraphQLTypeResolver<any, any> };
isTypeOfs: { [key: string]: GraphQLIsTypeOfFn<any, any> };
resolveInfos: { [key: string]: any };
}
interface DeferredField {
name: string;
responsePath: ObjectPath;
originPaths: string[];
destinationPaths: string[];
parentType: GraphQLObjectType;
fieldName: string;
jsFieldName: string;
fieldType: GraphQLOutputType;
fieldNodes: FieldNode[];
args: Arguments;
}
/**
* The context used during compilation.
*
* It stores deferred nodes to be processed later as well as the function arguments to be bounded at top level
*/
export interface CompilationContext extends GraphQLContext {
resolvers: { [key: string]: GraphQLFieldResolver<any, any, any> };
serializers: {
[key: string]: (
c: ExecutionContext,
v: any,
onError: (c: ExecutionContext, msg: string) => void
) => any;
};
hoistedFunctions: string[];
hoistedFunctionNames: Map<string, number>;
typeResolvers: { [key: string]: GraphQLTypeResolver<any, any> };
isTypeOfs: { [key: string]: GraphQLIsTypeOfFn<any, any> };
resolveInfos: { [key: string]: any };
deferred: DeferredField[];
options: CompilerOptions;
depth: number;
}
// prefix for the variable used ot cache validation results
const SAFETY_CHECK_PREFIX = "__validNode";
const GLOBAL_DATA_NAME = "__context.data";
const GLOBAL_ERRORS_NAME = "__context.errors";
const GLOBAL_NULL_ERRORS_NAME = "__context.nullErrors";
const GLOBAL_ROOT_NAME = "__context.rootValue";
export const GLOBAL_VARIABLES_NAME = "__context.variables";
const GLOBAL_CONTEXT_NAME = "__context.context";
const GLOBAL_EXECUTION_CONTEXT = "__context";
const GLOBAL_PROMISE_COUNTER = "__context.promiseCounter";
const GLOBAL_INSPECT_NAME = "__context.inspect";
const GLOBAL_SAFE_MAP_NAME = "__context.safeMap";
const GRAPHQL_ERROR = "__context.GraphQLError";
const GLOBAL_RESOLVE = "__context.resolve";
const GLOBAL_PARENT_NAME = "__parent";
const LOCAL_JS_FIELD_NAME_PREFIX = "__field";
export interface CompiledQuery<
TResult = { [key: string]: any },
TVariables = { [key: string]: any }
> {
operationName?: string;
query: (
root: any,
context: any,
variables: Maybe<TVariables>
) => Promise<ExecutionResult<TResult>> | ExecutionResult<TResult>;
subscribe?: (
root: any,
context: any,
variables: Maybe<TVariables>
) => Promise<
AsyncIterableIterator<ExecutionResult<TResult>> | ExecutionResult<TResult>
>;
stringify: (v: any) => string;
}
interface InternalCompiledQuery extends CompiledQuery {
__DO_NOT_USE_THIS_OR_YOU_WILL_BE_FIRED_compilation?: string;
}
/**
* It compiles a GraphQL query to an executable function
* @param {GraphQLSchema} schema GraphQL schema
* @param {DocumentNode} document Query being submitted
* @param {string} operationName name of the operation
* @param partialOptions compilation options to tune the compiler features
* @returns {CompiledQuery} the cacheable result
*/
export function compileQuery<
TResult = { [key: string]: any },
TVariables = { [key: string]: any }
>(
schema: GraphQLSchema,
document: TypedDocumentNode<TResult, TVariables>,
operationName?: string,
partialOptions?: Partial<CompilerOptions>
): CompiledQuery<TResult, TVariables> | ExecutionResult<TResult> {
if (!schema) {
throw new Error(`Expected ${schema} to be a GraphQL schema.`);
}
if (!document) {
throw new Error("Must provide document.");
}
if (
partialOptions &&
partialOptions.resolverInfoEnricher &&
typeof partialOptions.resolverInfoEnricher !== "function"
) {
throw new Error("resolverInfoEnricher must be a function");
}
try {
const options = {
disablingCapturingStackErrors: false,
customJSONSerializer: false,
disableLeafSerialization: false,
customSerializers: {},
...partialOptions
};
// If a valid context cannot be created due to incorrect arguments,
// a "Response" with only errors is returned.
const context = buildCompilationContext(
schema,
document,
options,
operationName
);
let stringify: (v: any) => string;
if (options.customJSONSerializer) {
const jsonSchema = queryToJSONSchema(context);
stringify = fastJson(jsonSchema);
} else {
stringify = JSON.stringify;
}
const getVariables = compileVariableParsing(
schema,
context.operation.variableDefinitions || []
);
const type = getOperationRootType(context.schema, context.operation);
const fieldMap = collectFields(
context,
type,
context.operation.selectionSet,
Object.create(null),
Object.create(null)
);
const functionBody = compileOperation(context, type, fieldMap);
const compiledQuery: InternalCompiledQuery = {
query: createBoundQuery(
context,
document,
// eslint-disable-next-line no-new-func
new Function("return " + functionBody)(),
getVariables,
context.operation.name != null
? context.operation.name.value
: undefined
),
stringify
};
if (context.operation.operation === "subscription") {
compiledQuery.subscribe = createBoundSubscribe(
context,
document,
compileSubscriptionOperation(
context,
type,
fieldMap,
compiledQuery.query
),
getVariables,
context.operation.name != null
? context.operation.name.value
: undefined
);
}
if ((options as any).debug) {
// result of the compilation useful for debugging issues
// and visualization tools like try-jit.
compiledQuery.__DO_NOT_USE_THIS_OR_YOU_WILL_BE_FIRED_compilation =
functionBody;
}
return compiledQuery as CompiledQuery<TResult, TVariables>;
} catch (err: any) {
return {
errors: normalizeErrors(err)
};
}
}
export function isCompiledQuery<
C extends CompiledQuery,
E extends ExecutionResult
>(query: C | E): query is C {
return "query" in query && typeof query.query === "function";
}
// Exported only for an error test
export function createBoundQuery(
compilationContext: CompilationContext,
document: DocumentNode,
func: (context: ExecutionContext) => Promise<any> | undefined,
getVariableValues: (inputs: { [key: string]: any }) => CoercedVariableValues,
operationName?: string
) {
const { resolvers, typeResolvers, isTypeOfs, serializers, resolveInfos } =
compilationContext;
const trimmer = createNullTrimmer(compilationContext);
const fnName = operationName || "query";
/* eslint-disable */
/**
* In-order to assign a debuggable name to the bound query function,
* we create an intermediate object with a method named as the
* intended function name. This is because Function.prototype.name
* is not writeable.
*
* http://www.ecma-international.org/ecma-262/6.0/#sec-method-definitions-runtime-semantics-propertydefinitionevaluation
*
* section: 14.3.9.3 - calls SetFunctionName
*/
/* eslint-enable */
const ret = {
[fnName](
rootValue: any,
context: any,
variables: Maybe<{ [key: string]: any }>
): Promise<ExecutionResult> | ExecutionResult {
// this can be shared across in a batch request
const parsedVariables = getVariableValues(variables || {});
// Return early errors if variable coercing failed.
if (failToParseVariables(parsedVariables)) {
return { errors: parsedVariables.errors };
}
const executionContext: ExecutionContext = {
rootValue,
context,
variables: parsedVariables.coerced,
safeMap,
inspect,
GraphQLError: GraphqlJitError,
resolvers,
typeResolvers,
isTypeOfs,
serializers,
resolveInfos,
trimmer,
promiseCounter: 0,
data: {},
nullErrors: [],
errors: []
};
// eslint-disable-next-line no-useless-call
const result = func.call(null, executionContext);
if (isPromise(result)) {
return result.then(postProcessResult);
}
return postProcessResult(executionContext);
}
};
return ret[fnName];
}
function postProcessResult({
data,
nullErrors,
errors,
trimmer
}: ExecutionContext) {
if (nullErrors.length > 0) {
const trimmed = trimmer(data, nullErrors);
return {
data: trimmed.data,
errors: errors.concat(trimmed.errors)
};
} else if (errors.length > 0) {
return {
data,
errors
};
}
return { data };
}
/**
* Create the main function body.
*
* Implements the "Evaluating operations" section of the spec.
*
* It defers all top level field for consistency and protection for null root values,
* all the fields are deferred regardless of presence of resolver or not.
*
* @param {CompilationContext} context compilation context with the execution context
* @returns {string} a function body to be instantiated together with the header, footer
*/
function compileOperation(
context: CompilationContext,
type: GraphQLObjectType,
fieldMap: FieldsAndNodes
) {
const serialExecution = context.operation.operation === "mutation";
const topLevel = compileObjectType(
context,
type,
[],
[GLOBAL_ROOT_NAME],
[GLOBAL_DATA_NAME],
undefined,
GLOBAL_ERRORS_NAME,
fieldMap,
true
);
let body = `function query (${GLOBAL_EXECUTION_CONTEXT}) {
"use strict";
`;
if (serialExecution) {
body += `${GLOBAL_EXECUTION_CONTEXT}.queue = [];`;
}
body += generateUniqueDeclarations(context, true);
body += `${GLOBAL_DATA_NAME} = ${topLevel}\n`;
if (serialExecution) {
body += compileDeferredFieldsSerially(context);
body += `
${GLOBAL_EXECUTION_CONTEXT}.finalResolve = () => {};
${GLOBAL_RESOLVE} = (context) => {
if (context.jobCounter >= context.queue.length) {
// All mutations have finished
context.finalResolve(context);
return;
}
context.queue[context.jobCounter++](context);
};
// There might not be a job to run due to invalid queries
if (${GLOBAL_EXECUTION_CONTEXT}.queue.length > 0) {
${GLOBAL_EXECUTION_CONTEXT}.jobCounter = 1; // since the first one will be run manually
${GLOBAL_EXECUTION_CONTEXT}.queue[0](${GLOBAL_EXECUTION_CONTEXT});
}
// Promises have been scheduled so a new promise is returned
// that will be resolved once every promise is done
if (${GLOBAL_PROMISE_COUNTER} > 0) {
return new Promise(resolve => ${GLOBAL_EXECUTION_CONTEXT}.finalResolve = resolve);
}
`;
} else {
body += compileDeferredFields(context);
body += `
// Promises have been scheduled so a new promise is returned
// that will be resolved once every promise is done
if (${GLOBAL_PROMISE_COUNTER} > 0) {
return new Promise(resolve => ${GLOBAL_RESOLVE} = resolve);
}`;
}
body += `
// sync execution, the results are ready
return undefined;
}`;
body += context.hoistedFunctions.join("\n");
return body;
}
/**
* Processes the deferred node list in the compilation context.
*
* Each deferred node get a copy of the compilation context with
* a new empty list for deferred nodes to properly scope the nodes.
* @param {CompilationContext} context compilation context
* @returns {string} compiled transformations all of deferred nodes
*/
function compileDeferredFields(context: CompilationContext): string {
let body = "";
context.deferred.forEach((deferredField, index) => {
body += `
if (${SAFETY_CHECK_PREFIX}${index}) {
${compileDeferredField(context, deferredField)}
}`;
});
return body;
}
function compileDeferredField(
context: CompilationContext,
deferredField: DeferredField,
appendix?: string
): string {
const {
name,
originPaths,
destinationPaths,
fieldNodes,
fieldType,
fieldName,
jsFieldName,
responsePath,
parentType,
args
} = deferredField;
const subContext = createSubCompilationContext(context);
const nodeBody = compileType(
subContext,
parentType,
fieldType,
fieldNodes,
[jsFieldName],
[`${GLOBAL_PARENT_NAME}.${name}`],
responsePath
);
const parentIndexes = getParentArgIndexes(context);
const resolverName = getResolverName(parentType.name, fieldName);
const resolverHandler = getHoistedFunctionName(
context,
`${name}${resolverName}Handler`
);
const topLevelArgs = getArgumentsName(resolverName);
const validArgs = getValidArgumentsVarName(resolverName);
const executionError = createErrorObject(
context,
fieldNodes,
responsePath,
"err.message != null ? err.message : err",
"err"
);
const executionInfo = getExecutionInfo(
subContext,
parentType,
fieldType,
fieldName,
fieldNodes,
responsePath
);
const emptyError = createErrorObject(context, fieldNodes, responsePath, '""');
const resolverParentPath = originPaths.join(".");
const resolverCall = `${GLOBAL_EXECUTION_CONTEXT}.resolvers.${resolverName}(
${resolverParentPath},${topLevelArgs},${GLOBAL_CONTEXT_NAME}, ${executionInfo})`;
const resultParentPath = destinationPaths.join(".");
const compiledArgs = compileArguments(
subContext,
args,
topLevelArgs,
validArgs,
fieldType,
responsePath
);
const body = `
${compiledArgs}
if (${validArgs} === true) {
var __value = null;
try {
__value = ${resolverCall};
} catch (err) {
${getErrorDestination(fieldType)}.push(${executionError});
}
if (${isPromiseInliner("__value")}) {
${promiseStarted()}
__value.then(result => {
${resolverHandler}(${GLOBAL_EXECUTION_CONTEXT}, ${resultParentPath}, result, ${parentIndexes});
${promiseDone()}
}, err => {
if (err) {
${getErrorDestination(fieldType)}.push(${executionError});
} else {
${getErrorDestination(fieldType)}.push(${emptyError});
}
${promiseDone()}
});
} else {
${resolverHandler}(${GLOBAL_EXECUTION_CONTEXT}, ${resultParentPath}, __value, ${parentIndexes});
}
}`;
context.hoistedFunctions.push(`
function ${resolverHandler}(${GLOBAL_EXECUTION_CONTEXT}, ${GLOBAL_PARENT_NAME}, ${jsFieldName}, ${parentIndexes}) {
${generateUniqueDeclarations(subContext)}
${GLOBAL_PARENT_NAME}.${name} = ${nodeBody};
${compileDeferredFields(subContext)}
${appendix || ""}
}
`);
return body;
}
function compileDeferredFieldsSerially(context: CompilationContext): string {
let body = "";
context.deferred.forEach((deferredField, index) => {
const { name, fieldName, parentType } = deferredField;
const resolverName = getResolverName(parentType.name, fieldName);
const mutationHandler = getHoistedFunctionName(
context,
`${name}${resolverName}Mutation`
);
body += `
if (${SAFETY_CHECK_PREFIX}${index}) {
${GLOBAL_EXECUTION_CONTEXT}.queue.push(${mutationHandler});
}
`;
const appendix = `
if (${GLOBAL_PROMISE_COUNTER} === 0) {
${GLOBAL_RESOLVE}(${GLOBAL_EXECUTION_CONTEXT});
}
`;
context.hoistedFunctions.push(`
function ${mutationHandler}(${GLOBAL_EXECUTION_CONTEXT}) {
${compileDeferredField(context, deferredField, appendix)}
}
`);
});
return body;
}
/**
* Processes a generic node.
*
* The type is analysed and later reprocessed in dedicated functions.
* @param {CompilationContext} context compilation context to hold deferred nodes
* @param parentType
* @param {GraphQLType} type type of current parent node
* @param {FieldNode[]} fieldNodes array of the field nodes
* @param originPaths originPaths path in the parent object from where to fetch results
* @param destinationPaths path in the where to write the result
* @param previousPath response path until this node
* @returns {string} body of the resolvable fieldNodes
*/
function compileType(
context: CompilationContext,
parentType: GraphQLObjectType,
type: GraphQLType,
fieldNodes: FieldNode[],
originPaths: string[],
destinationPaths: string[],
previousPath: ObjectPath
): string {
const sourcePath = originPaths.join(".");
let body = `${sourcePath} == null ? `;
let errorDestination;
if (isNonNullType(type)) {
type = type.ofType;
const nullErrorStr = `"Cannot return null for non-nullable field ${
parentType.name
}.${getFieldNodesName(fieldNodes)}."`;
body += `(${GLOBAL_NULL_ERRORS_NAME}.push(${createErrorObject(
context,
fieldNodes,
previousPath,
nullErrorStr
)}), null) :`;
errorDestination = GLOBAL_NULL_ERRORS_NAME;
} else {
body += "null : ";
errorDestination = GLOBAL_ERRORS_NAME;
}
body += "(";
// value can be an error obj
const errorPath = `${sourcePath}.message != null ? ${sourcePath}.message : ${sourcePath}`;
body += `${sourcePath} instanceof Error ? (${errorDestination}.push(${createErrorObject(
context,
fieldNodes,
previousPath,
errorPath,
sourcePath
)}), null) : `;
if (isLeafType(type)) {
body += compileLeafType(
context,
type,
originPaths,
fieldNodes,
previousPath,
errorDestination
);
} else if (isObjectType(type)) {
const fieldMap = collectSubfields(context, type, fieldNodes);
body += compileObjectType(
context,
type,
fieldNodes,
originPaths,
destinationPaths,
previousPath,
errorDestination,
fieldMap,
false
);
} else if (isAbstractType(type)) {
body += compileAbstractType(
context,
parentType,
type,
fieldNodes,
originPaths,
previousPath,
errorDestination
);
} else if (isListType(type)) {
body += compileListType(
context,
parentType,
type,
fieldNodes,
originPaths,
previousPath,
errorDestination
);
} else {
/* istanbul ignore next */
throw new Error(`unsupported type: ${type.toString()}`);
}
body += ")";
return body;
}
function compileLeafType(
context: CompilationContext,
type: GraphQLLeafType,
originPaths: string[],
fieldNodes: FieldNode[],
previousPath: ObjectPath,
errorDestination: string
) {
let body = "";
if (
context.options.disableLeafSerialization &&
(type instanceof GraphQLEnumType || isSpecifiedScalarType(type))
) {
body += `${originPaths.join(".")}`;
} else {
const serializerName = getSerializerName(type.name);
context.serializers[serializerName] = getSerializer(
type,
context.options.customSerializers[type.name]
);
const parentIndexes = getParentArgIndexes(context);
const serializerErrorHandler = getHoistedFunctionName(
context,
`${type.name}${originPaths.join("")}SerializerErrorHandler`
);
context.hoistedFunctions.push(`
function ${serializerErrorHandler}(${GLOBAL_EXECUTION_CONTEXT}, message, ${parentIndexes}) {
${errorDestination}.push(${createErrorObject(
context,
fieldNodes,
previousPath,
"message"
)});}
`);
body += `${GLOBAL_EXECUTION_CONTEXT}.serializers.${serializerName}(${GLOBAL_EXECUTION_CONTEXT}, ${originPaths.join(
"."
)}, ${serializerErrorHandler}, ${parentIndexes})`;
}
return body;
}
/**
* Compile a node of object type.
* @param {CompilationContext} context
* @param {GraphQLObjectType} type type of the node
* @param fieldNodes fieldNodes array with the nodes references
* @param originPaths originPaths path in the parent object from where to fetch results
* @param destinationPaths path in the where to write the result
* @param responsePath response path until this node
* @param errorDestination Path for error array
* @param fieldMap map of fields to fieldNodes array with the nodes references
* @param alwaysDefer used to force the field to be resolved with a resolver ala graphql-js
* @returns {string}
*/
function compileObjectType(
context: CompilationContext,
type: GraphQLObjectType,
fieldNodes: JitFieldNode[],
originPaths: string[],
destinationPaths: string[],
responsePath: ObjectPath | undefined,
errorDestination: string,
fieldMap: FieldsAndNodes,
alwaysDefer: boolean
): string {
const body = genFn();
// Begin object compilation paren
body("(");
if (typeof type.isTypeOf === "function" && !alwaysDefer) {
context.isTypeOfs[type.name + "IsTypeOf"] = type.isTypeOf;
body(
`!${GLOBAL_EXECUTION_CONTEXT}.isTypeOfs["${
type.name
}IsTypeOf"](${originPaths.join(
"."
)}) ? (${errorDestination}.push(${createErrorObject(
context,
fieldNodes,
responsePath as any,
`\`Expected value of type "${
type.name
}" but got: $\{${GLOBAL_INSPECT_NAME}(${originPaths.join(".")})}.\``
)}), null) :`
);
}
// object start
body("{");
for (const name of Object.keys(fieldMap)) {
const fieldNodes = fieldMap[name];
const field = resolveFieldDef(context, type, fieldNodes);
if (!field) {
// Field is invalid, should have been caught in validation
// but the error is swallowed for compatibility reasons.
continue;
}
// Key of the object
// `name` is the field name or an alias supplied by the user
body(`"${name}": `);
/**
* Value of the object
*
* The combined condition for whether a field should be included
* in the object.
*
* Here, the logical operation is `||` because every fieldNode
* is at the same level in the tree, if at least "one of" the nodes
* is included, then the field is included.
*
* For example,
*
* ```graphql
* {
* foo @skip(if: $c1)
* ... { foo @skip(if: $c2) }
* }
* ```
*
* The logic for `foo` becomes -
*
* `compilationFor($c1) || compilationFor($c2)`
*/
body(`
(
${
fieldNodes
.map((it) => it.__internalShouldInclude)
.filter((it) => it)
.join(" || ") || /* if(true) - default */ "true"
}
)
`);
// Inline __typename
// No need to call a resolver for typename
if (field === TypeNameMetaFieldDef) {
// type.name if field is included else undefined - to remove from object
// during serialization
body(`? "${type.name}" : undefined,`);
continue;
}
let resolver = field.resolve;
if (!resolver && alwaysDefer) {
const fieldName = field.name;
resolver = (parent) => parent && parent[fieldName];
}
if (resolver) {
context.deferred.push({
name,
responsePath: addPath(responsePath, name),
originPaths,
destinationPaths,
parentType: type,
fieldName: field.name,
jsFieldName: getJsFieldName(field.name),
fieldType: field.type,
fieldNodes,
args: getArgumentDefs(field, fieldNodes[0])
});
context.resolvers[getResolverName(type.name, field.name)] = resolver;
body(
`
? (
${SAFETY_CHECK_PREFIX}${context.deferred.length - 1} = true,
null
)
: (
${SAFETY_CHECK_PREFIX}${context.deferred.length - 1} = false,
undefined
)
`
);
} else {
// if included
body("?");
body(
compileType(
context,
type,
field.type,
fieldNodes,
originPaths.concat(field.name),
destinationPaths.concat(name),
addPath(responsePath, name)
)
);
// if not included
body(": undefined");
}
// End object property
body(",");
}
// End object
body("}");
// End object compilation paren
body(")");
return body.toString();
}
function compileAbstractType(
context: CompilationContext,
parentType: GraphQLObjectType,
type: GraphQLAbstractType,
fieldNodes: FieldNode[],
originPaths: string[],
previousPath: ObjectPath,
errorDestination: string
): string {
let resolveType: GraphQLTypeResolver<any, any>;
if (type.resolveType) {
resolveType = type.resolveType;
} else {
resolveType = (value: any, context: any, info: GraphQLResolveInfo) =>
defaultResolveTypeFn(value, context, info, type);
}
const typeResolverName = getTypeResolverName(type.name);
context.typeResolvers[typeResolverName] = resolveType;
const collectedTypes = context.schema
.getPossibleTypes(type)
.map((objectType) => {
const subContext = createSubCompilationContext(context);
const object = compileType(
subContext,
parentType,
objectType,
fieldNodes,
originPaths,
["__concrete"],
addPath(previousPath, objectType.name, "meta")
);
return `case "${objectType.name}": {
${generateUniqueDeclarations(subContext)}
const __concrete = ${object};
${compileDeferredFields(subContext)}
return __concrete;
}`;
})
.join("\n");
const finalTypeName = "finalType";
const nullTypeError = `"Runtime Object type is not a possible type for \\"${type.name}\\"."`;
/* eslint-disable max-len */
const notPossibleTypeError =
// eslint-disable-next-line no-template-curly-in-string
'`Runtime Object type "${nodeType}" is not a possible type for "' +
type.name +
'".`';
const noTypeError = `${finalTypeName} ? ${notPossibleTypeError} : "Abstract type ${
type.name
} must resolve to an Object type at runtime for field ${
parentType.name
}.${getFieldNodesName(fieldNodes)}. Either the ${
type.name
} type should provide a \\"resolveType\\" function or each possible types should provide an \\"isTypeOf\\" function."`;
/* eslint-enable max-len */
return `((nodeType, err) =>
{
if (err != null) {
${errorDestination}.push(${createErrorObject(
context,
fieldNodes,
previousPath,
"err.message != null ? err.message : err",
"err"
)});
return null;
}
if (nodeType == null) {
${errorDestination}.push(${createErrorObject(
context,
fieldNodes,
previousPath,
nullTypeError
)})
return null;
}
const ${finalTypeName} = typeof nodeType === "string" ? nodeType : nodeType.name;
switch(${finalTypeName}) {
${collectedTypes}
default:
${errorDestination}.push(${createErrorObject(
context,
fieldNodes,
previousPath,
noTypeError
)})
return null;
}
})(
${GLOBAL_EXECUTION_CONTEXT}.typeResolvers.${typeResolverName}(${originPaths.join(
"."
)},
${GLOBAL_CONTEXT_NAME},
${getExecutionInfo(
context,
parentType,
type,
type.name,
fieldNodes,
previousPath
)}))`;
}
/**
* Compile a list transformation.
*
* @param {CompilationContext} context
* @param {GraphQLObjectType} parentType type of the parent of object which contained this type
* @param {GraphQLList<GraphQLType>} type list type being compiled
* @param {FieldNode[]} fieldNodes
* @param originalObjectPaths
* @param {ObjectPath} responsePath
* @param errorDestination
* @returns {string} compiled list transformation
*/
function compileListType(
context: CompilationContext,
parentType: GraphQLObjectType,
type: GraphQLList<GraphQLType>,
fieldNodes: FieldNode[],
originalObjectPaths: string[],
responsePath: ObjectPath,
errorDestination: string
) {
const name = originalObjectPaths.join(".");
const listContext = createSubCompilationContext(context);
// context depth will be mutated, so we cache the current value.
const newDepth = ++listContext.depth;
const fieldType = type.ofType;
const dataBody = compileType(
listContext,
parentType,
fieldType,
fieldNodes,
["__currentItem"],
[`${GLOBAL_PARENT_NAME}[idx${newDepth}]`],
addPath(responsePath, "idx" + newDepth, "variable")
);
const errorMessage = `"Expected Iterable, but did not find one for field ${
parentType.name
}.${getFieldNodesName(fieldNodes)}."`;
const errorCase = `(${errorDestination}.push(${createErrorObject(
context,
fieldNodes,
responsePath,
errorMessage
)}), null)`;
const executionError = createErrorObject(
context,
fieldNodes,
addPath(responsePath, "idx" + newDepth, "variable"),
"err.message != null ? err.message : err",
"err"
);
const emptyError = createErrorObject(context, fieldNodes, responsePath, '""');
const uniqueDeclarations = generateUniqueDeclarations(listContext);
const deferredFields = compileDeferredFields(listContext);
const itemHandler = getHoistedFunctionName(
context,
`${parentType.name}${originalObjectPaths.join("")}MapItemHandler`
);
const childIndexes = getParentArgIndexes(listContext);
listContext.hoistedFunctions.push(`
function ${itemHandler}(${GLOBAL_EXECUTION_CONTEXT}, ${GLOBAL_PARENT_NAME}, __currentItem, ${childIndexes}) {
${uniqueDeclarations}
${GLOBAL_PARENT_NAME}[idx${newDepth}] = ${dataBody};
${deferredFields}
}
`);
const safeMapHandler = getHoistedFunctionName(
context,
`${parentType.name}${originalObjectPaths.join("")}MapHandler`
);
const parentIndexes = getParentArgIndexes(context);
listContext.hoistedFunctions.push(`
function ${safeMapHandler}(${GLOBAL_EXECUTION_CONTEXT}, __currentItem, idx${newDepth}, resultArray, ${parentIndexes}) {
if (${isPromiseInliner("__currentItem")}) {
${promiseStarted()}
__currentItem.then(result => {
${itemHandler}(${GLOBAL_EXECUTION_CONTEXT}, resultArray, result, ${childIndexes});
${promiseDone()}
}, err => {
resultArray.push(null);
if (err) {
${getErrorDestination(fieldType)}.push(${executionError});
} else {
${getErrorDestination(fieldType)}.push(${emptyError});
}
${promiseDone()}
});
} else {
${itemHandler}(${GLOBAL_EXECUTION_CONTEXT}, resultArray, __currentItem, ${childIndexes});
}
}
`);
return `(typeof ${name} === "string" || typeof ${name}[Symbol.iterator] !== "function") ? ${errorCase} :
${GLOBAL_SAFE_MAP_NAME}(${GLOBAL_EXECUTION_CONTEXT}, ${name}, ${safeMapHandler}, ${parentIndexes})`;
}
/**
* Implements a generic map operation for any iterable.
*
* If the iterable is not valid, null is returned.
* @param context
* @param {Iterable<any> | string} iterable possible iterable
* @param {(a: any) => any} cb callback that receives the item being iterated
* @param idx
* @returns {any[]} a new array with the result of the callback
*/
function safeMap(
context: ExecutionContext,
iterable: Iterable<any> | string,
cb: (
context: ExecutionContext,
a: any,
index: number,
resultArray: any[],
...idx: number[]
) => any,
...idx: number[]
): any[] {
let index = 0;
const result: any[] = [];
for (const a of iterable) {
cb(context, a, index, result, ...idx);
++index;
}
return result;
}
const MAGIC_MINUS_INFINITY =
"__MAGIC_MINUS_INFINITY__71d4310a_d4a3_4a05_b1fe_e60779d24998";
const MAGIC_PLUS_INFINITY =
"__MAGIC_PLUS_INFINITY__bb201c39_3333_4695_b4ad_7f1722e7aa7a";
const MAGIC_NAN = "__MAGIC_NAN__57f286b9_4c20_487f_b409_79804ddcb4f8";
const MAGIC_DATE = "__MAGIC_DATE__33a9e76d_02e0_4128_8e92_3530ad3da74d";
function specialValueReplacer(this: any, key: any, value: any) {
if (Number.isNaN(value)) {
return MAGIC_NAN;
}
if (value === Infinity) {
return MAGIC_PLUS_INFINITY;
}
if (value === -Infinity) {
return MAGIC_MINUS_INFINITY;
}
if (this[key] instanceof Date) {
return MAGIC_DATE + this[key].getTime();
}
return value;
}
function objectStringify(val: any): string {
return JSON.stringify(val, specialValueReplacer)
.replace(new RegExp(`"${MAGIC_NAN}"`, "g"), "NaN")
.replace(new RegExp(`"${MAGIC_PLUS_INFINITY}"`, "g"), "Infinity")
.replace(new RegExp(`"${MAGIC_MINUS_INFINITY}"`, "g"), "-Infinity")
.replace(new RegExp(`"${MAGIC_DATE}([^"]+)"`, "g"), "new Date($1)");
}
/**
* Calculates a GraphQLResolveInfo object for the resolver calls.
*
* if the resolver does not use, it returns null.
* @param {CompilationContext} context compilation context to submit the resolveInfoResolver
* @param parentType
* @param fieldType
* @param fieldName
* @param fieldNodes
* @param responsePath
* @returns {string} a call to the resolve info creator or "{}" if unused
*/
function getExecutionInfo(
context: CompilationContext,
parentType: GraphQLObjectType,
fieldType: GraphQLOutputType,
fieldName: string,
fieldNodes: FieldNode[],
responsePath: ObjectPath
) {
const resolveInfoName = createResolveInfoName(responsePath);
const { schema, fragments, operation } = context;
context.resolveInfos[resolveInfoName] = createResolveInfoThunk(
{
schema,
fragments,
operation,
parentType,
fieldName,
fieldType,
fieldNodes
},
context.options.resolverInfoEnricher
);
return `${GLOBAL_EXECUTION_CONTEXT}.resolveInfos.${resolveInfoName}(${GLOBAL_ROOT_NAME}, ${GLOBAL_VARIABLES_NAME}, ${serializeResponsePath(
responsePath
)})`;
}
function getArgumentsName(prefixName: string) {
return `${prefixName}Args`;
}
function getValidArgumentsVarName(prefixName: string) {
return `${prefixName}ValidArgs`;
}
function objectPath(topLevel: string, path?: ObjectPath) {
if (!path) {
return topLevel;
}
let objectPath = topLevel;
const flattened = flattenPath(path);
for (const section of flattened) {
if (section.type === "literal") {
objectPath += `["${section.key}"]`;
} else {
/* istanbul ignore next */
throw new Error("should only have received literal paths");
}
}
return objectPath;
}
/**
* Returns a static object with the all the arguments needed for the resolver
* @param context
* @param {Arguments} args
* @param topLevelArg name of the toplevel
* @param validArgs
* @param returnType
* @param path
* @returns {string}
*/
function compileArguments(
context: CompilationContext,
args: Arguments,
topLevelArg: string,
validArgs: string,
returnType: GraphQLOutputType,
path: ObjectPath
): string {
// default to assuming arguments are valid
let body = `
let ${validArgs} = true;
const ${topLevelArg} = ${objectStringify(args.values)};
`;
const errorDestination = getErrorDestination(returnType);
for (const variable of args.missing) {
const varName = variable.valueNode.name.value;
body += `if (Object.prototype.hasOwnProperty.call(${GLOBAL_VARIABLES_NAME}, "${varName}")) {`;
if (variable.argument && isNonNullType(variable.argument.definition.type)) {
const message = `'Argument "${
variable.argument.definition.name
}" of non-null type "${variable.argument.definition.type.toString()}" must not be null.'`;
body += `if (${GLOBAL_VARIABLES_NAME}['${
variable.valueNode.name.value
}'] == null) {
${errorDestination}.push(${createErrorObject(
context,
[variable.argument.node.value],
path,
message
)});
${validArgs} = false;
}`;
}
body += `
${objectPath(topLevelArg, variable.path)} = ${GLOBAL_VARIABLES_NAME}['${
variable.valueNode.name.value
}'];
}`;
// If there is no default value and no variable input
// throw a field error
if (
variable.argument &&
isNonNullType(variable.argument.definition.type) &&
variable.argument.definition.defaultValue === undefined
) {
const message = `'Argument "${
variable.argument.definition.name
}" of required type "${variable.argument.definition.type.toString()}" was provided the variable "$${varName}" which was not provided a runtime value.'`;
body += ` else {
${errorDestination}.push(${createErrorObject(
context,
[variable.argument.node.value],
path,
message
)});
${validArgs} = false;
}`;
}
}
return body;
}
/**
* Safety checks for resolver execution is done via side effects every time a resolver function
* is encountered.
*
* This function generates the declarations, so the side effect is valid code.
*
* @param {CompilationContext} context compilation context
* @param {boolean} defaultValue usually false, meant to be true at the top level
* @returns {string} a list of declarations eg: var __validNode0 = false;\nvar __validNode1 = false;
*/
function generateUniqueDeclarations(
context: CompilationContext,
defaultValue = false
) {
return context.deferred
.map(
(_, idx) => `
let ${SAFETY_CHECK_PREFIX}${idx} = ${defaultValue};
`
)
.join("\n");
}
function createSubCompilationContext(
context: CompilationContext
): CompilationContext {
return { ...context, deferred: [] };
}
export function isPromise(value: any): value is Promise<any> {
return (
value != null &&
typeof value === "object" &&
typeof value.then === "function"
);
}
export function isPromiseInliner(value: string): string {
return `${value} != null && typeof ${value} === "object" && typeof ${value}.then === "function"`;
}
/**
* Serializes the response path for an error response.
*
* @param {ObjectPath | undefined} path response path of a field
* @returns {string} filtered serialization of the response path
*/
function serializeResponsePathAsArray(path: ObjectPath) {
const flattened = flattenPath(path);
let src = "[";
for (let i = flattened.length - 1; i >= 0; i--) {
// meta is only used for the function name
if (flattened[i].type === "meta") {
continue;
}
src +=
flattened[i].type === "literal"
? `"${flattened[i].key}",`
: `${flattened[i].key},`;
}
return src + "]";
}
function getErrorDestination(type: GraphQLType): string {
return isNonNullType(type) ? GLOBAL_NULL_ERRORS_NAME : GLOBAL_ERRORS_NAME;
}
function createResolveInfoName(path: ObjectPath) {
return (
flattenPath(path)
.map((p) => p.key)
.join("_") + "Info"
);
}
/**
* Serializes the response path for the resolve info function
* @param {ObjectPath | undefined} path response path of a field
* @returns {string} filtered serialization of the response path
*/
function serializeResponsePath(path: ObjectPath | undefined): string {
if (!path) {
return "undefined";
}
if (path.type === "meta") {
// meta is ignored while serializing for the resolve info functions
return serializeResponsePath(path.prev);
}
const literalValue = `"${path.key}"`;
return `{
key: ${path.type === "literal" ? literalValue : path.key},
prev: ${serializeResponsePath(path.prev)}
}`;
}
/**
* Returned a bound serialization function of a scalar or enum
* @param {GraphQLScalarType | GraphQLEnumType} scalar
* @param customSerializer custom serializer
* @returns {(v: any) => any} bound serializationFunction
*/
function getSerializer(
scalar: GraphQLScalarType | GraphQLEnumType,
customSerializer?: GraphQLScalarSerializer<any>
) {
const { name } = scalar;
const serialize = customSerializer || ((val: any) => scalar.serialize(val));
return function leafSerializer(
context: ExecutionContext,
v: any,
onError: (c: ExecutionContext, msg: string, ...idx: number[]) => void,
...idx: number[]
) {
try {
const value = serialize(v);
if (isInvalid(value)) {
onError(
context,
`Expected a value of type "${name}" but received: ${v}`,
...idx
);
return null;
}
return value;
} catch (e: any) {
onError(
context,
(e && e.message) ||
`Expected a value of type "${name}" but received an Error`,
...idx
);
return null;
}
};
}
/**
* Default abstract type resolver.
*
* It only handle sync type resolving.
* @param value
* @param contextValue
* @param {GraphQLResolveInfo} info
* @param {GraphQLAbstractType} abstractType
* @returns {string}
*/
function defaultResolveTypeFn(
value: any,
contextValue: any,
info: GraphQLResolveInfo,
abstractType: GraphQLAbstractType
): string {
// First, look for `__typename`.
if (
value != null &&
typeof value === "object" &&
typeof value.__typename === "string"
) {
return value.__typename;
}
// Otherwise, test each possible type.
const possibleTypes = info.schema.getPossibleTypes(abstractType);
for (const type of possibleTypes) {
if (type.isTypeOf) {
const isTypeOfResult = type.isTypeOf(value, contextValue, info);
if (isPromise(isTypeOfResult)) {
throw new Error(
`Promises are not supported for resolving type of ${value}`
);
} else if (isTypeOfResult) {
return type.name;
}
}
}
throw new Error(
`Could not resolve the object type in possible types of ${abstractType.name} for the value: ` +
inspect(value)
);
}
/**
* Constructs a ExecutionContext object from the arguments passed to
* execute, which we will pass throughout the other execution methods.
*
* Throws a GraphQLError if a valid execution context cannot be created.
*/
function buildCompilationContext(
schema: GraphQLSchema,
document: DocumentNode,
options: CompilerOptions,
operationName?: string
): CompilationContext {
const errors: GraphQLError[] = [];
let operation: OperationDefinitionNode | void;
let hasMultipleAssumedOperations = false;
const fragments: { [key: string]: FragmentDefinitionNode } =
Object.create(null);
for (const definition of document.definitions) {
switch (definition.kind) {
case Kind.OPERATION_DEFINITION:
if (!operationName && operation) {
hasMultipleAssumedOperations = true;
} else if (
!operationName ||
(definition.name && definition.name.value === operationName)
) {
operation = definition;
}
break;
case Kind.FRAGMENT_DEFINITION:
fragments[definition.name.value] = definition;
break;
}
}
if (!operation) {
if (operationName) {
throw new GraphQLError(`Unknown operation named "${operationName}".`);
} else {
throw new GraphQLError("Must provide an operation.");
}
} else if (hasMultipleAssumedOperations) {
throw new GraphQLError(
"Must provide operation name if query contains multiple operations."
);
}
return {
schema,
fragments,
rootValue: null,
contextValue: null,
operation,
options,
resolvers: {},
serializers: {},
typeResolvers: {},
isTypeOfs: {},
resolveInfos: {},
hoistedFunctions: [],
hoistedFunctionNames: new Map(),
deferred: [],
depth: -1,
variableValues: {},
errors
} as unknown as CompilationContext;
}
function getFieldNodesName(nodes: FieldNode[]) {
return nodes.length > 1
? "(" + nodes.map(({ name }) => name.value).join(",") + ")"
: nodes[0].name.value;
}
function getHoistedFunctionName(context: CompilationContext, name: string) {
const count = context.hoistedFunctionNames.get(name);
if (count === undefined) {
context.hoistedFunctionNames.set(name, 0);
return name;
}
context.hoistedFunctionNames.set(name, count + 1);
return `${name}${count + 1}`;
}
function createErrorObject(
context: CompilationContext,
nodes: ASTNode[],
path: ObjectPath,
message: string,
originalError?: string
): string {
return `new ${GRAPHQL_ERROR}(${message},
${JSON.stringify(computeLocations(nodes))},
${serializeResponsePathAsArray(path)},
${originalError || "undefined"},
${context.options.disablingCapturingStackErrors ? "true" : "false"})`;
}
function getResolverName(parentName: string, name: string) {
return parentName + name + "Resolver";
}
function getTypeResolverName(name: string) {
return name + "TypeResolver";
}
function getSerializerName(name: string) {
return name + "Serializer";
}
function promiseStarted() {
return `
// increase the promise counter
++${GLOBAL_PROMISE_COUNTER};
`;
}
function promiseDone() {
return `
--${GLOBAL_PROMISE_COUNTER};
if (${GLOBAL_PROMISE_COUNTER} === 0) {
${GLOBAL_RESOLVE}(${GLOBAL_EXECUTION_CONTEXT});
}
`;
}
function normalizeErrors(err: Error[] | Error): GraphQLError[] {
if (Array.isArray(err)) {
return err.map((e) => normalizeError(e));
}
return [normalizeError(err)];
}
function normalizeError(err: Error): GraphQLError {
return err instanceof GraphQLError
? err
: new (GraphqlJitError as any)(
err.message,
(err as any).locations,
(err as any).path,
err
);
}
/**
* Returns true if a value is undefined, or NaN.
*/
function isInvalid(value: any): boolean {
// eslint-disable-next-line no-self-compare
return value === undefined || value !== value;
}
function getParentArgIndexes(context: CompilationContext) {
let args = "";
for (let i = 0; i <= context.depth; ++i) {
if (i > 0) {
args += ", ";
}
args += `idx${i}`;
}
return args;
}
function getJsFieldName(fieldName: string) {
return `${LOCAL_JS_FIELD_NAME_PREFIX}${fieldName}`;
}
export function isAsyncIterable<T = unknown>(
val: unknown
): val is AsyncIterableIterator<T> {
return typeof Object(val)[Symbol.asyncIterator] === "function";
}
function compileSubscriptionOperation(
context: CompilationContext,
type: GraphQLObjectType,
fieldMap: FieldsAndNodes,
queryFn: CompiledQuery["query"]
) {
const fieldNodes = Object.values(fieldMap)[0];
const fieldNode = fieldNodes[0];
const fieldName = fieldNode.name.value;
const field = resolveFieldDef(context, type, fieldNodes);
if (!field) {
throw new GraphQLError(
`The subscription field "${fieldName}" is not defined.`,
fieldNodes
);
}
const responsePath = addPath(undefined, fieldName);
const resolveInfoName = createResolveInfoName(responsePath);
const subscriber = field.subscribe;
async function executeSubscription(executionContext: ExecutionContext) {
const resolveInfo = executionContext.resolveInfos[resolveInfoName](
executionContext.rootValue,
executionContext.variables,
responsePath
);
try {
const eventStream = await subscriber?.(
executionContext.rootValue,
executionContext.variables,
executionContext.context,
resolveInfo
);
if (eventStream instanceof Error) {
throw eventStream;
}
return eventStream;
} catch (error) {
throw locatedError(
error,
resolveInfo.fieldNodes,
pathToArray(resolveInfo.path)
);
}
}
async function createSourceEventStream(executionContext: ExecutionContext) {
try {
const eventStream = await executeSubscription(executionContext);
// Assert field returned an event stream, otherwise yield an error.
if (!isAsyncIterable(eventStream)) {
throw new Error(
"Subscription field must return Async Iterable. " +
`Received: ${inspect(eventStream)}.`
);
}
return eventStream;
} catch (error) {
// If it is a GraphQLError, report it as an ExecutionResult, containing only errors and no data.
// Otherwise treat the error as a system-class error and re-throw it.
if (error instanceof GraphQLError) {
return { errors: [error] };
}
throw error;
}
}
return async function subscribe(executionContext: ExecutionContext) {
const resultOrStream = await createSourceEventStream(executionContext);
if (!isAsyncIterable(resultOrStream)) {
return resultOrStream;
}
// For each payload yielded from a subscription, map it over the normal
// GraphQL `execute` function, with `payload` as the rootValue.
// This implements the "MapSourceToResponseEvent" algorithm described in
// the GraphQL specification. The `execute` function provides the
// "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
// "ExecuteQuery" algorithm, for which `execute` is also used.
// We use our `query` function in place of `execute`
const mapSourceToResponse = (payload: any) =>
queryFn(payload, executionContext.context, executionContext.variables);
return mapAsyncIterator(resultOrStream, mapSourceToResponse);
};
}
function createBoundSubscribe(
compilationContext: CompilationContext,
document: DocumentNode,
func: (
context: ExecutionContext
) => Promise<AsyncIterableIterator<ExecutionResult> | ExecutionResult>,
getVariableValues: (inputs: { [key: string]: any }) => CoercedVariableValues,
operationName: string | undefined
): CompiledQuery["subscribe"] {
const { resolvers, typeResolvers, isTypeOfs, serializers, resolveInfos } =
compilationContext;
const trimmer = createNullTrimmer(compilationContext);
const fnName = operationName || "subscribe";
const ret = {
async [fnName](
rootValue: any,
context: any,
variables: Maybe<{ [key: string]: any }>
): Promise<AsyncIterableIterator<ExecutionResult> | ExecutionResult> {
// this can be shared across in a batch request
const parsedVariables = getVariableValues(variables || {});
// Return early errors if variable coercing failed.
if (failToParseVariables(parsedVariables)) {
return { errors: parsedVariables.errors };
}
const executionContext: ExecutionContext = {
rootValue,
context,
variables: parsedVariables.coerced,
safeMap,
inspect,
GraphQLError: GraphqlJitError,
resolvers,
typeResolvers,
isTypeOfs,
serializers,
resolveInfos,
trimmer,
promiseCounter: 0,
nullErrors: [],
errors: [],
data: {}
};
// eslint-disable-next-line no-useless-call
return func.call(null, executionContext);
}
};
return ret[fnName];
}
/**
* Given an AsyncIterable and a callback function, return an AsyncIterator
* which produces values mapped via calling the callback function.
*/
function mapAsyncIterator<T, U, R = undefined>(
iterable: AsyncGenerator<T, R, undefined> | AsyncIterable<T>,
callback: (value: T) => U | Promise<U>
): AsyncGenerator<U, R, undefined> {
const iterator = iterable[Symbol.asyncIterator]();
async function mapResult(
result: IteratorResult<T, R>
): Promise<IteratorResult<U, R>> {
if (result.done) {
return result;
}
try {
return { value: await callback(result.value), done: false };
} catch (error) {
if (typeof iterator.return === "function") {
try {
await iterator.return();
} catch (e) {
/* ignore error */
}
}
throw error;
}
}
return {
async next() {
return mapResult(await iterator.next());
},
async return(): Promise<IteratorResult<U, R>> {
return typeof iterator.return === "function"
? mapResult(await iterator.return())
: { value: undefined as unknown as R, done: true };
},
async throw(error?: Error) {
return typeof iterator.throw === "function"
? mapResult(await iterator.throw(error))
: Promise.reject(error);
},
[Symbol.asyncIterator]() {
return this;
}
};
} | the_stack |
import { Buffer, Neovim, Window } from '@chemzqm/neovim'
import debounce from 'debounce'
import { Disposable } from 'vscode-languageserver-protocol'
import { Mutex } from '../util/mutex'
import extensions from '../extensions'
import Highlighter from '../model/highligher'
import { IList, ListAction, ListContext, ListItem, ListMode, ListOptions, Matcher } from '../types'
import { disposeAll, wait } from '../util'
import workspace from '../workspace'
import window from '../window'
import ListConfiguration from './configuration'
import InputHistory from './history'
import Prompt from './prompt'
import UI from './ui'
import Worker from './worker'
const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
const logger = require('../util/logger')('list-session')
/**
* Activated list session with UI and worker
*/
export default class ListSession {
public readonly history: InputHistory
public readonly ui: UI
public readonly worker: Worker
private cwd: string
private interval: NodeJS.Timer
private loadingFrame = ''
private timer: NodeJS.Timer
private hidden = false
private disposables: Disposable[] = []
private savedHeight: number
private window: Window
private buffer: Buffer
private interactiveDebounceTime: number
private mutex: Mutex = new Mutex()
/**
* Original list arguments.
*/
private args: string[] = []
constructor(
private nvim: Neovim,
private prompt: Prompt,
private list: IList,
public readonly listOptions: ListOptions,
private listArgs: string[] = [],
private config: ListConfiguration
) {
this.ui = new UI(nvim, list.name, listOptions, config)
this.history = new InputHistory(prompt, list.name)
this.worker = new Worker(nvim, list, prompt, listOptions, {
interactiveDebounceTime: config.get<number>('interactiveDebounceTime', 100),
extendedSearchMode: config.get<boolean>('extendedSearchMode', true)
})
this.interactiveDebounceTime = config.get<number>('interactiveDebounceTime', 100)
let debouncedChangeLine = debounce(async () => {
let [previewing, currwin, lnum] = await nvim.eval('[coc#list#has_preview(),win_getid(),line(".")]') as [number, number, number]
if (previewing && currwin == this.winid) {
await this.doPreview(lnum - 1)
}
}, 50)
this.disposables.push({
dispose: () => {
debouncedChangeLine.clear()
}
})
this.ui.onDidChangeLine(debouncedChangeLine, null, this.disposables)
this.ui.onDidChangeLine(this.resolveItem, this, this.disposables)
this.ui.onDidLineChange(this.resolveItem, this, this.disposables)
let debounced = debounce(async () => {
let { autoPreview } = this.listOptions
if (!autoPreview) {
let [previewing, mode] = await nvim.eval('[coc#list#has_preview(),mode()]') as [number, string]
if (!previewing || mode != 'n') return
}
await this.doAction('preview')
}, 50)
this.disposables.push({
dispose: () => {
debounced.clear()
}
})
this.ui.onDidLineChange(debounced, null, this.disposables)
this.ui.onDidLineChange(() => {
this.updateStatus()
}, null, this.disposables)
this.ui.onDidOpen(async () => {
if (typeof this.list.doHighlight == 'function') {
this.list.doHighlight()
}
if (this.listOptions.first) {
await this.doAction()
}
}, null, this.disposables)
this.ui.onDidClose(async () => {
await this.hide()
}, null, this.disposables)
this.ui.onDidDoubleClick(async () => {
await this.doAction()
}, null, this.disposables)
this.worker.onDidChangeItems(async ({ items, reload, append, finished }) => {
let release = await this.mutex.acquire()
if (!this.hidden) {
try {
if (append) {
this.ui.appendItems(items)
} else {
let height = this.config.get<number>('height', 10)
if (finished && !listOptions.interactive && listOptions.input.length == 0) {
height = Math.min(items.length, height)
}
await this.ui.drawItems(items, Math.max(1, height), reload)
}
} catch (e) {
nvim.echoError(e)
}
}
release()
}, null, this.disposables)
this.worker.onDidChangeLoading(loading => {
if (this.hidden) return
if (loading) {
this.interval = setInterval(() => {
let idx = Math.floor((new Date()).getMilliseconds() / 100)
this.loadingFrame = frames[idx]
this.updateStatus()
}, 100)
} else {
if (this.interval) {
this.loadingFrame = ''
clearInterval(this.interval)
this.interval = null
}
this.updateStatus()
}
}, null, this.disposables)
}
public async start(args: string[]): Promise<void> {
this.args = args
this.cwd = workspace.cwd
this.hidden = false
let { listOptions, listArgs } = this
let res = await this.nvim.eval('[win_getid(),bufnr("%"),winheight("%")]')
this.listArgs = listArgs
this.history.load(listOptions.input || '')
this.window = this.nvim.createWindow(res[0])
this.buffer = this.nvim.createBuffer(res[1])
this.savedHeight = res[2]
await this.worker.loadItems(this.context)
}
public async reloadItems(): Promise<void> {
if (!this.window) return
let bufnr = await this.nvim.call('winbufnr', [this.window.id])
// can't reload since window not exists
if (bufnr == -1) return
this.buffer = this.nvim.createBuffer(bufnr)
await this.worker.loadItems(this.context, true)
}
public async call(fname: string): Promise<any> {
await this.nvim.call('coc#prompt#stop_prompt', ['list'])
let targets = await this.ui.getItems()
let context = {
name: this.name,
args: this.listArgs,
input: this.prompt.input,
winid: this.window?.id,
bufnr: this.buffer?.id,
targets
}
let res = await this.nvim.call(fname, [context])
this.prompt.start()
return res
}
public async chooseAction(): Promise<void> {
let { nvim } = this
let { actions, defaultAction } = this.list
let names: string[] = actions.map(o => o.name)
let idx = names.indexOf(defaultAction)
if (idx != -1) {
names.splice(idx, 1)
names.unshift(defaultAction)
}
let shortcuts: Set<string> = new Set()
let choices: string[] = []
let invalids: string[] = []
for (let name of names) {
let i = 0
for (let ch of name) {
if (!shortcuts.has(ch)) {
shortcuts.add(ch)
choices.push(`${name.slice(0, i)}&${name.slice(i)}`)
break
}
i++
}
if (i == name.length) {
invalids.push(name)
}
}
if (invalids.length) {
names = names.filter(s => !invalids.includes(s))
}
await nvim.call('coc#prompt#stop_prompt', ['list'])
let n = await nvim.call('confirm', ['Choose action:', choices.join('\n')]) as number
await wait(10)
this.prompt.start()
if (n) await this.doAction(names[n - 1])
if (invalids.length) {
nvim.echoError(`Can't create shortcut for actions: ${invalids.join(',')} of "${this.name}" list`)
}
}
public async doAction(name?: string): Promise<void> {
let { list } = this
name = name || list.defaultAction
let action = list.actions.find(o => o.name == name)
if (!action) {
window.showMessage(`Action ${name} not found`, 'error')
return
}
let items: ListItem[]
if (name == 'preview') {
let item = await this.ui.item
items = item ? [item] : []
} else {
items = await this.ui.getItems()
}
if (items.length) await this.doItemAction(items, action)
}
private async doPreview(index: number): Promise<void> {
let item = this.ui.getItem(index)
let action = this.list.actions.find(o => o.name == 'preview')
if (!item || !action) return
await this.doItemAction([item], action)
}
public async first(): Promise<void> {
await this.doDefaultAction(0)
}
public async last(): Promise<void> {
await this.doDefaultAction(this.ui.length - 1)
}
public async previous(): Promise<void> {
await this.doDefaultAction(this.ui.index - 1)
}
public async next(): Promise<void> {
await this.doDefaultAction(this.ui.index + 1)
}
private async doDefaultAction(index: number): Promise<void> {
let { ui } = this
let item = ui.getItem(index)
if (!item) return
ui.index = index
await this.doItemAction([item], this.defaultAction)
await ui.echoMessage(item)
}
/**
* list name
*/
public get name(): string {
return this.list.name
}
/**
* Window id used by list.
*
* @returns {number | undefined}
*/
public get winid(): number | undefined {
return this.ui.winid
}
public get length(): number {
return this.ui.length
}
private get defaultAction(): ListAction {
let { defaultAction, actions } = this.list
let action = actions.find(o => o.name == defaultAction)
if (!action) throw new Error(`default action "${defaultAction}" not found`)
return action
}
public async hide(): Promise<void> {
if (this.hidden) return
let { nvim, interval } = this
if (interval) clearInterval(interval)
this.hidden = true
this.worker.stop()
this.history.add()
let { winid } = this.ui
this.ui.reset()
if (this.window && winid) {
await nvim.call('coc#list#hide', [this.window.id, this.savedHeight, winid])
if (workspace.isVim) {
nvim.command('redraw', true)
// Needed for tabe action, don't know why.
await wait(10)
}
}
nvim.call('coc#prompt#stop_prompt', ['list'], true)
}
public toggleMode(): void {
let mode: ListMode = this.prompt.mode == 'normal' ? 'insert' : 'normal'
this.prompt.mode = mode
this.listOptions.mode = mode
this.updateStatus()
}
public stop(): void {
this.worker.stop()
}
private async resolveItem(): Promise<void> {
let index = this.ui.index
let item = this.ui.getItem(index)
if (!item || item.resolved) return
let { list } = this
if (typeof list.resolveItem == 'function') {
let resolved = await Promise.resolve(list.resolveItem(item))
if (resolved && index == this.ui.index) {
await this.ui.updateItem(resolved, index)
}
}
}
public async showHelp(): Promise<void> {
await this.hide()
let { list, nvim } = this
if (!list) return
nvim.pauseNotification()
nvim.command(`tabe +setl\\ previewwindow [LIST HELP]`, true)
nvim.command('setl nobuflisted noswapfile buftype=nofile bufhidden=wipe', true)
await nvim.resumeNotification()
let hasOptions = list.options && list.options.length
let buf = await nvim.buffer
let highligher = new Highlighter()
highligher.addLine('NAME', 'Label')
highligher.addLine(` ${list.name} - ${list.description || ''}\n`)
highligher.addLine('SYNOPSIS', 'Label')
highligher.addLine(` :CocList [LIST OPTIONS] ${list.name}${hasOptions ? ' [ARGUMENTS]' : ''}\n`)
if (list.detail) {
highligher.addLine('DESCRIPTION', 'Label')
let lines = list.detail.split('\n').map(s => ' ' + s)
highligher.addLine(lines.join('\n') + '\n')
}
if (hasOptions) {
highligher.addLine('ARGUMENTS', 'Label')
highligher.addLine('')
for (let opt of list.options) {
highligher.addLine(opt.name, 'Special')
highligher.addLine(` ${opt.description}`)
highligher.addLine('')
}
highligher.addLine('')
}
let config = workspace.getConfiguration(`list.source.${list.name}`)
if (Object.keys(config).length) {
highligher.addLine('CONFIGURATIONS', 'Label')
highligher.addLine('')
let props = {}
extensions.all.forEach(extension => {
let { packageJSON } = extension
let { contributes } = packageJSON
if (!contributes) return
let { configuration } = contributes
if (configuration) {
let { properties } = configuration
if (properties) {
for (let key of Object.keys(properties)) {
props[key] = properties[key]
}
}
}
})
for (let key of Object.keys(config)) {
let val = config[key]
let name = `list.source.${list.name}.${key}`
let description = props[name] && props[name].description ? props[name].description : key
highligher.addLine(` "${name}"`, 'MoreMsg')
highligher.addText(` - ${description}, current value: `)
highligher.addText(JSON.stringify(val), 'Special')
}
highligher.addLine('')
}
highligher.addLine('ACTIONS', 'Label')
highligher.addLine(` ${list.actions.map(o => o.name).join(', ')}`)
highligher.addLine('')
highligher.addLine(`see ':h coc-list-options' for available list options.`, 'Comment')
nvim.pauseNotification()
highligher.render(buf, 0, -1)
nvim.command('setl nomod', true)
nvim.command('setl nomodifiable', true)
nvim.command('normal! gg', true)
nvim.command('nnoremap <buffer> q :bd!<CR>', true)
await nvim.resumeNotification()
}
public switchMatcher(): void {
let { matcher, interactive } = this.listOptions
if (interactive) return
const list: Matcher[] = ['fuzzy', 'strict', 'regex']
let idx = list.indexOf(matcher) + 1
if (idx >= list.length) idx = 0
this.listOptions.matcher = list[idx]
this.prompt.matcher = list[idx]
this.worker.drawItems()
}
public updateStatus(): void {
let { ui, list, nvim } = this
if (!ui.winid) return
let buf = nvim.createBuffer(ui.bufnr)
let status = {
mode: this.prompt.mode.toUpperCase(),
args: this.args.join(' '),
name: list.name,
cwd: this.cwd,
loading: this.loadingFrame,
total: this.worker.length
}
nvim.pauseNotification()
buf.setVar('list_status', status, true)
nvim.command('redraws', true)
nvim.resumeNotification(false, true).logError()
}
public get context(): ListContext {
let { winid } = this.ui
return {
options: this.listOptions,
args: this.listArgs,
input: this.prompt.input,
cwd: workspace.cwd,
window: this.window,
buffer: this.buffer,
listWindow: winid ? this.nvim.createWindow(winid) : undefined
}
}
public onMouseEvent(key): Promise<void> {
switch (key) {
case '<LeftMouse>':
return this.ui.onMouse('mouseDown')
case '<LeftDrag>':
return this.ui.onMouse('mouseDrag')
case '<LeftRelease>':
return this.ui.onMouse('mouseUp')
case '<2-LeftMouse>':
return this.ui.onMouse('doubleClick')
}
}
public async doNumberSelect(ch: string): Promise<boolean> {
if (!this.listOptions.numberSelect) return false
let code = ch.charCodeAt(0)
if (code >= 48 && code <= 57) {
let n = Number(ch)
if (n == 0) n = 10
if (this.ui.length >= n) {
this.nvim.pauseNotification()
this.ui.setCursor(n, 0)
await this.nvim.resumeNotification()
await this.doAction()
return true
}
}
return false
}
public jumpBack(): void {
let { window, nvim } = this
if (window) {
nvim.pauseNotification()
nvim.call('coc#prompt#stop_prompt', ['list'], true)
this.nvim.call('win_gotoid', [window.id], true)
nvim.resumeNotification(false, true).logError()
}
}
public async resume(): Promise<void> {
if (this.winid) await this.hide()
let res = await this.nvim.eval('[win_getid(),bufnr("%"),winheight("%")]')
this.hidden = false
this.window = this.nvim.createWindow(res[0])
this.buffer = this.nvim.createBuffer(res[1])
this.savedHeight = res[2]
this.prompt.start()
await this.ui.resume()
if (this.listOptions.autoPreview) {
await this.doAction('preview')
}
}
private async doItemAction(items: ListItem[], action: ListAction): Promise<void> {
let { noQuit } = this.listOptions
let { nvim } = this
let persistAction = action.persist === true || action.name == 'preview'
let persist = this.winid && (persistAction || noQuit)
try {
if (persist) {
if (!persistAction) {
nvim.pauseNotification()
nvim.call('coc#prompt#stop_prompt', ['list'], true)
nvim.call('win_gotoid', [this.context.window.id], true)
await nvim.resumeNotification()
}
} else {
await this.hide()
}
if (action.multiple) {
await Promise.resolve(action.execute(items, this.context))
} else if (action.parallel) {
await Promise.all(items.map(item => Promise.resolve(action.execute(item, this.context))))
} else {
for (let item of items) {
await Promise.resolve(action.execute(item, this.context))
}
}
if (persist) {
this.ui.restoreWindow()
}
if (action.reload && persist) await this.worker.loadItems(this.context, true)
} catch (e) {
window.showMessage(e.message, 'error')
logger.error(`Error on action "${action.name}"`, e)
}
}
public onInputChange(): void {
if (this.timer) clearTimeout(this.timer)
let len = this.worker.length
this.listOptions.input = this.prompt.input
// reload or filter items
if (this.listOptions.interactive) {
this.worker.stop()
this.timer = setTimeout(async () => {
await this.worker.loadItems(this.context)
}, this.interactiveDebounceTime)
} else if (len) {
let wait = Math.max(Math.min(Math.floor(len / 200), 300), 50)
this.timer = setTimeout(() => {
this.worker.drawItems()
}, wait)
}
}
public dispose(): void {
if (!this.hidden) {
this.hidden = true
let { winid } = this.ui
this.ui.reset()
if (this.window && winid) {
this.nvim.call('coc#list#hide', [this.window.id, this.savedHeight, winid], true)
}
}
if (this.interval) {
clearInterval(this.interval)
}
if (this.timer) {
clearTimeout(this.timer)
}
disposeAll(this.disposables)
this.worker.dispose()
this.ui.dispose()
}
} | the_stack |
import * as moment from "moment";
/**
* Error body.
*/
export interface ErrorModel {
code?: string;
message?: string;
}
/**
* Error information returned by the API
*/
export interface APIError {
error?: ErrorModel;
}
/**
* A rectangle within which a face can be found
*/
export interface FaceRectangle {
/**
* The width of the rectangle, in pixels.
*/
width: number;
/**
* The height of the rectangle, in pixels.
*/
height: number;
/**
* The distance from the left edge if the image to the left edge of the rectangle, in pixels.
*/
left: number;
/**
* The distance from the top edge if the image to the top edge of the rectangle, in pixels.
*/
top: number;
}
/**
* Coordinates within an image
*/
export interface Coordinate {
/**
* The horizontal component, in pixels.
*/
x: number;
/**
* The vertical component, in pixels.
*/
y: number;
}
/**
* A collection of 27-point face landmarks pointing to the important positions of face components.
*/
export interface FaceLandmarks {
pupilLeft?: Coordinate;
pupilRight?: Coordinate;
noseTip?: Coordinate;
mouthLeft?: Coordinate;
mouthRight?: Coordinate;
eyebrowLeftOuter?: Coordinate;
eyebrowLeftInner?: Coordinate;
eyeLeftOuter?: Coordinate;
eyeLeftTop?: Coordinate;
eyeLeftBottom?: Coordinate;
eyeLeftInner?: Coordinate;
eyebrowRightInner?: Coordinate;
eyebrowRightOuter?: Coordinate;
eyeRightInner?: Coordinate;
eyeRightTop?: Coordinate;
eyeRightBottom?: Coordinate;
eyeRightOuter?: Coordinate;
noseRootLeft?: Coordinate;
noseRootRight?: Coordinate;
noseLeftAlarTop?: Coordinate;
noseRightAlarTop?: Coordinate;
noseLeftAlarOutTip?: Coordinate;
noseRightAlarOutTip?: Coordinate;
upperLipTop?: Coordinate;
upperLipBottom?: Coordinate;
underLipTop?: Coordinate;
underLipBottom?: Coordinate;
}
/**
* Properties describing facial hair attributes.
*/
export interface FacialHair {
moustache?: number;
beard?: number;
sideburns?: number;
}
/**
* Properties indicating head pose of the face.
*/
export interface HeadPose {
roll?: number;
yaw?: number;
pitch?: number;
}
/**
* Properties describing facial emotion in form of confidence ranging from 0 to 1.
*/
export interface Emotion {
anger?: number;
contempt?: number;
disgust?: number;
fear?: number;
happiness?: number;
neutral?: number;
sadness?: number;
surprise?: number;
}
/**
* Hair color and associated confidence
*/
export interface HairColor {
/**
* Name of the hair color. Possible values include: 'unknown', 'white', 'gray', 'blond', 'brown',
* 'red', 'black', 'other'
*/
color?: string;
/**
* Confidence level of the color
*/
confidence?: number;
}
/**
* Properties describing hair attributes.
*/
export interface Hair {
/**
* A number describing confidence level of whether the person is bald.
*/
bald?: number;
/**
* A boolean value describing whether the hair is visible in the image.
*/
invisible?: boolean;
/**
* An array of candidate colors and confidence level in the presence of each.
*/
hairColor?: HairColor[];
}
/**
* Properties describing present makeups on a given face.
*/
export interface Makeup {
/**
* A boolean value describing whether eye makeup is present on a face.
*/
eyeMakeup?: boolean;
/**
* A boolean value describing whether lip makeup is present on a face.
*/
lipMakeup?: boolean;
}
/**
* Properties describing occlusions on a given face.
*/
export interface Occlusion {
/**
* A boolean value indicating whether forehead is occluded.
*/
foreheadOccluded?: boolean;
/**
* A boolean value indicating whether eyes are occluded.
*/
eyeOccluded?: boolean;
/**
* A boolean value indicating whether the mouth is occluded.
*/
mouthOccluded?: boolean;
}
/**
* Accessory item and corresponding confidence level.
*/
export interface Accessory {
/**
* Type of an accessory. Possible values include: 'headWear', 'glasses', 'mask'
*/
type?: string;
/**
* Confidence level of an accessory
*/
confidence?: number;
}
/**
* Properties describing any presence of blur within the image.
*/
export interface Blur {
/**
* An enum value indicating level of blurriness. Possible values include: 'Low', 'Medium', 'High'
*/
blurLevel?: string;
/**
* A number indicating level of blurriness ranging from 0 to 1.
*/
value?: number;
}
/**
* Properties describing exposure level of the image.
*/
export interface Exposure {
/**
* An enum value indicating level of exposure. Possible values include: 'UnderExposure',
* 'GoodExposure', 'OverExposure'
*/
exposureLevel?: string;
/**
* A number indicating level of exposure level ranging from 0 to 1. [0, 0.25) is under exposure.
* [0.25, 0.75) is good exposure. [0.75, 1] is over exposure.
*/
value?: number;
}
/**
* Properties describing noise level of the image.
*/
export interface Noise {
/**
* An enum value indicating level of noise. Possible values include: 'Low', 'Medium', 'High'
*/
noiseLevel?: string;
/**
* A number indicating level of noise level ranging from 0 to 1. [0, 0.25) is under exposure.
* [0.25, 0.75) is good exposure. [0.75, 1] is over exposure. [0, 0.3) is low noise level. [0.3,
* 0.7) is medium noise level. [0.7, 1] is high noise level.
*/
value?: number;
}
/**
* Face Attributes
*/
export interface FaceAttributes {
/**
* Age in years
*/
age?: number;
/**
* Possible gender of the face. Possible values include: 'male', 'female'
*/
gender?: string;
/**
* Smile intensity, a number between [0,1]
*/
smile?: number;
/**
* Properties describing facial hair attributes.
*/
facialHair?: FacialHair;
/**
* Glasses type if any of the face. Possible values include: 'noGlasses', 'readingGlasses',
* 'sunglasses', 'swimmingGoggles'
*/
glasses?: string;
/**
* Properties indicating head pose of the face.
*/
headPose?: HeadPose;
/**
* Properties describing facial emotion in form of confidence ranging from 0 to 1.
*/
emotion?: Emotion;
/**
* Properties describing hair attributes.
*/
hair?: Hair;
/**
* Properties describing present makeups on a given face.
*/
makeup?: Makeup;
/**
* Properties describing occlusions on a given face.
*/
occlusion?: Occlusion;
/**
* Properties describing any accessories on a given face.
*/
accessories?: Accessory[];
/**
* Properties describing any presence of blur within the image.
*/
blur?: Blur;
/**
* Properties describing exposure level of the image.
*/
exposure?: Exposure;
/**
* Properties describing noise level of the image.
*/
noise?: Noise;
}
/**
* Detected Face object.
*/
export interface DetectedFace {
faceId?: string;
/**
* Possible values include: 'recognition_01', 'recognition_02'
*/
recognitionModel?: string;
faceRectangle: FaceRectangle;
faceLandmarks?: FaceLandmarks;
faceAttributes?: FaceAttributes;
}
/**
* Request body for find similar operation.
*/
export interface FindSimilarRequest {
/**
* FaceId of the query face. User needs to call Face - Detect first to get a valid faceId. Note
* that this faceId is not persisted and will expire 24 hours after the detection call
*/
faceId: string;
/**
* An existing user-specified unique candidate face list, created in Face List - Create a Face
* List. Face list contains a set of persistedFaceIds which are persisted and will never expire.
* Parameter faceListId, largeFaceListId and faceIds should not be provided at the same time.
*/
faceListId?: string;
/**
* An existing user-specified unique candidate large face list, created in LargeFaceList -
* Create. Large face list contains a set of persistedFaceIds which are persisted and will never
* expire. Parameter faceListId, largeFaceListId and faceIds should not be provided at the same
* time.
*/
largeFaceListId?: string;
/**
* An array of candidate faceIds. All of them are created by Face - Detect and the faceIds will
* expire 24 hours after the detection call. The number of faceIds is limited to 1000. Parameter
* faceListId, largeFaceListId and faceIds should not be provided at the same time.
*/
faceIds?: string[];
/**
* The number of top similar faces returned. The valid range is [1, 1000].
*/
maxNumOfCandidatesReturned?: number;
/**
* Similar face searching mode. It can be "matchPerson" or "matchFace". Possible values include:
* 'matchPerson', 'matchFace'
*/
mode?: string;
}
/**
* Response body for find similar face operation.
*/
export interface SimilarFace {
/**
* FaceId of candidate face when find by faceIds. faceId is created by Face - Detect and will
* expire 24 hours after the detection call
*/
faceId?: string;
/**
* PersistedFaceId of candidate face when find by faceListId. persistedFaceId in face list is
* persisted and will not expire. As showed in below response
*/
persistedFaceId?: string;
/**
* Similarity confidence of the candidate face. The higher confidence, the more similar. Range
* between [0,1].
*/
confidence: number;
}
/**
* Request body for group request.
*/
export interface GroupRequest {
/**
* Array of candidate faceId created by Face - Detect. The maximum is 1000 faces
*/
faceIds: string[];
}
/**
* An array of face groups based on face similarity.
*/
export interface GroupResult {
/**
* A partition of the original faces based on face similarity. Groups are ranked by number of
* faces
*/
groups: string[][];
/**
* Face ids array of faces that cannot find any similar faces from original faces.
*/
messyGroup?: string[];
}
/**
* Request body for identify face operation.
*/
export interface IdentifyRequest {
/**
* Array of query faces faceIds, created by the Face - Detect. Each of the faces are identified
* independently. The valid number of faceIds is between [1, 10].
*/
faceIds: string[];
/**
* PersonGroupId of the target person group, created by PersonGroup - Create. Parameter
* personGroupId and largePersonGroupId should not be provided at the same time.
*/
personGroupId?: string;
/**
* LargePersonGroupId of the target large person group, created by LargePersonGroup - Create.
* Parameter personGroupId and largePersonGroupId should not be provided at the same time.
*/
largePersonGroupId?: string;
/**
* The range of maxNumOfCandidatesReturned is between 1 and 5 (default is 1).
*/
maxNumOfCandidatesReturned?: number;
/**
* Confidence threshold of identification, used to judge whether one face belong to one person.
* The range of confidenceThreshold is [0, 1] (default specified by algorithm).
*/
confidenceThreshold?: number;
}
/**
* All possible faces that may qualify.
*/
export interface IdentifyCandidate {
/**
* Id of candidate
*/
personId: string;
/**
* Confidence threshold of identification, used to judge whether one face belong to one person.
* The range of confidenceThreshold is [0, 1] (default specified by algorithm).
*/
confidence: number;
}
/**
* Response body for identify face operation.
*/
export interface IdentifyResult {
/**
* FaceId of the query face
*/
faceId: string;
/**
* Identified person candidates for that face (ranked by confidence). Array size should be no
* larger than input maxNumOfCandidatesReturned. If no person is identified, will return an empty
* array.
*/
candidates: IdentifyCandidate[];
}
/**
* Request body for face to person verification.
*/
export interface VerifyFaceToPersonRequest {
/**
* FaceId of the face, comes from Face - Detect
*/
faceId: string;
/**
* Using existing personGroupId and personId for fast loading a specified person. personGroupId
* is created in PersonGroup - Create. Parameter personGroupId and largePersonGroupId should not
* be provided at the same time.
*/
personGroupId?: string;
/**
* Using existing largePersonGroupId and personId for fast loading a specified person.
* largePersonGroupId is created in LargePersonGroup - Create. Parameter personGroupId and
* largePersonGroupId should not be provided at the same time.
*/
largePersonGroupId?: string;
/**
* Specify a certain person in a person group or a large person group. personId is created in
* PersonGroup Person - Create or LargePersonGroup Person - Create.
*/
personId: string;
}
/**
* Request body for face to face verification.
*/
export interface VerifyFaceToFaceRequest {
/**
* FaceId of the first face, comes from Face - Detect
*/
faceId1: string;
/**
* FaceId of the second face, comes from Face - Detect
*/
faceId2: string;
}
/**
* Result of the verify operation.
*/
export interface VerifyResult {
/**
* True if the two faces belong to the same person or the face belongs to the person, otherwise
* false.
*/
isIdentical: boolean;
/**
* A number indicates the similarity confidence of whether two faces belong to the same person,
* or whether the face belongs to the person. By default, isIdentical is set to True if
* similarity confidence is greater than or equal to 0.5. This is useful for advanced users to
* override "isIdentical" and fine-tune the result on their own data.
*/
confidence: number;
}
/**
* PersonFace object.
*/
export interface PersistedFace {
/**
* The persistedFaceId of the target face, which is persisted and will not expire. Different from
* faceId created by Face - Detect and will expire in 24 hours after the detection call.
*/
persistedFaceId: string;
/**
* User-provided data attached to the face. The size limit is 1KB.
*/
userData?: string;
}
/**
* A combination of user defined name and user specified data for the person,
* largePersonGroup/personGroup, and largeFaceList/faceList.
*/
export interface NameAndUserDataContract {
/**
* User defined name, maximum length is 128.
*/
name?: string;
/**
* User specified data. Length should not exceed 16KB.
*/
userData?: string;
}
/**
* A combination of user defined name and user specified data and recognition model name for
* largePersonGroup/personGroup, and largeFaceList/faceList.
*/
export interface MetaDataContract extends NameAndUserDataContract {
/**
* Possible values include: 'recognition_01', 'recognition_02'
*/
recognitionModel?: string;
}
/**
* Face list object.
*/
export interface FaceList extends MetaDataContract {
/**
* FaceListId of the target face list.
*/
faceListId: string;
/**
* Persisted faces within the face list.
*/
persistedFaces?: PersistedFace[];
}
/**
* Person group object.
*/
export interface PersonGroup extends MetaDataContract {
/**
* PersonGroupId of the target person group.
*/
personGroupId: string;
}
/**
* Person object.
*/
export interface Person extends NameAndUserDataContract {
/**
* PersonId of the target face list.
*/
personId: string;
/**
* PersistedFaceIds of registered faces in the person. These persistedFaceIds are returned from
* Person - Add a Person Face, and will not expire.
*/
persistedFaceIds?: string[];
}
/**
* Large face list object.
*/
export interface LargeFaceList extends MetaDataContract {
/**
* LargeFaceListId of the target large face list.
*/
largeFaceListId: string;
}
/**
* Large person group object.
*/
export interface LargePersonGroup extends MetaDataContract {
/**
* LargePersonGroupId of the target large person groups
*/
largePersonGroupId: string;
}
/**
* Request to update face data.
*/
export interface UpdateFaceRequest {
/**
* User-provided data attached to the face. The size limit is 1KB.
*/
userData?: string;
}
/**
* Training status object.
*/
export interface TrainingStatus {
/**
* Training status: notstarted, running, succeeded, failed. If the training process is waiting to
* perform, the status is notstarted. If the training is ongoing, the status is running. Status
* succeed means this person group or large person group is ready for Face - Identify, or this
* large face list is ready for Face - Find Similar. Status failed is often caused by no person
* or no persisted face exist in the person group or large person group, or no persisted face
* exist in the large face list. Possible values include: 'nonstarted', 'running', 'succeeded',
* 'failed'
*/
status: string;
/**
* A combined UTC date and time string that describes the created time of the person group, large
* person group or large face list.
*/
created: Date;
/**
* A combined UTC date and time string that describes the last modify time of the person group,
* large person group or large face list, could be null value when the group is not successfully
* trained.
*/
lastAction?: Date;
/**
* A combined UTC date and time string that describes the last successful training time of the
* person group, large person group or large face list.
*/
lastSuccessfulTraining?: Date;
/**
* Show failure message when training failed (omitted when training succeed).
*/
message?: string;
}
/**
* Request body for applying snapshot operation.
*/
export interface ApplySnapshotRequest {
/**
* User specified target object id to be created from the snapshot.
*/
objectId: string;
/**
* Snapshot applying mode. Currently only CreateNew is supported, which means the apply operation
* will fail if target subscription already contains an object of same type and using the same
* objectId. Users can specify the "objectId" in request body to avoid such conflicts. Possible
* values include: 'CreateNew'
*/
mode?: string;
}
/**
* Snapshot object.
*/
export interface Snapshot {
/**
* Snapshot id.
*/
id: string;
/**
* Azure Cognitive Service Face account id of the subscriber who created the snapshot by Snapshot
* - Take.
*/
account: string;
/**
* Type of the source object in the snapshot, specified by the subscriber who created the
* snapshot when calling Snapshot - Take. Currently FaceList, PersonGroup, LargeFaceList and
* LargePersonGroup are supported. Possible values include: 'FaceList', 'LargeFaceList',
* 'LargePersonGroup', 'PersonGroup'
*/
type: string;
/**
* Array of the target Face subscription ids for the snapshot, specified by the user who created
* the snapshot when calling Snapshot - Take. For each snapshot, only subscriptions included in
* the applyScope of Snapshot - Take can apply it.
*/
applyScope: string[];
/**
* User specified data about the snapshot for any purpose. Length should not exceed 16KB.
*/
userData?: string;
/**
* A combined UTC date and time string that describes the created time of the snapshot. E.g.
* 2018-12-25T11:41:02.2331413Z.
*/
createdTime: Date;
/**
* A combined UTC date and time string that describes the last time when the snapshot was created
* or updated by Snapshot - Update. E.g. 2018-12-25T11:51:27.8705696Z.
*/
lastUpdateTime: Date;
}
/**
* Request body for taking snapshot operation.
*/
export interface TakeSnapshotRequest {
/**
* User specified type for the source object to take snapshot from. Currently FaceList,
* PersonGroup, LargeFaceList and LargePersonGroup are supported. Possible values include:
* 'FaceList', 'LargeFaceList', 'LargePersonGroup', 'PersonGroup'
*/
type: string;
/**
* User specified source object id to take snapshot from.
*/
objectId: string;
/**
* User specified array of target Face subscription ids for the snapshot. For each snapshot, only
* subscriptions included in the applyScope of Snapshot - Take can apply it.
*/
applyScope: string[];
/**
* User specified data about the snapshot for any purpose. Length should not exceed 16KB.
*/
userData?: string;
}
/**
* Request body for updating a snapshot, with a combination of user defined apply scope and user
* specified data.
*/
export interface UpdateSnapshotRequest {
/**
* Array of the target Face subscription ids for the snapshot, specified by the user who created
* the snapshot when calling Snapshot - Take. For each snapshot, only subscriptions included in
* the applyScope of Snapshot - Take can apply it.
*/
applyScope?: string[];
/**
* User specified data about the snapshot for any purpose. Length should not exceed 16KB.
*/
userData?: string;
}
/**
* Operation status object. Operation refers to the asynchronous backend task including taking a
* snapshot and applying a snapshot.
*/
export interface OperationStatus {
/**
* Operation status: notstarted, running, succeeded, failed. If the operation is requested and
* waiting to perform, the status is notstarted. If the operation is ongoing in backend, the
* status is running. Status succeeded means the operation is completed successfully,
* specifically for snapshot taking operation, it illustrates the snapshot is well taken and
* ready to apply, and for snapshot applying operation, it presents the target object has
* finished creating by the snapshot and ready to be used. Status failed is often caused by
* editing the source object while taking the snapshot or editing the target object while
* applying the snapshot before completion, see the field "message" to check the failure reason.
* Possible values include: 'notstarted', 'running', 'succeeded', 'failed'
*/
status: string;
/**
* A combined UTC date and time string that describes the time when the operation (take or apply
* a snapshot) is requested. E.g. 2018-12-25T11:41:02.2331413Z.
*/
createdTime: Date;
/**
* A combined UTC date and time string that describes the last time the operation (take or apply
* a snapshot) is actively migrating data. The lastActionTime will keep increasing until the
* operation finishes. E.g. 2018-12-25T11:51:27.8705696Z.
*/
lastActionTime?: Date;
/**
* When the operation succeeds successfully, for snapshot taking operation the snapshot id will
* be included in this field, and for snapshot applying operation, the path to get the target
* object will be returned in this field.
*/
resourceLocation?: string;
/**
* Show failure message when operation fails (omitted when operation succeeds).
*/
message?: string;
}
export interface ImageUrl {
/**
* Publicly reachable URL of an image
*/
url: string;
} | the_stack |
import { AccountIsLockedException } from "../Exceptions/AccountIsLockedException";
import { ArgumentException } from "../Exceptions/ArgumentException";
import { DateTime, DateTimeKind } from "../DateTime";
import { Dictionary, DictionaryWithStringKey } from "../AltDictionary";
import { EwsLogging } from "./EwsLogging";
import { EwsServiceXmlWriter } from "./EwsServiceXmlWriter";
import { EwsTraceListener } from "../Misc/EwsTraceListener";
import { EwsUtilities } from "./EwsUtilities";
import { Exception } from "../Exceptions/Exception";
import { ExchangeCredentials } from "../Credentials/ExchangeCredentials";
import { ExchangeServerInfo } from "./ExchangeServerInfo";
import { ExchangeVersion } from "../Enumerations/ExchangeVersion";
import { HttpStatusCode } from "../../lib/HttpStatusCode";
import { IEwsHttpWebRequestFactory } from "../Interfaces/IEwsHttpWebRequestFactory";
import { ITraceListener } from "../Interfaces/ITraceListener";
import { IXHROptions, IXHRApi } from "../Interfaces";
import { ResponseHeadersCapturedHandler, CustomXmlSerializationDelegate } from "../Misc/DelegateTypes";
import { ServiceLocalException } from "../Exceptions/ServiceLocalException";
import { ServiceRequestUnauthorizedException } from "../Exceptions/ServiceRequestUnauthorizedException";
import { SoapFaultDetails } from "../Misc/SoapFaultDetails";
import { StringHelper, hasValue } from "../ExtensionMethods";
import { Strings } from "../Strings";
import { TimeZoneDefinition } from "../ComplexProperties/TimeZones/TimeZoneDefinition";
import { TimeZoneInfo } from "../TimeZoneInfo";
import { TraceFlags } from "../Enumerations/TraceFlags";
import { Uri } from "../Uri";
import { XHRFactory } from "../XHRFactory";
/**
* Represents an abstract binding to an Exchange Service.
*/
export abstract class ExchangeServiceBase {
//#region const members
// private static lockObj: any = new Object();
private readonly requestedServerVersion: ExchangeVersion = ExchangeVersion.Exchange2013_SP1;
/**
* @internal Special HTTP status code that indicates that the account is locked.
*/
static AccountIsLocked: HttpStatusCode = HttpStatusCode.Autodiscover_ContactAdmin;
/**
* The binary secret.
*/
private static binarySecret: number[] = null;
//#endregion
//#region static members
/**
* Default UserAgent
*/
private static defaultUserAgent: string = `ExchangeServicesClient/${EwsUtilities.BuildVersion}`;
//#endregion
//#region fields
OnResponseHeadersCaptured: ResponseHeadersCapturedHandler;
private credentials: ExchangeCredentials = null;
// private useDefaultCredentials: boolean = false;
private timeout: number = 100000;
private traceEnabled: boolean = false;
private sendClientLatencies: boolean = true;
private traceFlags: TraceFlags = TraceFlags.All;
private traceListener: ITraceListener = new EwsTraceListener();
private preAuthenticate: boolean = false;
private userAgent: string = ExchangeServiceBase.defaultUserAgent;
private acceptGzipEncoding: boolean = true;
private keepAlive: boolean = true;
private connectionGroupName: string = null;
private clientRequestId: string = null;
private returnClientRequestId: boolean = false;
// private cookieContainer: CookieContainer = new CookieContainer();
protected timeZone: TimeZoneInfo = TimeZoneInfo.Local;
private timeZoneDefinition: TimeZoneDefinition = null;
private serverInfo: ExchangeServerInfo = null;
// private webProxy: IWebProxy = null;
private httpHeaders: Dictionary<string, string> = new DictionaryWithStringKey<string>();
private httpResponseHeaders: Dictionary<string, string> = new DictionaryWithStringKey<string>();
// private ewsHttpWebRequestFactory: IEwsHttpWebRequestFactory = new EwsHttpWebRequestFactory();
private suppressXmlVersionHeader: boolean = false;
//#endregion
//#region event handlers
/**
* Provides an event that applications can implement to emit custom SOAP headers in requests that are sent to Exchange.
* @event
*/
OnSerializeCustomSoapHeaders: CustomXmlSerializationDelegate;
//#endregion
//#region Properties
// /**
// * Gets or sets the cookie container.
// */
// get CookieContainer(): CookieContainer {
// return this.cookieContainer;
// }
// set CookieContainer(value: CookieContainer) {
// this.cookieContainer = value;
// }
/**
* @internal Gets the time zone this service is scoped to.
*/
get TimeZone(): TimeZoneInfo {
return this.timeZone;
}
/**
* @internal Gets a time zone definition generated from the time zone info to which this service is scoped.
*/
get TimeZoneDefinition(): TimeZoneDefinition {
if (this.timeZoneDefinition === null) {
this.timeZoneDefinition = new TimeZoneDefinition(this.TimeZone);
}
return this.timeZoneDefinition;
}
/**
* Gets or sets a value indicating whether client latency info is push to server.
*/
get SendClientLatencies(): boolean {
return this.sendClientLatencies;
}
set SendClientLatencies(value: boolean) {
this.sendClientLatencies = value;
}
/**
* Gets or sets a value indicating whether tracing is enabled.
*/
get TraceEnabled(): boolean {
return this.traceEnabled;
}
set TraceEnabled(value: boolean) {
this.traceEnabled = value;
if (this.traceEnabled && this.traceListener === null) {
this.traceListener = new EwsTraceListener();
}
}
/**
* Gets or sets the trace flags.
*/
get TraceFlags(): TraceFlags {
return this.traceFlags;
}
set TraceFlags(value: TraceFlags) {
this.traceFlags = value;
}
/**
* Gets or sets the trace listener.
*/
get TraceListener(): ITraceListener {
return this.traceListener;
}
set TraceListener(value: ITraceListener) {
this.traceListener = value;
this.traceEnabled = (value !== null);
}
/**
* Gets or sets the credentials used to authenticate with the Exchange Web Services. Setting the Credentials property automatically sets the UseDefaultCredentials to false.
*/
get Credentials(): ExchangeCredentials {
return this.credentials;
}
set Credentials(value: ExchangeCredentials) {
this.credentials = value;
// this.useDefaultCredentials = false;
// this.cookieContainer = new CookieContainer();
}
// /** // REF: No default credential in NodeJs
// * Gets or sets a value indicating whether the credentials of the user currently logged into Windows should be used to authenticate with the Exchange Web Services. Setting UseDefaultCredentials to true automatically sets the Credentials property to null.
// */
// get UseDefaultCredentials(): boolean {
// return this.useDefaultCredentials;
// }
// set UseDefaultCredentials(value: boolean) {
// this.useDefaultCredentials = value;
// if (value) {
// this.credentials = null;
// // this.cookieContainer = new CookieContainer();
// }
// }
/**
* Gets or sets the timeout used when sending HTTP requests and when receiving HTTP responses, in milliseconds. Defaults to 100000.
*/
get Timeout(): number {
return this.timeout;
}
set Timeout(value: number) {
if (value < 1) {
throw new ArgumentException(Strings.TimeoutMustBeGreaterThanZero);
}
this.timeout = value;
}
/**
* Gets or sets a value that indicates whether HTTP pre-authentication should be performed.
*/
get PreAuthenticate(): boolean {
return this.preAuthenticate;
}
set PreAuthenticate(value: boolean) {
this.preAuthenticate = value;
}
/**
* Gets or sets a value indicating whether GZip compression encoding should be accepted.
* @remarks This value will tell the server that the client is able to handle GZip compression encoding. The server will only send Gzip compressed content if it has been configured to do so.
* @remarks {ewsjs} not used in ewsjs
*/
get AcceptGzipEncoding(): boolean {
return this.acceptGzipEncoding;
}
set AcceptGzipEncoding(value: boolean) {
this.acceptGzipEncoding = value;
}
/**
* Gets the requested server version.
*/
get RequestedServerVersion(): ExchangeVersion {
return this.requestedServerVersion;
}
/**
* Gets or sets the user agent.
*/
get UserAgent(): string {
return this.userAgent;
}
set UserAgent(value: string) {
this.userAgent = `${value} (${ExchangeServiceBase.defaultUserAgent})`;
}
/**
* Gets information associated with the server that processed the last request. Will be null if no requests have been processed.
*/
get ServerInfo(): ExchangeServerInfo {
return this.serverInfo;
}
/** @internal set */
set ServerInfo(value: ExchangeServerInfo) {
this.serverInfo = value;
}
// /**
// * Gets or sets the web proxy that should be used when sending requests to EWS. Set this property to null to use the default web proxy.
// */
// get WebProxy(): IWebProxy {
// return this.webProxy;
// }
// set WebProxy(value: IWebProxy) {
// this.webProxy = value;
// }
/**
* Gets or sets if the request to the internet resource should contain a Connection HTTP header with the value Keep-alive
*/
get KeepAlive(): boolean {
return this.keepAlive;
}
set KeepAlive(value: boolean) {
this.keepAlive = value;
}
/**
* Gets or sets the name of the connection group for the request.
*/
get ConnectionGroupName(): string {
return this.connectionGroupName;
}
set ConnectionGroupName(value: string) {
this.connectionGroupName = value;
}
/**
* Gets or sets the request id for the request.
*/
get ClientRequestId(): string {
return this.clientRequestId;
}
set ClientRequestId(value: string) {
this.clientRequestId = value;
}
/**
* Gets or sets a flag to indicate whether the client requires the server side to return the request id.
*/
get ReturnClientRequestId(): boolean {
return this.returnClientRequestId;
}
set ReturnClientRequestId(value: boolean) {
this.returnClientRequestId = value;
}
/**
* Gets a collection of HTTP headers that will be sent with each request to EWS.
*/
get HttpHeaders(): Dictionary<string, string> {
return this.httpHeaders;
}
/**
* Gets a collection of HTTP headers from the last response.
*/
get HttpResponseHeaders(): Dictionary<string, string> {
return this.httpResponseHeaders;
}
/**
* @internal Gets the session key.
*/
static get SessionKey(): number[] {
// TODO: fix when implement Partner tokens
// // this has to be computed only once.
// lock(ExchangeServiceBase.lockObj)
// {
// if (ExchangeServiceBase.binarySecret === null) {
// RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create();
// ExchangeServiceBase.binarySecret = new byte[256 / 8];
// randomNumberGenerator.GetNonZeroBytes(binarySecret);
// }
// return ExchangeServiceBase.binarySecret;
// }
return null;
}
// /**
// * Gets or sets the HTTP web request factory.
// */
// get HttpWebRequestFactory(): IEwsHttpWebRequestFactory {
// return this.ewsHttpWebRequestFactory;
// }
// set HttpWebRequestFactory(value: IEwsHttpWebRequestFactory) {
// this.ewsHttpWebRequestFactory = ((value === null) ? new EwsHttpWebRequestFactory() : value);
// }
/**
* @internal For testing: suppresses generation of the SOAP version header.
*/
get SuppressXmlVersionHeader(): boolean {
return this.suppressXmlVersionHeader;
}
set SuppressXmlVersionHeader(value: boolean) {
this.suppressXmlVersionHeader = value;
}
//#endregion
//#region EWS JavaScript code
private xhrApi: IXHRApi = null;
get XHRApi(): IXHRApi {
return this.xhrApi || XHRFactory.XHRApi;
}
set XHRApi(xhrApi: IXHRApi) {
this.xhrApi = xhrApi || XHRFactory.XHRApi;
}
//#endregion
//#region Constructor
/**
* Initializes a new instance of the **ExchangeServiceBase** class.
*
*/
constructor();
/**
* Initializes a new instance of the **ExchangeServiceBase** class.
*
* @param {TimeZoneInfo} timeZone The time zone to which the service is scoped.
*/
constructor(timeZone: TimeZoneInfo);
/**
* Initializes a new instance of the **ExchangeServiceBase** class.
*
* @param {ExchangeVersion} requestedServerVersion The requested server version.
*/
constructor(requestedServerVersion: ExchangeVersion);
/**
* Initializes a new instance of the **ExchangeServiceBase** class.
*
* @param {ExchangeVersion} requestedServerVersion The requested server version.
* @param {TimeZoneInfo} timeZone The time zone to which the service is scoped.
*/
constructor(requestedServerVersion: ExchangeVersion, timeZone: TimeZoneInfo);
/**
* @internal Initializes a new instance of the **ExchangeServiceBase** class.
*
* @param {ExchangeServiceBase} service The other service.
*/
constructor(service: ExchangeServiceBase);
/**
* @internal Initializes a new instance of the **ExchangeServiceBase** class.
*
* @param {ExchangeServiceBase} service The other service.
* @param {ExchangeVersion} requestedServerVersion The requested server version.
*/
constructor(service: ExchangeServiceBase, requestedServerVersion: ExchangeVersion);
constructor(
versionServiceorTZ?: ExchangeVersion | ExchangeServiceBase | TimeZoneInfo,
versionOrTZ?: ExchangeVersion | TimeZoneInfo
) {
var argsLength = arguments.length;
if (argsLength > 2) {
throw new Error("ExchangeServiceBase.ts - ctor with " + argsLength + " parameters, invalid number of arguments, check documentation and try again.");
}
var timeZone: TimeZoneInfo = null;
var requestedServerVersion: ExchangeVersion = ExchangeVersion.Exchange2013_SP1;
var service: ExchangeServiceBase = null;
if (argsLength >= 1) {
if (versionServiceorTZ instanceof TimeZoneInfo) {
timeZone = versionServiceorTZ;
}
else if (versionServiceorTZ instanceof ExchangeServiceBase) {
service = versionServiceorTZ;
}
else if (typeof versionServiceorTZ === 'number') {
requestedServerVersion = versionServiceorTZ;
}
}
if (argsLength === 2) {
if (versionOrTZ instanceof TimeZoneInfo) {
if (typeof versionServiceorTZ !== 'number') {
throw new Error("ExchangeServiceBase.ts - ctor with " + argsLength + " parameters - incorrect uses of parameter at 1st position, it must be ExchangeVersion when using TimeZoneInfo at 2nd place");
}
timeZone = versionOrTZ;
}
else if (typeof versionOrTZ === 'number') {
if (!(versionServiceorTZ instanceof ExchangeServiceBase)) {
throw new Error("ExchangeServiceBase.ts - ctor with " + argsLength + " parameters - incorrect uses of parameter at 1st position, it must be ExchangeServiceBase when using ExchangeVersion at 2nd place");
}
requestedServerVersion = versionOrTZ;
}
}
this.requestedServerVersion = requestedServerVersion;
if (hasValue(timeZone)) {
this.timeZone = timeZone;
//this.useDefaultCredentials = true; //ref: no default credential in node.js
}
if (hasValue(service)) {
// this.useDefaultCredentials = service.useDefaultCredentials;
this.credentials = service.credentials;
this.Credentials = service.Credentials;
this.traceEnabled = service.traceEnabled;
this.traceListener = service.traceListener;
this.traceFlags = service.traceFlags;
this.timeout = service.timeout;
this.preAuthenticate = service.preAuthenticate;
this.userAgent = service.userAgent;
//this.acceptGzipEncoding = service.acceptGzipEncoding;
this.keepAlive = service.keepAlive;
this.connectionGroupName = service.connectionGroupName;
this.timeZone = service.timeZone;
this.httpHeaders = service.httpHeaders;
// this.ewsHttpWebRequestFactory = service.ewsHttpWebRequestFactory;
this.xhrApi = service.xhrApi;
}
}
//#endregion
/**
* @internal Converts the date time to universal date time string.
*
* @param {DateTime} value The value.
* @return {string} String representation of DateTime.
*/
ConvertDateTimeToUniversalDateTimeString(value: DateTime): string {
var dateTime: DateTime;
switch (value.Kind) {
case DateTimeKind.Unspecified:
dateTime = EwsUtilities.ConvertTime(
value,
this.TimeZone,
TimeZoneInfo.Utc);
break;
case DateTimeKind.Local:
dateTime = EwsUtilities.ConvertTime(
value,
TimeZoneInfo.Local,
TimeZoneInfo.Utc);
break;
default:
// The date is already in UTC, no need to convert it.
dateTime = value;
break;
}
//debug://todo:iso string should work
return dateTime.ToISOString();// ISO string should work .ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture);
}
/**
* @internal Converts xs:dateTime string with either "Z", "-00:00" bias, or "" suffixes to unspecified StartDate value ignoring the suffix.
*
* @param {string} value The string value to parse.
* @return {DateTime} The parsed DateTime value.
*/
ConvertStartDateToUnspecifiedDateTime(value: string): DateTime {
//EwsLogging.Log("ExchangeServiceBase.ConvConvertStartDateToUnspecifiedDateTime : DateTimeOffset not implemented, check date values")
value = value.substring(0, 10); //info: //ref: for DateTimeOffset substitution, this is being called only from recurring datetime StartDate and
if (StringHelper.IsNullOrEmpty(value)) {
return null;
}
else {
return DateTime.Parse(value);
//let dateTimeOffset:DateTimeOffset = DateTimeOffset.Parse(value, CultureInfo.InvariantCulture);
// Return only the date part with the kind==Unspecified.
//return dateTimeOffset.Date;
}
}
/**
* @internal Converts the universal date time string to local date time.
*
* @param {string} value The value.
* @return {DateTime} DateTime
*/
ConvertUniversalDateTimeStringToLocalDateTime(value: string): DateTime {
if (StringHelper.IsNullOrEmpty(value)) {
return null;
}
else {
// Assume an unbiased date/time is in UTC. Convert to UTC otherwise.
//ref: //fix: hard convert to UTC date as no request contains TZ information.
if (value.toLowerCase().indexOf("z") < 0 && ["+", "-"].indexOf(value.substr(19, 1)) < 0) {
value += "Z";
}
var dateTime: DateTime = DateTime.Parse(
value);
// CultureInfo.InvariantCulture,
// DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
if (this.TimeZone === TimeZoneInfo.Utc) {
// This returns a DateTime with Kind.Utc
return dateTime;
}
else {
var localTime: DateTime = EwsUtilities.ConvertTime(
dateTime,
TimeZoneInfo.Utc,
this.TimeZone);
if (EwsUtilities.IsLocalTimeZone(this.TimeZone)) {
// This returns a DateTime with Kind.Local
return new DateTime(localTime.TotalMilliSeconds, DateTimeKind.Local);
}
else {
// This returns a DateTime with Kind.Unspecified
return localTime;
}
}
}
}
/**
* @internal Calls the custom SOAP header serialization event handlers, if defined.
*
* @param {EwsServiceXmlWriter} writer The XmlWriter to which to write the custom SOAP headers.
*/
DoOnSerializeCustomSoapHeaders(writer: EwsServiceXmlWriter): void {
EwsLogging.Assert(
writer != null,
"ExchangeServiceBase.DoOnSerializeCustomSoapHeaders",
"writer is null");
if (this.OnSerializeCustomSoapHeaders != null) {
this.OnSerializeCustomSoapHeaders(writer);
}
}
/**
* @internal Processes an HTTP error response
*
* /remarks/ This method doesn't handle 500 ISE errors. This is handled by the caller since 500 ISE typically indicates that a SOAP fault has occurred and the handling of a SOAP fault is currently service specific.
* @param {XMLHttpRequest} httpWebResponse The HTTP web response.
* @param {SoapFaultDetails} webException The web exception.
* @param {TraceFlags} responseHeadersTraceFlag The trace flag for response headers.
* @param {TraceFlags} responseTraceFlag The trace flag for responses.
*
*/
InternalProcessHttpErrorResponse(httpWebResponse: XMLHttpRequest, soapFault: SoapFaultDetails, responseHeadersTraceFlag: TraceFlags, responseTraceFlag: TraceFlags): void {
EwsLogging.Assert(
httpWebResponse.status != 500, // HttpStatusCode.InternalServerError,
"ExchangeServiceBase.InternalProcessHttpErrorResponse",
"InternalProcessHttpErrorResponse does not handle 500 ISE errors, the caller is supposed to handle this.");
this.ProcessHttpResponseHeaders(responseHeadersTraceFlag, httpWebResponse);
let exception: Exception = null;
// Deal with new HTTP error code indicating that account is locked.
// The "unlock" URL is returned as the status description in the response.
if (httpWebResponse.status === ExchangeServiceBase.AccountIsLocked) {
EwsLogging.Assert(false, "ExchangeServiceBase.InternalProcessHttpErrorResponse", "Please report back to ews-javascript-api with example or response XML for future improvements of this code.");
let location: string = httpWebResponse.getResponseHeader("StatusDescription");
let accountUnlockUrl: Uri = null;
//if (Uri.IsWellFormedUriString(location, UriKind.Absolute)) {
if (Uri.ParseString(location).authority) { //todo: implement better Url parsing in Uri.
accountUnlockUrl = new Uri(location);
}
this.TraceMessage(responseTraceFlag, StringHelper.Format("Account is locked. Unlock URL is {0}", accountUnlockUrl.ToString()));
exception = new AccountIsLockedException(
StringHelper.Format(Strings.AccountIsLocked, accountUnlockUrl),
accountUnlockUrl,
null);
}
else if (httpWebResponse.status === 401 /*Unauthorized*/) {
exception = new ServiceRequestUnauthorizedException("401 Unauthorized");
}
if (exception) {
if (soapFault !== null) {
soapFault.Exception = exception;
if (StringHelper.IsNullOrEmpty(soapFault.message) && !StringHelper.IsNullOrEmpty(exception.message)) {
soapFault.message = exception.message;
}
}
else {
throw exception;
}
}
}
/**
* @internal Determines whether tracing is enabled for specified trace flag(s).
*
* @param {TraceFlags} traceFlags The trace flags.
* @return {boolean} True if tracing is enabled for specified trace flag(s).
*/
IsTraceEnabledFor(traceFlags: TraceFlags): boolean {
return this.TraceEnabled && ((this.TraceFlags & traceFlags) != 0);
}
/**
* @internal Creates an HttpWebRequest instance and initializes it with the appropriate parameters, based on the configuration of this service object.
*
* @param {Uri} url The URL that the HttpWebRequest should target.
* @param {boolean} acceptGzipEncoding If true, ask server for GZip compressed content.
* @param {boolean} allowAutoRedirect If true, redirection responses will be automatically followed.
* @return {IXHROptions} A initialized instance of IXHROptions.
*/
PrepareHttpWebRequestForUrl(url: Uri, acceptGzipEncoding: boolean, allowAutoRedirect: boolean): IXHROptions /*IEwsHttpWebRequest*/ {
// Verify that the protocol is something that we can handle
if ((url.Scheme != Uri.UriSchemeHttp) && (url.Scheme != Uri.UriSchemeHttps)) {
throw new ServiceLocalException("unsupported web protocol" + url);//string.Format(Strings.UnsupportedWebProtocol, url.Scheme));
}
var request: IXHROptions = { url: url.ToString() };
request.headers = {};
//request.PreAuthenticate = this.PreAuthenticate;
//request.Timeout = this.Timeout; //todo: implement this within IPromise
this.SetContentType(request);
request.type = "POST";
//request.headers["User-Agent"] = this.UserAgent || ExchangeServiceBase.defaultUserAgent; //todo:fix -> Noje.js is refusing to set this unsafe header -//
//request.AllowAutoRedirect = allowAutoRedirect;
//todo: figure out next 3 lines
//request.CookieContainer = this.CookieContainer;
//request.KeepAlive = this.keepAlive;
//request.ConnectionGroupName = this.connectionGroupName;
if (acceptGzipEncoding) {
request.headers["Accept-Encoding"] = "gzip,deflate";
}
if (!StringHelper.IsNullOrEmpty(this.clientRequestId)) {
request.headers["client-request-id"] = this.clientRequestId;
if (this.returnClientRequestId) {
request.headers["return-client-request-id"] = "true";
}
}
//if (this.webProxy != null) {
// request.Proxy = this.webProxy;
//}
if (this.HttpHeaders) {
for (var key of this.HttpHeaders.Keys) {
request.headers[key] = this.HttpHeaders.get(key);
}
}
// REF: no default credential in NodeJs
// request.UseDefaultCredentials = this.UseDefaultCredentials;
// if (!this.UseDefaultCredentials) {
var serviceCredentials = this.Credentials;
if (serviceCredentials === null) {
throw new ServiceLocalException(Strings.CredentialsRequired);
}
// Make sure that credentials have been authenticated if required
//serviceCredentials.PreAuthenticate(); //todo: fix preauthenticate if possible
// Apply credentials to the request
serviceCredentials.PrepareWebRequest(request);
// }
// else
// debugger;
this.httpResponseHeaders.clear();
return request;
}
/**
* @internal Processes an HTTP error response.
*
* @param {XMLHttpRequest} httpWebResponse The HTTP web response.
* @param {Exception} webException The web exception.
*/
abstract ProcessHttpErrorResponse(httpWebResponse: XMLHttpRequest/*IEwsHttpWebResponse*/, webException: Exception): void;
/**
* @internal Traces the HTTP response headers.
*
* @param {TraceFlags} traceType Kind of trace entry.
* @param {XMLHttpRequest} response The response.
*/
ProcessHttpResponseHeaders(traceType: TraceFlags, response: XMLHttpRequest): void {
//TODO: implement tracing properly
this.TraceHttpResponseHeaders(traceType, response);
this.SaveHttpResponseHeaders(response);
}
/**
* Save the HTTP response headers.
*
* @param {Object} response The response headers
*/
private SaveHttpResponseHeaders(response: any/* System.Net.WebHeaderCollection*/): any {
//debug:
this.httpResponseHeaders.clear();
for (var key in response.headers || {}) {
this.httpResponseHeaders.Add(key, response.headers[key]);
}
if (this.OnResponseHeadersCaptured != null) {
this.OnResponseHeadersCaptured(this.httpResponseHeaders);
}
}
/**
* @internal
* @virtual
*/
SetContentType(request: IXHROptions /*IEwsHttpWebRequest*/): void {
request.headers["Content-Type"] = "text/xml; charset=utf-8";
request.headers["Accept"] = "text/xml";
}
/**
* @internal Sets the user agent to a custom value
*
* @param {string} userAgent User agent string to set on the service
*/
SetCustomUserAgent(userAgent: string): void {
this.userAgent = userAgent;
}
/**
* @internal Traces the HTTP request headers.
*
* @param {TraceFlags} traceType Kind of trace entry.
* @param {IXHROptions} request The request.
*/
TraceHttpRequestHeaders(traceType: TraceFlags, request: IXHROptions): void {
if (this.IsTraceEnabledFor(traceType)) {
const traceTypeStr: string = TraceFlags[traceType];
const headersAsString: string = EwsUtilities.FormatHttpRequestHeaders(request.headers);
const logMessage: string = EwsUtilities.FormatLogMessage(traceTypeStr, headersAsString);
this.TraceListener.Trace(traceTypeStr, logMessage);
}
}
/**
* Traces the HTTP response headers.
*
* @param {TraceFlags} traceType Kind of trace entry.
* @param {XMLHttpRequest} response The response.
*/
private TraceHttpResponseHeaders(traceType: TraceFlags, response: XMLHttpRequest): void {
if (this.IsTraceEnabledFor(traceType)) {
const traceTypeStr: string = TraceFlags[traceType];
const headersAsString: string = EwsUtilities.FormatHttpResponseHeaders(response);
const logMessage: string = EwsUtilities.FormatLogMessage(traceTypeStr, headersAsString);
this.TraceListener.Trace(traceTypeStr, logMessage);
}
}
/**
* @internal Logs the specified string to the TraceListener if tracing is enabled.
*
* @param {TraceFlags} traceType Kind of trace entry.
* @param {string} logEntry The entry to log.
*/
TraceMessage(traceType: TraceFlags, logEntry: string): void { EwsLogging.Log(logEntry); /*throw new Error("Not implemented."); */ }
/**
* @internal Logs the specified XML to the TraceListener if tracing is enabled.
*
* @param {TraceFlags} traceType Kind of trace entry.
* @param {XMLHttpRequest} stream The XMLHttpRequest containing XML.
*/
TraceXml(traceType: TraceFlags, stream: XMLHttpRequest): void {
if (this.IsTraceEnabledFor(traceType)) {
const traceTypeStr: string = TraceFlags[traceType];
const logMessage: string = EwsUtilities.FormatLogMessageWithXmlContent(traceTypeStr, stream);
this.TraceListener.Trace(traceTypeStr, logMessage);
}
}
/**
* @internal Validates this instance.
* @virtual
*/
Validate(): void { }
} | the_stack |
import type { AgentMessage } from '../../../agent/AgentMessage'
import type { InboundMessageContext } from '../../../agent/models/InboundMessageContext'
import type { Logger } from '../../../logger'
import type { ConnectionRecord } from '../../connections'
import type { AutoAcceptProof } from '../ProofAutoAcceptType'
import type { ProofStateChangedEvent } from '../ProofEvents'
import type { PresentationPreview, PresentationPreviewAttribute } from '../messages'
import type { PresentationProblemReportMessage } from './../messages/PresentationProblemReportMessage'
import type { CredDef, IndyProof, Schema } from 'indy-sdk'
import { validateOrReject } from 'class-validator'
import { inject, Lifecycle, scoped } from 'tsyringe'
import { AgentConfig } from '../../../agent/AgentConfig'
import { EventEmitter } from '../../../agent/EventEmitter'
import { InjectionSymbols } from '../../../constants'
import { Attachment, AttachmentData } from '../../../decorators/attachment/Attachment'
import { AriesFrameworkError } from '../../../error'
import { JsonEncoder } from '../../../utils/JsonEncoder'
import { JsonTransformer } from '../../../utils/JsonTransformer'
import { uuid } from '../../../utils/uuid'
import { Wallet } from '../../../wallet/Wallet'
import { AckStatus } from '../../common'
import { ConnectionService } from '../../connections'
import { CredentialUtils, Credential, CredentialRepository } from '../../credentials'
import { IndyHolderService, IndyVerifierService } from '../../indy'
import { IndyLedgerService } from '../../ledger/services/IndyLedgerService'
import { ProofEventTypes } from '../ProofEvents'
import { ProofState } from '../ProofState'
import { PresentationProblemReportError, PresentationProblemReportReason } from '../errors'
import {
INDY_PROOF_ATTACHMENT_ID,
INDY_PROOF_REQUEST_ATTACHMENT_ID,
PresentationAckMessage,
PresentationMessage,
ProposePresentationMessage,
RequestPresentationMessage,
} from '../messages'
import {
AttributeFilter,
PartialProof,
ProofAttributeInfo,
ProofPredicateInfo,
ProofRequest,
RequestedAttribute,
RequestedCredentials,
RequestedPredicate,
RetrievedCredentials,
} from '../models'
import { ProofRepository } from '../repository'
import { ProofRecord } from '../repository/ProofRecord'
/**
* @todo add method to check if request matches proposal. Useful to see if a request I received is the same as the proposal I sent.
* @todo add method to reject / revoke messages
* @todo validate attachments / messages
*/
@scoped(Lifecycle.ContainerScoped)
export class ProofService {
private proofRepository: ProofRepository
private credentialRepository: CredentialRepository
private ledgerService: IndyLedgerService
private wallet: Wallet
private logger: Logger
private indyHolderService: IndyHolderService
private indyVerifierService: IndyVerifierService
private connectionService: ConnectionService
private eventEmitter: EventEmitter
public constructor(
proofRepository: ProofRepository,
ledgerService: IndyLedgerService,
@inject(InjectionSymbols.Wallet) wallet: Wallet,
agentConfig: AgentConfig,
indyHolderService: IndyHolderService,
indyVerifierService: IndyVerifierService,
connectionService: ConnectionService,
eventEmitter: EventEmitter,
credentialRepository: CredentialRepository
) {
this.proofRepository = proofRepository
this.credentialRepository = credentialRepository
this.ledgerService = ledgerService
this.wallet = wallet
this.logger = agentConfig.logger
this.indyHolderService = indyHolderService
this.indyVerifierService = indyVerifierService
this.connectionService = connectionService
this.eventEmitter = eventEmitter
}
/**
* Create a {@link ProposePresentationMessage} not bound to an existing presentation exchange.
* To create a proposal as response to an existing presentation exchange, use {@link ProofService.createProposalAsResponse}.
*
* @param connectionRecord The connection for which to create the presentation proposal
* @param presentationProposal The presentation proposal to include in the message
* @param config Additional configuration to use for the proposal
* @returns Object containing proposal message and associated proof record
*
*/
public async createProposal(
connectionRecord: ConnectionRecord,
presentationProposal: PresentationPreview,
config?: {
comment?: string
autoAcceptProof?: AutoAcceptProof
}
): Promise<ProofProtocolMsgReturnType<ProposePresentationMessage>> {
// Assert
connectionRecord.assertReady()
// Create message
const proposalMessage = new ProposePresentationMessage({
comment: config?.comment,
presentationProposal,
})
// Create record
const proofRecord = new ProofRecord({
connectionId: connectionRecord.id,
threadId: proposalMessage.threadId,
state: ProofState.ProposalSent,
proposalMessage,
autoAcceptProof: config?.autoAcceptProof,
})
await this.proofRepository.save(proofRecord)
this.eventEmitter.emit<ProofStateChangedEvent>({
type: ProofEventTypes.ProofStateChanged,
payload: { proofRecord, previousState: null },
})
return { message: proposalMessage, proofRecord }
}
/**
* Create a {@link ProposePresentationMessage} as response to a received presentation request.
* To create a proposal not bound to an existing presentation exchange, use {@link ProofService.createProposal}.
*
* @param proofRecord The proof record for which to create the presentation proposal
* @param presentationProposal The presentation proposal to include in the message
* @param config Additional configuration to use for the proposal
* @returns Object containing proposal message and associated proof record
*
*/
public async createProposalAsResponse(
proofRecord: ProofRecord,
presentationProposal: PresentationPreview,
config?: {
comment?: string
}
): Promise<ProofProtocolMsgReturnType<ProposePresentationMessage>> {
// Assert
proofRecord.assertState(ProofState.RequestReceived)
// Create message
const proposalMessage = new ProposePresentationMessage({
comment: config?.comment,
presentationProposal,
})
proposalMessage.setThread({ threadId: proofRecord.threadId })
// Update record
proofRecord.proposalMessage = proposalMessage
this.updateState(proofRecord, ProofState.ProposalSent)
return { message: proposalMessage, proofRecord }
}
/**
* Decline a proof request
* @param proofRecord The proof request to be declined
*/
public async declineRequest(proofRecord: ProofRecord): Promise<ProofRecord> {
proofRecord.assertState(ProofState.RequestReceived)
await this.updateState(proofRecord, ProofState.Declined)
return proofRecord
}
/**
* Process a received {@link ProposePresentationMessage}. This will not accept the presentation proposal
* or send a presentation request. It will only create a new, or update the existing proof record with
* the information from the presentation proposal message. Use {@link ProofService.createRequestAsResponse}
* after calling this method to create a presentation request.
*
* @param messageContext The message context containing a presentation proposal message
* @returns proof record associated with the presentation proposal message
*
*/
public async processProposal(
messageContext: InboundMessageContext<ProposePresentationMessage>
): Promise<ProofRecord> {
let proofRecord: ProofRecord
const { message: proposalMessage, connection } = messageContext
this.logger.debug(`Processing presentation proposal with id ${proposalMessage.id}`)
try {
// Proof record already exists
proofRecord = await this.getByThreadAndConnectionId(proposalMessage.threadId, connection?.id)
// Assert
proofRecord.assertState(ProofState.RequestSent)
this.connectionService.assertConnectionOrServiceDecorator(messageContext, {
previousReceivedMessage: proofRecord.proposalMessage,
previousSentMessage: proofRecord.requestMessage,
})
// Update record
proofRecord.proposalMessage = proposalMessage
await this.updateState(proofRecord, ProofState.ProposalReceived)
} catch {
// No proof record exists with thread id
proofRecord = new ProofRecord({
connectionId: connection?.id,
threadId: proposalMessage.threadId,
proposalMessage,
state: ProofState.ProposalReceived,
})
// Assert
this.connectionService.assertConnectionOrServiceDecorator(messageContext)
// Save record
await this.proofRepository.save(proofRecord)
this.eventEmitter.emit<ProofStateChangedEvent>({
type: ProofEventTypes.ProofStateChanged,
payload: {
proofRecord,
previousState: null,
},
})
}
return proofRecord
}
/**
* Create a {@link RequestPresentationMessage} as response to a received presentation proposal.
* To create a request not bound to an existing presentation exchange, use {@link ProofService.createRequest}.
*
* @param proofRecord The proof record for which to create the presentation request
* @param proofRequest The proof request to include in the message
* @param config Additional configuration to use for the request
* @returns Object containing request message and associated proof record
*
*/
public async createRequestAsResponse(
proofRecord: ProofRecord,
proofRequest: ProofRequest,
config?: {
comment?: string
}
): Promise<ProofProtocolMsgReturnType<RequestPresentationMessage>> {
// Assert
proofRecord.assertState(ProofState.ProposalReceived)
// Create message
const attachment = new Attachment({
id: INDY_PROOF_REQUEST_ATTACHMENT_ID,
mimeType: 'application/json',
data: new AttachmentData({
base64: JsonEncoder.toBase64(proofRequest),
}),
})
const requestPresentationMessage = new RequestPresentationMessage({
comment: config?.comment,
requestPresentationAttachments: [attachment],
})
requestPresentationMessage.setThread({
threadId: proofRecord.threadId,
})
// Update record
proofRecord.requestMessage = requestPresentationMessage
await this.updateState(proofRecord, ProofState.RequestSent)
return { message: requestPresentationMessage, proofRecord }
}
/**
* Create a {@link RequestPresentationMessage} not bound to an existing presentation exchange.
* To create a request as response to an existing presentation exchange, use {@link ProofService#createRequestAsResponse}.
*
* @param proofRequestTemplate The proof request template
* @param connectionRecord The connection for which to create the presentation request
* @returns Object containing request message and associated proof record
*
*/
public async createRequest(
proofRequest: ProofRequest,
connectionRecord?: ConnectionRecord,
config?: {
comment?: string
autoAcceptProof?: AutoAcceptProof
}
): Promise<ProofProtocolMsgReturnType<RequestPresentationMessage>> {
this.logger.debug(`Creating proof request`)
// Assert
connectionRecord?.assertReady()
// Create message
const attachment = new Attachment({
id: INDY_PROOF_REQUEST_ATTACHMENT_ID,
mimeType: 'application/json',
data: new AttachmentData({
base64: JsonEncoder.toBase64(proofRequest),
}),
})
const requestPresentationMessage = new RequestPresentationMessage({
comment: config?.comment,
requestPresentationAttachments: [attachment],
})
// Create record
const proofRecord = new ProofRecord({
connectionId: connectionRecord?.id,
threadId: requestPresentationMessage.threadId,
requestMessage: requestPresentationMessage,
state: ProofState.RequestSent,
autoAcceptProof: config?.autoAcceptProof,
})
await this.proofRepository.save(proofRecord)
this.eventEmitter.emit<ProofStateChangedEvent>({
type: ProofEventTypes.ProofStateChanged,
payload: { proofRecord, previousState: null },
})
return { message: requestPresentationMessage, proofRecord }
}
/**
* Process a received {@link RequestPresentationMessage}. This will not accept the presentation request
* or send a presentation. It will only create a new, or update the existing proof record with
* the information from the presentation request message. Use {@link ProofService.createPresentation}
* after calling this method to create a presentation.
*
* @param messageContext The message context containing a presentation request message
* @returns proof record associated with the presentation request message
*
*/
public async processRequest(messageContext: InboundMessageContext<RequestPresentationMessage>): Promise<ProofRecord> {
let proofRecord: ProofRecord
const { message: proofRequestMessage, connection } = messageContext
this.logger.debug(`Processing presentation request with id ${proofRequestMessage.id}`)
const proofRequest = proofRequestMessage.indyProofRequest
// Assert attachment
if (!proofRequest) {
throw new PresentationProblemReportError(
`Missing required base64 or json encoded attachment data for presentation request with thread id ${proofRequestMessage.threadId}`,
{ problemCode: PresentationProblemReportReason.Abandoned }
)
}
await validateOrReject(proofRequest)
this.logger.debug('received proof request', proofRequest)
try {
// Proof record already exists
proofRecord = await this.getByThreadAndConnectionId(proofRequestMessage.threadId, connection?.id)
// Assert
proofRecord.assertState(ProofState.ProposalSent)
this.connectionService.assertConnectionOrServiceDecorator(messageContext, {
previousReceivedMessage: proofRecord.requestMessage,
previousSentMessage: proofRecord.proposalMessage,
})
// Update record
proofRecord.requestMessage = proofRequestMessage
await this.updateState(proofRecord, ProofState.RequestReceived)
} catch {
// No proof record exists with thread id
proofRecord = new ProofRecord({
connectionId: connection?.id,
threadId: proofRequestMessage.threadId,
requestMessage: proofRequestMessage,
state: ProofState.RequestReceived,
})
// Assert
this.connectionService.assertConnectionOrServiceDecorator(messageContext)
// Save in repository
await this.proofRepository.save(proofRecord)
this.eventEmitter.emit<ProofStateChangedEvent>({
type: ProofEventTypes.ProofStateChanged,
payload: { proofRecord, previousState: null },
})
}
return proofRecord
}
/**
* Create a {@link PresentationMessage} as response to a received presentation request.
*
* @param proofRecord The proof record for which to create the presentation
* @param requestedCredentials The requested credentials object specifying which credentials to use for the proof
* @param config Additional configuration to use for the presentation
* @returns Object containing presentation message and associated proof record
*
*/
public async createPresentation(
proofRecord: ProofRecord,
requestedCredentials: RequestedCredentials,
config?: {
comment?: string
}
): Promise<ProofProtocolMsgReturnType<PresentationMessage>> {
this.logger.debug(`Creating presentation for proof record with id ${proofRecord.id}`)
// Assert
proofRecord.assertState(ProofState.RequestReceived)
const indyProofRequest = proofRecord.requestMessage?.indyProofRequest
if (!indyProofRequest) {
throw new PresentationProblemReportError(
`Missing required base64 or json encoded attachment data for presentation with thread id ${proofRecord.threadId}`,
{ problemCode: PresentationProblemReportReason.Abandoned }
)
}
// Get the matching attachments to the requested credentials
const attachments = await this.getRequestedAttachmentsForRequestedCredentials(
indyProofRequest,
requestedCredentials
)
// Create proof
const proof = await this.createProof(indyProofRequest, requestedCredentials)
// Create message
const attachment = new Attachment({
id: INDY_PROOF_ATTACHMENT_ID,
mimeType: 'application/json',
data: new AttachmentData({
base64: JsonEncoder.toBase64(proof),
}),
})
const presentationMessage = new PresentationMessage({
comment: config?.comment,
presentationAttachments: [attachment],
attachments,
})
presentationMessage.setThread({ threadId: proofRecord.threadId })
// Update record
proofRecord.presentationMessage = presentationMessage
await this.updateState(proofRecord, ProofState.PresentationSent)
return { message: presentationMessage, proofRecord }
}
/**
* Process a received {@link PresentationMessage}. This will not accept the presentation
* or send a presentation acknowledgement. It will only update the existing proof record with
* the information from the presentation message. Use {@link ProofService.createAck}
* after calling this method to create a presentation acknowledgement.
*
* @param messageContext The message context containing a presentation message
* @returns proof record associated with the presentation message
*
*/
public async processPresentation(messageContext: InboundMessageContext<PresentationMessage>): Promise<ProofRecord> {
const { message: presentationMessage, connection } = messageContext
this.logger.debug(`Processing presentation with id ${presentationMessage.id}`)
const proofRecord = await this.getByThreadAndConnectionId(presentationMessage.threadId, connection?.id)
// Assert
proofRecord.assertState(ProofState.RequestSent)
this.connectionService.assertConnectionOrServiceDecorator(messageContext, {
previousReceivedMessage: proofRecord.proposalMessage,
previousSentMessage: proofRecord.requestMessage,
})
// TODO: add proof class with validator
const indyProofJson = presentationMessage.indyProof
const indyProofRequest = proofRecord.requestMessage?.indyProofRequest
if (!indyProofJson) {
throw new PresentationProblemReportError(
`Missing required base64 or json encoded attachment data for presentation with thread id ${presentationMessage.threadId}`,
{ problemCode: PresentationProblemReportReason.Abandoned }
)
}
if (!indyProofRequest) {
throw new PresentationProblemReportError(
`Missing required base64 or json encoded attachment data for presentation request with thread id ${presentationMessage.threadId}`,
{ problemCode: PresentationProblemReportReason.Abandoned }
)
}
const isValid = await this.verifyProof(indyProofJson, indyProofRequest)
// Update record
proofRecord.isVerified = isValid
proofRecord.presentationMessage = presentationMessage
await this.updateState(proofRecord, ProofState.PresentationReceived)
return proofRecord
}
/**
* Create a {@link PresentationAckMessage} as response to a received presentation.
*
* @param proofRecord The proof record for which to create the presentation acknowledgement
* @returns Object containing presentation acknowledgement message and associated proof record
*
*/
public async createAck(proofRecord: ProofRecord): Promise<ProofProtocolMsgReturnType<PresentationAckMessage>> {
this.logger.debug(`Creating presentation ack for proof record with id ${proofRecord.id}`)
// Assert
proofRecord.assertState(ProofState.PresentationReceived)
// Create message
const ackMessage = new PresentationAckMessage({
status: AckStatus.OK,
threadId: proofRecord.threadId,
})
// Update record
await this.updateState(proofRecord, ProofState.Done)
return { message: ackMessage, proofRecord }
}
/**
* Process a received {@link PresentationAckMessage}.
*
* @param messageContext The message context containing a presentation acknowledgement message
* @returns proof record associated with the presentation acknowledgement message
*
*/
public async processAck(messageContext: InboundMessageContext<PresentationAckMessage>): Promise<ProofRecord> {
const { message: presentationAckMessage, connection } = messageContext
this.logger.debug(`Processing presentation ack with id ${presentationAckMessage.id}`)
const proofRecord = await this.getByThreadAndConnectionId(presentationAckMessage.threadId, connection?.id)
// Assert
proofRecord.assertState(ProofState.PresentationSent)
this.connectionService.assertConnectionOrServiceDecorator(messageContext, {
previousReceivedMessage: proofRecord.requestMessage,
previousSentMessage: proofRecord.presentationMessage,
})
// Update record
await this.updateState(proofRecord, ProofState.Done)
return proofRecord
}
/**
* Process a received {@link PresentationProblemReportMessage}.
*
* @param messageContext The message context containing a presentation problem report message
* @returns proof record associated with the presentation acknowledgement message
*
*/
public async processProblemReport(
messageContext: InboundMessageContext<PresentationProblemReportMessage>
): Promise<ProofRecord> {
const { message: presentationProblemReportMessage } = messageContext
const connection = messageContext.assertReadyConnection()
this.logger.debug(`Processing problem report with id ${presentationProblemReportMessage.id}`)
const proofRecord = await this.getByThreadAndConnectionId(presentationProblemReportMessage.threadId, connection?.id)
proofRecord.errorMessage = `${presentationProblemReportMessage.description.code}: ${presentationProblemReportMessage.description.en}`
await this.update(proofRecord)
return proofRecord
}
public async generateProofRequestNonce() {
return this.wallet.generateNonce()
}
/**
* Create a {@link ProofRequest} from a presentation proposal. This method can be used to create the
* proof request from a received proposal for use in {@link ProofService.createRequestAsResponse}
*
* @param presentationProposal The presentation proposal to create a proof request from
* @param config Additional configuration to use for the proof request
* @returns proof request object
*
*/
public async createProofRequestFromProposal(
presentationProposal: PresentationPreview,
config: { name: string; version: string; nonce?: string }
): Promise<ProofRequest> {
const nonce = config.nonce ?? (await this.generateProofRequestNonce())
const proofRequest = new ProofRequest({
name: config.name,
version: config.version,
nonce,
})
/**
* Create mapping of attributes by referent. This required the
* attributes to come from the same credential.
* @see https://github.com/hyperledger/aries-rfcs/blob/master/features/0037-present-proof/README.md#referent
*
* {
* "referent1": [Attribute1, Attribute2],
* "referent2": [Attribute3]
* }
*/
const attributesByReferent: Record<string, PresentationPreviewAttribute[]> = {}
for (const proposedAttributes of presentationProposal.attributes) {
if (!proposedAttributes.referent) proposedAttributes.referent = uuid()
const referentAttributes = attributesByReferent[proposedAttributes.referent]
// Referent key already exist, add to list
if (referentAttributes) {
referentAttributes.push(proposedAttributes)
}
// Referent key does not exist yet, create new entry
else {
attributesByReferent[proposedAttributes.referent] = [proposedAttributes]
}
}
// Transform attributes by referent to requested attributes
for (const [referent, proposedAttributes] of Object.entries(attributesByReferent)) {
// Either attributeName or attributeNames will be undefined
const attributeName = proposedAttributes.length == 1 ? proposedAttributes[0].name : undefined
const attributeNames = proposedAttributes.length > 1 ? proposedAttributes.map((a) => a.name) : undefined
const requestedAttribute = new ProofAttributeInfo({
name: attributeName,
names: attributeNames,
restrictions: [
new AttributeFilter({
credentialDefinitionId: proposedAttributes[0].credentialDefinitionId,
}),
],
})
proofRequest.requestedAttributes.set(referent, requestedAttribute)
}
this.logger.debug('proposal predicates', presentationProposal.predicates)
// Transform proposed predicates to requested predicates
for (const proposedPredicate of presentationProposal.predicates) {
const requestedPredicate = new ProofPredicateInfo({
name: proposedPredicate.name,
predicateType: proposedPredicate.predicate,
predicateValue: proposedPredicate.threshold,
restrictions: [
new AttributeFilter({
credentialDefinitionId: proposedPredicate.credentialDefinitionId,
}),
],
})
proofRequest.requestedPredicates.set(uuid(), requestedPredicate)
}
return proofRequest
}
/**
* Retrieves the linked attachments for an {@link indyProofRequest}
* @param indyProofRequest The proof request for which the linked attachments have to be found
* @param requestedCredentials The requested credentials
* @returns a list of attachments that are linked to the requested credentials
*/
public async getRequestedAttachmentsForRequestedCredentials(
indyProofRequest: ProofRequest,
requestedCredentials: RequestedCredentials
): Promise<Attachment[] | undefined> {
const attachments: Attachment[] = []
const credentialIds = new Set<string>()
const requestedAttributesNames: (string | undefined)[] = []
// Get the credentialIds if it contains a hashlink
for (const [referent, requestedAttribute] of Object.entries(requestedCredentials.requestedAttributes)) {
// Find the requested Attributes
const requestedAttributes = indyProofRequest.requestedAttributes.get(referent) as ProofAttributeInfo
// List the requested attributes
requestedAttributesNames.push(...(requestedAttributes.names ?? [requestedAttributes.name]))
// Find the attributes that have a hashlink as a value
for (const attribute of Object.values(requestedAttribute.credentialInfo.attributes)) {
if (attribute.toLowerCase().startsWith('hl:')) {
credentialIds.add(requestedAttribute.credentialId)
}
}
}
// Only continues if there is an attribute value that contains a hashlink
for (const credentialId of credentialIds) {
// Get the credentialRecord that matches the ID
const credentialRecord = await this.credentialRepository.getSingleByQuery({ credentialId })
if (credentialRecord.linkedAttachments) {
// Get the credentials that have a hashlink as value and are requested
const requestedCredentials = credentialRecord.credentialAttributes?.filter(
(credential) =>
credential.value.toLowerCase().startsWith('hl:') && requestedAttributesNames.includes(credential.name)
)
// Get the linked attachments that match the requestedCredentials
const linkedAttachments = credentialRecord.linkedAttachments.filter((attachment) =>
requestedCredentials?.map((credential) => credential.value.split(':')[1]).includes(attachment.id)
)
if (linkedAttachments) {
attachments.push(...linkedAttachments)
}
}
}
return attachments.length ? attachments : undefined
}
/**
* Create a {@link RetrievedCredentials} object. Given input proof request and presentation proposal,
* use credentials in the wallet to build indy requested credentials object for input to proof creation.
* If restrictions allow, self attested attributes will be used.
*
*
* @param proofRequest The proof request to build the requested credentials object from
* @param presentationProposal Optional presentation proposal to improve credential selection algorithm
* @returns RetrievedCredentials object
*/
public async getRequestedCredentialsForProofRequest(
proofRequest: ProofRequest,
presentationProposal?: PresentationPreview
): Promise<RetrievedCredentials> {
const retrievedCredentials = new RetrievedCredentials({})
for (const [referent, requestedAttribute] of proofRequest.requestedAttributes.entries()) {
let credentialMatch: Credential[] = []
const credentials = await this.getCredentialsForProofRequest(proofRequest, referent)
// If we have exactly one credential, or no proposal to pick preferences
// on the credentials to use, we will use the first one
if (credentials.length === 1 || !presentationProposal) {
credentialMatch = credentials
}
// If we have a proposal we will use that to determine the credentials to use
else {
const names = requestedAttribute.names ?? [requestedAttribute.name]
// Find credentials that matches all parameters from the proposal
credentialMatch = credentials.filter((credential) => {
const { attributes, credentialDefinitionId } = credential.credentialInfo
// Check if credentials matches all parameters from proposal
return names.every((name) =>
presentationProposal.attributes.find(
(a) =>
a.name === name &&
a.credentialDefinitionId === credentialDefinitionId &&
(!a.value || a.value === attributes[name])
)
)
})
}
retrievedCredentials.requestedAttributes[referent] = credentialMatch.map((credential: Credential) => {
return new RequestedAttribute({
credentialId: credential.credentialInfo.referent,
revealed: true,
credentialInfo: credential.credentialInfo,
})
})
}
for (const [referent] of proofRequest.requestedPredicates.entries()) {
const credentials = await this.getCredentialsForProofRequest(proofRequest, referent)
retrievedCredentials.requestedPredicates[referent] = credentials.map((credential) => {
return new RequestedPredicate({
credentialId: credential.credentialInfo.referent,
credentialInfo: credential.credentialInfo,
})
})
}
return retrievedCredentials
}
/**
* Takes a RetrievedCredentials object and auto selects credentials in a RequestedCredentials object
*
* Use the return value of this method as input to {@link ProofService.createPresentation} to
* automatically accept a received presentation request.
*
* @param retrievedCredentials The retrieved credentials object to get credentials from
*
* @returns RequestedCredentials
*/
public autoSelectCredentialsForProofRequest(retrievedCredentials: RetrievedCredentials): RequestedCredentials {
const requestedCredentials = new RequestedCredentials({})
Object.keys(retrievedCredentials.requestedAttributes).forEach((attributeName) => {
const attributeArray = retrievedCredentials.requestedAttributes[attributeName]
if (attributeArray.length === 0) {
throw new AriesFrameworkError('Unable to automatically select requested attributes.')
} else {
requestedCredentials.requestedAttributes[attributeName] = attributeArray[0]
}
})
Object.keys(retrievedCredentials.requestedPredicates).forEach((attributeName) => {
if (retrievedCredentials.requestedPredicates[attributeName].length === 0) {
throw new AriesFrameworkError('Unable to automatically select requested predicates.')
} else {
requestedCredentials.requestedPredicates[attributeName] =
retrievedCredentials.requestedPredicates[attributeName][0]
}
})
return requestedCredentials
}
/**
* Verify an indy proof object. Will also verify raw values against encodings.
*
* @param proofRequest The proof request to use for proof verification
* @param proofJson The proof object to verify
* @throws {Error} If the raw values do not match the encoded values
* @returns Boolean whether the proof is valid
*
*/
public async verifyProof(proofJson: IndyProof, proofRequest: ProofRequest): Promise<boolean> {
const proof = JsonTransformer.fromJSON(proofJson, PartialProof)
for (const [referent, attribute] of proof.requestedProof.revealedAttributes.entries()) {
if (!CredentialUtils.checkValidEncoding(attribute.raw, attribute.encoded)) {
throw new PresentationProblemReportError(
`The encoded value for '${referent}' is invalid. ` +
`Expected '${CredentialUtils.encode(attribute.raw)}'. ` +
`Actual '${attribute.encoded}'`,
{ problemCode: PresentationProblemReportReason.Abandoned }
)
}
}
// TODO: pre verify proof json
// I'm not 100% sure how much indy does. Also if it checks whether the proof requests matches the proof
// @see https://github.com/hyperledger/aries-cloudagent-python/blob/master/aries_cloudagent/indy/sdk/verifier.py#L79-L164
const schemas = await this.getSchemas(new Set(proof.identifiers.map((i) => i.schemaId)))
const credentialDefinitions = await this.getCredentialDefinitions(
new Set(proof.identifiers.map((i) => i.credentialDefinitionId))
)
return await this.indyVerifierService.verifyProof({
proofRequest: proofRequest.toJSON(),
proof: proofJson,
schemas,
credentialDefinitions,
})
}
/**
* Retrieve all proof records
*
* @returns List containing all proof records
*/
public async getAll(): Promise<ProofRecord[]> {
return this.proofRepository.getAll()
}
/**
* Retrieve a proof record by id
*
* @param proofRecordId The proof record id
* @throws {RecordNotFoundError} If no record is found
* @return The proof record
*
*/
public async getById(proofRecordId: string): Promise<ProofRecord> {
return this.proofRepository.getById(proofRecordId)
}
/**
* Retrieve a proof record by id
*
* @param proofRecordId The proof record id
* @return The proof record or null if not found
*
*/
public async findById(proofRecordId: string): Promise<ProofRecord | null> {
return this.proofRepository.findById(proofRecordId)
}
/**
* Delete a proof record by id
*
* @param proofId the proof record id
*/
public async deleteById(proofId: string) {
const proofRecord = await this.getById(proofId)
return this.proofRepository.delete(proofRecord)
}
/**
* Retrieve a proof record by connection id and thread id
*
* @param connectionId The connection id
* @param threadId The thread id
* @throws {RecordNotFoundError} If no record is found
* @throws {RecordDuplicateError} If multiple records are found
* @returns The proof record
*/
public async getByThreadAndConnectionId(threadId: string, connectionId?: string): Promise<ProofRecord> {
return this.proofRepository.getSingleByQuery({ threadId, connectionId })
}
public update(proofRecord: ProofRecord) {
return this.proofRepository.update(proofRecord)
}
/**
* Create indy proof from a given proof request and requested credential object.
*
* @param proofRequest The proof request to create the proof for
* @param requestedCredentials The requested credentials object specifying which credentials to use for the proof
* @returns indy proof object
*/
private async createProof(
proofRequest: ProofRequest,
requestedCredentials: RequestedCredentials
): Promise<IndyProof> {
const credentialObjects = [
...Object.values(requestedCredentials.requestedAttributes),
...Object.values(requestedCredentials.requestedPredicates),
].map((c) => c.credentialInfo)
const schemas = await this.getSchemas(new Set(credentialObjects.map((c) => c.schemaId)))
const credentialDefinitions = await this.getCredentialDefinitions(
new Set(credentialObjects.map((c) => c.credentialDefinitionId))
)
const proof = await this.indyHolderService.createProof({
proofRequest: proofRequest.toJSON(),
requestedCredentials: requestedCredentials.toJSON(),
schemas,
credentialDefinitions,
})
return proof
}
private async getCredentialsForProofRequest(
proofRequest: ProofRequest,
attributeReferent: string
): Promise<Credential[]> {
const credentialsJson = await this.indyHolderService.getCredentialsForProofRequest({
proofRequest: proofRequest.toJSON(),
attributeReferent,
})
return JsonTransformer.fromJSON(credentialsJson, Credential) as unknown as Credential[]
}
/**
* Update the record to a new state and emit an state changed event. Also updates the record
* in storage.
*
* @param proofRecord The proof record to update the state for
* @param newState The state to update to
*
*/
private async updateState(proofRecord: ProofRecord, newState: ProofState) {
const previousState = proofRecord.state
proofRecord.state = newState
await this.proofRepository.update(proofRecord)
this.eventEmitter.emit<ProofStateChangedEvent>({
type: ProofEventTypes.ProofStateChanged,
payload: { proofRecord, previousState: previousState },
})
}
/**
* Build schemas object needed to create and verify proof objects.
*
* Creates object with `{ schemaId: Schema }` mapping
*
* @param schemaIds List of schema ids
* @returns Object containing schemas for specified schema ids
*
*/
private async getSchemas(schemaIds: Set<string>) {
const schemas: { [key: string]: Schema } = {}
for (const schemaId of schemaIds) {
const schema = await this.ledgerService.getSchema(schemaId)
schemas[schemaId] = schema
}
return schemas
}
/**
* Build credential definitions object needed to create and verify proof objects.
*
* Creates object with `{ credentialDefinitionId: CredentialDefinition }` mapping
*
* @param credentialDefinitionIds List of credential definition ids
* @returns Object containing credential definitions for specified credential definition ids
*
*/
private async getCredentialDefinitions(credentialDefinitionIds: Set<string>) {
const credentialDefinitions: { [key: string]: CredDef } = {}
for (const credDefId of credentialDefinitionIds) {
const credDef = await this.ledgerService.getCredentialDefinition(credDefId)
credentialDefinitions[credDefId] = credDef
}
return credentialDefinitions
}
}
export interface ProofRequestTemplate {
proofRequest: ProofRequest
comment?: string
}
export interface ProofProtocolMsgReturnType<MessageType extends AgentMessage> {
message: MessageType
proofRecord: ProofRecord
} | the_stack |
import callbackQueue from 'callback-queue';
import pluralize from 'pluralize';
import request from 'request-retry-dayjs';
import async from 'async';
import dayjs from 'dayjs';
import Currencies from '@tf2autobot/tf2-currencies';
import sleepasync from 'sleep-async';
import Bot from './Bot';
import { Entry, PricesObject } from './Pricelist';
import { BPTFGetUserInfo, UserSteamID } from './MyHandler/interfaces';
import log from '../lib/logger';
import { exponentialBackoff } from '../lib/helpers';
import { noiseMakers, spellsData, killstreakersData, sheensData } from '../lib/data';
import { DictItem } from './Inventory';
import { PaintedNames } from './Options';
import { Paints, StrangeParts } from '@tf2autobot/tf2-schema';
export default class Listings {
private checkingAllListings = false;
private removingAllListings = false;
private cancelCheckingListings = false;
private autoRelistEnabled = false;
private autoRelistTimeout: NodeJS.Timeout;
private get isAutoRelistEnabled(): boolean {
return this.bot.options.miscSettings.autobump.enable;
}
private get isCreateListing(): boolean {
return this.bot.options.miscSettings.createListings.enable;
}
private templates: { buy: string; sell: string };
private readonly checkFn;
constructor(private readonly bot: Bot) {
this.bot = bot;
this.templates = {
buy:
this.bot.options.details.buy ||
'I am buying your %name% for %price%, I have %current_stock% / %max_stock%.',
sell: this.bot.options.details.sell || 'I am selling my %name% for %price%, I am selling %amount_trade%.'
};
this.checkFn = this.checkAccountInfo.bind(this);
}
setupAutorelist(): void {
if (!this.isAutoRelistEnabled || !this.isCreateListing) {
// Autobump is not enabled
return;
}
// Autobump is enabled, add autorelist listener
this.bot.listingManager.removeListener('autorelist', this.checkFn);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.bot.listingManager.on('autorelist', this.checkFn);
// Get account info
this.checkAccountInfo();
}
disableAutorelistOption(): void {
if (this.bot.listingManager) {
this.bot.listingManager.removeListener('autorelist', this.checkFn);
this.disableAutoRelist(false, 'permanent');
}
}
private enableAutoRelist(): void {
if (this.autoRelistEnabled || !this.isCreateListing) {
return;
}
log.debug('Enabled autorelist');
this.autoRelistEnabled = true;
clearTimeout(this.autoRelistTimeout);
const doneWait = (): void => {
async.eachSeries(
[
(callback): void => {
void this.redoListings().asCallback(callback);
},
(callback): void => {
void this.waitForListings().asCallback(callback);
}
],
(item, callback) => {
if (this.bot.botManager.isStopping) {
return;
}
item(callback);
},
() => {
log.debug('Done relisting');
if (this.autoRelistEnabled) {
log.debug('Waiting 30 minutes before relisting again');
this.autoRelistTimeout = setTimeout(doneWait, 30 * 60 * 1000);
}
}
);
};
this.autoRelistTimeout = setTimeout(doneWait, 30 * 60 * 1000);
}
private checkAccountInfo(): void {
void this.getAccountInfo.asCallback((err, info) => {
if (err) {
log.warn('Failed to get account info from backpack.tf: ', err);
// temporarilyy disable autoRelist, so on the next check, when backpack.tf
// back alive, might trigger to call this.enableAutoRelist()
clearTimeout(this.autoRelistTimeout);
this.disableAutoRelist(false, 'temporary');
return;
}
if (this.autoRelistEnabled && info.premium === 1) {
log.warn('Disabling autorelist! - Your account is premium, no need to forcefully bump listings');
} else if (!this.autoRelistEnabled && info.premium !== 1) {
log.warn(
'Enabling autorelist! - Consider paying for backpack.tf premium instead of forcefully bumping listings: https://backpack.tf/donate'
);
this.enableAutoRelist();
} else if (this.isAutoRelistEnabled && info.premium === 1) {
log.warn('Disabling autobump! - Your account is premium, no need to forcefully bump listings');
this.bot.handler.commands.useUpdateOptionsCommand(null, '!config miscSettings.autobump.enable=false');
}
});
}
private disableAutoRelist(setValue: boolean, type: 'temporary' | 'permanent') {
clearTimeout(this.autoRelistTimeout);
this.autoRelistEnabled = setValue;
log.debug(type === 'temporary' ? 'Temporarily disabled autorelist' : 'Disabled autorelist');
}
private get getAccountInfo(): Promise<UserSteamID> {
return new Promise((resolve, reject) => {
const steamID64 = this.bot.manager.steamID.getSteamID64();
const options = {
url: 'https://backpack.tf/api/users/info/v1',
method: 'GET',
qs: {
key: this.bot.options.bptfAPIKey,
steamids: steamID64
},
gzip: true,
json: true
};
void request(options, (err, reponse, body) => {
if (err) {
return reject(err);
}
return resolve((body as BPTFGetUserInfo).users[steamID64]);
});
});
}
checkBySKU(sku: string, data?: Entry | null, generics = false, showLogs = false): void {
if (!this.isCreateListing) {
return;
}
if (showLogs) {
log.debug(`Checking ${sku}...`);
}
let doneSomething = false;
const match = data?.enabled === false ? null : this.bot.pricelist.getPrice(sku, true, generics);
let hasBuyListing = false;
let hasSellListing = false;
const invManager = this.bot.inventoryManager;
const inventory = invManager.getInventory;
const amountCanBuy = invManager.amountCanTrade(sku, true, generics);
const amountCanSell = invManager.amountCanTrade(sku, false, generics);
const isFilterCantAfford = this.bot.options.pricelist.filterCantAfford.enable; // false by default
this.bot.listingManager.findListings(sku).forEach(listing => {
if (listing.intent === 1 && hasSellListing) {
if (showLogs) {
log.debug('Already have a sell listing, remove the listing.');
}
doneSomething = true;
listing.remove();
return;
}
if (listing.intent === 0) {
hasBuyListing = true;
} else if (listing.intent === 1) {
hasSellListing = true;
}
if (match === null || (match.intent !== 2 && match.intent !== listing.intent)) {
if (showLogs) {
log.debug('We are not trading the item, remove the listing.');
}
doneSomething = true;
listing.remove();
} else if ((listing.intent === 0 && amountCanBuy <= 0) || (listing.intent === 1 && amountCanSell <= 0)) {
if (showLogs) {
log.debug(`We are not ${listing.intent === 0 ? 'buying' : 'selling'} more, remove the listing.`);
}
doneSomething = true;
listing.remove();
} else if (
listing.intent === 0 &&
!invManager.isCanAffordToBuy(match.buy, invManager.getInventory) &&
isFilterCantAfford
) {
if (showLogs) {
log.debug(`we can't afford to buy, remove the listing.`);
}
doneSomething = true;
listing.remove();
} else {
if (listing.intent === 0 && /;[p][0-9]+/.test(sku)) {
// do nothing
} else {
const newDetails = this.getDetails(
listing.intent,
listing.intent === 0 ? amountCanBuy : amountCanSell,
match,
inventory.getItems[sku]?.filter(item => item.id === listing.id.replace('440_', ''))[0]
);
const keyPrice = this.bot.pricelist.getKeyPrice;
// if listing note don't have any parameters (%price%, %amount_trade%, etc), then we check if there's any changes with currencies
const isCurrenciesChanged =
listing.currencies?.toValue(keyPrice.metal) !==
match[listing.intent === 0 ? 'buy' : 'sell']?.toValue(keyPrice.metal);
const isListingDetailsChanged =
listing.details?.replace('[𝐀𝐮𝐭𝐨𝐤𝐞𝐲𝐬]', '') !== newDetails.replace('[𝐀𝐮𝐭𝐨𝐤𝐞𝐲𝐬]', '');
if (isCurrenciesChanged || isListingDetailsChanged) {
if (showLogs) {
log.debug(`Listing details don't match, updated listing`, {
sku: sku,
intent: listing.intent
});
}
doneSomething = true;
const currencies = match[listing.intent === 0 ? 'buy' : 'sell'];
listing.update({
currencies: currencies,
//promoted: listing.intent === 0 ? 0 : match.promoted,
details: newDetails
});
//TODO: make promote, demote
}
}
}
});
const matchNew = data?.enabled === false ? null : this.bot.pricelist.getPrice(sku, true, generics);
if (matchNew !== null && matchNew.enabled === true) {
const assetids = inventory.findBySKU(sku, true);
const canAffordToBuy = isFilterCantAfford
? invManager.isCanAffordToBuy(matchNew.buy, invManager.getInventory)
: true;
if (!hasBuyListing && amountCanBuy > 0 && canAffordToBuy && !/;[p][0-9]+/.test(sku)) {
if (showLogs) {
log.debug(`We have no buy order and we can buy more items, create buy listing.`);
}
doneSomething = true;
this.bot.listingManager.createListing({
time: matchNew.time || dayjs().unix(),
sku: sku,
intent: 0,
details: this.getDetails(0, amountCanBuy, matchNew),
currencies: matchNew.buy
});
}
if (!hasSellListing && amountCanSell > 0) {
if (showLogs) {
log.debug(`We have no sell order and we can sell items, create sell listing.`);
}
doneSomething = true;
this.bot.listingManager.createListing({
time: matchNew.time || dayjs().unix(),
id: assetids[assetids.length - 1],
intent: 1,
promoted: matchNew.promoted,
details: this.getDetails(
1,
amountCanSell,
matchNew,
inventory.getItems[sku]?.filter(item => item.id === assetids[assetids.length - 1])[0]
),
currencies: matchNew.sell
});
}
}
if (showLogs && !doneSomething) {
log.debug('Done check, nothing changed');
}
}
checkAll(): Promise<void> {
return new Promise(resolve => {
if (!this.isCreateListing) {
return resolve();
}
log.debug('Checking all');
const doneRemovingAll = (): void => {
const next = callbackQueue.add('checkAllListings', () => {
resolve();
});
if (next === false) {
return;
}
this.checkingAllListings = true;
const inventoryManager = this.bot.inventoryManager;
const inventory = inventoryManager.getInventory;
const currentPure = inventoryManager.getPureValue;
const keyPrice = this.bot.pricelist.getKeyPrice;
const pricelist = this.bot.pricelist.getPrices;
let skus = Object.keys(pricelist);
if (this.bot.options.pricelist.filterCantAfford.enable) {
skus = skus.filter(sku => {
const amountCanBuy = inventoryManager.amountCanTrade(sku, true);
if (
(amountCanBuy > 0 && inventoryManager.isCanAffordToBuy(pricelist[sku].buy, inventory)) ||
inventory.getAmount(sku, false, true) > 0
) {
// if can amountCanBuy is more than 0 and isCanAffordToBuy is true OR amount of item is more than 0
// return this entry
return true;
}
// Else ignore
return false;
});
}
skus = skus
.sort((a, b) => {
return (
currentPure.keys -
(pricelist[b].buy.keys - pricelist[a].buy.keys) * keyPrice.toValue() +
(currentPure.metal - Currencies.toScrap(pricelist[b].buy.metal - pricelist[a].buy.metal))
);
})
.sort((a, b) => {
return inventory.findBySKU(b).length - inventory.findBySKU(a).length;
});
log.debug('Checking listings for ' + pluralize('item', skus.length, true) + '...');
void this.recursiveCheckPricelist(skus, pricelist).asCallback(() => {
log.debug('Done checking all');
// Done checking all listings
this.checkingAllListings = false;
next();
});
};
if (!this.removingAllListings) {
return doneRemovingAll();
}
callbackQueue.add('removeAllListings', () => {
doneRemovingAll();
});
});
}
recursiveCheckPricelist(
skus: string[],
pricelist: PricesObject,
withDelay = false,
time?: number,
showLogs = false
): Promise<void> {
return new Promise(resolve => {
let index = 0;
const iteration = async (): Promise<void> => {
if (skus.length <= index || this.cancelCheckingListings) {
this.cancelCheckingListings = false;
return resolve();
}
if (withDelay) {
this.checkBySKU(skus[index], pricelist[skus[index]], false, showLogs);
index++;
await sleepasync().Promise.sleep(time ? time : 200);
void iteration();
} else {
setImmediate(() => {
this.checkBySKU(skus[index], pricelist[skus[index]]);
index++;
void iteration();
});
}
};
void iteration();
});
}
removeAll(): Promise<void> {
return new Promise((resolve, reject) => {
if (this.checkingAllListings) {
this.cancelCheckingListings = true;
}
log.debug('Removing all listings');
// Ensures that we don't to remove listings multiple times
const next = callbackQueue.add('removeAllListings', err => {
if (err) {
return reject(err);
}
return resolve(null);
});
if (next === false) {
// Function was already called
return;
}
void this.removeAllListings().asCallback(next);
});
}
private removeAllListings(): Promise<void> {
return new Promise((resolve, reject) => {
this.removingAllListings = true;
// Clear create queue
this.bot.listingManager.actions.create = [];
// Wait for backpack.tf to finish creating / removing listings
void this.waitForListings().then(() => {
if (this.bot.listingManager.listings.length === 0) {
log.debug('We have no listings');
this.removingAllListings = false;
return resolve();
}
log.debug('Removing all listings...');
// Remove all current listings
this.bot.listingManager.listings.forEach(listing => listing.remove());
// Clear timeout
clearTimeout(this.bot.listingManager._timeout);
// Remove listings
this.bot.listingManager._processActions(err => {
if (err) {
return reject(err);
}
// The request might fail, if it does we will try again
return resolve(this.removeAllListings());
});
});
});
}
redoListings(): Promise<void> {
return this.removeAll().then(() => {
return this.checkAll();
});
}
waitForListings(): Promise<void> {
return new Promise((resolve, reject) => {
let checks = 0;
const check = (): void => {
checks++;
log.debug('Checking listings...');
const prevCount = this.bot.listingManager.listings.length;
this.bot.listingManager.getListings(err => {
if (err) {
return reject(err);
}
if (this.bot.listingManager.listings.length !== prevCount) {
log.debug(
`Count changed: ${this.bot.listingManager.listings.length} listed, ${prevCount} previously`
);
setTimeout(() => {
check();
}, exponentialBackoff(checks));
} else {
log.debug("Count didn't change");
return resolve();
}
});
};
check();
});
}
private getDetails(intent: 0 | 1, amountCanTrade: number, entry: Entry, item?: DictItem): string {
const opt = this.bot.options;
const buying = intent === 0;
const key = buying ? 'buy' : 'sell';
const keyPrice = this.bot.pricelist.getKeyPrice;
let highValueString = '';
if (intent === 1) {
// if item undefined, then skip because it will make your bot crashed.
if (item) {
const toJoin: string[] = [];
const optD = opt.details.highValue;
const cT = optD.customText;
const cTSpt = optD.customText.separator;
const cTEnd = optD.customText.ender;
const optR = opt.detailsExtra;
const getPaints = this.bot.paints;
const getStrangeParts = this.bot.strangeParts;
const hv = item.hv;
if (hv) {
Object.keys(hv).forEach(attachment => {
if (
hv[attachment] &&
(attachment === 's'
? optD.showSpells
: attachment === 'sp'
? optD.showStrangeParts
: attachment === 'ke'
? optD.showKillstreaker
: attachment === 'ks'
? optD.showSheen
: optD.showPainted && opt.normalize.painted.our)
) {
if (attachment === 's') highValueString += `${cTSpt}${cT.spells} `;
else if (attachment === 'sp') highValueString += `${cTSpt}${cT.strangeParts} `;
else if (attachment === 'ke') highValueString += `${cTSpt}${cT.killstreaker} `;
else if (attachment === 'ks') highValueString += `${cTSpt}${cT.sheen} `;
else if (attachment === 'p') highValueString += `${cTSpt}${cT.painted} `;
for (const pSKU in hv[attachment]) {
if (!Object.prototype.hasOwnProperty.call(hv[attachment], pSKU)) {
continue;
}
if (attachment === 'sp' && hv[attachment as Attachment][pSKU] === true) {
const name = getAttachmentName(attachment, pSKU, getPaints, getStrangeParts);
toJoin.push(
`${name.replace(
name,
optR.strangeParts[name] ? optR.strangeParts[name] : name
)}`
);
} else {
if (attachment !== 'sp') {
const name = getAttachmentName(attachment, pSKU, getPaints, getStrangeParts);
toJoin.push(
`${name.replace(
name,
attachment === 's'
? optR.spells[name]
: attachment === 'ke'
? optR.killstreakers[name]
: attachment === 'ks'
? optR.sheens[name]
: optR.painted[name as PaintedNames].stringNote
)}`
);
}
}
}
if (toJoin.length > 0) {
highValueString += toJoin.join(' + ');
} else {
highValueString = highValueString.replace(
attachment === 's'
? `${cTSpt}${cT.spells} `
: attachment === 'sp'
? `${cTSpt}${cT.strangeParts} `
: attachment === 'ke'
? `${cTSpt}${cT.killstreaker} `
: attachment === 'ks'
? `${cTSpt}${cT.sheen} `
: `${cTSpt}${cT.painted} `,
''
);
}
toJoin.length = 0;
}
});
highValueString += highValueString.length > 0 ? cTEnd : '';
}
}
}
const optDs = opt.details.uses;
let details: string;
const inventory = this.bot.inventoryManager.getInventory;
const showBoldText = opt.details.showBoldText;
const isShowBoldOnPrice = showBoldText.onPrice;
const isShowBoldOnAmount = showBoldText.onAmount;
const isShowBoldOnCurrentStock = showBoldText.onCurrentStock;
const isShowBoldOnMaxStock = showBoldText.onMaxStock;
const style = showBoldText.style;
const replaceDetails = (details: string, entry: Entry, key: 'buy' | 'sell') => {
const price = entry[key].toString();
const maxStock = entry.max === -1 ? '∞' : entry.max.toString();
const currentStock = inventory.getAmount(entry.sku, false, true).toString();
const amountTrade = amountCanTrade.toString();
return details
.replace(/%price%/g, isShowBoldOnPrice ? boldDetails(price, style) : price)
.replace(/%name%/g, entry.name)
.replace(/%max_stock%/g, isShowBoldOnMaxStock ? boldDetails(maxStock, style) : maxStock)
.replace(/%current_stock%/g, isShowBoldOnCurrentStock ? boldDetails(currentStock, style) : currentStock)
.replace(/%amount_trade%/g, isShowBoldOnAmount ? boldDetails(amountTrade, style) : amountTrade);
};
const isCustomBuyNote = entry.note?.buy && intent === 0;
const isCustomSellNote = entry.note?.sell && intent === 1;
const isDueling = entry.sku === '241;6' && opt.miscSettings.checkUses.duel;
const isNoiseMaker = noiseMakers.has(entry.sku) && opt.miscSettings.checkUses.noiseMaker;
if (isCustomBuyNote || isCustomSellNote) {
details = replaceDetails(intent === 0 ? entry.note.buy : entry.note.sell, entry, key);
details = entry[key].toString().includes('key')
? details.replace(/%keyPrice%/g, 'Key rate: ' + keyPrice.toString() + '/key')
: details.replace(/%keyPrice%/g, '');
details = isDueling
? details.replace(/%uses%/g, optDs.duel ? optDs.duel : '(𝗢𝗡𝗟𝗬 𝗪𝗜𝗧𝗛 𝟱x 𝗨𝗦𝗘𝗦)')
: isNoiseMaker
? details.replace(/%uses%/g, optDs.noiseMaker ? optDs.noiseMaker : '(𝗢𝗡𝗟𝗬 𝗪𝗜𝗧𝗛 𝟐𝟱x 𝗨𝗦𝗘𝗦)')
: details.replace(/%uses%/g, '');
//
} else if (isDueling || isNoiseMaker) {
details = replaceDetails(this.templates[key], entry, key).replace(
/%uses%/g,
isDueling
? optDs.duel
? optDs.duel
: '(𝗢𝗡𝗟𝗬 𝗪𝗜𝗧𝗛 𝟱x 𝗨𝗦𝗘𝗦)'
: optDs.noiseMaker
? optDs.noiseMaker
: '(𝗢𝗡𝗟𝗬 𝗪𝗜𝗧𝗛 𝟐𝟱x 𝗨𝗦𝗘𝗦)'
);
details = entry[key].toString().includes('key')
? details.replace(/%keyPrice%/g, 'Key rate: ' + keyPrice.toString() + '/key')
: details.replace(/%keyPrice%/g, '');
//
} else if (entry.name === 'Mann Co. Supply Crate Key' || !entry[key].toString().includes('key')) {
// this part checks if the item Mann Co. Supply Crate Key or the buying/selling price involve keys.
details = replaceDetails(this.templates[key], entry, key)
.replace(/%keyPrice%/g, '')
.replace(/%uses%/g, '');
if (entry.name === 'Mann Co. Supply Crate Key' && this.bot.handler.autokeys.isEnabled) {
details = '[𝐀𝐮𝐭𝐨𝐤𝐞𝐲𝐬] ' + details;
}
//
} else {
// else if nothing above, then just use template/in config and replace every parameters.
details = replaceDetails(this.templates[key], entry, key)
.replace(/%keyPrice%/g, 'Key rate: ' + keyPrice.toString() + '/key')
.replace(/%uses%/g, '');
//
}
return details + (highValueString.length > 0 ? ' ' + highValueString : '');
}
}
type Attachment = 's' | 'sp' | 'ke' | 'ks' | 'p';
function getKeyByValue(object: { [key: string]: any }, value: any): string {
return Object.keys(object).find(key => object[key] === value);
}
function getAttachmentName(attachment: string, pSKU: string, paints: Paints, parts: StrangeParts): string {
if (attachment === 's') return getKeyByValue(spellsData, pSKU);
else if (attachment === 'sp') return getKeyByValue(parts, pSKU);
else if (attachment === 'ke') return getKeyByValue(killstreakersData, pSKU);
else if (attachment === 'ks') return getKeyByValue(sheensData, pSKU);
else if (attachment === 'p') return getKeyByValue(paints, pSKU);
}
function boldDetails(str: string, style: number): string {
// https://lingojam.com/BoldTextGenerator
if ([1, 2].includes(style)) {
// Bold numbers (serif)
str = str
.replace(/0/g, '𝟎') // can't use replaceAll yet 😪
.replace(/1/g, '𝟏')
.replace(/2/g, '𝟐')
.replace(/3/g, '𝟑')
.replace(/4/g, '𝟒')
.replace(/5/g, '𝟓')
.replace(/6/g, '𝟔')
.replace(/7/g, '𝟕')
.replace(/8/g, '𝟖')
.replace(/9/g, '𝟗')
.replace('.', '.')
.replace(',', ',');
if (style === 1) {
// Style 1 - Bold (serif)
return str.replace('ref', '𝐫𝐞𝐟').replace('keys', '𝐤𝐞𝐲𝐬').replace('key', '𝐤𝐞𝐲');
}
// Style 2 - Italic Bold (serif)
return str.replace('ref', '𝒓𝒆𝒇').replace('keys', '𝒌𝒆𝒚𝒔').replace('key', '𝒌𝒆𝒚');
}
// Bold numbers (sans):
str = str
.replace(/0/g, '𝟬')
.replace(/1/g, '𝟭')
.replace(/2/g, '𝟮')
.replace(/3/g, '𝟯')
.replace(/4/g, '𝟰')
.replace(/5/g, '𝟱')
.replace(/6/g, '𝟲')
.replace(/7/g, '𝟳')
.replace(/8/g, '𝟴')
.replace(/9/g, '𝟵')
.replace('.', '.')
.replace(',', ',');
if (style === 3) {
// Style 3 - Bold (sans)
return str.replace('ref', '𝗿𝗲𝗳').replace('keys', '𝗸𝗲𝘆𝘀').replace('key', '𝗸𝗲𝘆');
}
// Style 4 - Italic Bold (sans)
return str.replace('ref', '𝙧𝙚𝙛').replace('keys', '𝙠𝙚𝙮𝙨').replace('key', '𝙠𝙚𝙮');
} | the_stack |
import React, { useState } from 'react';
import {
addons,
makeDecorator,
OptionsParameter,
StoryContext,
StoryGetter,
} from '@storybook/addons';
// import { useAddonState } from '@storybook/client-api';
import { STORY_CHANGED, STORY_RENDERED } from '@storybook/core-events';
import {
ADDON_GLOBAL_DISABLE_STATE,
addonParameters,
} from '../share/constants';
import {
AttributesStatesDefault,
Orientation,
PseudoState,
PseudoStates,
PseudoStatesDefault,
PseudoStatesDefaultPrefix,
PseudoStatesParameters,
Selector,
WrapperPseudoStateSettings,
} from '../share/types';
import { SAPS_BUTTON_CLICK, SAPS_INIT_PSEUDO_STATES } from '../share/events';
import { getMixedPseudoStates, sanitizePseudoName } from '../share/utils';
import { AttributeStatesObj } from '../share/AttributeStatesObj';
import { PermutationStatsObj } from '../share/PermutationsStatesObj';
import { styles } from '../share/styles';
interface IState {
name: string;
// eslint-disable-next-line no-undef
states: Array<JSX.Element>;
pseudos?: PseudoStates;
permutation?: PermutationStatsObj;
}
function pseudoStateFn(
getStory: StoryGetter,
context: StoryContext,
settings: WrapperPseudoStateSettings
) {
const story = getStory(context);
const channel = addons.getChannel();
// are options set by user
const options: OptionsParameter = settings?.options;
// Are addonParameters set by user
const parameters: PseudoStatesParameters = settings?.parameters || {};
const addonDisabled = settings?.parameters?.disabled || false;
// notify toolbar button
channel.emit(SAPS_INIT_PSEUDO_STATES, addonDisabled);
const globallyDisabled =
sessionStorage.getItem(ADDON_GLOBAL_DISABLE_STATE) === 'true';
// const [isStoryDisabled, setIsStoryDisabled] = useAddonState<boolean>(ADDON_GLOBAL_DISABLE_STATE, false);
const [isStoryDisabled, setIsStoryDisabled] = useState(globallyDisabled);
if (addonDisabled) {
return story;
}
// use selector form parameters or if not set use settings selector or null
const selector: Selector | null = settings?.parameters?.selector || null;
// Use user values, default user options or default values
parameters.pseudos =
parameters?.pseudos || options?.pseudos || PseudoStatesDefault;
parameters.attributes =
parameters?.attributes || options?.attributes || AttributesStatesDefault;
let permutationsAsObject: Array<PermutationStatsObj> = [];
if (parameters.permutations) {
permutationsAsObject = [...parameters?.permutations].map((item) =>
PermutationStatsObj.fromPermutationState(item)
);
}
let attributesAsObject: Array<AttributeStatesObj> = [];
if (parameters.attributes) {
attributesAsObject = [...parameters?.attributes].map((item) =>
AttributeStatesObj.fromAttributeState(item)
);
}
// Use prefix without `:` because angular add component scope before each `:`
// Maybe not editable by user in angular context?
parameters.prefix =
parameters?.prefix || options?.prefix || PseudoStatesDefaultPrefix;
const states: IState[] = [];
// Create Normal states
states.push({
name: 'Normal',
pseudos: parameters.pseudos,
states: createPseudos(story, parameters.pseudos, attributesAsObject),
});
// create story's new template
for (const permutation of permutationsAsObject) {
states.push({
// label = permutation name if not specified in parameters
name: permutation.label || permutation.attr,
pseudos: parameters.pseudos,
permutation,
states: createPseudos(
story,
parameters.pseudos,
attributesAsObject,
permutation
),
});
}
/**
*
* @param pseudoState
* @param containerTmp
* @param selectorTmp
* @param permutation
*/
const applyPseudoStateToHost = (
pseudoState: PseudoState,
containerTmp: Element,
selectorTmp: Selector | null,
permutation: PermutationStatsObj | undefined
) => {
let host;
if (!selectorTmp) {
host = containerTmp.children[0];
} else if (typeof selectorTmp === 'string') {
host = containerTmp.querySelector(selectorTmp);
} else if (Array.isArray(selectorTmp)) {
for (const s of selectorTmp as Array<PseudoState>) {
applyPseudoStateToHost(pseudoState, containerTmp, s, permutation);
}
}
// get css module [path][name]__[local] and remove [local]
// TODO test if first class represents always css module
let moduleClass = null;
// try to find css module prefix
if (host?.classList[0]) {
moduleClass = host?.classList[0].match(/(.+?)?__/) as Array<string>;
}
let cssModulePrefix = '';
if (moduleClass && moduleClass?.length >= 1) {
cssModulePrefix = `${moduleClass[1]}__`;
}
const subPseudoStates = getMixedPseudoStates(pseudoState);
if (permutation) {
subPseudoStates.concat([permutation.attr]);
}
for (const s of subPseudoStates) {
host?.classList.add(`${cssModulePrefix}${parameters.prefix}${s.trim()}`);
// add default without module prefix to ensure compatibility with BEM syntax
host?.classList.add(`${parameters.prefix}${s.trim()}`);
}
};
// update pseudo states after story is rendered
const updatePseudoStates = () => {
if (parameters.pseudos) {
for (const state of states) {
for (const pstateRaw of state.pseudos ?? []) {
const pstate = sanitizePseudoName(pstateRaw);
const containers = document.querySelectorAll(
`.pseudo-states-addon__story--${pstate} .pseudo-states-addon__story__container`
);
/**
* For each story container found (one for every permutation present)
* cycle through the peudostate elements and add the pseudo state to them
*/
if (containers && containers.length > 0) {
containers.forEach((container) => {
if (container) {
applyPseudoStateToHost(
pstateRaw,
container,
selector,
state.permutation
);
}
});
}
}
}
}
};
// update when story is rendered
channel.once(STORY_RENDERED, () => {
updatePseudoStates();
});
const darkModeListner = () => {
setTimeout(() => {
updatePseudoStates();
});
};
/**
* Listen for changes of dark mode add-on and re-apply pseudo states.
* https://github.com/hipstersmoothie/storybook-dark-mode
*/
channel.on('DARK_MODE', darkModeListner);
const clickHandler = (value: boolean) => {
setIsStoryDisabled(value);
// update when disable state changed
updatePseudoStates();
};
channel.removeAllListeners(SAPS_BUTTON_CLICK);
channel.addListener(SAPS_BUTTON_CLICK, clickHandler);
channel.once(STORY_CHANGED, () => {
channel.removeAllListeners(SAPS_BUTTON_CLICK);
channel.off('DARK_MODE', darkModeListner);
});
const numberOfPseudos = parameters.pseudos ? parameters.pseudos.length : 0;
const numberOfAttributes = parameters.attributes
? parameters.attributes.length
: 0;
/**
* Grid can either be row or column oriented, depening on the
* parameters.styles variable (ROW or COLUMN). We flip the
* row / column count when ROW was given.
*/
const getGridStyles = () => {
switch (parameters.styles) {
case Orientation.ROW:
return {
gridTemplateRows: `repeat(${
1 + permutationsAsObject.length
}, min-content)`,
gridTemplateColumns: `repeat(${
1 + numberOfPseudos + numberOfAttributes
}, max-content)`,
gridAutoFlow: 'row',
};
case Orientation.COLUMN:
default:
return {
gridTemplateRows: `repeat(${
1 + numberOfPseudos + numberOfAttributes
}, min-content)`,
gridTemplateColumns: `repeat(${
1 + permutationsAsObject.length
}, min-content)`,
gridAutoFlow: 'column',
};
}
};
return isStoryDisabled ? (
story
) : (
<div
className="pseudo-states-addon__container"
style={{ ...styles.gridContainer, ...getGridStyles() }}
>
{/**
* Map over all states and return a Fragment (will vanish in DOM) with the
* full story including the normal state which is defined here
*/}
{states.map((state: IState) => (
<>
<div
className={`pseudo-states-addon__story pseudo-states-addon__story--${state.name}`}
>
<div className="pseudo-states-addon__story__header">
{state.name}:
</div>
<div className="pseudo-states-addon__story__container">
{/**
* Need to add permutation attributes to the normal state,
* therefore we clone the element and add the necessary props
*/}
{React.cloneElement(
story,
state.permutation
? {
[state.permutation.attr]: state.permutation.value,
}
: {}
)}
</div>
</div>
{state.states}
</>
))}
</div>
);
}
/**
* Given Pseudo States and Attributes, create all necessary
* react element children and push them to a JSX Array to
* return them to be rendered.
*/
const createPseudos = (
story: any,
pseudos: PseudoStates | undefined,
attributesAsObject: Array<AttributeStatesObj>,
permutation?: PermutationStatsObj
) => {
// eslint-disable-next-line no-undef
const states: Array<JSX.Element> = [];
if (pseudos) {
// Run through pseudo states and render a story element for each
for (const state of pseudos) {
const pstate = sanitizePseudoName(state);
// When a permutation was given, add it to the story props
const storyState = {
...story,
props: permutation
? {
...story.props,
[state]: true,
[permutation.attr]: permutation.value,
}
: {
...story.props,
[state]: true,
},
};
const pseudoStoryPart = (
<div
className={`pseudo-states-addon__story pseudo-states-addon__story--${pstate}`}
key={`pseudo-${pstate}`}
>
<div className="pseudo-states-addon__story__header">{state}:</div>
<div className="pseudo-states-addon__story__container">
{storyState}
</div>
</div>
);
states.push(pseudoStoryPart);
}
if (attributesAsObject) {
// Run through the given attributes and add a story element for each
for (const attr of attributesAsObject) {
// When a permutation was given, add it to the story props
const storyState = {
...story,
props: permutation
? {
...story.props,
[attr.attr]: attr.value,
[permutation.attr]: permutation.value,
}
: {
...story.props,
[attr.attr]: attr.value,
},
};
states.push(
<div
className={`pseudo-states-addon__story pseudo-states-addon__story--attr-${attr.attr}`}
key={`attr-${attr.attr}`}
>
<div className="pseudo-states-addon__story__header">
{attr.attr}:
</div>
<div className="pseudo-states-addon__story__container">
{storyState}
</div>
</div>
);
}
}
}
return states;
};
export const withPseudo = makeDecorator({
...addonParameters,
wrapper: (
getStory: StoryGetter,
context: StoryContext,
settings: WrapperPseudoStateSettings
) => {
return pseudoStateFn(getStory, context, settings);
},
});
if (module && module.hot && module.hot.decline) {
module.hot.decline();
}
export default withPseudo; | the_stack |
import { formatTick, computeTimeIntervalName } from './time-series';
import { TimeScaleOptions } from '../interfaces';
import * as Configuration from '../configuration';
import frLocaleObject from 'date-fns/locale/fr/index';
type TickTuple = [Date, string];
type Dataset = TickTuple[];
const timeScaleDefaultOptions = Configuration.timeScale;
const format = (
ticks: number[],
timeInterval: string,
timeScaleOptions: TimeScaleOptions
): string[] => {
return ticks.map((tick, i) =>
formatTick(tick, i, timeInterval, timeScaleOptions)
);
};
const getTimestampsAndFormattedTicks = (dataset: Dataset) => {
const timestamps = dataset.map((d) => d[0].getTime());
const formattedTicks = dataset.map((d) => d[1]);
return { timestamps, formattedTicks };
};
it('should format ticks with timeInterval 15seconds', () => {
const dataset: Dataset = [
[new Date(2020, 11, 10, 23, 59, 15), 'Dec 10, 11:59:15 PM'],
[new Date(2020, 11, 10, 23, 59, 30), '11:59:30 PM'],
[new Date(2020, 11, 10, 23, 59, 45), '11:59:45 PM'],
[new Date(2020, 11, 11, 0, 0, 0), 'Dec 11, 12:00:00 AM'],
[new Date(2020, 11, 11, 0, 0, 15), '12:00:15 AM'],
[new Date(2020, 11, 11, 0, 0, 30), '12:00:30 AM'],
[new Date(2020, 11, 11, 0, 0, 45), '12:00:45 AM'],
];
const { timestamps, formattedTicks } = getTimestampsAndFormattedTicks(
dataset
);
const timeInterval = computeTimeIntervalName(timestamps);
expect(timeInterval).toEqual('15seconds');
expect(format(timestamps, timeInterval, timeScaleDefaultOptions)).toEqual(
formattedTicks
);
});
it('should format ticks with timeInterval minute', () => {
const dataset: Dataset = [
[new Date(2020, 4, 21, 23, 47, 0), 'May 21, 11:47 PM'],
[new Date(2020, 4, 21, 23, 58, 0), '11:58 PM'],
[new Date(2020, 4, 21, 23, 59, 0), '11:59 PM'],
[new Date(2020, 4, 22, 0, 0, 0), 'May 22, 12:00 AM'],
[new Date(2020, 4, 22, 0, 1, 0), '12:01 AM'],
[new Date(2020, 4, 22, 0, 2, 0), '12:02 AM'],
[new Date(2020, 4, 22, 0, 3, 0), '12:03 AM'],
[new Date(2020, 4, 22, 11, 58, 0), '11:58 AM'],
[new Date(2020, 4, 22, 11, 59, 0), '11:59 AM'],
[new Date(2020, 4, 22, 12, 0, 0), '12:00 PM'],
[new Date(2020, 4, 22, 12, 1, 0, 0), '12:01 PM'],
[new Date(2020, 4, 22, 12, 2, 0), '12:02 PM'],
];
const { timestamps, formattedTicks } = getTimestampsAndFormattedTicks(
dataset
);
const timeInterval = computeTimeIntervalName(timestamps);
expect(timeInterval).toEqual('minute');
expect(format(timestamps, timeInterval, timeScaleDefaultOptions)).toEqual(
formattedTicks
);
});
it('should format ticks with timeInterval 30minutes', () => {
const dataset: Dataset = [
[new Date(2020, 11, 10, 22, 30), 'Dec 10, 10:30 PM'],
[new Date(2020, 11, 10, 23, 0), '11:00 PM'],
[new Date(2020, 11, 10, 23, 30), '11:30 PM'],
[new Date(2020, 11, 11, 0, 0), 'Dec 11, 12:00 AM'],
[new Date(2020, 11, 11, 0, 30), '12:30 AM'],
[new Date(2020, 11, 11, 1, 0), '1:00 AM'],
[new Date(2020, 11, 11, 1, 30), '1:30 AM'],
];
const { timestamps, formattedTicks } = getTimestampsAndFormattedTicks(
dataset
);
const timeInterval = computeTimeIntervalName(timestamps);
expect(timeInterval).toEqual('30minutes');
expect(format(timestamps, timeInterval, timeScaleDefaultOptions)).toEqual(
formattedTicks
);
});
it('should format ticks with timeInterval hourly', () => {
// hourly with default formats
const datasetDefaultFormats: Dataset = [
[new Date(2020, 11, 10, 22, 0), 'Dec 10, 10 PM'],
[new Date(2020, 11, 10, 23, 0), '11 PM'],
[new Date(2020, 11, 11, 0, 0), 'Dec 11, 12 AM'],
[new Date(2020, 11, 11, 1, 0), '01 AM'],
[new Date(2020, 11, 11, 2, 0), '02 AM'],
[new Date(2020, 11, 11, 3, 0), '03 AM'],
[new Date(2020, 11, 11, 4, 0), '04 AM'],
[new Date(2020, 11, 11, 11, 0), '11 AM'],
[new Date(2020, 11, 11, 12, 0), '12 PM'],
[new Date(2020, 11, 11, 13, 0), '01 PM'],
[new Date(2020, 11, 11, 14, 0), '02 PM'],
[new Date(2020, 11, 11, 15, 0), '03 PM'],
];
const {
timestamps: timestampsDefaultFormats,
formattedTicks: formattedTicksDefaultFormats,
} = getTimestampsAndFormattedTicks(datasetDefaultFormats);
const timeIntervalDefaultFormats = computeTimeIntervalName(
timestampsDefaultFormats
);
expect(timeIntervalDefaultFormats).toEqual('hourly');
expect(
format(
timestampsDefaultFormats,
timeIntervalDefaultFormats,
timeScaleDefaultOptions
)
).toEqual(formattedTicksDefaultFormats);
// hourly with custom formats
const datasetCustomFormats: Dataset = [
[new Date(2020, 11, 10, 22, 0), 'Dec 10, 22:00'],
[new Date(2020, 11, 10, 23, 0), '23:00'],
[new Date(2020, 11, 11, 0, 0), 'Dec 11, 00:00'],
[new Date(2020, 11, 11, 1, 0), '01:00'],
[new Date(2020, 11, 11, 2, 0), '02:00'],
[new Date(2020, 11, 11, 3, 0), '03:00'],
[new Date(2020, 11, 11, 4, 0), '04:00'],
[new Date(2020, 11, 11, 11, 0), '11:00'],
[new Date(2020, 11, 11, 12, 0), '12:00'],
[new Date(2020, 11, 11, 13, 0), '13:00'],
[new Date(2020, 11, 11, 14, 0), '14:00'],
[new Date(2020, 11, 11, 15, 0), '15:00'],
];
const {
timestamps: timestampsCustomFormats,
formattedTicks: formattedTicksCustomFormats,
} = getTimestampsAndFormattedTicks(datasetCustomFormats);
const timeIntervalCustomFormats = computeTimeIntervalName(
timestampsCustomFormats
);
expect(timeIntervalCustomFormats).toEqual('hourly');
const timeScaleCustomOptions = {
...timeScaleDefaultOptions,
timeIntervalFormats: {
hourly: { primary: 'MMM d, HH:mm', secondary: 'HH:mm' },
},
};
expect(
format(
timestampsCustomFormats,
timeIntervalCustomFormats,
timeScaleCustomOptions
)
).toEqual(formattedTicksCustomFormats);
});
it('should format ticks with timeInterval daily', () => {
const dataset: Dataset = [
[new Date(2019, 11, 30), 'Dec 30'],
[new Date(2019, 11, 31), '31'],
[new Date(2020, 0, 1), 'Jan 1'],
[new Date(2020, 0, 2), '2'],
[new Date(2020, 0, 3), '3'],
[new Date(2020, 0, 4), '4'],
[new Date(2020, 0, 5), '5'],
[new Date(2020, 0, 30), '30'],
[new Date(2020, 0, 31), '31'],
[new Date(2020, 1, 1), 'Feb 1'],
[new Date(2020, 1, 2), '2'],
[new Date(2020, 1, 3), '3'],
];
const { timestamps, formattedTicks } = getTimestampsAndFormattedTicks(
dataset
);
const timeInterval = computeTimeIntervalName(timestamps);
expect(timeInterval).toEqual('daily');
expect(format(timestamps, timeInterval, timeScaleDefaultOptions)).toEqual(
formattedTicks
);
});
it('should format ticks with timeInterval weekly', () => {
const dataset: Dataset = [
[new Date(2020, 0, 27), 'Mon, Jan 27'],
[new Date(2020, 0, 28), 'Tue'],
[new Date(2020, 0, 29), 'Wed'],
[new Date(2020, 0, 30), 'Thu'],
[new Date(2020, 0, 31), 'Fri'],
[new Date(2020, 1, 1), 'Sat'],
[new Date(2020, 1, 2), 'Sun'],
[new Date(2020, 1, 3), 'Mon, Feb 3'],
[new Date(2020, 1, 4), 'Tue'],
[new Date(2020, 1, 5), 'Wed'],
[new Date(2020, 1, 6), 'Thu'],
[new Date(2020, 1, 7), 'Fri'],
];
const { timestamps, formattedTicks } = getTimestampsAndFormattedTicks(
dataset
);
const timeInterval = computeTimeIntervalName(timestamps);
expect(timeInterval).toEqual('daily');
const timeScaleCustomOptions = {
...timeScaleDefaultOptions,
showDayName: true,
};
expect(format(timestamps, timeInterval, timeScaleCustomOptions)).toEqual(
formattedTicks
);
});
it('should format ticks with timeInterval monthly', () => {
// monthly with default formats
const datasetdefaultFormats: Dataset = [
[new Date(2018, 9), 'Oct 2018'],
[new Date(2018, 10), 'Nov'],
[new Date(2018, 11), 'Dec'],
[new Date(2019, 0), 'Jan 2019'],
[new Date(2019, 1), 'Feb'],
[new Date(2019, 2), 'Mar'],
[new Date(2019, 3), 'Apr'],
[new Date(2019, 10), 'Nov'],
[new Date(2019, 11), 'Dec'],
[new Date(2020, 0), 'Jan 2020'],
[new Date(2020, 1), 'Feb'],
[new Date(2020, 2), 'Mar'],
];
const {
timestamps: timestampsdefaultFormats,
formattedTicks: formattedTicksdefaultFormats,
} = getTimestampsAndFormattedTicks(datasetdefaultFormats);
const timeIntervaldefaultFormats = computeTimeIntervalName(
timestampsdefaultFormats
);
expect(timeIntervaldefaultFormats).toEqual('monthly');
expect(
format(
timestampsdefaultFormats,
timeIntervaldefaultFormats,
timeScaleDefaultOptions
)
).toEqual(formattedTicksdefaultFormats);
// monthly with custom formats
const datasetCustomFormats: Dataset = [
[new Date(2018, 9), 'oct. 2018'],
[new Date(2018, 10), 'nov.'],
[new Date(2018, 11), 'déc.'],
[new Date(2019, 0), 'janv. 2019'],
[new Date(2019, 1), 'févr.'],
[new Date(2019, 2), 'mars'],
[new Date(2019, 3), 'avr.'],
[new Date(2019, 10), 'nov.'],
[new Date(2019, 11), 'déc.'],
[new Date(2020, 0), 'janv. 2020'],
[new Date(2020, 1), 'févr.'],
[new Date(2020, 2), 'mars'],
];
const {
timestamps: timestampsCustomFormats,
formattedTicks: formattedTicksCustomFormats,
} = getTimestampsAndFormattedTicks(datasetCustomFormats);
const timeIntervalCustomFormats = computeTimeIntervalName(
timestampsCustomFormats
);
expect(timeIntervalCustomFormats).toEqual('monthly');
const timeScaleCustomOptions = {
...timeScaleDefaultOptions,
localeObject: frLocaleObject,
};
expect(
format(
timestampsCustomFormats,
timeIntervalCustomFormats,
timeScaleCustomOptions
)
).toEqual(formattedTicksCustomFormats);
});
it('should format ticks with timeInterval quarterly', () => {
const dataset: Dataset = [
[new Date(2017, 0), `Q1 '17`],
[new Date(2017, 3), `Q2`],
[new Date(2017, 6), `Q3`],
[new Date(2017, 9), `Q4`],
[new Date(2018, 1), `Q1 '18`],
[new Date(2018, 4), `Q2`],
[new Date(2018, 7), `Q3`],
[new Date(2019, 0), `Q1 '19`],
[new Date(2019, 5), `Q2`],
[new Date(2019, 7), `Q3`],
[new Date(2019, 10), `Q4`],
[new Date(2020, 0), `Q1 '20`],
];
const { timestamps, formattedTicks } = getTimestampsAndFormattedTicks(
dataset
);
const timeInterval = computeTimeIntervalName(timestamps);
expect(timeInterval).toEqual('quarterly');
expect(format(timestamps, timeInterval, timeScaleDefaultOptions)).toEqual(
formattedTicks
);
});
it('should format ticks with timeInterval yearly', () => {
const dataset: Dataset = [
[new Date(1977, 0), '1977'],
[new Date(1978, 0), '1978'],
[new Date(1979, 0), '1979'],
[new Date(1980, 0), '1980'],
[new Date(1981, 0), '1981'],
[new Date(1982, 0), '1982'],
[new Date(1983, 0), '1983'],
[new Date(2015, 0), '2015'],
[new Date(2016, 0), '2016'],
[new Date(2017, 0), '2017'],
[new Date(2018, 0), '2018'],
[new Date(2019, 0), '2019'],
];
const { timestamps, formattedTicks } = getTimestampsAndFormattedTicks(
dataset
);
const timeInterval = computeTimeIntervalName(timestamps);
expect(timeInterval).toEqual('yearly');
expect(format(timestamps, timeInterval, timeScaleDefaultOptions)).toEqual(
formattedTicks
);
}); | the_stack |
import { AbstractParam } from "../context/AbstractParam";
import { dbToGain, gainToDb } from "../type/Conversions";
import { Decibels, Frequency, Positive, Time, UnitMap, UnitName } from "../type/Units";
import { isAudioParam } from "../util/AdvancedTypeCheck";
import { optionsFromArguments } from "../util/Defaults";
import { Timeline } from "../util/Timeline";
import { isDefined } from "../util/TypeCheck";
import { ToneWithContext, ToneWithContextOptions } from "./ToneWithContext";
import { EQ } from "../util/Math";
import { assert, assertRange } from "../util/Debug";
export interface ParamOptions<TypeName extends UnitName> extends ToneWithContextOptions {
units: TypeName;
value?: UnitMap[TypeName];
param: AudioParam | Param<TypeName>;
convert: boolean;
minValue?: number;
maxValue?: number;
swappable?: boolean;
}
/**
* the possible automation types
*/
type AutomationType = "linearRampToValueAtTime" | "exponentialRampToValueAtTime" | "setValueAtTime" | "setTargetAtTime" | "cancelScheduledValues";
interface TargetAutomationEvent {
type: "setTargetAtTime";
time: number;
value: number;
constant: number;
}
interface NormalAutomationEvent {
type: Exclude<AutomationType, "setTargetAtTime">;
time: number;
value: number;
}
/**
* The events on the automation
*/
export type AutomationEvent = NormalAutomationEvent | TargetAutomationEvent;
/**
* Param wraps the native Web Audio's AudioParam to provide
* additional unit conversion functionality. It also
* serves as a base-class for classes which have a single,
* automatable parameter.
* @category Core
*/
export class Param<TypeName extends UnitName = "number">
extends ToneWithContext<ParamOptions<TypeName>>
implements AbstractParam<TypeName> {
readonly name: string = "Param";
readonly input: GainNode | AudioParam;
readonly units: UnitName;
convert: boolean;
overridden = false;
/**
* The timeline which tracks all of the automations.
*/
protected _events: Timeline<AutomationEvent>;
/**
* The native parameter to control
*/
protected _param: AudioParam;
/**
* The default value before anything is assigned
*/
protected _initialValue: number;
/**
* The minimum output value
*/
private _minOutput = 1e-7;
/**
* Private reference to the min and max values if passed into the constructor
*/
private readonly _minValue?: number;
private readonly _maxValue?: number;
/**
* If the underlying AudioParam can be swapped out
* using the setParam method.
*/
protected readonly _swappable: boolean;
/**
* @param param The AudioParam to wrap
* @param units The unit name
* @param convert Whether or not to convert the value to the target units
*/
constructor(param: AudioParam, units?: TypeName, convert?: boolean);
constructor(options: Partial<ParamOptions<TypeName>>);
constructor() {
super(optionsFromArguments(Param.getDefaults(), arguments, ["param", "units", "convert"]));
const options = optionsFromArguments(Param.getDefaults(), arguments, ["param", "units", "convert"]);
assert(isDefined(options.param) &&
(isAudioParam(options.param) || options.param instanceof Param), "param must be an AudioParam");
while (!isAudioParam(options.param)) {
options.param = options.param._param;
}
this._swappable = isDefined(options.swappable) ? options.swappable : false;
if (this._swappable) {
this.input = this.context.createGain();
// initialize
this._param = options.param;
this.input.connect(this._param);
} else {
this._param = this.input = options.param;
}
this._events = new Timeline<AutomationEvent>(1000);
this._initialValue = this._param.defaultValue;
this.units = options.units;
this.convert = options.convert;
this._minValue = options.minValue;
this._maxValue = options.maxValue;
// if the value is defined, set it immediately
if (isDefined(options.value) && options.value !== this._toType(this._initialValue)) {
this.setValueAtTime(options.value, 0);
}
}
static getDefaults(): ParamOptions<any> {
return Object.assign(ToneWithContext.getDefaults(), {
convert: true,
units: "number" as UnitName,
} as ParamOptions<any>);
}
get value(): UnitMap[TypeName] {
const now = this.now();
return this.getValueAtTime(now);
}
set value(value) {
this.cancelScheduledValues(this.now());
this.setValueAtTime(value, this.now());
}
get minValue(): number {
// if it's not the default minValue, return it
if (isDefined(this._minValue)) {
return this._minValue;
} else if (this.units === "time" || this.units === "frequency" ||
this.units === "normalRange" || this.units === "positive" ||
this.units === "transportTime" || this.units === "ticks" ||
this.units === "bpm" || this.units === "hertz" || this.units === "samples") {
return 0;
} else if (this.units === "audioRange") {
return -1;
} else if (this.units === "decibels") {
return -Infinity;
} else {
return this._param.minValue;
}
}
get maxValue(): number {
if (isDefined(this._maxValue)) {
return this._maxValue;
} else if (this.units === "normalRange" ||
this.units === "audioRange") {
return 1;
} else {
return this._param.maxValue;
}
}
/**
* Type guard based on the unit name
*/
private _is<T>(arg: any, type: UnitName): arg is T {
return this.units === type;
}
/**
* Make sure the value is always in the defined range
*/
private _assertRange(value: number): number {
if (isDefined(this.maxValue) && isDefined(this.minValue)) {
assertRange(value, this._fromType(this.minValue), this._fromType(this.maxValue));
}
return value;
}
/**
* Convert the given value from the type specified by Param.units
* into the destination value (such as Gain or Frequency).
*/
protected _fromType(val: UnitMap[TypeName]): number {
if (this.convert && !this.overridden) {
if (this._is<Time>(val, "time")) {
return this.toSeconds(val);
} else if (this._is<Decibels>(val, "decibels")) {
return dbToGain(val);
} else if (this._is<Frequency>(val, "frequency")) {
return this.toFrequency(val);
} else {
return val as number;
}
} else if (this.overridden) {
// if it's overridden, should only schedule 0s
return 0;
} else {
return val as number;
}
}
/**
* Convert the parameters value into the units specified by Param.units.
*/
protected _toType(val: number): UnitMap[TypeName] {
if (this.convert && this.units === "decibels") {
return gainToDb(val) as UnitMap[TypeName];
} else {
return val as UnitMap[TypeName];
}
}
//-------------------------------------
// ABSTRACT PARAM INTERFACE
// all docs are generated from ParamInterface.ts
//-------------------------------------
setValueAtTime(value: UnitMap[TypeName], time: Time): this {
const computedTime = this.toSeconds(time);
const numericValue = this._fromType(value);
assert(isFinite(numericValue) && isFinite(computedTime),
`Invalid argument(s) to setValueAtTime: ${JSON.stringify(value)}, ${JSON.stringify(time)}`);
this._assertRange(numericValue);
this.log(this.units, "setValueAtTime", value, computedTime);
this._events.add({
time: computedTime,
type: "setValueAtTime",
value: numericValue,
});
this._param.setValueAtTime(numericValue, computedTime);
return this;
}
getValueAtTime(time: Time): UnitMap[TypeName] {
const computedTime = Math.max(this.toSeconds(time), 0);
const after = this._events.getAfter(computedTime);
const before = this._events.get(computedTime);
let value = this._initialValue;
// if it was set by
if (before === null) {
value = this._initialValue;
} else if (before.type === "setTargetAtTime" && (after === null || after.type === "setValueAtTime")) {
const previous = this._events.getBefore(before.time);
let previousVal;
if (previous === null) {
previousVal = this._initialValue;
} else {
previousVal = previous.value;
}
if (before.type === "setTargetAtTime") {
value = this._exponentialApproach(before.time, previousVal, before.value, before.constant, computedTime);
}
} else if (after === null) {
value = before.value;
} else if (after.type === "linearRampToValueAtTime" || after.type === "exponentialRampToValueAtTime") {
let beforeValue = before.value;
if (before.type === "setTargetAtTime") {
const previous = this._events.getBefore(before.time);
if (previous === null) {
beforeValue = this._initialValue;
} else {
beforeValue = previous.value;
}
}
if (after.type === "linearRampToValueAtTime") {
value = this._linearInterpolate(before.time, beforeValue, after.time, after.value, computedTime);
} else {
value = this._exponentialInterpolate(before.time, beforeValue, after.time, after.value, computedTime);
}
} else {
value = before.value;
}
return this._toType(value);
}
setRampPoint(time: Time): this {
time = this.toSeconds(time);
let currentVal = this.getValueAtTime(time);
this.cancelAndHoldAtTime(time);
if (this._fromType(currentVal) === 0) {
currentVal = this._toType(this._minOutput);
}
this.setValueAtTime(currentVal, time);
return this;
}
linearRampToValueAtTime(value: UnitMap[TypeName], endTime: Time): this {
const numericValue = this._fromType(value);
const computedTime = this.toSeconds(endTime);
assert(isFinite(numericValue) && isFinite(computedTime),
`Invalid argument(s) to linearRampToValueAtTime: ${JSON.stringify(value)}, ${JSON.stringify(endTime)}`);
this._assertRange(numericValue);
this._events.add({
time: computedTime,
type: "linearRampToValueAtTime",
value: numericValue,
});
this.log(this.units, "linearRampToValueAtTime", value, computedTime);
this._param.linearRampToValueAtTime(numericValue, computedTime);
return this;
}
exponentialRampToValueAtTime(value: UnitMap[TypeName], endTime: Time): this {
let numericValue = this._fromType(value);
// the value can't be 0
numericValue = EQ(numericValue, 0) ? this._minOutput : numericValue;
this._assertRange(numericValue);
const computedTime = this.toSeconds(endTime);
assert(isFinite(numericValue) && isFinite(computedTime),
`Invalid argument(s) to exponentialRampToValueAtTime: ${JSON.stringify(value)}, ${JSON.stringify(endTime)}`);
// store the event
this._events.add({
time: computedTime,
type: "exponentialRampToValueAtTime",
value: numericValue,
});
this.log(this.units, "exponentialRampToValueAtTime", value, computedTime);
this._param.exponentialRampToValueAtTime(numericValue, computedTime);
return this;
}
exponentialRampTo(value: UnitMap[TypeName], rampTime: Time, startTime?: Time): this {
startTime = this.toSeconds(startTime);
this.setRampPoint(startTime);
this.exponentialRampToValueAtTime(value, startTime + this.toSeconds(rampTime));
return this;
}
linearRampTo(value: UnitMap[TypeName], rampTime: Time, startTime?: Time): this {
startTime = this.toSeconds(startTime);
this.setRampPoint(startTime);
this.linearRampToValueAtTime(value, startTime + this.toSeconds(rampTime));
return this;
}
targetRampTo(value: UnitMap[TypeName], rampTime: Time, startTime?: Time): this {
startTime = this.toSeconds(startTime);
this.setRampPoint(startTime);
this.exponentialApproachValueAtTime(value, startTime, rampTime);
return this;
}
exponentialApproachValueAtTime(value: UnitMap[TypeName], time: Time, rampTime: Time): this {
time = this.toSeconds(time);
rampTime = this.toSeconds(rampTime);
const timeConstant = Math.log(rampTime + 1) / Math.log(200);
this.setTargetAtTime(value, time, timeConstant);
// at 90% start a linear ramp to the final value
this.cancelAndHoldAtTime(time + rampTime * 0.9);
this.linearRampToValueAtTime(value, time + rampTime);
return this;
}
setTargetAtTime(value: UnitMap[TypeName], startTime: Time, timeConstant: Positive): this {
const numericValue = this._fromType(value);
// The value will never be able to approach without timeConstant > 0.
assert(isFinite(timeConstant) && timeConstant > 0, "timeConstant must be a number greater than 0");
const computedTime = this.toSeconds(startTime);
this._assertRange(numericValue);
assert(isFinite(numericValue) && isFinite(computedTime),
`Invalid argument(s) to setTargetAtTime: ${JSON.stringify(value)}, ${JSON.stringify(startTime)}`);
this._events.add({
constant: timeConstant,
time: computedTime,
type: "setTargetAtTime",
value: numericValue,
});
this.log(this.units, "setTargetAtTime", value, computedTime, timeConstant);
this._param.setTargetAtTime(numericValue, computedTime, timeConstant);
return this;
}
setValueCurveAtTime(values: UnitMap[TypeName][], startTime: Time, duration: Time, scaling = 1): this {
duration = this.toSeconds(duration);
startTime = this.toSeconds(startTime);
const startingValue = this._fromType(values[0]) * scaling;
this.setValueAtTime(this._toType(startingValue), startTime);
const segTime = duration / (values.length - 1);
for (let i = 1; i < values.length; i++) {
const numericValue = this._fromType(values[i]) * scaling;
this.linearRampToValueAtTime(this._toType(numericValue), startTime + i * segTime);
}
return this;
}
cancelScheduledValues(time: Time): this {
const computedTime = this.toSeconds(time);
assert(isFinite(computedTime), `Invalid argument to cancelScheduledValues: ${JSON.stringify(time)}`);
this._events.cancel(computedTime);
this._param.cancelScheduledValues(computedTime);
this.log(this.units, "cancelScheduledValues", computedTime);
return this;
}
cancelAndHoldAtTime(time: Time): this {
const computedTime = this.toSeconds(time);
const valueAtTime = this._fromType(this.getValueAtTime(computedTime));
// remove the schedule events
assert(isFinite(computedTime), `Invalid argument to cancelAndHoldAtTime: ${JSON.stringify(time)}`);
this.log(this.units, "cancelAndHoldAtTime", computedTime, "value=" + valueAtTime);
// if there is an event at the given computedTime
// and that even is not a "set"
const before = this._events.get(computedTime);
const after = this._events.getAfter(computedTime);
if (before && EQ(before.time, computedTime)) {
// remove everything after
if (after) {
this._param.cancelScheduledValues(after.time);
this._events.cancel(after.time);
} else {
this._param.cancelAndHoldAtTime(computedTime);
this._events.cancel(computedTime + this.sampleTime);
}
} else if (after) {
this._param.cancelScheduledValues(after.time);
// cancel the next event(s)
this._events.cancel(after.time);
if (after.type === "linearRampToValueAtTime") {
this.linearRampToValueAtTime(this._toType(valueAtTime), computedTime);
} else if (after.type === "exponentialRampToValueAtTime") {
this.exponentialRampToValueAtTime(this._toType(valueAtTime), computedTime);
}
}
// set the value at the given time
this._events.add({
time: computedTime,
type: "setValueAtTime",
value: valueAtTime,
});
this._param.setValueAtTime(valueAtTime, computedTime);
return this;
}
rampTo(value: UnitMap[TypeName], rampTime: Time = 0.1, startTime?: Time): this {
if (this.units === "frequency" || this.units === "bpm" || this.units === "decibels") {
this.exponentialRampTo(value, rampTime, startTime);
} else {
this.linearRampTo(value, rampTime, startTime);
}
return this;
}
/**
* Apply all of the previously scheduled events to the passed in Param or AudioParam.
* The applied values will start at the context's current time and schedule
* all of the events which are scheduled on this Param onto the passed in param.
*/
apply(param: Param | AudioParam): this {
const now = this.context.currentTime;
// set the param's value at the current time and schedule everything else
param.setValueAtTime(this.getValueAtTime(now) as number, now);
// if the previous event was a curve, then set the rest of it
const previousEvent = this._events.get(now);
if (previousEvent && previousEvent.type === "setTargetAtTime") {
// approx it until the next event with linear ramps
const nextEvent = this._events.getAfter(previousEvent.time);
// or for 2 seconds if there is no event
const endTime = nextEvent ? nextEvent.time : now + 2;
const subdivisions = (endTime - now) / 10;
for (let i = now; i < endTime; i += subdivisions) {
param.linearRampToValueAtTime(this.getValueAtTime(i) as number, i);
}
}
this._events.forEachAfter(this.context.currentTime, event => {
if (event.type === "cancelScheduledValues") {
param.cancelScheduledValues(event.time);
} else if (event.type === "setTargetAtTime") {
param.setTargetAtTime(event.value, event.time, event.constant);
} else {
param[event.type](event.value, event.time);
}
});
return this;
}
/**
* Replace the Param's internal AudioParam. Will apply scheduled curves
* onto the parameter and replace the connections.
*/
setParam(param: AudioParam): this {
assert(this._swappable, "The Param must be assigned as 'swappable' in the constructor");
const input = this.input as GainNode;
input.disconnect(this._param);
this.apply(param);
this._param = param;
input.connect(this._param);
return this;
}
dispose(): this {
super.dispose();
this._events.dispose();
return this;
}
get defaultValue(): UnitMap[TypeName] {
return this._toType(this._param.defaultValue);
}
//-------------------------------------
// AUTOMATION CURVE CALCULATIONS
// MIT License, copyright (c) 2014 Jordan Santell
//-------------------------------------
// Calculates the the value along the curve produced by setTargetAtTime
protected _exponentialApproach(t0: number, v0: number, v1: number, timeConstant: number, t: number): number {
return v1 + (v0 - v1) * Math.exp(-(t - t0) / timeConstant);
}
// Calculates the the value along the curve produced by linearRampToValueAtTime
protected _linearInterpolate(t0: number, v0: number, t1: number, v1: number, t: number): number {
return v0 + (v1 - v0) * ((t - t0) / (t1 - t0));
}
// Calculates the the value along the curve produced by exponentialRampToValueAtTime
protected _exponentialInterpolate(t0: number, v0: number, t1: number, v1: number, t: number): number {
return v0 * Math.pow(v1 / v0, (t - t0) / (t1 - t0));
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Creates a [Flex Template](https://cloud.google.com/dataflow/docs/guides/templates/using-flex-templates)
* job on Dataflow, which is an implementation of Apache Beam running on Google
* Compute Engine. For more information see the official documentation for [Beam](https://beam.apache.org)
* and [Dataflow](https://cloud.google.com/dataflow/).
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const bigDataJob = new gcp.dataflow.FlexTemplateJob("bigDataJob", {
* containerSpecGcsPath: "gs://my-bucket/templates/template.json",
* parameters: {
* inputSubscription: "messages",
* },
* }, {
* provider: google_beta,
* });
* ```
* ## Note on "destroy" / "apply"
*
* There are many types of Dataflow jobs. Some Dataflow jobs run constantly,
* getting new data from (e.g.) a GCS bucket, and outputting data continuously.
* Some jobs process a set amount of data then terminate. All jobs can fail while
* running due to programming errors or other issues. In this way, Dataflow jobs
* are different from most other provider / Google resources.
*
* The Dataflow resource is considered 'existing' while it is in a nonterminal
* state. If it reaches a terminal state (e.g. 'FAILED', 'COMPLETE',
* 'CANCELLED'), it will be recreated on the next 'apply'. This is as expected for
* jobs which run continuously, but may surprise users who use this resource for
* other kinds of Dataflow jobs.
*
* A Dataflow job which is 'destroyed' may be "cancelled" or "drained". If
* "cancelled", the job terminates - any data written remains where it is, but no
* new data will be processed. If "drained", no new data will enter the pipeline,
* but any data currently in the pipeline will finish being processed. The default
* is "cancelled", but if a user sets `onDelete` to `"drain"` in the
* configuration, you may experience a long wait for your `pulumi destroy` to
* complete.
*
* ## Import
*
* This resource does not support import.
*/
export class FlexTemplateJob extends pulumi.CustomResource {
/**
* Get an existing FlexTemplateJob 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?: FlexTemplateJobState, opts?: pulumi.CustomResourceOptions): FlexTemplateJob {
return new FlexTemplateJob(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:dataflow/flexTemplateJob:FlexTemplateJob';
/**
* Returns true if the given object is an instance of FlexTemplateJob. 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 FlexTemplateJob {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === FlexTemplateJob.__pulumiType;
}
/**
* The GCS path to the Dataflow job Flex
* Template.
*/
public readonly containerSpecGcsPath!: pulumi.Output<string>;
/**
* The unique ID of this job.
*/
public /*out*/ readonly jobId!: pulumi.Output<string>;
/**
* User labels to be specified for the job. Keys and values
* should follow the restrictions specified in the [labeling restrictions](https://cloud.google.com/compute/docs/labeling-resources#restrictions)
* page. **Note**: This field is marked as deprecated as the API does not currently
* support adding labels.
* **NOTE**: Google-provided Dataflow templates often provide default labels
* that begin with `goog-dataflow-provided`. Unless explicitly set in config, these
* labels will be ignored to prevent diffs on re-apply.
*
* @deprecated Deprecated until the API supports this field
*/
public readonly labels!: pulumi.Output<{[key: string]: any} | undefined>;
/**
* A unique name for the resource, required by Dataflow.
*/
public readonly name!: pulumi.Output<string>;
/**
* One of "drain" or "cancel". Specifies behavior of
* deletion during `pulumi destroy`. See above note.
*/
public readonly onDelete!: pulumi.Output<string | undefined>;
/**
* Key/Value pairs to be passed to the Dataflow job (as
* used in the template). Additional [pipeline options](https://cloud.google.com/dataflow/docs/guides/specifying-exec-params#setting-other-cloud-dataflow-pipeline-options)
* such as `serviceAccount`, `workerMachineType`, etc can be specified here.
*/
public readonly parameters!: pulumi.Output<{[key: string]: any} | undefined>;
/**
* The project in which the resource belongs. If it is not
* provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* The region in which the created job should run.
*/
public readonly region!: pulumi.Output<string>;
/**
* The current state of the resource, selected from the [JobState enum](https://cloud.google.com/dataflow/docs/reference/rest/v1b3/projects.jobs#Job.JobState)
*/
public /*out*/ readonly state!: pulumi.Output<string>;
/**
* Create a FlexTemplateJob 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: FlexTemplateJobArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: FlexTemplateJobArgs | FlexTemplateJobState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as FlexTemplateJobState | undefined;
inputs["containerSpecGcsPath"] = state ? state.containerSpecGcsPath : undefined;
inputs["jobId"] = state ? state.jobId : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["onDelete"] = state ? state.onDelete : undefined;
inputs["parameters"] = state ? state.parameters : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["region"] = state ? state.region : undefined;
inputs["state"] = state ? state.state : undefined;
} else {
const args = argsOrState as FlexTemplateJobArgs | undefined;
if ((!args || args.containerSpecGcsPath === undefined) && !opts.urn) {
throw new Error("Missing required property 'containerSpecGcsPath'");
}
inputs["containerSpecGcsPath"] = args ? args.containerSpecGcsPath : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["onDelete"] = args ? args.onDelete : undefined;
inputs["parameters"] = args ? args.parameters : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["region"] = args ? args.region : undefined;
inputs["jobId"] = undefined /*out*/;
inputs["state"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(FlexTemplateJob.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering FlexTemplateJob resources.
*/
export interface FlexTemplateJobState {
/**
* The GCS path to the Dataflow job Flex
* Template.
*/
containerSpecGcsPath?: pulumi.Input<string>;
/**
* The unique ID of this job.
*/
jobId?: pulumi.Input<string>;
/**
* User labels to be specified for the job. Keys and values
* should follow the restrictions specified in the [labeling restrictions](https://cloud.google.com/compute/docs/labeling-resources#restrictions)
* page. **Note**: This field is marked as deprecated as the API does not currently
* support adding labels.
* **NOTE**: Google-provided Dataflow templates often provide default labels
* that begin with `goog-dataflow-provided`. Unless explicitly set in config, these
* labels will be ignored to prevent diffs on re-apply.
*
* @deprecated Deprecated until the API supports this field
*/
labels?: pulumi.Input<{[key: string]: any}>;
/**
* A unique name for the resource, required by Dataflow.
*/
name?: pulumi.Input<string>;
/**
* One of "drain" or "cancel". Specifies behavior of
* deletion during `pulumi destroy`. See above note.
*/
onDelete?: pulumi.Input<string>;
/**
* Key/Value pairs to be passed to the Dataflow job (as
* used in the template). Additional [pipeline options](https://cloud.google.com/dataflow/docs/guides/specifying-exec-params#setting-other-cloud-dataflow-pipeline-options)
* such as `serviceAccount`, `workerMachineType`, etc can be specified here.
*/
parameters?: pulumi.Input<{[key: string]: any}>;
/**
* The project in which the resource belongs. If it is not
* provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The region in which the created job should run.
*/
region?: pulumi.Input<string>;
/**
* The current state of the resource, selected from the [JobState enum](https://cloud.google.com/dataflow/docs/reference/rest/v1b3/projects.jobs#Job.JobState)
*/
state?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a FlexTemplateJob resource.
*/
export interface FlexTemplateJobArgs {
/**
* The GCS path to the Dataflow job Flex
* Template.
*/
containerSpecGcsPath: pulumi.Input<string>;
/**
* User labels to be specified for the job. Keys and values
* should follow the restrictions specified in the [labeling restrictions](https://cloud.google.com/compute/docs/labeling-resources#restrictions)
* page. **Note**: This field is marked as deprecated as the API does not currently
* support adding labels.
* **NOTE**: Google-provided Dataflow templates often provide default labels
* that begin with `goog-dataflow-provided`. Unless explicitly set in config, these
* labels will be ignored to prevent diffs on re-apply.
*
* @deprecated Deprecated until the API supports this field
*/
labels?: pulumi.Input<{[key: string]: any}>;
/**
* A unique name for the resource, required by Dataflow.
*/
name?: pulumi.Input<string>;
/**
* One of "drain" or "cancel". Specifies behavior of
* deletion during `pulumi destroy`. See above note.
*/
onDelete?: pulumi.Input<string>;
/**
* Key/Value pairs to be passed to the Dataflow job (as
* used in the template). Additional [pipeline options](https://cloud.google.com/dataflow/docs/guides/specifying-exec-params#setting-other-cloud-dataflow-pipeline-options)
* such as `serviceAccount`, `workerMachineType`, etc can be specified here.
*/
parameters?: pulumi.Input<{[key: string]: any}>;
/**
* The project in which the resource belongs. If it is not
* provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The region in which the created job should run.
*/
region?: pulumi.Input<string>;
} | the_stack |
import chalk, { Chalk } from 'chalk'
/**
* A generic interface that holds all available language tokens.
*/
export interface Tokens<T> {
/**
* keyword in a regular Algol-style language
*/
keyword?: T
/**
* built-in or library object (constant, class, function)
*/
built_in?: T
/**
* user-defined type in a language with first-class syntactically significant types, like Haskell
*/
type?: T
/**
* special identifier for a built-in value ("true", "false", "null")
*/
literal?: T
/**
* number, including units and modifiers, if any.
*/
number?: T
/**
* literal regular expression
*/
regexp?: T
/**
* literal string, character
*/
string?: T
/**
* parsed section inside a literal string
*/
subst?: T
/**
* symbolic constant, interned string, goto label
*/
symbol?: T
/**
* class or class-level declaration (interfaces, traits, modules, etc)
*/
class?: T
/**
* function or method declaration
*/
function?: T
/**
* name of a class or a function at the place of declaration
*/
title?: T
/**
* block of function arguments (parameters) at the place of declaration
*/
params?: T
/**
* comment
*/
comment?: T
/**
* documentation markup within comments
*/
doctag?: T
/**
* flags, modifiers, annotations, processing instructions, preprocessor directive, etc
*/
meta?: T
/**
* keyword or built-in within meta construct
*/
'meta-keyword'?: T
/**
* string within meta construct
*/
'meta-string'?: T
/**
* heading of a section in a config file, heading in text markup
*/
section?: T
/**
* XML/HTML tag
*/
tag?: T
/**
* name of an XML tag, the first word in an s-expression
*/
name?: T
/**
* s-expression name from the language standard library
*/
'builtin-name'?: T
/**
* name of an attribute with no language defined semantics (keys in JSON, setting names in .ini), also sub-attribute within another highlighted object, like XML tag
*/
attr?: T
/**
* name of an attribute followed by a structured value part, like CSS properties
*/
attribute?: T
/**
* variable in a config or a template file, environment var expansion in a script
*/
variable?: T
/**
* list item bullet in text markup
*/
bullet?: T
/**
* code block in text markup
*/
code?: T
/**
* emphasis in text markup
*/
emphasis?: T
/**
* strong emphasis in text markup
*/
strong?: T
/**
* mathematical formula in text markup
*/
formula?: T
/**
* hyperlink in text markup
*/
link?: T
/**
* quotation in text markup
*/
quote?: T
/**
* tag selector in CSS
*/
'selector-tag'?: T
/**
* #id selector in CSS
*/
'selector-id'?: T
/**
* .class selector in CSS
*/
'selector-class'?: T
/**
* [attr] selector in CSS
*/
'selector-attr'?: T
/**
* :pseudo selector in CSS
*/
'selector-pseudo'?: T
/**
* tag of a template language
*/
'template-tag'?: T
/**
* variable in a template language
*/
'template-variable'?: T
/**
* added or changed line in a diff
*/
addition?: T
/**
* deleted line in a diff
*/
deletion?: T
}
/**
* Possible styles that can be used on a token in a JSON theme.
* See the [chalk](https://github.com/chalk/chalk) module for more information.
* `plain` means no styling.
*/
export type Style =
| 'reset'
| 'bold'
| 'dim'
| 'italic'
| 'underline'
| 'inverse'
| 'hidden'
| 'strikethrough'
| 'black'
| 'red'
| 'green'
| 'yellow'
| 'blue'
| 'magenta'
| 'cyan'
| 'white'
| 'gray'
| 'bgBlack'
| 'bgRed'
| 'bgGreen'
| 'bgYellow'
| 'bgBlue'
| 'bgMagenta'
| 'bgCyan'
| 'plain'
/**
* The schema of a JSON file defining a custom scheme. The key is a language token, while the value
* is a [chalk](https://github.com/chalk/chalk#styles) style.
*
* Example:
* ```json
* {
* "keyword": ["red", "bold"],
* "addition": "green",
* "deletion": ["red", "strikethrough"],
* "number": "plain"
* }
* ```
*/
export interface JsonTheme extends Tokens<Style | Style[]> {}
/**
* Passed to [[highlight]] as the `theme` option. A theme is a map of language tokens to a function
* that takes in string value of the token and returns a new string with colorization applied
* (typically a [chalk](https://github.com/chalk/chalk) style), but you can also provide your own
* formatting functions.
*
* Example:
* ```ts
* import {Theme, plain} from 'cli-highlight';
* import chalk = require('chalk');
*
* const myTheme: Theme = {
* keyword: chalk.red.bold,
* addition: chalk.green,
* deletion: chalk.red.strikethrough,
* number: plain
* };
* ```
*/
export interface Theme extends Tokens<(codePart: string) => string> {
/**
* things not matched by any token
*/
default?: (codePart: string) => string
}
/**
* Identity function for tokens that should not be styled (returns the input string as-is).
* See [[Theme]] for an example.
*/
export const plain = (codePart: string): string => codePart
/**
* The default theme. It is possible to override just individual keys.
*/
export const DEFAULT_THEME: Theme = {
/**
* keyword in a regular Algol-style language
*/
keyword: chalk.blue,
/**
* built-in or library object (constant, class, function)
*/
built_in: chalk.cyan,
/**
* user-defined type in a language with first-class syntactically significant types, like
* Haskell
*/
type: chalk.cyan.dim,
/**
* special identifier for a built-in value ("true", "false", "null")
*/
literal: chalk.blue,
/**
* number, including units and modifiers, if any.
*/
number: chalk.green,
/**
* literal regular expression
*/
regexp: chalk.red,
/**
* literal string, character
*/
string: chalk.red,
/**
* parsed section inside a literal string
*/
subst: plain,
/**
* symbolic constant, interned string, goto label
*/
symbol: plain,
/**
* class or class-level declaration (interfaces, traits, modules, etc)
*/
class: chalk.blue,
/**
* function or method declaration
*/
function: chalk.yellow,
/**
* name of a class or a function at the place of declaration
*/
title: plain,
/**
* block of function arguments (parameters) at the place of declaration
*/
params: plain,
/**
* comment
*/
comment: chalk.green,
/**
* documentation markup within comments
*/
doctag: chalk.green,
/**
* flags, modifiers, annotations, processing instructions, preprocessor directive, etc
*/
meta: chalk.grey,
/**
* keyword or built-in within meta construct
*/
'meta-keyword': plain,
/**
* string within meta construct
*/
'meta-string': plain,
/**
* heading of a section in a config file, heading in text markup
*/
section: plain,
/**
* XML/HTML tag
*/
tag: chalk.grey,
/**
* name of an XML tag, the first word in an s-expression
*/
name: chalk.blue,
/**
* s-expression name from the language standard library
*/
'builtin-name': plain,
/**
* name of an attribute with no language defined semantics (keys in JSON, setting names in
* .ini), also sub-attribute within another highlighted object, like XML tag
*/
attr: chalk.cyan,
/**
* name of an attribute followed by a structured value part, like CSS properties
*/
attribute: plain,
/**
* variable in a config or a template file, environment var expansion in a script
*/
variable: plain,
/**
* list item bullet in text markup
*/
bullet: plain,
/**
* code block in text markup
*/
code: plain,
/**
* emphasis in text markup
*/
emphasis: chalk.italic,
/**
* strong emphasis in text markup
*/
strong: chalk.bold,
/**
* mathematical formula in text markup
*/
formula: plain,
/**
* hyperlink in text markup
*/
link: chalk.underline,
/**
* quotation in text markup
*/
quote: plain,
/**
* tag selector in CSS
*/
'selector-tag': plain,
/**
* #id selector in CSS
*/
'selector-id': plain,
/**
* .class selector in CSS
*/
'selector-class': plain,
/**
* [attr] selector in CSS
*/
'selector-attr': plain,
/**
* :pseudo selector in CSS
*/
'selector-pseudo': plain,
/**
* tag of a template language
*/
'template-tag': plain,
/**
* variable in a template language
*/
'template-variable': plain,
/**
* added or changed line in a diff
*/
addition: chalk.green,
/**
* deleted line in a diff
*/
deletion: chalk.red,
/**
* things not matched by any token
*/
default: plain,
}
/**
* Converts a [[JsonTheme]] with string values to a [[Theme]] with formatter functions. Used by [[parse]].
*/
export function fromJson(json: JsonTheme): Theme {
const theme: Theme = {}
for (const key of Object.keys(json)) {
const style: string | string[] = (json as any)[key]
if (Array.isArray(style)) {
;(theme as any)[key] = style.reduce(
(previous: typeof chalk, current: string) => (current === 'plain' ? plain : (previous as any)[current]),
chalk
)
} else {
;(theme as any)[key] = (chalk as any)[style]
}
}
return theme
}
/**
* Converts a [[Theme]] with formatter functions to a [[JsonTheme]] with string values. Used by [[stringify]].
*/
export function toJson(theme: Theme): JsonTheme {
const jsonTheme: any = {}
for (const key of Object.keys(jsonTheme)) {
const style: Chalk & { _styles: string[] } = (jsonTheme as any)[key]
jsonTheme[key] = style._styles
}
return jsonTheme
}
/**
* Stringifies a [[Theme]] with formatter functions to a JSON string.
*
* ```ts
* import chalk = require('chalk');
* import {stringify} from 'cli-highlight';
* import * as fs from 'fs';
*
* const myTheme: Theme = {
* keyword: chalk.red.bold,
* addition: chalk.green,
* deletion: chalk.red.strikethrough,
* number: plain
* }
* const json = stringify(myTheme);
* fs.writeFile('mytheme.json', json, (err: any) => {
* if (err) throw err;
* console.log('Theme saved');
* });
* ```
*/
export function stringify(theme: Theme): string {
return JSON.stringify(toJson(theme))
}
/**
* Parses a JSON string into a [[Theme]] with formatter functions.
*
* ```ts
* import * as fs from 'fs';
* import {parse, highlight} from 'cli-highlight';
*
* fs.readFile('mytheme.json', 'utf8', (err: any, json: string) => {
* if (err) throw err;
* const code = highlight('SELECT * FROM table', {theme: parse(json)});
* console.log(code);
* });
* ```
*/
export function parse(json: string): Theme {
return fromJson(JSON.parse(json))
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { JobExecutions } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { SqlManagementClient } from "../sqlManagementClient";
import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro";
import { LroImpl } from "../lroImpl";
import {
JobExecution,
JobExecutionsListByAgentNextOptionalParams,
JobExecutionsListByAgentOptionalParams,
JobExecutionsListByJobNextOptionalParams,
JobExecutionsListByJobOptionalParams,
JobExecutionsListByAgentResponse,
JobExecutionsCancelOptionalParams,
JobExecutionsCreateOptionalParams,
JobExecutionsCreateResponse,
JobExecutionsListByJobResponse,
JobExecutionsGetOptionalParams,
JobExecutionsGetResponse,
JobExecutionsCreateOrUpdateOptionalParams,
JobExecutionsCreateOrUpdateResponse,
JobExecutionsListByAgentNextResponse,
JobExecutionsListByJobNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing JobExecutions operations. */
export class JobExecutionsImpl implements JobExecutions {
private readonly client: SqlManagementClient;
/**
* Initialize a new instance of the class JobExecutions class.
* @param client Reference to the service client
*/
constructor(client: SqlManagementClient) {
this.client = client;
}
/**
* Lists all executions in a job agent.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param options The options parameters.
*/
public listByAgent(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
options?: JobExecutionsListByAgentOptionalParams
): PagedAsyncIterableIterator<JobExecution> {
const iter = this.listByAgentPagingAll(
resourceGroupName,
serverName,
jobAgentName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByAgentPagingPage(
resourceGroupName,
serverName,
jobAgentName,
options
);
}
};
}
private async *listByAgentPagingPage(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
options?: JobExecutionsListByAgentOptionalParams
): AsyncIterableIterator<JobExecution[]> {
let result = await this._listByAgent(
resourceGroupName,
serverName,
jobAgentName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByAgentNext(
resourceGroupName,
serverName,
jobAgentName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByAgentPagingAll(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
options?: JobExecutionsListByAgentOptionalParams
): AsyncIterableIterator<JobExecution> {
for await (const page of this.listByAgentPagingPage(
resourceGroupName,
serverName,
jobAgentName,
options
)) {
yield* page;
}
}
/**
* Lists a job's executions.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param options The options parameters.
*/
public listByJob(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
jobName: string,
options?: JobExecutionsListByJobOptionalParams
): PagedAsyncIterableIterator<JobExecution> {
const iter = this.listByJobPagingAll(
resourceGroupName,
serverName,
jobAgentName,
jobName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByJobPagingPage(
resourceGroupName,
serverName,
jobAgentName,
jobName,
options
);
}
};
}
private async *listByJobPagingPage(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
jobName: string,
options?: JobExecutionsListByJobOptionalParams
): AsyncIterableIterator<JobExecution[]> {
let result = await this._listByJob(
resourceGroupName,
serverName,
jobAgentName,
jobName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByJobNext(
resourceGroupName,
serverName,
jobAgentName,
jobName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByJobPagingAll(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
jobName: string,
options?: JobExecutionsListByJobOptionalParams
): AsyncIterableIterator<JobExecution> {
for await (const page of this.listByJobPagingPage(
resourceGroupName,
serverName,
jobAgentName,
jobName,
options
)) {
yield* page;
}
}
/**
* Lists all executions in a job agent.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param options The options parameters.
*/
private _listByAgent(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
options?: JobExecutionsListByAgentOptionalParams
): Promise<JobExecutionsListByAgentResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serverName, jobAgentName, options },
listByAgentOperationSpec
);
}
/**
* Requests cancellation of a job execution.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobExecutionId The id of the job execution to cancel.
* @param options The options parameters.
*/
cancel(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
jobName: string,
jobExecutionId: string,
options?: JobExecutionsCancelOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{
resourceGroupName,
serverName,
jobAgentName,
jobName,
jobExecutionId,
options
},
cancelOperationSpec
);
}
/**
* Starts an elastic job execution.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param options The options parameters.
*/
async beginCreate(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
jobName: string,
options?: JobExecutionsCreateOptionalParams
): Promise<
PollerLike<
PollOperationState<JobExecutionsCreateResponse>,
JobExecutionsCreateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<JobExecutionsCreateResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, serverName, jobAgentName, jobName, options },
createOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Starts an elastic job execution.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param options The options parameters.
*/
async beginCreateAndWait(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
jobName: string,
options?: JobExecutionsCreateOptionalParams
): Promise<JobExecutionsCreateResponse> {
const poller = await this.beginCreate(
resourceGroupName,
serverName,
jobAgentName,
jobName,
options
);
return poller.pollUntilDone();
}
/**
* Lists a job's executions.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param options The options parameters.
*/
private _listByJob(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
jobName: string,
options?: JobExecutionsListByJobOptionalParams
): Promise<JobExecutionsListByJobResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serverName, jobAgentName, jobName, options },
listByJobOperationSpec
);
}
/**
* Gets a job execution.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobExecutionId The id of the job execution
* @param options The options parameters.
*/
get(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
jobName: string,
jobExecutionId: string,
options?: JobExecutionsGetOptionalParams
): Promise<JobExecutionsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
serverName,
jobAgentName,
jobName,
jobExecutionId,
options
},
getOperationSpec
);
}
/**
* Creates or updates a job execution.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param jobExecutionId The job execution id to create the job execution under.
* @param options The options parameters.
*/
async beginCreateOrUpdate(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
jobName: string,
jobExecutionId: string,
options?: JobExecutionsCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<JobExecutionsCreateOrUpdateResponse>,
JobExecutionsCreateOrUpdateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<JobExecutionsCreateOrUpdateResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{
resourceGroupName,
serverName,
jobAgentName,
jobName,
jobExecutionId,
options
},
createOrUpdateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Creates or updates a job execution.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param jobExecutionId The job execution id to create the job execution under.
* @param options The options parameters.
*/
async beginCreateOrUpdateAndWait(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
jobName: string,
jobExecutionId: string,
options?: JobExecutionsCreateOrUpdateOptionalParams
): Promise<JobExecutionsCreateOrUpdateResponse> {
const poller = await this.beginCreateOrUpdate(
resourceGroupName,
serverName,
jobAgentName,
jobName,
jobExecutionId,
options
);
return poller.pollUntilDone();
}
/**
* ListByAgentNext
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param nextLink The nextLink from the previous successful call to the ListByAgent method.
* @param options The options parameters.
*/
private _listByAgentNext(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
nextLink: string,
options?: JobExecutionsListByAgentNextOptionalParams
): Promise<JobExecutionsListByAgentNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serverName, jobAgentName, nextLink, options },
listByAgentNextOperationSpec
);
}
/**
* ListByJobNext
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param nextLink The nextLink from the previous successful call to the ListByJob method.
* @param options The options parameters.
*/
private _listByJobNext(
resourceGroupName: string,
serverName: string,
jobAgentName: string,
jobName: string,
nextLink: string,
options?: JobExecutionsListByJobNextOptionalParams
): Promise<JobExecutionsListByJobNextResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
serverName,
jobAgentName,
jobName,
nextLink,
options
},
listByJobNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByAgentOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/executions",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.JobExecutionListResult
},
default: {}
},
queryParameters: [
Parameters.skip,
Parameters.apiVersion2,
Parameters.createTimeMin,
Parameters.createTimeMax,
Parameters.endTimeMin,
Parameters.endTimeMax,
Parameters.isActive,
Parameters.top
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.jobAgentName
],
headerParameters: [Parameters.accept],
serializer
};
const cancelOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}/cancel",
httpMethod: "POST",
responses: { 200: {}, default: {} },
queryParameters: [Parameters.apiVersion2],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.jobAgentName,
Parameters.jobName,
Parameters.jobExecutionId
],
serializer
};
const createOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/start",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.JobExecution
},
201: {
bodyMapper: Mappers.JobExecution
},
202: {
bodyMapper: Mappers.JobExecution
},
204: {
bodyMapper: Mappers.JobExecution
},
default: {}
},
queryParameters: [Parameters.apiVersion2],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.jobAgentName,
Parameters.jobName
],
headerParameters: [Parameters.accept],
serializer
};
const listByJobOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.JobExecutionListResult
},
default: {}
},
queryParameters: [
Parameters.skip,
Parameters.apiVersion2,
Parameters.createTimeMin,
Parameters.createTimeMax,
Parameters.endTimeMin,
Parameters.endTimeMax,
Parameters.isActive,
Parameters.top
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.jobAgentName,
Parameters.jobName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.JobExecution
},
default: {}
},
queryParameters: [Parameters.apiVersion2],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.jobAgentName,
Parameters.jobName,
Parameters.jobExecutionId
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.JobExecution
},
201: {
bodyMapper: Mappers.JobExecution
},
202: {
bodyMapper: Mappers.JobExecution
},
204: {
bodyMapper: Mappers.JobExecution
},
default: {}
},
queryParameters: [Parameters.apiVersion2],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.jobAgentName,
Parameters.jobName,
Parameters.jobExecutionId
],
headerParameters: [Parameters.accept],
serializer
};
const listByAgentNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.JobExecutionListResult
},
default: {}
},
queryParameters: [
Parameters.skip,
Parameters.apiVersion2,
Parameters.createTimeMin,
Parameters.createTimeMax,
Parameters.endTimeMin,
Parameters.endTimeMax,
Parameters.isActive,
Parameters.top
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.nextLink,
Parameters.jobAgentName
],
headerParameters: [Parameters.accept],
serializer
};
const listByJobNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.JobExecutionListResult
},
default: {}
},
queryParameters: [
Parameters.skip,
Parameters.apiVersion2,
Parameters.createTimeMin,
Parameters.createTimeMax,
Parameters.endTimeMin,
Parameters.endTimeMax,
Parameters.isActive,
Parameters.top
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.serverName,
Parameters.nextLink,
Parameters.jobAgentName,
Parameters.jobName
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import * as handler from '../handler/queue';
import * as arraybuffers from '../arraybuffers/arraybuffers';
import * as logging from '../logging/logging';
declare const freedom: freedom.FreedomInModuleEnv;
var log: logging.Log = new logging.Log('DataChannel');
// Messages are limited to a 16KB length by SCTP. For maximum efficiency,
// this size should match the buffer size used by Freedom's TCP connection.
// http://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-07#section-6.6
export var CHUNK_SIZE = 1024 * 16;
// The maximum amount of bytes we should allow to get queued up in
// peerconnection. Any more and we start queueing in JS. There are two reasons
// to limit this:
// 1. Data channels are closed by WebRTC when the buffer fills, so we really
// don't want that to happen accidentally. More info in this thread, which
// mentions a limit of 16MB for Chrome 37+ and 100 messages for previous versions:
// https://code.google.com/p/webrtc/issues/detail?id=2866
// 2. This limit sets the reaction time for backpressure. Having extremely fast
// backpressure reaction time is crucial to preventing a huge backlog of TCP
// data events. If CHURN is enabled, this backlog also blocks all UDP data
// transmission, and if the backlog exceeds 5 seconds, it can cause the
// PeerConnection to experience ICE disconnection.
// Setting this value to zero would give the fastest possible backpressure
// reaction time, by pausing the socket after every message, forcing a call to
// "getBufferedAmount", and only resuming the socket after the message is
// actually sent. This appears to improve our resilience to disconnection when
// downloading from super-fast servers
// (https://github.com/uProxy/uproxy/issues/1511) or loading many pages
// simultaneously. However, lowering this value to zero also effectively
// negates the performance benefits from
// https://github.com/uProxy/uproxy/issues/1474, and even further regresses
// the CPU intensity. In testing on slow sharers with ultra-fast sources,
// 64 KiB seems to be the largest safe value, and when loading many pages
// simultaneously, 16 KiB seems to be the largest safe value.
export var PC_QUEUE_LIMIT = 16 * 1024;
// Javascript has trouble representing integers larger than 2^53. So we simply
// don't support trying to send array's bigger than that.
var MAX_MESSAGE_SIZE = Math.pow(2, 53);
interface StringData { str :string; }
interface BufferData { buffer :ArrayBuffer; }
export interface DataChannel {
// Guaranteed to be invariant for the life of the data channel.
getLabel : () => string;
// Promise for when the data channel has been opened.
onceOpened : Promise<void>;
// Promise for when the data channel has been closed (only fulfilled after
// the data channel has been opened).
// NOTE: There exists a bug in Chrome prior to version 37 which prevents
// this from fulfilling on the remote peer.
onceClosed : Promise<void>;
// Data from the peer. No data will be added to the queue after |onceClosed|
// is fulfilled.
dataFromPeerQueue :handler.QueueHandler<Data, void>;
// Send data; promise returns when all the data has been passed on to the
// undertlying network layer for ending.
send(data:Data) : Promise<void>;
// Returns the number of bytes which have been passed to the browser but
// which have not yet been handed off to usrsctplib.
getBrowserBufferedAmount() : Promise<number>;
// Returns the number of bytes which have been passed to send() but
// which have not yet been handed off to the browser.
getJavascriptBufferedAmount() : number;
// Returns whether the send buffer is currently in an overflow state.
isInOverflow() : boolean;
// Registers a function that will be called whenever the browser buffer
// overflows into the javascript buffer, and whenever the overflow is
// cleared. There can only be one listener at a time. Pass null to unset.
setOverflowListener(listener:(overflow:boolean) => void) : void;
// Closes this data channel once all outgoing messages have been sent.
// A channel cannot be re-opened once this has been called.
close() : Promise<void>;
toString() : string;
}
// Data sent to or received from a peer on a data channel in the peer
// connection.
export interface Data {
str ?:string;
buffer ?:ArrayBuffer;
// TODO: add when supported by WebRtc in Chrome and FF.
// https://code.google.com/p/webrtc/issues/detail?id=2276
//
// bufferView ?:ArrayBufferView;
// blob ?:Blob
// domString ?:DOMString
}
// Wrapper for a WebRtc Data Channels:
// http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcdatachannel
//
export class DataChannelClass implements DataChannel {
public dataFromPeerQueue :handler.Queue<Data,void>;
// The |toPeerDataQueue_| is chunked by the send call and congestion
// controlled by the handler this class sets.
private toPeerDataQueue_ :handler.Queue<Data,void>;
// This is the total number of bytes in all the ArrayBuffers in
// toPeerDataQueue_.
// TODO: Count bytes in strings as well.
private toPeerDataBytes_ :number;
// This is an upper bound on |bufferedAmount|, which is updated
// (increased) on each call to send. (However, these updates do not
// account for string messages.)
private lastBrowserBufferedAmount_ :number;
public onceOpened :Promise<void>;
public onceClosed :Promise<void>;
// True iff close() has been called.
private draining_ = false;
private fulfillDrained_ :() => void;
private onceDrained_ = new Promise((F, R) => {
this.fulfillDrained_ = F;
});
// True between onceOpened and onceClosed
private isOpen_ :boolean;
private rejectOpened_ :(e:Error) => void;
private overflow_ :boolean = false;
private overflowListener_ :(overflow:boolean) => void = null;
public getLabel = () : string => { return this.label_; }
// |rtcDataChannel_| is the freedom rtc data channel.
// |label_| is the rtcDataChannel_.getLabel() result
constructor(private rtcDataChannel_:freedom.RTCDataChannel.RTCDataChannel,
private label_ = '') {
this.dataFromPeerQueue = new handler.Queue<Data,void>();
this.toPeerDataQueue_ = new handler.Queue<Data,void>();
this.toPeerDataBytes_ = 0;
this.lastBrowserBufferedAmount_ = 0;
this.onceOpened = new Promise<void>((F,R) => {
this.rejectOpened_ = R;
this.rtcDataChannel_.getReadyState().then((state:string) => {
// RTCDataChannels created by a RTCDataChannelEvent have an initial
// state of open, so the onopen event for the channel will not
// fire. We need to fire the onOpenDataChannel event here
// http://www.w3.org/TR/webrtc/#idl-def-RTCDataChannelState
if (state === 'open') {
F();
} else if (state === 'connecting') {
// Firefox channels do not have an initial state of 'open'
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1000478
this.rtcDataChannel_.on('onopen', F);
}
});
});
this.onceClosed = new Promise<void>((F,R) => {
this.rtcDataChannel_.on('onclose', F);
});
this.rtcDataChannel_.on('onmessage', this.onDataFromPeer_);
this.rtcDataChannel_.on('onerror', (e:Event) => {
log.error('rtcDataChannel_.onerror: ' + e.toString);
});
this.onceOpened.then(() => {
this.isOpen_ = true;
this.sendNext_();
}, (e:Error) => {
log.debug('failed to open');
});
this.onceClosed.then(() => {
if(!this.isOpen_) {
// Make sure to reject the onceOpened promise if state went from
// |connecting| to |close|.
this.rejectOpened_(new Error(
'Failed to open; closed while trying to open.'));
}
this.isOpen_ = false;
});
this.onceDrained_.then(() => {
log.debug('all messages sent, closing');
this.rtcDataChannel_.close();
});
}
// Handle data we get from the peer by putting it, appropriately wrapped, on
// the queue of data from the peer.
private onDataFromPeer_ = (message:freedom.RTCDataChannel.Message) : void => {
if (typeof message.text === 'string') {
this.dataFromPeerQueue.handle({str: message.text});
} else if (message.buffer instanceof ArrayBuffer) {
this.dataFromPeerQueue.handle({buffer: message.buffer});
} else {
log.error('Unexpected data from peer: %1', message);
}
}
// Promise completes once all the data has been sent. This is async because
// there may be more data than fits in the buffer; we do chunking so that
// data larger than the SCTP message size limit (about 16k) can be sent and
// received reliably, and so that the internal buffer is not over-filled. If
// data is too big we also fail.
//
// CONSIDER: We could support blob data by streaming into array-buffers.
public send = (data:Data) : Promise<void> => {
// Note: you cannot just write |if(data.str) ...| because str may be empty
// which is treated as false. You have to do something more verbose, like
// |if (typeof data.str === 'string') ...|.
if (!(typeof data.str === 'string' ||
(typeof data.buffer === 'object') &&
(data.buffer instanceof ArrayBuffer)) ) {
return Promise.reject(
new Error('data to send must have at least `str:string` or ' +
'`buffer:ArrayBuffer` defined (typeof data.str === ' +
typeof data.str + '; typeof data.buffer === ' +
typeof data.buffer +
'; data.buffer instanceof ArrayBuffer === ' +
(data.buffer instanceof ArrayBuffer) + ')'));
}
if (this.draining_) {
return Promise.reject(new Error('send was called after close'));
}
var byteLength :number;
if (typeof data.str === 'string') {
// This calculation is based on the idea that JS strings are utf-16,
// but since all strings are converted to UTF-8 by the data channel
// this calculation is only an approximate upper bound on the actual
// message size.
byteLength = data.str.length * 2;
} else if (data.buffer) {
byteLength = data.buffer.byteLength;
}
if(byteLength > MAX_MESSAGE_SIZE) {
return Promise.reject(new Error(
'Data was too big to send, sorry. ' +
'Need to wait for real Blob support.'));
}
if(typeof data.str === 'string') {
return this.chunkStringOntoQueue_({str:data.str});
} else if(data.buffer) {
return this.chunkBufferOntoQueue_({buffer:data.buffer});
}
}
// TODO: add an issue for chunking strings, write issue number here, then
// write the code and resolve the issue :-)
private chunkStringOntoQueue_ = (data:StringData) : Promise<void> => {
return this.toPeerDataQueue_.handle(data);
}
private chunkBufferOntoQueue_ = (data:BufferData) : Promise<void> => {
var chunks = arraybuffers.chunk(data.buffer, CHUNK_SIZE);
var promises :Promise<void>[] = [];
chunks.forEach((chunk) => {
this.toPeerDataBytes_ += chunk.byteLength;
promises.push(this.toPeerDataQueue_.handle({buffer: chunk}));
});
// CONSIDER: can we change the interface to support not having the dummy
// extra return at the end?
return Promise.all(promises).then(() => { return; });
}
// Assumes data is chunked.
private handleSendDataToPeer_ = (data:Data) : void => {
if (typeof data.str === 'string') {
this.rtcDataChannel_.send.reckless(data.str);
} else if (data.buffer) {
this.toPeerDataBytes_ -= data.buffer.byteLength;
this.rtcDataChannel_.sendBuffer.reckless(data.buffer);
this.lastBrowserBufferedAmount_ += data.buffer.byteLength;
} else {
// If type-safety is ensured at compile time, this should never happen.
throw new Error('Bad data: ' + JSON.stringify(data));
}
this.sendNext_();
}
// Sets the overflow state, and calls the listener if it has changed.
private setOverflow_ = (overflow:boolean) => {
if (this.overflowListener_ && this.overflow_ !== overflow) {
this.overflowListener_(overflow);
}
this.overflow_ = overflow;
}
private canSendMore_ = () : boolean => {
return this.isOpen_ && this.lastBrowserBufferedAmount_ <= PC_QUEUE_LIMIT;
}
private sendNext_ = () : void => {
if (!this.canSendMore_()) {
this.setOverflow_(true);
this.waitForOverflowToClear_();
return;
}
if (this.toPeerDataQueue_.getLength() === 0) {
this.setOverflow_(false);
}
if (this.toPeerDataQueue_.isHandling()) {
log.error('Last packet handler should not still be present');
this.close();
return;
}
this.toPeerDataQueue_.setSyncNextHandler(this.handleSendDataToPeer_);
}
private waitForOverflowToClear_ = () : void => {
this.rtcDataChannel_.getBufferedAmount().then((bufferedAmount:number) => {
this.lastBrowserBufferedAmount_ = bufferedAmount;
if (this.canSendMore_()) {
this.sendNext_();
} else if (this.isOpen_) {
// TODO: Remove polling once https://code.google.com/p/webrtc/issues/detail?id=4613
// is resolved (adding an event to RTCDataChannel).
setTimeout(this.waitForOverflowToClear_, 20);
}
});
}
// Closes asynchronously, after waiting for all outgoing messages.
public close = () : Promise<void> => {
log.debug('close requested (%1 messages and %2 bytes to send)',
this.toPeerDataQueue_.getLength(),
this.lastBrowserBufferedAmount_);
var onceJavascriptBufferDrained = new Promise((F, R) => {
if (this.getJavascriptBufferedAmount() > 0) {
this.setOverflowListener((overflow:boolean) => {
if (!overflow) {
F();
}
});
} else {
F();
}
this.draining_ = true;
});
onceJavascriptBufferDrained.then(this.waitForBrowserToDrain_).then(
this.fulfillDrained_);
return this.onceClosed;
}
private waitForBrowserToDrain_ = () : Promise<void> => {
var drained :() => void;
var onceBrowserBufferDrained :Promise<void> =
new Promise<void>((F, R) => {
drained = F;
});
var loop = () : void => {
this.getBrowserBufferedAmount().then((amount:number) => {
if (amount === 0) {
drained();
} else if (this.isOpen_) {
setTimeout(loop, 20);
} else {
log.warn('Data channel was closed remotely with %1 bytes buffered',
amount);
}
});
};
loop();
return onceBrowserBufferDrained;
}
public getBrowserBufferedAmount = () : Promise<number> => {
return this.rtcDataChannel_.getBufferedAmount();
}
public getJavascriptBufferedAmount = () : number => {
return this.toPeerDataBytes_;
}
public isInOverflow = () : boolean => {
return this.overflow_;
}
public setOverflowListener = (listener:(overflow:boolean) => void) => {
if (this.draining_) {
throw new Error('Can\'t set overflow listener after close');
}
this.overflowListener_ = listener;
}
public toString = () : string => {
var s = this.getLabel() + ': isOpen_=' + this.isOpen_;
return s;
}
// This setter is not part of the DataChannel interface, and is only for
// use by the static constructor.
public setLabel = (label:string) => {
if (this.label_ !== '') {
throw new Error('Data Channel label was set twice, to '
+ this.label_ + ' and ' + label);
}
this.label_ = label;
}
} // class DataChannelClass
// Static constructor which constructs a core.rtcdatachannel instance
// given a core.rtcdatachannel GUID.
export function createFromFreedomId(id:string) : Promise<DataChannel> {
return createFromRtcDataChannel(freedom['core.rtcdatachannel'](id));
}
// Static constructor which constructs a core.rtcdatachannel instance
// given a core.rtcdatachannel instance.
export function createFromRtcDataChannel(
rtcDataChannel:freedom.RTCDataChannel.RTCDataChannel) : Promise<DataChannel> {
// We need to construct the data channel synchronously to avoid missing any
// early 'onmessage' events.
var dc = new DataChannelClass(rtcDataChannel);
return rtcDataChannel.setBinaryType('arraybuffer').then(() => {
return rtcDataChannel.getLabel().then((label:string) => {
dc.setLabel(label);
return dc;
});
});
} | the_stack |
import assert = require("assert")
import fs = require("fs")
import path = require("path")
import _=require("underscore")
import def = require("raml-definition-system")
import ll=require("../lowLevelAST")
import yll=require("../jsyaml/jsyaml2lowLevel")
import high = require("../highLevelImpl")
import hl=require("../highLevelAST")
import t3 = require("../artifacts/raml10parser")
import util = require("./test-utils")
import textutil=require('../../util/textutil')
import smg = require("../tools/schemaModelGen");
describe('Schema Tests', function() {
this.timeout(15000);
describe('generate model by json', function () {
it('generate type definition in text mode (outdated)', function () {
var content = fs.readFileSync(util.data("schema/schema.json")).toString();
var text = new smg.SchemaToModelGenerator().generateText(content);
//fs.writeFileSync(targetPath,z.serializeToString());
//console.log('Text: \n' + text);
util.compareToFile(text, util.data("schema/schema-type.txt"));
});
it('convert json to type #json11', function () {
var api = util.loadApi(util.data('schema/api-empty.raml'));
var schema = fs.readFileSync(util.data("schema/schema.json")).toString();
//util.showTypeProperties(api.definition());
//(<yll.ASTNode>api.lowLevel()).show('UPDATED NODE:');
new smg.SchemaToModelGenerator().generateTo(api, schema);
//fs.writeFileSync(targetPath,z.serializeToString());
//show(api);
//console.log(api.lowLevel().unit().contents());
util.compareToFile(api.lowLevel().unit().contents(), util.data("schema/api-empty-expanded.raml"));
});
it('convert json reference to type #jsonref1', function () {
var api = util.loadApi(util.data('schema/to-model/jsonref.raml'));
//var schema = fs.readFileSync(util.data("schema/jsonref.json")).toString();
//util.showTypeProperties(api.definition());
//(<yll.ASTNode>api.lowLevel()).show('UPDATED NODE:');
var body = <hl.IHighLevelNode>util.xpath(api, 'resources/methods/body');
var schema = body.attr('schema').value();
//console.log(schema);
new smg.SchemaToModelGenerator().generateTo(api, schema);
//fs.writeFileSync(targetPath,z.serializeToString());
//show(api);
//console.log(api.lowLevel().unit().contents());
util.compareToFile(api.lowLevel().unit().contents(), util.data("schema/to-model/jsonref-generated.raml"));
});
});
describe('generate json by model', function () {
describe('basic', function () {
it('simple type #type1', function () {
var api = util.loadApi(util.data('schema/basic/type1.raml'));
var type = <hl.IHighLevelNode>util.xpath(api, 'types[0]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//api.lowLevel().show('ORIGINAL NODE:');
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/basic/type1-generated.json"));
});
it('simple type #type2', function () {
var api = util.loadApi(util.data('schema/basic/type2.raml'));
var type = <hl.IHighLevelNode>util.xpath(api, 'types[1]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//api.lowLevel().show('ORIGINAL NODE:');
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/basic/type2-generated.json"));
});
});
describe('union types', function () {
it('convert union types for basic properties #union1', function () {
var api = util.loadApi(util.data('schema/union/union1.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[0]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/union/union1-to-schema.json"));
});
it('convert union types for recursive types #union2', function () {
var api = util.loadApi(util.data('schema/union/union2.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[1]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/union/union2-generated.json"));
});
it('convert union types for recursive types #union3', function () {
var api = util.loadApi(util.data('schema/union/union3.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[2]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/union/union3-gen.json"));
});
it('convert union types for recursive types #union4', function () {
var api = util.loadApi(util.data('schema/union/union4.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[2]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/union/union4-gen.json"));
});
it('convert union types for recursive types #union5', function () {
var api = util.loadApi(util.data('schema/union/union5.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[2]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/union/union5-gen.json"));
});
});
describe('inheritance', function () {
it('simple type inheritance #inher1', function () {
var api = util.loadApi(util.data('schema/inher/inher1.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[1]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/inher/inher1-generated.json"));
});
it('multiple types inheritance #inher2', function () {
var api = util.loadApi(util.data('schema/inher/inher2.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[3]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/inher/inher2-generated.json"));
});
});
describe('shortcuts', function () {
it('property with type shortcut type-short1', function () {
var api = util.loadApi(util.data('schema/shortcut/type-shortcut1.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[0]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/shortcut/type-shortcut1.json"));
});
it('property with type shortcut type-short2', function () {
var api = util.loadApi(util.data('schema/shortcut/type-shortcut2.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[1]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/shortcut/type-shortcut2.json"));
});
it('optional property short2', function () {
var api = util.loadApi(util.data('schema/shortcut/shortcut2.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[0]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/shortcut/shortcut2.json"));
});
});
describe('references', function () {
it('json schema reference #ref11', function () {
var api = util.loadApi(util.data('schema/refs/ref1.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[0]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/refs/ref11-generated.json"));
});
it('json schema reference #ref12', function () {
var api = util.loadApi(util.data('schema/refs/ref1.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[1]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/refs/ref12-generated.json"));
});
});
describe('enums', function () {
it('enum property #enum1', function () {
var api = util.loadApi(util.data('schema/enum/enum1.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[0]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/enum/enum1-gen.json"));
});
});
describe('type expressions', function () {
it('union #expr1', function () {
var api = util.loadApi(util.data('schema/typeexpr/expr1.raml'));
//api.lowLevel().show('ORIGINAL:');
var type = <hl.IHighLevelNode>util.xpath(api, 'types[2]');
var obj = new smg.ModelToSchemaGenerator().generateSchema(type);
var text = JSON.stringify(obj, null, 2);
//console.log('JSON:\n' + text);
//console.log(api.lowLevel().unit().contents());
//console.log(text);
util.compareToFile(text, util.data("schema/typeexpr/expr1-gen.json"));
});
});
});
}); | the_stack |
import { some, isEqual, reverse } from 'lodash';
import path from 'path';
import process from 'process';
import { getBuildArtifacts } from '../artifacts/BuildArtifacts';
import Contract from '../artifacts/Contract.js';
import { BuildArtifacts } from '../artifacts/BuildArtifacts.js';
import { Node, NodeMapping, TypeInfo, TypeInfoMapping, StorageInfo } from '../utils/ContractAST';
// TS-TODO: define return type after typing class members below.
export function getStorageLayout(contract: Contract, artifacts: BuildArtifacts): StorageLayoutInfo {
if (!artifacts) artifacts = getBuildArtifacts();
const layout = new StorageLayout(contract, artifacts);
const { types, storage } = layout.run();
return { types, storage };
}
// TS-TODO: Define parameter after typing class members below.
// TS-TODO: define return type after typing class members below.
export function getStructsOrEnums(info: StorageLayoutInfo): StorageInfo[] {
return info.storage.filter((variable: any) => containsStructOrEnum(variable.type, info.types));
}
// TS-TODO: Define parameter types type after typing class members below.
function containsStructOrEnum(typeName: string, types): boolean {
const type = types[typeName];
if (type.kind === 'struct' || type.kind === 'enum') return true;
else if (type.valueType) return containsStructOrEnum(type.valueType, types);
else return false;
}
const CONTRACT_TYPE_INFO: TypeInfo = {
id: 't_address',
kind: 'elementary',
label: 'address',
};
const FUNCTION_TYPE_INFO: TypeInfo = {
id: 't_function',
kind: 'elementary',
label: 'function',
};
export interface StorageLayoutInfo {
types: TypeInfoMapping;
storage: StorageInfo[];
}
class StorageLayout {
private artifacts: BuildArtifacts;
private contract: Contract;
private imports: Set<any>;
private nodes: NodeMapping;
// TS-TODO: types and storage could be private and exposed via a readonly getter.
public types: TypeInfoMapping;
public storage: StorageInfo[];
public constructor(contract: Contract, artifacts: BuildArtifacts) {
this.artifacts = artifacts;
this.contract = contract;
// Transitive closure of source files imported from the contract.
this.imports = new Set();
// Map from ast id to nodeset across all visited contracts.
// (Note that more than one node may have the same id, due to how truffle compiles artifacts).
this.nodes = {};
// Types info being collected for the current contract.
this.types = {};
// Storage layout for the current contract.
this.storage = [];
}
public run(): StorageLayout {
this.collectImports(this.contract.schema.ast);
this.collectNodes(this.contract.schema.ast);
// TS-TODO: define contractNode type.
this.getLinearizedBaseContracts().forEach((contractNode: Node) => {
this.visitVariables(contractNode);
});
return this;
}
// TS-TODO: could type ast from artifacts/web3.
private collectImports(ast: any): void {
ast.nodes
.filter(node => node.nodeType === 'ImportDirective')
.map(node => node.absolutePath)
.forEach(importPath => {
if (this.imports.has(importPath)) return;
this.imports.add(importPath);
this.artifacts.getArtifactsFromSourcePath(importPath).forEach(importedArtifact => {
this.collectNodes(importedArtifact.ast);
this.collectImports(importedArtifact.ast);
});
});
}
private collectNodes(node: Node): void {
// Return if we have already seen this node.
if (some(this.nodes[node.id] || [], n => isEqual(n, node))) return;
// Add node to collection with this id otherwise.
if (!this.nodes[node.id]) this.nodes[node.id] = [];
this.nodes[node.id].push(node);
// Call recursively to children.
if (node.nodes) node.nodes.forEach(this.collectNodes.bind(this));
}
private visitVariables(contractNode: Node): void {
const sourcePath = path.relative(process.cwd(), this.getNode(contractNode.scope, 'SourceUnit').absolutePath);
const varNodes = contractNode.nodes.filter((node: Node) => node.stateVariable && !node.constant);
varNodes.forEach(node => {
const typeInfo = this.getAndRegisterTypeInfo(node.typeName);
this.registerType(typeInfo);
const storageInfo = {
contract: contractNode.name,
path: sourcePath,
...this.getStorageInfo(node, typeInfo),
};
this.storage.push(storageInfo);
});
}
private registerType(typeInfo: TypeInfo): void {
this.types[typeInfo.id] = typeInfo;
}
private getNode(id: number, nodeType: string): Node | never {
if (!this.nodes[id]) throw Error(`No AST nodes with id ${id} found`);
const candidates = this.nodes[id].filter(node => node.nodeType === nodeType);
switch (candidates.length) {
case 0:
throw Error(
`No AST nodes of type ${nodeType} with id ${id} found (got ${this.nodes[id]
.map((node: any) => node.nodeType)
.join(', ')})`,
);
case 1:
return candidates[0];
default:
throw Error(
`Found more than one node of type ${nodeType} with the same id ${id}. Please try clearing your build artifacts and recompiling your contracts.`,
);
}
}
private getContractNode(): Node {
return this.contract.schema.ast.nodes.find(
node => node.nodeType === 'ContractDefinition' && node.name === this.contract.schema.contractName,
);
}
private getLinearizedBaseContracts(): number[] {
return reverse(
this.getContractNode().linearizedBaseContracts.map((id: number) => this.getNode(id, 'ContractDefinition')),
);
}
private getStorageInfo(varNode, typeInfo): StorageInfo {
return {
label: varNode.name,
astId: varNode.id,
type: typeInfo.id,
src: varNode.src,
};
}
private getAndRegisterTypeInfo(node: Node): TypeInfo {
const typeInfo = this.getTypeInfo(node);
this.registerType(typeInfo);
return typeInfo;
}
private getTypeInfo(node): TypeInfo {
switch (node.nodeType) {
case 'ElementaryTypeName':
return this.getElementaryTypeInfo(node);
case 'ArrayTypeName':
return this.getArrayTypeInfo(node);
case 'Mapping':
return this.getMappingTypeInfo(node);
case 'UserDefinedTypeName':
return this.getUserDefinedTypeInfo(node);
case 'FunctionTypeName':
return this.getFunctionTypeInfo();
default:
throw Error(`Cannot get type info for unknown node type ${node.nodeType}`);
}
}
private getUserDefinedTypeInfo({ referencedDeclaration, typeDescriptions }) {
const typeIdentifier = this.getTypeIdentifier(typeDescriptions);
switch (typeIdentifier) {
case 't_contract':
return this.getContractTypeInfo();
case 't_struct':
return this.getStructTypeInfo(referencedDeclaration);
case 't_enum':
return this.getEnumTypeInfo(referencedDeclaration);
default:
throw Error(`Unknown type identifier ${typeIdentifier} for ${typeDescriptions.typeString}`);
}
}
private getTypeIdentifier({ typeIdentifier }) {
return typeIdentifier.split('$', 1)[0];
}
private getElementaryTypeInfo({ typeDescriptions }): TypeInfo {
const identifier = typeDescriptions.typeIdentifier.replace(/_storage(_ptr)?$/, '');
return {
id: identifier,
kind: 'elementary',
label: typeDescriptions.typeString,
};
}
private getArrayTypeInfo({ baseType, length }): TypeInfo {
const { id: baseTypeId, label: baseTypeLabel } = this.getAndRegisterTypeInfo(baseType);
const lengthDescriptor = length ? length.value : 'dyn';
const lengthLabel = length ? length.value : '';
return {
id: `t_array:${lengthDescriptor}<${baseTypeId}>`,
valueType: baseTypeId,
length: lengthDescriptor,
kind: 'array',
label: `${baseTypeLabel}[${lengthLabel}]`,
};
}
private getMappingTypeInfo({ valueType }): TypeInfo {
// We ignore the keyTypeId, since it's always hashed and takes up the same amount of space; we only care about the last value type
const { id: valueTypeId, label: valueTypeLabel } = this.getValueTypeInfo(valueType);
return {
id: `t_mapping<${valueTypeId}>`,
valueType: valueTypeId,
label: `mapping(key => ${valueTypeLabel})`,
kind: 'mapping',
};
}
private getContractTypeInfo(): TypeInfo {
// Process a reference to a contract as an address, since we only care about storage size
return { ...CONTRACT_TYPE_INFO };
}
private getFunctionTypeInfo(): TypeInfo {
// Process a reference to a function disregarding types, since we only care how much space it takes
return { ...FUNCTION_TYPE_INFO };
}
private getStructTypeInfo(referencedDeclaration): TypeInfo {
// Identify structs by contract and name
const referencedNode = this.getNode(referencedDeclaration, 'StructDefinition');
const id = `t_struct<${referencedNode.canonicalName}>`;
if (this.types[id]) return this.types[id];
// We shortcircuit type registration in this scenario to handle recursive structs
const typeInfo = {
id,
kind: 'struct',
label: referencedNode.canonicalName,
members: [],
};
this.registerType(typeInfo);
// Store members info in type info
const members = referencedNode.members
.filter(member => member.nodeType === 'VariableDeclaration')
.map(member => {
const memberTypeInfo = this.getAndRegisterTypeInfo(member.typeName);
return this.getStorageInfo(member, memberTypeInfo);
});
Object.assign(typeInfo, { members });
return typeInfo;
}
private getEnumTypeInfo(referencedDeclaration): TypeInfo {
// Store canonical name and members for an enum
const referencedNode = this.getNode(referencedDeclaration, 'EnumDefinition');
return {
id: `t_enum<${referencedNode.canonicalName}>`,
kind: 'enum',
label: referencedNode.canonicalName,
members: referencedNode.members.map(m => m.name),
};
}
private getValueTypeInfo(node): TypeInfo {
return node.nodeType === 'Mapping' ? this.getValueTypeInfo(node.valueType) : this.getAndRegisterTypeInfo(node);
}
} | the_stack |
import {BackgroundColorValue, BorderColorValue, BorderRadiusValue, BorderSizeValue, ColorValue, DimensionValue, Direction, Responsive, ResponsiveProp, StyleProps, ViewStyleProps} from '@react-types/shared';
import {CSSProperties, HTMLAttributes} from 'react';
import {useBreakpoint} from './BreakpointProvider';
import {useLocale} from '@react-aria/i18n';
type Breakpoint = 'base' | 'S' | 'M' | 'L' | string;
type StyleName = string | string[] | ((dir: Direction) => string);
type StyleHandler = (value: any) => string;
export interface StyleHandlers {
[key: string]: [StyleName, StyleHandler]
}
export const baseStyleProps: StyleHandlers = {
margin: ['margin', dimensionValue],
marginStart: [rtl('marginLeft', 'marginRight'), dimensionValue],
marginEnd: [rtl('marginRight', 'marginLeft'), dimensionValue],
// marginLeft: ['marginLeft', dimensionValue],
// marginRight: ['marginRight', dimensionValue],
marginTop: ['marginTop', dimensionValue],
marginBottom: ['marginBottom', dimensionValue],
marginX: [['marginLeft', 'marginRight'], dimensionValue],
marginY: [['marginTop', 'marginBottom'], dimensionValue],
width: ['width', dimensionValue],
height: ['height', dimensionValue],
minWidth: ['minWidth', dimensionValue],
minHeight: ['minHeight', dimensionValue],
maxWidth: ['maxWidth', dimensionValue],
maxHeight: ['maxHeight', dimensionValue],
isHidden: ['display', hiddenValue],
alignSelf: ['alignSelf', passthroughStyle],
justifySelf: ['justifySelf', passthroughStyle],
position: ['position', anyValue],
zIndex: ['zIndex', anyValue],
top: ['top', dimensionValue],
bottom: ['bottom', dimensionValue],
start: [rtl('left', 'right'), dimensionValue],
end: [rtl('right', 'left'), dimensionValue],
left: ['left', dimensionValue],
right: ['right', dimensionValue],
order: ['order', anyValue],
flex: ['flex', flexValue],
flexGrow: ['flexGrow', passthroughStyle],
flexShrink: ['flexShrink', passthroughStyle],
flexBasis: ['flexBasis', passthroughStyle],
gridArea: ['gridArea', passthroughStyle],
gridColumn: ['gridColumn', passthroughStyle],
gridColumnEnd: ['gridColumnEnd', passthroughStyle],
gridColumnStart: ['gridColumnStart', passthroughStyle],
gridRow: ['gridRow', passthroughStyle],
gridRowEnd: ['gridRowEnd', passthroughStyle],
gridRowStart: ['gridRowStart', passthroughStyle]
};
export const viewStyleProps: StyleHandlers = {
...baseStyleProps,
backgroundColor: ['backgroundColor', backgroundColorValue],
borderWidth: ['borderWidth', borderSizeValue],
borderStartWidth: [rtl('borderLeftWidth', 'borderRightWidth'), borderSizeValue],
borderEndWidth: [rtl('borderRightWidth', 'borderLeftWidth'), borderSizeValue],
borderLeftWidth: ['borderLeftWidth', borderSizeValue],
borderRightWidth: ['borderRightWidth', borderSizeValue],
borderTopWidth: ['borderTopWidth', borderSizeValue],
borderBottomWidth: ['borderBottomWidth', borderSizeValue],
borderXWidth: [['borderLeftWidth', 'borderRightWidth'], borderSizeValue],
borderYWidth: [['borderTopWidth', 'borderBottomWidth'], borderSizeValue],
borderColor: ['borderColor', borderColorValue],
borderStartColor: [rtl('borderLeftColor', 'borderRightColor'), borderColorValue],
borderEndColor: [rtl('borderRightColor', 'borderLeftColor'), borderColorValue],
borderLeftColor: ['borderLeftColor', borderColorValue],
borderRightColor: ['borderRightColor', borderColorValue],
borderTopColor: ['borderTopColor', borderColorValue],
borderBottomColor: ['borderBottomColor', borderColorValue],
borderXColor: [['borderLeftColor', 'borderRightColor'], borderColorValue],
borderYColor: [['borderTopColor', 'borderBottomColor'], borderColorValue],
borderRadius: ['borderRadius', borderRadiusValue],
borderTopStartRadius: [rtl('borderTopLeftRadius', 'borderTopRightRadius'), borderRadiusValue],
borderTopEndRadius: [rtl('borderTopRightRadius', 'borderTopLeftRadius'), borderRadiusValue],
borderBottomStartRadius: [rtl('borderBottomLeftRadius', 'borderBottomRightRadius'), borderRadiusValue],
borderBottomEndRadius: [rtl('borderBottomRightRadius', 'borderBottomLeftRadius'), borderRadiusValue],
borderTopLeftRadius: ['borderTopLeftRadius', borderRadiusValue],
borderTopRightRadius: ['borderTopRightRadius', borderRadiusValue],
borderBottomLeftRadius: ['borderBottomLeftRadius', borderRadiusValue],
borderBottomRightRadius: ['borderBottomRightRadius', borderRadiusValue],
padding: ['padding', dimensionValue],
paddingStart: [rtl('paddingLeft', 'paddingRight'), dimensionValue],
paddingEnd: [rtl('paddingRight', 'paddingLeft'), dimensionValue],
paddingLeft: ['paddingLeft', dimensionValue],
paddingRight: ['paddingRight', dimensionValue],
paddingTop: ['paddingTop', dimensionValue],
paddingBottom: ['paddingBottom', dimensionValue],
paddingX: [['paddingLeft', 'paddingRight'], dimensionValue],
paddingY: [['paddingTop', 'paddingBottom'], dimensionValue],
overflow: ['overflow', passthroughStyle]
};
const borderStyleProps = {
borderWidth: 'borderStyle',
borderLeftWidth: 'borderLeftStyle',
borderRightWidth: 'borderRightStyle',
borderTopWidth: 'borderTopStyle',
borderBottomWidth: 'borderBottomStyle'
};
function rtl(ltr: string, rtl: string) {
return (direction: Direction) => (
direction === 'rtl' ? rtl : ltr
);
}
const UNIT_RE = /(%|px|em|rem|vw|vh|auto|cm|mm|in|pt|pc|ex|ch|rem|vmin|vmax|fr)$/;
const FUNC_RE = /^\s*\w+\(/;
const SPECTRUM_VARIABLE_RE = /(static-)?size-\d+|single-line-(height|width)/g;
export function dimensionValue(value: DimensionValue) {
if (typeof value === 'number') {
return value + 'px';
}
if (UNIT_RE.test(value)) {
return value;
}
if (FUNC_RE.test(value)) {
return value.replace(SPECTRUM_VARIABLE_RE, 'var(--spectrum-global-dimension-$&, var(--spectrum-alias-$&))');
}
return `var(--spectrum-global-dimension-${value}, var(--spectrum-alias-${value}))`;
}
export function responsiveDimensionValue(value: Responsive<DimensionValue>, matchedBreakpoints: Breakpoint[]) {
value = getResponsiveProp(value, matchedBreakpoints);
return dimensionValue(value);
}
type ColorType = 'default' | 'background' | 'border' | 'icon' | 'status';
function colorValue(value: ColorValue, type: ColorType = 'default') {
return `var(--spectrum-global-color-${value}, var(--spectrum-semantic-${value}-color-${type}))`;
}
function backgroundColorValue(value: BackgroundColorValue) {
return `var(--spectrum-alias-background-color-${value}, ${colorValue(value as ColorValue, 'background')})`;
}
function borderColorValue(value: BorderColorValue) {
if (value === 'default') {
return 'var(--spectrum-alias-border-color)';
}
return `var(--spectrum-alias-border-color-${value}, ${colorValue(value as ColorValue, 'border')})`;
}
function borderSizeValue(value: BorderSizeValue) {
return `var(--spectrum-alias-border-size-${value})`;
}
function borderRadiusValue(value: BorderRadiusValue) {
return `var(--spectrum-alias-border-radius-${value})`;
}
function hiddenValue(value: boolean) {
return value ? 'none' : undefined;
}
function anyValue(value: any) {
return value;
}
function flexValue(value: boolean | number | string) {
if (typeof value === 'boolean') {
return value ? '1' : undefined;
}
return '' + value;
}
export function convertStyleProps(props: ViewStyleProps, handlers: StyleHandlers, direction: Direction, matchedBreakpoints: Breakpoint[]) {
let style: CSSProperties = {};
for (let key in props) {
let styleProp = handlers[key];
if (!styleProp || props[key] == null) {
continue;
}
let [name, convert] = styleProp;
if (typeof name === 'function') {
name = name(direction);
}
let prop = getResponsiveProp(props[key], matchedBreakpoints);
let value = convert(prop);
if (Array.isArray(name)) {
for (let k of name) {
style[k] = value;
}
} else {
style[name] = value;
}
}
for (let prop in borderStyleProps) {
if (style[prop]) {
style[borderStyleProps[prop]] = 'solid';
style.boxSizing = 'border-box';
}
}
return style;
}
type StylePropsOptions = {
matchedBreakpoints?: Breakpoint[]
};
export function useStyleProps<T extends StyleProps>(
props: T,
handlers: StyleHandlers = baseStyleProps,
options: StylePropsOptions = {}
) {
let {
UNSAFE_className,
UNSAFE_style,
...otherProps
} = props;
let breakpointProvider = useBreakpoint();
let {direction} = useLocale();
let {
matchedBreakpoints = breakpointProvider?.matchedBreakpoints || ['base']
} = options;
let styles = convertStyleProps(props, handlers, direction, matchedBreakpoints);
let style = {...UNSAFE_style, ...styles};
// @ts-ignore
if (otherProps.className) {
console.warn(
'The className prop is unsafe and is unsupported in React Spectrum v3. ' +
'Please use style props with Spectrum variables, or UNSAFE_className if you absolutely must do something custom. ' +
'Note that this may break in future versions due to DOM structure changes.'
);
}
// @ts-ignore
if (otherProps.style) {
console.warn(
'The style prop is unsafe and is unsupported in React Spectrum v3. ' +
'Please use style props with Spectrum variables, or UNSAFE_style if you absolutely must do something custom. ' +
'Note that this may break in future versions due to DOM structure changes.'
);
}
let styleProps: HTMLAttributes<HTMLElement> = {
style,
className: UNSAFE_className
};
if (getResponsiveProp(props.isHidden, matchedBreakpoints)) {
styleProps.hidden = true;
}
return {
styleProps
};
}
export function passthroughStyle(value) {
return value;
}
export function getResponsiveProp<T>(prop: Responsive<T>, matchedBreakpoints: Breakpoint[]): T {
if (prop && typeof prop === 'object' && !Array.isArray(prop)) {
for (let i = 0; i < matchedBreakpoints.length; i++) {
let breakpoint = matchedBreakpoints[i];
if (prop[breakpoint] != null) {
return prop[breakpoint];
}
}
return (prop as ResponsiveProp<T>).base;
}
return prop as T;
} | the_stack |
import {tuiAssert} from '@taiga-ui/cdk/classes';
import {TuiDayOfWeek, TuiMonthNumber} from '@taiga-ui/cdk/enums';
import {TuiDayLike} from '@taiga-ui/cdk/interfaces';
import {TuiDateMode} from '@taiga-ui/cdk/types';
import {padStart} from '@taiga-ui/cdk/utils/format';
import {inRange, normalizeToIntNumber} from '@taiga-ui/cdk/utils/math';
import {DATE_FILLER_LENGTH} from './date-fillers';
import {DAYS_IN_WEEK, MIN_DAY, MONTHS_IN_YEAR} from './date-time';
import {TuiMonth} from './month';
import {TuiYear} from './year';
// TODO: Localized formatting
/**
* Immutable date object, consisting of day, month and year
*/
export class TuiDay extends TuiMonth {
constructor(year: number, month: number, readonly day: number) {
super(year, month);
tuiAssert.assert(TuiDay.isValidDay(year, month, day));
}
/**
* Creates {@link TuiDay} from native {@link Date} based on local time zone
*/
static fromLocalNativeDate(date: Date): TuiDay {
return new TuiDay(date.getFullYear(), date.getMonth(), date.getDate());
}
/**
* Creates {@link TuiDay} from native {@link Date} using UTC
*/
static fromUtcNativeDate(date: Date): TuiDay {
return new TuiDay(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
}
/**
* Check validity of year, month and day
*
* @param year
* @param month
* @param day
* @return boolean validity
*/
static isValidDay(year: number, month: number, day: number): boolean {
return (
TuiMonth.isValidMonth(year, month) &&
Number.isInteger(day) &&
inRange(
day,
MIN_DAY,
TuiMonth.getMonthDaysCount(month, TuiYear.isLeapYear(year)) + 1,
)
);
}
/**
* @deprecated DONT USE IT (will be deleted soon)
*
* Calculated day on a calendar grid
*
* @param month
* @param row row in a calendar
* @param col column in a calendar
* @return resulting day on these coordinates (could exceed passed month)
*/
static getDayFromMonthRowCol(month: TuiMonth, row: number, col: number): TuiDay {
tuiAssert.assert(Number.isInteger(row));
tuiAssert.assert(inRange(row, 0, 6));
tuiAssert.assert(Number.isInteger(col));
tuiAssert.assert(inRange(col, 0, DAYS_IN_WEEK));
let day = row * DAYS_IN_WEEK + col - month.monthStartDaysOffset + 1;
if (day > month.daysCount) {
day = day - month.daysCount;
month = month.append({month: 1});
}
if (day <= 0) {
month = month.append({month: -1});
day = month.daysCount + day;
}
return new TuiDay(month.year, month.month, day);
}
/**
* Current day based on local time zone
*/
static currentLocal(): TuiDay {
const nativeDate = new Date();
const year = nativeDate.getFullYear();
const month = nativeDate.getMonth();
const day = nativeDate.getDate();
return new TuiDay(year, month, day);
}
/**
* Calculates {@link TuiDay} normalizing year, month and day. {@link NaN} is turned into minimal value.
*
* @param year any year value, including invalid
* @param month any month value, including invalid (months start with 0)
* @param day any day value, including invalid
* @return normalized date
*/
static normalizeOf(year: number, month: number, day: number): TuiDay {
const normalizedYear = TuiYear.normalizeYearPart(year);
const normalizedMonth = TuiMonth.normalizeMonthPart(month);
const normalizedDay = TuiDay.normalizeDayPart(
day,
normalizedMonth,
normalizedYear,
);
return new TuiDay(normalizedYear, normalizedMonth, normalizedDay);
}
static lengthBetween(from: TuiDay, to: TuiDay): number {
return Math.round(
(to.toLocalNativeDate().getTime() - from.toLocalNativeDate().getTime()) /
(1000 * 60 * 60 * 24),
);
}
static parseRawDateString(
date: string,
dateMode: TuiDateMode = 'DMY',
): {day: number; month: number; year: number} {
tuiAssert.assert(
date.length === DATE_FILLER_LENGTH,
'[parseRawDateString]: wrong date string length',
);
switch (dateMode) {
case 'YMD':
return {
day: parseInt(date.slice(8, 10), 10),
month: parseInt(date.slice(5, 7), 10) - 1,
year: parseInt(date.slice(0, 4), 10),
};
case 'MDY':
return {
day: parseInt(date.slice(3, 5), 10),
month: parseInt(date.slice(0, 2), 10) - 1,
year: parseInt(date.slice(6, 10), 10),
};
default:
case 'DMY':
return {
day: parseInt(date.slice(0, 2), 10),
month: parseInt(date.slice(3, 5), 10) - 1,
year: parseInt(date.slice(6, 10), 10),
};
}
}
// TODO: Move month and year related code corresponding classes
/**
* Parsing a string with date with normalization
*
* @param rawDate date string
* @param dateMode date format of the date string (DMY | MDY | YMD)
* @return normalized date
*/
static normalizeParse(rawDate: string, dateMode: TuiDateMode = 'DMY'): TuiDay {
const {day, month, year} = this.parseRawDateString(rawDate, dateMode);
return TuiDay.normalizeOf(year, month, day);
}
/**
* Parsing a date stringified in a toJSON format
* @param yearMonthDayString date string in format of YYYY-MM-DD
* @return date
* @throws exceptions if any part of the date is invalid
*/
static jsonParse(yearMonthDayString: string): TuiDay {
const {day, month, year} = this.parseRawDateString(yearMonthDayString, 'YMD');
if (!TuiYear.isValidYear(year)) {
throw new Error('Invalid year: ' + year);
}
if (!TuiMonth.isValidMonth(year, month)) {
throw new Error('Invalid month: ' + month);
}
if (
!Number.isInteger(day) ||
!inRange(
day,
MIN_DAY,
TuiMonth.getMonthDaysCount(month, TuiYear.isLeapYear(year)) + 1,
)
) {
throw new Error('Invalid day: ' + day);
}
return new TuiDay(year, month, day);
}
protected static normalizeDayPart(day: number, month: number, year: number): number {
tuiAssert.assert(TuiMonth.isValidMonth(year, month));
const monthDaysCount = TuiMonth.getMonthDaysCount(
month,
TuiYear.isLeapYear(year),
);
return normalizeToIntNumber(day, 1, monthDaysCount);
}
get formattedDayPart(): string {
return padStart(this.day.toString(), 2, '0');
}
/**
* @deprecated use {@link getFormattedDay} instead
* TODO remove in 3.0
* Formatted whole date
*/
get formattedDay(): string {
return `${this.formattedDayPart}.${this.formattedMonth}`;
}
get isWeekend(): boolean {
const dayOfWeek = this.dayOfWeek(false);
return dayOfWeek === TuiDayOfWeek.Saturday || dayOfWeek === TuiDayOfWeek.Sunday;
}
/**
* Returns day of week
*
* @param startFromMonday whether week starts from Monday and not from Sunday
* @return day of week (from 0 to 6)
*/
dayOfWeek(startFromMonday: boolean = true): number {
const dayOfWeek = startFromMonday
? this.toLocalNativeDate().getDay() - 1
: this.toLocalNativeDate().getDay();
return dayOfWeek < 0 ? 6 : dayOfWeek;
}
/**
* Passed date is after current
*/
dayBefore(another: TuiDay): boolean {
return (
this.monthBefore(another) ||
(this.monthSame(another) && this.day < another.day)
);
}
/**
* Passed date is after or equals to current
*/
daySameOrBefore(another: TuiDay): boolean {
return (
this.monthBefore(another) ||
(this.monthSame(another) && this.day <= another.day)
);
}
/**
* Passed date is the same as current
*/
daySame(another: TuiDay): boolean {
return this.monthSame(another) && this.day === another.day;
}
/**
* Passed date is either before or the same as current
*/
daySameOrAfter(another: TuiDay): boolean {
return (
this.monthAfter(another) ||
(this.monthSame(another) && this.day >= another.day)
);
}
/**
* Passed date is before current
*/
dayAfter(another: TuiDay): boolean {
return (
this.monthAfter(another) ||
(this.monthSame(another) && this.day > another.day)
);
}
/**
* Clamping date between two limits
*
* @param min
* @param max
* @return clamped date
*/
dayLimit(min: TuiDay | null, max: TuiDay | null): TuiDay {
if (min !== null && this.dayBefore(min)) {
return min;
}
if (max !== null && this.dayAfter(max)) {
return max;
}
return this;
}
// TODO: Consider removing `backwards` option
/**
* Immutably alters current day by passed offset
*
* If resulting month has more days than original one, date is rounded to the maximum day
* in the resulting month. Offset of days will be calculated based on the resulted year and month
* to not interfere with parent classes methods
*
* @param offset
* @param backwards shift date backwards
* @return new date object as a result of offsetting current
*/
append(
{year = 0, month = 0, day = 0}: TuiDayLike,
backwards: boolean = false,
): TuiDay {
if (backwards) {
year *= -1;
month *= -1;
day *= -1;
}
const totalMonths = (this.year + year) * MONTHS_IN_YEAR + this.month + month;
let years = Math.floor(totalMonths / MONTHS_IN_YEAR);
let months = totalMonths % MONTHS_IN_YEAR;
let days =
Math.min(
this.day,
TuiMonth.getMonthDaysCount(months, TuiYear.isLeapYear(years)),
) + day;
while (days > TuiMonth.getMonthDaysCount(months, TuiYear.isLeapYear(years))) {
days -= TuiMonth.getMonthDaysCount(months, TuiYear.isLeapYear(years));
if (months === TuiMonthNumber.December) {
years++;
months = TuiMonthNumber.January;
} else {
months++;
}
}
while (days < MIN_DAY) {
if (months === TuiMonthNumber.January) {
years--;
months = TuiMonthNumber.December;
} else {
months--;
}
days += TuiMonth.getMonthDaysCount(months, TuiYear.isLeapYear(years));
}
return new TuiDay(years, months, days);
}
/**
* Returns formatted whole date
*/
getFormattedDay(dateFormat: TuiDateMode, separator: string): string {
tuiAssert.assert(
separator.length === 1,
'Separator should consist of only 1 symbol',
);
const dd = this.formattedDayPart;
const mm = this.formattedMonthPart;
const yyyy = this.formattedYear;
switch (dateFormat) {
case 'YMD':
return `${yyyy}${separator}${mm}${separator}${dd}`;
case 'MDY':
return `${mm}${separator}${dd}${separator}${yyyy}`;
case 'DMY':
default:
return `${dd}${separator}${mm}${separator}${yyyy}`;
}
}
toString(dateFormat: TuiDateMode = 'DMY', separator: string = '.'): string {
return this.getFormattedDay(dateFormat, separator);
}
toJSON(): string {
return `${super.toJSON()}-${this.formattedDayPart}`;
}
/**
* Returns native {@link Date} based on local time zone
*/
toLocalNativeDate(): Date {
return new Date(this.year, this.month, this.day);
}
/**
* Returns native {@link Date} based on UTC
*/
toUtcNativeDate(): Date {
return new Date(Date.UTC(this.year, this.month, this.day));
}
} | the_stack |
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import CacheHelper from 'App/Helpers/CacheHelper'
import UserServices from 'App/Services/UserServices'
import CompanyValidator from 'App/Validators/CompanyValidator'
import { CACHE_TAGS } from 'Contracts/cache'
import Logger from '@ioc:Adonis/Core/Logger'
import Company from 'App/Models/Company'
import Database from '@ioc:Adonis/Lucid/Database'
import Application from '@ioc:Adonis/Core/Application'
import { DateTime } from 'luxon'
import { snakeCase } from 'lodash'
import { AttachedFile, FileData } from 'types/file'
import FileUploadHelper from 'App/Helpers/FileUploadHelper'
import FileDeletionHelper from 'App/Helpers/FileDeletionHelper'
export default class CompaniesController {
public async index({ response, auth, request, bouncer }: HttpContextContract) {
await bouncer.with('CompanyPolicy').authorize('list')
const authUser = auth.user
if (authUser) {
const {
page,
descending,
perPage,
sortBy,
id,
name,
email,
type,
phone_number,
city,
company_size,
state,
country,
created_at,
updated_at,
} = request.qs()
const searchQuery = {
id: id ?? null,
name: name ?? null,
email: email ?? null,
type: type ?? null,
phone_number: phone_number ?? null,
city: city ?? '',
company_size: company_size ?? null,
state: state ?? null,
country: country ?? null,
created_at: created_at ?? null,
updated_at: updated_at ?? null,
}
let subquery = Database.from('companies')
.select(
'companies.id',
'companies.name',
'companies.phone_number',
'companies.address',
'companies.is_approved',
'companies.approved_at',
'companies.city',
'companies.created_at',
'companies.email',
'companies.updated_at',
'companies.type',
'companies.website',
'countries.name as country',
'states.name as state',
'company_sizes.size as company_size',
'uploaded_files.url as logo_url',
'uploaded_files.formats as logo_formats'
)
.leftJoin('company_user', (query) =>
query.on('company_user.company_id', '=', 'companies.id')
)
.where('company_user.user_id', authUser.id)
.leftJoin('company_sizes', (query) =>
query.on('company_sizes.id', '=', 'companies.company_size_id')
)
.leftJoin('countries', (query) => query.on('countries.id', '=', 'companies.country_id'))
.leftJoin('states', (query) => query.on('states.id', '=', 'companies.state_id'))
.leftJoin('uploaded_files', (query) => query.on('uploaded_files.id', '=', 'companies.logo'))
if (sortBy) {
subquery = subquery.orderBy(sortBy, descending === 'true' ? 'desc' : 'asc')
}
if (searchQuery) {
subquery.where((query) => {
for (const param in searchQuery) {
if (Object.prototype.hasOwnProperty.call(searchQuery, param)) {
let value = searchQuery[param]
if (value) {
if (value === 'true') value = true
if (value === 'false') value = false
if (param === 'company_size') {
query.where('company_sizes.id', value)
} else if (param === 'country') {
query.where('countries.name', value)
} else if (param === 'state') {
query.where('states.name', value)
} else if (param === 'company_size') {
query.where('company_sizes.id', value)
} else {
query.where(`companies.${param}`, value)
if (typeof value === 'string') {
query.orWhere(`companies.${param}`, 'like', `%${value}%`)
}
}
}
}
}
})
}
const companies = await subquery.paginate(page ? page : 1, perPage ? perPage : 20)
return response.ok({ data: companies })
}
}
public async store({ response, request, bouncer, auth, requestedCompany }: HttpContextContract) {
const {
isPersonalBrand,
name,
email,
phoneNumber,
address,
city,
size,
stateId,
countryId,
website,
logo,
} = await request.validate(CompanyValidator)
const requestMethod = request.method()
const user = auth.user
let companyModel: Company | undefined
if (user) {
if (requestMethod === 'POST') {
await bouncer.with('CompanyPolicy').authorize('create')
companyModel = await user?.related('companies').create({
name,
email,
phoneNumber,
address,
city,
companySizeId: size,
stateId,
countryId,
website,
type: isPersonalBrand ? 'personal' : 'corporate',
})
} else if (requestMethod === 'PATCH') {
companyModel = requestedCompany
await bouncer.with('CompanyPolicy').authorize('edit', companyModel!)
companyModel?.merge({
name,
email,
phoneNumber,
address,
city,
companySizeId: size,
stateId,
countryId,
website,
type: isPersonalBrand ? 'personal' : 'corporate',
})
await companyModel?.save()
}
await companyModel?.refresh()
// Check if company already has a logo
const oldLogo = companyModel?.logo
const hasOldLogo = !!oldLogo
// Process uploaded file (if any)
if (logo) {
const companyName = companyModel?.name!
const firstLetter = companyName.charAt(0)
const secondLetter = companyName.charAt(1)
const finalUploadDir = `uploads/company_logos/${firstLetter}/${secondLetter}`.toLowerCase()
const fileName = `${snakeCase(companyName)}_${DateTime.now().toMillis()}`.toLowerCase()
await logo.move(Application.tmpPath('uploads/company_logos/'), {
name: `${fileName}.${logo.extname}`,
overwrite: true,
})
// Generate file formats using sharp and persist them
const fileObject: AttachedFile = {
filePath: logo.filePath,
name: fileName,
type: logo.type!,
size: logo.size!,
}
const mime = logo.type + '/' + logo.subtype
const fileData: FileData = {
data: {
fileInfo: {
ext: '',
hash: '',
mime,
size: fileObject.size,
alternativeText: '',
caption: '',
name: fileObject.name,
path: fileObject.filePath,
},
},
files: logo,
}
const fileUploadHelper = new FileUploadHelper(
fileData,
finalUploadDir,
'local',
'company_logo'
)
await fileUploadHelper.upload().then(async (uploadedFileModel) => {
// Associate company with the uploaded file
companyModel?.merge({ logo: uploadedFileModel?.id })
await companyModel?.save()
})
if (hasOldLogo) {
// Delete old profile picture
await new FileDeletionHelper(oldLogo!).delete()
}
}
// Clear the user's entire cache
const userCompaniesTags = await new UserServices({ id: user.id }).getCompaniesCacheTags()
const sets = [
`${CACHE_TAGS.USER_CACHE_TAG_PREFIX}:${user.id}`,
`${CACHE_TAGS.COMPANY_USERS_CACHE_TAG_PREFIX}:${user.id}`,
`${CACHE_TAGS.COMPANY_USERS_INDEX_CACHE_TAG_PREFIX}:${user.id}`,
...userCompaniesTags,
]
await CacheHelper.flushTags(sets)
return response.created({ data: companyModel?.id })
} else return response.abort({ message: 'User not found' })
}
public async show({ response, requestedCompany, bouncer }: HttpContextContract) {
if (requestedCompany) {
// Check authorisation
await bouncer.with('CompanyPolicy').authorize('view', requestedCompany)
const company = await Company.query()
.where('id', requestedCompany.id)
.preload('companySize', (query) => query.select('id', 'size'))
.preload('country', (query) => query.select('id', 'name'))
.preload('state', (query) => query.select('id', 'name'))
.preload('companyLogo', (fileQuery) => fileQuery.select('formats', 'url'))
.first()
const serialisedCompany = company?.serialize({
fields: {
pick: [
'id',
'name',
'phone_number',
'address',
'is_approved',
'approved_at',
'city',
'created_at',
'email',
'updated_at',
'slug',
'type',
'website',
],
},
})
return response.ok({ data: serialisedCompany })
} else {
Logger.warn('Requested company not found at CompaniesController.show')
}
}
public async destroy({
response,
requestedCompany,
requestedUser,
bouncer,
auth,
}: HttpContextContract) {
if (requestedCompany) {
await bouncer.with('CompanyPolicy').authorize('delete', requestedCompany ?? undefined)
requestedCompany?.delete()
// Clear the company's entire cache
const userCompaniesTags = await new UserServices({
id: auth?.user?.id,
}).getCompaniesCacheTags()
const sets = [...userCompaniesTags]
await CacheHelper.flushTags(sets)
return response.created({ data: requestedUser?.id })
} else {
Logger.warn('Requested User not found in CompaniesController.destroy')
return response.abort({ message: 'Requested company not found' })
}
}
} | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import { BudgetsClient } from "./BudgetsClient";
import {
CreateBudgetActionCommand,
CreateBudgetActionCommandInput,
CreateBudgetActionCommandOutput,
} from "./commands/CreateBudgetActionCommand";
import {
CreateBudgetCommand,
CreateBudgetCommandInput,
CreateBudgetCommandOutput,
} from "./commands/CreateBudgetCommand";
import {
CreateNotificationCommand,
CreateNotificationCommandInput,
CreateNotificationCommandOutput,
} from "./commands/CreateNotificationCommand";
import {
CreateSubscriberCommand,
CreateSubscriberCommandInput,
CreateSubscriberCommandOutput,
} from "./commands/CreateSubscriberCommand";
import {
DeleteBudgetActionCommand,
DeleteBudgetActionCommandInput,
DeleteBudgetActionCommandOutput,
} from "./commands/DeleteBudgetActionCommand";
import {
DeleteBudgetCommand,
DeleteBudgetCommandInput,
DeleteBudgetCommandOutput,
} from "./commands/DeleteBudgetCommand";
import {
DeleteNotificationCommand,
DeleteNotificationCommandInput,
DeleteNotificationCommandOutput,
} from "./commands/DeleteNotificationCommand";
import {
DeleteSubscriberCommand,
DeleteSubscriberCommandInput,
DeleteSubscriberCommandOutput,
} from "./commands/DeleteSubscriberCommand";
import {
DescribeBudgetActionCommand,
DescribeBudgetActionCommandInput,
DescribeBudgetActionCommandOutput,
} from "./commands/DescribeBudgetActionCommand";
import {
DescribeBudgetActionHistoriesCommand,
DescribeBudgetActionHistoriesCommandInput,
DescribeBudgetActionHistoriesCommandOutput,
} from "./commands/DescribeBudgetActionHistoriesCommand";
import {
DescribeBudgetActionsForAccountCommand,
DescribeBudgetActionsForAccountCommandInput,
DescribeBudgetActionsForAccountCommandOutput,
} from "./commands/DescribeBudgetActionsForAccountCommand";
import {
DescribeBudgetActionsForBudgetCommand,
DescribeBudgetActionsForBudgetCommandInput,
DescribeBudgetActionsForBudgetCommandOutput,
} from "./commands/DescribeBudgetActionsForBudgetCommand";
import {
DescribeBudgetCommand,
DescribeBudgetCommandInput,
DescribeBudgetCommandOutput,
} from "./commands/DescribeBudgetCommand";
import {
DescribeBudgetPerformanceHistoryCommand,
DescribeBudgetPerformanceHistoryCommandInput,
DescribeBudgetPerformanceHistoryCommandOutput,
} from "./commands/DescribeBudgetPerformanceHistoryCommand";
import {
DescribeBudgetsCommand,
DescribeBudgetsCommandInput,
DescribeBudgetsCommandOutput,
} from "./commands/DescribeBudgetsCommand";
import {
DescribeNotificationsForBudgetCommand,
DescribeNotificationsForBudgetCommandInput,
DescribeNotificationsForBudgetCommandOutput,
} from "./commands/DescribeNotificationsForBudgetCommand";
import {
DescribeSubscribersForNotificationCommand,
DescribeSubscribersForNotificationCommandInput,
DescribeSubscribersForNotificationCommandOutput,
} from "./commands/DescribeSubscribersForNotificationCommand";
import {
ExecuteBudgetActionCommand,
ExecuteBudgetActionCommandInput,
ExecuteBudgetActionCommandOutput,
} from "./commands/ExecuteBudgetActionCommand";
import {
UpdateBudgetActionCommand,
UpdateBudgetActionCommandInput,
UpdateBudgetActionCommandOutput,
} from "./commands/UpdateBudgetActionCommand";
import {
UpdateBudgetCommand,
UpdateBudgetCommandInput,
UpdateBudgetCommandOutput,
} from "./commands/UpdateBudgetCommand";
import {
UpdateNotificationCommand,
UpdateNotificationCommandInput,
UpdateNotificationCommandOutput,
} from "./commands/UpdateNotificationCommand";
import {
UpdateSubscriberCommand,
UpdateSubscriberCommandInput,
UpdateSubscriberCommandOutput,
} from "./commands/UpdateSubscriberCommand";
/**
* <p>The AWS Budgets API enables you to use AWS Budgets to plan your service usage, service costs, and instance reservations. The API reference provides descriptions, syntax, and usage examples for each of the actions and data types for AWS Budgets. </p>
* <p>Budgets provide you with a way to see the following information:</p>
* <ul>
* <li>
* <p>How close your plan is to your budgeted amount or to the free tier limits</p>
* </li>
* <li>
* <p>Your usage-to-date, including how much you've used of your Reserved Instances (RIs)</p>
* </li>
* <li>
* <p>Your current estimated charges from AWS, and how much your predicted usage will accrue in charges by the end of the month</p>
* </li>
* <li>
* <p>How much of your budget has been used</p>
* </li>
* </ul>
* <p>AWS updates your budget status several times a day. Budgets track your unblended costs, subscriptions, refunds, and RIs. You can create the following types of budgets:</p>
* <ul>
* <li>
* <p>
* <b>Cost budgets</b> - Plan how much you want to spend on a service.</p>
* </li>
* <li>
* <p>
* <b>Usage budgets</b> - Plan how much you want to use one or more services.</p>
* </li>
* <li>
* <p>
* <b>RI utilization budgets</b> - Define a utilization threshold, and receive alerts when your RI usage falls below that threshold. This lets you see if your RIs are unused or under-utilized.</p>
* </li>
* <li>
* <p>
* <b>RI coverage budgets</b> - Define a coverage threshold, and receive alerts when the number of your instance hours that are covered by RIs fall below that threshold. This lets you see how much of your instance usage is covered by a reservation.</p>
* </li>
* </ul>
* <p>Service Endpoint</p>
* <p>The AWS Budgets API provides the following endpoint:</p>
* <ul>
* <li>
* <p>https://budgets.amazonaws.com</p>
* </li>
* </ul>
* <p>For information about costs that are associated with the AWS Budgets API, see <a href="https://aws.amazon.com/aws-cost-management/pricing/">AWS Cost Management Pricing</a>.</p>
*/
export class Budgets extends BudgetsClient {
/**
* <p>Creates a budget and, if included, notifications and subscribers. </p>
* <important>
* <p>Only one of <code>BudgetLimit</code> or <code>PlannedBudgetLimits</code> can be present in the syntax at one time. Use the syntax that matches your case. The Request Syntax section shows the <code>BudgetLimit</code> syntax. For <code>PlannedBudgetLimits</code>, see the <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_budgets_CreateBudget.html#API_CreateBudget_Examples">Examples</a> section. </p>
* </important>
*/
public createBudget(
args: CreateBudgetCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateBudgetCommandOutput>;
public createBudget(args: CreateBudgetCommandInput, cb: (err: any, data?: CreateBudgetCommandOutput) => void): void;
public createBudget(
args: CreateBudgetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateBudgetCommandOutput) => void
): void;
public createBudget(
args: CreateBudgetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateBudgetCommandOutput) => void),
cb?: (err: any, data?: CreateBudgetCommandOutput) => void
): Promise<CreateBudgetCommandOutput> | void {
const command = new CreateBudgetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Creates a budget action.
* </p>
*/
public createBudgetAction(
args: CreateBudgetActionCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateBudgetActionCommandOutput>;
public createBudgetAction(
args: CreateBudgetActionCommandInput,
cb: (err: any, data?: CreateBudgetActionCommandOutput) => void
): void;
public createBudgetAction(
args: CreateBudgetActionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateBudgetActionCommandOutput) => void
): void;
public createBudgetAction(
args: CreateBudgetActionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateBudgetActionCommandOutput) => void),
cb?: (err: any, data?: CreateBudgetActionCommandOutput) => void
): Promise<CreateBudgetActionCommandOutput> | void {
const command = new CreateBudgetActionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a notification. You must create the budget before you create the associated notification.</p>
*/
public createNotification(
args: CreateNotificationCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateNotificationCommandOutput>;
public createNotification(
args: CreateNotificationCommandInput,
cb: (err: any, data?: CreateNotificationCommandOutput) => void
): void;
public createNotification(
args: CreateNotificationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateNotificationCommandOutput) => void
): void;
public createNotification(
args: CreateNotificationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateNotificationCommandOutput) => void),
cb?: (err: any, data?: CreateNotificationCommandOutput) => void
): Promise<CreateNotificationCommandOutput> | void {
const command = new CreateNotificationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a subscriber. You must create the associated budget and notification before you create the subscriber.</p>
*/
public createSubscriber(
args: CreateSubscriberCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateSubscriberCommandOutput>;
public createSubscriber(
args: CreateSubscriberCommandInput,
cb: (err: any, data?: CreateSubscriberCommandOutput) => void
): void;
public createSubscriber(
args: CreateSubscriberCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateSubscriberCommandOutput) => void
): void;
public createSubscriber(
args: CreateSubscriberCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateSubscriberCommandOutput) => void),
cb?: (err: any, data?: CreateSubscriberCommandOutput) => void
): Promise<CreateSubscriberCommandOutput> | void {
const command = new CreateSubscriberCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a budget. You can delete your budget at any time.</p>
* <important>
* <p>Deleting a budget also deletes the notifications and subscribers that are associated with that budget.</p>
* </important>
*/
public deleteBudget(
args: DeleteBudgetCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteBudgetCommandOutput>;
public deleteBudget(args: DeleteBudgetCommandInput, cb: (err: any, data?: DeleteBudgetCommandOutput) => void): void;
public deleteBudget(
args: DeleteBudgetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteBudgetCommandOutput) => void
): void;
public deleteBudget(
args: DeleteBudgetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteBudgetCommandOutput) => void),
cb?: (err: any, data?: DeleteBudgetCommandOutput) => void
): Promise<DeleteBudgetCommandOutput> | void {
const command = new DeleteBudgetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Deletes a budget action.
* </p>
*/
public deleteBudgetAction(
args: DeleteBudgetActionCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteBudgetActionCommandOutput>;
public deleteBudgetAction(
args: DeleteBudgetActionCommandInput,
cb: (err: any, data?: DeleteBudgetActionCommandOutput) => void
): void;
public deleteBudgetAction(
args: DeleteBudgetActionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteBudgetActionCommandOutput) => void
): void;
public deleteBudgetAction(
args: DeleteBudgetActionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteBudgetActionCommandOutput) => void),
cb?: (err: any, data?: DeleteBudgetActionCommandOutput) => void
): Promise<DeleteBudgetActionCommandOutput> | void {
const command = new DeleteBudgetActionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a notification.</p>
* <important>
* <p>Deleting a notification also deletes the subscribers that are associated with the notification.</p>
* </important>
*/
public deleteNotification(
args: DeleteNotificationCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteNotificationCommandOutput>;
public deleteNotification(
args: DeleteNotificationCommandInput,
cb: (err: any, data?: DeleteNotificationCommandOutput) => void
): void;
public deleteNotification(
args: DeleteNotificationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteNotificationCommandOutput) => void
): void;
public deleteNotification(
args: DeleteNotificationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteNotificationCommandOutput) => void),
cb?: (err: any, data?: DeleteNotificationCommandOutput) => void
): Promise<DeleteNotificationCommandOutput> | void {
const command = new DeleteNotificationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a subscriber.</p>
* <important>
* <p>Deleting the last subscriber to a notification also deletes the notification.</p>
* </important>
*/
public deleteSubscriber(
args: DeleteSubscriberCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteSubscriberCommandOutput>;
public deleteSubscriber(
args: DeleteSubscriberCommandInput,
cb: (err: any, data?: DeleteSubscriberCommandOutput) => void
): void;
public deleteSubscriber(
args: DeleteSubscriberCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteSubscriberCommandOutput) => void
): void;
public deleteSubscriber(
args: DeleteSubscriberCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteSubscriberCommandOutput) => void),
cb?: (err: any, data?: DeleteSubscriberCommandOutput) => void
): Promise<DeleteSubscriberCommandOutput> | void {
const command = new DeleteSubscriberCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Describes a budget.</p>
* <important>
* <p>The Request Syntax section shows the <code>BudgetLimit</code> syntax. For <code>PlannedBudgetLimits</code>, see the <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_budgets_DescribeBudget.html#API_DescribeBudget_Examples">Examples</a> section. </p>
* </important>
*/
public describeBudget(
args: DescribeBudgetCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeBudgetCommandOutput>;
public describeBudget(
args: DescribeBudgetCommandInput,
cb: (err: any, data?: DescribeBudgetCommandOutput) => void
): void;
public describeBudget(
args: DescribeBudgetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeBudgetCommandOutput) => void
): void;
public describeBudget(
args: DescribeBudgetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeBudgetCommandOutput) => void),
cb?: (err: any, data?: DescribeBudgetCommandOutput) => void
): Promise<DescribeBudgetCommandOutput> | void {
const command = new DescribeBudgetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Describes a budget action detail.
* </p>
*/
public describeBudgetAction(
args: DescribeBudgetActionCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeBudgetActionCommandOutput>;
public describeBudgetAction(
args: DescribeBudgetActionCommandInput,
cb: (err: any, data?: DescribeBudgetActionCommandOutput) => void
): void;
public describeBudgetAction(
args: DescribeBudgetActionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeBudgetActionCommandOutput) => void
): void;
public describeBudgetAction(
args: DescribeBudgetActionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeBudgetActionCommandOutput) => void),
cb?: (err: any, data?: DescribeBudgetActionCommandOutput) => void
): Promise<DescribeBudgetActionCommandOutput> | void {
const command = new DescribeBudgetActionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Describes a budget action history detail.
* </p>
*/
public describeBudgetActionHistories(
args: DescribeBudgetActionHistoriesCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeBudgetActionHistoriesCommandOutput>;
public describeBudgetActionHistories(
args: DescribeBudgetActionHistoriesCommandInput,
cb: (err: any, data?: DescribeBudgetActionHistoriesCommandOutput) => void
): void;
public describeBudgetActionHistories(
args: DescribeBudgetActionHistoriesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeBudgetActionHistoriesCommandOutput) => void
): void;
public describeBudgetActionHistories(
args: DescribeBudgetActionHistoriesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeBudgetActionHistoriesCommandOutput) => void),
cb?: (err: any, data?: DescribeBudgetActionHistoriesCommandOutput) => void
): Promise<DescribeBudgetActionHistoriesCommandOutput> | void {
const command = new DescribeBudgetActionHistoriesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Describes all of the budget actions for an account.
* </p>
*/
public describeBudgetActionsForAccount(
args: DescribeBudgetActionsForAccountCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeBudgetActionsForAccountCommandOutput>;
public describeBudgetActionsForAccount(
args: DescribeBudgetActionsForAccountCommandInput,
cb: (err: any, data?: DescribeBudgetActionsForAccountCommandOutput) => void
): void;
public describeBudgetActionsForAccount(
args: DescribeBudgetActionsForAccountCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeBudgetActionsForAccountCommandOutput) => void
): void;
public describeBudgetActionsForAccount(
args: DescribeBudgetActionsForAccountCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeBudgetActionsForAccountCommandOutput) => void),
cb?: (err: any, data?: DescribeBudgetActionsForAccountCommandOutput) => void
): Promise<DescribeBudgetActionsForAccountCommandOutput> | void {
const command = new DescribeBudgetActionsForAccountCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Describes all of the budget actions for a budget.
* </p>
*/
public describeBudgetActionsForBudget(
args: DescribeBudgetActionsForBudgetCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeBudgetActionsForBudgetCommandOutput>;
public describeBudgetActionsForBudget(
args: DescribeBudgetActionsForBudgetCommandInput,
cb: (err: any, data?: DescribeBudgetActionsForBudgetCommandOutput) => void
): void;
public describeBudgetActionsForBudget(
args: DescribeBudgetActionsForBudgetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeBudgetActionsForBudgetCommandOutput) => void
): void;
public describeBudgetActionsForBudget(
args: DescribeBudgetActionsForBudgetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeBudgetActionsForBudgetCommandOutput) => void),
cb?: (err: any, data?: DescribeBudgetActionsForBudgetCommandOutput) => void
): Promise<DescribeBudgetActionsForBudgetCommandOutput> | void {
const command = new DescribeBudgetActionsForBudgetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Describes the history for <code>DAILY</code>, <code>MONTHLY</code>, and <code>QUARTERLY</code> budgets. Budget history isn't available for <code>ANNUAL</code> budgets.</p>
*/
public describeBudgetPerformanceHistory(
args: DescribeBudgetPerformanceHistoryCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeBudgetPerformanceHistoryCommandOutput>;
public describeBudgetPerformanceHistory(
args: DescribeBudgetPerformanceHistoryCommandInput,
cb: (err: any, data?: DescribeBudgetPerformanceHistoryCommandOutput) => void
): void;
public describeBudgetPerformanceHistory(
args: DescribeBudgetPerformanceHistoryCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeBudgetPerformanceHistoryCommandOutput) => void
): void;
public describeBudgetPerformanceHistory(
args: DescribeBudgetPerformanceHistoryCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeBudgetPerformanceHistoryCommandOutput) => void),
cb?: (err: any, data?: DescribeBudgetPerformanceHistoryCommandOutput) => void
): Promise<DescribeBudgetPerformanceHistoryCommandOutput> | void {
const command = new DescribeBudgetPerformanceHistoryCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the budgets that are associated with an account.</p>
* <important>
* <p>The Request Syntax section shows the <code>BudgetLimit</code> syntax. For <code>PlannedBudgetLimits</code>, see the <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_budgets_DescribeBudgets.html#API_DescribeBudgets_Examples">Examples</a> section. </p>
* </important>
*/
public describeBudgets(
args: DescribeBudgetsCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeBudgetsCommandOutput>;
public describeBudgets(
args: DescribeBudgetsCommandInput,
cb: (err: any, data?: DescribeBudgetsCommandOutput) => void
): void;
public describeBudgets(
args: DescribeBudgetsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeBudgetsCommandOutput) => void
): void;
public describeBudgets(
args: DescribeBudgetsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeBudgetsCommandOutput) => void),
cb?: (err: any, data?: DescribeBudgetsCommandOutput) => void
): Promise<DescribeBudgetsCommandOutput> | void {
const command = new DescribeBudgetsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the notifications that are associated with a budget.</p>
*/
public describeNotificationsForBudget(
args: DescribeNotificationsForBudgetCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeNotificationsForBudgetCommandOutput>;
public describeNotificationsForBudget(
args: DescribeNotificationsForBudgetCommandInput,
cb: (err: any, data?: DescribeNotificationsForBudgetCommandOutput) => void
): void;
public describeNotificationsForBudget(
args: DescribeNotificationsForBudgetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeNotificationsForBudgetCommandOutput) => void
): void;
public describeNotificationsForBudget(
args: DescribeNotificationsForBudgetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeNotificationsForBudgetCommandOutput) => void),
cb?: (err: any, data?: DescribeNotificationsForBudgetCommandOutput) => void
): Promise<DescribeNotificationsForBudgetCommandOutput> | void {
const command = new DescribeNotificationsForBudgetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the subscribers that are associated with a notification.</p>
*/
public describeSubscribersForNotification(
args: DescribeSubscribersForNotificationCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeSubscribersForNotificationCommandOutput>;
public describeSubscribersForNotification(
args: DescribeSubscribersForNotificationCommandInput,
cb: (err: any, data?: DescribeSubscribersForNotificationCommandOutput) => void
): void;
public describeSubscribersForNotification(
args: DescribeSubscribersForNotificationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeSubscribersForNotificationCommandOutput) => void
): void;
public describeSubscribersForNotification(
args: DescribeSubscribersForNotificationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeSubscribersForNotificationCommandOutput) => void),
cb?: (err: any, data?: DescribeSubscribersForNotificationCommandOutput) => void
): Promise<DescribeSubscribersForNotificationCommandOutput> | void {
const command = new DescribeSubscribersForNotificationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Executes a budget action.
* </p>
*/
public executeBudgetAction(
args: ExecuteBudgetActionCommandInput,
options?: __HttpHandlerOptions
): Promise<ExecuteBudgetActionCommandOutput>;
public executeBudgetAction(
args: ExecuteBudgetActionCommandInput,
cb: (err: any, data?: ExecuteBudgetActionCommandOutput) => void
): void;
public executeBudgetAction(
args: ExecuteBudgetActionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ExecuteBudgetActionCommandOutput) => void
): void;
public executeBudgetAction(
args: ExecuteBudgetActionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ExecuteBudgetActionCommandOutput) => void),
cb?: (err: any, data?: ExecuteBudgetActionCommandOutput) => void
): Promise<ExecuteBudgetActionCommandOutput> | void {
const command = new ExecuteBudgetActionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates a budget. You can change every part of a budget except for the <code>budgetName</code> and the <code>calculatedSpend</code>. When you modify a budget, the <code>calculatedSpend</code> drops to zero until AWS has new usage data to use for forecasting.</p>
* <important>
* <p>Only one of <code>BudgetLimit</code> or <code>PlannedBudgetLimits</code> can be present in the syntax at one time. Use the syntax that matches your case. The Request Syntax section shows the <code>BudgetLimit</code> syntax. For <code>PlannedBudgetLimits</code>, see the <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_budgets_UpdateBudget.html#API_UpdateBudget_Examples">Examples</a> section. </p>
* </important>
*/
public updateBudget(
args: UpdateBudgetCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateBudgetCommandOutput>;
public updateBudget(args: UpdateBudgetCommandInput, cb: (err: any, data?: UpdateBudgetCommandOutput) => void): void;
public updateBudget(
args: UpdateBudgetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateBudgetCommandOutput) => void
): void;
public updateBudget(
args: UpdateBudgetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateBudgetCommandOutput) => void),
cb?: (err: any, data?: UpdateBudgetCommandOutput) => void
): Promise<UpdateBudgetCommandOutput> | void {
const command = new UpdateBudgetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Updates a budget action.
* </p>
*/
public updateBudgetAction(
args: UpdateBudgetActionCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateBudgetActionCommandOutput>;
public updateBudgetAction(
args: UpdateBudgetActionCommandInput,
cb: (err: any, data?: UpdateBudgetActionCommandOutput) => void
): void;
public updateBudgetAction(
args: UpdateBudgetActionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateBudgetActionCommandOutput) => void
): void;
public updateBudgetAction(
args: UpdateBudgetActionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateBudgetActionCommandOutput) => void),
cb?: (err: any, data?: UpdateBudgetActionCommandOutput) => void
): Promise<UpdateBudgetActionCommandOutput> | void {
const command = new UpdateBudgetActionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates a notification.</p>
*/
public updateNotification(
args: UpdateNotificationCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateNotificationCommandOutput>;
public updateNotification(
args: UpdateNotificationCommandInput,
cb: (err: any, data?: UpdateNotificationCommandOutput) => void
): void;
public updateNotification(
args: UpdateNotificationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateNotificationCommandOutput) => void
): void;
public updateNotification(
args: UpdateNotificationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateNotificationCommandOutput) => void),
cb?: (err: any, data?: UpdateNotificationCommandOutput) => void
): Promise<UpdateNotificationCommandOutput> | void {
const command = new UpdateNotificationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates a subscriber.</p>
*/
public updateSubscriber(
args: UpdateSubscriberCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateSubscriberCommandOutput>;
public updateSubscriber(
args: UpdateSubscriberCommandInput,
cb: (err: any, data?: UpdateSubscriberCommandOutput) => void
): void;
public updateSubscriber(
args: UpdateSubscriberCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateSubscriberCommandOutput) => void
): void;
public updateSubscriber(
args: UpdateSubscriberCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateSubscriberCommandOutput) => void),
cb?: (err: any, data?: UpdateSubscriberCommandOutput) => void
): Promise<UpdateSubscriberCommandOutput> | void {
const command = new UpdateSubscriberCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
} | the_stack |
export default function makeDashboard(integrationId: string) {
return {
annotations: {
list: [
{
builtIn: 1,
datasource: "-- Grafana --",
enable: true,
hide: true,
iconColor: "rgba(0, 211, 255, 1)",
name: "Annotations & Alerts",
type: "dashboard"
}
]
},
editable: true,
gnetId: null,
graphTooltip: 0,
iteration: 1623960872107,
links: [],
panels: [
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 7,
w: 24,
x: 0,
y: 0
},
hiddenSeries: false,
id: 2,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(requests_slow_raft{integration_id="${integrationId}"})`,
interval: "",
legendFormat: "Slow Raft Proposals",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Slow Raft Proposals",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:141",
format: "short",
label: "proposals",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:142",
format: "short",
label: "",
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 7,
w: 24,
x: 0,
y: 7
},
hiddenSeries: false,
id: 4,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(requests_slow_distsender{integration_id="${integrationId}"})`,
interval: "",
legendFormat: "Slow DistSender RPCs",
queryType: "randomWalk",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Slow DistSender RPCs",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:88",
format: "short",
label: "proposals",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:89",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 7,
w: 24,
x: 0,
y: 14
},
hiddenSeries: false,
id: 6,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(requests_slow_lease{integration_id="${integrationId}"})`,
interval: "",
legendFormat: "Slow Lease Acquisitions",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Slow Lease Acquisitions",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:245",
format: "short",
label: "lease acquisitions",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:246",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
},
{
aliasColors: {},
bars: false,
dashLength: 10,
dashes: false,
datasource: "metrics",
fieldConfig: {
defaults: {},
overrides: []
},
fill: 1,
fillGradient: 0,
gridPos: {
h: 7,
w: 24,
x: 0,
y: 21
},
hiddenSeries: false,
id: 8,
legend: {
avg: false,
current: false,
max: false,
min: false,
show: true,
total: false,
values: false
},
lines: true,
linewidth: 1,
nullPointMode: "null",
options: {
alertThreshold: true
},
percentage: false,
pluginVersion: "",
pointradius: 2,
points: false,
renderer: "flot",
seriesOverrides: [],
spaceLength: 10,
stack: false,
steppedLine: false,
targets: [
{
exemplar: true,
expr: `sum(requests_slow_latch{integration_id="${integrationId}"})`,
interval: "",
legendFormat: "Slow Latch Acquisitions",
refId: "A"
}
],
thresholds: [],
timeFrom: null,
timeRegions: [],
timeShift: null,
title: "Slow Latch Acquisitions",
tooltip: {
shared: true,
sort: 0,
value_type: "individual"
},
type: "graph",
xaxis: {
buckets: null,
mode: "time",
name: null,
show: true,
values: []
},
yaxes: [
{
$$hashKey: "object:298",
format: "short",
label: "latch acquisitions",
logBase: 1,
max: null,
min: "0",
show: true
},
{
$$hashKey: "object:299",
format: "short",
label: null,
logBase: 1,
max: null,
min: null,
show: true
}
],
yaxis: {
align: false,
alignLevel: null
}
}
],
schemaVersion: 27,
style: "dark",
tags: [],
templating: {
list: [
{
allValue: ".*",
current: {
selected: false,
text: "All",
value: "$__all"
},
datasource: "metrics",
definition: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`,
description: null,
error: null,
hide: 0,
includeAll: true,
label: "Node",
multi: false,
name: "node",
options: [],
query: {
query: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`,
refId: "Prometheus-node-Variable-Query"
},
refresh: 1,
regex: "",
skipUrlSync: false,
sort: 3,
tagValuesQuery: "",
tags: [],
tagsQuery: "",
type: "query",
useTags: false
}
]
},
time: {
from: "now-1h",
to: "now"
},
timepicker: {},
timezone: "utc",
title: "CRDB Console: Slow Requests",
uid: `slo-${integrationId}`,
version: 2
};
}
export type Dashboard = ReturnType<typeof makeDashboard>; | the_stack |
* @module AccuDraw
*/
import { BeUiEvent } from "@itwin/core-bentley";
import {
AccuDraw, BeButtonEvent, CompassMode, IModelApp, ItemField,
NotifyMessageDetails, OutputMessagePriority, QuantityType, RotationMode,
} from "@itwin/core-frontend";
import { ConditionalBooleanValue } from "@itwin/appui-abstract";
import { UiStateStorage, UiStateStorageStatus } from "@itwin/core-react";
import { UiFramework, UserSettingsProvider } from "../UiFramework";
import { SyncUiEventDispatcher, SyncUiEventId } from "../syncui/SyncUiEventDispatcher";
import { AccuDrawUiSettings } from "./AccuDrawUiSettings";
// cspell:ignore dont
const compassModeToKeyMap = new Map<CompassMode, string>([
[CompassMode.Polar, "polar"],
[CompassMode.Rectangular, "rectangular"],
]);
const rotationModeToKeyMap = new Map<RotationMode, string>([
[RotationMode.Top, "top"],
[RotationMode.Front, "front"],
[RotationMode.Side, "side"],
[RotationMode.View, "view"],
[RotationMode.ACS, "ACS"],
[RotationMode.Context, "context"],
]);
/** Arguments for [[AccuDrawSetFieldFocusEvent]]
* @beta */
export interface AccuDrawSetFieldFocusEventArgs {
field: ItemField;
}
/** AccuDraw Set Field Focus event
* @beta */
export class AccuDrawSetFieldFocusEvent extends BeUiEvent<AccuDrawSetFieldFocusEventArgs> { }
/** Arguments for [[AccuDrawSetFieldValueToUiEvent]]
* @beta */
export interface AccuDrawSetFieldValueToUiEventArgs {
field: ItemField;
value: number;
formattedValue: string;
}
/** AccuDraw Set Field Value to Ui event
* @beta */
export class AccuDrawSetFieldValueToUiEvent extends BeUiEvent<AccuDrawSetFieldValueToUiEventArgs> { }
/** Arguments for [[AccuDrawSetFieldValueFromUiEvent]]
* @beta */
export interface AccuDrawSetFieldValueFromUiEventArgs {
field: ItemField;
stringValue: string;
}
/** AccuDraw Set Field Value from Ui event
* @beta */
export class AccuDrawSetFieldValueFromUiEvent extends BeUiEvent<AccuDrawSetFieldValueFromUiEventArgs> { }
/** Arguments for [[AccuDrawSetFieldLockEvent]]
* @beta */
export interface AccuDrawSetFieldLockEventArgs {
field: ItemField;
lock: boolean;
}
/** AccuDraw Set Field Lock event
* @beta */
export class AccuDrawSetFieldLockEvent extends BeUiEvent<AccuDrawSetFieldLockEventArgs> { }
/** Arguments for [[AccuDrawSetCompassModeEvent]]
* @beta */
export interface AccuDrawSetCompassModeEventArgs {
mode: CompassMode;
}
/** AccuDraw Set Compass Mode event
* @beta */
export class AccuDrawSetCompassModeEvent extends BeUiEvent<AccuDrawSetCompassModeEventArgs> { }
/** AccuDraw Grab Input Focus event
* @beta */
export class AccuDrawGrabInputFocusEvent extends BeUiEvent<{}> { }
/** AccuDraw Ui Settings Changed event
* @beta */
export class AccuDrawUiSettingsChangedEvent extends BeUiEvent<{}> { }
/** Implementation of AccuDraw that sends events for UI and status changes
* @beta
*/
export class FrameworkAccuDraw extends AccuDraw implements UserSettingsProvider {
private static _displayNotifications = false;
private static _uiSettings: AccuDrawUiSettings | undefined;
private static _settingsNamespace = "AppUiSettings";
private static _notificationsKey = "AccuDrawNotifications";
public readonly providerId = "FrameworkAccuDraw";
/** AccuDraw Set Field Focus event. */
public static readonly onAccuDrawSetFieldFocusEvent = new AccuDrawSetFieldFocusEvent();
/** AccuDraw Set Field Value to Ui event. */
public static readonly onAccuDrawSetFieldValueToUiEvent = new AccuDrawSetFieldValueToUiEvent();
/** AccuDraw Set Field Value from Ui event. */
public static readonly onAccuDrawSetFieldValueFromUiEvent = new AccuDrawSetFieldValueFromUiEvent();
/** AccuDraw Set Field Lock event. */
public static readonly onAccuDrawSetFieldLockEvent = new AccuDrawSetFieldLockEvent();
/** AccuDraw Set Mode event. */
public static readonly onAccuDrawSetCompassModeEvent = new AccuDrawSetCompassModeEvent();
/** AccuDraw Grab Input Focus event. */
public static readonly onAccuDrawGrabInputFocusEvent = new AccuDrawGrabInputFocusEvent();
/** Determines if AccuDraw.rotationMode === RotationMode.Top */
public static readonly isTopRotationConditional = new ConditionalBooleanValue(() => IModelApp.accuDraw.rotationMode === RotationMode.Top, [SyncUiEventId.AccuDrawRotationChanged]);
/** Determines if AccuDraw.rotationMode === RotationMode.Front */
public static readonly isFrontRotationConditional = new ConditionalBooleanValue(() => IModelApp.accuDraw.rotationMode === RotationMode.Front, [SyncUiEventId.AccuDrawRotationChanged]);
/** Determines if AccuDraw.rotationMode === RotationMode.Side */
public static readonly isSideRotationConditional = new ConditionalBooleanValue(() => IModelApp.accuDraw.rotationMode === RotationMode.Side, [SyncUiEventId.AccuDrawRotationChanged]);
/** Determines if AccuDraw.rotationMode === RotationMode.View */
public static readonly isViewRotationConditional = new ConditionalBooleanValue(() => IModelApp.accuDraw.rotationMode === RotationMode.View, [SyncUiEventId.AccuDrawRotationChanged]);
/** Determines if AccuDraw.rotationMode === RotationMode.ACS */
public static readonly isACSRotationConditional = new ConditionalBooleanValue(() => IModelApp.accuDraw.rotationMode === RotationMode.ACS, [SyncUiEventId.AccuDrawRotationChanged]);
/** Determines if AccuDraw.rotationMode === RotationMode.Context */
public static readonly isContextRotationConditional = new ConditionalBooleanValue(() => IModelApp.accuDraw.rotationMode === RotationMode.Context, [SyncUiEventId.AccuDrawRotationChanged]);
/** Determines if AccuDraw.compassMode === CompassMode.Polar */
public static readonly isPolarModeConditional = new ConditionalBooleanValue(() => IModelApp.accuDraw.compassMode === CompassMode.Polar, [SyncUiEventId.AccuDrawCompassModeChanged]);
/** Determines if AccuDraw.compassMode === CompassMode.Rectangular */
public static readonly isRectangularModeConditional = new ConditionalBooleanValue(() => IModelApp.accuDraw.compassMode === CompassMode.Rectangular, [SyncUiEventId.AccuDrawCompassModeChanged]);
/** AccuDraw Grab Input Focus event. */
public static readonly onAccuDrawUiSettingsChangedEvent = new AccuDrawUiSettingsChangedEvent();
/** Determines if notifications should be displayed for AccuDraw changes */
public static get displayNotifications(): boolean { return FrameworkAccuDraw._displayNotifications; }
public static set displayNotifications(v: boolean) {
FrameworkAccuDraw._displayNotifications = v;
UiFramework.getUiStateStorage().saveSetting(this._settingsNamespace, this._notificationsKey, v); // eslint-disable-line @typescript-eslint/no-floating-promises
}
/* @internal */
public async loadUserSettings(storage: UiStateStorage): Promise<void> {
const result = await storage.getSetting(FrameworkAccuDraw._settingsNamespace, FrameworkAccuDraw._notificationsKey);
if (result.status === UiStateStorageStatus.Success)
FrameworkAccuDraw._displayNotifications = result.setting;
}
/** AccuDraw User Interface settings */
public static get uiStateStorage(): AccuDrawUiSettings | undefined { return FrameworkAccuDraw._uiSettings; }
public static set uiStateStorage(v: AccuDrawUiSettings | undefined) {
FrameworkAccuDraw._uiSettings = v;
FrameworkAccuDraw.onAccuDrawUiSettingsChangedEvent.emit({});
}
constructor() {
super();
FrameworkAccuDraw.onAccuDrawSetFieldValueFromUiEvent.addListener(this.handleSetFieldValueFromUiEvent);
UiFramework.registerUserSettingsProvider(this);
}
private handleSetFieldValueFromUiEvent = async (args: AccuDrawSetFieldValueFromUiEventArgs) => {
return this.processFieldInput(args.field, args.stringValue, false);
};
/** @internal */
public override onCompassModeChange(): void {
FrameworkAccuDraw.onAccuDrawSetCompassModeEvent.emit({ mode: this.compassMode });
SyncUiEventDispatcher.dispatchSyncUiEvent(SyncUiEventId.AccuDrawCompassModeChanged);
this.outputCompassModeMessage();
}
/** @internal */
public override onRotationModeChange(): void {
SyncUiEventDispatcher.dispatchSyncUiEvent(SyncUiEventId.AccuDrawRotationChanged);
this.outputRotationMessage();
}
/** @internal */
public override onFieldLockChange(index: ItemField): void {
FrameworkAccuDraw.onAccuDrawSetFieldLockEvent.emit({ field: index, lock: this.getFieldLock(index) });
}
/** @internal */
public override onFieldValueChange(index: ItemField): void {
const value = this.getValueByIndex(index);
const formattedValue = FrameworkAccuDraw.getFieldDisplayValue(index);
FrameworkAccuDraw.onAccuDrawSetFieldValueToUiEvent.emit({ field: index, value, formattedValue });
}
private fieldValuesChanged(): void {
this.onFieldValueChange(ItemField.X_Item);
this.onFieldValueChange(ItemField.Y_Item);
this.onFieldValueChange(ItemField.Z_Item);
this.onFieldValueChange(ItemField.ANGLE_Item);
this.onFieldValueChange(ItemField.DIST_Item);
}
/** @internal */
public override setFocusItem(index: ItemField): void {
FrameworkAccuDraw.onAccuDrawSetFieldFocusEvent.emit({ field: index });
}
/** Implemented by sub-classes to update ui fields to show current deltas or coordinates when inactive.
* Should also choose active x or y input field in rectangular mode based on cursor position when
* axis isn't locked to support "smart lock".
* @internal
*/
public override onMotion(_ev: BeButtonEvent): void {
if (!this.isEnabled || this.isDeactivated || UiFramework.isContextMenuOpen)
return;
this.fieldValuesChanged();
if (!this.dontMoveFocus)
this.setFocusItem(this.newFocus);
}
/** Determine if the AccuDraw UI has focus
* @internal
*/
public override get hasInputFocus(): boolean {
let hasFocus = false;
const el = document.querySelector("div.uifw-accudraw-field-container");
if (el)
hasFocus = el.contains(document.activeElement);
return hasFocus;
}
/** Implement this method to set focus to the AccuDraw UI.
* @internal
*/
public override grabInputFocus(): void {
FrameworkAccuDraw.onAccuDrawGrabInputFocusEvent.emit({});
}
/** Gets the display value for an AccuDraw field */
public static getFieldDisplayValue(index: ItemField): string {
const value = IModelApp.accuDraw.getValueByIndex(index);
let formattedValue = value.toString();
const formatterSpec = IModelApp.quantityFormatter.findFormatterSpecByQuantityType(ItemField.ANGLE_Item === index ? QuantityType.Angle : QuantityType.Length);
// istanbul ignore else
if (formatterSpec)
formattedValue = IModelApp.quantityFormatter.formatQuantity(value, formatterSpec);
return formattedValue;
}
/** AccuDraw Set Field Value from Ui. */
public static setFieldValueFromUi(field: ItemField, stringValue: string): void {
FrameworkAccuDraw.onAccuDrawSetFieldValueFromUiEvent.emit({ field, stringValue });
}
private outputInfoMessage(message: string): void {
// istanbul ignore else
if (FrameworkAccuDraw.displayNotifications)
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, message));
}
private outputCompassModeMessage(): void {
if (FrameworkAccuDraw.displayNotifications) {
let modeKey = compassModeToKeyMap.get(this.compassMode);
// istanbul ignore if
if (modeKey === undefined)
modeKey = "polar";
const modeString = UiFramework.translate(`accuDraw.compassMode.${modeKey}`);
const modeMessage = UiFramework.localization.getLocalizedStringWithNamespace(UiFramework.localizationNamespace, "accuDraw.compassModeSet", { modeString });
this.outputInfoMessage(modeMessage);
}
}
private outputRotationMessage(): void {
if (FrameworkAccuDraw.displayNotifications) {
let rotationKey = rotationModeToKeyMap.get(this.rotationMode);
// istanbul ignore if
if (rotationKey === undefined)
rotationKey = "top";
const rotationString = UiFramework.translate(`accuDraw.rotation.${rotationKey}`);
const rotationMessage = UiFramework.localization.getLocalizedStringWithNamespace(UiFramework.localizationNamespace, "accuDraw.rotationSet", { rotationString });
this.outputInfoMessage(rotationMessage);
}
}
} | the_stack |
import type {
Feature,
Geometry,
Point,
MultiPoint,
LineString,
MultiLineString,
Polygon,
MultiPolygon,
GeometryCollection
} from '@loaders.gl/schema';
import BinaryWriter from './utils/binary-writer';
/**
* Integer code for geometry type
* Reference: https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry#Well-known_binary
*/
enum WKB {
Point = 1,
LineString = 2,
Polygon = 3,
MultiPoint = 4,
MultiLineString = 5,
MultiPolygon = 6,
GeometryCollection = 7
}
/**
* Options for encodeWKB
*/
interface WKBOptions {
/** Does the GeoJSON input have Z values? */
hasZ?: boolean;
/** Does the GeoJSON input have M values? */
hasM?: boolean;
/** Spatial reference for input GeoJSON */
srid?: any;
}
/**
* Encodes a GeoJSON object into WKB
* @param geojson A GeoJSON Feature or Geometry
* @returns string
*/
export default function encodeWKB(
geometry: Geometry | Feature,
options: WKBOptions | {wkb: WKBOptions}
): ArrayBuffer {
if (geometry.type === 'Feature') {
geometry = geometry.geometry;
}
// Options should be wrapped in a `wkb` key, but we allow top-level options here for backwards
// compatibility
if ('wkb' in options) {
options = options.wkb;
}
switch (geometry.type) {
case 'Point':
return encodePoint(geometry.coordinates, options);
case 'LineString':
return encodeLineString(geometry.coordinates, options);
case 'Polygon':
return encodePolygon(geometry.coordinates, options);
case 'MultiPoint':
return encodeMultiPoint(geometry, options);
case 'MultiPolygon':
return encodeMultiPolygon(geometry, options);
case 'MultiLineString':
return encodeMultiLineString(geometry, options);
case 'GeometryCollection':
return encodeGeometryCollection(geometry, options);
default:
const exhaustiveCheck: never = geometry;
throw new Error(`Unhandled case: ${exhaustiveCheck}`);
}
}
/** Calculate the binary size (in the WKB encoding) of a specific GeoJSON geometry */
function getGeometrySize(geometry: Geometry, options: WKBOptions): number {
switch (geometry.type) {
case 'Point':
return getPointSize(options);
case 'LineString':
return getLineStringSize(geometry.coordinates, options);
case 'Polygon':
return getPolygonSize(geometry.coordinates, options);
case 'MultiPoint':
return getMultiPointSize(geometry, options);
case 'MultiPolygon':
return getMultiPolygonSize(geometry, options);
case 'MultiLineString':
return getMultiLineStringSize(geometry, options);
case 'GeometryCollection':
return getGeometryCollectionSize(geometry, options);
default:
const exhaustiveCheck: never = geometry;
throw new Error(`Unhandled case: ${exhaustiveCheck}`);
}
}
/** Encode Point geometry as WKB ArrayBuffer */
function encodePoint(coordinates: Point['coordinates'], options: WKBOptions): ArrayBuffer {
const writer = new BinaryWriter(getPointSize(options));
writer.writeInt8(1);
writeWkbType(writer, WKB.Point, options);
// I believe this special case is to handle writing Point(NaN, NaN) correctly
if (typeof coordinates[0] === 'undefined' && typeof coordinates[1] === 'undefined') {
writer.writeDoubleLE(NaN);
writer.writeDoubleLE(NaN);
if (options.hasZ) {
writer.writeDoubleLE(NaN);
}
if (options.hasM) {
writer.writeDoubleLE(NaN);
}
} else {
writeCoordinate(writer, coordinates, options);
}
return writer.arrayBuffer;
}
/** Write coordinate to buffer */
function writeCoordinate(
writer: BinaryWriter,
coordinate: Point['coordinates'],
options: WKBOptions
): void {
writer.writeDoubleLE(coordinate[0]);
writer.writeDoubleLE(coordinate[1]);
if (options.hasZ) {
writer.writeDoubleLE(coordinate[2]);
}
if (options.hasM) {
writer.writeDoubleLE(coordinate[3]);
}
}
/** Get encoded size of Point geometry */
function getPointSize(options: WKBOptions): number {
const coordinateSize = getCoordinateSize(options);
return 1 + 4 + coordinateSize;
}
/** Encode LineString geometry as WKB ArrayBuffer */
function encodeLineString(
coordinates: LineString['coordinates'],
options: WKBOptions
): ArrayBuffer {
const size = getLineStringSize(coordinates, options);
const writer = new BinaryWriter(size);
writer.writeInt8(1);
writeWkbType(writer, WKB.LineString, options);
writer.writeUInt32LE(coordinates.length);
for (const coordinate of coordinates) {
writeCoordinate(writer, coordinate, options);
}
return writer.arrayBuffer;
}
/** Get encoded size of LineString geometry */
function getLineStringSize(coordinates: LineString['coordinates'], options: WKBOptions): number {
const coordinateSize = getCoordinateSize(options);
return 1 + 4 + 4 + coordinates.length * coordinateSize;
}
/** Encode Polygon geometry as WKB ArrayBuffer */
function encodePolygon(coordinates: Polygon['coordinates'], options: WKBOptions): ArrayBuffer {
const writer = new BinaryWriter(getPolygonSize(coordinates, options));
writer.writeInt8(1);
writeWkbType(writer, WKB.Polygon, options);
const [exteriorRing, ...interiorRings] = coordinates;
if (exteriorRing.length > 0) {
writer.writeUInt32LE(1 + interiorRings.length);
writer.writeUInt32LE(exteriorRing.length);
} else {
writer.writeUInt32LE(0);
}
for (const coordinate of exteriorRing) {
writeCoordinate(writer, coordinate, options);
}
for (const interiorRing of interiorRings) {
writer.writeUInt32LE(interiorRing.length);
for (const coordinate of interiorRing) {
writeCoordinate(writer, coordinate, options);
}
}
return writer.arrayBuffer;
}
/** Get encoded size of Polygon geometry */
function getPolygonSize(coordinates: Polygon['coordinates'], options: WKBOptions): number {
const coordinateSize = getCoordinateSize(options);
const [exteriorRing, ...interiorRings] = coordinates;
let size = 1 + 4 + 4;
if (exteriorRing.length > 0) {
size += 4 + exteriorRing.length * coordinateSize;
}
for (const interiorRing of interiorRings) {
size += 4 + interiorRing.length * coordinateSize;
}
return size;
}
/** Encode MultiPoint geometry as WKB ArrayBufer */
function encodeMultiPoint(multiPoint: MultiPoint, options: WKBOptions) {
const writer = new BinaryWriter(getMultiPointSize(multiPoint, options));
const points = multiPoint.coordinates;
writer.writeInt8(1);
writeWkbType(writer, WKB.MultiPoint, options);
writer.writeUInt32LE(points.length);
for (const point of points) {
// TODO: add srid to this options object? {srid: multiPoint.srid}
const arrayBuffer = encodePoint(point, options);
writer.writeBuffer(arrayBuffer);
}
return writer.arrayBuffer;
}
/** Get encoded size of MultiPoint geometry */
function getMultiPointSize(multiPoint: MultiPoint, options: WKBOptions) {
let coordinateSize = getCoordinateSize(options);
const points = multiPoint.coordinates;
// This is because each point has a 5-byte header?
coordinateSize += 5;
return 1 + 4 + 4 + points.length * coordinateSize;
}
/** Encode MultiLineString geometry as WKB ArrayBufer */
function encodeMultiLineString(multiLineString: MultiLineString, options: WKBOptions) {
const writer = new BinaryWriter(getMultiLineStringSize(multiLineString, options));
const lineStrings = multiLineString.coordinates;
writer.writeInt8(1);
writeWkbType(writer, WKB.MultiLineString, options);
writer.writeUInt32LE(lineStrings.length);
for (const lineString of lineStrings) {
// TODO: Handle srid?
const encodedLineString = encodeLineString(lineString, options);
writer.writeBuffer(encodedLineString);
}
return writer.arrayBuffer;
}
/** Get encoded size of MultiLineString geometry */
function getMultiLineStringSize(multiLineString: MultiLineString, options: WKBOptions): number {
let size = 1 + 4 + 4;
const lineStrings = multiLineString.coordinates;
for (const lineString of lineStrings) {
size += getLineStringSize(lineString, options);
}
return size;
}
function encodeMultiPolygon(multiPolygon: MultiPolygon, options: WKBOptions): ArrayBuffer {
const writer = new BinaryWriter(getMultiPolygonSize(multiPolygon, options));
const polygons = multiPolygon.coordinates;
writer.writeInt8(1);
writeWkbType(writer, WKB.MultiPolygon, options);
writer.writeUInt32LE(polygons.length);
for (const polygon of polygons) {
const encodedPolygon = encodePolygon(polygon, options);
writer.writeBuffer(encodedPolygon);
}
return writer.arrayBuffer;
}
function getMultiPolygonSize(multiPolygon: MultiPolygon, options: WKBOptions): number {
let size = 1 + 4 + 4;
const polygons = multiPolygon.coordinates;
for (const polygon of polygons) {
size += getPolygonSize(polygon, options);
}
return size;
}
function encodeGeometryCollection(
collection: GeometryCollection,
options: WKBOptions
): ArrayBuffer {
const writer = new BinaryWriter(getGeometryCollectionSize(collection, options));
writer.writeInt8(1);
writeWkbType(writer, WKB.GeometryCollection, options);
writer.writeUInt32LE(collection.geometries.length);
for (const geometry of collection.geometries) {
// TODO: handle srid? {srid: collection.srid}
const arrayBuffer = encodeWKB(geometry, options);
writer.writeBuffer(arrayBuffer);
}
return writer.arrayBuffer;
}
function getGeometryCollectionSize(collection: GeometryCollection, options: WKBOptions): number {
let size = 1 + 4 + 4;
for (const geometry of collection.geometries) {
size += getGeometrySize(geometry, options);
}
return size;
}
// HELPERS
/**
* Construct and write WKB integer code
* Reference: https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry#Well-known_binary
*/
function writeWkbType(writer: BinaryWriter, geometryType: number, options: WKBOptions): void {
const {hasZ, hasM, srid} = options;
let dimensionType = 0;
if (!srid) {
if (hasZ && hasM) {
dimensionType += 3000;
} else if (hasZ) {
dimensionType += 1000;
} else if (hasM) {
dimensionType += 2000;
}
} else {
if (hasZ) {
dimensionType |= 0x80000000;
}
if (hasM) {
dimensionType |= 0x40000000;
}
}
writer.writeUInt32LE((dimensionType + geometryType) >>> 0);
}
/** Get coordinate size given Z/M dimensions */
function getCoordinateSize(options: WKBOptions): number {
let coordinateSize = 16;
if (options.hasZ) {
coordinateSize += 8;
}
if (options.hasM) {
coordinateSize += 8;
}
return coordinateSize;
} | the_stack |
import { ControllerAbstract } from './lib'
import { PrompterConfigMode, PrompterViewInner } from '../PrompterView'
import Spline from 'cubic-spline'
import { invert } from 'underscore'
const LOCALSTORAGEMODE = 'prompter-controller-arrowkeys'
type JoyconMode = 'L' | 'R' | 'LR'
/**
* This class handles control of the prompter using
*/
export class JoyConController extends ControllerAbstract {
private prompterView: PrompterViewInner
private invertJoystick = false // change scrolling direction for joystick
private rangeRevMin = -1 // pedal "all back" position, the max-reverse-position
private rangeNeutralMin = -0.25 // pedal "back" position where reverse-range transistions to the neutral range
private rangeNeutralMax = 0.25 // pedal "front" position where scrolling starts, the 0 speed origin
private rangeFwdMax = 1 // pedal "all front" position where scrolling is maxed out
private speedMap = [1, 2, 3, 4, 5, 8, 12, 30]
private reverseSpeedMap = [1, 2, 3, 4, 5, 8, 12, 30]
private speedSpline: Spline
private reverseSpeedSpline: Spline
private updateSpeedHandle: number | null = null
private deadBand = 0.25
private currentPosition = 0
private lastInputValue = ''
private lastUsedJoyconIndex: number = -1
private lastUsedJoyconId: string | null = null
private lastUsedJoyconMode: JoyconMode | null
private lastButtonArray: number[] = []
constructor(view: PrompterViewInner) {
super(view)
this.prompterView = view
// assigns params from URL or falls back to the default
this.invertJoystick = view.configOptions.joycon_invertJoystick || this.invertJoystick
this.speedMap = view.configOptions.joycon_speedMap || this.speedMap
this.reverseSpeedMap = view.configOptions.joycon_reverseSpeedMap || this.reverseSpeedMap
this.rangeRevMin = view.configOptions.joycon_rangeRevMin || this.rangeRevMin
this.rangeNeutralMin = view.configOptions.joycon_rangeNeutralMin || this.rangeNeutralMin
this.rangeNeutralMax = view.configOptions.joycon_rangeNeutralMax || this.rangeNeutralMax
this.rangeFwdMax = view.configOptions.joycon_rangeFwdMax || this.rangeFwdMax
this.deadBand = Math.min(Math.abs(this.rangeNeutralMin), Math.abs(this.rangeNeutralMax))
// validate range settings, they need to be in sequence, or the logic will break
if (this.rangeNeutralMin <= this.rangeRevMin) {
console.error('rangeNeutralMin must be larger to rangeRevMin. Pedal control will not initialize.')
return
}
if (this.rangeNeutralMax <= this.rangeNeutralMin) {
console.error('rangeNeutralMax must be larger to rangeNeutralMin. Pedal control will not initialize')
return
}
if (this.rangeFwdMax <= this.rangeNeutralMax) {
console.error('rangeFwdMax must be larger to rangeNeutralMax. Pedal control will not initialize')
return
}
// create splines, using the input speedMaps, for both the forward range, and the reverse range
this.speedSpline = new Spline(
this.speedMap.map(
(y, index, array) =>
((this.rangeFwdMax - this.rangeNeutralMax) / (array.length - 1)) * index + this.rangeNeutralMax
),
this.speedMap
)
this.reverseSpeedSpline = new Spline(
this.reverseSpeedMap
.reverse()
.map(
(y, index, array) =>
((this.rangeNeutralMin - this.rangeRevMin) / (array.length - 1)) * index + this.rangeRevMin
),
this.reverseSpeedMap
)
window.addEventListener('gamepadconnected', this.updateScrollPosition.bind(this))
window.addEventListener('gamepaddisconnected', this.updateScrollPosition.bind(this))
}
public destroy() {}
public onKeyDown(e: KeyboardEvent) {
// Nothing
}
public onKeyUp(e: KeyboardEvent) {
// Nothing
}
public onMouseKeyDown(e: MouseEvent) {
// Nothing
}
public onMouseKeyUp(e: MouseEvent) {
// Nothing
}
public onWheel(e: WheelEvent) {
// Nothing
}
private onButtonRelease(button: string, mode?: JoyconMode | null) {}
private onButtonPressed(button: string, mode?: JoyconMode | null) {
if (mode === 'L') {
// Button overview JoyCon L single mode
// Arrows: Left = '0', Down = '1', Up = '2', Right = '3'
// Others: SL = '4', SR = '5', ZL = '6', L = '8', - = '9', Joystick = '10', Snapshot = '16'
switch (button) {
case '6':
// go to air
this.prompterView.scrollToLive()
break
// go to next
case '8':
this.prompterView.scrollToNext()
break
case '2':
// go to top
window.scrollTo(0, 0)
break
case '3':
// go to following
this.prompterView.scrollToFollowing()
break
case '0':
// // go to previous
this.prompterView.scrollToPrevious()
break
}
} else if (mode === 'R') {
// Button overview JoyCon R single mode
// "Arrows": A = '0', X = '1', B = '2', Y = '3'
// Others: SL = '4', SR = '5', ZR = '7', R = '8', + = '9', Joystick = '10', Home = '16'
switch (button) {
case '7':
// go to air
this.prompterView.scrollToLive()
break
// go to next
case '8':
this.prompterView.scrollToNext()
break
case '1':
// go to top
window.scrollTo(0, 0)
break
case '0':
// go to following
this.prompterView.scrollToFollowing()
break
case '3':
// // go to previous
this.prompterView.scrollToPrevious()
break
}
} else if (mode === 'LR') {
// Button overview JoyCon L+R paired mode
// L JoyCon Arrows: B = '0', A = '1', Y = '2', X = '3'
// L JoyCon Others: L = '4', ZL = '6', - = '8', Joystick = '10', Snapshot = '17', SL = '18', SR = '19'
// R JoyCon "Arrows": B = '0', A = '1', Y = '2', X = '3'
// R JoyCon Others: R = '5', ZR = '7', + = '9', Joystick = '11', Home = '16', SL = '20', SR = '21'
switch (button) {
case '6':
case '7':
// go to air
this.prompterView.scrollToLive()
break
// go to next
case '4':
case '5':
this.prompterView.scrollToNext()
break
case '12':
case '3':
// go to top
window.scrollTo(0, 0)
break
case '15':
case '1':
// go to following
this.prompterView.scrollToFollowing()
break
case '14':
case '2':
// // go to previous
this.prompterView.scrollToPrevious()
break
}
}
}
private getDataFromJoycons() {
if (navigator.getGamepads) {
let gamepads = navigator.getGamepads()
if (!(gamepads && typeof gamepads === 'object' && gamepads.length)) return
// try to re-use old index, if the id mathces
const lastpad = gamepads[this.lastUsedJoyconIndex]
if (lastpad && lastpad.connected && lastpad.id == this.lastUsedJoyconId) {
return { axes: lastpad.axes, buttons: lastpad.buttons }
}
// falls back to searching for compatible gamepad
for (const o of gamepads) {
if (
o &&
o.connected &&
o.id &&
typeof o.id === 'string' &&
o.id.match('STANDARD GAMEPAD Vendor: 057e')
) {
this.lastUsedJoyconIndex = o.index
this.lastUsedJoyconId = o.id
this.lastUsedJoyconMode =
o.axes.length === 4
? 'LR'
: o.id.match('Product: 2006')
? 'L'
: o.id.match('Product: 2007')
? 'R'
: null // we are setting lastUsedJoyconId as a member as opposed to returning it functional-style, to avoid doing this calculation pr. tick
// for documentation: L+R mode is also identified as Vendor: 057e Product: 200e
return { axes: o.axes, buttons: o.buttons }
}
}
}
return false
}
private getActiveInputsOfJoycons(input) {
// handle buttons
// @todo: should this be throttled??
const newButtons = input.buttons.map((i) => i.value)
if (this.lastButtonArray.length) {
for (let i in newButtons) {
const oldBtn = this.lastButtonArray[i]
const newBtn = newButtons[i]
if (oldBtn === newBtn) continue
if (!oldBtn && newBtn) {
// press
this.onButtonPressed(i, this.lastUsedJoyconMode)
} else if (oldBtn && !newBtn) {
// release
this.onButtonRelease(i, this.lastUsedJoyconMode)
}
}
}
this.lastButtonArray = newButtons
// hadle speed input
if (this.lastUsedJoyconMode === 'L' || this.lastUsedJoyconMode === 'R') {
// L or R mode
if (Math.abs(input.axes[0]) > this.deadBand) {
if (this.lastUsedJoyconMode === 'L') {
return input.axes[0] * -1 // in this mode, L is "negative"
} else if (this.lastUsedJoyconMode === 'R') {
return input.axes[0] * 1.4 // in this mode, R is "positive"
// factor increased by 1.4 to account for the R joystick being less sensitive than L
}
}
} else if (this.lastUsedJoyconMode === 'LR') {
// L + R mode
// get the first one that is moving outside of the deadband, priorotizing the L controller
if (Math.abs(input.axes[1]) > this.deadBand) {
return input.axes[1] * -1 // in this mode, we are "negative" on both sticks....
}
if (Math.abs(input.axes[3]) > this.deadBand) {
return input.axes[3] * -1.4 // in this mode, we are "negative" on both sticks....
// factor increased by 1.4 to account for the R joystick being less sensitive than L
}
}
return 0
}
private calculateSpeed(input) {
const { rangeRevMin, rangeNeutralMin, rangeNeutralMax, rangeFwdMax } = this
let inputValue = this.getActiveInputsOfJoycons(input)
// start by clamping value to the leagal range
inputValue = Math.min(Math.max(inputValue, rangeRevMin), rangeFwdMax) // clamps in between rangeRevMin and rangeFwdMax
// stores only for debugging
this.lastInputValue = inputValue.toFixed(2)
if (inputValue >= rangeRevMin && inputValue <= rangeNeutralMin) {
// 1) Use the reverse speed spline for the expected speed. The reverse speed is specified using positive values,
// so the result needs to be inversed
if (this.invertJoystick) {
return Math.round(this.reverseSpeedSpline.at(inputValue))
} else {
return Math.round(this.reverseSpeedSpline.at(inputValue)) * -1
}
} else if (inputValue >= rangeNeutralMin && inputValue <= rangeNeutralMax) {
// 2) we're in the neutral zone
return 0
} else if (inputValue >= rangeNeutralMax && inputValue <= rangeFwdMax) {
// 3) Use the speed spline to find the expected speed at this point
if (this.invertJoystick) {
return Math.round(this.speedSpline.at(inputValue)) * -1
} else {
return Math.round(this.speedSpline.at(inputValue))
}
} else {
// 4) we should never be able to hit this due to validation above
console.error(`Illegal input value ${inputValue}`)
return 0
}
}
private updateScrollPosition() {
if (this.updateSpeedHandle !== null) return
const input = this.getDataFromJoycons()
if (!input) return
const speed = this.calculateSpeed(input)
// update scroll position
window.scrollBy(0, speed)
const scrollPosition = window.scrollY
// check for reached end-of-scroll:
if (this.currentPosition !== undefined && scrollPosition !== undefined) {
if (this.currentPosition === scrollPosition) {
// We tried to move, but haven't
// @todo: haptic feedback
}
}
this.currentPosition = scrollPosition
// debug
// @todo: can this be throttled?
this.prompterView.DEBUG_controllerState({
source: PrompterConfigMode.JOYCON,
lastSpeed: speed,
lastEvent: 'ControlChange: ' + this.lastInputValue,
})
this.updateSpeedHandle = window.requestAnimationFrame(() => {
this.updateSpeedHandle = null
this.updateScrollPosition()
})
}
} | the_stack |
import gensync from "gensync";
import type { Handler } from "gensync";
import { forwardAsync, maybeAsync, isThenable } from "../gensync-utils/async";
import { mergeOptions } from "./util";
import * as context from "../index";
import Plugin from "./plugin";
import { getItemDescriptor } from "./item";
import { buildPresetChain } from "./config-chain";
import type {
ConfigContext,
ConfigChain,
PresetInstance,
} from "./config-chain";
import type { UnloadedDescriptor } from "./config-descriptors";
import traverse from "@babel/traverse";
import { makeWeakCache, makeWeakCacheSync } from "./caching";
import type { CacheConfigurator } from "./caching";
import {
validate,
checkNoUnwrappedItemOptionPairs,
} from "./validation/options";
import type { PluginItem } from "./validation/options";
import { validatePluginObject } from "./validation/plugins";
import { makePluginAPI, makePresetAPI } from "./helpers/config-api";
import type { PluginAPI, PresetAPI } from "./helpers/config-api";
import loadPrivatePartialConfig from "./partial";
import type { ValidatedOptions } from "./validation/options";
import * as Context from "./cache-contexts";
type LoadedDescriptor = {
value: {};
options: {};
dirname: string;
alias: string;
};
export type { InputOptions } from "./validation/options";
export type ResolvedConfig = {
options: any;
passes: PluginPasses;
};
export type { Plugin };
export type PluginPassList = Array<Plugin>;
export type PluginPasses = Array<PluginPassList>;
export default gensync<(inputOpts: unknown) => ResolvedConfig | null>(
function* loadFullConfig(inputOpts) {
const result = yield* loadPrivatePartialConfig(inputOpts);
if (!result) {
return null;
}
const { options, context, fileHandling } = result;
if (fileHandling === "ignored") {
return null;
}
const optionDefaults = {};
const { plugins, presets } = options;
if (!plugins || !presets) {
throw new Error("Assertion failure - plugins and presets exist");
}
const presetContext: Context.FullPreset = {
...context,
targets: options.targets,
};
const toDescriptor = (item: PluginItem) => {
const desc = getItemDescriptor(item);
if (!desc) {
throw new Error("Assertion failure - must be config item");
}
return desc;
};
const presetsDescriptors = presets.map(toDescriptor);
const initialPluginsDescriptors = plugins.map(toDescriptor);
const pluginDescriptorsByPass: Array<Array<UnloadedDescriptor>> = [[]];
const passes: Array<Array<Plugin>> = [];
const ignored = yield* enhanceError(
context,
function* recursePresetDescriptors(
rawPresets: Array<UnloadedDescriptor>,
pluginDescriptorsPass: Array<UnloadedDescriptor>,
): Handler<true | void> {
const presets: Array<{
preset: ConfigChain | null;
pass: Array<UnloadedDescriptor>;
}> = [];
for (let i = 0; i < rawPresets.length; i++) {
const descriptor = rawPresets[i];
if (descriptor.options !== false) {
try {
// Presets normally run in reverse order, but if they
// have their own pass they run after the presets
// in the previous pass.
if (descriptor.ownPass) {
presets.push({
preset: yield* loadPresetDescriptor(
descriptor,
presetContext,
),
pass: [],
});
} else {
presets.unshift({
preset: yield* loadPresetDescriptor(
descriptor,
presetContext,
),
pass: pluginDescriptorsPass,
});
}
} catch (e) {
if (e.code === "BABEL_UNKNOWN_OPTION") {
checkNoUnwrappedItemOptionPairs(rawPresets, i, "preset", e);
}
throw e;
}
}
}
// resolve presets
if (presets.length > 0) {
// The passes are created in the same order as the preset list, but are inserted before any
// existing additional passes.
pluginDescriptorsByPass.splice(
1,
0,
...presets
.map(o => o.pass)
.filter(p => p !== pluginDescriptorsPass),
);
for (const { preset, pass } of presets) {
if (!preset) return true;
pass.push(...preset.plugins);
const ignored = yield* recursePresetDescriptors(
preset.presets,
pass,
);
if (ignored) return true;
preset.options.forEach(opts => {
mergeOptions(optionDefaults, opts);
});
}
}
},
)(presetsDescriptors, pluginDescriptorsByPass[0]);
if (ignored) return null;
const opts: any = optionDefaults;
mergeOptions(opts, options);
const pluginContext: Context.FullPlugin = {
...presetContext,
assumptions: opts.assumptions ?? {},
};
yield* enhanceError(context, function* loadPluginDescriptors() {
pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors);
for (const descs of pluginDescriptorsByPass) {
const pass = [];
passes.push(pass);
for (let i = 0; i < descs.length; i++) {
const descriptor: UnloadedDescriptor = descs[i];
if (descriptor.options !== false) {
try {
pass.push(yield* loadPluginDescriptor(descriptor, pluginContext));
} catch (e) {
if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") {
// print special message for `plugins: ["@babel/foo", { foo: "option" }]`
checkNoUnwrappedItemOptionPairs(descs, i, "plugin", e);
}
throw e;
}
}
}
}
})();
opts.plugins = passes[0];
opts.presets = passes
.slice(1)
.filter(plugins => plugins.length > 0)
.map(plugins => ({ plugins }));
opts.passPerPreset = opts.presets.length > 0;
return {
options: opts,
passes: passes,
};
},
);
function enhanceError<T extends Function>(context, fn: T): T {
return function* (arg1, arg2) {
try {
return yield* fn(arg1, arg2);
} catch (e) {
// There are a few case where thrown errors will try to annotate themselves multiple times, so
// to keep things simple we just bail out if re-wrapping the message.
if (!/^\[BABEL\]/.test(e.message)) {
e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`;
}
throw e;
}
} as any;
}
/**
* Load a generic plugin/preset from the given descriptor loaded from the config object.
*/
const makeDescriptorLoader = <Context, API>(
apiFactory: (cache: CacheConfigurator<Context>) => API,
): ((d: UnloadedDescriptor, c: Context) => Handler<LoadedDescriptor>) =>
makeWeakCache(function* (
{ value, options, dirname, alias }: UnloadedDescriptor,
cache: CacheConfigurator<Context>,
): Handler<LoadedDescriptor> {
// Disabled presets should already have been filtered out
if (options === false) throw new Error("Assertion failure");
options = options || {};
let item = value;
if (typeof value === "function") {
const factory = maybeAsync(
value,
`You appear to be using an async plugin/preset, but Babel has been called synchronously`,
);
const api = {
...context,
...apiFactory(cache),
};
try {
item = yield* factory(api, options, dirname);
} catch (e) {
if (alias) {
e.message += ` (While processing: ${JSON.stringify(alias)})`;
}
throw e;
}
}
if (!item || typeof item !== "object") {
throw new Error("Plugin/Preset did not return an object.");
}
if (isThenable(item)) {
// @ts-expect-error - if we want to support async plugins
yield* [];
throw new Error(
`You appear to be using a promise as a plugin, ` +
`which your current version of Babel does not support. ` +
`If you're using a published plugin, ` +
`you may need to upgrade your @babel/core version. ` +
`As an alternative, you can prefix the promise with "await". ` +
`(While processing: ${JSON.stringify(alias)})`,
);
}
return { value: item, options, dirname, alias };
});
const pluginDescriptorLoader = makeDescriptorLoader<
Context.SimplePlugin,
PluginAPI
>(makePluginAPI);
const presetDescriptorLoader = makeDescriptorLoader<
Context.SimplePreset,
PresetAPI
>(makePresetAPI);
/**
* Instantiate a plugin for the given descriptor, returning the plugin/options pair.
*/
function* loadPluginDescriptor(
descriptor: UnloadedDescriptor,
context: Context.SimplePlugin,
): Handler<Plugin> {
if (descriptor.value instanceof Plugin) {
if (descriptor.options) {
throw new Error(
"Passed options to an existing Plugin instance will not work.",
);
}
return descriptor.value;
}
return yield* instantiatePlugin(
yield* pluginDescriptorLoader(descriptor, context),
context,
);
}
const instantiatePlugin = makeWeakCache(function* (
{ value, options, dirname, alias }: LoadedDescriptor,
cache: CacheConfigurator<Context.SimplePlugin>,
): Handler<Plugin> {
const pluginObj = validatePluginObject(value);
const plugin = {
...pluginObj,
};
if (plugin.visitor) {
plugin.visitor = traverse.explode({
...plugin.visitor,
});
}
if (plugin.inherits) {
const inheritsDescriptor = {
name: undefined,
alias: `${alias}$inherits`,
value: plugin.inherits,
options,
dirname,
};
const inherits = yield* forwardAsync(loadPluginDescriptor, run => {
// If the inherited plugin changes, reinstantiate this plugin.
return cache.invalidate(data => run(inheritsDescriptor, data));
});
plugin.pre = chain(inherits.pre, plugin.pre);
plugin.post = chain(inherits.post, plugin.post);
plugin.manipulateOptions = chain(
inherits.manipulateOptions,
plugin.manipulateOptions,
);
plugin.visitor = traverse.visitors.merge([
inherits.visitor || {},
plugin.visitor || {},
]);
}
return new Plugin(plugin, options, alias);
});
const validateIfOptionNeedsFilename = (
options: ValidatedOptions,
descriptor: UnloadedDescriptor,
): void => {
if (options.test || options.include || options.exclude) {
const formattedPresetName = descriptor.name
? `"${descriptor.name}"`
: "/* your preset */";
throw new Error(
[
`Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`,
`\`\`\``,
`babel.transform(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`,
`\`\`\``,
`See https://babeljs.io/docs/en/options#filename for more information.`,
].join("\n"),
);
}
};
const validatePreset = (
preset: PresetInstance,
context: ConfigContext,
descriptor: UnloadedDescriptor,
): void => {
if (!context.filename) {
const { options } = preset;
validateIfOptionNeedsFilename(options, descriptor);
if (options.overrides) {
options.overrides.forEach(overrideOptions =>
validateIfOptionNeedsFilename(overrideOptions, descriptor),
);
}
}
};
/**
* Generate a config object that will act as the root of a new nested config.
*/
function* loadPresetDescriptor(
descriptor: UnloadedDescriptor,
context: Context.FullPreset,
): Handler<ConfigChain | null> {
const preset = instantiatePreset(
yield* presetDescriptorLoader(descriptor, context),
);
validatePreset(preset, context, descriptor);
return yield* buildPresetChain(preset, context);
}
const instantiatePreset = makeWeakCacheSync(
({ value, dirname, alias }: LoadedDescriptor): PresetInstance => {
return {
options: validate("preset", value),
alias,
dirname,
};
},
);
function chain(a, b) {
const fns = [a, b].filter(Boolean);
if (fns.length <= 1) return fns[0];
return function (...args) {
for (const fn of fns) {
fn.apply(this, args);
}
};
} | the_stack |
import { html, PropertyValues, TemplateResult } from 'lit';
import { property, state } from 'lit/decorators.js';
import { createRef } from 'lit/directives/ref.js';
import { listen, redispatchEvent, vdsEvent } from '../../base/events';
import { DEV_MODE } from '../../global/env';
import {
CanPlay,
MediaProviderElement,
MediaType,
PlayingEvent,
ReplayEvent
} from '../../media';
import { getSlottedChildren } from '../../utils/dom';
import { getNumberOfDecimalPlaces } from '../../utils/number';
import { keysOf } from '../../utils/object';
import { isNil, isNumber, isUndefined } from '../../utils/unit';
import { MediaNetworkState } from './MediaNetworkState';
import { MediaReadyState } from './MediaReadyState';
export const AUDIO_EXTENSIONS =
/\.(m4a|mp4a|mpga|mp2|mp2a|mp3|m2a|m3a|wav|weba|aac|oga|spx)($|\?)/i;
export const VIDEO_EXTENSIONS = /\.(mp4|og[gv]|webm|mov|m4v)($|\?)/i;
/**
* A DOMString` indicating the `CORS` setting for this media element.
*
* @link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin
*/
export type MediaCrossOriginOption = 'anonymous' | 'use-credentials';
/**
* Is a `DOMString` that reflects the `preload` HTML attribute, indicating what data should be
* preloaded, if any.
*/
export type MediaPreloadOption = 'none' | 'metadata' | 'auto';
/**
* `DOMTokenList` that helps the user agent select what controls to show on the media element
* whenever the user agent shows its own set of controls. The `DOMTokenList` takes one or more of
* three possible values: `nodownload`, `nofullscreen`, and `noremoteplayback`.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/controlsList
*/
export type MediaControlsList =
| 'nodownload'
| 'nofullscreen'
| 'noremoteplayback'
| 'nodownload nofullscreen'
| 'nodownload noremoteplayback'
| 'nofullscreen noremoteplayback'
| 'nodownload nofullscreen noremoteplayback';
/**
* The object which serves as the source of the media associated with the `HTMLMediaElement`. The
* object can be a `MediaStream`, `MediaSource`, `Blob`, or `File` (which inherits from `Blob`).
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
* @link https://developer.mozilla.org/en-US/docs/Web/API/MediaStream
* @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource
* @link https://developer.mozilla.org/en-US/docs/Web/API/Blob
* @link https://developer.mozilla.org/en-US/docs/Web/API/File
*/
export type MediaSrcObject = MediaStream | MediaSource | Blob | File;
/**
* Enables loading, playing and controlling media files via the HTML5 MediaElement API. This is
* used internally by the `vds-audio` and `vds-video` components. This provider only contains
* glue code so don't bother using it on it's own.
*
* @slot Pass `<source>` and `<track>` elements to the underlying HTML5 media player.
*/
export class Html5MediaElement extends MediaProviderElement {
// -------------------------------------------------------------------------------------------
// Properties
// -------------------------------------------------------------------------------------------
/**
* Determines what controls to show on the media element whenever the browser shows its own set
* of controls (e.g. when the controls attribute is specified).
*
* @example 'nodownload nofullscreen noremoteplayback'
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/controlsList
*/
@property()
controlsList: MediaControlsList | undefined = undefined;
/**
* Whether to use CORS to fetch the related image. See
* [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for more
* information.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/crossOrigin
*/
@property()
crossOrigin: MediaCrossOriginOption | undefined;
/**
* Reflects the muted attribute, which indicates whether the audio output should be muted by
* default. This property has no dynamic effect. To mute and unmute the audio output, use
* the `muted` property.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/defaultMuted
*/
@property({ type: Boolean })
defaultMuted: boolean | undefined;
/**
* A `double` indicating the default playback rate for the media.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/defaultPlaybackRate
*/
@property({ type: Number })
defaultPlaybackRate: number | undefined;
/**
* Whether to disable the capability of remote playback in devices that are
* attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast,
* DLNA, AirPlay, etc).
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/disableRemotePlayback
* @see https://www.w3.org/TR/remote-playback/#the-disableremoteplayback-attribute
*/
@property({ type: Boolean })
disableRemotePlayback: boolean | undefined;
/**
* Provides a hint to the browser about what the author thinks will lead to the best user
* experience with regards to what content is loaded before the video is played. See
* [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-preload) for more
* information.
*/
@property()
preload: MediaPreloadOption | undefined;
/**
* The width of the media player.
*/
@property({ type: Number })
width: number | undefined;
/**
* The height of the media player.
*/
@property({ type: Number })
height: number | undefined;
@state()
protected _src = '';
/**
* The URL of a media resource to use.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/src
*/
@property()
get src(): string {
return this._src;
}
set src(newSrc) {
if (this._src !== newSrc) {
this._src = newSrc;
this._handleMediaSrcChange();
}
}
protected readonly _mediaRef = createRef<HTMLMediaElement>();
get mediaElement() {
return this._mediaRef.value;
}
/**
* Sets or returns the object which serves as the source of the media associated with the
* `HTMLMediaElement`.
*
* @default undefined
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
*/
get srcObject(): MediaSrcObject | undefined {
return this.mediaElement?.srcObject ?? undefined;
}
set srcObject(newSrcObject) {
if (
!isUndefined(this.mediaElement) &&
this.mediaElement.srcObject !== newSrcObject
) {
// TODO: this has to be attached after `firstUpdated`?
this.mediaElement.srcObject = newSrcObject ?? null;
this._handleMediaSrcChange();
}
}
/**
* Indicates the readiness state of the media.
*
* @default ReadyState.HaveNothing
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState
*/
get readyState() {
return this.mediaElement?.readyState ?? MediaReadyState.HaveNothing;
}
/**
* Indicates the current state of the fetching of media over the network.
*
* @default NetworkState.Empty
*/
get networkState() {
return this.mediaElement?.networkState ?? MediaNetworkState.Empty;
}
// -------------------------------------------------------------------------------------------
// Lifecycle
// -------------------------------------------------------------------------------------------
protected override firstUpdated(changedProps: PropertyValues): void {
super.firstUpdated(changedProps);
this._bindMediaEventListeners();
}
override disconnectedCallback() {
this._isReplay = false;
this._isLoopedReplay = false;
this._replayTriggerEvent = undefined;
super.disconnectedCallback();
this._cancelTimeUpdates();
}
// -------------------------------------------------------------------------------------------
// Render
// -------------------------------------------------------------------------------------------
/**
* Override this to modify the content rendered inside `<audio>` and `<video>` elements.
*/
protected _renderMediaChildren(): TemplateResult {
return html`
<slot @slotchange="${this._handleDefaultSlotChange}"></slot>
Your browser does not support the <code>audio</code> or
<code>video</code> element.
`;
}
// -------------------------------------------------------------------------------------------
// Time Updates
// The `timeupdate` event fires surprisingly infrequently during playback, meaning your progress
// bar (or whatever else is synced to the currentTime) moves in a choppy fashion. This helps
// resolve that :)
// -------------------------------------------------------------------------------------------
protected _timeRAF?: number = undefined;
protected _cancelTimeUpdates() {
if (isNumber(this._timeRAF)) window.cancelAnimationFrame(this._timeRAF);
this._timeRAF = undefined;
}
protected _requestTimeUpdates() {
// Time updates are already in progress.
if (!isUndefined(this._timeRAF)) return;
this._requestTimeUpdate();
}
protected _requestTimeUpdate() {
const newTime = this.mediaElement?.currentTime ?? 0;
if (this.ctx.currentTime !== newTime) {
this._updateCurrentTime(newTime);
}
this._timeRAF = window.requestAnimationFrame(() => {
if (isUndefined(this._timeRAF)) return;
this._requestTimeUpdate();
});
}
protected _updateCurrentTime(newTime: number, originalEvent?: Event) {
// Avoid errors where `currentTime` can have higher precision than duration.
this.ctx.currentTime = Math.min(newTime, this.duration);
this.dispatchEvent(
vdsEvent('vds-time-update', {
detail: this.ctx.currentTime,
originalEvent
})
);
}
// -------------------------------------------------------------------------------------------
// Slots
// -------------------------------------------------------------------------------------------
protected _handleDefaultSlotChange() {
if (isNil(this.mediaElement)) return;
this._cancelTimeUpdates();
this._cleanupOldSourceNodes();
this._attachNewSourceNodes();
}
protected _cleanupOldSourceNodes() {
const nodes = this.mediaElement?.querySelectorAll('source,track');
nodes?.forEach((node) => node.remove());
}
protected _attachNewSourceNodes() {
const validTags = new Set(['source', 'track']);
const nodes = getSlottedChildren(this).filter((node) =>
validTags.has(node.tagName.toLowerCase())
);
/* c8 ignore start */
if (DEV_MODE && nodes.length > 0) {
this._logger
.logGroup('Found `<source>` and `<track>` elements')
.appendWithLabel('Nodes', nodes)
.end();
}
/* c8 ignore stop */
nodes.forEach((node) => this.mediaElement?.appendChild(node.cloneNode()));
window.requestAnimationFrame(() => {
this._handleMediaSrcChange();
});
}
// -------------------------------------------------------------------------------------------
// Events
// -------------------------------------------------------------------------------------------
protected _bindMediaEventListeners() {
if (isNil(this.mediaElement)) return;
const eventListeners = {
abort: this._handleAbort,
canplay: this._handleCanPlay,
canplaythrough: this._handleCanPlayThrough,
durationchange: this._handleDurationChange,
emptied: this._handleEmptied,
ended: this._handleEnded,
error: this._handleError,
loadeddata: this._handleLoadedData,
loadedmetadata: this._handleLoadedMetadata,
loadstart: this._handleLoadStart,
pause: this._handlePause,
play: this._handlePlay,
playing: this._handlePlaying,
progress: this._handleProgress,
ratechange: this._handleRateChange,
seeked: this._handleSeeked,
seeking: this._handleSeeking,
stalled: this._handleStalled,
suspend: this._handleSuspend,
timeupdate: this._handleTimeUpdate,
volumechange: this._handleVolumeChange,
waiting: this._handleWaiting
};
keysOf(eventListeners).forEach((type) => {
const handler = eventListeners[type].bind(this);
this._disconnectDisposal.add(
listen(this.mediaElement!, type, async (event: Event) => {
/* c8 ignore start */
if (DEV_MODE && type !== 'timeupdate') {
this._logger
.debugGroup(`📺 fired \`${event.type}\``)
.appendWithLabel('Event', event)
.appendWithLabel('Engine', this.engine)
.appendWithLabel('Context', this.mediaState)
.end();
}
/* c8 ignore stop */
await handler(event);
// re-dispatch native event for spec-compliance.
redispatchEvent(this, event);
this.requestUpdate();
})
);
});
/* c8 ignore start */
if (DEV_MODE) {
this._logger.debug('attached event listeners');
}
/* c8 ignore stop */
}
protected _handleAbort(event: Event) {
this.dispatchEvent(vdsEvent('vds-abort', { originalEvent: event }));
}
protected _handleCanPlay(event: Event) {
if (this.ctx.canPlay) return;
this.ctx.buffered = this.mediaElement!.buffered;
this.ctx.seekable = this.mediaElement!.seekable;
if (!this._willAnotherEngineAttach()) this._handleMediaReady(event);
}
protected _handleCanPlayThrough(event: Event) {
if (this.ctx.canPlayThrough) return;
this.ctx.canPlayThrough = true;
this.dispatchEvent(
vdsEvent('vds-can-play-through', { originalEvent: event })
);
}
protected _handleLoadStart(event: Event) {
this.ctx.currentSrc = this.mediaElement!.currentSrc;
this.dispatchEvent(vdsEvent('vds-load-start', { originalEvent: event }));
}
protected _handleEmptied(event: Event) {
this.dispatchEvent(vdsEvent('vds-emptied', { originalEvent: event }));
}
protected _handleLoadedData(event: Event) {
this.dispatchEvent(vdsEvent('vds-loaded-data', { originalEvent: event }));
}
/**
* Can be used to indicate another engine such as `hls.js` will attach to the media element
* so it can handle certain ready events.
*/
protected _willAnotherEngineAttach(): boolean {
return false;
}
protected _handleLoadedMetadata(event: Event) {
this.ctx.duration = this.mediaElement!.duration;
this.dispatchEvent(
vdsEvent('vds-duration-change', {
detail: this.ctx.duration,
originalEvent: event
})
);
this.dispatchEvent(
vdsEvent('vds-loaded-metadata', { originalEvent: event })
);
this._determineMediaType(event);
}
protected _determineMediaType(event: Event) {
this.ctx.mediaType = this._getMediaType();
this.dispatchEvent(
vdsEvent('vds-media-type-change', {
detail: this.ctx.mediaType,
originalEvent: event
})
);
}
protected _isReplay = false;
protected _isLoopedReplay = false;
protected _replayTriggerEvent?: ReplayEvent['triggerEvent'];
protected _handlePlay(event: Event) {
this.ctx.paused = false;
if (this.ended || this._isReplay || this._isLoopedReplay) {
this.ctx.ended = false;
this._isReplay = false;
const replayEvent = vdsEvent('vds-replay', { originalEvent: event });
replayEvent.triggerEvent = this._replayTriggerEvent;
this._replayTriggerEvent = undefined;
this._playingTriggerEvent = replayEvent;
this.dispatchEvent(replayEvent);
}
if (this._isLoopedReplay) {
return;
}
const playEvent = vdsEvent('vds-play', { originalEvent: event });
playEvent.autoplay = this._autoplayAttemptPending;
this.dispatchEvent(playEvent);
this._playingTriggerEvent = playEvent;
}
protected _handlePause(event: Event) {
// Don't fire if resuming from loop.
if (
this.loop &&
// Avoid errors where `currentTime` can have higher precision than duration.
Math.min(this.mediaElement!.currentTime, this.duration) === this.duration
) {
return;
}
this._cancelTimeUpdates();
this.ctx.paused = true;
this.ctx.playing = false;
this.ctx.waiting = false;
this.dispatchEvent(vdsEvent('vds-pause', { originalEvent: event }));
}
protected _playingTriggerEvent: PlayingEvent['triggerEvent'];
protected _handlePlaying(event: Event) {
this.ctx.playing = true;
this.ctx.waiting = false;
this.ctx.ended = false;
if (this._isLoopedReplay) {
this._isLoopedReplay = false;
this._requestTimeUpdates();
return;
}
const playingEvent = vdsEvent('vds-playing', { originalEvent: event });
playingEvent.triggerEvent = this._playingTriggerEvent;
this._playingTriggerEvent = undefined;
this.dispatchEvent(playingEvent);
if (!this.ctx.started) {
this.ctx.currentTime = 0;
this.ctx.started = true;
this.dispatchEvent(vdsEvent('vds-started', { originalEvent: event }));
}
this._requestTimeUpdates();
}
protected _handleDurationChange(event: Event) {
if (this.ended) {
this._updateCurrentTime(this.mediaElement!.duration, event);
}
this.ctx.duration = this.mediaElement!.duration;
this.dispatchEvent(
vdsEvent('vds-duration-change', {
detail: this.ctx.duration,
originalEvent: event
})
);
}
protected _handleProgress(event: Event) {
this.ctx.buffered = this.mediaElement!.buffered;
this.ctx.seekable = this.mediaElement!.seekable;
this.dispatchEvent(vdsEvent('vds-progress', { originalEvent: event }));
}
protected _handleRateChange(event: Event) {
// TODO: no-op for now but we'll add playback rate support later.
throw Error('Not implemented');
}
protected _handleSeeking(event: Event) {
this.ctx.currentTime = this.mediaElement!.currentTime;
this.ctx.seeking = true;
if (this.ended) {
this.ctx.ended = false;
this._isReplay = true;
}
this.dispatchEvent(
vdsEvent('vds-seeking', {
detail: this.ctx.currentTime,
originalEvent: event
})
);
}
protected _handleSeeked(event: Event) {
this.ctx.currentTime = this.mediaElement!.currentTime;
this.ctx.seeking = false;
this.ctx.waiting = false;
const seekedEvent = vdsEvent('vds-seeked', {
detail: this.ctx.currentTime,
originalEvent: event
});
this.dispatchEvent(seekedEvent);
// Play or replay has greater priority.
if (!this._playingTriggerEvent) {
this._playingTriggerEvent = seekedEvent;
setTimeout(() => {
this._playingTriggerEvent = undefined;
}, 150);
}
const currentTime = this.mediaElement!.currentTime;
// HLS: If precision has increased by seeking to the end, we'll call `play()` to properly end.
if (
Math.trunc(currentTime) === Math.trunc(this.duration) &&
getNumberOfDecimalPlaces(this.duration) >
getNumberOfDecimalPlaces(currentTime)
) {
this._updateCurrentTime(this.duration, event);
if (!this.ended) {
try {
this.play();
} catch (e) {
// no-op
}
}
}
}
protected _handleStalled(event: Event) {
this.dispatchEvent(vdsEvent('vds-stalled', { originalEvent: event }));
}
protected _handleTimeUpdate(event: Event) {
// -- Time updates are performed in `requestTimeUpdates()`.
}
protected _handleVolumeChange(event: Event) {
this.ctx.volume = this.mediaElement!.volume;
this.ctx.muted = this.mediaElement!.muted;
this.dispatchEvent(
vdsEvent('vds-volume-change', {
detail: {
volume: this.ctx.volume,
muted: this.ctx.muted
},
originalEvent: event
})
);
}
protected _handleWaiting(event: Event) {
this.ctx.playing = false;
this.ctx.waiting = true;
this.dispatchEvent(vdsEvent('vds-waiting', { originalEvent: event }));
}
protected _handleSuspend(event: Event) {
const suspendEvent = vdsEvent('vds-suspend', { originalEvent: event });
this.dispatchEvent(suspendEvent);
}
protected _handleEnded(event: Event) {
this._cancelTimeUpdates();
this.ctx.duration = this.mediaElement!.duration;
this._updateCurrentTime(this.ctx.duration, event);
if (this.loop) {
const loopedEvent = vdsEvent('vds-looped', { originalEvent: event });
this._replayTriggerEvent = loopedEvent;
this.dispatchEvent(loopedEvent);
this._handleLoop();
} else {
this.ctx.ended = true;
this.ctx.waiting = false;
this.dispatchEvent(vdsEvent('vds-ended', { originalEvent: event }));
}
}
protected _handleLoop() {
window.requestAnimationFrame(async () => {
try {
this.mediaElement!.controls = false;
this._isLoopedReplay = true;
await this.play();
// We temporarily hide controls while looping to prevent flashing. Any of these events
// will put the controls back in their previous state.
const dispose: (() => void)[] = [];
(['pointerdown', 'pointermove', 'keydown'] as const).forEach((type) => {
dispose.push(
listen(
window,
type,
() => {
dispose.forEach((fn) => fn());
this.mediaElement!.controls = this.controls;
},
{ once: true }
)
);
});
} catch (e) {
this._isLoopedReplay = false;
this.mediaElement!.controls = this.controls;
}
});
}
protected _handleError(event: Event) {
this.ctx.error = this.mediaElement!.error;
this.dispatchEvent(
vdsEvent('vds-error', {
detail: this.mediaElement!.error,
originalEvent: event
})
);
}
// -------------------------------------------------------------------------------------------
// Provider Methods
// -------------------------------------------------------------------------------------------
protected _getPaused() {
return this.mediaElement!.paused;
}
protected _getVolume() {
return this.mediaElement!.volume;
}
protected _setVolume(newVolume: number) {
this.mediaElement!.volume = newVolume;
}
protected _setCurrentTime(newTime: number) {
if (this.mediaElement!.currentTime !== newTime) {
this.mediaElement!.currentTime = newTime;
}
}
protected _getMuted() {
return this.mediaElement!.muted;
}
protected _setMuted(isMuted: boolean) {
this.mediaElement!.muted = isMuted;
}
protected override async _handleMediaSrcChange(): Promise<void> {
super._handleMediaSrcChange();
if (!this._willAnotherEngineAttach()) {
// Wait for `src` attribute to be updated on underlying `<audio>` or `<video>` element.
await this.updateComplete;
/* c8 ignore start */
if (DEV_MODE) {
this._logger.debug('Calling `load()` on media element');
}
/* c8 ignore stop */
this.mediaElement?.load();
}
}
// -------------------------------------------------------------------------------------------
// Readonly Properties
// -------------------------------------------------------------------------------------------
get engine() {
return this.mediaElement;
}
override get buffered() {
if (isNil(this.mediaElement)) return new TimeRanges();
return this.mediaElement.buffered;
}
/**
* Returns a `MediaError` object for the most recent error, or `undefined` if there has not been
* an error.
*
* @default undefined
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error
*/
override get error() {
return this.mediaElement?.error ?? undefined;
}
// -------------------------------------------------------------------------------------------
// Methods
// -------------------------------------------------------------------------------------------
canPlayType(type: string): CanPlay {
if (isNil(this.mediaElement)) {
return CanPlay.No;
}
return this.mediaElement.canPlayType(type) as CanPlay;
}
async play() {
/* c8 ignore start */
if (DEV_MODE) {
this._logger.info('attempting to play...');
}
/* c8 ignore stop */
try {
this._throwIfNotReadyForPlayback();
await this._resetPlaybackIfEnded();
return this.mediaElement?.play();
} catch (error) {
const playErrorEvent = vdsEvent('vds-play-error');
playErrorEvent.autoplay = this._autoplayAttemptPending;
playErrorEvent.error = error as Error;
throw error;
}
}
async pause() {
/* c8 ignore start */
if (DEV_MODE) {
this._logger.info('attempting to pause...');
}
/* c8 ignore stop */
this._throwIfNotReadyForPlayback();
return this.mediaElement?.pause();
}
/**
* 🧑🔬 **EXPERIMENTAL:** Returns a `MediaStream` object which is streaming a real-time capture
* of the content being rendered in the media element. This method will return `undefined`
* if this API is not available.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/captureStream
*/
captureStream(): MediaStream | undefined {
this._throwIfNotReadyForPlayback();
return this.mediaElement?.captureStream?.();
}
/**
* Resets the media element to its initial state and begins the process of selecting a media
* source and loading the media in preparation for playback to begin at the beginning. The
* amount of media data that is prefetched is determined by the value of the element's
* `preload` attribute.
*
* 💡 You should generally not need to call this method as it's handled by the library.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/load
*/
load(): void {
this.mediaElement?.load();
}
protected _getMediaType(): MediaType {
if (AUDIO_EXTENSIONS.test(this.currentSrc)) {
return MediaType.Audio;
}
if (VIDEO_EXTENSIONS.test(this.currentSrc)) {
return MediaType.Video;
}
return MediaType.Unknown;
}
} | the_stack |
/// <reference path="..\..\typings\jquery\jquery.d.ts" />
/// <reference path="..\..\typings\jquery.gridster\gridster.d.ts" />
/// <reference path="..\..\typings\select2\select2.d.ts" />
/// <reference path="..\..\typings\highcharts\highstock.d.ts" />
/// <reference path="..\..\typings\bootstrap.v3.datetimepicker\bootstrap.v3.datetimepicker.d.ts" />
/// <reference path="..\..\typings\jquery.dataTables/jquery.dataTables.d.ts" />
var defaultMachineName = "127.0.0.1";
var baseUri = "/data";
var currentMachineName = "";
var currentCounterName = "";
var wires: { [index: string]: any; } = {};
var gridster: Gridster = null;
var graphToSeriesMap: { [index: string]: string[]; } = {};
var seriesToMetadataMap: { [index: string]: IDataSeries; } = {};
var chartData = {}; // map from seriesId to data
interface IDataSeries {
id: string;
name: string;
type: string;
}
function queryData(machineName: any, environmentName: any, timeoutValue: any, pivotDimension: any, counterName: any, limit: any, params: any, startTime: any, endTime: any, width: any, height: any, top: any, left: any, seriesId: any, graphId: any) {
if (seriesId === "") seriesId = generateUuid();
if (pivotDimension !== "") {
params["dimension"] = pivotDimension;
}
var queryParams = decodeURIComponent(params) + "&" + getStartEndTimes(startTime, endTime);
var gridData = [];
var perDimensionData = {};
var seriesMachines = machineName;
if (machineName === "") seriesMachines = environmentName;
var seriesDescription = counterName + " for " + seriesMachines.substr(0, 28);
if (seriesMachines.length > 28) {
seriesDescription += "... (" + seriesMachines.split(",").length + " machines)";
}
if (pivotDimension !== "") {
seriesDescription += " (split by " + pivotDimension + ")";
}
if (decodeURIComponent(params) !== "") {
seriesDescription += " [" + decodeURIComponent(params) + "]";
}
seriesDescription += " from " + new Date(startTime).toLocaleTimeString() + " to " + new Date(endTime).toLocaleTimeString();
var queryPayload = { machineName: machineName, environmentName: environmentName, counterName: counterName, queryCommand: "query", queryParameters: queryParams, timeoutValue: timeoutValue };
$.ajax({
url: baseUri + "/query",
type: "POST",
data: queryPayload,
success: (values => {
var series: IDataSeries[] = [];
var seriesPrefix = "";
if (graphToSeriesMap[graphId] !== undefined && graphToSeriesMap[graphId].length > 0) {
seriesPrefix += "series" + graphToSeriesMap[graphId].length + " - ";
} else {
seriesPrefix += "series0 - ";
}
// Build data sets
if (pivotDimension !== "") {
values.forEach(value => {
if (!perDimensionData[value.DimensionVal]) {
perDimensionData[seriesPrefix + value.DimensionVal] = [];
}
perDimensionData[seriesPrefix + value.DimensionVal].push([new Date(parseInt(value.EndTime.substr(6))).getTime(), value.ChartValue]);
});
series = Object.keys(perDimensionData).map(seriesFromMachine);
} else {
series = [seriesPrefix + counterName].map(seriesFromMachine);
}
var grid = $("<table>").addClass("ms-grid");
var chartDiv;
var thisChart;
var data;
// Add to existing chart
if (graphToSeriesMap[graphId] !== undefined && graphToSeriesMap[graphId].length > 0) {
chartDiv = $("#" + graphId + "_chart");
thisChart = chartDiv.highcharts();
data = values.map(value => [new Date(parseInt(value.EndTime.substr(6))).getTime(), value.ChartValue]);
graphToSeriesMap[graphId].map(val => {
series.push(seriesToMetadataMap[val]);
});
chartDiv.highcharts(getHighchartsConfig(null, series, {}));
thisChart = chartDiv.highcharts();
highchartsResizeHack(chartDiv);
thisChart.get(seriesFromMachine(seriesPrefix + counterName).id).setData(data, false);
graphToSeriesMap[graphId].map(val => {
thisChart.get(seriesToMetadataMap[val].id).setData(chartData[val], false);
});
values.forEach(value => {
gridData.push([new Date(parseInt(value.EndTime.substr(6))).toLocaleString(), value.ChartValue, value.MachineCount]);
});
thisChart.redraw();
chartData[seriesId] = data;
graphToSeriesMap[graphId].push(seriesId);
seriesToMetadataMap[seriesId] = seriesFromMachine(seriesPrefix + counterName);
}
// Create new chart
else {
graphToSeriesMap[graphId] = [];
graphToSeriesMap[graphId].push(seriesId);
seriesToMetadataMap[seriesId] = seriesFromMachine(seriesPrefix + counterName);
chartDiv = $("<div>").addClass("chartContainer").attr("id", graphId + "_chart");
var maxDescWidth = 84 * width;
var seriesWrap = $("<li>").attr("id", graphId).addClass("seriesWrap").append($("<div>").addClass("seriesTitle").attr("id", graphId + "_title").attr("title", seriesDescription).text(seriesDescription.substr(0, maxDescWidth) + "..."), chartDiv.highcharts(getHighchartsConfig(null, series, {})), $("<div>").addClass("table-wrapper").attr("id", graphId + "_table").hide());
if (top > 0 && left > 0) {
gridster.add_widget(seriesWrap[0], width, height, top, left);
} else {
gridster.add_widget(seriesWrap[0], width, height);
}
thisChart = chartDiv.highcharts();
highchartsResizeHack(chartDiv);
if (pivotDimension !== "") {
Object.keys(perDimensionData).map(dimension => {
thisChart.get(seriesFromMachine(dimension).id).setData(perDimensionData[dimension], false);
});
chartData[seriesId] = perDimensionData;
values.forEach(value => {
gridData.push([new Date(parseInt(value.EndTime.substr(6))).toLocaleString(), value.ChartValue, value.MachineCount]);
});
} else {
data = values.map(value => [new Date(parseInt(value.EndTime.substr(6))).getTime(), value.ChartValue]);
chartData[seriesId] = data;
//renderChart(data);
thisChart.get(seriesFromMachine(seriesPrefix + counterName).id).setData(data, false);
values.forEach(value => {
gridData.push([new Date(parseInt(value.EndTime.substr(6))).toLocaleString(), value.ChartValue, value.MachineCount]);
});
}
}
$("#" + graphId + "_table").append($("<h4>").text(seriesDescription), grid);
grid.DataTable({
paging: false,
scrollY: "300px",
"data": gridData,
"columns": [
{ "title": "EndTime" },
{ "title": "Value" },
{ "title": "MachineCount" }
]
});
thisChart.redraw();
var newCounter = {
graphId: graphId,
counter: counterName,
machines: machineName,
environmentName: environmentName,
startTime: startTime,
endTime: endTime,
dimensions: replaceAll($.param(params), "&", "%26"),
pivotDimension: pivotDimension,
top: 1,
left: 1,
width: 1,
height: 1
};
wires[seriesId] = newCounter;
if (graphToSeriesMap[graphId].length == 1) {
$("#" + graphId + "_title").append(
$("<i class='fa fa-times-circle'></i>").addClass("toggle").click(() => {
for (var val in graphToSeriesMap[graphId]) {
delete wires[val];
delete seriesToMetadataMap[val];
}
gridster.remove_widget($("#" + graphId)[0]);
delete graphToSeriesMap[graphId];
updateWires();
}),
$("<i class='fa fa-table'></i>").addClass("toggle").click(e => {
if ($("#" + graphId + "_chart").is(":hidden")) {
$("#" + graphId + "_table").hide();
$("#" + graphId + "_chart").show();
$(e.target).removeClass("fa-line-chart");
$(e.target).addClass("fa-table");
} else {
$("#" + graphId + "_chart").hide();
$("#" + graphId + "_table").show();
$("th").each(function() {
if (this.textContent == "EndTime") {
this.click();
this.click();
}
});
$(e.target).removeClass("fa-table");
$(e.target).addClass("fa-line-chart");
}
}),
$("<i class='fa fa-bookmark'></i>").addClass("toggle").click(() => {
alert(document.URL.split("?")[0] + "?" + "wires={\"counters\":[" + JSON.stringify(wires[seriesId]) + "]}");
}
),
$("<i class='fa fa-info-circle'></i>").addClass("toggle").click(() => {
alert(seriesDescription);
}
));
}
updateWires();
refreshPath();
})
});
return;
}
// Utility functions
var seriesFromMachine = name => {
return {
id: "metric-" + name,
name: name,
type: "line"
};
};
function refreshMachinesList() {
var machines = [];
var machineList = $("#machineName");
machineList.html("");
if ($("#EnvironmentList").val() === "localhost") {
machines.push(defaultMachineName);
machineList.append($("<option class='machineNameOption' />").val(defaultMachineName).text(defaultMachineName));
$("#machineName").hide();
} else if ($("#EnvironmentList").val() === undefined || $("#EnvironmentList").val() === null) {
machines.push(defaultMachineName);
} else {
$.get(baseUri + "/machines?environment=" + $("#EnvironmentList").val(), result => {
for(var machine in result) {
machines.push(machine);
}
machines.sort();
machines.map(m => {
machineList.append($("<option class='machineNameOption' />").val(m.Hostname).text(m.Hostname));
});
if ($("#queryEnvironment").is(":checked")) {
$("#machineName").hide();
}
});
}
$(".machineNameOption").first().attr("checked", "checked");
}
function getMachineName() {
var result: string;
if ($("#queryEnvironment").is(":checked")) {
result = "";
} else if ($("#machineList").is(":checked")) {
result = $("#machineName").val();
if (result == null) return defaultMachineName;
if (result.toString().indexOf("Unable") !== -1) return defaultMachineName;
result = $("#machineName").val().join();
} else {
result = $("#manualMachineName").val();
}
return result;
}
function getStartEndTimes(startTime: any, endTime: any) {
if (startTime !== "" && endTime !== "") {
return "start=" + new Date(startTime).toISOString() + "&end=" + new Date(endTime).toISOString();
}
return "start=1 hour ago&end=now";
}
function refreshEnvironments() {
$.get(baseUri + "/environments").done(data => {
$("#EnvironmentList").select2({ data: data });
updateCounters();
});
}
function updateCounters() {
if ($("#queryEnvironment").is(":checked")) {
$("#machineName").hide();
$("#manualMachineName").hide();
} else if ($("#machineList").is(":checked")) {
$("#machineName").show();
$("#manualMachineName").hide();
} else {
$("#machineName").hide();
$("#manualMachineName").show();
}
refreshCounters();
}
function refreshCounters() {
var queryPayload = { machineName: getMachineName(), environmentName: $("#EnvironmentList").val(), counterName: "/*", queryCommand: "list", queryParameters: "", timeoutValue: getTimeoutValue() };
$.post(baseUri + "/info", queryPayload).done(data => {
$("#counters").select2({ data: data });
updateDimensions(data[0]);
});
}
function updateDimensions(counterName: string) {
var queryPayload = { machineName: getMachineName(), environmentName: $("#EnvironmentList").val(), counterName: counterName, queryCommand: "listDimensions", queryParameters: "", timeoutValue: getTimeoutValue() };
$("#splitBy").empty();
$("#splitBy").append($("<option>").text("none"));
$.post(baseUri + "/info", queryPayload).done(dimensions => {
var dimensionList = $("<div>").addClass("dimensionGrid");
dimensionList.addClass("dimensionValues");
dimensions.forEach(dimension => {
$("#dimensionGrid").empty();
var dimensionLabel = ($("<label>").text(dimension).attr("for", "dim_" + dimension).addClass("dimValLabel"));
var dimensionSelector = $("<li>").append($("<select>").attr("name", dimension).attr("id", dimension).addClass("dimension"));
dimensionList.append($("<li>").append(dimensionLabel, $("<i>").addClass("fa fa-plus-circle").click(e => { updateDimensionValues(counterName, dimension, dimensionSelector, e); })), dimensionSelector);
dimensionSelector.hide();
$("#splitBy").append($("<option>").text(dimension));
});
$("#splitBy").select2({
minimumResultsForSearch: 10
});
$("#dimensionGrid").append(dimensionList);
});
}
function updateDimensionValues(counterName: any, dimensionName: any, dimensionSelector: any, e: any) {
var toggleButton = $(e.target);
if (toggleButton.hasClass("fa-plus-circle")) {
var queryPayload = { machineName: getMachineName(), environmentName: $("#EnvironmentList").val(), counterName: counterName, queryCommand: "listDimensionValues", queryParameters: "dimension=" + dimensionName, timeoutValue: getTimeoutValue() };
$.post(baseUri + "/info", queryPayload).done(data => {
$("#" + dimensionName).select2({ data: data });
dimensionSelector.show();
$(e.target).removeClass("fa-plus-circle");
$(e.target).addClass("fa-minus-circle");
});
} else {
$(e.target).removeClass("fa-minus-circle");
$(e.target).addClass("fa-plus-circle");
dimensionSelector.hide();
}
};
function getJsonResponse() {
var queryParams = getQueryParams();
var pivotDimension = $("#splitBy").val();
if (pivotDimension === "none") {
pivotDimension = "";
}
var graphIdVal = $("#graphId").val();
if (graphIdVal === "" || graphIdVal === "new graph" || graphIdVal === null) {
graphIdVal = generateUuid();
}
queryData(getMachineName(), $("#EnvironmentList").val(), getTimeoutValue(), pivotDimension, $("#counters").val(), 10, queryParams, $("#start").data("datetimepicker").getLocalDate(), $("#end").data("datetimepicker").getLocalDate(), 1, 1, 0, 0, generateUuid(), graphIdVal);
}
function getTimeoutValue() {
return $("#timeout").val();
}
function hydrateWires(wires: any) {
if (wires != undefined) {
$.each(wires.counters,(index, counter) => {
queryData(counter.machines, counter.environmentName, 5000, counter.pivotDimension, counter.counter, 10, "", counter.startTime, counter.endTime, counter.width, counter.height, counter.top, counter.left, generateUuid(), counter.graphId);
});
}
}
function getQueryParams() {
var queryParams = {};
$(".dimension").each((i, val) => {
var dimensionName = $(val).attr("name");
if ($(val).val() != "" && $(val).val() != null) {
queryParams[dimensionName] = $(val).val();
}
});
var percentileValue = $("#percentile").val();
if (percentileValue != "") {
queryParams["percentile"] = percentileValue;
}
return queryParams;
}
function getDefaultPercentiles() {
var defaults = [];
defaults.push("average");
defaults.push("minimum");
defaults.push("maximum");
for (var i = 0; i < 100; i++) {
defaults.push(i);
}
return defaults;
}
window.onload = () => {
$("#start").datetimepicker({ language: "en", format: "MM/dd/yyyy HH:mm:ss PP", pick12HourFormat: true });
var endDate = new Date();
$("#start").data("datetimepicker").setLocalDate(new Date(endDate.getTime() - 3600000));
$("#end").datetimepicker({ language: "en", format: "MM/dd/yyyy HH:mm:ss PP", pick12HourFormat: true });
$("#end").data("datetimepicker").setLocalDate(endDate);
$("#getData").click(getJsonResponse);
$("#EnvironmentList").blur(() => {
updateCounters();
});
refreshEnvironments();
$("#queryEnvironment").click(updateCounters);
$("#queryEnvironment").click(() => {
if ($("#queryEnvironment").is(":checked")) {
$("#machineNameArea").hide();
} else {
$("#machineNameArea").show();
}
});
$("#machineList").click(updateCounters);
$("#manualMode").click(updateCounters);
$("#counters").change(() => { updateDimensions($("#counters").val()); });
$("#splitBy").select2();
gridster = $(".gridster ul").gridster({
widget_margins: [10, 10],
min_cols: 2,
widget_base_dimensions: [640, 300]
}).data("gridster");
$("#loading").hide();
$(document).ajaxStart(() => {
$("#loading").show();
}).ajaxStop(() => {
$("#loading").hide();
});
}
function paramsUnserialize(p: any) {
var ret = {},
seg = p.replace(/^\?/, "").split("&"),
len = seg.length,
i = 0,
s: string[];
for (; i < len; i++) {
if (!seg[i]) {
continue;
}
s = seg[i].split("=");
ret[s[0]] = s[1];
}
return ret;
}
function updateWires() {
for (var key in graphToSeriesMap) {
if (graphToSeriesMap.hasOwnProperty(key)) {
updateWire(key);
}
}
}
function updateWire(graphId: any) {
var masterWindow = $("#" + graphId);
var top = masterWindow.attr("data-col");
var left = masterWindow.attr("data-row");
var width = masterWindow.attr("data-sizex");
var height = masterWindow.attr("data-sizey");
graphToSeriesMap[graphId].map(seriesId => {
wires[seriesId].top = top;
wires[seriesId].left = left;
wires[seriesId].width = width;
wires[seriesId].height = height;
});
refreshPath();
}
function refreshPath() {
var wireArray = [];
var keyArray = [];
var key;
for (key in wires) {
if (wires.hasOwnProperty(key)) {
wireArray.push(JSON.stringify(wires[key]));
}
}
for (key in graphToSeriesMap) {
if (graphToSeriesMap.hasOwnProperty(key)) {
keyArray.push(key);
}
}
keyArray.push("new graph");
$("#graphId").select2({ data: keyArray });
var newPath = "?wires={\"counters\":[" + wireArray.toString() + "]}";
if (typeof (window.history.pushState) == "function") {
window.history.pushState(null, newPath, newPath);
} else {
window.location.hash = "#!" + newPath;
}
}
function generateUuid() {
var d = new Date().getTime();
var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === "x" ? r : (r & 0x7 | 0x8)).toString(16);
});
return uuid;
};
function replaceAll(txt: any, replace: any, withThis: any) {
return txt.replace(new RegExp(replace, "g"), withThis);
}
function highchartsResizeHack(value: any) {
setTimeout(() => {
$(window).resize();
}, 0);
return value;
}
function getHighchartsConfig(selectPoint: any, series: any, options: any) {
Highcharts.setOptions({
global: {
timezoneOffset: new Date().getTimezoneOffset()
}
});
return {
chart: {
backgroundColor: "rgba(255, 255, 255, 0)",
plotBackgroundColor: "rgba(255, 255, 255, 0.9)",
zoomType: "x",
reflow: true,
type: "StockChart",
style: {
fontFamily: "Segoe UI"
}
},
credits: { enabled: false },
title: {
text: "",
style: {
"font-weight": "lighter"
}
},
navigator: {
enabled: true,
baseSeries: 0,
height: 30
},
tooltip: {
shared: true,
xDateFormat: "%A, %b %d, %Y %H:%M:%S",
formatter(tooltip) {
var items = this.points,
series = items[0].series,
s;
// sort the values
items.sort((a, b) => ((a.y < b.y) ? -1 : ((a.y > b.y) ? 1 : 0)));
// make them descend (so we spot high outliers)
items.reverse();
return tooltip.defaultFormatter.call(this, tooltip);
}
},
scrollbar: { liveRedraw: false },
rangeSelector: { enabled: false },
legend: {
enabled: true,
maxHeight: 100,
padding: 3,
title: { text: " " }
},
plotOptions: {
series: {
shadow: false,
marker: { enabled: false },
point: {
events: selectPoint ? {
click: selectPoint
} : {}
},
cursor: selectPoint ? "pointer" : undefined
},
line: {
animation: false
}
},
xAxis: {
type: "datetime",
dateTimeLabelFormats: {
second: "%Y-%m-%d<br/>%H:%M:%S",
minute: "%m-%d<br/>%l:%M%p",
hour: "%m-%d<br/>%l:%M%p",
day: "%Y<br/>%m-%d",
week: "%Y<br/>%m-%d",
month: "%Y-%m",
year: "%Y"
}
},
yAxis: (options.separateYAxes && options.separateYAxes()) ? series.map((series, index) => {
return {
min: 0,
opposite: index % 2 === 1,
title: {
text: ""
},
lineWidth: 1,
id: "yAxis_" + index
};
}) : {
min: 0,
title: {
text: ""
},
lineWidth: 1,
id: "yAxis_" + 0
},
series: series.map((s,i) => {
return {
data: [],
id: s.id,
name: s.name,
type: s.type,
tooltip: {
valueDecimals: 2
},
yAxis: "yAxis_" + ((options.separateYAxes && options.separateYAxes()) ? i : 0)
};
})
};
} | the_stack |
import { v4 as uuid4 } from "uuid";
import { pureDeepObjectAssign } from "vis-util/esnext";
import {
DataInterface,
DataInterfaceForEachOptions,
DataInterfaceGetIdsOptions,
DataInterfaceGetOptions,
DataInterfaceGetOptionsArray,
DataInterfaceGetOptionsObject,
DataInterfaceMapOptions,
DataInterfaceOrder,
DeepPartial,
EventPayloads,
FullItem,
Id,
OptId,
PartItem,
UpdateItem,
isId,
} from "./data-interface";
import { Queue, QueueOptions } from "./queue";
import { DataSetPart } from "./data-set-part";
import { DataStream } from "./data-stream";
/**
* Initial DataSet configuration object.
*
* @typeParam IdProp - Name of the property that contains the id.
*/
export interface DataSetInitialOptions<IdProp extends string> {
/**
* The name of the field containing the id of the items. When data is fetched from a server which uses some specific field to identify items, this field name can be specified in the DataSet using the option `fieldId`. For example [CouchDB](http://couchdb.apache.org/) uses the field `'_id'` to identify documents.
*/
fieldId?: IdProp;
/**
* Queue data changes ('add', 'update', 'remove') and flush them at once. The queue can be flushed manually by calling `DataSet.flush()`, or can be flushed after a configured delay or maximum number of entries.
*
* When queue is true, a queue is created with default options. Options can be specified by providing an object.
*/
queue?: QueueOptions | false;
}
/** DataSet configuration object. */
export interface DataSetOptions {
/**
* Queue configuration object or false if no queue should be used.
*
* - If false and there was a queue before it will be flushed and then removed.
* - If [[QueueOptions]] the existing queue will be reconfigured or a new queue will be created.
*/
queue?: Queue | QueueOptions | false;
}
/**
* Add an id to given item if it doesn't have one already.
*
* @remarks
* The item will be modified.
*
* @param item - The item that will have an id after a call to this function.
* @param idProp - The key of the id property.
*
* @typeParam Item - Item type that may or may not have an id.
* @typeParam IdProp - Name of the property that contains the id.
*
* @returns true
*/
function ensureFullItem<Item extends PartItem<IdProp>, IdProp extends string>(
item: Item,
idProp: IdProp
): FullItem<Item, IdProp> {
if (item[idProp] == null) {
// generate an id
item[idProp] = uuid4() as any;
}
return item as FullItem<Item, IdProp>;
}
/**
* # DataSet
*
* Vis.js comes with a flexible DataSet, which can be used to hold and
* manipulate unstructured data and listen for changes in the data. The DataSet
* is key/value based. Data items can be added, updated and removed from the
* DataSet, and one can subscribe to changes in the DataSet. The data in the
* DataSet can be filtered and ordered. Data can be normalized when appending it
* to the DataSet as well.
*
* ## Example
*
* The following example shows how to use a DataSet.
*
* ```javascript
* // create a DataSet
* var options = {};
* var data = new vis.DataSet(options);
*
* // add items
* // note that the data items can contain different properties and data formats
* data.add([
* {id: 1, text: 'item 1', date: new Date(2013, 6, 20), group: 1, first: true},
* {id: 2, text: 'item 2', date: '2013-06-23', group: 2},
* {id: 3, text: 'item 3', date: '2013-06-25', group: 2},
* {id: 4, text: 'item 4'}
* ]);
*
* // subscribe to any change in the DataSet
* data.on('*', function (event, properties, senderId) {
* console.log('event', event, properties);
* });
*
* // update an existing item
* data.update({id: 2, group: 1});
*
* // remove an item
* data.remove(4);
*
* // get all ids
* var ids = data.getIds();
* console.log('ids', ids);
*
* // get a specific item
* var item1 = data.get(1);
* console.log('item1', item1);
*
* // retrieve a filtered subset of the data
* var items = data.get({
* filter: function (item) {
* return item.group == 1;
* }
* });
* console.log('filtered items', items);
* ```
*
* @typeParam Item - Item type that may or may not have an id.
* @typeParam IdProp - Name of the property that contains the id.
*/
export class DataSet<
Item extends PartItem<IdProp>,
IdProp extends string = "id"
>
extends DataSetPart<Item, IdProp>
implements DataInterface<Item, IdProp> {
/** Flush all queued calls. */
public flush?: () => void;
/** @inheritDoc */
public length: number;
/** @inheritDoc */
public get idProp(): IdProp {
return this._idProp;
}
private readonly _options: DataSetInitialOptions<IdProp>;
private readonly _data: Map<Id, FullItem<Item, IdProp>>;
private readonly _idProp: IdProp;
private _queue: Queue<this> | null = null;
/**
* @param options - DataSet configuration.
*/
public constructor(options?: DataSetInitialOptions<IdProp>);
/**
* @param data - An initial set of items for the new instance.
* @param options - DataSet configuration.
*/
public constructor(data: Item[], options?: DataSetInitialOptions<IdProp>);
/**
* Construct a new DataSet.
*
* @param data - Initial data or options.
* @param options - Options (type error if data is also options).
*/
public constructor(
data?: Item[] | DataSetInitialOptions<IdProp>,
options?: DataSetInitialOptions<IdProp>
) {
super();
// correctly read optional arguments
if (data && !Array.isArray(data)) {
options = data;
data = [];
}
this._options = options || {};
this._data = new Map(); // map with data indexed by id
this.length = 0; // number of items in the DataSet
this._idProp = this._options.fieldId || ("id" as IdProp); // name of the field containing id
// add initial data when provided
if (data && data.length) {
this.add(data);
}
this.setOptions(options);
}
/**
* Set new options.
*
* @param options - The new options.
*/
public setOptions(options?: DataSetOptions): void {
if (options && options.queue !== undefined) {
if (options.queue === false) {
// delete queue if loaded
if (this._queue) {
this._queue.destroy();
this._queue = null;
}
} else {
// create queue and update its options
if (!this._queue) {
this._queue = Queue.extend(this, {
replace: ["add", "update", "remove"],
});
}
if (options.queue && typeof options.queue === "object") {
this._queue.setOptions(options.queue);
}
}
}
}
/**
* Add a data item or an array with items.
*
* After the items are added to the DataSet, the DataSet will trigger an event `add`. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
*
* ## Example
*
* ```javascript
* // create a DataSet
* const data = new vis.DataSet()
*
* // add items
* const ids = data.add([
* { id: 1, text: 'item 1' },
* { id: 2, text: 'item 2' },
* { text: 'item without an id' }
* ])
*
* console.log(ids) // [1, 2, '<UUIDv4>']
* ```
*
* @param data - Items to be added (ids will be generated if missing).
* @param senderId - Sender id.
*
* @returns addedIds - Array with the ids (generated if not present) of the added items.
*
* @throws When an item with the same id as any of the added items already exists.
*/
public add(data: Item | Item[], senderId?: Id | null): (string | number)[] {
const addedIds: Id[] = [];
let id: Id;
if (Array.isArray(data)) {
// Array
const idsToAdd: Id[] = data.map((d) => d[this._idProp] as Id);
if (idsToAdd.some((id) => this._data.has(id))) {
throw new Error("A duplicate id was found in the parameter array.");
}
for (let i = 0, len = data.length; i < len; i++) {
id = this._addItem(data[i]);
addedIds.push(id);
}
} else if (data && typeof data === "object") {
// Single item
id = this._addItem(data);
addedIds.push(id);
} else {
throw new Error("Unknown dataType");
}
if (addedIds.length) {
this._trigger("add", { items: addedIds }, senderId);
}
return addedIds;
}
/**
* Update existing items. When an item does not exist, it will be created.
*
* @remarks
* The provided properties will be merged in the existing item. When an item does not exist, it will be created.
*
* After the items are updated, the DataSet will trigger an event `add` for the added items, and an event `update`. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
*
* ## Example
*
* ```javascript
* // create a DataSet
* const data = new vis.DataSet([
* { id: 1, text: 'item 1' },
* { id: 2, text: 'item 2' },
* { id: 3, text: 'item 3' }
* ])
*
* // update items
* const ids = data.update([
* { id: 2, text: 'item 2 (updated)' },
* { id: 4, text: 'item 4 (new)' }
* ])
*
* console.log(ids) // [2, 4]
* ```
*
* ## Warning for TypeScript users
* This method may introduce partial items into the data set. Use add or updateOnly instead for better type safety.
*
* @param data - Items to be updated (if the id is already present) or added (if the id is missing).
* @param senderId - Sender id.
*
* @returns updatedIds - The ids of the added (these may be newly generated if there was no id in the item from the data) or updated items.
*
* @throws When the supplied data is neither an item nor an array of items.
*/
public update(
data: DeepPartial<Item> | DeepPartial<Item>[],
senderId?: Id | null
): Id[] {
const addedIds: Id[] = [];
const updatedIds: Id[] = [];
const oldData: FullItem<Item, IdProp>[] = [];
const updatedData: FullItem<Item, IdProp>[] = [];
const idProp = this._idProp;
const addOrUpdate = (item: DeepPartial<Item>): void => {
const origId: OptId = item[idProp];
if (origId != null && this._data.has(origId)) {
const fullItem = item as FullItem<Item, IdProp>; // it has an id, therefore it is a fullitem
const oldItem = Object.assign({}, this._data.get(origId));
// update item
const id = this._updateItem(fullItem);
updatedIds.push(id);
updatedData.push(fullItem);
oldData.push(oldItem);
} else {
// add new item
const id = this._addItem(item as any);
addedIds.push(id);
}
};
if (Array.isArray(data)) {
// Array
for (let i = 0, len = data.length; i < len; i++) {
if (data[i] && typeof data[i] === "object") {
addOrUpdate(data[i]);
} else {
console.warn(
"Ignoring input item, which is not an object at index " + i
);
}
}
} else if (data && typeof data === "object") {
// Single item
addOrUpdate(data);
} else {
throw new Error("Unknown dataType");
}
if (addedIds.length) {
this._trigger("add", { items: addedIds }, senderId);
}
if (updatedIds.length) {
const props = { items: updatedIds, oldData: oldData, data: updatedData };
// TODO: remove deprecated property 'data' some day
//Object.defineProperty(props, 'data', {
// 'get': (function() {
// console.warn('Property data is deprecated. Use DataSet.get(ids) to retrieve the new data, use the oldData property on this object to get the old data');
// return updatedData;
// }).bind(this)
//});
this._trigger("update", props, senderId);
}
return addedIds.concat(updatedIds);
}
/**
* Update existing items. When an item does not exist, an error will be thrown.
*
* @remarks
* The provided properties will be deeply merged into the existing item.
* When an item does not exist (id not present in the data set or absent), an error will be thrown and nothing will be changed.
*
* After the items are updated, the DataSet will trigger an event `update`.
* When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
*
* ## Example
*
* ```javascript
* // create a DataSet
* const data = new vis.DataSet([
* { id: 1, text: 'item 1' },
* { id: 2, text: 'item 2' },
* { id: 3, text: 'item 3' },
* ])
*
* // update items
* const ids = data.update([
* { id: 2, text: 'item 2 (updated)' }, // works
* // { id: 4, text: 'item 4 (new)' }, // would throw
* // { text: 'item 4 (new)' }, // would also throw
* ])
*
* console.log(ids) // [2]
* ```
*
* @param data - Updates (the id and optionally other props) to the items in this data set.
* @param senderId - Sender id.
*
* @returns updatedIds - The ids of the updated items.
*
* @throws When the supplied data is neither an item nor an array of items, when the ids are missing.
*/
public updateOnly(
data: UpdateItem<Item, IdProp> | UpdateItem<Item, IdProp>[],
senderId?: Id | null
): Id[] {
if (!Array.isArray(data)) {
data = [data];
}
const updateEventData = data
.map((update): {
oldData: FullItem<Item, IdProp>;
update: UpdateItem<Item, IdProp>;
} => {
const oldData = this._data.get(update[this._idProp]);
if (oldData == null) {
throw new Error("Updating non-existent items is not allowed.");
}
return { oldData, update };
})
.map(({ oldData, update }): {
id: Id;
oldData: FullItem<Item, IdProp>;
updatedData: FullItem<Item, IdProp>;
} => {
const id = oldData[this._idProp];
const updatedData = pureDeepObjectAssign(oldData, update);
this._data.set(id, updatedData);
return {
id,
oldData: oldData,
updatedData,
};
});
if (updateEventData.length) {
const props: EventPayloads<Item, IdProp>["update"] = {
items: updateEventData.map((value): Id => value.id),
oldData: updateEventData.map(
(value): FullItem<Item, IdProp> => value.oldData
),
data: updateEventData.map(
(value): FullItem<Item, IdProp> => value.updatedData
),
};
// TODO: remove deprecated property 'data' some day
//Object.defineProperty(props, 'data', {
// 'get': (function() {
// console.warn('Property data is deprecated. Use DataSet.get(ids) to retrieve the new data, use the oldData property on this object to get the old data');
// return updatedData;
// }).bind(this)
//});
this._trigger("update", props, senderId);
return props.items;
} else {
return [];
}
}
/** @inheritDoc */
public get(): FullItem<Item, IdProp>[];
/** @inheritDoc */
public get(
options: DataInterfaceGetOptionsArray<Item>
): FullItem<Item, IdProp>[];
/** @inheritDoc */
public get(
options: DataInterfaceGetOptionsObject<Item>
): Record<Id, FullItem<Item, IdProp>>;
/** @inheritDoc */
public get(
options: DataInterfaceGetOptions<Item>
): FullItem<Item, IdProp>[] | Record<Id, FullItem<Item, IdProp>>;
/** @inheritDoc */
public get(id: Id): null | FullItem<Item, IdProp>;
/** @inheritDoc */
public get(
id: Id,
options: DataInterfaceGetOptionsArray<Item>
): null | FullItem<Item, IdProp>;
/** @inheritDoc */
public get(
id: Id,
options: DataInterfaceGetOptionsObject<Item>
): Record<Id, FullItem<Item, IdProp>>;
/** @inheritDoc */
public get(
id: Id,
options: DataInterfaceGetOptions<Item>
): null | FullItem<Item, IdProp> | Record<Id, FullItem<Item, IdProp>>;
/** @inheritDoc */
public get(ids: Id[]): FullItem<Item, IdProp>[];
/** @inheritDoc */
public get(
ids: Id[],
options: DataInterfaceGetOptionsArray<Item>
): FullItem<Item, IdProp>[];
/** @inheritDoc */
public get(
ids: Id[],
options: DataInterfaceGetOptionsObject<Item>
): Record<Id, FullItem<Item, IdProp>>;
/** @inheritDoc */
public get(
ids: Id[],
options: DataInterfaceGetOptions<Item>
): FullItem<Item, IdProp>[] | Record<Id, FullItem<Item, IdProp>>;
/** @inheritDoc */
public get(
ids: Id | Id[],
options?: DataInterfaceGetOptions<Item>
):
| null
| FullItem<Item, IdProp>
| FullItem<Item, IdProp>[]
| Record<Id, FullItem<Item, IdProp>>;
/** @inheritDoc */
public get(
first?: DataInterfaceGetOptions<Item> | Id | Id[],
second?: DataInterfaceGetOptions<Item>
):
| null
| FullItem<Item, IdProp>
| FullItem<Item, IdProp>[]
| Record<Id, FullItem<Item, IdProp>> {
// @TODO: Woudn't it be better to split this into multiple methods?
// parse the arguments
let id: Id | undefined = undefined;
let ids: Id[] | undefined = undefined;
let options: DataInterfaceGetOptions<Item> | undefined = undefined;
if (isId(first)) {
// get(id [, options])
id = first;
options = second;
} else if (Array.isArray(first)) {
// get(ids [, options])
ids = first;
options = second;
} else {
// get([, options])
options = first;
}
// determine the return type
const returnType =
options && options.returnType === "Object" ? "Object" : "Array";
// @TODO: WTF is this? Or am I missing something?
// var returnType
// if (options && options.returnType) {
// var allowedValues = ['Array', 'Object']
// returnType =
// allowedValues.indexOf(options.returnType) == -1
// ? 'Array'
// : options.returnType
// } else {
// returnType = 'Array'
// }
// build options
const filter = options && options.filter;
const items: FullItem<Item, IdProp>[] = [];
let item: undefined | FullItem<Item, IdProp> = undefined;
let itemIds: undefined | Id[] = undefined;
let itemId: undefined | Id = undefined;
// convert items
if (id != null) {
// return a single item
item = this._data.get(id);
if (item && filter && !filter(item)) {
item = undefined;
}
} else if (ids != null) {
// return a subset of items
for (let i = 0, len = ids.length; i < len; i++) {
item = this._data.get(ids[i]);
if (item != null && (!filter || filter(item))) {
items.push(item);
}
}
} else {
// return all items
itemIds = [...this._data.keys()];
for (let i = 0, len = itemIds.length; i < len; i++) {
itemId = itemIds[i];
item = this._data.get(itemId);
if (item != null && (!filter || filter(item))) {
items.push(item);
}
}
}
// order the results
if (options && options.order && id == undefined) {
this._sort(items, options.order);
}
// filter fields of the items
if (options && options.fields) {
const fields = options.fields;
if (id != undefined && item != null) {
item = this._filterFields(item, fields) as FullItem<Item, IdProp>;
} else {
for (let i = 0, len = items.length; i < len; i++) {
items[i] = this._filterFields(items[i], fields) as FullItem<
Item,
IdProp
>;
}
}
}
// return the results
if (returnType == "Object") {
const result: Record<string, FullItem<Item, IdProp>> = {};
for (let i = 0, len = items.length; i < len; i++) {
const resultant = items[i];
// @TODO: Shoudn't this be this._fieldId?
// result[resultant.id] = resultant
const id: Id = resultant[this._idProp];
result[id] = resultant;
}
return result;
} else {
if (id != null) {
// a single item
return item ?? null;
} else {
// just return our array
return items;
}
}
}
/** @inheritDoc */
public getIds(options?: DataInterfaceGetIdsOptions<Item>): Id[] {
const data = this._data;
const filter = options && options.filter;
const order = options && options.order;
const itemIds = [...data.keys()];
const ids: Id[] = [];
if (filter) {
// get filtered items
if (order) {
// create ordered list
const items = [];
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = this._data.get(id);
if (item != null && filter(item)) {
items.push(item);
}
}
this._sort(items, order);
for (let i = 0, len = items.length; i < len; i++) {
ids.push(items[i][this._idProp]);
}
} else {
// create unordered list
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = this._data.get(id);
if (item != null && filter(item)) {
ids.push(item[this._idProp]);
}
}
}
} else {
// get all items
if (order) {
// create an ordered list
const items = [];
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
items.push(data.get(id)!);
}
this._sort(items, order);
for (let i = 0, len = items.length; i < len; i++) {
ids.push(items[i][this._idProp]);
}
} else {
// create unordered list
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = data.get(id);
if (item != null) {
ids.push(item[this._idProp]);
}
}
}
}
return ids;
}
/** @inheritDoc */
public getDataSet(): DataSet<Item, IdProp> {
return this;
}
/** @inheritDoc */
public forEach(
callback: (item: Item, id: Id) => void,
options?: DataInterfaceForEachOptions<Item>
): void {
const filter = options && options.filter;
const data = this._data;
const itemIds = [...data.keys()];
if (options && options.order) {
// execute forEach on ordered list
const items: FullItem<Item, IdProp>[] = this.get(options);
for (let i = 0, len = items.length; i < len; i++) {
const item = items[i];
const id = item[this._idProp];
callback(item, id);
}
} else {
// unordered
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = this._data.get(id);
if (item != null && (!filter || filter(item))) {
callback(item, id);
}
}
}
}
/** @inheritDoc */
public map<T>(
callback: (item: Item, id: Id) => T,
options?: DataInterfaceMapOptions<Item, T>
): T[] {
const filter = options && options.filter;
const mappedItems: T[] = [];
const data = this._data;
const itemIds = [...data.keys()];
// convert and filter items
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = this._data.get(id);
if (item != null && (!filter || filter(item))) {
mappedItems.push(callback(item, id));
}
}
// order items
if (options && options.order) {
this._sort(mappedItems, options.order);
}
return mappedItems;
}
private _filterFields<K extends string>(item: null, fields: K[]): null;
private _filterFields<K extends string>(
item: Record<K, unknown>,
fields: K[]
): Record<K, unknown>;
private _filterFields<K extends string>(
item: Record<K, unknown>,
fields: K[] | Record<K, string>
): any;
/**
* Filter the fields of an item.
*
* @param item - The item whose fields should be filtered.
* @param fields - The names of the fields that will be kept.
*
* @typeParam K - Field name type.
*
* @returns The item without any additional fields.
*/
private _filterFields<K extends string>(
item: Record<K, unknown> | null,
fields: K[] | Record<K, unknown>
): Record<K, unknown> | null {
if (!item) {
// item is null
return item;
}
return (Array.isArray(fields)
? // Use the supplied array
fields
: // Use the keys of the supplied object
(Object.keys(fields) as K[])
).reduce<Record<string, unknown>>((filteredItem, field): Record<
string,
unknown
> => {
filteredItem[field] = item[field];
return filteredItem;
}, {});
}
/**
* Sort the provided array with items.
*
* @param items - Items to be sorted in place.
* @param order - A field name or custom sort function.
*
* @typeParam T - The type of the items in the items array.
*/
private _sort<T>(items: T[], order: DataInterfaceOrder<T>): void {
if (typeof order === "string") {
// order by provided field name
const name = order; // field name
items.sort((a, b): -1 | 0 | 1 => {
// @TODO: How to treat missing properties?
const av = (a as any)[name];
const bv = (b as any)[name];
return av > bv ? 1 : av < bv ? -1 : 0;
});
} else if (typeof order === "function") {
// order by sort function
items.sort(order);
} else {
// TODO: extend order by an Object {field:string, direction:string}
// where direction can be 'asc' or 'desc'
throw new TypeError("Order must be a function or a string");
}
}
/**
* Remove an item or multiple items by “reference” (only the id is used) or by id.
*
* The method ignores removal of non-existing items, and returns an array containing the ids of the items which are actually removed from the DataSet.
*
* After the items are removed, the DataSet will trigger an event `remove` for the removed items. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
*
* ## Example
* ```javascript
* // create a DataSet
* const data = new vis.DataSet([
* { id: 1, text: 'item 1' },
* { id: 2, text: 'item 2' },
* { id: 3, text: 'item 3' }
* ])
*
* // remove items
* const ids = data.remove([2, { id: 3 }, 4])
*
* console.log(ids) // [2, 3]
* ```
*
* @param id - One or more items or ids of items to be removed.
* @param senderId - Sender id.
*
* @returns The ids of the removed items.
*/
public remove(id: Id | Item | (Id | Item)[], senderId?: Id | null): Id[] {
const removedIds: Id[] = [];
const removedItems: FullItem<Item, IdProp>[] = [];
// force everything to be an array for simplicity
const ids = Array.isArray(id) ? id : [id];
for (let i = 0, len = ids.length; i < len; i++) {
const item = this._remove(ids[i]);
if (item) {
const itemId: OptId = item[this._idProp];
if (itemId != null) {
removedIds.push(itemId);
removedItems.push(item);
}
}
}
if (removedIds.length) {
this._trigger(
"remove",
{ items: removedIds, oldData: removedItems },
senderId
);
}
return removedIds;
}
/**
* Remove an item by its id or reference.
*
* @param id - Id of an item or the item itself.
*
* @returns The removed item if removed, null otherwise.
*/
private _remove(id: Id | Item): FullItem<Item, IdProp> | null {
// @TODO: It origianlly returned the item although the docs say id.
// The code expects the item, so probably an error in the docs.
let ident: OptId;
// confirm the id to use based on the args type
if (isId(id)) {
ident = id;
} else if (id && typeof id === "object") {
ident = id[this._idProp]; // look for the identifier field using ._idProp
}
// do the removing if the item is found
if (ident != null && this._data.has(ident)) {
const item = this._data.get(ident) || null;
this._data.delete(ident);
--this.length;
return item;
}
return null;
}
/**
* Clear the entire data set.
*
* After the items are removed, the [[DataSet]] will trigger an event `remove` for all removed items. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
*
* @param senderId - Sender id.
*
* @returns removedIds - The ids of all removed items.
*/
public clear(senderId?: Id | null): Id[] {
const ids = [...this._data.keys()];
const items: FullItem<Item, IdProp>[] = [];
for (let i = 0, len = ids.length; i < len; i++) {
items.push(this._data.get(ids[i])!);
}
this._data.clear();
this.length = 0;
this._trigger("remove", { items: ids, oldData: items }, senderId);
return ids;
}
/**
* Find the item with maximum value of a specified field.
*
* @param field - Name of the property that should be searched for max value.
*
* @returns Item containing max value, or null if no items.
*/
public max(field: keyof Item): Item | null {
let max = null;
let maxField = null;
for (const item of this._data.values()) {
const itemField = item[field];
if (
typeof itemField === "number" &&
(maxField == null || itemField > maxField)
) {
max = item;
maxField = itemField;
}
}
return max || null;
}
/**
* Find the item with minimum value of a specified field.
*
* @param field - Name of the property that should be searched for min value.
*
* @returns Item containing min value, or null if no items.
*/
public min(field: keyof Item): Item | null {
let min = null;
let minField = null;
for (const item of this._data.values()) {
const itemField = item[field];
if (
typeof itemField === "number" &&
(minField == null || itemField < minField)
) {
min = item;
minField = itemField;
}
}
return min || null;
}
public distinct<T extends keyof Item>(prop: T): Item[T][];
public distinct(prop: string): unknown[];
/**
* Find all distinct values of a specified field
*
* @param prop - The property name whose distinct values should be returned.
*
* @returns Unordered array containing all distinct values. Items without specified property are ignored.
*/
public distinct<T extends string>(prop: T): unknown[] {
const data = this._data;
const itemIds = [...data.keys()];
const values: unknown[] = [];
let count = 0;
for (let i = 0, len = itemIds.length; i < len; i++) {
const id = itemIds[i];
const item = data.get(id);
const value = (item as any)[prop];
let exists = false;
for (let j = 0; j < count; j++) {
if (values[j] == value) {
exists = true;
break;
}
}
if (!exists && value !== undefined) {
values[count] = value;
count++;
}
}
return values;
}
/**
* Add a single item. Will fail when an item with the same id already exists.
*
* @param item - A new item to be added.
*
* @returns Added item's id. An id is generated when it is not present in the item.
*/
private _addItem(item: Item): Id {
const fullItem = ensureFullItem(item, this._idProp);
const id = fullItem[this._idProp];
// check whether this id is already taken
if (this._data.has(id)) {
// item already exists
throw new Error(
"Cannot add item: item with id " + id + " already exists"
);
}
this._data.set(id, fullItem);
++this.length;
return id;
}
/**
* Update a single item: merge with existing item.
* Will fail when the item has no id, or when there does not exist an item with the same id.
*
* @param update - The new item
*
* @returns The id of the updated item.
*/
private _updateItem(update: FullItem<Item, IdProp>): Id {
const id: OptId = update[this._idProp];
if (id == null) {
throw new Error(
"Cannot update item: item has no id (item: " +
JSON.stringify(update) +
")"
);
}
const item = this._data.get(id);
if (!item) {
// item doesn't exist
throw new Error("Cannot update item: no item with id " + id + " found");
}
this._data.set(id, { ...item, ...update });
return id;
}
/** @inheritDoc */
public stream(ids?: Iterable<Id>): DataStream<Item> {
if (ids) {
const data = this._data;
return new DataStream<Item>({
*[Symbol.iterator](): IterableIterator<[Id, Item]> {
for (const id of ids) {
const item = data.get(id);
if (item != null) {
yield [id, item];
}
}
},
});
} else {
return new DataStream({
[Symbol.iterator]: this._data.entries.bind(this._data),
});
}
}
/* develblock:start */
public get testLeakData(): Map<Id, FullItem<Item, IdProp>> {
return this._data;
}
public get testLeakIdProp(): IdProp {
return this._idProp;
}
public get testLeakOptions(): DataSetInitialOptions<IdProp> {
return this._options;
}
public get testLeakQueue(): Queue<this> | null {
return this._queue;
}
public set testLeakQueue(v: Queue<this> | null) {
this._queue = v;
}
/* develblock:end */
} | the_stack |
import * as vscode from 'vscode';
import * as path from 'path';
import { copyFile } from 'fs';
import { runTlc, stopProcess } from '../tla2tools';
import { TlcModelCheckerStdoutParser } from '../parsers/tlc';
import { updateCheckResultView, revealEmptyCheckResultView, revealLastCheckResultView } from '../checkResultView';
import { applyDCollection } from '../diagnostic';
import { ChildProcess } from 'child_process';
import { saveStreamToFile } from '../outputSaver';
import { replaceExtension, LANG_TLAPLUS, LANG_TLAPLUS_CFG, listFiles, exists } from '../common';
import { ModelCheckResultSource, ModelCheckResult, SpecFiles } from '../model/check';
import { ToolOutputChannel } from '../outputChannels';
import { Utils } from 'vscode-uri';
export const CMD_CHECK_MODEL_RUN = 'tlaplus.model.check.run';
export const CMD_CHECK_MODEL_RUN_AGAIN = 'tlaplus.model.check.runAgain';
export const CMD_CHECK_MODEL_CUSTOM_RUN = 'tlaplus.model.check.customRun';
export const CMD_CHECK_MODEL_STOP = 'tlaplus.model.check.stop';
export const CMD_CHECK_MODEL_DISPLAY = 'tlaplus.model.check.display';
export const CMD_SHOW_TLC_OUTPUT = 'tlaplus.showTlcOutput';
export const CTX_TLC_RUNNING = 'tlaplus.tlc.isRunning';
export const CTX_TLC_CAN_RUN_AGAIN = 'tlaplus.tlc.canRunAgain';
const CFG_CREATE_OUT_FILES = 'tlaplus.tlc.modelChecker.createOutFiles';
const TEMPLATE_CFG_PATH = path.resolve(__dirname, '../../../tools/template.cfg');
let checkProcess: ChildProcess | undefined;
let lastCheckFiles: SpecFiles | undefined;
const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 0);
const outChannel = new ToolOutputChannel('TLC', mapTlcOutputLine);
class CheckResultHolder {
checkResult: ModelCheckResult | undefined;
}
/**
* Runs TLC on a TLA+ specification.
*/
export async function checkModel(
fileUri: vscode.Uri | undefined,
diagnostic: vscode.DiagnosticCollection,
extContext: vscode.ExtensionContext
): Promise<void> {
const uri = fileUri ? fileUri : getActiveEditorFileUri(extContext);
if (!uri) {
return;
}
const specFiles = await getSpecFiles(uri, false);
if (!specFiles) {
return;
}
doCheckModel(specFiles, true, extContext, diagnostic, true);
}
export async function runLastCheckAgain(
diagnostic: vscode.DiagnosticCollection,
extContext: vscode.ExtensionContext
): Promise<void> {
if (!lastCheckFiles) {
vscode.window.showWarningMessage('No last check to run');
return;
}
if (!canRunTlc(extContext)) {
return;
}
doCheckModel(lastCheckFiles, true, extContext, diagnostic, false);
}
export async function checkModelCustom(
diagnostic: vscode.DiagnosticCollection,
extContext: vscode.ExtensionContext
): Promise<void> {
const editor = getEditorIfCanRunTlc(extContext);
if (!editor) {
return;
}
const doc = editor.document;
if (doc.languageId !== LANG_TLAPLUS) {
vscode.window.showWarningMessage('File in the active editor is not a .tla, it cannot be checked as a model');
return;
}
// Accept .tla files here because TLC configs and TLA+ modules can share the same file:
// https://github.com/alygin/vscode-tlaplus/issues/220
const configFiles = await listFiles(path.dirname(doc.uri.fsPath),
(fName) => fName.endsWith('.cfg') || fName.endsWith('.tla'));
configFiles.sort();
const cfgFileName = await vscode.window.showQuickPick(
configFiles,
{ canPickMany: false, placeHolder: 'Select a model config file', matchOnDetail: true }
);
if (!cfgFileName || cfgFileName.length === 0) {
return;
}
const specFiles = new SpecFiles(
doc.uri.fsPath,
path.join(path.dirname(doc.uri.fsPath), cfgFileName)
);
doCheckModel(specFiles, true, extContext, diagnostic, true);
}
/**
* Reveals model checking view panel.
*/
export function displayModelChecking(extContext: vscode.ExtensionContext): void {
revealLastCheckResultView(extContext);
}
/**
* Stops the current model checking process.
*/
export function stopModelChecking(
terminateLastRun: (lastSpecFiles: SpecFiles | undefined) => boolean =
(lastSpecFiles: SpecFiles | undefined): boolean => { return true; },
silent: boolean = false
): void {
if (checkProcess && terminateLastRun(lastCheckFiles)) {
stopProcess(checkProcess);
} else if (!silent) {
vscode.window.showInformationMessage("There're no currently running model checking processes");
}
}
export function showTlcOutput(): void {
outChannel.revealWindow();
}
function getActiveEditorFileUri(extContext: vscode.ExtensionContext): vscode.Uri | undefined {
const editor = getEditorIfCanRunTlc(extContext);
if (!editor) {
return undefined;
}
const doc = editor.document;
if (doc.languageId !== LANG_TLAPLUS && doc.languageId !== LANG_TLAPLUS_CFG) {
vscode.window.showWarningMessage(
'File in the active editor is not a .tla or .cfg file, it cannot be checked as a model');
return undefined;
}
return doc.uri;
}
export function getEditorIfCanRunTlc(extContext: vscode.ExtensionContext): vscode.TextEditor | undefined {
if (!canRunTlc(extContext)) {
return undefined;
}
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showWarningMessage('No editor is active, cannot find a TLA+ model to check');
return undefined;
}
return editor;
}
function canRunTlc(extContext: vscode.ExtensionContext): boolean {
if (checkProcess) {
vscode.window.showWarningMessage(
'Another model checking process is currently running',
'Show currently running process'
).then(() => revealLastCheckResultView(extContext));
return false;
}
return true;
}
export async function doCheckModel(
specFiles: SpecFiles,
showCheckResultView: boolean,
extContext: vscode.ExtensionContext,
diagnostic: vscode.DiagnosticCollection,
showOptionsPrompt: boolean,
extraOpts: string[] = [],
debuggerPortCallback?: (port?: number) => void
): Promise<ModelCheckResult | undefined> {
try {
lastCheckFiles = specFiles;
vscode.commands.executeCommand('setContext', CTX_TLC_CAN_RUN_AGAIN, true);
updateStatusBarItem(true);
const procInfo = await runTlc(
specFiles.tlaFilePath, path.basename(specFiles.cfgFilePath), showOptionsPrompt, extraOpts);
if (procInfo === undefined) {
// Command cancelled by user
return undefined;
}
outChannel.bindTo(procInfo);
checkProcess = procInfo.process;
checkProcess.on('close', () => {
checkProcess = undefined;
updateStatusBarItem(false);
});
if (showCheckResultView) {
attachFileSaver(specFiles.tlaFilePath, checkProcess);
revealEmptyCheckResultView(ModelCheckResultSource.Process, extContext);
}
const resultHolder = new CheckResultHolder();
const checkResultCallback = (checkResult: ModelCheckResult) => {
resultHolder.checkResult = checkResult;
if (showCheckResultView) {
updateCheckResultView(checkResult);
}
};
const stdoutParser = new TlcModelCheckerStdoutParser(
ModelCheckResultSource.Process,
checkProcess.stdout,
specFiles,
true,
checkResultCallback,
debuggerPortCallback
);
const dCol = await stdoutParser.readAll();
applyDCollection(dCol, diagnostic);
return resultHolder.checkResult;
} catch (err) {
statusBarItem.hide();
vscode.window.showErrorMessage(err.message);
}
return undefined;
}
function attachFileSaver(tlaFilePath: string, proc: ChildProcess) {
const createOutFiles = vscode.workspace.getConfiguration().get<boolean>(CFG_CREATE_OUT_FILES);
if (typeof(createOutFiles) === 'undefined' || createOutFiles) {
const outFilePath = replaceExtension(tlaFilePath, 'out');
saveStreamToFile(proc.stdout, outFilePath);
}
}
/**
* Finds all files that needed to run model check.
*/
export async function getSpecFiles(fileUri: vscode.Uri, warn = true, prefix = 'MC'): Promise<SpecFiles | undefined> {
let specFiles;
// a) Check the given input if it exists.
specFiles = await checkSpecFiles(fileUri, false);
if (specFiles) {
return specFiles;
}
// b) Check alternatives:
// Unless the given filePath already starts with 'MC', prepend MC to the name
// and check if it exists. If yes, it becomes the spec file. If not, fall back
// to the original file. The assumptions is that a user usually has Spec.tla
// open in the editor and doesn't want to switch to MC.tla before model-checking.
// TODO: Ideally, we wouldn't just check filenames here but check the parse result
// TODO: if the module in MCSpec.tla actually extends the module in Spec.
const b = Utils.basename(fileUri);
if (!b.startsWith(prefix) && !b.endsWith('.cfg')) {
const str = fileUri.toString();
const n = str.substr(0, str.lastIndexOf(b)) + prefix + b;
const filePath = vscode.Uri.parse(n).fsPath;
specFiles = new SpecFiles(filePath, replaceExtension(filePath, 'cfg'));
// Here, we make sure that the .cfg *and* the .tla exist.
let canRun = true;
canRun = await checkModelExists(specFiles.cfgFilePath, warn);
canRun = canRun && await checkModuleExists(specFiles.tlaFilePath, warn);
if (canRun) {
return specFiles;
}
}
// c) Deliberately trigger the warning dialog by checking the given input again
// knowing that it doesn't exist.
return await checkSpecFiles(fileUri, warn);
}
async function checkSpecFiles(fileUri: vscode.Uri, warn = true): Promise<SpecFiles | undefined> {
const filePath = fileUri.fsPath;
let specFiles;
let canRun = true;
if (filePath.endsWith('.cfg')) {
specFiles = new SpecFiles(replaceExtension(filePath, 'tla'), filePath);
canRun = await checkModuleExists(specFiles.tlaFilePath, warn);
} else if (filePath.endsWith('.tla')) {
specFiles = new SpecFiles(filePath, replaceExtension(filePath, 'cfg'));
canRun = await checkModelExists(specFiles.cfgFilePath, warn);
}
return canRun ? specFiles : undefined;
}
async function checkModuleExists(modulePath: string, warn = true): Promise<boolean> {
const moduleExists = await exists(modulePath);
if (!moduleExists && warn) {
const moduleFile = path.basename(modulePath);
vscode.window.showWarningMessage(`Corresponding TLA+ module file ${moduleFile} doesn't exist.`);
}
return moduleExists;
}
async function checkModelExists(cfgPath: string, warn = true): Promise<boolean> {
const cfgExists = await exists(cfgPath);
if (!cfgExists && warn) {
showConfigAbsenceWarning(cfgPath);
}
return cfgExists;
}
function updateStatusBarItem(active: boolean) {
statusBarItem.text = 'TLC' + (active ? ' $(gear~spin)' : '');
statusBarItem.tooltip = 'TLA+ model checking' + (active ? ' is running' : ' result');
statusBarItem.command = CMD_CHECK_MODEL_DISPLAY;
statusBarItem.show();
vscode.commands.executeCommand('setContext', CTX_TLC_RUNNING, active);
}
function showConfigAbsenceWarning(cfgPath: string) {
const fileName = path.basename(cfgPath);
const createOption = 'Create model file';
vscode.window.showWarningMessage(`Model file ${fileName} doesn't exist. Cannot check model.`, createOption)
.then((option) => {
if (option === createOption) {
createModelFile(cfgPath);
}
});
}
async function createModelFile(cfgPath: string) {
copyFile(TEMPLATE_CFG_PATH, cfgPath, (err) => {
if (err) {
console.warn(`Error creating config file: ${err}`);
vscode.window.showWarningMessage(`Cannot create model file: ${err}`);
return;
}
vscode.workspace.openTextDocument(cfgPath)
.then(doc => vscode.window.showTextDocument(doc));
});
}
function mapTlcOutputLine(line: string): string | undefined {
if (line === '') {
return line;
}
const cleanLine = line.replace(/@!@!@(START|END)MSG \d+(:\d+)? @!@!@/g, '');
return cleanLine === '' ? undefined : cleanLine;
} | the_stack |
const availableImapServer = /imap\-mail\.outlook\.com$|imap\.mail\.yahoo\.(com|co\.jp|co\.uk|au)$|imap\.mail\.me\.com$|imap\.gmail\.com$|gmx\.(com|us|net)$|imap\.zoho\.com$/i
/**
* getImapSmtpHost
* @param email <string>
* @return Imap & Smtp info
*/
const getImapSmtpHost = function ( _email: string ) {
const email = _email.toLowerCase()
const yahoo = function ( domain: string ) {
if ( /yahoo.co.jp$/i.test ( domain ))
return 'yahoo.co.jp';
if ( /((.*\.){0,1}yahoo|yahoogroups|yahooxtra|yahoogruppi|yahoogrupper)(\..{2,3}){1,2}$/.test ( domain ))
return 'yahoo.com';
if ( /(^hotmail|^outlook|^live|^msn)(\..{2,3}){1,2}$/.test ( domain ))
return 'hotmail.com';
if ( /^(me|^icould|^mac)\.com/.test ( domain ))
return 'me.com'
return domain
}
const emailSplit = email.split ( '@' )
if ( emailSplit.length !== 2 )
return null
const domain = yahoo ( emailSplit [1].toLowerCase() )
const ret = {
imap: 'imap.' + domain,
smtp: 'smtp.' + domain,
SmtpPort: [465,587,994],
ImapPort: 993,
imapSsl: true,
smtpSsl: true,
haveAppPassword: false,
ApplicationPasswordInformationUrl: ['']
}
switch ( domain ) {
// yahoo domain have two different
// the yahoo.co.jp is different other yahoo.*
case 'yahoo.co.jp': {
ret.imap = 'imap.mail.yahoo.co.jp'
ret.smtp = 'smtp.mail.yahoo.co.jp'
break
}
// gmail
case 'google.com':
case 'googlemail.com':
case 'gmail': {
ret.haveAppPassword = true;
ret.ApplicationPasswordInformationUrl = [
'https://support.google.com/accounts/answer/185833?hl=zh-Hans',
'https://support.google.com/accounts/answer/185833?hl=ja',
'https://support.google.com/accounts/answer/185833?hl=en'
]
break
}
case 'gandi.net': {
ret.imap = ret.smtp = 'mail.gandi.net'
break
}
// yahoo.com
case 'rocketmail.com':
case 'y7mail.com':
case 'ymail.com':
case 'yahoo.com': {
ret.imap = 'imap.mail.yahoo.com'
ret.smtp = (/^bizmail.yahoo.com$/.test(emailSplit[1]))
? 'smtp.bizmail.yahoo.com'
: 'smtp.mail.yahoo.com'
ret.haveAppPassword = true;
ret.ApplicationPasswordInformationUrl = [
'https://help.yahoo.com/kb/SLN15241.html',
'https://help.yahoo.com/kb/SLN15241.html',
'https://help.yahoo.com/kb/SLN15241.html'
]
break
}
case 'mail.ee': {
ret.smtp = 'mail.ee'
ret.imap = 'mail.inbox.ee'
break
}
// gmx.com
case 'gmx.co.uk':
case 'gmx.de':
case 'gmx.us':
case 'gmx.com' : {
ret.smtp = 'mail.gmx.com'
ret.imap = 'imap.gmx.com'
break
}
// aim.com
case 'aim.com': {
ret.imap = 'imap.aol.com'
break
}
// outlook.com
case 'windowslive.com':
case 'hotmail.com':
case 'outlook.com': {
ret.imap = 'imap-mail.outlook.com'
ret.smtp = 'smtp-mail.outlook.com'
break
}
// apple mail
case 'icloud.com':
case 'mac.com':
case 'me.com': {
ret.imap = 'imap.mail.me.com'
ret.smtp = 'smtp.mail.me.com'
break
}
// 163.com
case '126.com':
case '163.com': {
ret.imap = 'appleimap.' + domain
ret.smtp = 'applesmtp.' + domain
break
}
case 'sina.com':
case 'yeah.net': {
ret.smtpSsl = false
break
}
}
return ret
}
class keyPairSign {
public signError = ko.observable ( false )
public conformButtom = ko.observable ( false )
public requestActivEmailrunning = ko.observable ( false )
public showSentActivEmail = ko.observable ( -1 )
public conformText = ko.observable ('')
public conformTextError = ko.observable ( false )
public requestError = ko.observable (-1)
public conformTextErrorNumber = ko.observable ( -1 )
public activeing = ko.observable ( false )
public showRequestActivEmailButtonError = ko.observable ( false )
constructor ( private exit: () => void ) {
const self = this
this.conformText.subscribe ( function ( newValue ) {
if ( !newValue || !newValue.length ) {
self.conformButtom ( false )
} else {
self.conformButtom ( true )
}
})
}
public checkActiveEmailSubmit () {
const self = this
this.conformTextError ( false )
this.activeing ( true )
let text = this.conformText()
const showFromatError = ( err ) => {
self.activeing ( false )
self.conformTextErrorNumber ( _view.connectInformationMessage.getErrorIndex ( err ))
self.conformTextError ( true )
return $( '.activating.element1' ).popup({
on: 'click',
onHidden: function () {
self.conformTextError ( false )
}
})
}
if ( ! text || ! text.length || !/^-+BEGIN PGP MESSAGE-+\n/.test ( text )) {
return showFromatError ( 'PgpMessageFormatError' )
}
// support Outlook mail
/*
if ( / /.test ( text )) {
text = text.replace ( / PGP MESSAGE/g, '__PGP__MESSAGE').replace (/ /g, '\r\n').replace (/__/g, ' ' )
text = text.replace ( / MESSAGE-----/,' MESSAGE-----\r\n' )
}
/** */
return _view.keyPairCalss.decryptMessage ( text, ( err, obj ) => {
if ( err ) {
return showFromatError ( 'PgpDecryptError' )
}
const com: QTGateAPIRequestCommand = {
command: 'activePassword',
Args: [ obj ],
error: null,
subCom: null
}
return _view.keyPairCalss.emitRequest ( com, ( err, com: QTGateAPIRequestCommand ) => {
if ( err ) {
return showFromatError ( err )
}
if ( com ) {
if ( com.error ) {
return showFromatError ( com.error )
}
const keyPair: keypair = _view.localServerConfig ().keypair
keyPair.verified = true
keyPair.publicKey = Buffer.from ( com.Args[0],'base64').toString ()
_view.keyPair ( keyPair )
_view.sectionLogin ( false )
self.exit ()
}
})
})
/*
return _view.connectInformationMessage.sockEmit ( 'checkActiveEmailSubmit', text, function ( err, req: QTGateAPIRequestCommand ) {
self.activeing ( false )
if ( err !== null && err > -1 || req && req.error != null && req.error > -1 ) {
self.conformTextErrorNumber ( err !== null && err > -1 ? err : req.error )
self.conformTextError ( true )
}
if (!req ) {
const config = _view.localServerConfig()
config.keypair.verified = true
_view.localServerConfig ( config )
_view.keyPair ( config.keypair )
_view.sectionLogin ( false )
self.exit ()
}
})
*/
}
public clearError () {
_view.connectInformationMessage.hideMessage()
this.showRequestActivEmailButtonError ( false )
}
public requestActivEmail () {
const self = this
this.requestActivEmailrunning ( true )
const com: QTGateAPIRequestCommand = {
command: 'requestActivEmail',
Args: [],
error: null,
subCom: null
}
const errorProcess = ( err ) => {
this.requestActivEmailrunning ( false )
this.showRequestActivEmailButtonError ( true )
_view.connectInformationMessage.showErrorMessage ( err )
}
_view.keyPairCalss.emitRequest ( com, ( err, com: QTGateAPIRequestCommand ) => {
if ( err ) {
return errorProcess ( err )
}
if ( !com ) {
return
}
if ( com.error ) {
return errorProcess ( err )
}
if ( com.Args[0] && com.Args[0].length ) {
return _view.connectInformationMessage.sockEmit ( 'checkActiveEmailSubmit', com.Args [0], () => {
const config = _view.localServerConfig()
config.keypair.verified = true
_view.keyPair ( config.keypair )
_view.sectionLogin ( false )
localStorage.setItem ( "config", JSON.stringify ( config ))
self.exit ()
})
}
self.conformButtom ( false )
self.showSentActivEmail (1)
const u = self.showSentActivEmail()
})
/*
return _view.connectInformationMessage.sockEmit ( 'requestActivEmail', function ( err ) {
self.requestActivEmailrunning ( false )
if ( err !== null && err > -1 ) {
return self.requestError ( err )
}
self.conformButtom ( false ),[h]
self.showSentActivEmail (1)
const u = self.showSentActivEmail()
})
*/
}
}
class imapForm {
public emailAddress = ko.observable ('')
public password = ko.observable ('')
public emailAddressShowError = ko.observable ( false )
public passwordShowError = ko.observable ( false )
public EmailAddressErrorType = ko.observable ( 0 )
public showForm = ko.observable ( true )
public checkProcessing = ko.observable ( false )
public checkImapError = ko.observable ( -1 )
public showCheckProcess = ko.observable ( false )
public checkImapStep = ko.observable (0)
private clearError () {
this.emailAddressShowError ( false )
this.EmailAddressErrorType (0)
this.passwordShowError ( false )
}
private errorProcess ( err ) {
// Invalid login
if ( /Authentication|login/i.test ( err )) {
return this.checkImapError ( 1 )
}
// Cannot connect to email server!
if ( /ENOTFOUND/i.test ( err )) {
return this.checkImapError ( 0 )
}
// https://github.com/KloakIT/Kloak_platform/issues/2
if ( /certificate/i.test ( err )) {
return this.checkImapError ( 0 )
}
this.checkImapError ( 5 )
}
private checkImapSetup () {
let self = this
this.checkProcessing ( true )
this.checkImapStep (0)
const imapTest = function ( err ) {
if ( err && typeof err === "string" || err !== null && err > -1 ) {
return errorProcess ( err )
}
self.checkImapStep (5)
}
const smtpTest = function ( err ) {
if ( err && typeof err === "string" || err !== null && err > -1 ) {
return errorProcess ( err )
}
self.checkImapStep (2)
}
const imapTestFinish = function ( err: Error, IinputData: string ) {
removeAllListen ()
if ( err ) {
return errorProcess ( err )
}
_view.keyPairCalss.decrypt_withLocalServerKey ( IinputData, ( err, data: IinputData ) => {
if ( err ) {
return errorProcess ( err )
}
return self.exit ( data )
})
}
const removeAllListen = function () {
_view.connectInformationMessage.socketIo.removeEventListener ( 'smtpTest', smtpTest )
_view.connectInformationMessage.socketIo.removeEventListener ( 'imapTest', imapTest )
_view.connectInformationMessage.socketIo.removeEventListener ( 'imapTestFinish', imapTestFinish )
}
const errorProcess = function ( err ) {
removeAllListen ()
if ( typeof err === "number") {
return self.checkImapError ( err )
}
return self.errorProcess ( err )
}
_view.connectInformationMessage.socketIo.on ( 'smtpTest', smtpTest )
_view.connectInformationMessage.socketIo.on ( 'imapTest', imapTest )
_view.connectInformationMessage.socketIo.on ( 'imapTestFinish', imapTestFinish )
const imapServer = getImapSmtpHost( self.emailAddress())
const imapConnectData = {
email: self.account,
account: self.account,
smtpServer: imapServer.smtp,
smtpUserName: self.emailAddress(),
smtpPortNumber: imapServer.SmtpPort,
smtpSsl: imapServer.smtpSsl,
smtpIgnoreCertificate: false,
smtpUserPassword: self.password (),
imapServer: imapServer.imap,
imapPortNumber: imapServer.ImapPort,
imapSsl: imapServer.imapSsl,
imapUserName: self.emailAddress(),
imapIgnoreCertificate: false,
imapUserPassword: self.password (),
timeZoneOffset: new Date ().getTimezoneOffset (),
language: _view.tLang (),
imapTestResult: null,
clientFolder: uuid_generate(),
serverFolder: uuid_generate(),
randomPassword: uuid_generate(),
uuid: uuid_generate(),
confirmRisk: false,
clientIpAddress: null,
ciphers: null,
sendToQTGate: false
}
_view.keyPairCalss.emitLocalCommand ( 'checkImap', imapConnectData, err => {
})
}
private checkEmailAddress ( email: string ) {
this.clearError ()
if ( checkEmail ( email ).length ) {
this.EmailAddressErrorType (0)
this.emailAddressShowError ( true )
return initPopupArea ()
}
const imapServer = getImapSmtpHost ( email )
if ( !availableImapServer.test ( imapServer.imap )) {
this.EmailAddressErrorType (2)
this.emailAddressShowError ( true )
return initPopupArea ()
}
}
constructor ( private account: string, imapData: IinputData, private exit: ( IinputData: IinputData ) => void ) {
const self = this
if ( imapData ) {
this.emailAddress ( imapData.imapUserName )
this.password ( imapData.imapUserPassword )
}
this.emailAddress.subscribe ( function ( newValue ) {
return self.checkEmailAddress ( newValue )
})
this.password.subscribe ( function ( newValue ) {
return self.clearError ()
})
}
public imapAccountGoCheckClick () {
const self = this
this.checkEmailAddress ( this.emailAddress() )
if ( this.emailAddressShowError() || !this.password().length ) {
return
}
this.showForm ( false )
this.showCheckProcess ( true )
this.checkImapError ( -1 )
return this.checkImapSetup ()
}
public returnImapSetup () {
this.showForm ( true )
this.showCheckProcess ( false )
this.checkImapError ( -1 )
}
} | the_stack |
import BigNumber from 'bignumber.js'
import { ApiClient } from '../.'
/**
* Blockchain RPCs for DeFi Blockchain
*/
export class Blockchain {
private readonly client: ApiClient
constructor (client: ApiClient) {
this.client = client
}
/**
* Get various state info regarding blockchain processing.
*
* @return {Promise<BlockchainInfo>}
*/
async getBlockchainInfo (): Promise<BlockchainInfo> {
return await this.client.call('getblockchaininfo', [], 'number')
}
/**
* Get a hash of block in best-block-chain at height provided.
*
* @param {number} height
* @return {Promise<string>}
*/
async getBlockHash (height: number): Promise<string> {
return await this.client.call('getblockhash', [height], 'number')
}
/**
* Get the height of the most-work fully-validated chain.
*
* @return {Promise<number>}
*/
async getBlockCount (): Promise<number> {
return await this.client.call('getblockcount', [], 'number')
}
/**
* Get block string hex with a provided block header hash.
*
* @param {string} hash of the block
* @param {number} verbosity 0
* @return {Promise<string>} block as string that is serialized, hex-encoded data
*/
getBlock (hash: string, verbosity: 0): Promise<string>
/**
* Get block data with a provided block header hash.
*
* @param {string} hash of the block
* @param {number} verbosity 1
* @return {Promise<Block<string>>} block information with transaction as txid
*/
getBlock (hash: string, verbosity: 1): Promise<Block<string>>
/**
* Get block data with a provided block header hash.
*
* @param {string} hash of the block
* @param {number} verbosity 2
* @return {Promise<Block<Transaction>>} block information and detailed information about each transaction.
*/
getBlock (hash: string, verbosity: 2): Promise<Block<Transaction>>
async getBlock<T> (hash: string, verbosity: 0 | 1 | 2): Promise<string | Block<T>> {
return await this.client.call('getblock', [hash, verbosity], verbosity === 2
? {
tx: {
vout: {
value: 'bignumber'
}
}
}
: 'number')
}
/**
* Get block header data with particular header hash.
* Returns an Object with information for block header.
*
* @param {string} hash of the block
* @param {boolean} verbosity true
* @return {Promise<BlockHeader>}
*/
getBlockHeader (hash: string, verbosity: true): Promise<BlockHeader>
/**
* Get block header data with particular header hash.
* Returns a string that is serialized, hex-encoded data for block header.
*
* @param {string} hash of the block
* @param {boolean} verbosity false
* @return {Promise<string>}
*/
getBlockHeader (hash: string, verbosity: false): Promise<string>
async getBlockHeader (hash: string, verbosity: boolean): Promise<string | BlockHeader> {
return await this.client.call('getblockheader', [hash, verbosity], 'number')
}
/**
* Return information about all known tips in the block tree
* including the main chain as well as orphaned branches.
*
* @return {Promise<ChainTip[]>}
*/
async getChainTips (): Promise<ChainTip[]> {
return await this.client.call('getchaintips', [], 'number')
}
/**
* Get the proof-of-work difficulty as a multiple of the minimum difficulty.
*
* @return {Promise<number>}
*/
async getDifficulty (): Promise<number> {
return await this.client.call('getdifficulty', [], 'number')
}
/**
* Get details of unspent transaction output (UTXO).
*
* @param {string} txId the transaction id
* @param {number} index vout number
* @param {boolean} includeMempool default true, whether to include mempool
* @return {Promise<UTXODetails>}
*/
async getTxOut (txId: string, index: number, includeMempool = true): Promise<UTXODetails> {
return await this.client.call('gettxout', [
txId, index, includeMempool
], {
value: 'bignumber'
})
}
/**
* Get all transaction ids in memory pool as string
*
* @param {boolean} verbose false
* @return {Promise<string[]>}
*/
getRawMempool (verbose: false): Promise<string[]>
/**
* Get all transaction ids in memory pool as json object
*
* @param {boolean} verbose true
* @return {Promise<MempoolTx>}
*/
getRawMempool (verbose: true): Promise<MempoolTx>
/**
* Get all transaction ids in memory pool as string[] if verbose is false
* else as json object
*
* @param {boolean} verbose default = false, true for json object, false for array of transaction ids
* @return {Promise<string[] | MempoolTx>}
*/
async getRawMempool (verbose: boolean): Promise<string[] | MempoolTx> {
return await this.client.call('getrawmempool', [verbose], 'bignumber')
}
/**
* Get block statistics for a given window.
*
* @param {number} hashOrHeight The block hash or height of the target block.
* @param {Array<keyof BlockStats>} stats Default = all values. See BlockStats Interface.
* @return {Promise<BlockStats>}
*/
async getBlockStats (hashOrHeight: number | string, stats?: Array<keyof BlockStats>): Promise<BlockStats> {
return await this.client.call('getblockstats', [hashOrHeight, stats], 'number')
}
/**
* Get the hash of the best (tip) block in the most-work fully-validated chain.
*
* @returns {Promise<string>}
*/
async getBestBlockHash (): Promise<string> {
return await this.client.call('getbestblockhash', [], 'number')
}
/**
* Returns details on the active state of the TX memory pool.
*
* @return {Promise<MempoolInfo>}
*/
async getMempoolInfo (): Promise<MempoolInfo> {
return await this.client.call('getmempoolinfo', [], { mempoolminfee: 'bignumber', minrelaytxfee: 'bignumber' })
}
/**
* Wait for any new block
*
* @param {number} [timeout=30000] in millis
* @return Promise<WaitBlockResult> the current block on timeout or exit
*/
async waitForNewBlock (timeout: number = 30000): Promise<WaitBlockResult> {
return await this.client.call('waitfornewblock', [timeout], 'number')
}
/**
* Waits for block height equal or higher than provided and returns the height and hash of the current tip.
*
*
* @param {number} height
* @param {number} [timeout=30000] in millis
* @return Promise<WaitBlockResult> the current block on timeout or exit
*/
async waitForBlockHeight (height: number, timeout: number = 30000): Promise<WaitBlockResult> {
return await this.client.call('waitforblockheight', [height, timeout], 'number')
}
}
/**
* TODO(fuxingloh): defid prune=1 is not type supported yet
*/
export interface BlockchainInfo {
chain: 'main' | 'test' | 'regtest' | string
blocks: number
headers: number
bestblockhash: string
difficulty: number
mediantime: number
verificationprogress: number
initialblockdownload: boolean
chainwork: string
size_on_disk: number
pruned: boolean
softforks: {
[id: string]: {
type: 'buried' | 'bip9'
active: boolean
height: number
}
}
warnings: string
}
export interface Block<T> {
hash: string
confirmations: number
strippedsize: number
size: number
weight: number
height: number
masternode: string
minter: string
mintedBlocks: number
stakeModifier: string
version: number
versionHex: string
merkleroot: string
time: number
mediantime: number
bits: string
difficulty: number
chainwork: string
tx: T[]
nTx: number
previousblockhash: string
nextblockhash: string
}
export interface BlockHeader {
hash: string
confirmations: number
height: number
version: number
versionHex: string
merkleroot: string
time: number
mediantime: number
bits: string
difficulty: number
chainwork: string
nTx: number
previousblockhash: string
nextblockhash: string
}
export interface Transaction {
txid: string
hash: string
version: number
size: number
vsize: number
weight: number
locktime: number
vin: Vin[]
vout: Vout[]
hex: string
}
export interface Vin {
coinbase?: string
txid: string
vout: number
scriptSig: {
asm: string
hex: string
}
txinwitness?: string[]
sequence: string
}
export interface Vout {
value: BigNumber
n: number
scriptPubKey: ScriptPubKey
tokenId: number
}
export interface UTXODetails {
bestblock: string
confirmations: number
value: BigNumber
scriptPubKey: ScriptPubKey
coinbase: boolean
}
export interface ScriptPubKey {
asm: string
hex: string
type: string
reqSigs: number
addresses: string[]
}
export interface ChainTip {
height: number
hash: string
branchlen: number
status: string
}
export interface MempoolTx {
[key: string]: {
vsize: BigNumber
/**
* @deprecated same as vsize. Only returned if defid is started with -deprecatedrpc=size
*/
size: BigNumber
weight: BigNumber
fee: BigNumber
modifiedfee: BigNumber
time: BigNumber
height: BigNumber
descendantcount: BigNumber
descendantsize: BigNumber
descendantfees: BigNumber
ancestorcount: BigNumber
ancestorsize: BigNumber
ancestorfees: BigNumber
wtxid: string
fees: {
base: BigNumber
modified: BigNumber
ancestor: BigNumber
descendant: BigNumber
}
depends: string[]
spentby: string[]
'bip125-replaceable': boolean
}
}
export interface BlockStats {
avgfee: number
avgfeerate: number
avgtxsize: number
blockhash: string
height: number
ins: number
maxfee: number
maxfeerate: number
maxtxsize: number
medianfee: number
mediantime: number
mediantxsize: number
minfee: number
minfeerate: number
mintxsize: number
outs: number
subsidy: number
swtxs: number
time: number
totalfee: number
txs: number
swtotal_size: number
swtotal_weight: number
total_out: number
total_size: number
total_weight: number
utxo_increase: number
utxo_size_inc: number
feerate_percentiles: [number, number, number, number, number]
}
export interface MempoolInfo {
loaded: boolean
size: number
bytes: number
usage: number
maxmempool: number
mempoolminfee: BigNumber
minrelaytxfee: BigNumber
}
export interface WaitBlockResult {
hash: string
height: number
} | the_stack |
import { Route } from 'vue-router';
import { sync } from 'vuex-router-sync';
import { VuexAction, VuexModule, VuexMutation, VuexStore } from '../../utils/vuex';
import { CommunityJoinLocation } from '../../_common/analytics/analytics.service';
import { Api } from '../../_common/api/api.service';
import { Backdrop } from '../../_common/backdrop/backdrop.service';
import AppBackdrop from '../../_common/backdrop/backdrop.vue';
import { Community, joinCommunity, leaveCommunity } from '../../_common/community/community.model';
import { Connection } from '../../_common/connection/connection-service';
import { ContentFocus } from '../../_common/content-focus/content-focus.service';
import { FiresidePost } from '../../_common/fireside/post/post-model';
import { Growls } from '../../_common/growls/growls.service';
import { ModalConfirm } from '../../_common/modal/confirm/confirm-service';
import { Screen } from '../../_common/screen/screen-service';
import {
SidebarActions,
SidebarMutations,
SidebarStore,
} from '../../_common/sidebar/sidebar.store';
import {
Actions as AppActions,
AppStore,
appStore,
Mutations as AppMutations,
} from '../../_common/store/app-store';
import { ThemeActions, ThemeMutations, ThemeStore } from '../../_common/theme/theme.store';
import { Translate } from '../../_common/translate/translate.service';
import { ActivityFeedState } from '../components/activity/feed/state';
import { BroadcastModal } from '../components/broadcast-modal/broadcast-modal.service';
import { GridClient } from '../components/grid/client.service';
import { GridClientLazy } from '../components/lazy';
import { router } from '../views';
import { BannerActions, BannerMutations, BannerStore } from './banner';
import * as _ClientLibraryMod from './client-library';
import { CommunityStates } from './community-state';
import { Actions as LibraryActions, LibraryStore, Mutations as LibraryMutations } from './library';
// Re-export our sub-modules.
export { BannerModule, BannerStore } from './banner';
export type Actions = AppActions &
ThemeActions &
LibraryActions &
BannerActions &
SidebarActions &
_ClientLibraryMod.Actions & {
bootstrap: void;
logout: void;
clear: void;
loadGrid: void;
clearGrid: void;
loadNotificationState: void;
clearNotificationState: void;
markNotificationsAsRead: void;
toggleCbarMenu: void;
toggleLeftPane: void;
toggleRightPane: void;
toggleChatPane: void;
clearPanes: void;
joinCommunity: { community: Community; location?: CommunityJoinLocation };
leaveCommunity: {
community: Community;
location?: CommunityJoinLocation;
shouldConfirm: boolean;
};
};
export type Mutations = AppMutations &
ThemeMutations &
LibraryMutations &
BannerMutations &
SidebarMutations &
_ClientLibraryMod.Mutations & {
showShell: void;
hideShell: void;
showFooter: void;
hideFooter: void;
setHasContentSidebar: boolean;
setNotificationCount: { type: UnreadItemType; count: number };
incrementNotificationCount: { type: UnreadItemType; count: number };
setHasNewFriendRequests: boolean;
setHasNewUnlockedStickers: boolean;
setActiveCommunity: Community;
clearActiveCommunity: void;
viewCommunity: Community;
featuredPost: FiresidePost;
};
let bootstrapResolver: ((value?: any) => void) | null = null;
let backdrop: AppBackdrop | null = null;
export let tillStoreBootstrapped = new Promise(resolve => (bootstrapResolver = resolve));
let _wantsGrid = false;
let _gridLoadPromise: Promise<typeof GridClient> | null = null;
let _gridBootstrapResolvers: ((client: GridClient) => void)[] = [];
/**
* Returns a promise that resolves once the Grid client is available.
*/
export function tillGridBootstrapped() {
return new Promise<GridClient>(resolve => {
if (store.state.grid) {
resolve(store.state.grid);
} else {
_gridBootstrapResolvers.push(resolve);
}
});
}
const modules: any = {
app: appStore,
theme: new ThemeStore(),
library: new LibraryStore(),
banner: new BannerStore(),
sidebar: new SidebarStore(),
};
if (GJ_IS_CLIENT) {
const m: typeof _ClientLibraryMod = require('./client-library');
modules.clientLibrary = new m.ClientLibraryStore();
}
// the two types an event notification can assume, either "activity" for the post activity feed or "notifications"
type UnreadItemType = 'activity' | 'notifications';
type TogglableLeftPane = '' | 'chat' | 'context' | 'library';
@VuexModule({
store: true,
modules,
})
export class Store extends VuexStore<Store, Actions, Mutations> {
app!: AppStore;
theme!: ThemeStore;
library!: LibraryStore;
banner!: BannerStore;
sidebar!: SidebarStore;
clientLibrary!: _ClientLibraryMod.ClientLibraryStore;
/** From the vuex-router-sync. */
route!: Route;
grid: GridClient | null = null;
isBootstrapped = false;
isLibraryBootstrapped = false;
isShellBootstrapped = false;
isShellHidden = false;
isFooterHidden = false;
/** Unread items in the activity feed. */
unreadActivityCount = 0;
/** Unread items in the notification feed. */
unreadNotificationsCount = 0;
hasNewFriendRequests = false;
hasNewUnlockedStickers = false;
notificationState: ActivityFeedState | null = null;
mobileCbarShowing = false;
lastOpenLeftPane: Exclude<TogglableLeftPane, 'context'> = 'library';
overlayedLeftPane: TogglableLeftPane = '';
overlayedRightPane = '';
hasContentSidebar = false;
/** Will be set to the community they're currently viewing (if any). */
activeCommunity: null | Community = null;
communities: Community[] = [];
communityStates: CommunityStates = new CommunityStates();
get hasTopBar() {
return !this.isShellHidden;
}
get hasSidebar() {
return !this.isShellHidden;
}
get hasCbar() {
if (this.isShellHidden || this.app.isUserTimedOut) {
return false;
}
// The cbar is pretty empty without a user and active context pane,
// so we want to hide it if those conditions are met.
if (!this.app.user && !this.sidebar.activeContextPane && !Screen.isXs) {
return false;
}
return this.mobileCbarShowing || !Screen.isXs;
}
get hasFooter() {
return !this.isFooterHidden;
}
/**
* Returns the current overlaying pane if there is one.
*
* Large breakpoint defaults to 'context' on applicable routes.
* */
get visibleLeftPane(): TogglableLeftPane {
// If there's no other left-pane pane opened, Large breakpoint should
// always show the 'context' pane if there is a context component set.
if (Screen.isLg && this.sidebar.activeContextPane && !this.overlayedLeftPane) {
return 'context';
}
return this.overlayedLeftPane;
}
get visibleRightPane() {
return this.overlayedRightPane;
}
get notificationCount() {
return this.unreadActivityCount + this.unreadNotificationsCount;
}
@VuexAction
async bootstrap() {
const prevResolver = bootstrapResolver;
// Detach so that errors in it doesn't cause the not found page to show. This is considered
// a sort of "async" load.
try {
const [shellPayload, libraryPayload] = await Promise.all([
Api.sendRequest('/web/dash/shell', null, { detach: true }),
Api.sendRequest('/web/library', null, { detach: true }),
]);
this._setLibraryBootstrapped();
this._shellPayload(shellPayload);
// If we failed to finish before we unbootstrapped, then stop.
if (bootstrapResolver !== prevResolver) {
return;
}
this.commit('library/bootstrap', libraryPayload);
} catch (e) {}
this._setBootstrapped();
if (!GJ_IS_CLIENT && !GJ_IS_SSR) {
BroadcastModal.check();
}
}
@VuexAction
async logout() {
const result = await ModalConfirm.show(
Translate.$gettext('Are you seriously going to leave us?'),
Translate.$gettext('Logout?')
);
if (!result) {
return;
}
// Must send POST.
// This should clear out the user as well.
await Api.sendRequest('/web/dash/account/logout', {});
// We go to the homepage currently just in case they're in a view they shouldn't be.
router.push({ name: 'discover.home' });
Growls.success(
Translate.$gettext('You are now logged out.'),
Translate.$gettext('Goodbye!')
);
}
@VuexAction
async clear() {
tillStoreBootstrapped = new Promise(resolve => (bootstrapResolver = resolve));
this.commit('library/clear');
}
@VuexAction
async loadGrid() {
if (_wantsGrid) {
return;
}
_wantsGrid = true;
_gridLoadPromise ??= GridClientLazy();
const GridClient_ = await _gridLoadPromise;
// If they disconnected before we loaded it in.
if (!_wantsGrid) {
return;
}
this._setGrid(new GridClient_());
}
@VuexAction
async clearGrid() {
_wantsGrid = false;
if (this.grid) {
this.grid.disconnect();
}
this._setGrid(null);
}
@VuexAction
async loadNotificationState() {
const state = new ActivityFeedState({
type: 'Notification',
name: 'notification',
url: `/web/dash/activity/more/notifications`,
});
this._setNotificationState(state);
}
@VuexAction
async clearNotificationState() {
this._setNotificationState(null);
}
@VuexAction
async markNotificationsAsRead() {
if (!this.notificationState) {
return;
}
// Reset the watermark first so that it happens immediately.
this._resetNotificationWatermark();
await Api.sendRequest('/web/dash/activity/mark-all-read', {});
}
// This Action is only used for the 'Xs' breakpoint.
@VuexAction
async toggleCbarMenu() {
this._toggleCbarMenu();
if (this.visibleLeftPane) {
// Close the left-pane if the cbar is also closing.
this._toggleLeftPane();
} else {
// Open the left-pane depending on the SidebarStore information when the cbar shows.
this._toggleLeftPane(
this.sidebar.activeContextPane ? 'context' : this.lastOpenLeftPane
);
}
this.checkBackdrop();
}
/** Show the context pane if there's one available. */
@VuexAction
async showContextPane() {
if (this.visibleLeftPane !== 'context' && this.sidebar.activeContextPane) {
this.toggleLeftPane('context');
}
}
/** Passing no value will close any open left-panes. */
@VuexAction
async toggleLeftPane(type?: TogglableLeftPane) {
if (type === 'context' && !this.sidebar.activeContextPane) {
// Don't show the context pane if the SidebarStore has no context to show.
this._toggleLeftPane();
return;
}
this._toggleLeftPane(type);
this.checkBackdrop();
}
@VuexAction
async toggleRightPane(type?: string) {
this._toggleRightPane(type);
this.checkBackdrop();
}
@VuexAction
async toggleChatPane() {
this._toggleLeftPane('chat');
this.checkBackdrop();
}
@VuexAction
async clearPanes() {
this._clearPanes();
this.checkBackdrop();
}
/** Using this will add or remove backdrops as needed for overlaying panes. */
@VuexAction
async checkBackdrop() {
if (
(!!this.overlayedRightPane || !!this.overlayedLeftPane) &&
// We only want backdrops on the Lg breakpoint if the pane isn't context.
!(Screen.isLg && this.overlayedLeftPane === 'context')
) {
if (backdrop) {
return;
}
this._addBackdrop();
backdrop!.$on('clicked', () => {
this._clearPanes();
this.checkBackdrop();
});
} else if (backdrop) {
this._removeBackdrop();
}
}
@VuexMutation
hideShell() {
this.isShellHidden = true;
}
@VuexMutation
showShell() {
this.isShellHidden = false;
}
@VuexMutation
hideFooter() {
this.isFooterHidden = true;
}
@VuexMutation
showFooter() {
this.isFooterHidden = false;
}
@VuexMutation
setHasContentSidebar(isShowing: Mutations['setHasContentSidebar']) {
// We use this to scooch the footer over to make room for the sidebar content, but we only care about
// that when the sidebar isn't behaving as an overlay - which is currently only on the Lg breakpoint.
if (Screen.isLg) {
this.hasContentSidebar = isShowing;
} else {
this.hasContentSidebar = false;
}
}
@VuexMutation
incrementNotificationCount(payload: Mutations['incrementNotificationCount']) {
if (payload.type === 'activity') {
this.unreadActivityCount += payload.count;
} else {
this.unreadNotificationsCount += payload.count;
}
}
@VuexMutation
setNotificationCount(payload: Mutations['setNotificationCount']) {
if (payload.type === 'activity') {
this.unreadActivityCount = payload.count;
} else {
this.unreadNotificationsCount = payload.count;
}
}
@VuexMutation
setHasNewFriendRequests(has: Mutations['setHasNewFriendRequests']) {
this.hasNewFriendRequests = has;
}
@VuexMutation
setHasNewUnlockedStickers(has: Mutations['setHasNewUnlockedStickers']) {
this.hasNewUnlockedStickers = has;
}
@VuexMutation
private _setBootstrapped() {
this.isBootstrapped = true;
if (bootstrapResolver) {
bootstrapResolver();
}
}
@VuexMutation
private _setLibraryBootstrapped() {
this.isLibraryBootstrapped = true;
}
@VuexMutation
private _shellPayload(payload: any) {
this.isShellBootstrapped = true;
this.communities = Community.populate(payload.communities);
}
@VuexAction
async joinCommunity({ community, location }: Actions['joinCommunity']) {
if (community._removed) {
return;
}
if (!community.is_member) {
await joinCommunity(community, location);
}
this.grid?.joinCommunity(community);
this._joinCommunity(community);
}
@VuexMutation
private _joinCommunity(community: Community) {
if (this.communities.find(c => c.id === community.id)) {
return;
}
this.communities.unshift(community);
}
@VuexAction
async leaveCommunity({ community, location, shouldConfirm }: Actions['leaveCommunity']) {
if (community.is_member && !community._removed) {
if (shouldConfirm) {
const result = await ModalConfirm.show(
Translate.$gettext(`Are you sure you want to leave this community?`),
Translate.$gettext(`Leave community?`)
);
if (!result) {
return;
}
}
await leaveCommunity(community, location);
}
this.grid?.leaveCommunity(community);
this._leaveCommunity(community);
}
@VuexMutation
private _leaveCommunity(community: Community) {
const communityState = this.communityStates.getCommunityState(community);
communityState.reset();
const idx = this.communities.findIndex(c => c.id === community.id);
if (idx === -1) {
return;
}
this.communities.splice(idx, 1);
}
@VuexMutation
setActiveCommunity(community: Mutations['setActiveCommunity']) {
this.activeCommunity = community;
}
@VuexMutation
clearActiveCommunity() {
this.activeCommunity = null;
}
@VuexMutation
viewCommunity(community: Mutations['viewCommunity']) {
const communityState = this.communityStates.getCommunityState(community);
communityState.hasUnreadFeaturedPosts = false;
const idx = this.communities.findIndex(c => c.id === community.id);
if (idx === -1) {
return;
}
this.communities.splice(idx, 1);
this.communities.unshift(community);
}
@VuexMutation
featuredPost(post: Mutations['featuredPost']) {
if (this.grid) {
this.grid.recordFeaturedPost(post);
}
}
@VuexMutation
private _setGrid(grid: GridClient | null) {
if (grid !== null) {
for (const resolver of _gridBootstrapResolvers) {
resolver(grid);
}
_gridBootstrapResolvers = [];
}
this.grid = grid;
}
@VuexMutation
private _setNotificationState(state: ActivityFeedState | null) {
this.notificationState = state;
}
@VuexMutation
private _resetNotificationWatermark() {
// Mark all loaded notifications as read through the feed watermark.
// It's better than having to reload from the backend.
if (this.notificationState) {
this.notificationState.notificationWatermark = Date.now();
}
}
@VuexMutation
private _toggleCbarMenu() {
this.mobileCbarShowing = !this.mobileCbarShowing;
}
@VuexMutation
private _toggleLeftPane(type: TogglableLeftPane = '') {
if (!this.hasSidebar) {
this.overlayedLeftPane = '';
return;
}
if (this.overlayedLeftPane === type) {
this.overlayedLeftPane = '';
} else {
this.overlayedLeftPane = type;
}
if (type && type !== 'context') {
this.lastOpenLeftPane = type;
}
this.mobileCbarShowing = !!this.overlayedLeftPane;
this.overlayedRightPane = '';
}
@VuexMutation
private _toggleRightPane(type = '') {
if (this.overlayedRightPane === type) {
this.overlayedRightPane = '';
} else {
this.overlayedRightPane = type;
}
this.overlayedLeftPane = '';
}
@VuexMutation
private _clearPanes() {
this.overlayedRightPane = '';
this.overlayedLeftPane = '';
this.mobileCbarShowing = false;
}
@VuexMutation
private _addBackdrop() {
if (backdrop) {
return;
}
backdrop = Backdrop.push({ context: document.body });
}
@VuexMutation
private _removeBackdrop() {
if (!backdrop) {
return;
}
Backdrop.remove(backdrop);
backdrop = null;
}
}
export const store = new Store();
// Sync the routes into the store.
sync(store, router, { moduleName: 'route' });
// Sync with the ContentFocus service.
ContentFocus.registerWatcher(
// We only care if the panes are overlaying, not if they're visible in the
// page without overlaying. Example is that context panes show in-page on
// large displays.
() => !store.state.overlayedLeftPane && !store.state.overlayedRightPane
);
// If we were offline, but we're online now, make sure our library is bootstrapped. Remember we
// always have an app user even if we were offline.
if (GJ_IS_CLIENT) {
store.watch(
() => Connection.isOffline,
(isOffline, prev) => {
if (!isOffline && prev === true) {
store.dispatch('bootstrap');
}
}
);
} | the_stack |
import type {Mutable, Class} from "@swim/util";
import {Affinity, Animator} from "@swim/component";
import {
AnyLength,
Length,
AnyAngle,
Angle,
AnyR2Point,
R2Point,
R2Segment,
R2Box,
R2Circle,
} from "@swim/math";
import {AnyGeoPoint, GeoPoint, GeoBox} from "@swim/geo";
import {AnyColor, Color} from "@swim/style";
import {ThemeAnimator} from "@swim/theme";
import {ViewContextType, View} from "@swim/view";
import {
GraphicsView,
FillViewInit,
FillView,
StrokeViewInit,
StrokeView,
PaintingContext,
PaintingRenderer,
CanvasContext,
CanvasRenderer,
} from "@swim/graphics";
import {Arc} from "@swim/graphics";
import {GeoViewInit, GeoView} from "../geo/GeoView";
import {GeoRippleOptions, GeoRippleView} from "../effect/GeoRippleView";
import type {GeoArcViewObserver} from "./GeoArcViewObserver";
/** @public */
export type AnyGeoArcView = GeoArcView | GeoArcViewInit;
/** @public */
export interface GeoArcViewInit extends GeoViewInit, FillViewInit, StrokeViewInit {
geoCenter?: AnyGeoPoint;
viewCenter?: R2Point;
innerRadius?: AnyLength;
outerRadius?: AnyLength;
startAngle?: AnyAngle;
sweepAngle?: AnyAngle;
padAngle?: AnyAngle;
padRadius?: AnyLength | null;
cornerRadius?: AnyLength;
}
/** @public */
export class GeoArcView extends GeoView implements FillView, StrokeView {
constructor() {
super();
Object.defineProperty(this, "viewBounds", {
value: R2Box.undefined(),
writable: true,
enumerable: true,
configurable: true,
});
}
override readonly observerType?: Class<GeoArcViewObserver>;
@Animator<GeoArcView, GeoPoint | null, AnyGeoPoint | null>({
type: GeoPoint,
value: null,
didSetState(newGeoCenter: GeoPoint | null, oldGeoCenter: GeoPoint | null): void {
this.owner.projectGeoCenter(newGeoCenter);
},
willSetValue(newGeoCenter: GeoPoint | null, oldGeoCenter: GeoPoint | null): void {
this.owner.callObservers("viewWillSetGeoCenter", newGeoCenter, oldGeoCenter, this.owner);
},
didSetValue(newGeoCenter: GeoPoint | null, oldGeoCenter: GeoPoint | null): void {
this.owner.setGeoBounds(newGeoCenter !== null ? newGeoCenter.bounds : GeoBox.undefined());
if (this.mounted) {
this.owner.projectArc(this.owner.viewContext);
}
this.owner.callObservers("viewDidSetGeoCenter", newGeoCenter, oldGeoCenter, this.owner);
},
})
readonly geoCenter!: Animator<this, GeoPoint | null, AnyGeoPoint | null>;
@Animator<GeoArcView, R2Point | null, AnyR2Point | null>({
type: R2Point,
value: R2Point.undefined(),
updateFlags: View.NeedsRender,
})
readonly viewCenter!: Animator<this, R2Point | null, AnyR2Point | null>;
@ThemeAnimator({type: Length, value: Length.zero(), updateFlags: View.NeedsRender})
readonly innerRadius!: ThemeAnimator<this, Length, AnyLength>;
@ThemeAnimator({type: Length, value: Length.zero(), updateFlags: View.NeedsRender})
readonly outerRadius!: ThemeAnimator<this, Length, AnyLength>;
@ThemeAnimator({type: Angle, value: Angle.zero(), updateFlags: View.NeedsRender})
readonly startAngle!: ThemeAnimator<this, Angle, AnyAngle>;
@ThemeAnimator({type: Angle, value: Angle.zero(), updateFlags: View.NeedsRender})
readonly sweepAngle!: ThemeAnimator<this, Angle, AnyAngle>;
@ThemeAnimator({type: Angle, value: Angle.zero(), updateFlags: View.NeedsRender})
readonly padAngle!: ThemeAnimator<this, Angle, AnyAngle>;
@ThemeAnimator({type: Length, value: null, updateFlags: View.NeedsRender})
readonly padRadius!: ThemeAnimator<this, Length | null, AnyLength | null>;
@ThemeAnimator({type: Length, value: Length.zero(), updateFlags: View.NeedsRender})
readonly cornerRadius!: ThemeAnimator<this, Length, AnyLength>;
@ThemeAnimator({type: Color, value: null, inherits: true, updateFlags: View.NeedsRender})
readonly fill!: ThemeAnimator<this, Color | null, AnyColor | null>;
@ThemeAnimator({type: Color, value: null, inherits: true, updateFlags: View.NeedsRender})
readonly stroke!: ThemeAnimator<this, Color | null, AnyColor | null>;
@ThemeAnimator({type: Length, value: null, inherits: true, updateFlags: View.NeedsRender})
readonly strokeWidth!: ThemeAnimator<this, Length | null, AnyLength | null>;
get value(): Arc | null {
const viewCenter = this.viewCenter.value;
if (viewCenter !== null && viewCenter.isDefined()) {
return new Arc(viewCenter, this.innerRadius.value, this.outerRadius.value,
this.startAngle.value, this.sweepAngle.value, this.padAngle.value,
this.padRadius.value, this.cornerRadius.value);
} else {
return null;
}
}
get state(): Arc | null {
const viewCenter = this.viewCenter.state;
if (viewCenter !== null && viewCenter.isDefined()) {
return new Arc(viewCenter, this.innerRadius.state, this.outerRadius.state,
this.startAngle.state, this.sweepAngle.state, this.padAngle.state,
this.padRadius.state, this.cornerRadius.state);
} else {
return null;
}
}
protected override onProject(viewContext: ViewContextType<this>): void {
super.onProject(viewContext);
this.projectArc(viewContext);
}
protected projectGeoCenter(geoCenter: GeoPoint | null): void {
if (this.mounted) {
const viewContext = this.viewContext as ViewContextType<this>;
const viewCenter = geoCenter !== null && geoCenter.isDefined()
? viewContext.geoViewport.project(geoCenter)
: null;
this.viewCenter.setInterpolatedValue(this.viewCenter.value, viewCenter);
this.projectArc(viewContext);
}
}
protected projectArc(viewContext: ViewContextType<this>): void {
if (Affinity.Intrinsic >= (this.viewCenter.flags & Affinity.Mask)) { // this.viewCenter.hasAffinity(Affinity.Intrinsic)
const geoCenter = this.geoCenter.value;
const viewCenter = geoCenter !== null && geoCenter.isDefined()
? viewContext.geoViewport.project(geoCenter)
: null;
(this.viewCenter as Mutable<typeof this.viewCenter>).value = viewCenter; // this.viewCenter.setValue(viewCenter, Affinity.Intrinsic)
}
const viewFrame = viewContext.viewFrame;
const size = Math.min(viewFrame.width, viewFrame.height);
const r = this.outerRadius.getValue().pxValue(size);
const p0 = this.viewCenter.value;
const p1 = this.viewCenter.state;
if (p0 !== null && p1 !== null && (
viewFrame.intersectsCircle(new R2Circle(p0.x, p0.y, r)) ||
viewFrame.intersectsSegment(new R2Segment(p0.x, p0.y, p1.x, p1.y)))) {
this.setCulled(false);
} else {
this.setCulled(true);
}
}
protected override onRender(viewContext: ViewContextType<this>): void {
super.onRender(viewContext);
const renderer = viewContext.renderer;
if (renderer instanceof PaintingRenderer && !this.hidden && !this.culled) {
this.renderArc(renderer.context, viewContext.viewFrame);
}
}
protected renderArc(context: PaintingContext, frame: R2Box): void {
const arc = this.value;
if (arc !== null && frame.isDefined()) {
// save
const contextFillStyle = context.fillStyle;
const contextLineWidth = context.lineWidth;
const contextStrokeStyle = context.strokeStyle;
context.beginPath();
arc.draw(context, frame);
const fill = this.fill.value;
if (fill !== null) {
context.fillStyle = fill.toString();
context.fill();
}
const stroke = this.stroke.value;
if (stroke !== null) {
const strokeWidth = this.strokeWidth.value;
if (strokeWidth !== null) {
const size = Math.min(frame.width, frame.height);
context.lineWidth = strokeWidth.pxValue(size);
}
context.strokeStyle = stroke.toString();
context.stroke();
}
// restore
context.fillStyle = contextFillStyle;
context.lineWidth = contextLineWidth;
context.strokeStyle = contextStrokeStyle;
}
}
protected override renderGeoBounds(viewContext: ViewContextType<this>, outlineColor: Color, outlineWidth: number): void {
// nop
}
protected override updateGeoBounds(): void {
// nop
}
override readonly viewBounds!: R2Box;
override deriveViewBounds(): R2Box {
const viewCenter = this.viewCenter.value;
if (viewCenter !== null && viewCenter.isDefined()) {
const viewFrame = this.viewContext.viewFrame;
const size = Math.min(viewFrame.width, viewFrame.height);
const radius = this.outerRadius.getValue().pxValue(size);
return new R2Box(viewCenter.x - radius, viewCenter.y - radius,
viewCenter.x + radius, viewCenter.y + radius);
} else {
return R2Box.undefined();
}
}
override get popoverFrame(): R2Box {
const viewCenter = this.viewCenter.value;
if (viewCenter !== null && viewCenter.isDefined()) {
const viewFrame = this.viewContext.viewFrame;
const size = Math.min(viewFrame.width, viewFrame.height);
const inversePageTransform = this.pageTransform.inverse();
const px = inversePageTransform.transformX(viewCenter.x, viewCenter.y);
const py = inversePageTransform.transformY(viewCenter.x, viewCenter.y);
const r = (this.innerRadius.getValue().pxValue(size) + this.outerRadius.getValue().pxValue(size)) / 2;
const a = this.startAngle.getValue().radValue() + this.sweepAngle.getValue().radValue() / 2;
const x = px + r * Math.cos(a);
const y = py + r * Math.sin(a);
return new R2Box(x, y, x, y);
} else {
return this.pageBounds;
}
}
protected override hitTest(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null {
const renderer = viewContext.renderer;
if (renderer instanceof CanvasRenderer) {
const p = renderer.transform.transform(x, y);
return this.hitTestArc(p.x, p.y, renderer.context, viewContext.viewFrame);
}
return null;
}
protected hitTestArc(x: number, y: number, context: CanvasContext, frame: R2Box): GraphicsView | null {
const arc = this.value;
if (arc !== null) {
context.beginPath();
arc.draw(context, frame);
if (this.fill.value !== null && context.isPointInPath(x, y)) {
return this;
} else if (this.stroke.value !== void 0) {
const strokeWidth = this.strokeWidth.value;
if (strokeWidth !== null) {
// save
const contextLineWidth = context.lineWidth;
const size = Math.min(frame.width, frame.height);
context.lineWidth = strokeWidth.pxValue(size);
const pointInStroke = context.isPointInStroke(x, y);
// restore
context.lineWidth = contextLineWidth;
if (pointInStroke) {
return this;
}
}
}
}
return null;
}
ripple(options?: GeoRippleOptions): GeoRippleView | null {
return GeoRippleView.ripple(this, options);
}
override init(init: GeoArcViewInit): void {
super.init(init);
if (init.geoCenter !== void 0) {
this.geoCenter(init.geoCenter);
}
if (init.viewCenter !== void 0) {
this.viewCenter(init.viewCenter);
}
if (init.innerRadius !== void 0) {
this.innerRadius(init.innerRadius);
}
if (init.outerRadius !== void 0) {
this.outerRadius(init.outerRadius);
}
if (init.startAngle !== void 0) {
this.startAngle(init.startAngle);
}
if (init.sweepAngle !== void 0) {
this.sweepAngle(init.sweepAngle);
}
if (init.padAngle !== void 0) {
this.padAngle(init.padAngle);
}
if (init.padRadius !== void 0) {
this.padRadius(init.padRadius);
}
if (init.cornerRadius !== void 0) {
this.cornerRadius(init.cornerRadius);
}
if (init.fill !== void 0) {
this.fill(init.fill);
}
if (init.stroke !== void 0) {
this.stroke(init.stroke);
}
if (init.strokeWidth !== void 0) {
this.strokeWidth(init.strokeWidth);
}
}
} | the_stack |
import { Injectable, Inject } from '@angular/core'
import { Response } from '@angular/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import {Jsonp} from '@angular/http'
import { Observable } from "rxjs/Rx";
import './rxjs-operators';
import { ConfigService } from './config.service';
import { AuthService } from './auth.service';
import { UtilsService } from './utils.service';
@Injectable()
export class VmdirService {
getUrl:string
listing:any;
postServer:string
postPort
constructor(private utilsService:UtilsService, private configService:ConfigService, private authService: AuthService, private httpClient:HttpClient) {}
getDirListing(rootDn:string): Observable<string[]> {
this.postServer = this.authService.getPostServer();
this.postPort = this.authService.getPostPort();
let headers = this.authService.getAuthHeader();
this.getUrl = 'https://' + this.postServer + ':' + this.postPort + '/v1/post/ldap';
if(rootDn == null) {
rootDn = this.authService.getRootDnQuery();
}
console.log("root DN:" + rootDn);
this.getUrl += '?scope=one&dn='+rootDn+'&attrs=dn';
console.log(this.getUrl);
return this.httpClient.get(this.getUrl, {headers})
.share()
.map((res: Response) => res)
.do(listing => this.listing = listing)
.catch(err => this.utilsService.handleError(err))
}
getAttributes(rootDn:string): Observable<string[]> {
let headers = this.authService.getAuthHeader();
this.getUrl = 'https://' + this.postServer + ':' + this.postPort + '/v1/post/ldap';
if(rootDn == null) {
rootDn = this.authService.getRootDnQuery();
}
console.log("root DN:" + rootDn);
this.getUrl += '?scope=base&dn='+rootDn+'&attrs='+encodeURIComponent('*,+');
return this.httpClient.get(this.getUrl, {headers})
.share()
.map((res: Response) => res)
.do(listing => this.listing = listing)
.catch(err => this.utilsService.handleError(err))
}
getACLString(rootDn:string): Observable<string[]> {
let headers = this.authService.getAuthHeader();
this.getUrl = 'https://' + this.postServer + ':' + this.postPort + '/v1/post/ldap';
let url = this.getUrl + '?scope=base&dn=' + rootDn + '&attrs=vmwaclstring';
console.log(url);
return this.httpClient.get(url, {headers})
.share()
.map((res: Response) => res)
.catch(err => this.utilsService.handleError(err))
}
getJsonObjEntry(operation:string,attrType:string, attrValue:any):any{
let jsonObjEntry:any={};
jsonObjEntry.operation = operation;
jsonObjEntry.attribute = {};
jsonObjEntry.attribute.type = attrType;
jsonObjEntry.attribute.value = [attrValue];
return jsonObjEntry;
}
constructJsonBody(initialValMap:Map<string,any>, attrArr:string[], attrMap:Map<string,any>, schemaMap:Map<string,any>): string {
let jsonOut:string;
let jsonArrObj:any[] = [];
for(let attrEntry of attrArr) {
let attrType:string = attrEntry; //has the key
let updatedVal:any = attrMap[attrType];
let initVal = initialValMap[attrType];
if(initialValMap[attrType] && schemaMap[attrType]['isSingleValued'][0] == 'FALSE'){ //handle list attribute update
//create a map of Existing and new values
let newMap = new Map<string, boolean>();
for (var p = 0; p < updatedVal.value.length; p ++){
newMap[updatedVal.value[p]] = false;
}
for(var i = 0;i < initVal.length; i ++){
if(undefined == newMap[initVal[i]]) {// current value missing in new list, so delete it
jsonArrObj.push(this.getJsonObjEntry('delete', attrType, initVal[i]));
}else{
newMap[initVal[i]] = true; // new list[i] = old list[i]
}
}
for (var i = 0; i < updatedVal.value.length; i ++){
if(!newMap[updatedVal.value[i]]){ // If new list value, add!
jsonArrObj.push(this.getJsonObjEntry('add', attrType, updatedVal.value[i]));
}
}
}
else if(!initialValMap[attrType] && schemaMap[attrType]['isSingleValued'][0] == 'FALSE'){ // handle list attribute addition
for(var k = 0;k < updatedVal.value.length; k ++){
jsonArrObj.push(this.getJsonObjEntry('add', attrType, updatedVal.value[k]));
}
}
else{ //handle single valued attr update(add/replace)
let operation:string;
if(!initVal || !initVal.length){
operation = 'add';
}else{
operation = 'replace';
}
jsonArrObj.push(this.getJsonObjEntry(operation, attrType, updatedVal.value));
}
}
return JSON.stringify(jsonArrObj);
}
updateAttributes(rootDn:string, originalValMap:Map<string,any>, attribsArr:string[], modifiedAttributesMap:Map<string,any>, schemaMap:Map<string,any>): Observable<string[]> {
let headers = this.authService.getAuthHeader();
let body = this.constructJsonBody(originalValMap, attribsArr, modifiedAttributesMap, schemaMap);
this.getUrl = 'https://' + this.postServer + ':' + this.postPort + '/v1/post/ldap';
let updateUrl = this.getUrl + '?dn='+rootDn;
console.log(updateUrl);
return this.httpClient.patch(updateUrl, body, {headers})
.share()
.map((res: Response) => res)
.catch(err => this.utilsService.handleError(err))
}
constructSDJsonBody(aclString:string):string{
let jsonOut = "[{\
\"operation\": \"" + "replace" +"\",\
\"attribute\": {\
\"type\":\"" + 'vmwaclstring' + "\",\
\"value\": [\"" + aclString +"\"]\
}\
}]"
console.log(JSON.parse(jsonOut));
return jsonOut;
}
createAttrObject(attr:string, value:string):any{
let obj:any = {};
obj.type=attr;
obj.value=value.split(',');
return obj;
}
createAttrObjArray(attrMap:any, attrsArr:string[], opAttrMap:any, jsonObjAttrs:any[]){
for(let i = 0;i < attrsArr.length; i ++){
if(attrMap[attrsArr[i]].length){
if(opAttrMap[attrsArr[i]] != true){
jsonObjAttrs.push(this.createAttrObject(attrsArr[i], attrMap[attrsArr[i]]));
}
}
}
}
constructObjectAddJsonBody(mustAttrMap:any, mayAttrMap:any, opAttrMap:any):any[]{
let jsonObjAttrs:any[] = [];
let mustAttrsArr:string[] = Object.keys(mustAttrMap);
let mayAttrsArr:string[] = Object.keys(mayAttrMap);
this.createAttrObjArray(mustAttrMap, mustAttrsArr, opAttrMap, jsonObjAttrs);
this.createAttrObjArray(mayAttrMap, mayAttrsArr, opAttrMap, jsonObjAttrs);
return jsonObjAttrs;
}
addNewObject(rootDn:string, mustAttrMap:any, mayAttrMap:any, opAttrMap:any): Observable<string[]> {
let headers = this.authService.getAuthHeader();
if(mustAttrMap['cn'] && mustAttrMap['cn'].length){
mayAttrMap['cn'] = '';
}
let jsonObj:any = {};
jsonObj.dn = rootDn;
jsonObj.attributes = this.constructObjectAddJsonBody(mustAttrMap, mayAttrMap, opAttrMap);
let body = JSON.stringify(jsonObj);
let addUrl = 'https://' + this.postServer + ':' + this.postPort + '/v1/post/ldap';
console.log(addUrl);
return this.httpClient.put(addUrl, body, {headers})
.share()
.map((res: Response) => res)
.catch(err => this.utilsService.handleError(err))
}
updateAclString(rootDn:string, aclStrVal:string){
let headers = this.authService.getAuthHeader();
let body = this.constructSDJsonBody(aclStrVal);
let url = 'https://' + this.postServer + ':' + this.postPort + '/v1/post/ldap';
url += '?dn=' + encodeURIComponent(rootDn);
console.log(url);
return this.httpClient.patch(url, body, {headers})
.share()
.map((res: Response) => res)
.catch(err => this.utilsService.handleError(err))
}
delete(rootDn:string) {
let headers = this.authService.getAuthHeader();
this.getUrl = 'https://' + this.postServer + ':' + this.postPort + '/v1/post/ldap'
let deleteUrl = this.getUrl + '?dn='+rootDn;
console.log(deleteUrl);
return this.httpClient.delete(deleteUrl, {headers})
.share()
.map((res: Response) => res)
.catch(err => this.utilsService.handleError(err))
}
getObjectBySID(objectSid:string): Observable<string[]> {
let headers = this.authService.getAuthHeader();
this.getUrl = 'https://' + this.postServer + ':' + this.postPort + '/v1/post/ldap';
let url = this.getUrl + '?scope=sub&dn=' + this.authService.getRootDnQuery() + '&filter=' + encodeURIComponent('objectsid='+objectSid);
console.log(url);
return this.httpClient.get(url, {headers})
.share()
.map((res: Response) => res)
.catch(err => this.utilsService.handleError(err))
}
getAllStrObjectClasses():Observable<any> {
let headers = this.authService.getAuthHeader();
this.getUrl = 'https://' + this.postServer + ':' + this.postPort + '/v1/post/ldap';
let url = this.getUrl + '?scope=one&dn=' + encodeURIComponent('cn=schemacontext') + '&filter=' + encodeURIComponent('objectclass=classschema') + '&attrs='+encodeURIComponent('subClassOf,cn,systemMustContain,systemMayContain,auxiliaryClass,mayContain,mustContain,objectClassCategory');
console.log(url);
return this.httpClient.get(url, {headers})
.share()
.map((res: Response) => res)
.catch(err => this.utilsService.handleError(err))
}
getAuxObjectClass(objectClass:string):Observable<string[]> {
let headers = this.authService.getAuthHeader();
this.getUrl = 'https://' + this.postServer + ':' + this.postPort + '/v1/post/ldap';
let url = this.getUrl + '?scope=base&dn=' + encodeURIComponent('cn='+objectClass+',cn=schemacontext') + '&attrs=auxiliaryClass';
console.log(url);
return this.httpClient.get(url, {headers})
.share()
.map((res: Response) => res)
.catch(err => this.utilsService.handleError(err))
}
getObjectByGUID(objectGuid:string): Observable<string[]> {
let headers = this.authService.getAuthHeader();
this.getUrl = 'https://' + this.postServer + ':' + this.postPort + '/v1/post/ldap';
let url = this.getUrl + '?scope=sub&dn=' + this.authService.getRootDnQuery() + '&filter=' + encodeURIComponent('objectguid='+objectGuid);
console.log(url);
return this.httpClient.get(url, {headers})
.share()
.map((res: Response) => res)
.catch(err => this.utilsService.handleError(err))
}
} | the_stack |
import { Filter } from './filters/Filter';
import { IMediaContext } from './interfaces/IMediaContext';
import { IMediaInstance } from './interfaces/IMediaInstance';
import { SoundLoader } from './SoundLoader';
import { CompleteCallback, Options, PlayOptions, Sound } from './Sound';
import { HTMLAudioContext } from './htmlaudio/HTMLAudioContext';
import { WebAudioContext } from './webaudio/WebAudioContext';
type SoundSourceMap = {[id: string]: Options | string | ArrayBuffer | HTMLAudioElement};
type SoundMap = {[id: string]: Sound};
/**
* Manages the playback of sounds. This is the main class for PixiJS Sound. If you're
* using the browser-based bundled this is `PIXI.sound`. Otherwise, you can do this:
* @example
* import { sound } from '@pixi/sound';
*
* // sound is an instance of SoundLibrary
* sound.add('my-sound', 'path/to/file.mp3');
* sound.play('my-sound');
* @class
*/
class SoundLibrary
{
/**
* For legacy approach for Audio. Instead of using WebAudio API
* for playback of sounds, it will use HTML5 `<audio>` element.
*/
private _useLegacy: boolean;
/** The global context to use. */
private _context: IMediaContext;
/** The WebAudio specific context */
private _webAudioContext: WebAudioContext;
/** The HTML Audio (legacy) context. */
private _htmlAudioContext: HTMLAudioContext;
/** The map of all sounds by alias. */
private _sounds: SoundMap;
constructor()
{
this.init();
}
/**
* Re-initialize the sound library, this will
* recreate the AudioContext. If there's a hardware-failure
* call `close` and then `init`.
* @return Sound instance
*/
public init(): this
{
if (this.supported)
{
this._webAudioContext = new WebAudioContext();
}
this._htmlAudioContext = new HTMLAudioContext();
this._sounds = {};
this.useLegacy = !this.supported;
return this;
}
/**
* The global context to use.
* @type {IMediaContext}
* @readonly
*/
public get context(): IMediaContext
{
return this._context;
}
/**
* Apply filters to all sounds. Can be useful
* for setting global planning or global effects.
* **Only supported with WebAudio.**
* @example
* import { sound, filters } from '@pixi/sound';
* // Adds a filter to pan all output left
* sound.filtersAll = [
* new filters.StereoFilter(-1)
* ];
* @type {filters.Filter[]}
*/
public get filtersAll(): Filter[]
{
if (!this.useLegacy)
{
return this._context.filters;
}
return [];
}
public set filtersAll(filtersAll: Filter[])
{
if (!this.useLegacy)
{
this._context.filters = filtersAll;
}
}
/**
* `true` if WebAudio is supported on the current browser.
* @readonly
* @type {boolean}
*/
public get supported(): boolean
{
return WebAudioContext.AudioContext !== null;
}
/**
* Register an existing sound with the library cache.
* @method add
* @instance
* @param {string} alias - The sound alias reference.
* @param {Sound} sound - Sound reference to use.
* @return {Sound} Instance of the Sound object.
*/
/**
* Adds a new sound by alias.
* @param alias - The sound alias reference.
* @param {ArrayBuffer|String|Options|HTMLAudioElement} options - Either the path or url to the source file.
* or the object of options to use.
* @return Instance of the Sound object.
*/
public add(alias: string, options: Options | string | ArrayBuffer | HTMLAudioElement | Sound): Sound;
/**
* Adds multiple sounds at once.
* @param map - Map of sounds to add, the key is the alias, the value is the
* `string`, `ArrayBuffer`, `HTMLAudioElement` or the list of options
* (see {@link Options} for full options).
* @param globalOptions - The default options for all sounds.
* if a property is defined, it will use the local property instead.
* @return Instance to the Sound object.
*/
public add(map: SoundSourceMap, globalOptions?: Options): SoundMap;
/**
* @ignore
*/
public add(source: string | SoundSourceMap,
sourceOptions?: Options | string | ArrayBuffer | HTMLAudioElement | Sound): any
{
if (typeof source === 'object')
{
const results: SoundMap = {};
for (const alias in source)
{
const options: Options = this._getOptions(
source[alias],
sourceOptions as Options,
);
results[alias] = this.add(alias, options);
}
return results;
}
// eslint-disable-next-line no-console
console.assert(!this._sounds[source], `Sound with alias ${source} already exists.`);
if (sourceOptions instanceof Sound)
{
this._sounds[source] = sourceOptions;
return sourceOptions;
}
const options: Options = this._getOptions(sourceOptions);
const sound: Sound = Sound.from(options);
this._sounds[source] = sound;
return sound;
}
/**
* Internal methods for getting the options object
* @private
* @param source - The source options
* @param overrides - Override default options
* @return The construction options
*/
private _getOptions(source: string | ArrayBuffer | HTMLAudioElement | Options, overrides?: Options): Options
{
let options: Options;
if (typeof source === 'string')
{
options = { url: source };
}
else if (source instanceof ArrayBuffer || source instanceof HTMLAudioElement)
{
options = { source };
}
else
{
options = source as Options;
}
options = { ...options, ...(overrides || {}) };
return options;
}
/**
* Do not use WebAudio, force the use of legacy. This **must** be called before loading any files.
* @type {boolean}
*/
public get useLegacy(): boolean
{
return this._useLegacy;
}
public set useLegacy(legacy: boolean)
{
SoundLoader.setLegacy(legacy);
this._useLegacy = legacy;
// Set the context to use
this._context = (!legacy && this.supported)
? this._webAudioContext
: this._htmlAudioContext;
}
/**
* Removes a sound by alias.
* @param alias - The sound alias reference.
* @return Instance for chaining.
*/
public remove(alias: string): this
{
this.exists(alias, true);
this._sounds[alias].destroy();
delete this._sounds[alias];
return this;
}
/**
* Set the global volume for all sounds. To set per-sound volume see {@link SoundLibrary#volume}.
* @type {number}
*/
public get volumeAll(): number
{
return this._context.volume;
}
public set volumeAll(volume: number)
{
this._context.volume = volume;
this._context.refresh();
}
/**
* Set the global speed for all sounds. To set per-sound speed see {@link SoundLibrary#speed}.
* @type {number}
*/
public get speedAll(): number
{
return this._context.speed;
}
public set speedAll(speed: number)
{
this._context.speed = speed;
this._context.refresh();
}
/**
* Toggle paused property for all sounds.
* @return `true` if all sounds are paused.
*/
public togglePauseAll(): boolean
{
return this._context.togglePause();
}
/**
* Pauses any playing sounds.
* @return Instance for chaining.
*/
public pauseAll(): this
{
this._context.paused = true;
this._context.refreshPaused();
return this;
}
/**
* Resumes any sounds.
* @return Instance for chaining.
*/
public resumeAll(): this
{
this._context.paused = false;
this._context.refreshPaused();
return this;
}
/**
* Toggle muted property for all sounds.
* @return `true` if all sounds are muted.
*/
public toggleMuteAll(): boolean
{
return this._context.toggleMute();
}
/**
* Mutes all playing sounds.
* @return Instance for chaining.
*/
public muteAll(): this
{
this._context.muted = true;
this._context.refresh();
return this;
}
/**
* Unmutes all playing sounds.
* @return Instance for chaining.
*/
public unmuteAll(): this
{
this._context.muted = false;
this._context.refresh();
return this;
}
/**
* Stops and removes all sounds. They cannot be used after this.
* @return Instance for chaining.
*/
public removeAll(): this
{
for (const alias in this._sounds)
{
this._sounds[alias].destroy();
delete this._sounds[alias];
}
return this;
}
/**
* Stops all sounds.
* @return Instance for chaining.
*/
public stopAll(): this
{
for (const alias in this._sounds)
{
this._sounds[alias].stop();
}
return this;
}
/**
* Checks if a sound by alias exists.
* @param alias - Check for alias.
* @return true if the sound exists.
*/
public exists(alias: string, assert = false): boolean
{
const exists = !!this._sounds[alias];
if (assert)
{
// eslint-disable-next-line no-console
console.assert(exists, `No sound matching alias '${alias}'.`);
}
return exists;
}
/**
* Find a sound by alias.
* @param alias - The sound alias reference.
* @return Sound object.
*/
public find(alias: string): Sound
{
this.exists(alias, true);
return this._sounds[alias];
}
/**
* Plays a sound.
* @method play
* @instance
* @param {string} alias - The sound alias reference.
* @param {string} sprite - The alias of the sprite to play.
* @return {IMediaInstance|null} The sound instance, this cannot be reused
* after it is done playing. Returns `null` if the sound has not yet loaded.
*/
/**
* Plays a sound.
* @param alias - The sound alias reference.
* @param {PlayOptions|Function} options - The options or callback when done.
* @return The sound instance,
* this cannot be reused after it is done playing. Returns a Promise if the sound
* has not yet loaded.
*/
public play(
alias: string,
options?: PlayOptions | CompleteCallback | string): IMediaInstance | Promise<IMediaInstance>
{
return this.find(alias).play(options);
}
/**
* Stops a sound.
* @param alias - The sound alias reference.
* @return Sound object.
*/
public stop(alias: string): Sound
{
return this.find(alias).stop();
}
/**
* Pauses a sound.
* @param alias - The sound alias reference.
* @return Sound object.
*/
public pause(alias: string): Sound
{
return this.find(alias).pause();
}
/**
* Resumes a sound.
* @param alias - The sound alias reference.
* @return Instance for chaining.
*/
public resume(alias: string): Sound
{
return this.find(alias).resume();
}
/**
* Get or set the volume for a sound.
* @param alias - The sound alias reference.
* @param volume - Optional current volume to set.
* @return The current volume.
*/
public volume(alias: string, volume?: number): number
{
const sound = this.find(alias);
if (volume !== undefined)
{
sound.volume = volume;
}
return sound.volume;
}
/**
* Get or set the speed for a sound.
* @param alias - The sound alias reference.
* @param speed - Optional current speed to set.
* @return The current speed.
*/
public speed(alias: string, speed?: number): number
{
const sound = this.find(alias);
if (speed !== undefined)
{
sound.speed = speed;
}
return sound.speed;
}
/**
* Get the length of a sound in seconds.
* @param alias - The sound alias reference.
* @return The current duration in seconds.
*/
public duration(alias: string): number
{
return this.find(alias).duration;
}
/**
* Closes the sound library. This will release/destroy
* the AudioContext(s). Can be used safely if you want to
* initialize the sound library later. Use `init` method.
*/
public close(): this
{
this.removeAll();
this._sounds = null;
if (this._webAudioContext)
{
this._webAudioContext.destroy();
this._webAudioContext = null;
}
if (this._htmlAudioContext)
{
this._htmlAudioContext.destroy();
this._htmlAudioContext = null;
}
this._context = null;
return this;
}
}
export { SoundLibrary };
export type { SoundSourceMap, SoundMap }; | the_stack |
import fs from 'fs';
import * as pathModule from 'path';
import {
isString,
uniq,
parseError,
castArray,
get,
has,
joinList,
} from '@terascope/utils';
import {
OperationAPIConstructor,
FetcherConstructor,
SlicerConstructor,
ProcessorConstructor,
ObserverConstructor,
SchemaConstructor,
ProcessorModule,
APIModule,
ReaderModule,
} from '../operations';
import { readerShim, processorShim } from '../operations/shims';
import {
ASSET_KEYWORD,
LoaderOptions,
ValidLoaderOptions,
AssetBundleType,
OperationLocationType,
OpTypeToRepositoryKey,
OperationResults,
FindOperationResults,
OperationTypeName
} from './interfaces';
export class OperationLoader {
private readonly options: ValidLoaderOptions;
private readonly availableExtensions: string[];
private readonly invalidPaths: string[];
allowedFile: (name: string) => boolean;
constructor(options: LoaderOptions = {}) {
this.options = this.validateOptions(options);
this.availableExtensions = availableExtensions();
this.invalidPaths = ['node_modules', ...ignoreDirectories()];
this.allowedFile = (fileName: string) => {
const char = fileName.charAt(0);
const isPrivate = char === '.' || char === '_';
return !isPrivate && !this.invalidPaths.includes(fileName);
};
}
private _getBundledRepository(dirPath: string): Record<string, any>|undefined {
const asset = this.require(dirPath);
return get(asset, ASSET_KEYWORD) ?? get(asset, `default.${ASSET_KEYWORD}`);
}
private _getBundledOperation<T>(
dirPath: string, opName: string, type: OperationTypeName
): T {
const repository = this._getBundledRepository(dirPath);
if (repository == null) {
throw new Error(`Empty asset repository found at path: ${dirPath}`);
}
const operation = get(repository, opName);
if (!operation) {
throw new Error(`Could not find operation ${opName}, must be one of ${joinList(Object.keys(repository))}`);
}
const repoType = OpTypeToRepositoryKey[type];
const opType = operation[repoType];
if (!opType) {
throw new Error(`Operation ${opName}, does not have ${repoType} registered`);
}
return opType;
}
private isBundledOperation(dirPath: string, name: string):boolean {
try {
const repository = this._getBundledRepository(dirPath);
return has(repository, name);
} catch (_err) {
return false;
}
}
private getBundleType({
codePath,
name
}: { codePath: string|null, name: string}): AssetBundleType|null {
if (!codePath) return null;
if (this.isBundledOperation(codePath, name)) {
return AssetBundleType.BUNDLED;
}
if (this.isLegacyOperation(codePath)) {
return AssetBundleType.LEGACY;
}
return AssetBundleType.STANDARD;
}
private isLegacyOperation(codePath: string): boolean {
try {
const results = this.require(codePath);
return ['newReader', 'newSlicer', 'newProcessor'].some((key) => has(results, key));
} catch (_err) {
return false;
}
}
find(name: string, assetIds?: string[]): FindOperationResults {
let filePath: string | null = null;
let location: OperationLocationType | null = null;
const findCodeFn = this.findCode(name);
const findCodeByConvention = (basePath?: string, subfolders?: string[]) => {
if (!basePath) return;
if (!fs.existsSync(basePath)) return;
if (!subfolders || !subfolders.length) return;
for (const folder of subfolders) {
const folderPath = pathModule.join(basePath, folder);
// we check for v3 version of asset
if (this.isBundledOperation(folderPath, name)) {
filePath = folderPath;
}
if (!filePath && fs.existsSync(folderPath)) {
filePath = findCodeFn(folderPath);
}
}
};
for (const assetPath of this.options.assetPath) {
location = OperationLocationType.asset;
findCodeByConvention(assetPath, assetIds);
if (filePath) break;
}
if (!filePath) {
location = OperationLocationType.builtin;
findCodeByConvention(this.getBuiltinDir(), ['.']);
}
if (!filePath) {
location = OperationLocationType.teraslice;
findCodeByConvention(this.options.terasliceOpPath, ['readers', 'processors']);
}
if (!filePath) {
location = OperationLocationType.module;
filePath = this.resolvePath(name);
}
const bundle_type = this.getBundleType({ codePath: filePath, name });
return { path: filePath, location, bundle_type };
}
loadProcessor(name: string, assetIds?: string[]): ProcessorModule {
const { path, bundle_type } = this.findOrThrow(name, assetIds);
if (bundle_type === AssetBundleType.LEGACY) {
return this.shimLegacyProcessor(name, path);
}
let Processor: ProcessorConstructor | undefined;
let Schema: SchemaConstructor | undefined;
let API: OperationAPIConstructor | undefined;
try {
Processor = this.require(path, OperationTypeName.processor, { name, bundle_type });
} catch (err) {
throw new Error(`Failure loading processor from module: ${name}, error: ${parseError(err, true)}`);
}
try {
Schema = this.require(path, OperationTypeName.schema, { name, bundle_type });
} catch (err) {
throw new Error(`Failure loading schema from module: ${name}, error: ${parseError(err, true)}`);
}
try {
API = this.require(path, OperationTypeName.api, { name, bundle_type });
} catch (err) {
// do nothing
}
return {
// @ts-expect-error
Processor,
// @ts-expect-error
Schema,
API,
};
}
loadReader(name: string, assetIds?: string[]): ReaderModule {
const { path, bundle_type } = this.findOrThrow(name, assetIds);
if (bundle_type === AssetBundleType.LEGACY) {
return this.shimLegacyReader(name, path);
}
let Fetcher: FetcherConstructor | undefined;
let Slicer: SlicerConstructor | undefined;
let Schema: SchemaConstructor | undefined;
let API: OperationAPIConstructor | undefined;
try {
Slicer = this.require(path, OperationTypeName.slicer, { name, bundle_type });
} catch (err) {
throw new Error(`Failure loading slicer from module: ${name}, error: ${parseError(err, true)}`);
}
try {
Fetcher = this.require(path, OperationTypeName.fetcher, { name, bundle_type });
} catch (err) {
throw new Error(`Failure loading fetcher from module: ${name}, error: ${parseError(err, true)}`);
}
try {
Schema = this.require(path, OperationTypeName.schema, { name, bundle_type });
} catch (err) {
throw new Error(`Failure loading schema from module: ${name}, error: ${parseError(err, true)}`);
}
try {
API = this.require(path, OperationTypeName.api, { name, bundle_type });
} catch (err) {
// do nothing
}
return {
// @ts-expect-error
Slicer,
// @ts-expect-error
Fetcher,
// @ts-expect-error
Schema,
API,
};
}
loadAPI(name: string, assetIds?: string[]): APIModule {
const [apiName] = name.split(':', 1);
const { path, bundle_type } = this.findOrThrow(apiName, assetIds);
let API: OperationAPIConstructor | undefined;
try {
API = this.require(path, OperationTypeName.api, { name: apiName, bundle_type });
} catch (err) {
// do nothing
}
let Observer: ObserverConstructor | undefined;
try {
Observer = this.require(
path, OperationTypeName.observer, { name: apiName, bundle_type }
);
} catch (err) {
// do nothing
}
let Schema: SchemaConstructor | undefined;
try {
Schema = this.require(path, OperationTypeName.schema, { name: apiName, bundle_type });
} catch (err) {
throw new Error(`Failure loading schema from module: ${apiName}, error: ${parseError(err, true)}`);
}
if (Observer == null && API == null) {
throw new Error(`Failure to load api module: ${apiName}, requires at least an api.js or observer.js`);
} else if (Observer != null && API != null) {
throw new Error(`Failure to load api module: ${apiName}, required only one api.js or observer.js`);
}
const type = API != null ? 'api' : 'observer';
return {
// @ts-expect-error
API: API || Observer,
// @ts-expect-error
Schema,
type,
};
}
private findOrThrow(name: string, assetIds?: string[]): OperationResults {
this.verifyOpName(name);
const results = this.find(name, assetIds);
if (!results.path) {
throw new Error(`Unable to find module for operation: ${name}`);
}
if (!results.location) {
throw new Error(`Unable to gather location for operation: ${name}`);
}
if (!results.bundle_type) {
throw new Error(`Unable to determine the bundle_type for operation: ${name}`);
}
return results as OperationResults;
}
private shimLegacyReader(name: string, codePath: string): ReaderModule {
try {
return readerShim(this.require(codePath));
} catch (err) {
throw new Error(`Failure loading reader: ${name}, error: ${parseError(err, true)}`);
}
}
private shimLegacyProcessor(name: string, codePath: string): ProcessorModule {
try {
return processorShim(this.require(codePath));
} catch (err) {
throw new Error(`Failure loading processor: ${name}, error: ${parseError(err, true)}`);
}
}
private require<T>(
dir: string,
type?: OperationTypeName,
{ bundle_type, name }: { bundle_type?: AssetBundleType, name?: string } = {}
): T {
const filePaths = type
? this.availableExtensions.map((ext) => pathModule.format({
dir,
name: type,
ext,
}))
: [dir];
let err: Error | undefined;
if (bundle_type && bundle_type === AssetBundleType.BUNDLED) {
if (!type) throw new Error('Must provide a operation type if using a version parameter');
if (!name) throw new Error('Must provide a operation name if using a version parameter');
try {
return this._getBundledOperation(dir, name, type);
} catch (_err) {
err = _err;
}
} else {
for (const filePath of filePaths) {
try {
const mod = require(filePath);
return mod.default || mod;
} catch (_err) {
err = _err;
}
}
}
if (err) {
throw err;
} else {
throw new Error(`Unable to find module at paths: ${filePaths.join(', ')}`);
}
}
private resolvePath(filePath: string): string | null {
if (!filePath) return null;
if (fs.existsSync(filePath)) return filePath;
try {
return require.resolve(filePath);
} catch (err) {
for (const ext of this.availableExtensions) {
try {
return pathModule.dirname(
require.resolve(
pathModule.format({
dir: filePath,
name: 'schema',
ext,
})
)
);
} catch (_err) {
// do nothing
}
}
return null;
}
}
private verifyOpName(name: string): void {
if (!isString(name)) {
throw new TypeError('Please verify that the "_op" name exists for each operation');
}
if (!this.allowedFile(name)) throw new Error(`Invalid name: ${name}, it is private or otherwise restricted`);
}
private findCode(name: string) {
let filePath: string | null = null;
const codeNames = this.availableExtensions.map((ext) => pathModule.format({
name,
ext,
}));
const allowedNames = uniq([name, ...codeNames]);
const findCode = (rootDir: string): string | null => {
const fileNames = fs.readdirSync(rootDir)
.filter(this.allowedFile);
for (const fileName of fileNames) {
if (filePath) break;
const nextPath = pathModule.join(rootDir, fileName);
// if name is same as fileName/dir then we found it
if (allowedNames.includes(fileName)) {
filePath = this.resolvePath(nextPath);
}
if (!filePath && this.isDir(nextPath)) {
filePath = findCode(nextPath);
}
}
return filePath;
};
return findCode;
}
private isDir(filePath: string) {
return fs.statSync(filePath).isDirectory();
}
private getBuiltinDir() {
if (this.availableExtensions.includes('.ts')) {
return pathModule.join(__dirname, '../builtin');
}
return pathModule.join(__dirname, '..', '..', '..', 'dist', 'src', 'builtin');
}
private validateOptions(options: LoaderOptions): ValidLoaderOptions {
const assetPath = castArray<string|undefined>(options.assetPath);
const validOptions = Object.assign({}, options, { assetPath });
return validOptions as ValidLoaderOptions;
}
}
function availableExtensions(): string[] {
// populated by teraslice Jest configuration
// @ts-expect-error
return global.availableExtensions ? global.availableExtensions : ['.js', '.mjs', '.cjs'];
}
function ignoreDirectories() {
// populated by teraslice Jest configuration
// @ts-expect-error
return global.ignoreDirectories || [];
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* A Secret is a logical secret whose value and versions can be accessed.
*
* To get more information about Secret, see:
*
* * [API documentation](https://cloud.google.com/secret-manager/docs/reference/rest/v1/projects.secrets)
*
* ## Example Usage
* ### Secret Config Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const secret_basic = new gcp.secretmanager.Secret("secret-basic", {
* labels: {
* label: "my-label",
* },
* replication: {
* userManaged: {
* replicas: [
* {
* location: "us-central1",
* },
* {
* location: "us-east1",
* },
* ],
* },
* },
* secretId: "secret",
* });
* ```
*
* ## Import
*
* Secret can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:secretmanager/secret:Secret default projects/{{project}}/secrets/{{secret_id}}
* ```
*
* ```sh
* $ pulumi import gcp:secretmanager/secret:Secret default {{project}}/{{secret_id}}
* ```
*
* ```sh
* $ pulumi import gcp:secretmanager/secret:Secret default {{secret_id}}
* ```
*/
export class Secret extends pulumi.CustomResource {
/**
* Get an existing Secret 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?: SecretState, opts?: pulumi.CustomResourceOptions): Secret {
return new Secret(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:secretmanager/secret:Secret';
/**
* Returns true if the given object is an instance of Secret. 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 Secret {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Secret.__pulumiType;
}
/**
* The time at which the Secret was created.
*/
public /*out*/ readonly createTime!: pulumi.Output<string>;
/**
* Timestamp in UTC when the Secret is scheduled to expire. This is always provided on output, regardless of what was sent on input.
* A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".
*/
public readonly expireTime!: pulumi.Output<string>;
/**
* The labels assigned to this Secret.
* Label keys must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes,
* and must conform to the following PCRE regular expression: [\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}
* Label values must be between 0 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes,
* and must conform to the following PCRE regular expression: [\p{Ll}\p{Lo}\p{N}_-]{0,63}
* No more than 64 labels can be assigned to a given resource.
* An object containing a list of "key": value pairs. Example:
* { "name": "wrench", "mass": "1.3kg", "count": "3" }.
*/
public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* The resource name of the Pub/Sub topic that will be published to, in the following format: projects/*/topics/*.
* For publication to succeed, the Secret Manager Service Agent service account must have pubsub.publisher permissions on the topic.
*/
public /*out*/ readonly name!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* The replication policy of the secret data attached to the Secret. It cannot be changed
* after the Secret has been created.
* Structure is documented below.
*/
public readonly replication!: pulumi.Output<outputs.secretmanager.SecretReplication>;
/**
* The rotation time and period for a Secret. At `nextRotationTime`, Secret Manager will send a Pub/Sub notification to the topics configured on the Secret. `topics` must be set to configure rotation.
* Structure is documented below.
*/
public readonly rotation!: pulumi.Output<outputs.secretmanager.SecretRotation | undefined>;
/**
* This must be unique within the project.
*/
public readonly secretId!: pulumi.Output<string>;
/**
* A list of up to 10 Pub/Sub topics to which messages are published when control plane operations are called on the secret or its versions.
* Structure is documented below.
*/
public readonly topics!: pulumi.Output<outputs.secretmanager.SecretTopic[] | undefined>;
/**
* The TTL for the Secret.
* A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s".
*/
public readonly ttl!: pulumi.Output<string | undefined>;
/**
* Create a Secret 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: SecretArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: SecretArgs | SecretState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as SecretState | undefined;
inputs["createTime"] = state ? state.createTime : undefined;
inputs["expireTime"] = state ? state.expireTime : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["replication"] = state ? state.replication : undefined;
inputs["rotation"] = state ? state.rotation : undefined;
inputs["secretId"] = state ? state.secretId : undefined;
inputs["topics"] = state ? state.topics : undefined;
inputs["ttl"] = state ? state.ttl : undefined;
} else {
const args = argsOrState as SecretArgs | undefined;
if ((!args || args.replication === undefined) && !opts.urn) {
throw new Error("Missing required property 'replication'");
}
if ((!args || args.secretId === undefined) && !opts.urn) {
throw new Error("Missing required property 'secretId'");
}
inputs["expireTime"] = args ? args.expireTime : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["replication"] = args ? args.replication : undefined;
inputs["rotation"] = args ? args.rotation : undefined;
inputs["secretId"] = args ? args.secretId : undefined;
inputs["topics"] = args ? args.topics : undefined;
inputs["ttl"] = args ? args.ttl : undefined;
inputs["createTime"] = undefined /*out*/;
inputs["name"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Secret.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Secret resources.
*/
export interface SecretState {
/**
* The time at which the Secret was created.
*/
createTime?: pulumi.Input<string>;
/**
* Timestamp in UTC when the Secret is scheduled to expire. This is always provided on output, regardless of what was sent on input.
* A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".
*/
expireTime?: pulumi.Input<string>;
/**
* The labels assigned to this Secret.
* Label keys must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes,
* and must conform to the following PCRE regular expression: [\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}
* Label values must be between 0 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes,
* and must conform to the following PCRE regular expression: [\p{Ll}\p{Lo}\p{N}_-]{0,63}
* No more than 64 labels can be assigned to a given resource.
* An object containing a list of "key": value pairs. Example:
* { "name": "wrench", "mass": "1.3kg", "count": "3" }.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The resource name of the Pub/Sub topic that will be published to, in the following format: projects/*/topics/*.
* For publication to succeed, the Secret Manager Service Agent service account must have pubsub.publisher permissions on the topic.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The replication policy of the secret data attached to the Secret. It cannot be changed
* after the Secret has been created.
* Structure is documented below.
*/
replication?: pulumi.Input<inputs.secretmanager.SecretReplication>;
/**
* The rotation time and period for a Secret. At `nextRotationTime`, Secret Manager will send a Pub/Sub notification to the topics configured on the Secret. `topics` must be set to configure rotation.
* Structure is documented below.
*/
rotation?: pulumi.Input<inputs.secretmanager.SecretRotation>;
/**
* This must be unique within the project.
*/
secretId?: pulumi.Input<string>;
/**
* A list of up to 10 Pub/Sub topics to which messages are published when control plane operations are called on the secret or its versions.
* Structure is documented below.
*/
topics?: pulumi.Input<pulumi.Input<inputs.secretmanager.SecretTopic>[]>;
/**
* The TTL for the Secret.
* A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s".
*/
ttl?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Secret resource.
*/
export interface SecretArgs {
/**
* Timestamp in UTC when the Secret is scheduled to expire. This is always provided on output, regardless of what was sent on input.
* A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".
*/
expireTime?: pulumi.Input<string>;
/**
* The labels assigned to this Secret.
* Label keys must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes,
* and must conform to the following PCRE regular expression: [\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}
* Label values must be between 0 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes,
* and must conform to the following PCRE regular expression: [\p{Ll}\p{Lo}\p{N}_-]{0,63}
* No more than 64 labels can be assigned to a given resource.
* An object containing a list of "key": value pairs. Example:
* { "name": "wrench", "mass": "1.3kg", "count": "3" }.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The replication policy of the secret data attached to the Secret. It cannot be changed
* after the Secret has been created.
* Structure is documented below.
*/
replication: pulumi.Input<inputs.secretmanager.SecretReplication>;
/**
* The rotation time and period for a Secret. At `nextRotationTime`, Secret Manager will send a Pub/Sub notification to the topics configured on the Secret. `topics` must be set to configure rotation.
* Structure is documented below.
*/
rotation?: pulumi.Input<inputs.secretmanager.SecretRotation>;
/**
* This must be unique within the project.
*/
secretId: pulumi.Input<string>;
/**
* A list of up to 10 Pub/Sub topics to which messages are published when control plane operations are called on the secret or its versions.
* Structure is documented below.
*/
topics?: pulumi.Input<pulumi.Input<inputs.secretmanager.SecretTopic>[]>;
/**
* The TTL for the Secret.
* A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s".
*/
ttl?: pulumi.Input<string>;
} | the_stack |
import {addCanvas, addTitle, colors, sizes} from "./internal/layout";
import {
point,
drawOpen,
calcBouncePercentage,
drawLine,
drawPoint,
tempStyles,
drawClosed,
forceStyles,
} from "./internal/canvas";
import {
split,
expandHandle,
splitLine,
forPoints,
mapPoints,
coordPoint,
distance,
mod,
shift,
} from "../internal/util";
import {timingFunctions} from "../internal/animate/timing";
import {Coord, Point} from "../internal/types";
import {rand} from "../internal/rand";
import {genFromOptions} from "../internal/gen";
import {BlobOptions} from "../public/blobs";
import {interpolateBetween, interpolateBetweenSmooth} from "../internal/animate/interpolate";
import {divide} from "../internal/animate/prepare";
import {statefulAnimationGenerator} from "../internal/animate/state";
import {CanvasKeyframe} from "../public/animate";
const makePoly = (pointCount: number, radius: number, center: Coord): Point[] => {
const angle = (2 * Math.PI) / pointCount;
const points: Point[] = [];
const nullHandle = {angle: 0, length: 0};
for (let i = 0; i < pointCount; i++) {
const coord = expandHandle(center, {angle: i * angle, length: radius});
points.push({...coord, handleIn: nullHandle, handleOut: nullHandle});
}
return points;
};
const centeredBlob = (options: BlobOptions, center: Coord): Point[] => {
return mapPoints(genFromOptions(options), ({curr}) => {
curr.x += center.x - options.size / 2;
curr.y += center.y - options.size / 2;
return curr;
});
};
const calcFullDetails = (percentage: number, a: Point, b: Point) => {
const a0: Coord = a;
const a1 = expandHandle(a, a.handleOut);
const a2 = expandHandle(b, b.handleIn);
const a3: Coord = b;
const b0 = splitLine(percentage, a0, a1);
const b1 = splitLine(percentage, a1, a2);
const b2 = splitLine(percentage, a2, a3);
const c0 = splitLine(percentage, b0, b1);
const c1 = splitLine(percentage, b1, b2);
const d0 = splitLine(percentage, c0, c1);
return {a0, a1, a2, a3, b0, b1, b2, c0, c1, d0};
};
addTitle(4, "Vector graphics");
addCanvas(
1.3,
// Pixelated circle.
(ctx, width, height) => {
const center: Coord = {x: width * 0.5, y: height * 0.5};
const gridSize = width * 0.01;
const gridCountX = width / gridSize;
const gridCountY = height / gridSize;
// https://www.desmos.com/calculator/psohl602g5
const radius = width * 0.3;
const falloff = width * 0.0015;
const thickness = width * 0.007;
for (let x = 0; x < gridCountX; x++) {
for (let y = 0; y < gridCountY; y++) {
const curr = {x: x * gridSize + gridSize / 2, y: y * gridSize + gridSize / 2};
const d = distance(curr, center);
const opacity = Math.max(
0,
Math.min(1, Math.abs(thickness / (d - radius)) - falloff),
);
tempStyles(
ctx,
() => {
ctx.globalAlpha = opacity;
ctx.fillStyle = colors.highlight;
},
() => ctx.fillRect(x * gridSize, y * gridSize, gridSize, gridSize),
);
}
}
return `Raster image formats store pixel information and have a fixed resolution.`;
},
// Smooth circle.
(ctx, width, height) => {
const pt = width * 0.01;
const shapeSize = width * 0.6;
const cx = width * 0.5;
const cy = height * 0.5;
tempStyles(
ctx,
() => {
ctx.lineWidth = pt;
ctx.strokeStyle = colors.highlight;
},
() => {
ctx.beginPath();
ctx.arc(cx, cy, shapeSize / 2, 0, 2 * Math.PI);
ctx.stroke();
},
);
return `By contrast vector formats can scale infinitely because they are defined by
formulas. They are ideal for artwork with sharp lines that will be viewed at varying
sizes.`;
},
);
addCanvas(2, (ctx, width, height, animate) => {
const startPeriod = (1 + Math.E) * 1000;
const endPeriod = (1 + Math.PI) * 1000;
animate((frameTime) => {
const startPercentage = calcBouncePercentage(startPeriod, timingFunctions.ease, frameTime);
const startLengthPercentage = calcBouncePercentage(
startPeriod * 0.8,
timingFunctions.ease,
frameTime,
);
const startAngle = split(startPercentage, -45, +45);
const startLength = width * 0.1 + width * 0.2 * startLengthPercentage;
const start = point(width * 0.2, height * 0.5, 0, 0, startAngle, startLength);
const endPercentage = calcBouncePercentage(endPeriod, timingFunctions.ease, frameTime);
const endLengthPercentage = calcBouncePercentage(
endPeriod * 0.8,
timingFunctions.ease,
frameTime,
);
const endAngle = split(endPercentage, 135, 225);
const endLength = width * 0.1 + width * 0.2 * endLengthPercentage;
const end = point(width * 0.8, height * 0.5, endAngle, endLength, 0, 0);
drawOpen(ctx, start, end, true);
});
return `Vector-based images are commonly defined using Bezier curves. The cubic bezier is made
up of four coordinates: the start/end points and their corresponding "handles". These
handles define the direction and "momentum" of the line.`;
});
addCanvas(2, (ctx, width, height, animate) => {
const period = Math.PI * Math.E * 1000;
const start = point(width * 0.3, height * 0.8, 0, 0, -105, width * 0.32);
const end = point(width * 0.7, height * 0.8, -75, width * 0.25, 0, 0);
animate((frameTime) => {
const percentage = calcBouncePercentage(period, timingFunctions.ease, frameTime);
const d = calcFullDetails(percentage, start, end);
tempStyles(
ctx,
() => {
ctx.fillStyle = colors.secondary;
ctx.strokeStyle = colors.secondary;
},
() => {
drawLine(ctx, d.a0, d.a1, 1);
drawLine(ctx, d.a1, d.a2, 1);
drawLine(ctx, d.a2, d.a3, 1);
drawLine(ctx, d.b0, d.b1, 1);
drawLine(ctx, d.b1, d.b2, 1);
drawLine(ctx, d.c0, d.c1, 1);
drawPoint(ctx, d.a0, 1.3, "a0");
drawPoint(ctx, d.a1, 1.3, "a1");
drawPoint(ctx, d.a2, 1.3, "a2");
drawPoint(ctx, d.a3, 1.3, "a3");
drawPoint(ctx, d.b0, 1.3, "b0");
drawPoint(ctx, d.b1, 1.3, "b1");
drawPoint(ctx, d.b2, 1.3, "b2");
drawPoint(ctx, d.c0, 1.3, "c0");
drawPoint(ctx, d.c1, 1.3, "c1");
},
);
tempStyles(
ctx,
() => (ctx.fillStyle = colors.highlight),
() => drawPoint(ctx, d.d0, 3),
);
drawOpen(ctx, start, end, false);
});
return `Curves can be drawn geometrically by recursively splitting points by a percentage
until there is only one point remaining. Note there is no constant relationship between the
percentage that "drew" the point and the arc lengths before/after it. Uniform motion along
the curve can only be approximated.`;
});
addTitle(4, "Making a blob");
addCanvas(
1.3,
(ctx, width, height) => {
const center: Coord = {x: width * 0.5, y: height * 0.5};
const radius = width * 0.3;
const points = 5;
const shape = makePoly(points, radius, center);
// Draw lines from center to each point..
tempStyles(
ctx,
() => {
ctx.fillStyle = colors.secondary;
ctx.strokeStyle = colors.secondary;
},
() => {
drawPoint(ctx, center, 2);
forPoints(shape, ({curr}) => {
drawLine(ctx, center, curr, 1, 2);
});
},
);
drawClosed(ctx, shape, false);
return `Initial points are rotated evenly around the center.`;
},
(ctx, width, height, animate) => {
const period = Math.PI * 1000;
const center: Coord = {x: width * 0.5, y: height * 0.5};
const radius = width * 0.3;
const points = 5;
const randSeed = "abcd";
const randStrength = 0.5;
const shape = makePoly(points, radius, center);
animate((frameTime) => {
const percentage = calcBouncePercentage(period, timingFunctions.ease, frameTime);
const rgen = rand(randSeed);
// Draw original shape.
tempStyles(
ctx,
() => {
ctx.fillStyle = colors.secondary;
ctx.strokeStyle = colors.secondary;
},
() => {
drawPoint(ctx, center, 2);
forPoints(shape, ({curr, next}) => {
drawLine(ctx, curr, next(), 1, 2);
});
},
);
// Draw randomly shifted shape.
const shiftedShape = shape.map((p): Point => {
const randOffset = percentage * (randStrength * rgen() - randStrength / 2);
return coordPoint(splitLine(randOffset, p, center));
});
drawClosed(ctx, shiftedShape, true);
});
return `Each point is randomly moved toward or away from the center.`;
},
);
addCanvas(
1.3,
(ctx, width, height) => {
const options: BlobOptions = {
extraPoints: 2,
randomness: 6,
seed: "random",
size: width * 0.7,
};
const center: Coord = {x: width * 0.5, y: height * 0.5};
const polyBlob = centeredBlob(options, center).map(coordPoint);
// Draw polygon blob.
tempStyles(
ctx,
() => {
ctx.fillStyle = colors.secondary;
ctx.strokeStyle = colors.secondary;
},
() => {
drawPoint(ctx, center, 2);
forPoints(polyBlob, ({curr}) => {
drawLine(ctx, center, curr, 1, 2);
});
},
);
drawClosed(ctx, polyBlob, false);
return `In this state, the points have handles of length zero.`;
},
(ctx, width, height, animate) => {
const period = Math.PI * 1000;
const options: BlobOptions = {
extraPoints: 2,
randomness: 6,
seed: "random",
size: width * 0.7,
};
const center: Coord = {x: width * 0.5, y: height * 0.5};
const blob = centeredBlob(options, center);
animate((frameTime) => {
const percentage = calcBouncePercentage(period, timingFunctions.ease, frameTime);
// Draw original blob.
tempStyles(
ctx,
() => {
ctx.fillStyle = colors.secondary;
ctx.strokeStyle = colors.secondary;
},
() => {
drawPoint(ctx, center, 2);
forPoints(blob, ({curr, next}) => {
drawLine(ctx, curr, next(), 1, 2);
});
},
);
// Draw animated blob.
const animatedBlob = mapPoints(blob, ({curr}) => {
curr.handleIn.length *= percentage;
curr.handleOut.length *= percentage;
return curr;
});
drawClosed(ctx, animatedBlob, true);
});
return `The blob is smoothed by making handles parallel to the line between the points
immediately before and after. The length of the handles is a function of the distance to
the nearest neighbor.`;
},
);
addTitle(4, "Interpolating between blobs");
addCanvas(2, (ctx, width, height, animate) => {
const period = Math.PI * 1000;
const center: Coord = {x: width * 0.5, y: height * 0.5};
const fadeSpeed = 10;
const fadeLead = 0.05;
const fadeFloor = 0.2;
const blobA = centeredBlob(
{
extraPoints: 3,
randomness: 6,
seed: "12345",
size: height * 0.8,
},
center,
);
const blobB = centeredBlob(
{
extraPoints: 3,
randomness: 6,
seed: "abc",
size: height * 0.8,
},
center,
);
animate((frameTime) => {
const percentage = calcBouncePercentage(period, timingFunctions.ease, frameTime);
const shiftedFrameTime = frameTime + period * fadeLead;
const shiftedPercentage = calcBouncePercentage(
period,
timingFunctions.ease,
shiftedFrameTime,
);
const shiftedPeriodPercentage = mod(shiftedFrameTime, period) / period;
forceStyles(ctx, () => {
const {pt} = sizes();
ctx.fillStyle = "transparent";
ctx.lineWidth = pt;
ctx.strokeStyle = colors.secondary;
ctx.setLineDash([2 * pt]);
if (shiftedPeriodPercentage > 0.5) {
ctx.globalAlpha = fadeFloor + fadeSpeed * (1 - shiftedPercentage);
drawClosed(ctx, blobA, false);
ctx.globalAlpha = fadeFloor;
drawClosed(ctx, blobB, false);
} else {
ctx.globalAlpha = fadeFloor + fadeSpeed * shiftedPercentage;
drawClosed(ctx, blobB, false);
ctx.globalAlpha = fadeFloor;
drawClosed(ctx, blobA, false);
}
});
drawClosed(ctx, interpolateBetween(percentage, blobA, blobB), true);
});
return `Interpolation requires points to be paired up from shape A to B. This means both blobs
must have the same number of points and that the points should be matched in a way that
minimizes movement.`;
});
addCanvas(
1.3,
(ctx, width, height, animate) => {
const period = (Math.E / Math.PI) * 1000;
const center: Coord = {x: width * 0.5, y: height * 0.5};
const blob = centeredBlob(
{
extraPoints: 3,
randomness: 6,
seed: "shift",
size: height * 0.9,
},
center,
);
const shiftedBlob = shift(1, blob);
let prev = 0;
let count = 0;
animate((frameTime) => {
const animationTime = mod(frameTime, period);
const percentage = timingFunctions.ease(mod(animationTime, period) / period);
// Count animation loops.
if (percentage < prev) count++;
prev = percentage;
// Draw lines points are travelling.
tempStyles(
ctx,
() => {
ctx.fillStyle = colors.secondary;
ctx.strokeStyle = colors.secondary;
},
() => {
drawPoint(ctx, center, 2);
forPoints(blob, ({curr, next}) => {
drawLine(ctx, curr, next(), 1, 2);
});
},
);
// Pause in-place every other animation loop.
if (count % 2 === 0) {
drawClosed(ctx, interpolateBetweenSmooth(2, percentage, blob, shiftedBlob), true);
} else {
drawClosed(ctx, blob, true);
}
});
return `Points cannot be swapped without resulting in a different shape. However, a likely
enough optimal order can be selected by shifting the points and comparing the point
position deltas.`;
},
(ctx, width, height, animate) => {
const period = Math.PI * Math.E * 1000;
const center: Coord = {x: width * 0.5, y: height * 0.5};
const blob = centeredBlob(
{
extraPoints: 3,
randomness: 6,
seed: "flip",
size: height * 0.9,
},
center,
);
const reversedBlob = mapPoints(blob, ({curr}) => {
const temp = curr.handleIn;
curr.handleIn = curr.handleOut;
curr.handleOut = temp;
return curr;
});
reversedBlob.reverse();
animate((frameTime) => {
const percentage = calcBouncePercentage(period, timingFunctions.ease, frameTime);
forceStyles(ctx, () => {
const {pt} = sizes();
ctx.fillStyle = "transparent";
ctx.lineWidth = pt;
ctx.strokeStyle = colors.secondary;
ctx.setLineDash([2 * pt]);
drawClosed(ctx, blob, false);
});
drawClosed(ctx, interpolateBetweenSmooth(2, percentage, blob, reversedBlob), true);
});
return `The only safe re-ordering is to reverse the points and again iterate through all
possible shifts.`;
},
);
addCanvas(
1.3,
(ctx, width, height, animate) => {
const period = Math.PI * 1000;
const center: Coord = {x: width * 0.5, y: height * 0.5};
const maxExtraPoints = 4;
const {pt} = sizes();
const blob = centeredBlob(
{
extraPoints: 0,
randomness: 6,
seed: "flip",
size: height * 0.9,
},
center,
);
animate((frameTime) => {
const percentage = mod(frameTime, period) / period;
const extraPoints = Math.floor(percentage * (maxExtraPoints + 1));
drawClosed(ctx, divide(extraPoints + blob.length, blob), true);
forPoints(blob, ({curr}) => {
ctx.beginPath();
ctx.arc(curr.x, curr.y, pt * 6, 0, 2 * Math.PI);
tempStyles(
ctx,
() => {
ctx.strokeStyle = colors.secondary;
ctx.lineWidth = pt;
},
() => {
ctx.stroke();
},
);
});
});
return `Points are added until they both have the same count. These new points should be as
evenly distributed as possible.`;
},
(ctx, width, height, animate) => {
const period = Math.PI ** Math.E * 1000;
const start = point(width * 0.1, height * 0.6, 0, 0, -45, width * 0.5);
const end = point(width * 0.9, height * 0.6, 160, width * 0.3, 0, 0);
animate((frameTime) => {
const percentage = calcBouncePercentage(period, timingFunctions.ease, frameTime);
const d = calcFullDetails(percentage, start, end);
tempStyles(
ctx,
() => {
ctx.fillStyle = colors.secondary;
ctx.strokeStyle = colors.secondary;
},
() => {
drawLine(ctx, d.a0, d.a1, 1);
drawLine(ctx, d.a1, d.a2, 1);
drawLine(ctx, d.a2, d.a3, 1);
drawLine(ctx, d.b0, d.b1, 1);
drawLine(ctx, d.b1, d.b2, 1);
drawPoint(ctx, d.a0, 1.3);
drawPoint(ctx, d.a1, 1.3);
drawPoint(ctx, d.a2, 1.3);
drawPoint(ctx, d.a3, 1.3);
drawPoint(ctx, d.b0, 1.3);
drawPoint(ctx, d.b1, 1.3);
drawPoint(ctx, d.b2, 1.3);
},
);
forceStyles(ctx, () => {
const {pt} = sizes();
ctx.fillStyle = colors.secondary;
ctx.strokeStyle = colors.secondary;
ctx.lineWidth = pt;
drawOpen(ctx, start, end, false);
});
tempStyles(
ctx,
() => {
ctx.fillStyle = colors.highlight;
ctx.strokeStyle = colors.highlight;
},
() => {
drawLine(ctx, d.c0, d.c1, 1);
drawPoint(ctx, d.c0, 1.3);
drawPoint(ctx, d.c1, 1.3);
},
);
tempStyles(
ctx,
() => (ctx.fillStyle = colors.highlight),
() => drawPoint(ctx, d.d0, 2),
);
});
return `Curve splitting uses the innermost line from the cubic bezier curve drawing demo and
makes either side of the final point the handles.`;
},
);
addCanvas(1.8, (ctx, width, height) => {
// Only animate in the most recent painter call.
const animationID = Math.random();
const wasReplaced = () => (ctx.canvas as any).animationID !== animationID;
const period = Math.PI * 1000;
const center: Coord = {x: width * 0.5, y: height * 0.5};
const size = Math.min(width, height) * 0.8;
const canvasBlobGenerator = (keyframe: CanvasKeyframe): Point[] => {
return mapPoints(genFromOptions(keyframe.blobOptions), ({curr}) => {
curr.x += center.x - size / 2;
curr.y += center.y - size / 2;
return curr;
});
};
const animation = statefulAnimationGenerator(
canvasBlobGenerator,
(points: Point[]) => drawClosed(ctx, points, true),
() => {},
)();
const renderFrame = () => {
if (wasReplaced()) return;
ctx.clearRect(0, 0, width, height);
animation.renderFrame();
requestAnimationFrame(renderFrame);
};
requestAnimationFrame(renderFrame);
const loopAnimation = (): void => {
if (wasReplaced()) return;
animation.transition(genFrame());
};
let frameCount = -1;
const genFrame = (overrides: Partial<CanvasKeyframe> = {}): CanvasKeyframe => {
frameCount++;
return {
duration: period,
timingFunction: "ease",
callback: loopAnimation,
blobOptions: {
extraPoints: Math.max(0, mod(frameCount, 4) - 1),
randomness: 4,
seed: Math.random(),
size,
},
...overrides,
};
};
animation.transition(genFrame({duration: 0}));
ctx.canvas.onclick = () => {
if (wasReplaced()) return;
animation.playPause();
};
(ctx.canvas as any).animationID = animationID;
return `Points can be removed at the end of animations as the target shape has been reached.
However if the animation is interrupted during interpolation there is no opportunity to
clean up the extra points.`;
}); | the_stack |
import { kea } from 'kea'
import api from 'lib/api'
import { errorToast, eventToName, toParams } from 'lib/utils'
import { sessionsPlayLogicType } from './sessionsPlayLogicType'
import { SessionPlayerData, SessionRecordingId, SessionType } from '~/types'
import dayjs from 'dayjs'
import { EventIndex } from '@posthog/react-rrweb-player'
import { sessionsTableLogic } from 'scenes/sessions/sessionsTableLogic'
import { toast } from 'react-toastify'
import { eventUsageLogic, RecordingWatchedSource } from 'lib/utils/eventUsageLogic'
import { teamLogic } from '../teamLogic'
import { eventWithTime } from 'rrweb/typings/types'
const IS_TEST_MODE = process.env.NODE_ENV === 'test'
export const sessionsPlayLogic = kea<sessionsPlayLogicType>({
connect: {
logic: [eventUsageLogic],
values: [
sessionsTableLogic,
['sessions', 'pagination', 'orderedSessionRecordingIds', 'loadedSessionEvents'],
teamLogic,
['currentTeamId'],
],
actions: [
sessionsTableLogic,
['fetchNextSessions', 'appendNewSessions', 'closeSessionPlayer', 'loadSessionEvents'],
],
},
actions: {
toggleAddingTagShown: () => {},
setAddingTag: (payload: string) => ({ payload }),
goToNext: true,
goToPrevious: true,
openNextRecordingOnLoad: true,
setSource: (source: RecordingWatchedSource) => ({ source }),
reportUsage: (recordingData: SessionPlayerData, loadTime: number) => ({ recordingData, loadTime }),
loadRecording: (sessionRecordingId?: string, url?: string) => ({ sessionRecordingId, url }),
},
reducers: {
sessionRecordingId: [
null as SessionRecordingId | null,
{
loadRecording: (_, { sessionRecordingId }) => sessionRecordingId ?? null,
},
],
addingTagShown: [
false,
{
toggleAddingTagShown: (state) => !state,
},
],
addingTag: [
'',
{
setAddingTag: (_, { payload }) => payload,
},
],
loadingNextRecording: [
false,
{
openNextRecordingOnLoad: () => true,
loadRecording: () => false,
closeSessionPlayer: () => false,
},
],
chunkIndex: [
0,
{
loadRecordingSuccess: (state) => state + 1,
},
],
sessionPlayerDataLoading: [
false,
{
loadRecordingSuccess: (_, { sessionPlayerData }) => {
// If sessionPlayerData doesn't have a next url, it means the entire recording is still loading.
return !!sessionPlayerData?.next
},
},
],
source: [
RecordingWatchedSource.Unknown as RecordingWatchedSource,
{
setSource: (_, { source }) => source,
},
],
},
listeners: ({ values, actions }) => ({
toggleAddingTagShown: () => {
// Clear text when tag input is dismissed
if (!values.addingTagShown) {
actions.setAddingTag('')
}
},
goToNext: () => {
if (values.recordingIndex < values.orderedSessionRecordingIds.length - 1) {
const id = values.orderedSessionRecordingIds[values.recordingIndex + 1]
actions.loadRecording(id)
} else if (values.pagination) {
// :TRICKY: Load next page of sessions, which will call appendNewSessions which will call goToNext again
actions.openNextRecordingOnLoad()
actions.fetchNextSessions()
} else {
toast('Found no more recordings.', { type: 'info' })
}
},
goToPrevious: () => {
const id = values.orderedSessionRecordingIds[values.recordingIndex - 1]
actions.loadRecording(id)
},
appendNewSessions: () => {
if (values.sessionRecordingId && values.loadingNextRecording) {
actions.goToNext()
}
},
loadRecordingSuccess: async () => {
// If there is more data to poll for load the next batch.
// This will keep calling loadRecording until `next` is empty.
if (!!values.sessionPlayerData?.next) {
await actions.loadRecording(undefined, values.sessionPlayerData.next)
}
},
loadRecordingFailure: ({ error }) => {
errorToast(
'Error fetching your session recording',
'Your recording returned the following error response:',
error
)
},
reportUsage: async ({ recordingData, loadTime }, breakpoint) => {
await breakpoint()
eventUsageLogic.actions.reportRecordingViewed(recordingData, values.source, loadTime, 0)
await breakpoint(IS_TEST_MODE ? 1 : 10000)
eventUsageLogic.actions.reportRecordingViewed(recordingData, values.source, loadTime, 10)
},
}),
loaders: ({ values, actions }) => ({
tags: [
['activating', 'watched', 'deleted'] as string[],
{
createTag: async () => {
const newTag = [values.addingTag]
const promise = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 3000)) // TODO: Temp to simulate loading
await promise()
actions.toggleAddingTagShown()
return values.tags.concat(newTag)
},
},
],
sessionPlayerData: {
loadRecording: async ({ sessionRecordingId, url }): Promise<SessionPlayerData> => {
const startTime = performance.now()
let response
if (url) {
// Subsequent calls to get rest of recording
response = await api.get(url)
} else {
// Very first call
const params = toParams({ session_recording_id: sessionRecordingId, save_view: true })
response = await api.get(`api/projects/${values.currentTeamId}/events/session_recording?${params}`)
actions.reportUsage(response.result, performance.now() - startTime)
}
const currData = values.sessionPlayerData
return {
...response.result,
snapshots: [...(currData?.snapshots ?? []), ...(response.result?.snapshots ?? [])],
}
},
},
}),
selectors: {
sessionDate: [
(selectors) => [selectors.sessionPlayerData],
(sessionPlayerData: SessionPlayerData): string | null => {
if (!sessionPlayerData?.start_time) {
return null
}
return dayjs(sessionPlayerData.start_time).format('MMM Do')
},
],
eventIndex: [
(selectors) => [selectors.sessionPlayerData],
(sessionPlayerData: SessionPlayerData): EventIndex => new EventIndex(sessionPlayerData?.snapshots || []),
],
recordingIndex: [
(selectors) => [selectors.orderedSessionRecordingIds, selectors.sessionRecordingId],
(recordingIds: SessionRecordingId[], id: SessionRecordingId): number => recordingIds.indexOf(id),
],
showPrev: [(selectors) => [selectors.recordingIndex], (index: number): boolean => index > 0],
showNext: [
(selectors) => [selectors.recordingIndex, selectors.orderedSessionRecordingIds, selectors.pagination],
(index: number, ids: SessionRecordingId[], pagination: Record<string, any> | null) =>
index > -1 && (index < ids.length - 1 || pagination !== null),
],
session: [
(selectors) => [selectors.sessionRecordingId, selectors.sessions],
(id: SessionRecordingId, sessions: Array<SessionType>): SessionType | null => {
const [session] = sessions.filter(
(s) => s.session_recordings.filter((recording) => id === recording.id).length > 0
)
return session
},
],
shouldLoadSessionEvents: [
(selectors) => [selectors.session, selectors.loadedSessionEvents],
(session, sessionEvents) => session && !sessionEvents[session.global_session_id],
],
firstChunkLoaded: [(selectors) => [selectors.chunkIndex], (chunkIndex) => chunkIndex > 0],
isPlayable: [
(selectors) => [
selectors.firstChunkLoaded,
selectors.sessionPlayerDataLoading,
selectors.sessionPlayerData,
],
(firstChunkLoaded, sessionPlayerDataLoading, sessionPlayerData) =>
(firstChunkLoaded || // If first chunk is ready
!sessionPlayerDataLoading) && // data isn't being fetched
sessionPlayerData?.snapshots.length >= 2 && // more than two snapshots needed to init Replayed
!!sessionPlayerData?.snapshots?.find((s: eventWithTime) => s.type === 2), // there's a full snapshot in the data that was loaded
],
highlightedSessionEvents: [
(selectors) => [selectors.session, selectors.loadedSessionEvents],
(session, sessionEvents) => {
if (!session) {
return []
}
const events = sessionEvents[session.global_session_id] || []
return events.filter((e) => (session.matching_events || []).includes(e.id))
},
],
shownPlayerEvents: [
(selectors) => [selectors.sessionPlayerData, selectors.eventIndex, selectors.highlightedSessionEvents],
(sessionPlayerData, eventIndex, events) => {
if (!sessionPlayerData) {
return []
}
const startTime = +dayjs(sessionPlayerData.start_time)
const pageChangeEvents = eventIndex.pageChangeEvents().map(({ playerTime, href }) => ({
playerTime,
text: href,
color: 'blue',
}))
const highlightedEvents = events.map((event) => ({
playerTime: +dayjs(event.timestamp) - startTime,
text: eventToName(event),
color: 'orange',
}))
return [...pageChangeEvents, ...highlightedEvents].sort((a, b) => a.playerTime - b.playerTime)
},
],
},
urlToAction: ({ actions, values }) => {
const urlToAction = (
_: any,
params: {
sessionRecordingId?: SessionRecordingId
source?: string
}
): void => {
const { sessionRecordingId, source } = params
if (source && (Object.values(RecordingWatchedSource) as string[]).includes(source)) {
actions.setSource(source as RecordingWatchedSource)
}
if (values && sessionRecordingId !== values.sessionRecordingId && sessionRecordingId) {
actions.loadRecording(sessionRecordingId)
}
}
return {
'/sessions': urlToAction,
'/recordings': urlToAction,
'/person/*': urlToAction,
}
},
}) | the_stack |
import * as React from "react";
import { Input, LabeledInput, ProgressLinear, Radio, Select, SelectOption } from "@itwin/itwinui-react";
import { Dialog, Icon, InputStatus } from "@itwin/core-react";
import { ModalDialogManager } from "@itwin/appui-react";
import { MapLayersUiItemsProvider } from "../MapLayersUiItemsProvider";
import { MapTypesOptions } from "../Interfaces";
import {
IModelApp, MapLayerImageryProviderStatus, MapLayerSettingsService, MapLayerSource,
MapLayerSourceStatus, NotifyMessageDetails, OutputMessagePriority, ScreenViewport,
} from "@itwin/core-frontend";
import { MapLayerProps } from "@itwin/core-common";
import "./MapUrlDialog.scss";
import { DialogButtonType, SpecialKey } from "@itwin/appui-abstract";
export const MAP_TYPES = {
wms: "WMS",
arcGis: "ArcGIS",
wmts: "WMTS",
tileUrl: "TileURL",
};
interface MapUrlDialogProps {
activeViewport?: ScreenViewport;
isOverlay: boolean;
onOkResult: () => void;
onCancelResult?: () => void;
mapTypesOptions?: MapTypesOptions;
// An optional layer definition can be provide to enable the edit mode
layerRequiringCredentials?: MapLayerProps;
mapLayerSourceToEdit?: MapLayerSource;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
export function MapUrlDialog(props: MapUrlDialogProps) {
const { isOverlay, onOkResult, mapTypesOptions } = props;
const supportWmsAuthentication = (mapTypesOptions?.supportWmsAuthentication ? true : false);
const getMapUrlFromProps = React.useCallback(() => {
if (props.mapLayerSourceToEdit) {
return props.mapLayerSourceToEdit.url;
} else if (props.layerRequiringCredentials?.url) {
return props.layerRequiringCredentials.url;
}
return "";
}, [props.layerRequiringCredentials, props.mapLayerSourceToEdit]);
const getMapNameFromProps = React.useCallback(() => {
if (props.mapLayerSourceToEdit) {
return props.mapLayerSourceToEdit.name;
} else if (props.layerRequiringCredentials?.name) {
return props.layerRequiringCredentials.name;
}
return "";
}, [props.layerRequiringCredentials, props.mapLayerSourceToEdit]);
const getFormatFromProps = React.useCallback(() => {
if (props.mapLayerSourceToEdit) {
return props.mapLayerSourceToEdit.formatId;
} else if (props.layerRequiringCredentials?.formatId) {
return props.layerRequiringCredentials.formatId;
}
return undefined;
}, [props.layerRequiringCredentials, props.mapLayerSourceToEdit]);
const [dialogTitle] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString(props.layerRequiringCredentials || props.mapLayerSourceToEdit ? "mapLayers:CustomAttach.EditCustomLayer" : "mapLayers:CustomAttach.AttachCustomLayer"));
const [typeLabel] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.Type"));
const [nameLabel] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.Name"));
const [nameInputPlaceHolder] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.NameInputPlaceHolder"));
const [urlLabel] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.URL"));
const [urlInputPlaceHolder] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.UrlInputPlaceHolder"));
const [iTwinSettingsLabel] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.StoreOnITwinSettings"));
const [modelSettingsLabel] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.StoreOnModelSettings"));
const [missingCredentialsLabel] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.MissingCredentials"));
const [invalidCredentialsLabel] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.InvalidCredentials"));
const [serverRequireCredentials, setServerRequireCredentials] = React.useState(props.layerRequiringCredentials ?? false);
const [invalidCredentialsProvided, setInvalidCredentialsProvided] = React.useState(false);
const [layerAttachPending, setLayerAttachPending] = React.useState(false);
const [warningMessage, setWarningMessage] = React.useState(props.layerRequiringCredentials ? missingCredentialsLabel : undefined);
const [mapUrl, setMapUrl] = React.useState(getMapUrlFromProps());
const [mapName, setMapName] = React.useState(getMapNameFromProps());
const [userName, setUserName] = React.useState("");
const [password, setPassword] = React.useState("");
const [noSaveSettingsWarning] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.NoSaveSettingsWarning"));
const [passwordLabel] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:AuthenticationInputs.Password"));
const [passwordRequiredLabel] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:AuthenticationInputs.PasswordRequired"));
const [userNameLabel] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:AuthenticationInputs.Username"));
const [userNameRequiredLabel] = React.useState(MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:AuthenticationInputs.UsernameRequired"));
const [settingsStorage, setSettingsStorageRadio] = React.useState("ITwin");
const [mapType, setMapType] = React.useState(getFormatFromProps() ?? MAP_TYPES.arcGis);
// 'isMounted' is used to prevent any async operation once the hook has been
// unloaded. Otherwise we get a 'Can't perform a React state update on an unmounted component.' warning in the console.
const isMounted = React.useRef(false);
React.useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
const [mapTypes] = React.useState((): SelectOption<string>[] => {
const types = [
{ value: MAP_TYPES.arcGis, label: MAP_TYPES.arcGis },
{ value: MAP_TYPES.wms, label: MAP_TYPES.wms },
{ value: MAP_TYPES.wmts, label: MAP_TYPES.wmts },
];
if (mapTypesOptions?.supportTileUrl)
types.push({ value: MAP_TYPES.tileUrl, label: MAP_TYPES.tileUrl });
return types;
});
const [isSettingsStorageAvailable] = React.useState(props?.activeViewport?.iModel?.iTwinId && props?.activeViewport?.iModel?.iModelId);
// Even though the settings storage is available,
// we don't always want to enable it in the UI.
const [settingsStorageDisabled] = React.useState(!isSettingsStorageAvailable || props.mapLayerSourceToEdit !== undefined || props.layerRequiringCredentials !== undefined);
const isAuthSupported = React.useCallback(() => {
return ((mapType === MAP_TYPES.wms || mapType === MAP_TYPES.wms) && supportWmsAuthentication)
|| mapType === MAP_TYPES.arcGis;
}, [mapType, supportWmsAuthentication]);
// const [layerIdxToEdit] = React.useState((): number | undefined => {
const [layerRequiringCredentialsIdx] = React.useState((): number | undefined => {
if (props.layerRequiringCredentials === undefined || !props.layerRequiringCredentials.name || !props.layerRequiringCredentials.url) {
return undefined;
}
const indexInDisplayStyle = props.activeViewport?.displayStyle.findMapLayerIndexByNameAndUrl(props.layerRequiringCredentials.name, props.layerRequiringCredentials.url, isOverlay);
if (indexInDisplayStyle === undefined || indexInDisplayStyle < 0) {
return undefined;
} else {
return indexInDisplayStyle;
}
});
// Update warning message based on the dialog state and server response
React.useEffect(() => {
if (invalidCredentialsProvided) {
setWarningMessage(invalidCredentialsLabel);
} else if (serverRequireCredentials && (!userName || !password)) {
setWarningMessage(missingCredentialsLabel);
} else {
setWarningMessage(undefined);
}
}, [invalidCredentialsProvided, invalidCredentialsLabel, missingCredentialsLabel, serverRequireCredentials, userName, password, setWarningMessage]);
const handleMapTypeSelection = React.useCallback((newValue: string) => {
setMapType(newValue);
}, [setMapType]);
const handleCancel = React.useCallback(() => {
if (props.onCancelResult) {
props.onCancelResult();
return;
}
ModalDialogManager.closeDialog();
}, [props]);
const onUsernameChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
setUserName(event.target.value);
if (invalidCredentialsProvided)
setInvalidCredentialsProvided(false);
}, [setUserName, invalidCredentialsProvided, setInvalidCredentialsProvided]);
const onPasswordChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
setPassword(event.target.value);
if (invalidCredentialsProvided)
setInvalidCredentialsProvided(false);
}, [setPassword, invalidCredentialsProvided, setInvalidCredentialsProvided]);
const doAttach = React.useCallback(async (source: MapLayerSource): Promise<boolean> => {
// Returns a promise, When true, the dialog should closed
return new Promise<boolean>((resolve, _reject) => {
const vp = props?.activeViewport;
if (vp === undefined || source === undefined) {
resolve(true);
return;
}
const storeOnIModel = "Model" === settingsStorage;
source.validateSource(true).then(async (validation) => {
if (validation.status === MapLayerSourceStatus.Valid
|| validation.status === MapLayerSourceStatus.RequireAuth
|| validation.status === MapLayerSourceStatus.InvalidCredentials) {
const sourceRequireAuth = (validation.status === MapLayerSourceStatus.RequireAuth);
const invalidCredentials = (validation.status === MapLayerSourceStatus.InvalidCredentials);
const closeDialog = !sourceRequireAuth && !invalidCredentials;
resolve(closeDialog);
if (sourceRequireAuth && !serverRequireCredentials) {
setServerRequireCredentials(true);
}
if (invalidCredentials) {
setInvalidCredentialsProvided(true);
return;
} else if (invalidCredentialsProvided) {
setInvalidCredentialsProvided(false); // flag reset
}
if (validation.status === MapLayerSourceStatus.Valid) {
// Attach layer and update settings service (only if editing)
if (layerRequiringCredentialsIdx !== undefined) {
// Update username / password
vp.displayStyle.changeMapLayerProps({
subLayers: validation.subLayers,
}, layerRequiringCredentialsIdx, isOverlay);
vp.displayStyle.changeMapLayerCredentials(layerRequiringCredentialsIdx, isOverlay, source.userName, source.password);
// Reset the provider's status
const provider = vp.getMapLayerImageryProvider(layerRequiringCredentialsIdx, isOverlay);
if (provider && provider.status !== MapLayerImageryProviderStatus.Valid) {
provider.status = MapLayerImageryProviderStatus.Valid;
}
} else {
// Update service settings if storage is available and we are not prompting user for credentials
if (!settingsStorageDisabled && !props.layerRequiringCredentials) {
if (!(await MapLayerSettingsService.storeSourceInSettingsService(source, storeOnIModel, vp.iModel.iTwinId!, vp.iModel.iModelId!)))
return;
}
const layerSettings = source.toLayerSettings(validation.subLayers);
if (layerSettings) {
vp.displayStyle.attachMapLayerSettings(layerSettings, isOverlay, undefined);
const msg = IModelApp.localization.getLocalizedString("mapLayers:Messages.MapLayerAttached", { sourceName: source.name, sourceUrl: source.url });
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, msg));
} else {
const msgError = MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:Messages.MapLayerLayerSettingsConversionError");
const msg = MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.MapLayerAttachError", { error: msgError, sourceUrl: source.url });
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, msg));
}
}
vp.invalidateRenderPlan();
}
if (closeDialog) {
// This handler will close the layer source handler, and therefore the MapUrl dialog.
// don't call it if the dialog needs to remains open.
onOkResult();
}
} else {
const msg = MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.ValidationError");
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, `${msg} ${source.url}`));
resolve(true);
}
resolve(false);
}).catch((error) => {
const msg = MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.MapLayerAttachError", { error, sourceUrl: source.url });
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, msg));
resolve(true);
});
});
}, [props.activeViewport, props.layerRequiringCredentials, settingsStorage, serverRequireCredentials, invalidCredentialsProvided, onOkResult, layerRequiringCredentialsIdx, isOverlay, settingsStorageDisabled]);
const onNameChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
setMapName(event.target.value);
}, [setMapName]);
const onRadioChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
setSettingsStorageRadio(event.target.value);
}, [setSettingsStorageRadio]);
const onUrlChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
setMapUrl(event.target.value);
}, [setMapUrl]);
const handleOk = React.useCallback(() => {
let source: MapLayerSource | undefined;
if (mapUrl && mapName) {
source = MapLayerSource.fromJSON({
url: mapUrl,
name: mapName,
formatId: mapType,
userName,
password,
});
if (source === undefined || props.mapLayerSourceToEdit) {
ModalDialogManager.closeDialog();
if (source === undefined) {
// Close the dialog and inform end user something went wrong.
const msgError = MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:Messages.MapLayerLayerSourceCreationFailed");
const msg = MapLayersUiItemsProvider.localization.getLocalizedString("mapLayers:CustomAttach.MapLayerAttachError", { error: msgError, sourceUrl: mapUrl });
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, msg));
return;
}
// Simply change the source definition in the setting service
if (props.mapLayerSourceToEdit !== undefined) {
const vp = props.activeViewport;
void (async () => {
if (isSettingsStorageAvailable && vp) {
if (!(await MapLayerSettingsService.replaceSourceInSettingsService(props.mapLayerSourceToEdit!, source, vp.iModel.iTwinId!, vp.iModel.iModelId!))) {
const errorMessage = IModelApp.localization.getLocalizedString("mapLayers:Messages.MapLayerEditError", { layerName: props.mapLayerSourceToEdit?.name });
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, errorMessage));
return;
}
}
})();
return;
}
}
setLayerAttachPending(true);
void (async () => {
// Code below is executed in the an async manner but
// I don't necessarily want to mark the handler as async
// so Im wrapping it un in a void wrapper.
try {
const closeDialog = await doAttach(source);
if (isMounted.current) {
setLayerAttachPending(false);
}
// In theory the modal dialog should always get closed by the parent
// AttachLayerPanel's 'onOkResult' handler. We close it here just in case.
if (closeDialog) {
ModalDialogManager.closeDialog();
}
} catch (_error) {
ModalDialogManager.closeDialog();
}
})();
}
}, [mapUrl, mapName, mapType, userName, password, props.mapLayerSourceToEdit, props.activeViewport, isSettingsStorageAvailable, doAttach]);
const dialogContainer = React.useRef<HTMLDivElement>(null);
const readyToSave = React.useCallback(() => {
const credentialsSet = !!userName && !!password;
return (!!mapUrl && !!mapName)
&& (!serverRequireCredentials || (serverRequireCredentials && credentialsSet) && !layerAttachPending)
&& !invalidCredentialsProvided;
}, [mapUrl, mapName, userName, password, layerAttachPending, invalidCredentialsProvided, serverRequireCredentials]);
const buttonCluster = React.useMemo(() => [
{ type: DialogButtonType.OK, onClick: handleOk, disabled: !readyToSave() },
{ type: DialogButtonType.Cancel, onClick: handleCancel },
], [readyToSave, handleCancel, handleOk]);
const handleOnKeyDown = React.useCallback((event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === SpecialKey.Enter) {
if (readyToSave())
handleOk();
}
}, [handleOk, readyToSave]);
return (
<div ref={dialogContainer}>
<Dialog
className="map-layer-url-dialog"
title={dialogTitle}
opened={true}
resizable={true}
movable={true}
modal={true}
buttonCluster={buttonCluster}
onClose={handleCancel}
onEscape={handleCancel}
minHeight={120}
maxWidth={600}
titleStyle={{paddingLeft: "10px"}}
footerStyle={{paddingBottom: "10px", paddingRight: "10px"}}
trapFocus={false}
>
<div className="map-layer-url-dialog-content">
<div className="map-layer-source-url">
<span className="map-layer-source-label">{typeLabel}</span>
<Select
className="map-layer-source-select"
options={mapTypes}
value={mapType}
disabled={props.layerRequiringCredentials !== undefined || props.mapLayerSourceToEdit !== undefined}
onChange={handleMapTypeSelection} />
<span className="map-layer-source-label">{nameLabel}</span>
<Input className="map-layer-source-input" placeholder={nameInputPlaceHolder} onChange={onNameChange} value={mapName} disabled={props.layerRequiringCredentials !== undefined} />
<span className="map-layer-source-label">{urlLabel}</span>
<Input className="map-layer-source-input" placeholder={urlInputPlaceHolder} onKeyPress={handleOnKeyDown} onChange={onUrlChange} disabled={props.mapLayerSourceToEdit !== undefined} value={mapUrl} />
{isAuthSupported() && props.mapLayerSourceToEdit === undefined &&
<>
<span className="map-layer-source-label">{userNameLabel}</span>
<LabeledInput
className="map-layer-source-input"
displayStyle="inline"
placeholder={serverRequireCredentials ? userNameRequiredLabel : userNameLabel}
status={!userName && serverRequireCredentials ? InputStatus.Warning : undefined}
onChange={onUsernameChange} />
<span className="map-layer-source-label">{passwordLabel}</span>
<LabeledInput
className="map-layer-source-input"
displayStyle="inline"
type="password" placeholder={serverRequireCredentials ? passwordRequiredLabel : passwordLabel}
status={!password && serverRequireCredentials ? InputStatus.Warning : undefined}
onChange={onPasswordChange}
onKeyPress={handleOnKeyDown} />
</>
}
{/* Store settings options, not shown when editing a layer */}
{isSettingsStorageAvailable && <div title={settingsStorageDisabled ? noSaveSettingsWarning : ""}>
<Radio disabled={settingsStorageDisabled}
name="settingsStorage" value="iTwin"
label={iTwinSettingsLabel} checked={settingsStorage === "iTwin"}
onChange={onRadioChange} />
<Radio disabled={settingsStorageDisabled}
name="settingsStorage" value="Model"
label={modelSettingsLabel} checked={settingsStorage === "Model"}
onChange={onRadioChange} />
</div>}
</div>
</div>
{/* Warning message */}
<div className="map-layer-source-warnMessage">
{warningMessage ?
<>
<Icon className="map-layer-source-warnMessage-icon" iconSpec="icon-status-warning" />
<span className="map-layer-source-warnMessage-label">{warningMessage}</span >
</>
:
// Place holder to avoid dialog resize
<span className="map-layer-source-placeholder"> </span>
}
</div>
{/* Progress bar */}
{layerAttachPending &&
<div className="map-layer-source-progressBar">
<ProgressLinear indeterminate />
</div>
}
</Dialog>
</div >
);
} | the_stack |
import { ApplicationRef, ChangeDetectorRef, ElementRef, NgZone, QueryList, SimpleChanges } from '@angular/core';
import { fakeAsync, tick } from '@angular/core/testing';
import { deepClone } from '@angular-ru/cdk/object';
import { Any, Fn, Nullable, PlainObject } from '@angular-ru/cdk/typings';
import { NgxColumnComponent, NgxTableViewChangesService, TableBuilderComponent } from '@angular-ru/cdk/virtual-table';
import { WebWorkerThreadService } from '@angular-ru/cdk/webworker';
import { MapToTableEntriesPipe } from '../../../../../../virtual-table/src/pipes/map-to-table-entries.pipe';
import { TableSelectedItemsPipe } from '../../../../../../virtual-table/src/pipes/table-selected-items.pipe';
import { ContextMenuService } from '../../../../../../virtual-table/src/services/context-menu/context-menu.service';
import { DraggableService } from '../../../../../../virtual-table/src/services/draggable/draggable.service';
import { FilterableService } from '../../../../../../virtual-table/src/services/filterable/filterable.service';
import { ResizableService } from '../../../../../../virtual-table/src/services/resizer/resizable.service';
import { SelectionService } from '../../../../../../virtual-table/src/services/selection/selection.service';
import { SortableService } from '../../../../../../virtual-table/src/services/sortable/sortable.service';
import { TemplateParserService } from '../../../../../../virtual-table/src/services/template-parser/template-parser.service';
describe('[TEST]: Lifecycle table', () => {
let table: TableBuilderComponent<PlainObject>;
let sortable: SortableService<PlainObject>;
let draggable: DraggableService<PlainObject>;
let resizeService: ResizableService;
let changes: SimpleChanges;
const mockChangeDetector: Partial<ChangeDetectorRef> = {
detectChanges: (): void => {
// ...
}
};
const appRef: Partial<ApplicationRef> = {
tick: (): void => {
// ...
}
};
const mockNgZone: Partial<NgZone> = {
run: (callback: Fn): Any => callback(),
runOutsideAngular: (callback: Fn): Any => callback()
};
const webWorker: Partial<WebWorkerThreadService> = {
run<T, K>(workerFunction: (input: K) => T, data?: K): Promise<T> {
return Promise.resolve(workerFunction(data!));
}
};
interface PeriodicElement {
name: Nullable<string>;
position: number;
weight: number;
symbol: string;
}
// noinspection DuplicatedCode
const data: PeriodicElement[] = [
{ position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
{ position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
{ position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
{ position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
{ position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
{ position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
{ position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
{ position: 8, name: null, weight: 15.9994, symbol: 'O' },
{ position: 9, name: null, weight: 18.9984, symbol: 'F' },
{ position: 10, name: null, weight: 20.1797, symbol: 'Ne' }
];
beforeEach(() => {
const worker: WebWorkerThreadService = webWorker as WebWorkerThreadService;
const zone: NgZone = mockNgZone as NgZone;
const app: ApplicationRef = appRef as ApplicationRef;
const view: NgxTableViewChangesService = new NgxTableViewChangesService();
const parser: TemplateParserService<PlainObject> = new TemplateParserService();
draggable = new DraggableService(parser);
resizeService = new ResizableService();
// @ts-ignore
sortable = new SortableService(worker, zone);
table = new TableBuilderComponent(mockChangeDetector as ChangeDetectorRef, {
// eslint-disable-next-line complexity
get(token: Any): Any {
switch (token) {
case SelectionService:
return new SelectionService(zone);
case TemplateParserService:
return parser;
case NgZone:
return zone;
case ResizableService:
return resizeService;
case SortableService:
return sortable;
case ContextMenuService:
return new ContextMenuService();
case ApplicationRef:
return app;
case FilterableService:
return new FilterableService({
get(_token: Any): Any {
// eslint-disable-next-line sonarjs/no-nested-switch
switch (_token) {
case ApplicationRef:
return app;
case WebWorkerThreadService:
return worker;
case NgZone:
return zone;
}
}
});
case DraggableService:
return draggable;
case NgxTableViewChangesService:
return view;
}
}
});
const element: HTMLElement = document.createElement('div') as HTMLElement;
Object.defineProperty(element, 'offsetHeight', { value: 900 });
table.scrollContainer = { nativeElement: element };
table.primaryKey = 'position';
changes = {};
table.columnList = new QueryList<ElementRef<HTMLDivElement>>();
});
it('should be basic api', async () => {
table.setSource(deepClone(data));
// eslint-disable-next-line deprecation/deprecation
expect(new TableSelectedItemsPipe(table).transform({ 1: true, 2: true })).toEqual([
{ position: 1, name: 'Hydrogen', symbol: 'H', weight: 1.0079 },
{ position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' }
]);
// expect MapToTableEntriesPipe pipe works
expect(new MapToTableEntriesPipe(table).transform([1, 2])).toEqual([
{ position: 1, name: 'Hydrogen', symbol: 'H', weight: 1.0079 },
{ position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' }
]);
// expect MapToTableEntriesPipe pipe works with another ordering
expect(new MapToTableEntriesPipe(table).transform([2, 1])).toEqual([
{ position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
{ position: 1, name: 'Hydrogen', symbol: 'H', weight: 1.0079 }
]);
// enable and check filter
table.enableFiltering = true;
table.filterable.filterValue = 'Hydrogen';
table.filterable.filterType = 'START_WITH';
await table.sortAndFilter();
expect(table.source).toEqual([{ name: 'Hydrogen', position: 1, symbol: 'H', weight: 1.0079 }]);
// expect selection pipe works even with filtered values
// eslint-disable-next-line deprecation/deprecation
expect(new TableSelectedItemsPipe(table).transform({})).toEqual([]);
// eslint-disable-next-line deprecation/deprecation
expect(new TableSelectedItemsPipe(table).transform({ 1: true, 2: true })).toEqual([
{ position: 1, name: 'Hydrogen', symbol: 'H', weight: 1.0079 },
{ position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' }
]);
expect(table.lastItem).toEqual({ position: 1, name: 'Hydrogen', symbol: 'H', weight: 1.0079 });
// reset filter
table.enableFiltering = true;
table.filterable.filterValue = null;
table.filterable.filterType = null;
await table.sortAndFilter();
expect(table.source).toEqual(data);
expect(table.lastItem).toEqual({ position: 10, name: null, weight: 20.1797, symbol: 'Ne' });
});
it('should be unchecked state before ngOnChange', () => {
table.source = deepClone(data);
expect(table.isRendered).toBe(false);
expect(table.modelColumnKeys).toEqual([]);
expect(table.dirty).toBe(true);
expect(table.rendering).toBe(false);
expect(table.contentInit).toBe(false);
expect(table.displayedColumns).toEqual([]);
expect(table.contentCheck).toBe(false);
expect(table.sourceExists).toBe(true);
});
it('should be correct generate modelColumnKeys after ngOnChange', () => {
table.source = deepClone(data);
table.enableSelection = true;
table.ngOnChanges(changes);
table.ngOnInit();
expect(table.isRendered).toBe(false);
expect(table.modelColumnKeys).toEqual(['position', 'name', 'weight', 'symbol']);
expect(table.dirty).toBe(true);
expect(table.rendering).toBe(false);
expect(table.contentInit).toBe(false);
expect(table.displayedColumns).toEqual([]);
expect(table.contentCheck).toBe(false);
expect(table.sourceExists).toBe(true);
expect(table.selection.primaryKey).toBe('position');
});
it('should be correct state after ngAfterContentInit when source empty', () => {
table.source = null;
table.enableSelection = true;
table.ngOnChanges(changes);
table.ngOnInit();
table.ngAfterContentInit();
expect(table.isRendered).toBe(false);
expect(table.modelColumnKeys).toEqual([]);
expect(table.dirty).toBe(false);
expect(table.rendering).toBe(false);
expect(table.contentInit).toBe(true);
expect(table.displayedColumns).toEqual([]);
expect(table.contentCheck).toBe(false);
expect(table.sourceExists).toBe(false);
});
it('should be correct state after ngAfterContentInit', fakeAsync(() => {
table.source = deepClone(data);
table.ngOnChanges(changes);
table.ngOnInit();
table.ngAfterContentInit();
expect(table.isRendered).toBe(false);
expect(table.modelColumnKeys).toEqual(['position', 'name', 'weight', 'symbol']);
expect(table.dirty).toBe(false);
expect(table.rendering).toBe(false);
expect(table.contentInit).toBe(true);
expect(table.displayedColumns).toEqual([]);
expect(table.contentCheck).toBe(false);
expect(table.sourceExists).toBe(true);
tick(600);
expect(table.rendering).toBe(false);
expect(table.isRendered).toBe(true);
expect(table.positionColumns).toEqual(['position', 'name', 'weight', 'symbol']);
tick(400);
expect(table.rendering).toBe(false);
expect(table.isRendered).toBe(true);
expect(table.positionColumns).toEqual(['position', 'name', 'weight', 'symbol']);
}));
it('should be correct template changes', fakeAsync(() => {
const templates: QueryList<NgxColumnComponent<PlainObject>> = new QueryList();
table.columnTemplates = templates;
table.source = [];
table.ngOnChanges(changes);
table.ngOnInit();
table.ngAfterContentInit();
table.ngAfterViewInit();
expect(table.isRendered).toBe(false);
expect(table.modelColumnKeys).toEqual([]);
expect(table.dirty).toBe(false);
expect(table.rendering).toBe(false);
expect(table.contentInit).toBe(true);
expect(table.displayedColumns).toEqual([]);
expect(table.contentCheck).toBe(false);
expect(table.sourceExists).toBe(false);
table.source = deepClone(data);
templates.reset([new NgxColumnComponent()]);
templates.notifyOnChanges();
tick(1000);
expect(table.isRendered).toBe(false);
expect(table.modelColumnKeys).toEqual([]);
expect(table.dirty).toBe(false);
expect(table.rendering).toBe(false);
expect(table.contentInit).toBe(true);
expect(table.displayedColumns).toEqual([]);
expect(table.contentCheck).toBe(true);
expect(table.sourceExists).toBe(true);
tick(1000);
expect(table.isRendered).toBe(false);
expect(table.afterViewInitDone).toBe(true);
}));
it('should be correct template changes with check renderCount', fakeAsync(() => {
const templates: QueryList<NgxColumnComponent<PlainObject>> = new QueryList();
table.columnTemplates = templates;
table.source = deepClone(data);
table.ngOnChanges(changes);
table.ngOnInit();
table.ngAfterContentInit();
table.ngAfterViewInit();
table.ngAfterViewChecked();
tick(600);
expect(table.afterViewInitDone).toBe(false);
expect(table.isRendered).toBe(true);
expect(table.modelColumnKeys).toEqual(['position', 'name', 'weight', 'symbol']);
expect(table.dirty).toBe(false);
expect(table.rendering).toBe(false);
expect(table.contentInit).toBe(true);
expect(table.displayedColumns).toEqual(['position', 'name', 'weight', 'symbol']);
expect(table.contentCheck).toBe(false);
expect(table.sourceExists).toBe(true);
table.source = deepClone(data);
templates.reset([new NgxColumnComponent()]);
templates.notifyOnChanges();
expect(table.isRendered).toBe(true);
expect(table.modelColumnKeys).toEqual(['position', 'name', 'weight', 'symbol']);
expect(table.dirty).toBe(false);
expect(table.rendering).toBe(false);
expect(table.contentInit).toBe(true);
expect(table.displayedColumns).toEqual(['position', 'name', 'weight', 'symbol']);
expect(table.contentCheck).toBe(true);
expect(table.sourceExists).toBe(true);
templates.reset([new NgxColumnComponent(), new NgxColumnComponent()]);
templates.notifyOnChanges();
table.ngAfterViewChecked();
expect(table.afterViewInitDone).toBe(false);
tick(1000);
expect(table.afterViewInitDone).toBe(true);
}));
it('should be correct template changes query list', fakeAsync(() => {
const templates: QueryList<NgxColumnComponent<PlainObject>> = new QueryList();
table.columnTemplates = templates;
table.source = [];
table.ngOnChanges(changes);
table.ngOnInit();
table.ngAfterContentInit();
table.ngAfterViewInit();
table.ngAfterViewChecked();
templates.reset([new NgxColumnComponent()]);
templates.notifyOnChanges();
table.source = deepClone(data);
table.ngOnChanges(changes);
tick(1000);
expect(table.isRendered).toBe(false);
expect(table.modelColumnKeys).toEqual(['position', 'name', 'weight', 'symbol']);
expect(table.dirty).toBe(false);
expect(table.rendering).toBe(false);
expect(table.contentInit).toBe(true);
expect(table.displayedColumns).toEqual([]);
expect(table.contentCheck).toBe(true);
expect(table.sourceExists).toBe(true);
table.ngAfterViewChecked();
tick(1000);
expect(table.isRendered).toBe(true);
expect(table.modelColumnKeys).toEqual(['position', 'name', 'weight', 'symbol']);
expect(table.dirty).toBe(false);
expect(table.rendering).toBe(false);
expect(table.contentInit).toBe(true);
expect(table.displayedColumns).toEqual(['position', 'name', 'weight', 'symbol']);
expect(table.contentCheck).toBe(false);
expect(table.sourceExists).toBe(true);
}));
it('should be correct ngOnDestroy', () => {
expect(table.destroy$.closed).toBe(false);
// eslint-disable-next-line deprecation/deprecation
expect(table.destroy$.isStopped).toBe(false);
table.ngOnChanges(changes);
table.ngOnInit();
table.ngAfterContentInit();
table.ngAfterViewInit();
table.ngAfterViewChecked();
table.ngOnDestroy();
expect(table.destroy$.closed).toBe(false);
// eslint-disable-next-line deprecation/deprecation
expect(table.destroy$.isStopped).toBe(true);
});
it('should be correct sync rendering', fakeAsync(() => {
table.source = deepClone(data);
table.ngOnChanges(changes);
table.renderTable();
tick(1000);
expect(table.positionColumns).toEqual(['position', 'name', 'weight', 'symbol']);
}));
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.