text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as moment from 'moment';
import { Text } from '@microsoft/sp-core-library';
import { isEmpty } from '@microsoft/sp-lodash-subset';
import { IPersonaProps, ITag } from 'office-ui-fabric-react';
import { IQuerySettings } from '../../webparts/contentQuery/components/IQuerySettings';
import { IQueryFilter } from '../../controls/PropertyPaneQueryFilterPanel/components/QueryFilter/IQueryFilter';
import { QueryFilterOperator } from '../../controls/PropertyPaneQueryFilterPanel/components/QueryFilter/QueryFilterOperator';
import { QueryFilterJoin } from '../../controls/PropertyPaneQueryFilterPanel/components/QueryFilter/QueryFilterJoin';
import { QueryFilterFieldType } from '../../controls/PropertyPaneQueryFilterPanel/components/QueryFilter/QueryFilterFieldType';
export class CamlQueryHelper {
/*************************************************************************************************
* Generates a full CAML query based on the provided IQuerySettings
* @param querySettings : A IQuerySettings object required for generating the CAML query
*************************************************************************************************/
public static generateCamlQuery(querySettings:IQuerySettings): string {
let query = '';
// Generates the <Where /> part
if(querySettings.filters && !isEmpty(querySettings.filters)) {
let sortedFilters = querySettings.filters.sort((a, b) => { return a.index - b.index; });
query += Text.format('<Where>{0}</Where>', this.generateFilters(sortedFilters));
}
// Generates the <OrderBy /> part
if(querySettings.orderBy && !isEmpty(querySettings.orderBy)) {
let isAscending = querySettings.orderByDirection == 'desc' ? 'FALSE' : 'TRUE';
query += Text.format("<OrderBy><FieldRef Name='{0}' Ascending='{1}' /></OrderBy>", querySettings.orderBy, isAscending);
}
// Wraps the <Where /> and <OrderBy /> into a <Query /> tag
query = Text.format('<Query>{0}</Query>', query);
// Generates the <RowLimit /> part
if(querySettings.limitEnabled) {
query += Text.format('<RowLimit>{0}</RowLimit>', querySettings.itemLimit);
}
// Generates the <ViewFields /> part
if(querySettings.viewFields && !isEmpty(querySettings.viewFields)) {
query += Text.format('<ViewFields>{0}</ViewFields>', querySettings.viewFields.map(field => Text.format("<FieldRef Name='{0}' />", field)).join(''));
}
// Wraps the everything into a final <View /> tag
if(querySettings.recursiveEnabled) {
query = Text.format('<View Scope="RecursiveAll">{0}</View>', query);
}
else {
query = Text.format('<View>{0}</View>', query);
}
return query;
}
/*************************************************************************************************
* Generates the CAML filters based on the specified array of IQueryFilter objects
* @param filters : The filters that needs to be converted to a CAML string
*************************************************************************************************/
private static generateFilters(filters:IQueryFilter[]): string {
// Store the generic filter format for later use
let query = '';
let filterXml = '';
// Appends a CAML node for each filter
let itemCount = 0;
for(let filter of filters.reverse()) {
filterXml = '<{0}><FieldRef Name="{1}" /><Value {2} Type="{3}">{4}</Value></{0}>';
itemCount++;
let specialAttribute = '';
// Sets the special attribute if needed
if(filter.field.type == QueryFilterFieldType.Datetime) {
specialAttribute = 'IncludeTimeValue="' + filter.includeTime + '"';
}
// If it's a <IsNull /> or <IsNotNull> filter
if(filter.operator == QueryFilterOperator.IsNull || filter.operator == QueryFilterOperator.IsNotNull) {
filterXml = '<{0}><FieldRef Name="{1}" /></{0}>';
query += Text.format(filterXml, QueryFilterOperator[filter.operator], filter.field.internalName);
}
// If it's a taxonomy filter
else if (filter.field.type == QueryFilterFieldType.Taxonomy) {
query += this.generateTaxonomyFilter(filter);
}
// If it's a user filter
else if (filter.field.type == QueryFilterFieldType.User) {
query += this.generateUserFilter(filter);
}
// If it's any other kind of filter (Text, DateTime, Lookup, Number etc...)
else {
let valueType = (filter.field.type == QueryFilterFieldType.Lookup ? QueryFilterFieldType[QueryFilterFieldType.Text] : QueryFilterFieldType[filter.field.type]);
query += Text.format(filterXml, QueryFilterOperator[filter.operator], filter.field.internalName, specialAttribute, valueType, this.formatFilterValue(filter));
}
// Appends the Join tags if needed
if (itemCount >= 2) {
let logicalJoin = QueryFilterJoin[filter.join];
query = Text.format("<{0}>", logicalJoin) + query;
query += Text.format("</{0}>", logicalJoin);
}
}
return query;
}
/*************************************************************************************************
* Generates a valid CAML filter string based on the specified taxonomy filter
* @param filter : The taxonomy filter that needs to be formatted into a CAML filter string
*************************************************************************************************/
private static generateTaxonomyFilter(filter:IQueryFilter): string
{
let filterOutput = '';
let filterTerms = filter.value as ITag[];
if(isEmpty(filter.value)) {
return '';
}
else if (filter.operator == QueryFilterOperator.ContainsAny || filterTerms == null) {
let values = filterTerms != null ? filterTerms.map(x => Text.format("<Value Type='Integer'>{0}</Value>", x.key)).join('') : '';
filterOutput = Text.format("<In><FieldRef Name='{0}' LookupId='TRUE' /><Values>{1}</Values></In>", filter.field.internalName, values);
}
else if (filter.operator == QueryFilterOperator.ContainsAll) {
let taxFilters: IQueryFilter[] = [];
for(let term of filterTerms) {
let termValue:ITag[] = [ term ];
let taxFilter:IQueryFilter = {
index: null,
field: filter.field,
value: termValue,
join: QueryFilterJoin.And,
operator: QueryFilterOperator.ContainsAny
};
taxFilters.push(taxFilter);
}
filterOutput = this.generateFilters(taxFilters);
}
return filterOutput;
}
/*************************************************************************************************
* Generates a valid CAML filter string based on the specified user filter
* @param filter : The user filter that needs to be formatted into a CAML filter string
*************************************************************************************************/
private static generateUserFilter(filter:IQueryFilter): string
{
let filterOutput = '';
let filterUsers = filter.value as IPersonaProps[];
if(filter.me) {
filterOutput = Text.format("<Eq><FieldRef Name='{0}' /><Value Type='Integer'><UserID /></Value></Eq>", filter.field.internalName);
}
else if(isEmpty(filter.value)) {
return '';
}
else if (filter.operator == QueryFilterOperator.ContainsAny || filterUsers == null)
{
let values = filterUsers != null ? filterUsers.map(x => Text.format("<Value Type='Integer'>{0}</Value>", x.optionalText)).join('') : '';
filterOutput = Text.format("<In><FieldRef Name='{0}' LookupId='TRUE' /><Values>{1}</Values></In>", filter.field.internalName, values);
}
else if (filter.operator == QueryFilterOperator.ContainsAll)
{
let userFilters: IQueryFilter[] = [];
for(let user of filterUsers) {
let userValue:IPersonaProps[] = [ user ];
let userFilter:IQueryFilter = {
index: null,
field: filter.field,
value: userValue,
join: QueryFilterJoin.And,
operator: QueryFilterOperator.ContainsAny
};
userFilters.push(userFilter);
}
filterOutput = this.generateFilters(userFilters);
}
return filterOutput;
}
/*************************************************************************************************
* Returns the value of the specified filter correctly formatted based on its type of value
* @param filter : The filter that needs its value to be formatted
*************************************************************************************************/
private static formatFilterValue(filter:IQueryFilter): string
{
let filterValue = "";
if(filter.field.type == QueryFilterFieldType.Datetime) {
if(filter.expression != null && !isEmpty(filter.expression)) {
filterValue = this.formatDateExpressionFilterValue(filter.expression);
}
else {
filterValue = this.formatDateFilterValue(filter.value as string);
}
}
else {
filterValue = this.formatTextFilterValue(filter.value as string);
}
return filterValue;
}
/*************************************************************************************************
* Converts the specified serialized ISO date into the required string format
* @param dateValue : A valid ISO 8601 date string
*************************************************************************************************/
private static formatDateFilterValue(dateValue:string): string {
let date = moment(dateValue, moment.ISO_8601, true);
if(date.isValid()) {
dateValue = date.format("YYYY-MM-DDTHH:mm:ss\\Z");
}
return dateValue || '';
}
/*************************************************************************************************
* Replaces any "[Today]" or "[Today] +/- [digit]" expression by it's actual value
* @param filterValue : The filter value
*************************************************************************************************/
private static formatDateExpressionFilterValue(filterValue: string): string {
// Replaces any "[Today] +/- [digit]" expression
let regex = new RegExp("\\[Today\\]\\s*[\\+-]\\s*\\[{0,1}\\d{1,}\\]{0,1}");
let results = regex.exec(filterValue);
if(results != null) {
for(let result of results) {
let operator = result.indexOf('+') > 0 ? '+' : '-';
let addOrRemove = operator == '+' ? 1 : -1;
let operatorSplit = result.split(operator);
let digit = parseInt(operatorSplit[operatorSplit.length - 1].replace("[", "").replace("]", "").trim()) * addOrRemove;
let dt = new Date();
dt.setDate(dt.getDate() + digit);
let formatDate = moment(dt).format("YYYY-MM-DDTHH:mm:ss\\Z");
filterValue = filterValue.replace(result, formatDate);
}
}
// Replaces any "[Today]" expression by it's actual value
let formattedDate = moment(new Date()).format("YYYY-MM-DDTHH:mm:ss\\Z");
filterValue = filterValue.replace("[Today]", formattedDate);
return filterValue;
}
/*************************************************************************************************
* Formats the specified text filter value
* @param textValue : The text filter value which needs to be formatted
*************************************************************************************************/
private static formatTextFilterValue(textValue:string): string {
let regex = new RegExp("\\[PageQueryString:[A-Za-z0-9_-]*\\]");
let results = regex.exec(textValue);
if(results != null) {
for(let result of results) {
let parameter = result.substring(17, result.length - 1);
textValue = textValue.replace(result, this.getUrlParameter(parameter));
}
}
return textValue != null ? textValue : '';
}
/*************************************************************************************************
* Returns the value of the query string parameter with the specified name
* @param name : The name of the query string parameter
* @param url : Optionnaly, the specific url to use instead of the current url
*************************************************************************************************/
private static getUrlParameter(name: string, url?: string): string {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
} | the_stack |
import { env } from "./env";
/**
* A custom error type for failed pipeline requests.
*/
export class RecorderError extends Error {
constructor(message: string, public statusCode?: number) {
super(message);
this.name = "RecorderError";
this.statusCode = statusCode;
}
}
export type RecordingState = "started" | "stopped";
/**
* Helper class to manage the recording state to make sure the proxy-tool is not flooded with unintended requests.
*/
export class RecordingStateManager {
private currentState: RecordingState = "stopped";
/**
* validateState
*/
private validateState(nextState: RecordingState) {
if (nextState === "started") {
if (this.state === "started") {
throw new RecorderError("Already started, should not have called start again.");
}
}
if (nextState === "stopped") {
if (this.state === "stopped") {
throw new RecorderError("Already stopped, should not have called stop again.");
}
}
}
public get state(): RecordingState {
return this.currentState;
}
public set state(nextState: RecordingState) {
// Validate state transition
this.validateState(nextState);
this.currentState = nextState;
}
}
/**
* Keywords that should be passed as part of the headers(except for "Reset") to the proxy-tool to be able to leverage the sanitizer.
*
* "x-abstraction-identifier" - header
*/
export type ProxyToolSanitizers =
| "GeneralRegexSanitizer"
| "RemoveHeaderSanitizer"
| "BodyKeySanitizer"
| "BodyRegexSanitizer"
| "ContinuationSanitizer"
| "HeaderRegexSanitizer"
| "OAuthResponseSanitizer"
| "UriRegexSanitizer"
| "UriSubscriptionIdSanitizer"
| "Reset";
/**
* Maps the sanitizer options to the header value expected by the proxy-tool
*
* Keys = Keys of the SanitizerOptions(excluding `connectionStringSanitizers`)
* Values = Keywords that should be passed as part of the headers to the proxy-tool to be able to leverage the sanitizer.
*/
export const sanitizerKeywordMapping: Record<
Exclude<keyof SanitizerOptions, "connectionStringSanitizers">,
ProxyToolSanitizers
> = {
bodyKeySanitizers: "BodyKeySanitizer",
bodyRegexSanitizers: "BodyRegexSanitizer",
continuationSanitizers: "ContinuationSanitizer",
generalRegexSanitizers: "GeneralRegexSanitizer",
headerRegexSanitizers: "HeaderRegexSanitizer",
oAuthResponseSanitizer: "OAuthResponseSanitizer",
removeHeaderSanitizer: "RemoveHeaderSanitizer",
resetSanitizer: "Reset",
uriRegexSanitizers: "UriRegexSanitizer",
uriSubscriptionIdSanitizer: "UriSubscriptionIdSanitizer"
};
/**
* This sanitizer offers a general regex replace across request/response Body, Headers, and URI. For the body, this means regex applying to the raw JSON.
*/
export interface RegexSanitizer {
/**
* The substitution value.
*/
value: string;
/**
* A regex. Can be defined as a simple regex replace OR if groupForReplace is set, a substitution operation.
*/
regex?: string;
/**
* The capture group that needs to be operated upon. Do not set if you're invoking a simple replacement operation.
*/
groupForReplace?: string;
}
/**
* This sanitizer offers regex update of a specific JTokenPath.
*
* EG: "TableName" within a json response body having its value replaced by whatever substitution is offered.
* This simply means that if you are attempting to replace a specific key wholesale, this sanitizer will be simpler
* than configuring a BodyRegexSanitizer that has to match against the full "KeyName": "Value" that is part of the json structure.
*
* Further reading is available [here](https://www.newtonsoft.com/json/help/html/SelectToken.htm#SelectTokenJSONPath).
*
* If the body is NOT a JSON object, this sanitizer will NOT be applied.
*/
interface BodyKeySanitizer extends RegexSanitizer {
/**
* The SelectToken path (which could possibly match multiple entries) that will be used to select JTokens for value replacement.
*/
jsonPath: string;
}
/**
* Can be used for multiple purposes:
*
* 1) To replace a key with a specific value, do not set "regex" value.
* 2) To do a simple regex replace operation, define arguments "key", "value", and "regex"
* 3) To do a targeted substitution of a specific group, define all arguments "key", "value", and "regex"
*/
interface HeaderRegexSanitizer extends RegexSanitizer {
/**
* The name of the header we're operating against.
*/
key: string;
}
/**
* Internally,
* - connection strings are parsed and
* - each part of the connection string is mapped with its corresponding fake value
* - `generalRegexSanitizer` is applied for each of the parts with the real and fake values that are parsed
*/
interface ConnectionStringSanitizer {
/**
* Real connection string with all the secrets
*/
actualConnString?: string;
/**
* Fake connection string - with all the parts of the connection string mapped to fake values
*/
fakeConnString: string;
}
/**
* Test-proxy tool supports "extensions" or "customizations" to the recording experience.
* This means that non-default sanitizations such as the generalized regex find/replace on different parts of the recordings in various ways are possible.
*/
export interface SanitizerOptions {
/**
* This sanitizer offers a general regex replace across request/response Body, Headers, and URI. For the body, this means regex applying to the raw JSON.
*/
generalRegexSanitizers?: RegexSanitizer[];
/**
* Internally,
* - connection strings are parsed and
* - each part of the connection string is mapped with its corresponding fake value
* - `generalRegexSanitizer` is applied for each of the parts with the real and fake values that are parsed
*/
connectionStringSanitizers?: ConnectionStringSanitizer[];
/**
* This sanitizer offers regex replace within a returned body.
*
* Specifically, this means regex applying to the raw JSON.
* If you are attempting to simply replace a specific key, the BodyKeySanitizer is probably the way to go.
*
* Regardless, there are examples present in `recorder-new/test/testProxyTests.spec.ts`.
*/
bodyRegexSanitizers?: RegexSanitizer[];
/**
* This sanitizer offers regex update of a specific JTokenPath.
*
* EG: "TableName" within a json response body having its value replaced by whatever substitution is offered.
* This simply means that if you are attempting to replace a specific key wholesale, this sanitizer will be simpler
* than configuring a BodyRegexSanitizer that has to match against the full "KeyName": "Value" that is part of the json structure.
*
* Further reading is available [here](https://www.newtonsoft.com/json/help/html/SelectToken.htm#SelectTokenJSONPath).
*
* If the body is NOT a JSON object, this sanitizer will NOT be applied.
*/
bodyKeySanitizers?: BodyKeySanitizer[];
/**
* TODO
* Has a bug, not implemented fully.
*/
continuationSanitizers?: Array<{ key: string; method?: string; resetAfterFirst: boolean }>;
/**
* Can be used for multiple purposes:
*
* 1) To replace a key with a specific value, do not set "regex" value.
* 2) To do a simple regex replace operation, define arguments "key", "value", and "regex"
* 3) To do a targeted substitution of a specific group, define all arguments "key", "value", and "regex"
*/
headerRegexSanitizers?: HeaderRegexSanitizer[];
/**
* General use sanitizer for cleaning URIs via regex. Runs a regex replace on the member of your choice.
*/
uriRegexSanitizers?: RegexSanitizer[];
/**
* A simple sanitizer that should be used to clean out one or multiple headers by their key.
* Removes headers from before saving a recording.
*/
removeHeaderSanitizer?: {
/**
* Array of header names.
*/
headersForRemoval: string[];
};
/**
* TODO: To be tested with scenarios, not to be used yet.
*/
oAuthResponseSanitizer?: boolean;
/**
* This sanitizer relies on UriRegexSanitizer to replace real subscriptionIds within a URI w/ a default or configured fake value.
* This sanitizer is targeted using the regex "/subscriptions/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})". This is not a setting that can be changed for this sanitizer. For full regex support, take a look at UriRegexSanitizer. You CAN modify the value that the subscriptionId is replaced WITH however.
*/
uriSubscriptionIdSanitizer?: {
/**
* The fake subscriptionId that will be placed where the real one is in the real request. The default replacement value is "00000000-0000-0000-0000-000000000000".
*/
value: string;
};
/**
* This clears the sanitizers that are added.
*/
resetSanitizer?: boolean;
}
/**
* Used in record and playback modes. No effect in live mode.
*
* Options to be provided as part of the `recorder.start()` call.
*/
export interface RecorderStartOptions {
/**
* Used in record and playback modes. No effect in live mode.
*
* 1. The key-value pairs will be used as the environment variables in playback mode.
* 2. If the env variables are present in the recordings as plain strings, they will be replaced with the provided values in record mode
*/
envSetupForPlayback: Record<string, string>;
/**
* Used in record mode. No effect in playback and live modes.
*
* Generated recordings are updated by the "proxy-tool" based on the sanitizer options provided.
*/
sanitizerOptions?: SanitizerOptions;
}
/**
* Throws error message when the `label` is not defined when it should have been defined in the given mode.
*
* Returns true if the param exists.
*/
export function ensureExistence<T>(thing: T | undefined, label: string): thing is T {
if (!thing) {
throw new RecorderError(
`Something went wrong, ${label} should not have been undefined in "${getTestMode()}" mode.`
);
}
return true; // Since we would throw error if undefined
}
export type TestMode = "record" | "playback" | "live";
/**
* Returns the test mode.
*
* If TEST_MODE is not defined, defaults to playback.
*/
export function getTestMode(): TestMode {
if (isPlaybackMode()) {
return "playback";
}
return env.TEST_MODE as "record" | "live";
}
/** Make a lazy value that can be deferred and only computed once. */
export const once = <T>(make: () => T): (() => T) => {
let value: T;
return () => (value = value ?? make());
};
export function isRecordMode() {
return env.TEST_MODE === "record";
}
export function isLiveMode() {
return env.TEST_MODE === "live";
}
export function isPlaybackMode() {
return !isRecordMode() && !isLiveMode();
}
/**
* Loads the environment variables in both node and browser modes corresponding to the key-value pairs provided.
*
* Example-
*
* Suppose `variables` is { ACCOUNT_NAME: "my_account_name", ACCOUNT_KEY: "fake_secret" },
* `setEnvironmentVariables` loads the ACCOUNT_NAME and ACCOUNT_KEY in the environment accordingly.
*/
export function setEnvironmentVariables(variables: { [key: string]: string }) {
for (const [key, value] of Object.entries(variables)) {
env[key] = value;
}
} | the_stack |
import { StepFunctions } from 'aws-sdk';
import * as setup from './hotswap-test-setup';
let mockUpdateMachineDefinition: (params: StepFunctions.Types.UpdateStateMachineInput) => StepFunctions.Types.UpdateStateMachineOutput;
let hotswapMockSdkProvider: setup.HotswapMockSdkProvider;
beforeEach(() => {
hotswapMockSdkProvider = setup.setupHotswapTests();
mockUpdateMachineDefinition = jest.fn();
hotswapMockSdkProvider.setUpdateStateMachineMock(mockUpdateMachineDefinition);
});
test('returns undefined when a new StateMachine is added to the Stack', async () => {
// GIVEN
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
},
},
},
});
// WHEN
const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact);
// THEN
expect(deployStackResult).toBeUndefined();
});
test('calls the updateStateMachine() API when it receives only a definitionString change without Fn::Join in a state machine', async () => {
// GIVEN
setup.setCurrentCfnStackTemplate({
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: '{ Prop: "old-value" }',
StateMachineName: 'my-machine',
},
},
},
});
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: '{ Prop: "new-value" }',
StateMachineName: 'my-machine',
},
},
},
},
});
// WHEN
const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact);
// THEN
expect(deployStackResult).not.toBeUndefined();
expect(mockUpdateMachineDefinition).toHaveBeenCalledWith({
definition: '{ Prop: "new-value" }',
stateMachineArn: 'arn:aws:states:here:123456789012:stateMachine:my-machine',
});
});
test('calls the updateStateMachine() API when it receives only a definitionString change with Fn::Join in a state machine', async () => {
// GIVEN
setup.setCurrentCfnStackTemplate({
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: {
'Fn::Join': [
'\n',
[
'{',
' "StartAt" : "SuccessState"',
' "States" : {',
' "SuccessState": {',
' "Type": "Pass"',
' "Result": "Success"',
' "End": true',
' }',
' }',
'}',
],
],
},
StateMachineName: 'my-machine',
},
},
},
});
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: {
'Fn::Join': [
'\n',
[
'{',
' "StartAt": "SuccessState",',
' "States": {',
' "SuccessState": {',
' "Type": "Succeed"',
' }',
' }',
'}',
],
],
},
StateMachineName: 'my-machine',
},
},
},
},
});
// WHEN
const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact);
// THEN
expect(deployStackResult).not.toBeUndefined();
expect(mockUpdateMachineDefinition).toHaveBeenCalledWith({
definition: JSON.stringify({
StartAt: 'SuccessState',
States: {
SuccessState: {
Type: 'Succeed',
},
},
}, null, 2),
stateMachineArn: 'arn:aws:states:here:123456789012:stateMachine:my-machine',
});
});
test('calls the updateStateMachine() API when it receives a change to the definitionString in a state machine that has no name', async () => {
// GIVEN
setup.setCurrentCfnStackTemplate({
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: '{ "Prop" : "old-value" }',
},
},
},
});
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: '{ "Prop" : "new-value" }',
},
},
},
},
});
// WHEN
setup.pushStackResourceSummaries(setup.stackSummaryOf('Machine', 'AWS::StepFunctions::StateMachine', 'arn:aws:states:here:123456789012:stateMachine:my-machine'));
const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact);
// THEN
expect(deployStackResult).not.toBeUndefined();
expect(mockUpdateMachineDefinition).toHaveBeenCalledWith({
definition: '{ "Prop" : "new-value" }',
stateMachineArn: 'arn:aws:states:here:123456789012:stateMachine:my-machine',
});
});
test('does not call the updateStateMachine() API when it receives a change to a property that is not the definitionString in a state machine', async () => {
// GIVEN
setup.setCurrentCfnStackTemplate({
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: '{ "Prop" : "old-value" }',
LoggingConfiguration: { // non-definitionString property
IncludeExecutionData: true,
},
},
},
},
});
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: '{ "Prop" : "new-value" }',
LoggingConfiguration: {
IncludeExecutionData: false,
},
},
},
},
},
});
// WHEN
const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact);
// THEN
expect(deployStackResult).toBeUndefined();
expect(mockUpdateMachineDefinition).not.toHaveBeenCalled();
});
test('does not call the updateStateMachine() API when a resource has a DefinitionString property but is not an AWS::StepFunctions::StateMachine is changed', async () => {
// GIVEN
setup.setCurrentCfnStackTemplate({
Resources: {
Machine: {
Type: 'AWS::NotStepFunctions::NotStateMachine',
Properties: {
DefinitionString: '{ Prop: "old-value" }',
},
},
},
});
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Resources: {
Machine: {
Type: 'AWS::NotStepFunctions::NotStateMachine',
Properties: {
DefinitionString: '{ Prop: "new-value" }',
},
},
},
},
});
// WHEN
const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact);
// THEN
expect(deployStackResult).toBeUndefined();
expect(mockUpdateMachineDefinition).not.toHaveBeenCalled();
});
test('can correctly hotswap old style synth changes', async () => {
// GIVEN
setup.setCurrentCfnStackTemplate({
Parameters: { AssetParam1: { Type: 'String' } },
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: { Ref: 'AssetParam1' },
StateMachineName: 'machine-name',
},
},
},
});
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Parameters: { AssetParam2: { Type: String } },
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: { Ref: 'AssetParam2' },
StateMachineName: 'machine-name',
},
},
},
},
});
// WHEN
setup.pushStackResourceSummaries(setup.stackSummaryOf('Machine', 'AWS::StepFunctions::StateMachine', 'arn:aws:states:here:123456789012:stateMachine:my-machine'));
const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact, { AssetParam2: 'asset-param-2' });
// THEN
expect(deployStackResult).not.toBeUndefined();
expect(mockUpdateMachineDefinition).toHaveBeenCalledWith({
definition: 'asset-param-2',
stateMachineArn: 'arn:aws:states:here:123456789012:stateMachine:machine-name',
});
});
test('calls the updateStateMachine() API when it receives a change to the definitionString that uses Attributes in a state machine', async () => {
// GIVEN
setup.setCurrentCfnStackTemplate({
Resources: {
Func: {
Type: 'AWS::Lambda::Function',
},
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: {
'Fn::Join': [
'\n',
[
'{',
' "StartAt" : "SuccessState"',
' "States" : {',
' "SuccessState": {',
' "Type": "Succeed"',
' }',
' }',
'}',
],
],
},
StateMachineName: 'my-machine',
},
},
},
});
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Resources: {
Func: {
Type: 'AWS::Lambda::Function',
},
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: {
'Fn::Join': [
'',
[
'"Resource": ',
{ 'Fn::GetAtt': ['Func', 'Arn'] },
],
],
},
StateMachineName: 'my-machine',
},
},
},
},
});
// WHEN
setup.pushStackResourceSummaries(
setup.stackSummaryOf('Machine', 'AWS::StepFunctions::StateMachine', 'arn:aws:states:here:123456789012:stateMachine:my-machine'),
setup.stackSummaryOf('Func', 'AWS::Lambda::Function', 'my-func'),
);
const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact);
// THEN
expect(deployStackResult).not.toBeUndefined();
expect(mockUpdateMachineDefinition).toHaveBeenCalledWith({
definition: '"Resource": arn:aws:lambda:here:123456789012:function:my-func',
stateMachineArn: 'arn:aws:states:here:123456789012:stateMachine:my-machine',
});
});
test("will not perform a hotswap deployment if it cannot find a Ref target (outside the state machine's name)", async () => {
// GIVEN
setup.setCurrentCfnStackTemplate({
Parameters: {
Param1: { Type: 'String' },
},
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: {
'Fn::Join': [
'',
[
'{ Prop: "old-value" }, ',
'{ "Param" : ',
{ 'Fn::Sub': '${Param1}' },
' }',
],
],
},
},
},
},
});
setup.pushStackResourceSummaries(setup.stackSummaryOf('Machine', 'AWS::StepFunctions::StateMachine', 'my-machine'));
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Parameters: {
Param1: { Type: 'String' },
},
Resources: {
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: {
'Fn::Join': [
'',
[
'{ Prop: "new-value" }, ',
'{ "Param" : ',
{ 'Fn::Sub': '${Param1}' },
' }',
],
],
},
},
},
},
},
});
// THEN
await expect(() =>
hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact),
).rejects.toThrow(/Parameter or resource 'Param1' could not be found for evaluation/);
});
test("will not perform a hotswap deployment if it doesn't know how to handle a specific attribute (outside the state machines's name)", async () => {
// GIVEN
setup.setCurrentCfnStackTemplate({
Resources: {
Bucket: {
Type: 'AWS::S3::Bucket',
},
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: {
'Fn::Join': [
'',
[
'{ Prop: "old-value" }, ',
'{ "S3Bucket" : ',
{ 'Fn::GetAtt': ['Bucket', 'UnknownAttribute'] },
' }',
],
],
},
StateMachineName: 'my-machine',
},
},
},
});
setup.pushStackResourceSummaries(
setup.stackSummaryOf('Machine', 'AWS::StepFunctions::StateMachine', 'arn:aws:states:here:123456789012:stateMachine:my-machine'),
setup.stackSummaryOf('Bucket', 'AWS::S3::Bucket', 'my-bucket'),
);
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Resources: {
Bucket: {
Type: 'AWS::S3::Bucket',
},
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: {
'Fn::Join': [
'',
[
'{ Prop: "new-value" }, ',
'{ "S3Bucket" : ',
{ 'Fn::GetAtt': ['Bucket', 'UnknownAttribute'] },
' }',
],
],
},
StateMachineName: 'my-machine',
},
},
},
},
});
// THEN
await expect(() =>
hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact),
).rejects.toThrow("We don't support the 'UnknownAttribute' attribute of the 'AWS::S3::Bucket' resource. This is a CDK limitation. Please report it at https://github.com/aws/aws-cdk/issues/new/choose");
});
test('knows how to handle attributes of the AWS::Events::EventBus resource', async () => {
// GIVEN
setup.setCurrentCfnStackTemplate({
Resources: {
EventBus: {
Type: 'AWS::Events::EventBus',
Properties: {
Name: 'my-event-bus',
},
},
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: {
'Fn::Join': ['', [
'{"EventBus1Arn":"',
{ 'Fn::GetAtt': ['EventBus', 'Arn'] },
'","EventBus1Name":"',
{ 'Fn::GetAtt': ['EventBus', 'Name'] },
'","EventBus1Ref":"',
{ Ref: 'EventBus' },
'"}',
]],
},
StateMachineName: 'my-machine',
},
},
},
});
setup.pushStackResourceSummaries(
setup.stackSummaryOf('EventBus', 'AWS::Events::EventBus', 'my-event-bus'),
);
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Resources: {
EventBus: {
Type: 'AWS::Events::EventBus',
Properties: {
Name: 'my-event-bus',
},
},
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: {
'Fn::Join': ['', [
'{"EventBus2Arn":"',
{ 'Fn::GetAtt': ['EventBus', 'Arn'] },
'","EventBus2Name":"',
{ 'Fn::GetAtt': ['EventBus', 'Name'] },
'","EventBus2Ref":"',
{ Ref: 'EventBus' },
'"}',
]],
},
StateMachineName: 'my-machine',
},
},
},
},
});
// THEN
const result = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact);
expect(result).not.toBeUndefined();
expect(mockUpdateMachineDefinition).toHaveBeenCalledWith({
stateMachineArn: 'arn:aws:states:here:123456789012:stateMachine:my-machine',
definition: JSON.stringify({
EventBus2Arn: 'arn:aws:events:here:123456789012:event-bus/my-event-bus',
EventBus2Name: 'my-event-bus',
EventBus2Ref: 'my-event-bus',
}),
});
});
test('knows how to handle attributes of the AWS::DynamoDB::Table resource', async () => {
// GIVEN
setup.setCurrentCfnStackTemplate({
Resources: {
Table: {
Type: 'AWS::DynamoDB::Table',
Properties: {
KeySchema: [{
AttributeName: 'name',
KeyType: 'HASH',
}],
AttributeDefinitions: [{
AttributeName: 'name',
AttributeType: 'S',
}],
BillingMode: 'PAY_PER_REQUEST',
},
},
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: '{}',
StateMachineName: 'my-machine',
},
},
},
});
setup.pushStackResourceSummaries(
setup.stackSummaryOf('Table', 'AWS::DynamoDB::Table', 'my-dynamodb-table'),
);
const cdkStackArtifact = setup.cdkStackArtifactOf({
template: {
Resources: {
Table: {
Type: 'AWS::DynamoDB::Table',
Properties: {
KeySchema: [{
AttributeName: 'name',
KeyType: 'HASH',
}],
AttributeDefinitions: [{
AttributeName: 'name',
AttributeType: 'S',
}],
BillingMode: 'PAY_PER_REQUEST',
},
},
Machine: {
Type: 'AWS::StepFunctions::StateMachine',
Properties: {
DefinitionString: {
'Fn::Join': ['', [
'{"TableName":"',
{ Ref: 'Table' },
'","TableArn":"',
{ 'Fn::GetAtt': ['Table', 'Arn'] },
'"}',
]],
},
StateMachineName: 'my-machine',
},
},
},
},
});
// THEN
const result = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact);
expect(result).not.toBeUndefined();
expect(mockUpdateMachineDefinition).toHaveBeenCalledWith({
stateMachineArn: 'arn:aws:states:here:123456789012:stateMachine:my-machine',
definition: JSON.stringify({
TableName: 'my-dynamodb-table',
TableArn: 'arn:aws:dynamodb:here:123456789012:table/my-dynamodb-table',
}),
});
}); | the_stack |
import * as t from '@aws-accelerator/common-types';
import * as c from '@aws-accelerator/config';
export * from '@aws-accelerator/config';
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface CloudWatchDefaultAlarmDefinition extends Omit<c.CloudWatchAlarmsConfig, 'definitions'> {
/**
* Interface definition for Default definition of CloudWatch alarm
* from "CloudWatchAlarmsConfig" excluding definitions
*/
}
export interface ResolvedConfigBase {
/**
* The organizational unit to which this VPC belongs.
*/
ouKey?: string;
/**
* The resolved account key where the VPC should be deployed.
*/
accountKey: string;
}
export interface ResolvedVpcConfig extends ResolvedConfigBase {
/**
* The VPC config to be deployed.
*/
vpcConfig: c.VpcConfig;
/**
* Deployment config
*/
deployments?: c.DeploymentConfig;
}
export interface ResolvedCertificateConfig extends ResolvedConfigBase {
/**
* The certificates config to be deployed.
*/
certificates: c.CertificateConfig[];
}
export interface ResolvedIamConfig extends ResolvedConfigBase {
/**
* The IAM config to be deployed.
*/
iam: c.IamConfig;
}
export interface ResolvedAlbConfig extends ResolvedConfigBase {
/**
* The albs config to be deployed.
*/
albs: (c.AlbConfigType | c.GwlbConfigType)[];
}
export interface ResolvedMadConfig extends ResolvedConfigBase {
/**
* The mad config to be deployed.
*/
mad: c.MadDeploymentConfig;
}
export interface ResolvedRsysLogConfig extends ResolvedConfigBase {
/**
* The rsyslog config to be deployed.
*/
rsyslog: c.RsyslogConfig;
}
export class AcceleratorConfig implements t.TypeOf<typeof c.AcceleratorConfigType> {
readonly 'replacements': c.ReplacementsConfig;
readonly 'global-options': c.GlobalOptionsConfig;
readonly 'mandatory-account-configs': c.AccountsConfig;
readonly 'workload-account-configs': c.AccountsConfig;
readonly 'organizational-units': c.OrganizationalUnitsConfig;
constructor(values: t.TypeOf<typeof c.AcceleratorConfigType>) {
Object.assign(this, values);
}
/**
* @return AccountConfig
*/
getAccountByKey(accountKey: string): c.AccountConfig {
return this['mandatory-account-configs'][accountKey] ?? this['workload-account-configs'][accountKey];
}
/**
* @return [accountKey: string, accountConfig: AccountConfig][]
*/
getMandatoryAccountConfigs(): [string, c.AccountConfig][] {
return Object.entries(this['mandatory-account-configs']);
}
/**
* @return [accountKey: string, accountConfig: AccountConfig][]
*/
getWorkloadAccountConfigs(): [string, c.AccountConfig][] {
return Object.entries(this['workload-account-configs']).filter(([_, value]) => !value.deleted);
}
/**
* @return [accountKey: string, accountConfig: AccountConfig][]
*/
getAccountConfigs(): [string, c.AccountConfig][] {
return [...this.getMandatoryAccountConfigs(), ...this.getWorkloadAccountConfigs()];
}
/**
* @return [accountKey: string, accountConfig: AccountConfig][]
*/
getAccountConfigsForOu(ou: string): [string, c.AccountConfig][] {
return this.getAccountConfigs().filter(([_, accountConfig]) => accountConfig.ou === ou);
}
/**
* @return [accountKey: string, accountConfig: AccountConfig][]
*/
getOrganizationalUnits(): [string, c.OrganizationalUnitConfig][] {
return Object.entries(this['organizational-units']);
}
/**
* @return string // Account Key for Mandatory accounts
*/
getMandatoryAccountKey(accountName: c.MandatoryAccountType): string {
if (accountName === 'master') {
return this['global-options']['aws-org-management'].account;
} else if (accountName === 'central-security') {
return this['global-options']['central-security-services'].account;
} else if (accountName === 'central-operations') {
return this['global-options']['central-operations-services'].account;
} else if (accountName === 'central-log') {
return this['global-options']['central-log-services'].account;
} else {
// Invalid account name
throw new Error(`Invalid Account Type sent to "getMandatoryAccountKey"`);
}
}
/**
* Find all VPC configurations in mandatory accounts, workload accounts and organizational units. VPC configuration in
* organizational units will have the correct `accountKey` based on the `deploy` value of the VPC configuration.
*/
getVpcConfigs(): ResolvedVpcConfig[] {
const vpcConfigs: ResolvedVpcConfig[] = [];
// Add mandatory account VPC configuration first
for (const [accountKey, accountConfig] of this.getMandatoryAccountConfigs()) {
for (const vpcConfig of accountConfig.vpc || []) {
vpcConfigs.push({
accountKey,
vpcConfig,
deployments: accountConfig.deployments,
});
}
}
const prioritizedOus = this.getOrganizationalUnits();
// Sort OUs by OU priority
// Config for mandatory OUs should be first in the list
prioritizedOus.sort(([_, ou1], [__, ou2]) => priorityByOuType(ou1, ou2));
for (const [ouKey, ouConfig] of prioritizedOus) {
for (const vpcConfig of ouConfig.vpc || []) {
const destinationAccountKey = vpcConfig.deploy;
if (destinationAccountKey === 'local') {
// When deploy is 'local' then the VPC should be deployed in all accounts in the OU
for (const [accountKey, accountConfig] of this.getAccountConfigsForOu(ouKey)) {
if (vpcConfig['opt-in']) {
if (!accountConfig['opt-in-vpcs'] || !accountConfig['opt-in-vpcs'].includes(vpcConfig.name)) {
continue;
}
}
vpcConfigs.push({
ouKey,
accountKey,
vpcConfig,
deployments: accountConfig.deployments,
});
}
} else {
// When deploy is not 'local' then the VPC should only be deployed in the given account
vpcConfigs.push({
ouKey,
accountKey: destinationAccountKey,
vpcConfig,
});
}
}
}
// Add workload accounts as they are lower priority
for (const [accountKey, accountConfig] of this.getWorkloadAccountConfigs()) {
for (const vpcConfig of accountConfig.vpc || []) {
vpcConfigs.push({
accountKey,
vpcConfig,
deployments: accountConfig.deployments,
});
}
}
return vpcConfigs;
}
/**
* Find all VPC configurations in mandatory accounts, workload accounts and organizational units. VPC configuration in
* organizational units will have the correct `accountKey` based on the `deploy` value of the VPC configuration.
*/
getVpcConfigs2(): ResolvedVpcConfig[] {
const result: ResolvedVpcConfig[] = [];
for (const [key, config] of this.getAccountAndOuConfigs()) {
const vpcConfigs = config.vpc;
if (!vpcConfigs || vpcConfigs.length === 0) {
continue;
}
if (c.MandatoryAccountConfigType.is(config)) {
for (const vpcConfig of vpcConfigs) {
result.push({
accountKey: key,
vpcConfig,
deployments: config.deployments,
});
}
} else if (c.OrganizationalUnitConfigType.is(config)) {
for (const vpcConfig of vpcConfigs) {
const destinationAccountKey = vpcConfig.deploy;
if (destinationAccountKey === 'local') {
// When deploy is 'local' then the VPC should be deployed in all accounts in the OU
for (const [accountKey, accountConfig] of this.getAccountConfigsForOu(key)) {
result.push({
ouKey: key,
accountKey,
vpcConfig,
deployments: accountConfig.deployments,
});
}
} else {
// When deploy is not 'local' then the VPC should only be deployed in the given account
result.push({
ouKey: key,
accountKey: destinationAccountKey,
vpcConfig,
});
}
}
}
}
return result;
}
/**
* Find all certificate configurations in mandatory accounts, workload accounts and organizational units.
*/
getCertificateConfigs(): ResolvedCertificateConfig[] {
const result: ResolvedCertificateConfig[] = [];
for (const [key, config] of this.getAccountAndOuConfigs()) {
const certificates = config.certificates;
if (!certificates || certificates.length === 0) {
continue;
}
if (c.MandatoryAccountConfigType.is(config)) {
result.push({
accountKey: key,
certificates,
});
} else if (c.OrganizationalUnitConfigType.is(config)) {
for (const [accountKey, _] of this.getAccountConfigsForOu(key)) {
result.push({
ouKey: key,
accountKey,
certificates,
});
}
}
}
return result;
}
/**
* Find all IAM configurations in mandatory accounts, workload accounts and organizational units.
*/
getIamConfigs(): ResolvedIamConfig[] {
const result: ResolvedIamConfig[] = [];
for (const [key, config] of this.getAccountAndOuConfigs()) {
const iam = config.iam;
if (!iam) {
continue;
}
if (c.MandatoryAccountConfigType.is(config)) {
result.push({
accountKey: key,
iam,
});
} else if (c.OrganizationalUnitConfigType.is(config)) {
for (const [accountKey, _] of this.getAccountConfigsForOu(key)) {
result.push({
ouKey: key,
accountKey,
iam,
});
}
}
}
return result;
}
/**
* Find all alb configurations in mandatory accounts, workload accounts and organizational units.
*/
getElbConfigs(): ResolvedAlbConfig[] {
const result: ResolvedAlbConfig[] = [];
for (const [key, config] of this.getAccountAndOuConfigs()) {
const albs = config.alb;
if (!albs || albs.length === 0) {
continue;
}
if (c.MandatoryAccountConfigType.is(config)) {
result.push({
accountKey: key,
albs,
});
} else if (c.OrganizationalUnitConfigType.is(config)) {
for (const [accountKey, _] of this.getAccountConfigsForOu(key)) {
result.push({
ouKey: key,
accountKey,
albs,
});
}
}
}
return result;
}
/**
* Find all mad configurations in mandatory accounts, workload accounts and organizational units.
*/
getMadConfigs(): ResolvedMadConfig[] {
const result: ResolvedMadConfig[] = [];
for (const [key, config] of this.getAccountConfigs()) {
const mad = config.deployments?.mad;
if (!mad) {
continue;
}
result.push({
accountKey: key,
mad,
});
}
return result;
}
/**
* Find all rsyslog configurations in mandatory accounts, workload accounts and organizational units.
*/
getRsysLogConfigs(): ResolvedRsysLogConfig[] {
const result: ResolvedRsysLogConfig[] = [];
for (const [key, config] of this.getAccountConfigs()) {
const rsyslog = config.deployments?.rsyslog;
if (!rsyslog) {
continue;
}
result.push({
accountKey: key,
rsyslog,
});
}
return result;
}
/**
* Iterate all account configs and organizational unit configs in order.
*/
private *getAccountAndOuConfigs(): IterableIterator<[string, c.MandatoryAccountConfig | c.OrganizationalUnitConfig]> {
// Add mandatory account VPC configuration first
for (const [accountKey, accountConfig] of this.getMandatoryAccountConfigs()) {
yield [accountKey, accountConfig];
}
const prioritizedOus = this.getOrganizationalUnits();
// Sort OUs by OU priority
// Config for mandatory OUs should be first in the list
prioritizedOus.sort(([_, ou1], [__, ou2]) => priorityByOuType(ou1, ou2));
for (const [ouKey, ouConfig] of prioritizedOus) {
yield [ouKey, ouConfig];
}
// Add workload accounts as they are lower priority
for (const [accountKey, accountConfig] of this.getWorkloadAccountConfigs()) {
yield [accountKey, accountConfig];
}
}
static fromBuffer(content: Buffer): AcceleratorConfig {
return this.fromString(content.toString());
}
static fromString(content: string): AcceleratorConfig {
return this.fromObject(JSON.parse(content));
}
static fromObject<S>(content: S): AcceleratorConfig {
const values = t.parse(c.AcceleratorConfigType, content);
return new AcceleratorConfig(values);
}
}
function priorityByOuType(ou1: c.OrganizationalUnit, ou2: c.OrganizationalUnit) {
// Mandatory has highest priority
if (ou1.type === 'mandatory') {
return -1;
}
return 1;
}
export class AcceleratorUpdateConfig extends AcceleratorConfig {
'replacements': c.ReplacementsConfig;
'global-options': c.GlobalOptionsConfig;
'mandatory-account-configs': c.AccountsConfig;
'workload-account-configs': c.AccountsConfig;
'organizational-units': c.OrganizationalUnitsConfig;
constructor(values: t.TypeOf<typeof c.AcceleratorConfigType>) {
super(values);
Object.assign(this, values);
}
} | the_stack |
import { LRUCache } from "@here/harp-lrucache";
import * as THREE from "three";
import { Font, FontMetrics } from "./FontCatalog";
import { GlyphData } from "./GlyphData";
import { GlyphClearMaterial, GlyphCopyMaterial } from "./TextMaterials";
/**
* Maximum number of texture atlas pages we can copy from in a single go. This amount is determined
* by the maximum number of texture units available on a pixel shader for all devices:
* https://webglstats.com/webgl/parameter/MAX_TEXTURE_IMAGE_UNITS
*/
const MAX_NUM_COPY_PAGES = 8;
/**
* Maximum texture size supported. This amount is determined by the maximum texture size supported
* for all devices:
* https://webglstats.com/webgl/parameter/MAX_TEXTURE_SIZE
*/
const MAX_TEXTURE_SIZE = 4096;
/**
* @hidden
* Information stored for every entry in a [[GlyphTextureCache]].
*/
export interface GlyphCacheEntry {
glyphData: GlyphData;
location: THREE.Vector2;
}
/**
* @hidden
* Unified glyph SDF bitmap storage for all fonts in a [[FontCatalog]].
* Implemented as an abstraction layer on top of an LRUCache and WebGLRenderTarget.
*/
export class GlyphTextureCache {
private readonly m_cacheWidth: number;
private readonly m_cacheHeight: number;
private readonly m_textureSize: THREE.Vector2;
private readonly m_entryCache: LRUCache<string, GlyphCacheEntry>;
private readonly m_scene: THREE.Scene;
private readonly m_camera: THREE.OrthographicCamera;
private readonly m_rt: THREE.WebGLRenderTarget;
private readonly m_copyTextureSet: Set<THREE.Texture>;
private readonly m_copyTransform: THREE.Matrix3;
private readonly m_copyPositions: THREE.Vector2[];
private m_copyMaterial?: GlyphCopyMaterial;
private m_copyVertexBuffer: THREE.InterleavedBuffer;
private readonly m_copyPositionAttribute: THREE.InterleavedBufferAttribute;
private readonly m_copyUVAttribute: THREE.InterleavedBufferAttribute;
private readonly m_copyGeometry: THREE.BufferGeometry;
private m_copyMesh: THREE.Mesh;
private m_copyGeometryDrawCount: number;
private m_clearMaterial?: GlyphClearMaterial;
private m_clearPositionAttribute: THREE.BufferAttribute;
private readonly m_clearGeometry: THREE.BufferGeometry;
private m_clearMesh: THREE.Mesh;
private m_clearGeometryDrawCount: number;
/**
* Creates a `GlyphTextureCache` object.
*
* @param capacity - Cache's maximum glyph capacity.
* @param entryWidth - Maximum entry width.
* @param entryHeight - Maximum entry height.
*
* @returns New `GlyphTextureCache`.
*/
constructor(
readonly capacity: number,
readonly entryWidth: number,
readonly entryHeight: number
) {
const nRows = Math.floor(Math.sqrt(capacity));
this.m_cacheHeight = nRows * nRows < capacity ? nRows + 1 : nRows;
this.m_cacheWidth = nRows * this.m_cacheHeight < capacity ? nRows + 1 : nRows;
this.m_textureSize = new THREE.Vector2(
this.m_cacheWidth * entryWidth,
this.m_cacheHeight * entryHeight
);
if (this.m_textureSize.y > MAX_TEXTURE_SIZE || this.m_textureSize.x > MAX_TEXTURE_SIZE) {
// eslint-disable-next-line no-console
console.warn(
"GlyphTextureCache texture size (" +
this.m_textureSize.x +
", " +
this.m_textureSize.y +
") exceeds WebGL's widely supported MAX_TEXTURE_SIZE (" +
MAX_TEXTURE_SIZE +
").\n" +
"This could result in rendering errors on some devices.\n" +
"Please consider reducing its capacity or input assets size."
);
}
this.m_entryCache = new LRUCache<string, GlyphCacheEntry>(capacity);
this.initCacheEntries();
this.m_scene = new THREE.Scene();
this.m_camera = new THREE.OrthographicCamera(
0,
this.m_textureSize.x,
this.m_textureSize.y,
0
);
this.m_camera.position.z = 1;
this.m_camera.updateMatrixWorld(false);
this.m_rt = new THREE.WebGLRenderTarget(this.m_textureSize.x, this.m_textureSize.y, {
wrapS: THREE.ClampToEdgeWrapping,
wrapT: THREE.ClampToEdgeWrapping,
depthBuffer: false,
stencilBuffer: false
});
this.m_copyTextureSet = new Set<THREE.Texture>();
this.m_copyTransform = new THREE.Matrix3();
this.m_copyPositions = [];
this.m_copyPositions.push(
new THREE.Vector2(),
new THREE.Vector2(),
new THREE.Vector2(),
new THREE.Vector2()
);
this.m_copyVertexBuffer = new THREE.InterleavedBuffer(new Float32Array(capacity * 20), 5);
this.m_copyVertexBuffer.setUsage(THREE.DynamicDrawUsage);
this.m_copyPositionAttribute = new THREE.InterleavedBufferAttribute(
this.m_copyVertexBuffer,
3,
0
);
this.m_copyUVAttribute = new THREE.InterleavedBufferAttribute(
this.m_copyVertexBuffer,
2,
3
);
this.m_copyGeometry = new THREE.BufferGeometry();
this.m_copyGeometry.setAttribute("position", this.m_copyPositionAttribute);
this.m_copyGeometry.setAttribute("uv", this.m_copyUVAttribute);
const copyIndexBuffer = new THREE.BufferAttribute(new Uint32Array(capacity * 6), 1);
copyIndexBuffer.setUsage(THREE.DynamicDrawUsage);
this.m_copyGeometry.setIndex(copyIndexBuffer);
this.m_copyMesh = new THREE.Mesh(this.m_copyGeometry);
this.m_copyMesh.frustumCulled = false;
this.m_copyGeometryDrawCount = 0;
this.m_clearPositionAttribute = new THREE.BufferAttribute(
new Float32Array(capacity * 8),
2
);
this.m_clearPositionAttribute.setUsage(THREE.DynamicDrawUsage);
this.m_clearGeometry = new THREE.BufferGeometry();
this.m_clearGeometry.setAttribute("position", this.m_clearPositionAttribute);
const clearIndexBuffer = new THREE.BufferAttribute(new Uint32Array(capacity * 6), 1);
clearIndexBuffer.setUsage(THREE.DynamicDrawUsage);
this.m_clearGeometry.setIndex(clearIndexBuffer);
this.m_clearMesh = new THREE.Mesh(this.m_clearGeometry);
this.m_clearMesh.frustumCulled = false;
this.m_clearGeometryDrawCount = 0;
this.m_scene.add(this.m_clearMesh, this.m_copyMesh);
}
/**
* Release all allocated resources.
*/
dispose(): void {
this.m_entryCache.clear();
this.m_scene.remove(this.m_clearMesh, this.m_copyMesh);
this.m_rt.dispose();
this.m_clearMaterial?.dispose();
this.m_copyMaterial?.dispose();
this.m_copyTextureSet.clear();
this.m_clearGeometry.dispose();
this.m_copyGeometry.dispose();
}
/**
* Internal WebGL Texture.
*/
get texture(): THREE.Texture {
return this.m_rt.texture;
}
/**
* Internal WebGL Texture size.
*/
get textureSize(): THREE.Vector2 {
return this.m_textureSize;
}
/**
* Add a new entry to the GlyphTextureCache. If the limit of entries is hit, the least requested
* entry will be replaced.
*
* @param hash - Entry's hash.
* @param glyph - Entry's glyph data.
*/
add(hash: string, glyph: GlyphData): void {
const entry = this.m_entryCache.get(hash);
if (entry !== undefined) {
return;
}
const oldestEntry = this.m_entryCache.oldest;
if (oldestEntry === null) {
throw new Error("GlyphTextureCache is uninitialized!");
}
this.clearCacheEntry(oldestEntry.value);
this.copyGlyphToCache(hash, glyph, oldestEntry.value.location);
}
/**
* Checks if an entry is in the cache.
*
* @param hash - Entry's hash.
*
* @returns Test result.
*/
has(hash: string): boolean {
return this.m_entryCache.has(hash);
}
/**
* Retrieves an entry from the cache.
*
* @param hash - Entry's hash.
*
* @returns Retrieval result.
*/
get(hash: string): GlyphCacheEntry | undefined {
return this.m_entryCache.get(hash);
}
/**
* Clears the internal LRUCache.
*/
clear(): void {
this.m_copyGeometryDrawCount = 0;
this.m_clearGeometryDrawCount = 0;
this.m_entryCache.clear();
this.m_copyTextureSet.clear();
this.initCacheEntries();
}
/**
* Updates the internal WebGLRenderTarget.
* The update will copy the newly introduced glyphs since the previous update.
*
* @param renderer - WebGLRenderer.
*/
update(renderer: THREE.WebGLRenderer): void {
let oldRenderTarget: THREE.RenderTarget | null = null;
const willClearGeometry = this.m_clearGeometryDrawCount > 0;
const willCopyGeometry = this.m_copyGeometryDrawCount > 0;
if (willClearGeometry || willCopyGeometry) {
oldRenderTarget = renderer.getRenderTarget();
renderer.setRenderTarget(this.m_rt);
}
if (willClearGeometry) {
if (!this.m_clearMaterial) {
this.m_clearMaterial = new GlyphClearMaterial({
rendererCapabilities: renderer.capabilities
});
this.m_clearMesh.material = this.m_clearMaterial;
}
if (this.m_clearGeometry.index === null) {
throw new Error("GlyphTextureCache clear geometry index is uninitialized!");
}
this.m_clearPositionAttribute.needsUpdate = true;
this.m_clearPositionAttribute.updateRange.offset = 0;
this.m_clearPositionAttribute.updateRange.count = this.m_clearGeometryDrawCount * 8;
this.m_clearGeometry.index.needsUpdate = true;
this.m_clearGeometry.index.updateRange.offset = 0;
this.m_clearGeometry.index.updateRange.count = this.m_clearGeometryDrawCount * 6;
this.m_clearGeometry.setDrawRange(0, this.m_clearGeometryDrawCount * 6);
this.m_clearMesh.visible = true;
this.m_copyMesh.visible = false;
renderer.render(this.m_scene, this.m_camera);
this.m_clearGeometryDrawCount = 0;
this.m_clearMesh.visible = false;
}
if (willCopyGeometry) {
if (!this.m_copyMaterial) {
this.m_copyMaterial = new GlyphCopyMaterial({
rendererCapabilities: renderer.capabilities
});
this.m_copyMesh.material = this.m_copyMaterial;
}
if (this.m_copyGeometry.index === null) {
throw new Error("GlyphTextureCache copy geometry index is uninitialized!");
}
this.m_copyVertexBuffer.needsUpdate = true;
this.m_copyVertexBuffer.updateRange.offset = 0;
this.m_copyVertexBuffer.updateRange.count = this.m_copyGeometryDrawCount * 20;
this.m_copyGeometry.index.needsUpdate = true;
this.m_copyGeometry.index.updateRange.offset = 0;
this.m_copyGeometry.index.updateRange.count = this.m_copyGeometryDrawCount * 6;
this.m_copyGeometry.setDrawRange(0, this.m_copyGeometryDrawCount * 6);
this.m_copyMesh.visible = true;
const srcPages = Array.from(this.m_copyTextureSet);
const nCopies = Math.ceil(this.m_copyTextureSet.size / MAX_NUM_COPY_PAGES);
for (let copyIndex = 0; copyIndex < nCopies; copyIndex++) {
const pageOffset = copyIndex * MAX_NUM_COPY_PAGES;
this.m_copyMaterial.uniforms.pageOffset.value = pageOffset;
for (let i = 0; i < MAX_NUM_COPY_PAGES; i++) {
const pageIndex = pageOffset + i;
if (pageIndex < this.m_copyTextureSet.size) {
this.m_copyMaterial.uniforms["page" + i].value = srcPages[pageIndex];
}
}
renderer.render(this.m_scene, this.m_camera);
}
this.m_copyTextureSet.clear();
this.m_copyGeometryDrawCount = 0;
}
if (willClearGeometry || willCopyGeometry) {
renderer.setRenderTarget(oldRenderTarget);
}
}
private initCacheEntries() {
const dummyMetrics: FontMetrics = {
size: 0,
distanceRange: 0,
base: 0,
lineHeight: 0,
lineGap: 0,
capHeight: 0,
xHeight: 0
};
const dummyFont: Font = {
name: "",
metrics: dummyMetrics,
charset: ""
};
const dummyGlyphData = new GlyphData(
0,
"",
0,
0,
0,
0,
0,
0,
0,
0,
0,
THREE.Texture.DEFAULT_IMAGE,
dummyFont
);
for (let i = 0; i < this.m_cacheHeight; i++) {
for (let j = 0; j < this.m_cacheWidth; j++) {
const dummyEntry: GlyphCacheEntry = {
glyphData: dummyGlyphData,
location: new THREE.Vector2(j, i)
};
this.m_entryCache.set(`Dummy_${i * this.m_cacheHeight + j}`, dummyEntry);
}
}
}
private copyGlyphToCache(hash: string, glyph: GlyphData, cacheLocation: THREE.Vector2) {
this.m_copyTextureSet.add(glyph.texture);
let copyTextureIndex = 0;
for (const value of this.m_copyTextureSet.values()) {
if (value === glyph.texture) {
break;
}
copyTextureIndex++;
}
glyph.copyIndex = copyTextureIndex;
this.m_copyTransform.set(
1.0,
0.0,
cacheLocation.x * this.entryWidth - glyph.offsetX,
0.0,
1.0,
cacheLocation.y * this.entryHeight - glyph.positions[0].y,
0.0,
0.0,
0.0
);
for (let i = 0; i < 4; ++i) {
this.m_copyPositions[i].set(glyph.positions[i].x, glyph.positions[i].y);
this.m_copyPositions[i].applyMatrix3(this.m_copyTransform);
}
if (this.m_copyGeometryDrawCount >= this.capacity) {
return;
}
const baseVertex = this.m_copyGeometryDrawCount * 4;
const baseIndex = this.m_copyGeometryDrawCount * 6;
for (let i = 0; i < 4; ++i) {
this.m_copyPositionAttribute.setXYZ(
baseVertex + i,
this.m_copyPositions[i].x,
this.m_copyPositions[i].y,
glyph.copyIndex
);
this.m_copyUVAttribute.setXY(
baseVertex + i,
glyph.sourceTextureCoordinates[i].x,
glyph.sourceTextureCoordinates[i].y
);
}
if (this.m_copyGeometry.index === null) {
throw new Error("GlyphTextureCache copy geometry index is uninitialized!");
}
this.m_copyGeometry.index.setX(baseIndex, baseVertex);
this.m_copyGeometry.index.setX(baseIndex + 1, baseVertex + 1);
this.m_copyGeometry.index.setX(baseIndex + 2, baseVertex + 2);
this.m_copyGeometry.index.setX(baseIndex + 3, baseVertex + 2);
this.m_copyGeometry.index.setX(baseIndex + 4, baseVertex + 1);
this.m_copyGeometry.index.setX(baseIndex + 5, baseVertex + 3);
++this.m_copyGeometryDrawCount;
const u0 = this.m_copyPositions[0].x / this.m_textureSize.x;
const v0 = this.m_copyPositions[0].y / this.m_textureSize.y;
const u1 = this.m_copyPositions[3].x / this.m_textureSize.x;
const v1 = this.m_copyPositions[3].y / this.m_textureSize.y;
glyph.dynamicTextureCoordinates[0].set(u0, v0);
glyph.dynamicTextureCoordinates[1].set(u1, v0);
glyph.dynamicTextureCoordinates[2].set(u0, v1);
glyph.dynamicTextureCoordinates[3].set(u1, v1);
glyph.isInCache = true;
this.m_entryCache.set(hash, {
glyphData: glyph,
location: cacheLocation
});
}
private clearCacheEntry(entry: GlyphCacheEntry) {
entry.glyphData.isInCache = false;
this.m_copyPositions[0].set(
entry.location.x * this.entryWidth,
entry.location.y * this.entryHeight
);
this.m_copyPositions[1].set(
(entry.location.x + 1) * this.entryWidth,
entry.location.y * this.entryHeight
);
this.m_copyPositions[2].set(
entry.location.x * this.entryWidth,
(entry.location.y + 1) * this.entryHeight
);
this.m_copyPositions[3].set(
(entry.location.x + 1) * this.entryWidth,
(entry.location.y + 1) * this.entryHeight
);
if (this.m_clearGeometryDrawCount >= this.capacity) {
return;
}
const baseVertex = this.m_clearGeometryDrawCount * 4;
const baseIndex = this.m_clearGeometryDrawCount * 6;
for (let i = 0; i < 4; ++i) {
this.m_clearPositionAttribute.setXY(
baseVertex + i,
this.m_copyPositions[i].x,
this.m_copyPositions[i].y
);
}
if (this.m_clearGeometry.index === null) {
throw new Error("GlyphTextureCache clear geometry index is uninitialized!");
}
this.m_clearGeometry.index.setX(baseIndex, baseVertex);
this.m_clearGeometry.index.setX(baseIndex + 1, baseVertex + 1);
this.m_clearGeometry.index.setX(baseIndex + 2, baseVertex + 2);
this.m_clearGeometry.index.setX(baseIndex + 3, baseVertex + 2);
this.m_clearGeometry.index.setX(baseIndex + 4, baseVertex + 1);
this.m_clearGeometry.index.setX(baseIndex + 5, baseVertex + 3);
++this.m_clearGeometryDrawCount;
}
} | the_stack |
import * as msgpack from "notepack.io";
import * as socketio from "socket.io";
import { Adapter, BroadcastOptions, Room, SocketId } from "socket.io-adapter";
import { PacketType } from "socket.io-parser";
import * as uuid from "uuid";
import { promiseTimeout } from "@fluidframework/server-services-client";
export interface ISocketIoRedisConnection {
publish(channel: string, message: string): Promise<void>;
}
export interface ISocketIoRedisSubscriptionConnection extends ISocketIoRedisConnection {
subscribe(
channels: string | string[],
callback: (channel: string, messageBuffer: Buffer) => void,
forceSubscribe?: boolean): Promise<void>;
unsubscribe(channels: string | string[]): Promise<void>;
isSubscribed(channel: string): boolean;
}
export interface ISocketIoRedisOptions {
// the connection used for publishing messages
pubConnection: ISocketIoRedisConnection;
// the connection used for subscriptions
subConnection: ISocketIoRedisSubscriptionConnection;
// when set, enables per room health checks. messages are periodically published
healthChecks?: {
// how often to health check each room in milliseconds
interval: number,
// how long to wait for a health check to complete before failing it in milliseconds
timeout: number;
// determines if the adapter should resubscribe to the room if a health check fails
resubscribeOnFailure: boolean;
// called when a health check succeeds or fails. useful for telemetry purposes
onHealthCheck?(callerId: string, startTime: number, error?: any): void;
};
// called when receiving a message. useful for telemetry purposes
onReceive?(channel: string, startTime: number, packet: any, error?: any): void;
}
/**
* Custom version of the socket.io-redis adapter
* Differences between this and socket.io-redis:
* - Creates per room subscriptions which significantly reduces Redis server load for
* Fluid scenarios when running a large amount of Fluid frontend servers.
* - Contains a health checker that verifies each room is works *
* - Optionally disables rooms for the default "/" namespace to reduce memory usage
* (https://github.com/socketio/socket.io/issues/3089)
* - Callbacks for telemetry logging
* The Redis pubsub channels are compatible with socket.io-redis
* References:
* - https://github.com/socketio/socket.io-redis
* - https://github.com/socketio/socket.io-emitter
* - https://github.com/socketio/socket.io-adapter
*/
export class RedisSocketIoAdapter extends Adapter {
private static options: ISocketIoRedisOptions;
private static shouldDisableDefaultNamespace: boolean;
/**
* Map of room id to socket ids
* Shows what sockets are in a given room
*/
public rooms: Map<Room, Set<SocketId>> = new Map();
/**
* Map of socket id to room ids
* Shows what rooms the given socket is id
*/
public sids: Map<SocketId, Set<Room>> = new Map();
private _uniqueRoomCount = 0;
private readonly uid: string;
private readonly channel: string;
private readonly pendingHealthChecks: Map<string, () => void> = new Map();
private readonly roomHealthCheckTimeoutIds: Map<string, NodeJS.Timeout> = new Map();
/**
* Set the Redis connections to use
*/
public static setup(options: ISocketIoRedisOptions, shouldDisableDefaultNamespace?: boolean) {
this.options = options;
this.shouldDisableDefaultNamespace = shouldDisableDefaultNamespace ?? false;
}
constructor(public readonly nsp: socketio.Namespace) {
super(nsp);
// todo: better id here?
this.uid = uuid.v4().substring(0, 6);
this.channel = `socket.io#${nsp.name}#`;
}
/**
* Check if this instance is connected to the default socket io namespace
*/
public get isDefaultNamespaceAndDisable() {
return RedisSocketIoAdapter.shouldDisableDefaultNamespace && this.nsp.name === "/";
}
/**
* Returns the number of unique rooms (not including built in user rooms)
*/
public get uniqueRoomCount() {
return this._uniqueRoomCount;
}
/**
* Gets a list of sockets by sid.
*/
public async sockets(rooms: Set<Room>): Promise<Set<SocketId>> {
const sids = new Set<SocketId>();
if (rooms.size) {
for (const room of rooms) {
const roomSockets = this.rooms.get(room);
if (roomSockets) {
for (const id of roomSockets) {
if (this.nsp.sockets.has(id)) {
sids.add(id);
}
}
}
}
} else {
for (const id of this.sids.keys()) {
if (this.nsp.sockets.has(id)) {
sids.add(id);
}
}
}
return sids;
}
/**
* Gets the list of rooms a given socket has joined.
*/
public socketRooms(id: SocketId): Set<Room> | undefined {
return this.sids.get(id);
}
/**
* Add a socket to a list of rooms
*/
public async addAll(socketId: SocketId, roomIds: Set<Room>): Promise<void> {
if (!this.isDefaultNamespaceAndDisable) {
const newRooms: Room[] = [];
for (const roomId of roomIds) {
let socketRooms = this.sids.get(socketId);
if (!socketRooms) {
socketRooms = new Set();
this.sids.set(socketId, socketRooms);
}
socketRooms.add(roomId);
let roomSocketIds = this.rooms.get(roomId);
if (!roomSocketIds) {
roomSocketIds = new Set();
this.rooms.set(roomId, roomSocketIds);
// don't count the built in user rooms
if (socketId !== roomId) {
this._uniqueRoomCount++;
newRooms.push(roomId);
}
}
roomSocketIds.add(socketId);
}
if (newRooms.length > 0) {
// subscribe to the new rooms
await this.subscribeToRooms(newRooms);
}
}
}
/**
* Removes a socket from a room
*/
public async del(socketId: SocketId, roomId: Room): Promise<void> {
if (!this.isDefaultNamespaceAndDisable) {
this.sids.get(socketId)?.delete(roomId);
const shouldUnsubscribe = this.removeFromRoom(socketId, roomId);
if (shouldUnsubscribe) {
// don't delay socket removal due to the redis subscription
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.unsubscribeFromRooms([roomId]);
}
}
}
/**
* Removes a socket
*/
public async delAll(socketId: SocketId): Promise<void> {
if (!this.isDefaultNamespaceAndDisable) {
const rooms = this.sids.get(socketId);
if (rooms) {
const unsubscribeRooms = [];
for (const roomId of rooms) {
const shouldUnsubscribe = this.removeFromRoom(socketId, roomId);
if (shouldUnsubscribe) {
unsubscribeRooms.push(roomId);
}
}
if (unsubscribeRooms.length > 0) {
// don't delay socket removal due to the redis subscription
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.unsubscribeFromRooms(unsubscribeRooms);
}
this.sids.delete(socketId);
}
}
}
/**
* Broadcast packets
*/
public broadcast(packet: any, opts: BroadcastOptions): void {
if (this.isDefaultNamespaceAndDisable) {
return;
}
if (opts.rooms.size !== 1) {
// block full broadcasts and multi room broadcasts
return;
}
super.broadcast(packet, opts);
this.publish(packet, opts);
}
/**
* Publishes the packet to Redis
*/
private publish(packet: any, opts: BroadcastOptions) {
// include the room in the channel name
const channel = `${this.channel}${opts.rooms.values().next().value}#`;
// don't provide any "opts"
const msg = msgpack.encode([this.uid, packet]);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
RedisSocketIoAdapter.options.pubConnection.publish(channel, msg);
}
/**
* Handles messages from the Redis subscription
*/
private onRoomMessage(channel: string, messageBuffer: Buffer) {
if (!channel.startsWith(this.channel)) {
// sent to different channel
return;
}
const room = channel.slice(this.channel.length, -1);
if (room !== "" && !this.rooms.has(room)) {
// ignore unknown room
return;
}
const args = msgpack.decode(messageBuffer);
const messageUid = args.shift();
let packet = args[0];
const isHealthCheckPacket = typeof (packet) === "string";
if (this.uid === messageUid) {
if (isHealthCheckPacket) {
// this is a health check packet sent to the per room subscription
// the message was sent by this server to itself for the health check. complete the health check now
this.pendingHealthChecks.get(packet)?.();
}
return;
} else if (isHealthCheckPacket) {
// ignore health check packets sent by other servers
return;
}
const startTime = Date.now();
try {
if (packet) {
if (packet.data === undefined) {
// the data is the packet itself
// recreate the packet object
packet = {
data: packet,
};
}
if (packet.nsp === undefined) {
// default to this namespace
// the packet namespace is in the channel name
packet.nsp = this.nsp.name;
}
if (packet.type === undefined) {
// default to a normal socketio event
packet.type = PacketType.EVENT;
}
}
if (!packet || packet.nsp !== this.nsp.name) {
// ignoring different namespace
throw new Error(`Invalid namespace. ${packet.nsp} !== ${this.nsp.name}`);
}
const opts: BroadcastOptions = {
rooms: new Set([room]),
};
// only allow room broadcasts
super.broadcast(packet, opts);
if (RedisSocketIoAdapter.options.onReceive) {
RedisSocketIoAdapter.options.onReceive(channel, startTime, packet);
}
} catch (ex) {
if (RedisSocketIoAdapter.options.onReceive) {
RedisSocketIoAdapter.options.onReceive(channel, startTime, packet, ex);
}
}
}
/**
* Removes a socket from the room
*/
private removeFromRoom(socketId: string, roomId: string) {
const roomSocketIds = this.rooms.get(roomId);
if (roomSocketIds) {
roomSocketIds.delete(socketId);
if (roomSocketIds.size === 0) {
this.rooms.delete(roomId);
// don't count the built in user rooms
if (socketId !== roomId) {
this._uniqueRoomCount--;
return true;
}
}
}
return false;
}
/**
* Subscribes to the rooms and starts the health checkers
*/
private async subscribeToRooms(rooms: string[]) {
await RedisSocketIoAdapter.options.subConnection.subscribe(
this.getChannelNames(rooms),
this.onRoomMessage.bind(this), true);
for (const room of rooms) {
this.queueRoomHealthCheck(room);
}
}
/**
* Unsubscribes to the rooms and clears the health checkers
*/
private async unsubscribeFromRooms(rooms: string[]) {
await RedisSocketIoAdapter.options.subConnection.unsubscribe(this.getChannelNames(rooms));
for (const room of rooms) {
this.clearRoomHealthCheckTimeout(room);
}
}
private getChannelNames(rooms: string[]) {
return rooms.map((room) => `${this.channel}${room}#`);
}
/**
* Queues a future health check
*/
private queueRoomHealthCheck(room: string) {
this.clearRoomHealthCheckTimeout(room);
if (!RedisSocketIoAdapter.options.healthChecks ||
!RedisSocketIoAdapter.options.subConnection.isSubscribed(room)) {
return;
}
const timeoutId = setTimeout(
// eslint-disable-next-line @typescript-eslint/no-misused-promises
async () => {
return this.runRoomHealthCheck(room);
},
RedisSocketIoAdapter.options.healthChecks.interval);
this.roomHealthCheckTimeoutIds.set(room, timeoutId);
}
/**
* Runs a health check
* It will publish a message over the pub connection and wait until it receives it
*/
private async runRoomHealthCheck(room: string) {
const healthCheckId = uuid.v4();
const startTime = Date.now();
const callerId = `${room},${healthCheckId}`;
try {
const msg = msgpack.encode([this.uid, healthCheckId]);
const healthCheckPromise = new Promise<void>((resolve) => {
this.pendingHealthChecks.set(healthCheckId, resolve);
});
// tslint:disable-next-line: no-floating-promises
await RedisSocketIoAdapter.options.pubConnection.publish(`${this.channel}${room}#`, msg);
await promiseTimeout(RedisSocketIoAdapter.options.healthChecks.timeout, healthCheckPromise);
if (RedisSocketIoAdapter.options.healthChecks.onHealthCheck) {
RedisSocketIoAdapter.options.healthChecks.onHealthCheck(callerId, startTime);
}
} catch (ex) {
if (RedisSocketIoAdapter.options.healthChecks.onHealthCheck) {
RedisSocketIoAdapter.options.healthChecks.onHealthCheck(callerId, startTime, ex);
}
if (RedisSocketIoAdapter.options.healthChecks.resubscribeOnFailure) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.subscribeToRooms([room]);
}
} finally {
this.pendingHealthChecks.delete(healthCheckId);
}
// queue a health check even though we are not currrently subscribed
// the fact that this health check timer is still running means we still want to be subscribed to the room
// likely caused by a redis disconnection & a reconnection is in progress
this.queueRoomHealthCheck(room);
}
/**
* Clears the health check timeout
*/
private clearRoomHealthCheckTimeout(room: string) {
const timeoutId = this.roomHealthCheckTimeoutIds.get(room);
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
this.roomHealthCheckTimeoutIds.delete(room);
}
}
} | the_stack |
import React, { useEffect, useRef } from 'react'
import { useValues, useActions, BindLogic } from 'kea'
import { decodeParams } from 'kea-router'
import { Button, Spin, Space, Badge, Switch, Row } from 'antd'
import { Link } from 'lib/components/Link'
import { sessionsTableLogic } from 'scenes/sessions/sessionsTableLogic'
import { humanFriendlyDetailedTime, stripHTTP, pluralize, humanFriendlyDuration } from '~/lib/utils'
import { SessionDetails } from './SessionDetails'
import dayjs from 'dayjs'
import { SessionType } from '~/types'
import {
CaretLeftOutlined,
CaretRightOutlined,
PoweroffOutlined,
QuestionCircleOutlined,
PlayCircleOutlined,
} from '@ant-design/icons'
import { SessionRecordingsButton, sessionPlayerUrl } from './SessionRecordingsButton'
import { LinkButton } from 'lib/components/LinkButton'
import { SessionsFilterBox } from 'scenes/sessions/filters/SessionsFilterBox'
import { EditFiltersPanel } from 'scenes/sessions/filters/EditFiltersPanel'
import { SearchAllBox } from 'scenes/sessions/filters/SearchAllBox'
import { Tooltip } from 'lib/components/Tooltip'
import dayjsGenerateConfig from 'rc-picker/lib/generate/dayjs'
import generatePicker from 'antd/es/date-picker/generatePicker'
import { ResizableTable, ResizableColumnType, ANTD_EXPAND_BUTTON_WIDTH } from 'lib/components/ResizableTable'
import { teamLogic } from 'scenes/teamLogic'
import { IconEventsShort } from 'lib/components/icons'
import { ExpandIcon } from 'lib/components/ExpandIcon'
import { urls } from 'scenes/urls'
import { SessionPlayerDrawer } from 'scenes/session-recordings/SessionPlayerDrawer'
import { RecordingWatchedSource } from 'lib/utils/eventUsageLogic'
const DatePicker = generatePicker<dayjs.Dayjs>(dayjsGenerateConfig)
interface SessionsTableProps {
personIds?: string[]
isPersonPage?: boolean
}
function getSessionRecordingsDurationSum(session: SessionType): number {
return session.session_recordings.map(({ recording_duration }) => recording_duration).reduce((a, b) => a + b, 0)
}
export const MATCHING_EVENT_ICON_SIZE = 26
export function SessionsView({ personIds, isPersonPage = false }: SessionsTableProps): JSX.Element {
const logic = sessionsTableLogic({ personIds })
const {
sessions,
sessionsLoading,
pagination,
isLoadingNext,
selectedDate,
properties,
sessionRecordingId,
firstRecordingId,
expandedRowKeysProps,
showOnlyMatches,
filters,
} = useValues(logic)
const {
fetchNextSessions,
previousDay,
nextDay,
setFilters,
applyFilters,
onExpandedRowsChange,
setShowOnlyMatches,
closeSessionPlayer,
} = useActions(logic)
const { currentTeam } = useValues(teamLogic)
const sessionsTableRef = useRef<HTMLInputElement>(null)
const columns: ResizableColumnType<SessionType>[] = [
{
title: 'Person',
key: 'person',
render: function RenderSession(session: SessionType) {
return (
<Link to={`/person/${encodeURIComponent(session.distinct_id)}`} className="ph-no-capture">
{session?.email || session.distinct_id}
</Link>
)
},
ellipsis: true,
span: 3,
},
{
title: 'Session duration',
render: function RenderDuration(session: SessionType) {
if (session.session_recordings.length > 0) {
const seconds = getSessionRecordingsDurationSum(session)
return <span>{humanFriendlyDuration(Math.max(seconds, session.length))}</span>
}
return <span>{humanFriendlyDuration(session.length)}</span>
},
span: 3,
},
{
title: 'Start time',
render: function RenderStartTime(session: SessionType) {
return humanFriendlyDetailedTime(session.start_time)
},
span: 3,
},
{
title: 'Start point',
render: function RenderStartPoint(session: SessionType) {
return session.start_url ? stripHTTP(session.start_url) : 'N/A'
},
ellipsis: true,
span: 4,
},
{
title: 'End point',
render: function RenderEndPoint(session: SessionType) {
return session.end_url ? stripHTTP(session.end_url) : 'N/A'
},
ellipsis: true,
span: 4,
},
{
title: (
<Tooltip
title={
currentTeam?.session_recording_opt_in
? 'Replay sessions as if you were right next to your users.'
: 'Recordings is turned off for this project. Click to go to settings.'
}
delayMs={0}
>
<span style={{ whiteSpace: 'nowrap' }}>
{currentTeam?.session_recording_opt_in ? (
<>
Recordings
<QuestionCircleOutlined className="info-indicator" />
</>
) : (
<Link to={urls.projectSettings() + '#session-recording'} style={{ color: 'inherit' }}>
Recordings
<PoweroffOutlined className="info-indicator" />
</Link>
)}
</span>
</Tooltip>
),
render: function RenderEndPoint(session: SessionType) {
return session.session_recordings.length ? (
<SessionRecordingsButton
sessionRecordings={session.session_recordings}
source={RecordingWatchedSource.SessionsList}
/>
) : null
},
span: 4,
defaultWidth: 184,
},
]
useEffect(() => {
// scroll to sessions table if filters are defined in url from the get go
if (decodeParams(window.location.hash)?.['#backTo'] === 'Insights' && sessionsTableRef.current) {
sessionsTableRef.current.scrollIntoView({ behavior: 'smooth' })
}
}, [])
return (
<div className="events" data-attr="events-table">
<Space className="mb-05">
<Button onClick={previousDay} icon={<CaretLeftOutlined />} data-attr="sessions-prev-date" />
<DatePicker
value={selectedDate}
onChange={(date) => setFilters(properties, date)}
allowClear={false}
data-attr="sessions-date-picker"
/>
<Button onClick={nextDay} icon={<CaretRightOutlined />} data-attr="sessions-next-date" />
</Space>
<SearchAllBox />
<SessionsFilterBox selector="new" />
<BindLogic logic={sessionsTableLogic} props={{ personIds }}>
<EditFiltersPanel onSubmit={applyFilters} />
</BindLogic>
{/* scroll to */}
<div ref={sessionsTableRef} />
<div className="sessions-view-actions">
<div className="sessions-view-actions-left-items">
{filters.length > 0 && (
<Row className="action ml-05">
<Switch
// @ts-expect-error `id` prop is valid on switch
id="show-only-matches"
onChange={setShowOnlyMatches}
checked={showOnlyMatches}
/>
<label className="ml-025" htmlFor="show-only-matches">
<b>Show only event matches</b>
</label>
</Row>
)}
</div>
<div className="sessions-view-actions-right-items">
<Tooltip
title={
firstRecordingId === null
? 'No recordings found for this date.'
: currentTeam?.session_recording_opt_in
? 'Play all recordings found for this date.'
: 'Recordings is turned off for this project. Enable in Project Settings.'
}
>
<LinkButton
to={
firstRecordingId
? sessionPlayerUrl(firstRecordingId, RecordingWatchedSource.SessionsListPlayAll)
: '#'
}
type="primary"
data-attr="play-all-recordings"
disabled={firstRecordingId === null} // We allow playback of previously recorded sessions even if new recordings are disabled
icon={<PlayCircleOutlined />}
>
Play all
</LinkButton>
</Tooltip>
</div>
</div>
<ResizableTable
locale={{
emptyText: selectedDate
? `No Sessions on ${selectedDate.format(
selectedDate.year() == dayjs().year() ? 'MMM D' : 'MMM D, YYYY'
)}`
: 'No Sessions',
}}
data-attr="sessions-table"
size="small"
rowKey="global_session_id"
pagination={{ pageSize: 99999, hideOnSinglePage: true }}
rowClassName="cursor-pointer"
dataSource={sessions}
columns={columns}
loading={sessionsLoading}
expandable={{
expandedRowRender: function renderExpand(session) {
return (
<BindLogic logic={sessionsTableLogic} props={{ personIds }}>
<SessionDetails key={session.global_session_id} session={session} />
</BindLogic>
)
},
expandIcon: function _renderExpandIcon(expandProps) {
const { record: session } = expandProps
return (
<ExpandIcon {...expandProps}>
{session?.matching_events?.length > 0 ? (
<Tooltip
title={`${pluralize(session.matching_events.length, 'event')} ${pluralize(
session.matching_events.length,
'matches',
'match',
false
)} your event filters.`}
>
<Badge
className="sessions-matching-events-icon cursor-pointer"
count={<span className="badge-text">{session.matching_events.length}</span>}
offset={[0, MATCHING_EVENT_ICON_SIZE]}
size="small"
>
<IconEventsShort size={MATCHING_EVENT_ICON_SIZE} />
</Badge>
</Tooltip>
) : (
<></>
)}
</ExpandIcon>
)
},
columnWidth: ANTD_EXPAND_BUTTON_WIDTH + MATCHING_EVENT_ICON_SIZE,
rowExpandable: () => true,
onExpandedRowsChange: onExpandedRowsChange,
expandRowByClick: true,
...expandedRowKeysProps,
}}
/>
{!!sessionRecordingId && <SessionPlayerDrawer isPersonPage={isPersonPage} onClose={closeSessionPlayer} />}
<div style={{ marginTop: '5rem' }} />
<div
style={{
margin: '2rem auto 5rem',
textAlign: 'center',
}}
>
{(pagination || isLoadingNext) && (
<Button type="primary" onClick={fetchNextSessions} data-attr="load-more-sessions">
{isLoadingNext ? <Spin> </Spin> : 'Load more sessions'}
</Button>
)}
</div>
</div>
)
} | the_stack |
import { describe, it, expect } from "@jest/globals";
import { NamedNode, Literal, BlankNode } from "@rdfjs/types";
import { DataFactory } from "n3";
import { IriString, Thing, UrlString } from "../interfaces";
import {
getUrl,
getBoolean,
getDatetime,
getDate,
getTime,
getDecimal,
getInteger,
getStringEnglish,
getStringWithLocale,
getStringNoLocale,
getLiteral,
getNamedNode,
getUrlAll,
getBooleanAll,
getDatetimeAll,
getDateAll,
getTimeAll,
getDecimalAll,
getIntegerAll,
getStringEnglishAll,
getStringWithLocaleAll,
getStringByLocaleAll,
getStringNoLocaleAll,
getLiteralAll,
getNamedNodeAll,
getTerm,
getTermAll,
getIriAll,
getPropertyAll,
} from "./get";
import { xmlSchemaTypes } from "../datatypes";
import { createThing, ValidPropertyUrlExpectedError } from "./thing";
import { mockThingFrom } from "./mock";
import { localNodeSkolemPrefix } from "../rdf.internal";
import { addStringNoLocale } from "./add";
import { removeStringNoLocale } from "./remove";
const SUBJECT = "https://arbitrary.vocab/subject";
const PREDICATE = "https://some.vocab/predicate";
function getMockThingWithLiteralFor(
predicate: IriString,
literalValue: string,
literalType:
| "string"
| "integer"
| "decimal"
| "boolean"
| "dateTime"
| "date"
| "time"
): Thing {
return {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
[predicate]: {
literals: {
[`http://www.w3.org/2001/XMLSchema#${literalType}`]: [literalValue],
},
},
},
};
}
function getMockThingWithLiteralsFor(
predicate: IriString,
literal1Value: string,
literal2Value: string,
literalType:
| "string"
| "integer"
| "decimal"
| "boolean"
| "dateTime"
| "date"
| "time"
): Thing {
return {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
[predicate]: {
literals: {
[`http://www.w3.org/2001/XMLSchema#${literalType}`]: [
literal1Value,
literal2Value,
],
},
},
},
};
}
describe("getPropertyAll", () => {
it("returns all Properties for which a value is defined", () => {
const mockThing = getMockThingWithLiteralsFor(
"https://some.vocab/predicate1",
"value1",
"value2",
"string"
);
expect(getPropertyAll(mockThing)).toStrictEqual([
"https://some.vocab/predicate1",
]);
});
it("returns all Properties for which a value is defined, excluding Properties that no longer have a value", () => {
let mockThing = getMockThingWithLiteralsFor(
"https://some.vocab/predicate1",
"value1",
"value2",
"string"
);
mockThing = addStringNoLocale(
mockThing,
"https://arbitrary.vocab/predicate2",
"value 3"
);
mockThing = addStringNoLocale(
mockThing,
"https://some.vocab/predicate3",
"value 4"
);
mockThing = removeStringNoLocale(
mockThing,
"https://arbitrary.vocab/predicate2",
"value 3"
);
expect(getPropertyAll(mockThing)).toStrictEqual([
"https://some.vocab/predicate1",
"https://some.vocab/predicate3",
]);
});
it("returns an empty array for an empty Thing", () => {
expect(getPropertyAll(createThing())).toStrictEqual([]);
});
});
describe("getIri", () => {
function getMockThingWithIri(
predicate: IriString,
iri: IriString = "https://arbitrary.vocab/object"
): Thing {
const thing: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
[predicate]: {
namedNodes: [iri],
},
},
};
return thing;
}
it("returns the IRI value for the given Property", () => {
const thingWithIri = getMockThingWithIri(
"https://some.vocab/predicate",
"https://some.vocab/object"
);
expect(getUrl(thingWithIri, "https://some.vocab/predicate")).toBe(
"https://some.vocab/object"
);
});
it("accepts Properties as Named Nodes", () => {
const thingWithIri = getMockThingWithIri(
"https://some.vocab/predicate",
"https://some.vocab/object"
);
expect(
getUrl(
thingWithIri,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toBe("https://some.vocab/object");
});
it("returns an LocalNode if that is the first match", () => {
const thingWithIriAndLocalNode = getMockThingWithIri(
"https://some.vocab/predicate",
`${localNodeSkolemPrefix}someLocalNode`
);
(
thingWithIriAndLocalNode.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]
).push("https://some.vocab/object");
expect(
getUrl(thingWithIriAndLocalNode, "https://some.vocab/predicate")
).toBe("#someLocalNode");
});
it("returns null if no IRI value was found", () => {
const thingWithoutIri = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(getUrl(thingWithoutIri, "https://some.vocab/predicate")).toBeNull();
});
it("returns LocalNodes", () => {
const thingWithIri = getMockThingWithIri(
"https://some.vocab/predicate",
`${localNodeSkolemPrefix}someLocalNode`
);
expect(getUrl(thingWithIri, "https://some.vocab/predicate")).toBe(
"#someLocalNode"
);
});
it("does not return non-IRI values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = [
"https://some.vocab/object",
"https://arbitrary.vocab/object",
];
expect(
getUrl(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toBe("https://some.vocab/object");
});
it("returns null if no IRI value was found for the given Predicate", () => {
const thingWithIri = getMockThingWithIri("https://some.vocab/predicate");
expect(
getUrl(thingWithIri, "https://some-other.vocab/predicate")
).toBeNull();
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getUrl(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getUrl(mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url")
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getUrl(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getIriAll", () => {
function getMockThingWithIris(
predicate: IriString,
iri1: IriString = "https://arbitrary.vocab/object1",
iri2: IriString = "https://arbitrary.vocab/object2"
): Thing {
return {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
[predicate]: {
namedNodes: [iri1, iri2],
},
},
};
}
it("returns the IRI values for the given Predicate", () => {
const thingWithIris = getMockThingWithIris(
"https://some.vocab/predicate",
"https://some.vocab/object1",
"https://some.vocab/object2"
);
expect(getUrlAll(thingWithIris, "https://some.vocab/predicate")).toEqual([
"https://some.vocab/object1",
"https://some.vocab/object2",
]);
});
it("accepts Properties as Named Nodes", () => {
const thingWithIris = getMockThingWithIris(
"https://some.vocab/predicate",
"https://some.vocab/object1",
"https://some.vocab/object2"
);
expect(
getUrlAll(
thingWithIris,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toEqual(["https://some.vocab/object1", "https://some.vocab/object2"]);
});
it("returns an empty array if no IRI value was found", () => {
const thingWithoutIris = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(getUrlAll(thingWithoutIris, "https://some.vocab/predicate")).toEqual(
[]
);
});
it("does not return non-IRI values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://some.vocab/object"];
expect(
getUrlAll(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toEqual(["https://some.vocab/object"]);
});
it("returns an empty array if no IRI value was found for the given Predicate", () => {
const thingWithIri = getMockThingWithIris("https://some.vocab/predicate");
expect(
getUrlAll(thingWithIri, "https://some-other.vocab/predicate")
).toEqual([]);
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getUrlAll(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getUrlAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getIriAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getBoolean", () => {
it("returns the boolean value for the given Predicate", () => {
const thingWithBoolean = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"1",
"boolean"
);
expect(getBoolean(thingWithBoolean, "https://some.vocab/predicate")).toBe(
true
);
});
it("accepts Properties as Named Nodes", () => {
const thingWithBoolean = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"0",
"boolean"
);
expect(
getBoolean(
thingWithBoolean,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toBe(false);
});
it("returns null if no boolean value was found", () => {
const thingWithoutBoolean = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getBoolean(thingWithoutBoolean, "https://some.vocab/predicate")
).toBeNull();
});
it("does not return non-boolean values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#boolean"] as string[]) = [
"1",
];
expect(
getBoolean(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toBe(true);
});
it("returns null if no boolean value was found for the given Predicate", () => {
const thingWithBoolean = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"1",
"boolean"
);
expect(
getBoolean(thingWithBoolean, "https://some-other.vocab/predicate")
).toBeNull();
});
it("returns null if an invalid value, marked as boolean, was found for the given Predicate", () => {
const thingWithNonBoolean = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Not a boolean",
"boolean"
);
expect(
getBoolean(thingWithNonBoolean, "https://some.vocab/predicate")
).toBeNull();
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getBoolean(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getBoolean(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getBoolean(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getBooleanAll", () => {
it("returns the boolean values for the given Predicate", () => {
const thingWithBooleans = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"1",
"0",
"boolean"
);
expect(
getBooleanAll(thingWithBooleans, "https://some.vocab/predicate")
).toEqual([true, false]);
});
it("accepts Properties as Named Nodes", () => {
const thingWithBooleans = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"1",
"0",
"boolean"
);
expect(
getBooleanAll(
thingWithBooleans,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toEqual([true, false]);
});
it("returns an empty array if no boolean values were found", () => {
const thingWithoutBooleans = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getBooleanAll(thingWithoutBooleans, "https://some.vocab/predicate")
).toEqual([]);
});
it("does not return non-boolean values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#boolean"] as string[]) = [
"1",
];
expect(
getBooleanAll(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toEqual([true]);
});
it("returns an empty array if no boolean values were found for the given Predicate", () => {
const thingWithBoolean = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"1",
"boolean"
);
expect(
getBooleanAll(thingWithBoolean, "https://some-other.vocab/predicate")
).toEqual([]);
});
it("does not include invalid values marked as boolean", () => {
const thingWithNonBoolean = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"Not a boolean",
"0",
"boolean"
);
expect(
getBooleanAll(thingWithNonBoolean, "https://some.vocab/predicate")
).toEqual([false]);
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getBooleanAll(
null as unknown as Thing,
"https://arbitrary.vocab/predicate"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getBooleanAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getBooleanAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getDatetime", () => {
it("returns the datetime value for the given Predicate", () => {
const thingWithDatetime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"1990-11-12T13:37:42.000Z",
"dateTime"
);
const expectedDate = new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0));
expect(
getDatetime(thingWithDatetime, "https://some.vocab/predicate")
).toEqual(expectedDate);
});
it("accepts Properties as Named Nodes", () => {
const thingWithDatetime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"1990-11-12T13:37:42.000Z",
"dateTime"
);
const expectedDate = new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0));
expect(
getDatetime(
thingWithDatetime,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toEqual(expectedDate);
});
it("returns null if no datetime value was found", () => {
const thingWithoutDatetime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getDatetime(thingWithoutDatetime, "https://some.vocab/predicate")
).toBeNull();
});
it("does not return non-datetime values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#dateTime"] as string[]) = [
"1990-11-12T13:37:42.000Z",
];
const expectedDate = new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0));
expect(
getDatetime(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toEqual(expectedDate);
});
it("returns null if no datetime value was found for the given Predicate", () => {
const thingWithDatetime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"1990-11-12T13:37:42.000Z",
"dateTime"
);
expect(
getDatetime(thingWithDatetime, "https://some-other.vocab/predicate")
).toBeNull();
});
it("returns null if an invalid value, marked as datetime, was found for the given Predicate", () => {
const thingWithNonDatetime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Not a datetime",
"dateTime"
);
expect(
getDatetime(thingWithNonDatetime, "https://some.vocab/predicate")
).toBeNull();
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getDatetime(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getDatetime(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getDatetime(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getDatetimeAll", () => {
it("returns the datetime values for the given Predicate", () => {
const thingWithDatetimes = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"1955-06-08T13:37:42.000Z",
"1990-11-12T13:37:42.000Z",
"dateTime"
);
const expectedDate1 = new Date(Date.UTC(1955, 5, 8, 13, 37, 42, 0));
const expectedDate2 = new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0));
expect(
getDatetimeAll(thingWithDatetimes, "https://some.vocab/predicate")
).toEqual([expectedDate1, expectedDate2]);
});
it("accepts Properties as Named Nodes", () => {
const thingWithDatetimes = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"1955-06-08T13:37:42.000Z",
"1990-11-12T13:37:42.000Z",
"dateTime"
);
const expectedDate1 = new Date(Date.UTC(1955, 5, 8, 13, 37, 42, 0));
const expectedDate2 = new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0));
expect(
getDatetimeAll(
thingWithDatetimes,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toEqual([expectedDate1, expectedDate2]);
});
it("returns an empty array if no datetime values were found", () => {
const thingWithoutDatetimes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getDatetimeAll(thingWithoutDatetimes, "https://some.vocab/predicate")
).toEqual([]);
});
it("does not return non-datetime values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#dateTime"] as string[]) = [
"1990-11-12T13:37:42.000Z",
];
const expectedDate = new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0));
expect(
getDatetimeAll(
thingWithDifferentDatatypes,
"https://some.vocab/predicate"
)
).toEqual([expectedDate]);
});
it("returns an empty array if no datetime values were found for the given Predicate", () => {
const thingWithDatetime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"1990-11-12T13:37:42.000Z",
"dateTime"
);
expect(
getDatetimeAll(thingWithDatetime, "https://some-other.vocab/predicate")
).toEqual([]);
});
it("does not return invalid values marked as datetime", () => {
const thingWithNonDatetime = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"Not a datetime",
"1990-11-12T13:37:42.000Z",
"dateTime"
);
const expectedDate = new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0));
expect(
getDatetimeAll(thingWithNonDatetime, "https://some.vocab/predicate")
).toEqual([expectedDate]);
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getDatetimeAll(
null as unknown as Thing,
"https://arbitrary.vocab/predicate"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getDatetimeAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getDatetimeAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getDate", () => {
it("returns the date value for the given Predicate", () => {
const thingWithDate = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"1990-11-12Z",
"date"
);
const expectedDate = new Date(Date.UTC(1990, 10, 12, 12));
expect(getDate(thingWithDate, "https://some.vocab/predicate")).toEqual(
expectedDate
);
});
it("accepts Properties as Named Nodes", () => {
const thingWithDate = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"1990-11-12Z",
"date"
);
const expectedDate = new Date(Date.UTC(1990, 10, 12, 12));
expect(
getDate(
thingWithDate,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toEqual(expectedDate);
});
it("returns null if no date value was found", () => {
const thingWithoutDate = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getDate(thingWithoutDate, "https://some.vocab/predicate")
).toBeNull();
});
it("does not return non-date values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#date"] as string[]) = [
"1990-11-12Z",
];
const expectedDate = new Date(Date.UTC(1990, 10, 12, 12));
expect(
getDate(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toEqual(expectedDate);
});
it("returns null if no date value was found for the given Predicate", () => {
const thingWithDate = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"1990-11-12",
"date"
);
expect(
getDate(thingWithDate, "https://some-other.vocab/predicate")
).toBeNull();
});
it("returns null if an invalid value, marked as date, was found for the given Predicate", () => {
const thingWithNonDate = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Not a date",
"date"
);
expect(
getDate(thingWithNonDate, "https://some.vocab/predicate")
).toBeNull();
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getDate(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getDate(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getDate(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getDateAll", () => {
it("returns the date values for the given Predicate", () => {
const thingWithDates = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"1955-06-08",
"1990-11-12",
"date"
);
const expectedDate1 = new Date(Date.UTC(1955, 5, 8, 12));
const expectedDate2 = new Date(Date.UTC(1990, 10, 12, 12));
expect(getDateAll(thingWithDates, "https://some.vocab/predicate")).toEqual([
expectedDate1,
expectedDate2,
]);
});
it("accepts Properties as Named Nodes", () => {
const thingWithDates = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"1955-06-08",
"1990-11-12",
"date"
);
const expectedDate1 = new Date(Date.UTC(1955, 5, 8, 12));
const expectedDate2 = new Date(Date.UTC(1990, 10, 12, 12));
expect(
getDateAll(
thingWithDates,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toEqual([expectedDate1, expectedDate2]);
});
it("returns an empty array if no date values were found", () => {
const thingWithoutDates = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getDateAll(thingWithoutDates, "https://some.vocab/predicate")
).toEqual([]);
});
it("does not return non-date values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#date"] as string[]) = [
"1990-11-12",
];
const expectedDate = new Date(Date.UTC(1990, 10, 12, 12));
expect(
getDateAll(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toEqual([expectedDate]);
});
it("returns an empty array if no date values were found for the given Predicate", () => {
const thingWithDate = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"1990-11-12",
"date"
);
expect(
getDateAll(thingWithDate, "https://some-other.vocab/predicate")
).toEqual([]);
});
it("does not return invalid values marked as date", () => {
const thingWithNonDate = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"Not a date",
"1990-11-12",
"date"
);
const expectedDate = new Date(Date.UTC(1990, 10, 12, 12));
expect(
getDateAll(thingWithNonDate, "https://some.vocab/predicate")
).toEqual([expectedDate]);
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getDateAll(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getDateAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getDateAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getTime", () => {
it("returns the time value for the given Predicate", () => {
const thingWithTime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"13:37:42",
"time"
);
const expectedTime = {
hour: 13,
minute: 37,
second: 42,
};
expect(
getTime(thingWithTime, "https://some.vocab/predicate")
).toStrictEqual(expectedTime);
});
it("accepts Properties as Named Nodes", () => {
const thingWithTime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"13:37:42",
"time"
);
const expectedTime = {
hour: 13,
minute: 37,
second: 42,
};
expect(
getTime(
thingWithTime,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toStrictEqual(expectedTime);
});
it("returns null if no time value was found", () => {
const thingWithoutTime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getTime(thingWithoutTime, "https://some.vocab/predicate")
).toBeNull();
});
it("does not return non-time values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#time"] as string[]) = [
"13:37:42",
];
const expectedTime = {
hour: 13,
minute: 37,
second: 42,
};
expect(
getTime(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toStrictEqual(expectedTime);
});
it("returns null if no time value was found for the given Predicate", () => {
const thingWithTime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"13:37:42",
"time"
);
expect(
getTime(thingWithTime, "https://some-other.vocab/predicate")
).toBeNull();
});
it("returns null if an invalid value, marked as time, was found for the given Predicate", () => {
const thingWithNonTime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Not a time",
"time"
);
expect(
getTime(thingWithNonTime, "https://some.vocab/predicate")
).toBeNull();
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getTime(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getTime(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getTime(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getTimeAll", () => {
it("returns the time values for the given Predicate", () => {
const thingWithTimes = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"14:37:42",
"13:37:42",
"time"
);
const expectedTime1 = {
hour: 14,
minute: 37,
second: 42,
};
const expectedTime2 = {
hour: 13,
minute: 37,
second: 42,
};
expect(
getTimeAll(thingWithTimes, "https://some.vocab/predicate")
).toStrictEqual([expectedTime1, expectedTime2]);
});
it("accepts Properties as Named Nodes", () => {
const thingWithTimes = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"14:37:42",
"13:37:42",
"time"
);
const expectedTime1 = {
hour: 14,
minute: 37,
second: 42,
};
const expectedTime2 = {
hour: 13,
minute: 37,
second: 42,
};
expect(
getTimeAll(
thingWithTimes,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toStrictEqual([expectedTime1, expectedTime2]);
});
it("returns an empty array if no time values were found", () => {
const thingWithoutTimes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getTimeAll(thingWithoutTimes, "https://some.vocab/predicate")
).toStrictEqual([]);
});
it("does not return non-time values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#time"] as string[]) = [
"13:37:42",
];
const expectedTime = {
hour: 13,
minute: 37,
second: 42,
};
expect(
getTimeAll(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toStrictEqual([expectedTime]);
});
it("returns an empty array if no time values were found for the given Predicate", () => {
const thingWithTime = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"13:37:42",
"time"
);
expect(
getTimeAll(thingWithTime, "https://some-other.vocab/predicate")
).toStrictEqual([]);
});
it("does not return invalid values marked as time", () => {
const thingWithNonTime = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"Not a time",
"13:37:42",
"time"
);
const expectedTime = {
hour: 13,
minute: 37,
second: 42,
};
expect(
getTimeAll(thingWithNonTime, "https://some.vocab/predicate")
).toStrictEqual([expectedTime]);
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getTimeAll(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getTimeAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getTimeAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getDecimal", () => {
it("returns the decimal value for the given Predicate", () => {
const thingWithDecimal = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"13.37",
"decimal"
);
expect(getDecimal(thingWithDecimal, "https://some.vocab/predicate")).toBe(
13.37
);
});
it("accepts Properties as Named Nodes", () => {
const thingWithDecimal = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"13.37",
"decimal"
);
expect(
getDecimal(
thingWithDecimal,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toBe(13.37);
});
it("returns null if no decimal value was found", () => {
const thingWithoutDecimal = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getDecimal(thingWithoutDecimal, "https://some.vocab/predicate")
).toBeNull();
});
it("does not return non-decimal values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#decimal"] as string[]) = [
"13.37",
];
expect(
getDecimal(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toBe(13.37);
});
it("returns null if no decimal value was found for the given Predicate", () => {
const thingWithDecimal = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"13.37",
"decimal"
);
expect(
getDecimal(thingWithDecimal, "https://some-other.vocab/predicate")
).toBeNull();
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getDecimal(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getDecimal(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getDecimal(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getDecimalAll", () => {
it("returns the decimal values for the given Predicate", () => {
const thingWithDecimals = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"13.37",
"7.2",
"decimal"
);
expect(
getDecimalAll(thingWithDecimals, "https://some.vocab/predicate")
).toEqual([13.37, 7.2]);
});
it("accepts Properties as Named Nodes", () => {
const thingWithDecimals = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"13.37",
"7.2",
"decimal"
);
expect(
getDecimalAll(
thingWithDecimals,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toEqual([13.37, 7.2]);
});
it("returns an empty array if no decimal values were found", () => {
const thingWithoutDecimals = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getDecimalAll(thingWithoutDecimals, "https://some.vocab/predicate")
).toEqual([]);
});
it("does not return non-decimal values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#decimal"] as string[]) = [
"13.37",
];
expect(
getDecimalAll(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toEqual([13.37]);
});
it("returns an empty array if no decimal values were found for the given Predicate", () => {
const thingWithDecimal = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"13.37",
"decimal"
);
expect(
getDecimalAll(thingWithDecimal, "https://some-other.vocab/predicate")
).toEqual([]);
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getDecimalAll(
null as unknown as Thing,
"https://arbitrary.vocab/predicate"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getDecimalAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getDecimalAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getInteger", () => {
it("returns the integer value for the given Predicate", () => {
const thingWithInteger = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(getInteger(thingWithInteger, "https://some.vocab/predicate")).toBe(
42
);
});
it("accepts Properties as Named Nodes", () => {
const thingWithInteger = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getInteger(
thingWithInteger,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toBe(42);
});
it("returns null if no integer value was found", () => {
const thingWithoutInteger = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"13.37",
"decimal"
);
expect(
getInteger(thingWithoutInteger, "https://some.vocab/predicate")
).toBeNull();
});
it("does not return non-integer values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#integer"] as string[]) = [
"42",
];
expect(
getInteger(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toBe(42);
});
it("returns null if no integer value was found for the given Predicate", () => {
const thingWithInteger = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getInteger(thingWithInteger, "https://some-other.vocab/predicate")
).toBeNull();
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getInteger(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getInteger(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getInteger(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getIntegerAll", () => {
it("returns the integer values for the given Predicate", () => {
const thingWithIntegers = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"42",
"1337",
"integer"
);
expect(
getIntegerAll(thingWithIntegers, "https://some.vocab/predicate")
).toEqual([42, 1337]);
});
it("accepts Properties as Named Nodes", () => {
const thingWithIntegers = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"42",
"1337",
"integer"
);
expect(
getIntegerAll(
thingWithIntegers,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toEqual([42, 1337]);
});
it("returns an empty array if no integer values were found", () => {
const thingWithoutIntegers = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"13.37",
"decimal"
);
expect(
getIntegerAll(thingWithoutIntegers, "https://some.vocab/predicate")
).toEqual([]);
});
it("does not return non-integer values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals!["http://www.w3.org/2001/XMLSchema#integer"] as string[]) = [
"42",
];
expect(
getIntegerAll(thingWithDifferentDatatypes, "https://some.vocab/predicate")
).toEqual([42]);
});
it("returns an empty array if no integer values were found for the given Predicate", () => {
const thingWithInteger = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getIntegerAll(thingWithInteger, "https://some-other.vocab/predicate")
).toEqual([]);
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getIntegerAll(
null as unknown as Thing,
"https://arbitrary.vocab/predicate"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getIntegerAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getIntegerAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getStringEnglish", () => {
it("returns the English string value for the given Predicate", () => {
const thingWithLocaleString: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
en: ["Some value"],
},
},
},
};
expect(
getStringEnglish(thingWithLocaleString, "https://some.vocab/predicate")
).toBe("Some value");
});
});
describe("getStringEnglishAll", () => {
it("treats empty-string locale literally - i.e. only returns values added with an empty language tag", () => {
const thingWithLocaleStrings: Thing = {
type: "Subject",
url: SUBJECT,
predicates: {
[PREDICATE]: {
langStrings: {
en: ["value x", "value y"],
fr: ["value 1"],
"": ["value 2"],
es: ["value 3"],
},
literals: {
[xmlSchemaTypes.string]: ["value 1"],
},
},
},
};
expect(getStringEnglishAll(thingWithLocaleStrings, PREDICATE)).toEqual([
"value x",
"value y",
]);
});
});
describe("getStringWithLocale", () => {
it("returns the string value for the given Predicate in the given locale", () => {
const thingWithLocaleString: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"nl-NL": ["Some value"],
},
},
},
};
expect(
getStringWithLocale(
thingWithLocaleString,
"https://some.vocab/predicate",
"nl-NL"
)
).toBe("Some value");
});
it("accepts Properties as Named Nodes", () => {
const thingWithLocaleString: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"nl-NL": ["Some value"],
},
},
},
};
expect(
getStringWithLocale(
thingWithLocaleString,
DataFactory.namedNode("https://some.vocab/predicate"),
"nl-NL"
)
).toBe("Some value");
});
it("supports matching locales with different casing", () => {
const thingWithLocaleString: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"nl-NL": ["Some value"],
},
},
},
};
expect(
getStringWithLocale(
thingWithLocaleString,
"https://some.vocab/predicate",
"NL-nL"
)
).toBe("Some value");
});
it("returns null if no locale string value was found", () => {
const thingWithoutStringNoLocale = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getStringWithLocale(
thingWithoutStringNoLocale,
"https://some.vocab/predicate",
"nl-NL"
)
).toBeNull();
});
it("returns null if no locale string with the requested locale was found", () => {
const thingWithDifferentLocaleString: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"nl-NL": ["Some value"],
},
},
},
};
expect(
getStringWithLocale(
thingWithDifferentLocaleString,
"https://some.vocab/predicate",
"en-GB"
)
).toBeNull();
expect(
getStringWithLocale(
thingWithDifferentLocaleString,
"https://some.vocab/predicate",
"nl"
)
).toBeNull();
});
it("does not return non-locale-string values", () => {
const literalWithLocale = DataFactory.literal("Some value", "nl-NL");
const quadWithLocaleString = DataFactory.quad(
DataFactory.namedNode("https://arbitrary.vocab/subject"),
DataFactory.namedNode("https://some.vocab/predicate"),
literalWithLocale
);
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.langStrings as Record<string, string[]>) = {
"nl-NL": ["Some value"],
};
expect(
getStringWithLocale(
thingWithDifferentDatatypes,
"https://some.vocab/predicate",
"nl-NL"
)
).toBe("Some value");
});
it("returns null if no locale string was found for the given Predicate", () => {
const thingWithLocaleString: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"nl-NL": ["Some value"],
},
},
},
};
expect(
getStringWithLocale(
thingWithLocaleString,
"https://some-other.vocab/predicate",
"nl-NL"
)
).toBeNull();
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getStringWithLocale(
null as unknown as Thing,
"https://arbitrary.vocab/predicate",
"nl-NL"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getStringWithLocale(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url",
"nl-NL"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getStringWithLocale(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url",
"nl-NL"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getStringByLocaleAll", () => {
it("returns all the string values for the given Predicate keyed by their locale", () => {
const thingWithLocaleStrings: Thing = {
type: "Subject",
url: SUBJECT,
predicates: {
[PREDICATE]: {
langStrings: {
en: ["value 1", "value 2"],
fr: ["value 3"],
es: ["value 4"],
},
},
},
};
expect(
Array.from(getStringByLocaleAll(thingWithLocaleStrings, PREDICATE))
).toEqual([
["en", ["value 1", "value 2"]],
["fr", ["value 3"]],
["es", ["value 4"]],
]);
});
it("excludes non-language string values", () => {
const thingWithLocaleStrings: Thing = {
type: "Subject",
url: SUBJECT,
predicates: {
[PREDICATE]: {
langStrings: {
fr: ["value 1"],
es: ["value 3", "value 5"],
},
literals: {
[xmlSchemaTypes.string]: ["value 2", "value 4"],
},
},
},
};
expect(
Array.from(getStringByLocaleAll(thingWithLocaleStrings, PREDICATE))
).toEqual([
["fr", ["value 1"]],
["es", ["value 3", "value 5"]],
]);
});
it("allows empty language tags - literal is still an rdf:langString", () => {
const thingWithLocaleStrings: Thing = {
type: "Subject",
url: SUBJECT,
predicates: {
[PREDICATE]: {
langStrings: {
fr: ["chien"],
"": ["dog"],
},
},
},
};
// An empty language tag is valid, and even in Turtle should be serialized
// as an rdf:langString, e.g.:
// <SUBJECT> <PREDICATE> "chien"@fr .
// <SUBJECT> <PREDICATE> "dog"^^rdf:langString .
expect(
Array.from(getStringByLocaleAll(thingWithLocaleStrings, PREDICATE))
).toEqual([
["fr", ["chien"]],
["", ["dog"]],
]);
});
it("ignores non-string literals", () => {
const thingWithLocaleStrings: Thing = {
type: "Subject",
url: SUBJECT,
predicates: {
[PREDICATE]: {
langStrings: {
fr: ["value 1"],
},
literals: {
[xmlSchemaTypes.string]: ["value 2"],
[xmlSchemaTypes.decimal]: ["99.999"],
},
},
},
};
expect(
Array.from(getStringByLocaleAll(thingWithLocaleStrings, PREDICATE))
).toEqual([["fr", ["value 1"]]]);
});
it("ignores non-string literals even when there are no lang strings", () => {
const thingWithLocaleStrings: Thing = {
type: "Subject",
url: SUBJECT,
predicates: {
[PREDICATE]: {
literals: {
[xmlSchemaTypes.string]: ["value 2"],
[xmlSchemaTypes.decimal]: ["99.999"],
},
},
},
};
expect(
Array.from(getStringByLocaleAll(thingWithLocaleStrings, PREDICATE))
).toEqual([]);
});
it("ignores non-string literals even when there is no data at all", () => {
const thingWithLocaleStrings: Thing = {
type: "Subject",
url: SUBJECT,
predicates: {},
};
expect(
Array.from(getStringByLocaleAll(thingWithLocaleStrings, PREDICATE))
).toEqual([]);
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getStringByLocaleAll(
null as unknown as Thing,
"https://arbitrary.vocab/predicate"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getStringByLocaleAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getStringByLocaleAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getStringWithLocaleAll", () => {
it("treats empty-string locale literally - i.e. only returns values added with an empty language tag", () => {
const thingWithLocaleStrings: Thing = {
type: "Subject",
url: SUBJECT,
predicates: {
[PREDICATE]: {
langStrings: {
fr: ["value 2"],
"": ["value 3"],
es: ["value 4"],
},
literals: {
[xmlSchemaTypes.string]: ["value 1"],
},
},
},
};
// TODO: Not sure this RDF-spec compliant - need to double check, but
// according to https://w3c.github.io/rdf-dir-literal/langString.html#literals
// it seems language tags *must* be non-empty...
expect(
getStringWithLocaleAll(thingWithLocaleStrings, PREDICATE, "")
).toEqual(["value 3"]);
});
it("returns the string values for the given Predicate in the given locale", () => {
const thingWithLocaleStrings: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"nl-NL": ["Some value 1", "Some value 2"],
},
},
},
};
expect(
getStringWithLocaleAll(
thingWithLocaleStrings,
"https://some.vocab/predicate",
"nl-NL"
)
).toEqual(["Some value 1", "Some value 2"]);
});
it("accepts Properties as Named Nodes", () => {
const thingWithLocaleStrings: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"nl-NL": ["Some value 1", "Some value 2"],
},
},
},
};
expect(
getStringWithLocaleAll(
thingWithLocaleStrings,
DataFactory.namedNode("https://some.vocab/predicate"),
"nl-NL"
)
).toEqual(["Some value 1", "Some value 2"]);
});
it("supports matching locales with different casing", () => {
const thingWithLocaleString: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"nl-NL": ["Some value"],
},
},
},
};
expect(
getStringWithLocaleAll(
thingWithLocaleString,
"https://some.vocab/predicate",
"NL-nL"
)
).toEqual(["Some value"]);
});
it("returns an empty array if no locale string values were found", () => {
const thingWithoutStringNoLocales = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getStringWithLocaleAll(
thingWithoutStringNoLocales,
"https://some.vocab/predicate",
"nl-NL"
)
).toEqual([]);
});
it("returns an empty array if no locale strings with the requested locale were found", () => {
const thingWithDifferentLocaleStrings: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"nl-NL": ["Some value"],
},
},
},
};
expect(
getStringWithLocaleAll(
thingWithDifferentLocaleStrings,
"https://some.vocab/predicate",
"en-GB"
)
).toEqual([]);
expect(
getStringWithLocaleAll(
thingWithDifferentLocaleStrings,
"https://some.vocab/predicate",
"nl"
)
).toEqual([]);
});
it("does not return non-locale-string values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.langStrings as Record<string, string[]>) = {
"nl-NL": ["Some value"],
};
expect(
getStringWithLocaleAll(
thingWithDifferentDatatypes,
"https://some.vocab/predicate",
"nl-NL"
)
).toEqual(["Some value"]);
});
it("returns an empty array if no locale strings were found for the given Predicate", () => {
const thingWithLocaleString: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"nl-NL": ["Arbitrary value"],
},
},
},
};
expect(
getStringWithLocaleAll(
thingWithLocaleString,
"https://some-other.vocab/predicate",
"nl-NL"
)
).toEqual([]);
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getStringWithLocaleAll(
null as unknown as Thing,
"https://arbitrary.vocab/predicate",
"nl-NL"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getStringWithLocaleAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url",
"nl-NL"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getStringWithLocaleAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url",
"nl-NL"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getStringNoLocale", () => {
it("returns the string value for the given Predicate", () => {
const thingWithStringNoLocale = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Some value",
"string"
);
expect(
getStringNoLocale(thingWithStringNoLocale, "https://some.vocab/predicate")
).toBe("Some value");
});
it("accepts Properties as Named Nodes", () => {
const thingWithStringNoLocale = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Some value",
"string"
);
expect(
getStringNoLocale(
thingWithStringNoLocale,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toBe("Some value");
});
it("returns null if no string value was found", () => {
const thingWithoutStringNoLocale = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getStringNoLocale(
thingWithoutStringNoLocale,
"https://some.vocab/predicate"
)
).toBeNull();
});
it("does not return non-string values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals![xmlSchemaTypes.string] as string[]) = ["Some value"];
expect(
getStringNoLocale(
thingWithDifferentDatatypes,
"https://some.vocab/predicate"
)
).toBe("Some value");
});
it("returns null if no string value was found for the given Predicate", () => {
const thingWithStringNoLocale = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
expect(
getStringNoLocale(
thingWithStringNoLocale,
"https://some-other.vocab/predicate"
)
).toBeNull();
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getStringNoLocale(
null as unknown as Thing,
"https://arbitrary.vocab/predicate"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getStringNoLocale(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getStringNoLocale(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getStringNoLocaleAll", () => {
it("returns the string values for the given Predicate", () => {
const thingWithStringNoLocales = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"Some value 1",
"Some value 2",
"string"
);
expect(
getStringNoLocaleAll(
thingWithStringNoLocales,
"https://some.vocab/predicate"
)
).toEqual(["Some value 1", "Some value 2"]);
});
it("accepts Properties as Named Nodes", () => {
const thingWithStringNoLocales = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"Some value 1",
"Some value 2",
"string"
);
expect(
getStringNoLocaleAll(
thingWithStringNoLocales,
DataFactory.namedNode("https://some.vocab/predicate")
)
).toEqual(["Some value 1", "Some value 2"]);
});
it("returns an empty array if no string values were found", () => {
const thingWithoutStringNoLocales = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
expect(
getStringNoLocaleAll(
thingWithoutStringNoLocales,
"https://some.vocab/predicate"
)
).toEqual([]);
});
it("does not return non-string values", () => {
const thingWithDifferentDatatypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"42",
"integer"
);
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
(thingWithDifferentDatatypes.predicates["https://some.vocab/predicate"]
.literals![xmlSchemaTypes.string] as string[]) = ["Some value"];
expect(
getStringNoLocaleAll(
thingWithDifferentDatatypes,
"https://some.vocab/predicate"
)
).toEqual(["Some value"]);
});
it("returns an empty array if no string values were found for the given Predicate", () => {
const thingWithStringNoLocale = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary value",
"string"
);
expect(
getStringNoLocaleAll(
thingWithStringNoLocale,
"https://some-other.vocab/predicate"
)
).toEqual([]);
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getStringNoLocaleAll(
null as unknown as Thing,
"https://arbitrary.vocab/predicate"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getStringNoLocaleAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getStringNoLocaleAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getLiteral", () => {
it("returns the Literal for the given Predicate", () => {
const thingWithLiteral = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Some string",
"string"
);
const foundLiteral = getLiteral(
thingWithLiteral,
"https://some.vocab/predicate"
);
expect(foundLiteral).not.toBeNull();
expect((foundLiteral as Literal).termType).toBe("Literal");
expect((foundLiteral as Literal).value).toBe("Some string");
});
it("can return langStrings", () => {
const thingWithLocaleString: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"empty-locale": [],
"nl-NL": ["Some lang string"],
},
},
},
};
const foundLiteral = getLiteral(
thingWithLocaleString,
"https://some.vocab/predicate"
);
expect(foundLiteral).not.toBeNull();
expect((foundLiteral as Literal).termType).toBe("Literal");
expect((foundLiteral as Literal).value).toBe("Some lang string");
expect((foundLiteral as Literal).language.toLowerCase()).toBe("nl-nl");
});
it("accepts Properties as Named Nodes", () => {
const thingWithLiteral = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Some string",
"string"
);
const foundLiteral = getLiteral(
thingWithLiteral,
DataFactory.namedNode("https://some.vocab/predicate")
);
expect(foundLiteral).not.toBeNull();
expect((foundLiteral as Literal).termType).toBe("Literal");
expect((foundLiteral as Literal).value).toBe("Some string");
});
it("returns null if no Literal value was found", () => {
const thingWithoutLiteral: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"empty-locale": [],
},
literals: {
"https://empty.data/type": [],
},
},
},
};
expect(
getLiteral(thingWithoutLiteral, "https://some.vocab/predicate")
).toBeNull();
});
it("does not return non-Literal values", () => {
const thingWithDifferentTermTypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary string",
"string"
);
(thingWithDifferentTermTypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
expect(
(
getLiteral(
thingWithDifferentTermTypes,
"https://some.vocab/predicate"
) as Literal
).termType
).toBe("Literal");
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getLiteral(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getLiteral(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getLiteral(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getLiteralAll", () => {
it("returns the Literals for the given Predicate", () => {
const thingWithLiterals = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"Some string 1",
"Some string 2",
"string"
);
const foundLiterals = getLiteralAll(
thingWithLiterals,
"https://some.vocab/predicate"
);
expect(foundLiterals).toHaveLength(2);
expect(foundLiterals[0].termType).toBe("Literal");
expect(foundLiterals[0].value).toBe("Some string 1");
expect(foundLiterals[1].termType).toBe("Literal");
expect(foundLiterals[1].value).toBe("Some string 2");
});
it("returns the lang string Literals for the given Predicate", () => {
const thingWithLocaleString: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"empty-locale": [],
"nl-NL": ["Some lang string"],
},
},
},
};
const foundLiterals = getLiteralAll(
thingWithLocaleString,
"https://some.vocab/predicate"
);
expect(foundLiterals).toHaveLength(1);
expect(foundLiterals[0].termType).toBe("Literal");
expect(foundLiterals[0].value).toBe("Some lang string");
expect(foundLiterals[0].language.toLowerCase()).toBe("nl-nl");
});
it("accepts Properties as Named Nodes", () => {
const thingWithLiterals = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"Some string 1",
"Some string 2",
"string"
);
const foundLiterals = getLiteralAll(
thingWithLiterals,
DataFactory.namedNode("https://some.vocab/predicate")
);
expect(foundLiterals).toHaveLength(2);
expect(foundLiterals[0].termType).toBe("Literal");
expect(foundLiterals[0].value).toBe("Some string 1");
expect(foundLiterals[1].termType).toBe("Literal");
expect(foundLiterals[1].value).toBe("Some string 2");
});
it("returns an empty array if no Literal values were found", () => {
const thingWithoutLiterals: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
langStrings: {
"empty-locale": [],
},
literals: {
"https://empty.data/type": [],
},
},
},
};
expect(
getLiteralAll(thingWithoutLiterals, "https://some.vocab/predicate")
).toEqual([]);
});
it("does not return non-Literal values", () => {
const thingWithDifferentTermTypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary string",
"string"
);
(thingWithDifferentTermTypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
const foundLiterals = getLiteralAll(
thingWithDifferentTermTypes,
"https://some.vocab/predicate"
);
expect(foundLiterals).toHaveLength(1);
expect(foundLiterals[0].termType).toBe("Literal");
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getLiteralAll(
null as unknown as Thing,
"https://arbitrary.vocab/predicate"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getLiteralAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getLiteralAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
function getMockThingWithNamedNode(
predicate: IriString,
object: IriString
): Thing {
return {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
[predicate]: {
namedNodes: [object],
},
},
};
}
function getMockThingWithNamedNodes(
predicate: IriString,
object1: IriString,
object2: IriString
): Thing {
return {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
[predicate]: {
namedNodes: [object1, object2],
},
},
};
}
describe("getNamedNode", () => {
it("returns the Named Node for the given Predicate", () => {
const thingWithNamedNode = getMockThingWithNamedNode(
"https://some.vocab/predicate",
"https://some.vocab/object"
);
const foundNamedNode = getNamedNode(
thingWithNamedNode,
"https://some.vocab/predicate"
);
expect(foundNamedNode).not.toBeNull();
expect((foundNamedNode as NamedNode).termType).toBe("NamedNode");
expect((foundNamedNode as NamedNode).value).toBe(
"https://some.vocab/object"
);
});
it("accepts Properties as Named Nodes", () => {
const thingWithNamedNode = getMockThingWithNamedNode(
"https://some.vocab/predicate",
"https://some.vocab/object"
);
const foundNamedNode = getNamedNode(
thingWithNamedNode,
DataFactory.namedNode("https://some.vocab/predicate")
);
expect(foundNamedNode).not.toBeNull();
expect((foundNamedNode as NamedNode).termType).toBe("NamedNode");
expect((foundNamedNode as NamedNode).value).toBe(
"https://some.vocab/object"
);
});
it("returns null if no Named Node value was found", () => {
const thingWithoutNamedNode: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {},
};
expect(
getNamedNode(thingWithoutNamedNode, "https://some.vocab/predicate")
).toBeNull();
});
it("does not return non-NamedNode values", () => {
const thingWithDifferentTermTypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary string",
"string"
);
(thingWithDifferentTermTypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
expect(
(
getNamedNode(
thingWithDifferentTermTypes,
"https://some.vocab/predicate"
) as NamedNode
).termType
).toBe("NamedNode");
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getNamedNode(
null as unknown as Thing,
"https://arbitrary.vocab/predicate"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getNamedNode(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getNamedNode(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getNamedNodeAll", () => {
it("returns the Named Nodes for the given Predicate", () => {
const thingWithNamedNodes = getMockThingWithNamedNodes(
"https://some.vocab/predicate",
"https://some.vocab/object1",
"https://some.vocab/object2"
);
const foundNamedNodes = getNamedNodeAll(
thingWithNamedNodes,
"https://some.vocab/predicate"
);
expect(foundNamedNodes).toHaveLength(2);
expect(foundNamedNodes[0].termType).toBe("NamedNode");
expect(foundNamedNodes[0].value).toBe("https://some.vocab/object1");
expect(foundNamedNodes[1].termType).toBe("NamedNode");
expect(foundNamedNodes[1].value).toBe("https://some.vocab/object2");
});
it("accepts Properties as Named Nodes", () => {
const thingWithNamedNodes = getMockThingWithNamedNodes(
"https://some.vocab/predicate",
"https://some.vocab/object1",
"https://some.vocab/object2"
);
const foundNamedNodes = getNamedNodeAll(
thingWithNamedNodes,
DataFactory.namedNode("https://some.vocab/predicate")
);
expect(foundNamedNodes).toHaveLength(2);
expect(foundNamedNodes[0].termType).toBe("NamedNode");
expect(foundNamedNodes[0].value).toBe("https://some.vocab/object1");
expect(foundNamedNodes[1].termType).toBe("NamedNode");
expect(foundNamedNodes[1].value).toBe("https://some.vocab/object2");
});
it("returns an empty array if no Named Node values were found", () => {
const thingWithoutNamedNodes: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {},
};
expect(
getNamedNodeAll(thingWithoutNamedNodes, "https://some.vocab/predicate")
).toEqual([]);
});
it("does not return non-NamedNode values", () => {
const thingWithDifferentTermTypes = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Arbitrary string",
"string"
);
(thingWithDifferentTermTypes.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://arbitrary.vocab/object"];
const foundNamedNodes = getNamedNodeAll(
thingWithDifferentTermTypes,
"https://some.vocab/predicate"
);
expect(foundNamedNodes).toHaveLength(1);
expect(foundNamedNodes[0].termType).toBe("NamedNode");
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getNamedNodeAll(
null as unknown as Thing,
"https://arbitrary.vocab/predicate"
)
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getNamedNodeAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getNamedNodeAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getTerm", () => {
it("returns the NamedNode for the given Predicate", () => {
const thingWithNamedNode = getMockThingWithNamedNode(
"https://some.vocab/predicate",
"https://some.vocab/object"
);
const foundTerm = getTerm(
thingWithNamedNode,
"https://some.vocab/predicate"
);
expect(foundTerm).not.toBeNull();
expect((foundTerm as NamedNode).termType).toBe("NamedNode");
expect((foundTerm as NamedNode).value).toBe("https://some.vocab/object");
});
it("returns the Literal for the given Predicate", () => {
const thingWithLiteral = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Some string",
"string"
);
const foundTerm = getTerm(thingWithLiteral, "https://some.vocab/predicate");
expect(foundTerm).not.toBeNull();
expect((foundTerm as Literal).termType).toBe("Literal");
expect((foundTerm as Literal).value).toBe("Some string");
expect((foundTerm as Literal).datatype.value).toBe(
"http://www.w3.org/2001/XMLSchema#string"
);
});
it("returns a NamedNode for a Local Node", () => {
const thingWithNamedNode = getMockThingWithNamedNode(
"https://some.vocab/predicate",
localNodeSkolemPrefix + "local-node-name"
);
const foundTerm = getTerm(
thingWithNamedNode,
"https://some.vocab/predicate"
);
expect(foundTerm).not.toBeNull();
expect((foundTerm as NamedNode).termType).toBe("NamedNode");
expect((foundTerm as NamedNode).value).toBe("#local-node-name");
});
it("returns the Blank Node for the given Predicate", () => {
const thingWithBlankNode: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
blankNodes: ["_:some-blank-node"],
},
},
};
const foundTerm = getTerm(
thingWithBlankNode,
"https://some.vocab/predicate"
);
expect(foundTerm).not.toBeNull();
expect((foundTerm as BlankNode).termType).toBe("BlankNode");
expect((foundTerm as BlankNode).value).toBe("some-blank-node");
});
it("returns the cycle Blank Node for the given Predicate", () => {
const thingWithBlankNode: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
blankNodes: [
{
"https://arbitrary-other.vocab/predicate": {
namedNodes: ["https://arbitrary.url"],
},
},
],
},
},
};
const foundTerm = getTerm(
thingWithBlankNode,
"https://some.vocab/predicate"
);
expect(foundTerm).not.toBeNull();
expect((foundTerm as BlankNode).termType).toBe("BlankNode");
});
it("accepts Properties as Named Nodes", () => {
const thingWithNamedNode = getMockThingWithNamedNode(
"https://some.vocab/predicate",
"https://some.vocab/object"
);
const foundTerm = getTerm(
thingWithNamedNode,
DataFactory.namedNode("https://some.vocab/predicate")
);
expect(foundTerm).not.toBeNull();
expect((foundTerm as NamedNode).termType).toBe("NamedNode");
expect((foundTerm as NamedNode).value).toBe("https://some.vocab/object");
});
it("returns null if no value was found", () => {
const thingWithoutTerm: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {},
};
expect(
getTerm(thingWithoutTerm, "https://some.vocab/predicate")
).toBeNull();
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getTerm(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getTerm(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getTerm(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
});
describe("getTermAll", () => {
it("returns the Named Nodes for the given Predicate", () => {
const thingWithNamedNodes = getMockThingWithNamedNodes(
"https://some.vocab/predicate",
"https://some.vocab/object1",
"https://some.vocab/object2"
);
const foundTerms = getTermAll(
thingWithNamedNodes,
"https://some.vocab/predicate"
);
expect(foundTerms).toHaveLength(2);
expect(foundTerms[0].termType).toBe("NamedNode");
expect(foundTerms[0].value).toBe("https://some.vocab/object1");
expect(foundTerms[1].termType).toBe("NamedNode");
expect(foundTerms[1].value).toBe("https://some.vocab/object2");
});
it("returns the Literals for the given Predicate", () => {
const thingWithLiterals = getMockThingWithLiteralsFor(
"https://some.vocab/predicate",
"Some string 1",
"Some string 2",
"string"
);
const foundTerms = getTermAll(
thingWithLiterals,
"https://some.vocab/predicate"
);
expect(foundTerms).toHaveLength(2);
expect(foundTerms[0].termType).toBe("Literal");
expect(foundTerms[0].value).toBe("Some string 1");
expect((foundTerms[0] as Literal).datatype.value).toBe(
"http://www.w3.org/2001/XMLSchema#string"
);
expect(foundTerms[1].termType).toBe("Literal");
expect(foundTerms[1].value).toBe("Some string 2");
expect((foundTerms[1] as Literal).datatype.value).toBe(
"http://www.w3.org/2001/XMLSchema#string"
);
});
it("returns NamedNodes for Local Nodes", () => {
const thingWithNamedNode = getMockThingWithNamedNode(
"https://some.vocab/predicate",
localNodeSkolemPrefix + "local-node-name"
);
const foundTerms = getTermAll(
thingWithNamedNode,
"https://some.vocab/predicate"
);
expect(foundTerms).toHaveLength(1);
expect(foundTerms[0].termType).toBe("NamedNode");
expect(foundTerms[0].value).toBe("#local-node-name");
});
it("returns Blank Nodes for the given Predicate", () => {
const thingWithBlankNode: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
blankNodes: ["_:some-blank-node"],
},
},
};
const foundTerms = getTermAll(
thingWithBlankNode,
"https://some.vocab/predicate"
);
expect(foundTerms).toHaveLength(1);
expect(foundTerms[0].termType).toBe("BlankNode");
expect(foundTerms[0].value).toBe("some-blank-node");
});
it("returns cycle Blank Nodes for the given Predicate", () => {
const thingWithBlankNode: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {
"https://some.vocab/predicate": {
blankNodes: [
{
"https://arbitrary-other.vocab/predicate": {
namedNodes: ["https://arbitrary.url"],
},
},
],
},
},
};
const foundTerms = getTermAll(
thingWithBlankNode,
"https://some.vocab/predicate"
);
expect(foundTerms).toHaveLength(1);
expect(foundTerms[0].termType).toBe("BlankNode");
});
it("returns Terms of different TermTypes for the given Predicate", () => {
const thingWithMixedTerms = getMockThingWithLiteralFor(
"https://some.vocab/predicate",
"Some string",
"string"
);
(thingWithMixedTerms.predicates["https://some.vocab/predicate"]
.namedNodes as UrlString[]) = ["https://some.vocab/object1"];
const foundTerms = getTermAll(
thingWithMixedTerms,
"https://some.vocab/predicate"
);
expect(foundTerms).toHaveLength(2);
expect(foundTerms[0].termType).toBe("NamedNode");
expect(foundTerms[0].value).toBe("https://some.vocab/object1");
expect(foundTerms[1].termType).toBe("Literal");
expect(foundTerms[1].value).toBe("Some string");
expect((foundTerms[1] as Literal).datatype.value).toBe(
"http://www.w3.org/2001/XMLSchema#string"
);
});
it("accepts Properties as Named Nodes", () => {
const thingWithNamedNodes = getMockThingWithNamedNodes(
"https://some.vocab/predicate",
"https://some.vocab/object1",
"https://some.vocab/object2"
);
const foundNamedNodes = getTermAll(
thingWithNamedNodes,
DataFactory.namedNode("https://some.vocab/predicate")
);
expect(foundNamedNodes).toHaveLength(2);
expect(foundNamedNodes[0].termType).toBe("NamedNode");
expect(foundNamedNodes[0].value).toBe("https://some.vocab/object1");
expect(foundNamedNodes[1].termType).toBe("NamedNode");
expect(foundNamedNodes[1].value).toBe("https://some.vocab/object2");
});
it("returns an empty array if no values were found", () => {
const thingWithoutTerms: Thing = {
type: "Subject",
url: "https://arbitrary.vocab/subject",
predicates: {},
};
expect(
getTermAll(thingWithoutTerms, "https://some.vocab/predicate")
).toEqual([]);
});
it("throws an error when passed something other than a Thing", () => {
expect(() =>
getTermAll(null as unknown as Thing, "https://arbitrary.vocab/predicate")
).toThrow("Expected a Thing, but received: [null].");
});
it("throws an error when passed an invalid property URL", () => {
expect(() =>
getTermAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
)
).toThrow(
"Expected a valid URL to identify a property, but received: [not-a-url]."
);
});
it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => {
let thrownError;
try {
getTermAll(
mockThingFrom("https://arbitrary.pod/resource#thing"),
"not-a-url"
);
} catch (e) {
thrownError = e;
}
expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError);
});
}); | the_stack |
import { TreeGrid } from '../../src/treegrid/base/treegrid';
import { createGrid, destroy } from '../base/treegridutil.spec';
import { sampleData, projectData } from '../base/datasource.spec';
import { Edit } from '../../src/treegrid/actions/edit';
import { Freeze } from '../../src/treegrid/actions/freeze-column';
import { Page } from '../../src/treegrid/actions/page';
import { Toolbar } from '../../src/treegrid/actions/toolbar';
import { profile, inMB, getMemoryProfile } from '../common.spec';
import { Sort } from '../../src/treegrid/actions/sort';
import { Filter } from '../../src/treegrid/actions/filter';
import { isNullOrUndefined, select } from '@syncfusion/ej2-base';
/**
* Grid Batch Edit spec
*/
TreeGrid.Inject(Edit, Toolbar, Sort, Filter, Page, Freeze);
describe('Frozen Columns With Editing', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Hierarchy Frozen- Batch Add', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch" },
allowSorting: true,
allowFiltering: true,
frozenColumns: 3,
treeColumnIndex: 1,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[3].taskID === 41).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(0).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Hierarchy Frozen- Batch Add for next page', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
allowPaging: true,
pageSettings: { pageSize: 2},
frozenColumns: 3,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition:'Below' },
treeColumnIndex: 1,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220, validationRules: { required: true } },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
],
},
done
);
});
it('Add - Batch Editing for next page', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[0].taskID === 41).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
gridObj.goToPage(2);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(0).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = "Planning Progress";
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Hierarchy Frozen- Batch Add NewRowPosition Below', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Below" },
allowSorting: true,
allowFiltering: true,
treeColumnIndex: 1,
frozenColumns: 3,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[0].subtasks[1].taskID === 41).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
gridObj.selectRow(1);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(2).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Hierarchy Frozen- Batch Add NewRowPosition Above', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Above" },
allowSorting: true,
allowFiltering: true,
treeColumnIndex: 1,
frozenColumns: 3,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[0].taskID === 41).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(0).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Hierarchy Frozen- Batch Add NewRowPosition Child', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Child" },
allowSorting: true,
allowFiltering: true,
treeColumnIndex: 1,
frozenColumns: 3,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[0].subtasks[0].subtasks.length === 1).toBe(true);
expect(gridObj.getRowByIndex(1).querySelectorAll('.e-treegridexpand').length === 1).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
gridObj.selectRow(1);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(2).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Hierarchy Frozen- Random action checking', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
allowPaging: true,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Child" },
allowSorting: true,
allowFiltering: true,
frozenColumns: 3,
treeColumnIndex: 1,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[1].subtasks[3].taskID === 41).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
gridObj.selectRow(5);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_delete' } });
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(6).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Hierarchy Frozen- Batch cancel checking', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
allowPaging: true,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Child" },
allowSorting: true,
allowFiltering: true,
frozenColumns: 3,
treeColumnIndex: 1,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[0].subtasks[0].taskID === 2).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
gridObj.selectRow(6);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_delete' } });
gridObj.selectRow(1);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(2).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
gridObj.selectRow(3);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(4).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 42;
expect(gridObj.getBatchChanges()[addedRecords].length === 2).toBe(true);
gridObj.selectRow(5);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_cancel' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Hierarchy Frozen - Random Batch update checking', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
allowPaging: true,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Below" },
allowSorting: true,
allowFiltering: true,
frozenColumns: 3,
treeColumnIndex: 1,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[1].subtasks.length === 5).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
gridObj.selectRow(5);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_delete' } });
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 42;
expect(gridObj.getBatchChanges()[addedRecords].length === 2).toBe(true);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
// describe('Hierarchy Frozen - Child update count checking', () => {
// let gridObj: TreeGrid;
// let actionComplete: () => void;
// beforeAll((done: Function) => {
// gridObj = createGrid(
// {
// dataSource: sampleData,
// childMapping: 'subtasks',
// allowPaging: true,
// editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Below" },
// allowSorting: true,
// allowFiltering: true,
// treeColumnIndex: 1,
// frozenColumns: 3,
// toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
// columns: [
// {
// field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
// validationRules: { required: true, number: true}, width: 90
// },
// { field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
// { field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
// format: 'yMd' },
// { field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
// type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
// { field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
// { field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
// { field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
// { field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
// ]
// },
// done
// );
// });
// it('Add - Batch Editing', (done: Function) => {
// actionComplete = (args?: Object): void => {
// if (args['requestType'] == "batchSave" ) {
// expect(gridObj.dataSource[1].taskID === 42).toBe(true);
// }
// done();
// }
// let addedRecords = 'addedRecords';
// gridObj.grid.actionComplete = actionComplete;
// gridObj.selectRow(1);
// (<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
// (gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
// gridObj.selectRow(0);
// (<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
// (gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 42;
// expect(gridObj.getBatchChanges()[addedRecords].length === 2).toBe(true);
// (<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
// select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
// });
// afterAll(() => {
// destroy(gridObj);
// });
// });
describe('Hierarchy Frozen - gotopage delete and add', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
allowPaging: true,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Below" },
allowSorting: true,
allowFiltering: true,
frozenColumns: 3,
treeColumnIndex: 1,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[2].subtasks[1].subtasks[0].subtasks[6] === 42).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
gridObj.grid.goToPage(3);
gridObj.selectRow(4);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_delete' } });
gridObj.selectRow(3);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 42;
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Hierarchy Frozen editing - Batch Mode', () => {
let gridObj: TreeGrid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, mode: 'Batch', allowDeleting: true, allowAdding: true },
frozenColumns: 3,
treeColumnIndex: 1,
toolbar: ['Add', 'Edit', 'Update'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('record double click', () => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(2, 1).dispatchEvent(event);
});
it('batch changeds and save record', () => {
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'test';
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
expect(gridObj.getBatchChanges()['changedRecords'].length === 1).toBe(true);
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
it('Batch Add Datasource check - Batch Editing', () => {
expect(gridObj.dataSource[0].subtasks[1].taskName === 'test').toBe(true);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Hierarchy Frozen editing - Batch Edit with expand/collapse request', () => {
let gridObj: TreeGrid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, mode: 'Batch', allowDeleting: true, allowAdding: true },
treeColumnIndex: 1,
toolbar: ['Add', 'Edit', 'Update'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('record double click', () => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(2, 1).dispatchEvent(event);
});
it('batch edit', () => {
let click: MouseEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'test';
gridObj.getRowByIndex(1).dispatchEvent(click);
});
it('collapse record', () => {
let method: string = 'expandCollapseRequest';
gridObj[method](gridObj.getRowByIndex(0).querySelector('.e-treegridexpand'));
expect(gridObj.getBatchChanges()['changedRecords'].length === 1).toBe(true);
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Filtering Frozen Columns with Edit', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
allowFiltering:true,
frozenColumns: 3,
treeColumnIndex: 1,
editSettings: {
allowAdding: true,
allowEditing: true,
allowDeleting: true,
mode: 'Batch',
newRowPosition: 'Bottom'
},
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Filtering with batch update', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[0].taskName === 'test').toBe(true);
}
done();
}
gridObj.filterByColumn('priority', 'equal', 'Normal', 'and', true);
gridObj.grid.actionComplete = actionComplete;
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(0, 2).dispatchEvent(event);
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'test';
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
expect(gridObj.getBatchChanges()['changedRecords'].length === 1).toBe(true);
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Sorting Frozen Columns with Edit', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
allowSorting: true,
treeColumnIndex: 1,
frozenColumns: 3,
editSettings: {
allowAdding: true,
allowEditing: true,
allowDeleting: true,
mode: 'Batch'
},
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Sorting with batch update', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[2].taskName === 'test').toBe(true);
}
done();
}
gridObj.sortByColumn('taskID', 'Descending', false);
gridObj.grid.actionComplete = actionComplete;
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(0, 2).dispatchEvent(event);
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'test';
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
expect(gridObj.getBatchChanges()['changedRecords'].length === 1).toBe(true);
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('FlatData Frozen - Batch Add', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: projectData,
idMapping: 'TaskID',
parentIdMapping: 'parentID',
treeColumnIndex: 1,
frozenColumns: 3,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch" },
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{ field: "TaskID", headerText: "Task ID", width: 90, isPrimaryKey: true },
{ field: 'TaskName', headerText: 'Task Name', width: 60 },
{ field: 'Progress', headerText: 'Progress', textAlign: 'Right', width: 90 },
{ field: 'StartDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'EndDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[4].taskID === 41).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(0).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('FlatData Frozen - Batch Add NewRowPosition Below', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: projectData,
idMapping: 'TaskID',
parentIdMapping: 'parentID',
treeColumnIndex: 1,
frozenColumns: 3,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Below" },
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{ field: "TaskID", headerText: "Task ID", width: 90, isPrimaryKey: true },
{ field: 'TaskName', headerText: 'Task Name', width: 60 },
{ field: 'Progress', headerText: 'Progress', textAlign: 'Right', width: 90 },
{ field: 'StartDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'EndDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[2].taskID === 41).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
gridObj.selectRow(1);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(2).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('FlatData Frozen - Batch Add NewRowPosition Above', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: projectData,
idMapping: 'TaskID',
parentIdMapping: 'parentID',
treeColumnIndex: 1,
frozenColumns: 3,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Above" },
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{ field: "TaskID", headerText: "Task ID", width: 90, isPrimaryKey: true },
{ field: 'TaskName', headerText: 'Task Name', width: 60 },
{ field: 'Progress', headerText: 'Progress', textAlign: 'Right', width: 90 },
{ field: 'StartDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd'},
{ field: 'EndDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[1].taskID === 41).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
gridObj.selectRow(1);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(1).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('FlatData Frozen - Batch Add NewRowPosition Child', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: projectData,
idMapping: 'TaskID',
parentIdMapping: 'parentID',
frozenColumns: 3,
treeColumnIndex: 1,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Child" },
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{ field: "TaskID", headerText: "Task ID", width: 90, isPrimaryKey: true },
{ field: 'TaskName', headerText: 'Task Name', width: 60 },
{ field: 'Progress', headerText: 'Progress', textAlign: 'Right', width: 90 },
{ field: 'StartDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd'},
{ field: 'EndDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
]
},
done
);
});
it('Add - Batch Editing', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.getRowByIndex(1).querySelectorAll('.e-treegridexpand').length === 1).toBe(true);
expect(gridObj.dataSource[2].taskID === 41).toBe(true);
}
done();
}
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
gridObj.selectRow(1);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
expect(gridObj.getRowByIndex(2).classList.contains('e-insertedrow')).toBe(true);
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Flat data - Batch Edit ', () => {
let gridObj: TreeGrid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: projectData,
idMapping: 'TaskID',
frozenColumns: 3,
parentIdMapping: 'parentID',
treeColumnIndex: 1,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch" },
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{ field: "TaskID", headerText: "Task ID", width: 90, isPrimaryKey: true },
{ field: 'TaskName', headerText: 'Task Name', width: 60 },
{ field: 'Progress', headerText: 'Progress', textAlign: 'Right', width: 90 },
{ field: 'StartDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd'},
{ field: 'EndDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
]
},
done
);
});
it('record double click', () => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(2, 1).dispatchEvent(event);
});
it('batch changes and save record', () => {
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'test';
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
expect(gridObj.getBatchChanges()["changedRecords"].length === 1).toBe(true);
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
it('Batch Add Datasource check - Batch Editing', () => {
expect(gridObj.dataSource[2].TaskName === 'test').toBe(true);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Filtering', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: projectData,
idMapping: 'TaskID',
parentIdMapping: 'parentID',
treeColumnIndex: 1,
frozenColumns: 3,
allowFiltering: true,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch" },
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{ field: "TaskID", headerText: "Task ID", width: 90, isPrimaryKey: true },
{ field: 'TaskName', headerText: 'Task Name', width: 60 },
{ field: 'Progress', headerText: 'Progress', textAlign: 'Right', width: 90 },
{ field: 'StartDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd'},
{ field: 'EndDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
]
},
done
);
});
it('Filtering with batch update', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[0].TaskName === 'test').toBe(true);
}
done();
}
gridObj.filterByColumn('TaskName', 'equal', 'Parent Task 1', 'and', true);
gridObj.grid.actionComplete = actionComplete;
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(0, 2).dispatchEvent(event);
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'test';
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
expect(gridObj.getBatchChanges()['changedRecords'].length === 1).toBe(true);
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Sorting', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: projectData,
idMapping: 'TaskID',
parentIdMapping: 'parentID',
treeColumnIndex: 1,
frozenColumns: 3,
allowSorting: true,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch" },
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{ field: "TaskID", headerText: "Task ID", width: 90, isPrimaryKey: true },
{ field: 'TaskName', headerText: 'Task Name', width: 60 },
{ field: 'Progress', headerText: 'Progress', textAlign: 'Right', width: 90 },
{ field: 'StartDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd'},
{ field: 'EndDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
]
},
done
);
});
it('Sorting with batch update', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.dataSource[3].TaskName === 'test').toBe(true);
}
done();
}
gridObj.sortByColumn('TaskID', 'Descending', false);
gridObj.grid.actionComplete = actionComplete;
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(0, 1).dispatchEvent(event);
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'test';
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
expect(gridObj.getBatchChanges()['changedRecords'].length === 1).toBe(true);
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
});
afterAll(() => {
destroy(gridObj);
});
});
describe(' Batch Delete cancel checking', () => {
let gridObj: TreeGrid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
allowPaging: true,
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch", newRowPosition: "Child" },
allowSorting: true,
allowFiltering: true,
treeColumnIndex: 1,
frozenColumns: 3,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd'},
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Batch Delete cancel action ', () => {
let childRecords: string = 'childRecords';
gridObj.selectRow(6);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_delete' } });
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_cancel' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
expect(gridObj.getCurrentViewRecords()[0][childRecords].length === 4).toBe(true);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('While delete all records then add record showing script error', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Batch" },
allowSorting: true,
allowFiltering: true,
frozenColumns: 3,
treeColumnIndex: 1,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220, },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Delete all records then add new record', (done: Function) => {
actionComplete = (args?: Object): void => {
if (args['requestType'] == "batchSave" ) {
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
}
done();
}
gridObj.selectRow(0);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_delete' } });
gridObj.selectRow(6);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_delete' } });
gridObj.selectRow(12);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_delete' } });
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
let addedRecords = 'addedRecords';
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 40;
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(0, 1).dispatchEvent(event);
gridObj.grid.actionComplete = actionComplete;
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
});
it('Add - Batch Editing', () => {
let addedRecords = 'addedRecords';
gridObj.grid.actionComplete = actionComplete;
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
(gridObj.element.querySelector('.e-editedbatchcell').querySelector('input') as any).value = 41;
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
select('#' + gridObj.element.id + '_gridcontrol' + 'EditConfirm', gridObj.element).querySelectorAll('button')[0].click();
expect(gridObj.getBatchChanges()[addedRecords].length === 1).toBe(true);
});
afterAll(() => {
destroy(gridObj);
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
}); | the_stack |
import React from 'react';
import { createRouteURL } from '../router';
import { timeAgo, useErrorState } from '../util';
import { useConnectApi } from '.';
import { ApiError, apiFactory, apiFactoryWithNamespace, post } from './apiProxy';
import CronJob from './cronJob';
import DaemonSet from './daemonSet';
import Deployment from './deployment';
import { KubeEvent } from './event';
import Job from './job';
import ReplicaSet from './replicaSet';
import StatefulSet from './statefulSet';
export interface Cluster {
name: string;
useToken?: boolean;
[propName: string]: any;
}
export interface KubeObjectInterface {
kind: string;
apiVersion?: string;
metadata: KubeMetadata;
[otherProps: string]: any;
}
export interface StringDict {
[key: string]: string;
}
export interface KubeMetadata {
uid: string;
name: string;
namespace?: string;
creationTimestamp: string;
resourceVersion: string;
selfLink: string;
labels?: StringDict;
annotations?: StringDict;
ownerReferences?: KubeOwnerReference[];
}
export interface KubeOwnerReference {
apiVersion: string;
blockOwnerDeletion: boolean;
controller: boolean;
kind: string;
name: string;
uid: string;
}
// We have to define a KubeObject implementation here because the KubeObject
// class is defined within the function and therefore not inferable.
export interface KubeObjectIface<T extends KubeObjectInterface | KubeEvent> {
apiList: (onList: (arg: InstanceType<KubeObjectIface<T>>[]) => void) => any;
useApiList: (
onList: (arg: InstanceType<KubeObjectIface<T>>[]) => void,
onError?: (err: ApiError) => void
) => any;
useApiGet: (
onGet: (...args: any) => void,
name: string,
namespace?: string,
onError?: (err: ApiError) => void
) => void;
useList: (
onList?: (...arg: any[]) => any
) => [any[], ApiError | null, (items: any[]) => void, (err: ApiError | null) => void];
getErrorMessage: (err: ApiError | null) => string | null;
new (json: T): any;
className: string;
[prop: string]: any;
}
export function makeKubeObject<T extends KubeObjectInterface | KubeEvent>(
objectName: string
): KubeObjectIface<T> {
class KubeObject {
static apiEndpoint: ReturnType<typeof apiFactoryWithNamespace | typeof apiFactory>;
jsonData: T | null = null;
constructor(json: T) {
this.jsonData = json;
}
static get className(): string {
return objectName;
}
get detailsRoute(): string {
return this._class().className;
}
get listRoute(): string {
return this.detailsRoute + 's';
}
getDetailsLink() {
const params = {
namespace: this.getNamespace(),
name: this.getName(),
};
const link = createRouteURL(this.detailsRoute, params);
return link;
}
getListLink() {
return createRouteURL(this.listRoute);
}
getName() {
return this.metadata.name;
}
getNamespace() {
return this.metadata.namespace;
}
getCreationTs() {
return this.metadata.creationTimestamp;
}
getAge() {
return timeAgo(this.getCreationTs());
}
getValue(prop: string) {
return this.jsonData![prop];
}
get metadata() {
return this.jsonData!.metadata;
}
get kind() {
return this.jsonData!.kind;
}
static apiList<U extends KubeObject>(
onList: (arg: U[]) => void,
onError?: (err: ApiError) => void
) {
const createInstance = (item: T) => this.create(item) as U;
const args: any[] = [(list: T[]) => onList(list.map((item: T) => createInstance(item) as U))];
if (this.apiEndpoint.isNamespaced) {
args.unshift(null);
}
if (onError) {
args.push(onError);
}
return this.apiEndpoint.list.bind(null, ...args);
}
static useApiList<U extends KubeObject>(
onList: (...arg: any[]) => any,
onError?: (err: ApiError) => void
) {
const listCallback = onList as (arg: U[]) => void;
useConnectApi(this.apiList(listCallback, onError));
}
static useList<U extends KubeObject>(): [
U[] | null,
ApiError | null,
(items: U[]) => void,
(err: ApiError | null) => void
] {
const [objList, setObjList] = React.useState<U[] | null>(null);
const [error, setError] = useErrorState(setObjList);
function setList(items: U[] | null) {
setObjList(items);
if (items !== null) {
setError(null);
}
}
this.useApiList(setList, setError);
// Return getters and then the setters as the getters are more likely to be used with
// this function.
return [objList, error, setObjList, setError];
}
static create<U extends KubeObject>(this: new (arg: T) => U, item: T): U {
return new this(item) as U;
}
static apiGet<U extends KubeObject>(
onGet: (...args: any) => void,
name: string,
namespace?: string
) {
const createInstance = (item: T) => this.create(item) as U;
const args: any[] = [name, (obj: T) => onGet(createInstance(obj))];
if (this.apiEndpoint.isNamespaced) {
args.unshift(namespace);
}
return this.apiEndpoint.get.bind(null, ...args);
}
static useApiGet<U extends KubeObject>(
onGet: (...args: any) => any,
name: string,
namespace?: string
) {
// We do the type conversion here because we want to be able to use hooks that may not have
// the exact signature as get callbacks.
const getCallback = onGet as (item: U) => void;
useConnectApi(this.apiGet(getCallback, name, namespace));
}
private _class() {
return this.constructor as typeof KubeObject;
}
delete() {
const args: string[] = [this.getName()];
if (this._class().apiEndpoint.isNamespaced) {
args.unshift(this.getNamespace()!);
}
return this._class().apiEndpoint.delete(...args);
}
update(data: KubeObjectInterface) {
return this._class().put(data);
}
static put(data: KubeObjectInterface) {
return this.apiEndpoint.put(data);
}
async getAuthorization(verb: string) {
const resourceAttrs: {
name: string;
verb: string;
namespace?: string;
} = {
name: this.getName(),
verb,
};
const namespace = this.getNamespace();
if (!!namespace) {
resourceAttrs['namespace'] = namespace;
}
const spec = {
resourceAttributes: resourceAttrs,
};
const versions = ['v1', 'v1beta1'];
for (let i = 0; i < versions.length; i++) {
const version = versions[i];
try {
return await post(
`/apis/authorization.k8s.io/${version}/selfsubjectaccessreviews`,
{
kind: 'SelfSubjectAccessReview',
apiVersion: `authorization.k8s.io/${version}`,
spec,
},
false
);
} catch (err) {
// If this is the last attempt or the error is not 404, let it throw.
if ((err as ApiError).status !== 404 || i === versions.length - 1) {
throw err;
}
}
}
}
static getErrorMessage(err: ApiError | null) {
if (!err) {
return null;
}
switch (err.status) {
case 404:
return 'Error: Not found';
case 403:
return 'Error: No permissions';
default:
return 'Error';
}
}
}
return KubeObject as KubeObjectIface<T>;
}
export type KubeObjectClass = ReturnType<typeof makeKubeObject>;
export type KubeObject = InstanceType<KubeObjectClass>;
export interface KubeCondition {
type: string;
status: string;
lastProbeTime: number;
lastTransitionTime?: string;
lastUpdateTime?: string;
reason?: string;
message?: string;
}
export interface KubeContainer {
name: string;
image: string;
command?: string[];
args?: string[];
ports: {
name?: string;
containerPort: number;
protocol: string;
}[];
resources?: {
limits: {
cpu: string;
memory: string;
};
requests: {
cpu: string;
memory: string;
};
};
env?: {
name: string;
value?: string;
valueFrom?: {
fieldRef?: {
apiVersion: string;
fieldPath: string;
};
secretKeyRef?: {
key: string;
name: string;
};
configMapKeyRef?: {
key: string;
name: string;
};
};
}[];
envFrom?: {
configMapRef?: {
name: string;
};
}[];
volumeMounts?: {
name: string;
readOnly: boolean;
mountPath: string;
}[];
livenessProbe?: KubeContainerProbe;
readinessProbe?: KubeContainerProbe;
imagePullPolicy: string;
}
interface KubeContainerProbe {
httpGet?: {
path?: string;
port: number;
scheme: string;
host?: string;
};
exec?: {
command: string[];
};
tcpSocket?: {
port: number;
};
initialDelaySeconds?: number;
timeoutSeconds?: number;
periodSeconds?: number;
successThreshold?: number;
failureThreshold?: number;
}
export interface LabelSelector {
matchExpressions?: {
key: string;
operator: string;
values: string[];
};
matchLabels?: {
[key: string]: string;
};
}
export interface KubeMetrics {
metadata: KubeMetadata;
usage: {
cpu: string;
memory: string;
};
status: {
capacity: {
cpu: string;
memory: string;
};
};
}
export interface KubeContainerStatus {
containerID: string;
image: string;
imageID: string;
lastState: string;
name: string;
ready: boolean;
restartCount: number;
state: {
running: {
startedAt: number;
};
terminated: {
containerID: string;
exitCode: number;
finishedAt: number;
message: string;
reason: string;
signal: number;
startedAt: number;
};
waiting: {
message: string;
reason: string;
};
};
}
export type Workload = DaemonSet | ReplicaSet | StatefulSet | Job | CronJob | Deployment; | the_stack |
import IORedis from 'ioredis';
import lodash from 'lodash';
import * as shortid from 'shortid';
import { ReplyError } from 'redis-errors';
import { initScripts, Redis } from './commands';
import { waitUntilInitialized } from './common';
import { parseStreamResponse, parseXPendingResponse, StreamValue } from './redis-transformers';
import { Task } from './task';
import { TimeoutError } from './errors';
import { defaultOptions, LoggingOptions, ConsumerOptions, RedisOptions } from './defaults';
export interface ConsumerUnitOptions {
redisOptions?: RedisOptions;
loggingOptions?: LoggingOptions;
consumerOptions?: ConsumerOptions;
}
export interface Metadata {
id: string;
qname: string;
retryCount: number;
consumerName: string;
}
export class ConsumerUnit {
_paused: boolean;
_QNAME: string;
_DEDUPSET: string;
qname: string;
_GRPNAME: string;
workerFn: Function;
_pendingTasks: Task[];
_totalTasks: number;
consumerOptions: ConsumerOptions;
loggingOptions: LoggingOptions;
_redis: Redis;
redisOptions: RedisOptions = defaultOptions.redisOptions;
_name = '';
_isInitialized = false;
_loopStarted = false;
constructor(
qname: string,
workerFn: Function,
{ consumerOptions, redisOptions, loggingOptions }: ConsumerUnitOptions = {}
) {
this._paused = true;
this._QNAME = `${defaultOptions.NAMESPACE}:queue:${qname}`;
this._DEDUPSET = `${defaultOptions.NAMESPACE}:queue:${qname}:dedupset`;
this.qname = qname;
this._GRPNAME = `${defaultOptions.NAMESPACE}:queue:${qname}:cg`;
this.workerFn = workerFn;
this._pendingTasks = [];
this._totalTasks = 0;
this.consumerOptions = lodash.merge({}, defaultOptions.consumerOptions, consumerOptions);
this.loggingOptions = lodash.merge({}, defaultOptions.loggingOptions, loggingOptions);
this.redisOptions = lodash.merge({}, defaultOptions.redisOptions, redisOptions);
this._redis = new IORedis(this.redisOptions) as Redis;
this._initialize();
}
start() {
waitUntilInitialized(this, '_isInitialized').then(() => {
this._paused = false;
this._processLoop();
});
}
pause() {
// TODO: Update globally `${orkidDefaults.NAMESPACE}:queue:${this.qname}:settings`
// Also inform other queues via pub/sub
this._paused = true;
}
resume() {
this.start();
}
_log(msg: string, ...optionalParams: any[]) {
if (this.loggingOptions.enabled && this.loggingOptions.loggerFn) {
this.loggingOptions.loggerFn(`Orkid :: ${this._name}`, msg, ...optionalParams);
}
}
async _ensureConsumerGroupExists() {
try {
// XGROUP CREATE mystream mygroup 0 MKSTREAM
this._log('Ensuring consumer group exists', { QNAME: this._QNAME, GRPNAME: this._GRPNAME });
// xgroup: https://redis.io/commands/xgroup
await this._redis.xgroup('CREATE', this._QNAME, this._GRPNAME, 0, 'MKSTREAM');
} catch (e) {
// BUSYGROUP -> the consumer group is already present, ignore
if (!(e instanceof ReplyError && e.message.includes('BUSYGROUP'))) {
throw e;
}
}
}
async _initialize() {
if (this._name) {
// We already have a name? Reconnecting in this case
// https://redis.io/commands/client-setname
await this._redis.client('SETNAME', this._name);
return;
}
await initScripts(this._redis);
const id = await this._redis.client('id');
this._name = `${this._GRPNAME}:c:${id}-${shortid.generate()}`;
await this._redis.client('SETNAME', this._name);
await this._ensureConsumerGroupExists();
this._isInitialized = true;
}
async _getPendingTasks() {
this._log('Checking pending tasks');
// xreadgroup: https://redis.io/commands/xreadgroup
const redisReply = await this._redis.xreadgroup(
'GROUP',
this._GRPNAME,
this._name,
'COUNT',
this.consumerOptions.taskBufferSize,
'STREAMS',
this._QNAME,
'0'
);
const taskObj = parseStreamResponse(redisReply);
// @ts-ignore
const tasks: StreamValue[] = [].concat(...Object.values(taskObj));
for (const t of tasks) {
const task = new Task(t.id, t.data);
this._pendingTasks.push(task);
}
// Used for testing
return tasks.length;
}
async _waitForTask() {
this._log(`Waiting for tasks. Processed so far: ${this._totalTasks}`);
// xreadgroup: https://redis.io/commands/xreadgroup
await this._redis.xreadgroup(
'GROUP',
this._GRPNAME,
this._name,
'BLOCK',
0,
'COUNT',
1,
'STREAMS',
this._QNAME,
'>'
);
this._log('Got new task');
}
/*
Cleanup does the following things:
- Get list of all consumers in current group
- Find out which consumers are not active anymore in redis but have tasks
- Find out which consumers are not active anymore in redis and empty
- Claim ownership of tasks from inactive and non-empty consumers to process
- Delete inactive and empty consumers to keep things tidy
*/
async _cleanUp() {
/* Returns items that are present in setA but not in setB */
function difference(setA: Set<string>, setB: Set<string>) {
const _difference = new Set(setA);
for (const elem of setB) {
_difference.delete(elem);
}
return _difference;
}
// xinfo: https://redis.io/commands/xinfo
// Get the list of every consumer in a specific consumer group
const info = await this._redis.xinfo('CONSUMERS', this._QNAME, this._GRPNAME);
const consumerInfo: Record<string, any> = {};
for (const inf of info) {
const data: Record<string, any> = {};
for (let i = 0; i < inf.length; i += 2) {
data[inf[i]] = inf[i + 1];
}
consumerInfo[inf[1]] = data;
}
const consumerNames = Object.keys(consumerInfo);
const pendingConsumerNames: Set<string> = new Set();
const emptyIdleConsumerNames: Set<string> = new Set();
// Separate consumers with some pending tasks and no pending tasks
for (const con of consumerNames) {
if (consumerInfo[con].pending) {
pendingConsumerNames.add(con);
} else if (consumerInfo[con].idle > <number>this.consumerOptions.stealFromInactiveConsumersAfterMs * 2) {
// Just to be safe, only delete really old consumers
emptyIdleConsumerNames.add(con);
}
}
// https://redis.io/commands/client-list
const clients = (await this._redis.client('LIST')).split('\n');
const activeWorkers: Set<string> = new Set();
// Orkid consumers always set a name to redis connection
// Filter active connections those have names
for (const cli of clients) {
const values = cli.split(' ');
for (const v of values) {
if (v.startsWith('name=')) {
const namePair = v.split('=');
if (namePair.length > 1 && namePair[1].length) {
activeWorkers.add(namePair[1]);
}
}
}
}
// Workers that have pending tasks but are not active anymore in redis
const orphanWorkers = difference(pendingConsumerNames, activeWorkers);
// Workers that have not pending tasks and also are not active anymore in redis
const orphanEmptyWorkers = difference(emptyIdleConsumerNames, activeWorkers);
const claimInfo: Record<string, number> = {};
for (const w of orphanWorkers) {
// xpending: https://redis.io/commands/xpending
const redisXPendingReply = await this._redis.xpending(this._QNAME, this._GRPNAME, '-', '+', 1000, w);
const pendingTasks = parseXPendingResponse(redisXPendingReply);
let ids: string[] = [];
if (Array.isArray(pendingTasks)) {
ids = pendingTasks.map(t => t.id);
}
// xclaim: https://redis.io/commands/xclaim
const claim = <Array<any>>(
await this._redis.xclaim(
this._QNAME,
this._GRPNAME,
this._name,
<number>this.consumerOptions.stealFromInactiveConsumersAfterMs,
...ids,
'JUSTID'
)
);
claimInfo[w] = claim.length;
this._log(`Claimed ${claim.length} pending tasks from worker ${w}`);
}
// Housecleaning. Remove empty and inactive consumers since redis doesn't do that itself
const deleteInfo = [];
for (const w of orphanEmptyWorkers) {
// Our custom lua script to recheck and delete consumer atomically and safely
await this._redis.delconsumer(this._QNAME, this._GRPNAME, w);
deleteInfo.push(w);
this._log(`Deleted old consumer ${w}`);
}
// Return value used for testing
const retval = {
consumerNames,
pendingConsumerNames: Array.from(pendingConsumerNames),
emptyIdleConsumerNames: Array.from(emptyIdleConsumerNames),
activeWorkers: Array.from(activeWorkers),
orphanWorkers: Array.from(orphanWorkers),
orphanEmptyWorkers: Array.from(orphanEmptyWorkers),
claimInfo,
deleteInfo
};
this._log(`Cleanup result:`, retval);
return retval;
}
async _processLoop() {
if (this._loopStarted) {
return;
}
this._loopStarted = true;
while (!this._paused) {
await this._cleanUp();
await this._getPendingTasks();
if (!this._pendingTasks.length) {
await this._waitForTask();
}
while (this._pendingTasks.length && !this._paused) {
await this._processTask();
}
}
this._loopStarted = false;
}
async _processTask() {
if (!this._pendingTasks.length) {
return;
}
const task = this._pendingTasks.shift() as Task;
this._log('Starting to process task', task);
this._totalTasks++;
await this._redis
.pipeline()
.hincrby(defaultOptions.STAT, 'processed', 1)
.hincrby(`${defaultOptions.STAT}:${this.qname}`, 'processed', 1)
.exec();
const metadata = { id: task.id, qname: this.qname, retryCount: task.retryCount, consumerName: this._name };
try {
const result = await this._wrapWorkerFn(task.dataObj, metadata);
await this._processSuccess(task, result);
} catch (e) {
if (e instanceof TimeoutError) {
this._log(`Worker ${task.id} timed out`, e);
} else {
this._log(`Worker ${task.id} crashed`, e);
}
await this._processFailure(task, e);
}
}
async _processSuccess(task: Task, result: any) {
this._log(`Worker ${task.id} returned`, result);
const resultVal = JSON.stringify({
id: task.id,
qname: this.qname,
data: task.dataObj,
dedupKey: task.dedupKey,
retryCount: task.retryCount,
result,
at: new Date().toISOString()
});
// Add to success list
const timestamp = new Date().getTime().toString();
await this._redis
.pipeline()
.dequeue(this._QNAME, this._DEDUPSET, this._GRPNAME, task.id, task.dedupKey) // Remove from queue
.zadd(defaultOptions.RESULTLIST, timestamp, resultVal)
.zremrangebyrank(defaultOptions.RESULTLIST, 0, (defaultOptions.queueOptions.maxGlobalListSize! + 1) * -1)
.zadd(`${defaultOptions.RESULTLIST}:${this.qname}`, timestamp, resultVal)
.zremrangebyrank(
`${defaultOptions.RESULTLIST}:${this.qname}`,
0,
(defaultOptions.queueOptions.maxIndividualQueueResultSize! + 1) * -1
)
.exec();
}
async _processFailure(task: Task, error: Error) {
const info = JSON.stringify({
id: task.id,
qname: this.qname,
data: task.dataObj,
dedupKey: task.dedupKey,
retryCount: task.retryCount,
error: {
name: error.name,
message: error.message,
stack: error.stack
},
at: new Date().toISOString()
});
if (task.retryCount < <number>this.consumerOptions.maxRetry) {
task.incrRetry();
// Send again to the queue
await this._redis
.pipeline()
.requeue(this.qname, this._DEDUPSET, this._GRPNAME, task.id, task.dataString, task.dedupKey, task.retryCount)
.hincrby(defaultOptions.STAT, 'retries', 1)
.hincrby(`${defaultOptions.STAT}:${this.qname}`, 'retries', 1)
.exec();
} else {
// Move to deadlist
const timestamp = new Date().getTime().toString();
await this._redis
.pipeline()
.dequeue(this._QNAME, this._DEDUPSET, this._GRPNAME, task.id, task.dedupKey) // Remove from queue
.zadd(defaultOptions.DEADLIST, timestamp, info)
.zremrangebyrank(defaultOptions.DEADLIST, 0, (defaultOptions.queueOptions.maxGlobalListSize! + 1) * -1)
.zadd(`${defaultOptions.DEADLIST}:${this.qname}`, timestamp, info)
.zremrangebyrank(
`${defaultOptions.DEADLIST}:${this.qname}`,
0,
(defaultOptions.queueOptions.maxIndividualQueueResultSize! + 1) * -1
)
.hincrby(defaultOptions.STAT, 'dead', 1)
.hincrby(`${defaultOptions.STAT}:${this.qname}`, 'dead', 1)
.exec();
}
// Add to failed list in all cases
const timestamp = new Date().getTime().toString();
await this._redis
.pipeline()
.zadd(defaultOptions.FAILEDLIST, timestamp, info)
.zremrangebyrank(defaultOptions.FAILEDLIST, 0, (defaultOptions.queueOptions.maxGlobalListSize! + 1) * -1)
.zadd(`${defaultOptions.FAILEDLIST}:${this.qname}`, timestamp, info)
.zremrangebyrank(
`${defaultOptions.FAILEDLIST}:${this.qname}`,
0,
(defaultOptions.queueOptions.maxIndividualQueueResultSize! + 1) * -1
)
.hincrby(defaultOptions.STAT, 'failed', 1)
.hincrby(`${defaultOptions.STAT}:${this.qname}`, 'failed', 1)
.exec();
}
_wrapWorkerFn(data: any, metadata: Metadata) {
const timeoutMs = this.consumerOptions.workerFnTimeoutMs;
const workerP = this.workerFn(data, metadata);
if (timeoutMs) {
const timeoutP = new Promise((_, reject) => {
const to = setTimeout(() => {
clearTimeout(to);
reject(new TimeoutError(`Task timed out after ${timeoutMs}ms`));
}, timeoutMs);
});
return Promise.race([timeoutP, workerP]);
}
return workerP;
}
async _disconnect() {
this._paused = true;
await waitUntilInitialized(this, '_isInitialized');
await this._redis.disconnect();
}
} | the_stack |
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import { KmsKeyringClass } from '../src/kms_keyring'
import {
NodeAlgorithmSuite,
AlgorithmSuiteIdentifier,
NodeDecryptionMaterial,
EncryptedDataKey,
Keyring,
needs,
Newable,
} from '@aws-crypto/material-management'
chai.use(chaiAsPromised)
const { expect } = chai
describe('KmsKeyring: decrypt EDK order', () => {
describe('with a single configured CMK', () => {
it('short circuit on the first success', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const { edk } = edkHelper()
const edks = [...Array(5)].map(() => edk)
const state = buildProviderState(edks, suite)
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
keyIds: [edk.providerInfo],
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(state.calls).to.equal(1)
})
it('errors should not halt, but also short circuit after success', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const { edk } = edkHelper()
const edks = [...Array(5)].map(() => edk)
const state = buildProviderState(edks, suite, { failureCount: 1 })
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
keyIds: [edk.providerInfo],
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(state.calls).to.equal(2)
})
it('only contract KMS for the single configured CMK', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const edks = [...Array(5)].map(edkHelper).map(({ edk }) => edk)
const state = buildProviderState(edks, suite, { edkSuccessIndex: 4 })
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
keyIds: edks.slice(-1).map((v) => v.providerInfo),
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(state.calls).to.equal(1)
})
})
describe('with multiple configured CMKs', () => {
it('if no EDKs match any CMKs never call KMS', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const edks = [...Array(5)].map(edkHelper).map(({ edk }) => edk)
const keyIds = [...Array(5)]
.map(edkHelper)
.map(({ edk }) => edk)
.map((v) => v.providerInfo)
let calls = 0
const clientProvider: any = () => {
calls += 1
}
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider,
keyIds,
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(false)
expect(calls).to.equal(0)
})
it('short circuit on the first success', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const edks = [...Array(5)].map(edkHelper).map(({ edk }) => edk)
const state = buildProviderState(edks, suite)
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
keyIds: edks.map((v) => v.providerInfo),
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(state.calls).to.equal(1)
})
it('errors should not halt, but also short circuit after success', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const edks = [...Array(5)].map(edkHelper).map(({ edk }) => edk)
const state = buildProviderState(edks, suite, { failureCount: 1 })
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
keyIds: edks.map((v) => v.providerInfo),
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(state.calls).to.equal(2)
})
it('only contract KMS for a single overlapping CMK', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const edks = [...Array(5)].map(edkHelper).map(({ edk }) => edk)
const keyIds = [...Array(5)]
.map(edkHelper)
.map(({ edk }) => edk)
.map((v) => v.providerInfo)
.concat(edks.slice(-1).map((v) => v.providerInfo))
const state = buildProviderState(edks, suite, { edkSuccessIndex: 4 })
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
keyIds: keyIds,
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(state.calls).to.equal(1)
})
})
describe('with a discovery filter that has 1 account', () => {
it('fail every KMS call to ensure we make them all', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const info = edkHelper()
const edks = [...Array(5)].map(() => info.edk)
const accountIDs = [info.accountId]
const state = buildProviderState(edks, suite, {
failureCount: edks.length,
})
const discovery = true
const discoveryFilter = {
partition: 'aws',
accountIDs,
}
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
discovery,
discoveryFilter,
})
await expect(
testKeyring.onDecrypt(new NodeDecryptionMaterial(suite, context), edks)
).to.rejectedWith(
'Unable to decrypt data key and one or more KMS CMKs had an error'
)
expect(state.calls).to.equal(edks.length)
})
it('filter the first, fail the second, and still only 1 KMS call', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const info = edkHelper()
const edks = [edkHelper().edk, info.edk, info.edk, info.edk]
const accountIDs = [info.accountId]
const state = buildProviderState(edks, suite, { failureCount: 1 })
const discovery = true
const discoveryFilter = {
partition: 'aws',
accountIDs,
}
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
discovery,
discoveryFilter,
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(state.calls).to.equal(2)
})
it('filter all out all EDKs results in 0 KMS calls', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const edks = [...Array(5)].map(edkHelper).map(({ edk }) => edk)
const accountIDs = [edkHelper().accountId]
const state = buildProviderState(edks, suite, {
failureCount: edks.length,
})
const discovery = true
const discoveryFilter = {
partition: 'aws',
accountIDs,
}
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
discovery,
discoveryFilter,
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(false)
expect(state.calls).to.equal(0)
})
})
describe('with a discovery filter that has more than 1 account', () => {
it('with only 1 account match', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const info = edkHelper()
const edks = [info.edk]
const accountIDs = [
edkHelper().accountId,
edkHelper().accountId,
edkHelper().accountId,
info.accountId,
]
const state = buildProviderState(edks, suite)
const discovery = true
const discoveryFilter = {
partition: 'aws',
accountIDs,
}
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
discovery,
discoveryFilter,
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(state.calls).to.equal(1)
})
it('where none of the account ids match results in not KMS call', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const edks = [edkHelper().edk]
const accountIDs = [
edkHelper().accountId,
edkHelper().accountId,
edkHelper().accountId,
]
const state = buildProviderState(edks, suite, {
failureCount: edks.length,
})
const discovery = true
const discoveryFilter = {
partition: 'aws',
accountIDs,
}
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
discovery,
discoveryFilter,
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(false)
expect(state.calls).to.equal(0)
})
it('where an account id match but not the partition results in not KMS call', async () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const info = edkHelper()
const edks = [info.edk]
const accountIDs = [
edkHelper().accountId,
edkHelper().accountId,
info.accountId,
]
const state = buildProviderState(edks, suite, {
failureCount: edks.length,
})
const discovery = true
const discoveryFilter = {
partition: 'NOTaws',
accountIDs,
}
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
discovery,
discoveryFilter,
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(false)
expect(state.calls).to.equal(0)
})
describe('filter will reject EDKs for every combination !p,a|p,!a|!p,!a', () => {
const context = { some: 'context' }
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256
)
const noMatchInfo = [
edkHelper('aws'),
edkHelper('notAWS'),
edkHelper('stillNotAws'),
]
const matchInfo = [edkHelper(), edkHelper()]
const edks = [
...noMatchInfo.map(({ edk }) => edk),
...matchInfo.map(({ edk }) => edk),
]
const accountIDs = [
noMatchInfo[1].accountId,
...matchInfo.map(({ accountId }) => accountId),
]
const discovery = true
const discoveryFilter = {
partition: 'aws',
accountIDs,
}
it('fail all calls and verify count', async () => {
const state = buildProviderState(edks, suite, {
failureCount: matchInfo.length,
})
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
discovery,
discoveryFilter,
})
await expect(
testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
).to.rejectedWith(
'Unable to decrypt data key and one or more KMS CMKs had an error'
)
expect(state.calls).to.equal(matchInfo.length)
})
it('fail first call verify success of the second', async () => {
const state = buildProviderState(edks, suite, {
failureCount: 1,
edkSuccessIndex: 4,
})
class TestKmsKeyring extends KmsKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestKmsKeyring({
clientProvider: state.clientProvider,
discovery,
discoveryFilter,
})
const material = await testKeyring.onDecrypt(
new NodeDecryptionMaterial(suite, context),
edks
)
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(state.calls).to.equal(matchInfo.length)
})
})
})
})
function edkHelper(partition?: any) {
// Very dirty uuid "thing"
const keyId = [...Array(3)]
.map(() => Math.random().toString(16).slice(2))
.join('')
const accountId = Math.random().toString().slice(2, 14)
const edk = new EncryptedDataKey({
providerId: 'aws-kms',
providerInfo: `arn:${
typeof partition === 'string' ? partition : 'aws'
}:kms:us-east-1:${accountId}:key/${keyId}`,
encryptedDataKey: Buffer.alloc(5),
})
return {
keyId,
accountId,
edk,
}
}
function buildProviderState(
edks: EncryptedDataKey[],
{ keyLengthBytes }: NodeAlgorithmSuite,
{
failureCount = 0,
edkSuccessIndex,
}: { failureCount?: number; edkSuccessIndex?: number } = {} as any
) {
const providerState = { clientProvider: clientProvider as any, calls: 0 }
return providerState
function clientProvider() {
return { decrypt }
async function decrypt({ KeyId }: any) {
providerState.calls += 1
const { calls } = providerState
// If I need to fail some of the filtered elements
needs(calls > failureCount, 'try again')
/* It may be that the list of EDKs will be flittered.
* in which case the success EDK
* the call count will not
* match the index of the intended EDK.
* In which case just use the one provided...
*/
expect(KeyId).to.equal(edks[edkSuccessIndex || calls - 1].providerInfo)
return {
Plaintext: new Uint8Array(keyLengthBytes),
KeyId,
}
}
}
} | the_stack |
import "@effectful/serialization";
import "@effectful/serialization/dom";
import config from "./config";
export interface Env {
/** local variables */
$: any[];
/** local's sub-scope (loops block scoping) */
}
/** common prototype for call descriptions of each function */
export interface ProtoFrame extends Env {
/** closure captured frame */
// $: Env | null;
/** meta-data */
meta: FunctionDescr;
/** a constructed function's value */
func: () => any;
parent: Frame | null;
}
/** function's call desciption */
export interface Frame extends ProtoFrame, Env {
closure: Closure;
/** current state */
state: number;
/** next iteration state */
goto: number;
/** captured `this` */
self: object | undefined;
/** captured `arguments` */
args: object | undefined;
/** if called as `new` expression */
newTarget: boolean;
/** location's desciption */
brk: Brk | null;
/** current return value */
result?: any;
/** current exception value */
error?: any;
/** next function in the stack */
next: Frame | null;
/** like `next` but keeps real caller for coroutines */
caller: Frame | null;
/** set `context.enabled = true` on exit */
restoreEnabled: any;
/** called if function exits with some resulting value */
onReturn: ((value: any) => void) | null;
/** called if function exits with some exception */
onError: ((reason: any) => void) | null;
/** the promise to settle on `onReturn`/`onError` */
promise: Promise<any> | null;
/** when this frame was last updated */
timestamp: Record | null;
/**
* if the frame is suspended this may provide some
* information what exactly it is awaiting
*/
awaiting?: any;
/** the control flow is currently within generator's */
running: boolean;
done: boolean;
/** global env object (searched by name) */
$g: any;
/** the stop's reason displayed in VSCode */
stopReason: string | null;
}
export interface Record {
operations?: Operation;
prev: Record | null;
}
/** operations trace - callbacks to be executed on reverting state */
export interface Operation {
prev?: Operation;
call(): void;
}
export interface Journal {
/** current checkpoint */
now: Record | null;
/** a list of changes to undo */
past: Record | null;
/** a list of changes to redo */
future: Record | null;
/** the data is collected now */
enabled: boolean;
}
export const journal: Journal = {
now: null,
past: null,
future: null,
enabled: false
};
/** breakpoint description */
export interface Brk {
/** debugger's specific type of the breakpoint */
flags: BrkFlag;
/** unique identifier within the function */
id: number;
meta: FunctionDescr;
line: number;
column: number;
endLine: number;
endColumn: number;
scope: ScopeInfo;
/** textual representation of the location */
location: string;
scopeDepth: number;
logPoint: ((frame: Frame) => void) | null;
breakpoint: {
id: number;
condition: (frame: Frame) => boolean | null;
hitCondition: (frame: Frame) => number;
hits: number;
signal: () => void;
} | null;
}
export enum BrkFlag {
HAS_EH = 1 << 0,
EXPR = 1 << 1,
STMT = 1 << 2,
DEBUGGER_STMT = 1 << 3,
EXIT = 1 << 4,
EMPTY = 1 << 5
}
/** module's description */
export interface Module {
name: string;
/** unique id for loaded modules */
fullPath?: string;
/** unique id (a number for generated modules) */
id?: number | string;
functions: { [name: string]: FunctionDescr };
// pure: boolean;
topLevel: FunctionDescr;
/** `module` object from CommonJS */
cjs: any;
version: number;
/** parent's variables for eval */
evalContext?: { [name: string]: VarInfo };
/** string which is safe to use as a prefix to avoid clashes with other names */
safePrefix: string;
api: any;
closSyms: { [name: string]: any };
params: null | { [name: string]: any };
lines?: Brk[][];
exports: any;
onReload: null | ((next: Module) => void);
prevVersion: Module | null;
}
/** function's description */
export type FunctionDescr = {
/** module where the function is defined */
module: Module;
id: number | null;
name: string;
origName: string | null;
calleeName: number | null;
fullName: string;
blackbox: boolean;
parent: FunctionDescr | null; // Frame?
states: Brk[];
statesByLine: Brk[];
canSkip: boolean;
uniqName: string;
persistName: string;
params: string[];
flags: number;
func: (...args: any[]) => any;
handler: (frame: Frame, locals: { [name: string]: any }, input: any) => any;
errHandler: (f: Frame, locals: { [name: string]: any }) => void;
finHandler: (f: Frame, locals: { [name: string]: any }) => void;
errState: number;
finState: number;
constr: ($$: { [name: string]: any }) => any;
evalMemo?: Map<string, (...args: any[]) => any>;
exitBreakpoint: Brk | null;
line?: number;
column?: number;
endLine?: number;
endColumn?: number;
location?: string;
code: string;
/* number of frame-local variables */
localsNum: number;
/* number of variables in top scope */
varsNum: number;
/** where arguments start */
shift: number;
deps: FunctionDescr[];
scopeDepth: number;
onReload: null | ((prev: Closure, next: Closure) => void);
};
export type NonBlackboxFunctionDescr = FunctionDescr & {
line: number;
column: number;
endLine: number;
endColumn: number;
};
/** describse variable scope (decl depth, function depth, location) */
export type VarInfo = [number, number, string | null];
/** pre-calculated scope information */
export interface ScopeInfo {
/** original variable name to its storing index and depth to parent */
[name: string]: VarInfo;
}
/** passed to this runtime by compiler */
export type Scope = any[] &
(
| {
/** scope object's index and location to their original names */
0: { [name: string]: [number, string | null] };
/** parent's scope */
1: Scope | null;
/** statement's level */
2: number;
length: 3;
}
| {
/** memoized `ScopeInfo` */
3: ScopeInfo;
length: 4;
}
);
type AnyFunc = (...args: any[]) => any;
export interface State {
/** stopping on break points if `true`, otherwise ignoring them */
enabled: boolean;
/** everything is done */
terminated: boolean;
/**
* the engine now runs some code and expects a breakpoint
* otherwise it is some new thread which isn't tracked by the debugger
* and on a next non-blackbox function call it is suspended in `queue`, to run after
* with `running: true` (if the breakpoints aren't ignored by `enabled:false`)
*/
running: boolean;
/** child launch request is received and handled */
launched: boolean;
/** current breakpoint id */
brk: Brk | null;
/** loaded modules (by full path) */
modules: { [name: string]: Module };
/** loaded modules (by CommonJs id) */
modulesById: { [name: string]: Module };
/** saved context for synchronous functions */
syncStack: Job[];
/** next functions to run */
queue: Job[];
/** this is called if a thread scheduled in async `queue` is started or some thread was finished */
onThread: () => void;
/** executed immediately if some code is started (e.g. some async handler) */
onFirstFrame: () => void;
/** in error state */
error: boolean;
/** currently propagating exception */
exception: any;
/** a current value to be passed into the top of `stack` (or an exception if `error:true`) */
value: any;
/** a callback called when some module's sources are changed */
onLoad: ((module: Module, hot: boolean) => void) | null;
/** a callback called after module's top level is executed */
onAfterLoad: ((module: Module) => void) | null;
/** current execution stack */
top: Frame | null;
/** queries if the engine should stop on this `brk` */
needsBreak: (brk: Brk, frame: Frame, param?: any) => boolean;
/** reference of a function which is expected to be called */
call: any;
/** module id which is expected to be required */
moduleId: string | null;
/** currently suspended but not exited frames (e.g. on `await` expressions) */
suspended: Set<Frame>;
/** stop on any exceptions */
brkOnAnyException: boolean;
/** stop on uncaught exceptions */
brkOnUncaughtException: boolean;
/**
* `top` of currently debugging thread,
* the value is saved here while some blackbox thread may run
*/
pausedTop: Frame | null;
/** some new generated source can be debugged */
onNewSource: (id: number, code: string) => void;
/** stopping on a breakpoint */
onStop: () => void;
/** unique number of this execution context */
threadId: number;
/* signals we need to stop on next breakpoint with the reason */
stopNext: string | null;
}
/** known closures */
export const closures = new WeakMap<AnyFunc, Closure>();
export const functions = new WeakMap<AnyFunc, FunctionDescr>();
export const thunks = new WeakMap<any, () => void | null>();
export const binds = new WeakMap<
AnyFunc,
{ self: any; args: any[]; fun: AnyFunc }
>();
const CLOSURE_PARENT = 0;
const CLOSURE_VARS = 1;
const CLOSURE_META = 2;
const CLOSURE_FUNC = 3;
export interface Closure {
[CLOSURE_PARENT]: Frame | null;
[CLOSURE_VARS]: any[] | null;
[CLOSURE_META]: FunctionDescr;
[CLOSURE_FUNC]: () => any;
}
export { CLOSURE_PARENT, CLOSURE_VARS, CLOSURE_META, CLOSURE_FUNC };
/** a part of context stores information about currently executing function */
export interface Job {
top: Frame | null;
debug: boolean;
value: any;
// stopOnEntry?: boolean;
}
export const undef = { _undef: true };
/** global storage for the whole state of the running program */
export const context: State = {
enabled: false,
terminated: false,
running: false,
error: false,
launched: false,
brk: null,
top: null,
modules: {},
modulesById: {},
syncStack: [],
queue: [],
call: null,
needsBreak: nop,
value: void 0,
suspended: new Set(),
moduleId: null,
brkOnAnyException: false,
brkOnUncaughtException: false,
onNewSource: nop,
onThread: nop,
onFirstFrame: nop,
onStop: nop,
pausedTop: null,
threadId: 0,
exception: undef,
stopNext: null,
onLoad: null,
onAfterLoad: null
};
export function nop() {
return false;
}
declare global {
interface Function {
__effectful__nativeCall(this: any, ...args: any[]): any;
__effectful__nativeApply(this: any, self: any, args: any[]): any;
}
}
/** original global objects monkey-patched by this runtime */
export const native = {
// tslint:disable-next-line:no-console
console: { log: console.log, error: console.error, warn: console.warn },
Proxy,
Promise,
// tslint:disable-next-line:object-literal-shorthand
eval: eval,
Function,
FunctionMethods: {
call: Function.prototype.call,
apply: Function.prototype.apply,
bind: Function.prototype.bind
},
PromiseMethods: {
then: Promise.prototype.then,
catch: Promise.prototype.catch,
finally: Promise.prototype.finally
},
Object: {
defineProperty: Object.defineProperty,
assign: Object.assign,
setPrototypeOf: Object.setPrototypeOf,
freeze: Object.freeze,
isFrozen: Object.isFrozen,
seal: Object.seal,
isSealed: Object.isSealed,
preventExtensions: Object.preventExtensions,
isExtensible: Object.isExtensible,
defineProperties: Object.defineProperties,
entries: Object.entries,
keys: Object.keys,
values: Object.values,
getOwnPropertyNames: Object.getOwnPropertyNames,
getOwnPropertySymbols: Object.getOwnPropertySymbols,
getOwnPropertyDescriptors: Object.getOwnPropertyDescriptors,
getOwnPropertyDescriptor: Object.getOwnPropertyDescriptor,
getPrototypeOf: Object.getPrototypeOf,
create: Object.create
},
Array: {
shift: Array.prototype.shift,
unshift: Array.prototype.unshift,
push: Array.prototype.push,
pop: Array.prototype.pop,
splice: Array.prototype.splice,
sort: Array.prototype.sort,
reverse: Array.prototype.reverse,
slice: Array.prototype.slice,
from: Array.from,
filter: Array.prototype.filter,
map: Array.prototype.map
},
Map,
Set,
Reflect: {
construct: Reflect.construct,
apply: Reflect.apply,
get: Reflect.get,
set: Reflect.set,
has: Reflect.has,
defineProperty: Reflect.defineProperty,
deleteProperty: Reflect.deleteProperty,
getOwnPropertyDescriptor: Reflect.getOwnPropertyDescriptor,
ownKeys: Reflect.ownKeys,
isExtensible: Reflect.isExtensible,
preventExtensions: Reflect.preventExtensions,
setPrototypeOf: Reflect.setPrototypeOf,
getPrototypeOf: Reflect.getPrototypeOf
},
WeakMap: {
set: WeakMap.prototype.set,
delete: WeakMap.prototype.delete
},
WeakSet: {
add: WeakSet.prototype.add,
delete: WeakSet.prototype.delete
},
setInterval,
setTimeout,
clearTimeout,
clearInterval,
setImmediate: typeof setImmediate !== "undefined" && setImmediate,
clearImmediate: typeof clearImmediate !== "undefined" && clearImmediate
};
export const token = { _effectToken: true };
export const sideEffectToken = { _sideEffectToken: true };
interface IdsStore {
free(descriptor: number): void;
allocate(): number;
}
/** generates number from 0 till `1 << bits`, reuses numbers from `release` call */
export function idsStore(bits: number = 16): IdsStore {
// TODO: ensure optimization with typed arrays and SMI
const max = 1 << bits;
// stores elements of a linked list of free ids
const store: number[] = [];
let head = -1;
return {
free(id: number) {
store[id] = head;
head = id;
},
allocate(): number {
if (head === -1) {
const id = store.length;
if (id > max) throw new Error("id's generator overflow");
store.push(-1);
return id;
}
const id = head;
head = store[id];
store[id] = -1;
return id;
}
};
}
/** catch/finally handler state ids mapping */
export type StateMap = ((f: Frame) => void) | undefined;
/** handler function */
export type Handler = (f: Frame, pat: any) => any;
/** breakpoint positions */
export type States = [number, string, Scope][];
export const THREAD_BITS = 10;
export const THREAD_MASK = ~(-1 << THREAD_BITS);
export const MAX_ID = 1 << (32 - THREAD_BITS);
export function toGlobal(local: number) {
if (local > MAX_ID) throw new Error("id value overflow");
return (local << THREAD_BITS) | context.threadId;
}
export function toLocal(local: number) {
return local >> THREAD_BITS;
}
export function toThread(local: number) {
return local & THREAD_MASK;
}
export const isWindows =
typeof process !== "undefined" && process.platform === "win32";
export const normalizeDrive = isWindows
? function normalizeDrive(path: string) {
return path && path.length > 2 && path[1] === ":"
? path.charAt(0).toUpperCase() + path.slice(1)
: path;
}
: function (path: string) {
return path;
};
export const normalizePath = isWindows
? function normalizePath(path: string) {
return normalizeDrive(path.replace(/\\/g, "/"));
}
: function normalizePath(path: string) {
return path;
};
export class ForInIterator implements Iterable<string>, Iterator<string> {
fields: string[];
pos: number;
obj: any;
constructor(obj: any, fields: string[]) {
this.fields = fields;
this.pos = 0;
this.obj = obj;
}
[Symbol.iterator]() {
return this;
}
next(): IteratorResult<string> {
for (;;) {
if (this.pos >= this.fields.length)
return { done: true, value: undefined };
const value = this.fields[this.pos++];
if (value in this.obj) return { done: false, value };
}
}
}
export function forInIterator(obj: object): Iterable<string> {
const fields: string[] = [];
for (let i in obj) fields.push(i);
return new ForInIterator(obj, fields);
}
export interface GeneratorFrame extends Frame {
sent: any;
iter: Iterable<any>;
}
export type Item = { value: any; done: boolean };
export interface AsyncGeneratorFrame extends Frame {
running: boolean;
queue: (() => void)[];
onReturn: (value: any) => void;
onError: (reason: any) => void;
promise: Promise<Item>;
sent: any;
iter: AsyncIterable<any>;
}
export enum Flag {
ASYNC_FUNCTION = 1 << 0,
GENERATOR_FUNCTION = 1 << 1,
ARROW_FUNCTION = 1 << 2,
HAS_THIS = 1 << 3,
HAS_ARGUMENTS = 1 << 4,
FILE_TOP_LEVEL = 1 << 5,
BLACKBOX = 1 << 7,
SLOPPY = 1 << 8,
HAS_FUNCTION_SENT = 1 << 9,
HAS_DICTIONARY_SCOPE = 1 << 10,
// report uncaught
EXCEPTION_BOUNDARY = 1 << 11
}
export function defaultErrHandler(f: Frame) {
f.state = f.goto = f.meta.errState;
}
export function defaultFinHandler(f: Frame) {
f.state = f.goto = f.meta.finState;
}
export const nativeFuncs = new WeakSet<any>();
export function patchNative(obj: any, name: string | symbol, value: any) {
nativeFuncs.add(value);
native.Object.defineProperty(obj, name, {
configurable: true,
writable: true,
value
});
}
let statusBufImpl: SharedArrayBuffer = <any>null;
try {
statusBufImpl = new SharedArrayBuffer(4);
} catch (e) {
// this may be disabled in some browsers due to Spectre
// tslint:disable-next-line
console.warn(
"DEBUGGER: no SharedArrayBuffer, so pausing running code won't work"
);
}
export const statusBuf = statusBufImpl;
let interruptTimeoutHandler: any = 0;
let afterInterruptCallback: null | (() => void) = null;
let eventQueuePaused = false;
export function pauseEventQueue() {
eventQueuePaused = true;
}
export function resumeEventQueue() {
eventQueuePaused = false;
signalThread();
}
const nativeSetTimeout = setTimeout;
const nativeClearTimeout = clearTimeout;
export function afterInterrupt(cb: () => void) {
nativeClearTimeout(interruptTimeoutHandler);
afterInterruptCallback = cb;
interruptTimeoutHandler = nativeSetTimeout(resumeAfterInterrupt, 0);
}
export function resumeAfterInterrupt() {
const callback = afterInterruptCallback;
if (callback) {
interruptTimeoutHandler = 0;
afterInterruptCallback = null;
callback();
}
}
export function cancelInterrupt() {
nativeClearTimeout(interruptTimeoutHandler);
afterInterruptCallback = null;
interruptTimeoutHandler = 0;
}
let threadScheduled = false;
export function liftSync(fun: (this: any, ...args: any[]) => any): any {
return function (this: any) {
const savedDebug = context.enabled;
try {
context.enabled = false;
return (<any>fun).__effectful__nativeApply(this, <any>arguments);
} finally {
context.enabled = savedDebug;
}
};
}
const asap =
typeof process !== "undefined" && typeof process.nextTick === "function"
? process.nextTick
: typeof setImmediate === "function"
? setImmediate
: setTimeout;
/**
* scheduling some job (usually async calls) in managable event queue
*/
export function signalThread() {
if (threadScheduled) return;
threadScheduled = true;
asap(function thread() {
threadScheduled = false;
if (eventQueuePaused) return;
if (config.onBeforeExec) liftSync(config.onBeforeExec)();
context.onThread();
});
}
if (config.patchRT) {
Object.defineProperty(Function.prototype, "__effectful__nativeCall", {
configurable: true,
writable: true,
value: native.FunctionMethods.call
});
Object.defineProperty(Function.prototype, "__effectful__nativeApply", {
configurable: true,
writable: true,
value: native.FunctionMethods.apply
});
Object.defineProperty(Function.prototype, "__effectful__nativeBind", {
configurable: true,
writable: true,
value: native.FunctionMethods.bind
});
}
/** # for debugger's debug */
export function metaDescr(meta: FunctionDescr): string {
if (!meta) return "<NO META>";
return `${meta.origName}/${meta.name}@${meta.module.name}:${meta.line}`;
}
function frameLocaction(frame: Frame, state: number): string {
const brk = frame.meta.states[state];
if (brk) return `${state}@${brk.line}:${brk.column}`;
return `${state}`;
}
function frameInfoDescr(frame: Frame) {
if (!frame) return "<NO FRAME>";
return `${frame.restoreEnabled !== undef ? "! " : " "}${metaDescr(
frame.meta
)},S:${frameLocaction(frame, frame.state)},G:${frameLocaction(
frame,
frame.goto
)}`;
}
export function stackDescr(top = context.top || context.pausedTop): string[] {
const res = [];
for (let i = top; i; i = i.next) {
res.push(frameInfoDescr(i));
}
for (let i = 0, len = res.length; i < len; ++i)
res[i] = `F${len - i}:${res[i]}`;
return res;
}
export function trace(...args: [any, ...any[]]) {
native.console.log.apply(native.console, args);
}
if (config.verbose) Error.stackTraceLimit = Infinity;
export function mergeVersions(from: any, to: any) {
if (typeof from !== "object" || typeof to !== "object") return;
for (const i of native.Object.keys(to)) {
const fromProp = from[i];
const toProp = to[i];
if (typeof fromProp !== "function" || typeof toProp !== "function")
continue;
const fromClos = closures.get(fromProp);
const toClos = closures.get(toProp);
if (!fromClos || !toClos) return;
const fromMeta = fromClos[CLOSURE_META];
const toMeta = toClos[CLOSURE_META];
if (fromMeta.onReload) {
fromMeta.onReload(fromClos, toClos);
} else native.Object.assign(fromMeta, toMeta);
native.Object.assign(fromClos, toClos);
closures.set(fromProp, toClos);
}
}
export function mergeModule(mod: Module, prevMod: Module) {
if (!prevMod) return;
const cjs = mod.cjs;
const prevCjs = prevMod.cjs;
if (!cjs || !prevCjs) return;
if (prevMod.onReload) {
mod.onReload = prevMod.onReload;
prevMod.onReload(mod);
} else {
mergeVersions(prevCjs.exports, cjs.exports);
}
}
export const isNode =
typeof process !== "undefined" &&
process.release &&
process.release.name === "node";
export const isBrowser = typeof window !== "undefined" && !isNode;
if ((<any>module).hot) (<any>module).hot.addStatusHandler(resumeEventQueue);
export function staticToMethod(stat: (...args: unknown[]) => unknown) {
return function (this: unknown) {
const args = native.Array.from(arguments);
native.Array.unshift.call(args, this);
return stat.apply(undefined, args);
};
} | the_stack |
function isEndOfTag(char: string){
return char === '>';
}
function isStartOfTag(char: string){
return char === '<';
}
function isWhitespace(char: string){
return /^\s+$/.test(char);
}
/**
* Determines if the given token is a tag.
*
* @param {string} token The token in question.
*
* @return {boolean|string} False if the token is not a tag, or the tag name otherwise.
*/
function isTag(token: string){
var match = token.match(/^\s*<([^!>][^>]*)>\s*$/);
return !!match && match[1].trim().split(' ')[0];
}
function isntTag(token: string){
return !isTag(token);
}
function isStartofHTMLComment(word: string){
return /^<!--/.test(word);
}
function isEndOfHTMLComment(word: string){
return /-->$/.test(word);
}
/**
* Regular expression to check atomic tags.
* @see function diff.
*/
var atomicTagsRegExp: RegExp;
// Added head and style (for style tags inside the body)
var defaultAtomicTagsRegExp = new RegExp('^<(iframe|object|math|svg|script|video|head|style)');
/**
* Checks if the current word is the beginning of an atomic tag. An atomic tag is one whose
* child nodes should not be compared - the entire tag should be treated as one token. This
* is useful for tags where it does not make sense to insert <ins> and <del> tags.
*
* @param {string} word The characters of the current token read so far.
*
* @return {string|null} The name of the atomic tag if the word will be an atomic tag,
* null otherwise
*/
function isStartOfAtomicTag(word: string){
var result = atomicTagsRegExp.exec(word);
return result && result[1];
}
/**
* Checks if the current word is the end of an atomic tag (i.e. it has all the characters,
* except for the end bracket of the closing tag, such as '<iframe></iframe').
*
* @param {string} word The characters of the current token read so far.
* @param {string} tag The ending tag to look for.
*
* @return {boolean} True if the word is now a complete token (including the end tag),
* false otherwise.
*/
function isEndOfAtomicTag(word: string, tag: string){
return word.substring(word.length - tag.length - 2) === ('</' + tag);
}
/**
* Checks if a tag is a void tag.
*
* @param {string} token The token to check.
*
* @return {boolean} True if the token is a void tag, false otherwise.
*/
function isVoidTag(token: string){
return /^\s*<[^>]+\/>\s*$/.test(token);
}
/**
* Checks if a token can be wrapped inside a tag.
*
* @param {string} token The token to check.
*
* @return {boolean} True if the token can be wrapped inside a tag, false otherwise.
*/
function isWrappable(token: string){
var is_img = /^<img[\s>]/.test(token);
return is_img|| isntTag(token) || isStartOfAtomicTag(token) || isVoidTag(token);
}
/**
* Creates a token that holds a string and key representation. The key is used for diffing
* comparisons and the string is used to recompose the document after the diff is complete.
*
* @param {string} currentWord The section of the document to create a token for.
*
* @return {Object} A token object with a string and key property.
*/
function createToken(currentWord: string){
return {
string: currentWord,
key: getKeyForToken(currentWord)
};
}
/**
* A Match stores the information of a matching block. A matching block is a list of
* consecutive tokens that appear in both the before and after lists of tokens.
*
* @param {number} startInBefore The index of the first token in the list of before tokens.
* @param {number} startInAfter The index of the first token in the list of after tokens.
* @param {number} length The number of consecutive matching tokens in this block.
* @param {Segment} segment The segment where the match was found.
*/
function Match(this: any, startInBefore: number, startInAfter: number, length: number, segment: any){
this.segment = segment;
this.length = length;
this.startInBefore = startInBefore + segment.beforeIndex;
this.startInAfter = startInAfter + segment.afterIndex;
this.endInBefore = this.startInBefore + this.length - 1;
this.endInAfter = this.startInAfter + this.length - 1;
this.segmentStartInBefore = startInBefore;
this.segmentStartInAfter = startInAfter;
this.segmentEndInBefore = (this.segmentStartInBefore + this.length) - 1;
this.segmentEndInAfter = (this.segmentStartInAfter + this.length) - 1;
}
/**
* Tokenizes a string of HTML.
*
* @param {string} html The string to tokenize.
*
* @return {Array.<string>} The list of tokens.
*/
function htmlToTokens(html: string){
var mode = 'char';
var currentWord = '';
var currentAtomicTag = '';
var words: Array<any> = [];
for (var i = 0; i < html.length; i++){
var char = html[i];
switch (mode){
case 'tag':
var atomicTag = isStartOfAtomicTag(currentWord);
if (atomicTag){
mode = 'atomic_tag';
currentAtomicTag = atomicTag;
currentWord += char;
} else if (isStartofHTMLComment(currentWord)){
mode = 'html_comment';
currentWord += char;
} else if (isEndOfTag(char)){
currentWord += '>';
words.push(createToken(currentWord));
currentWord = '';
if (isWhitespace(char)){
mode = 'whitespace';
} else {
mode = 'char';
}
} else {
currentWord += char;
}
break;
case 'atomic_tag':
if (isEndOfTag(char) && isEndOfAtomicTag(currentWord, currentAtomicTag)){
currentWord += '>';
words.push(createToken(currentWord));
currentWord = '';
currentAtomicTag = '';
mode = 'char';
} else {
currentWord += char;
}
break;
case 'html_comment':
currentWord += char;
if (isEndOfHTMLComment(currentWord)){
currentWord = '';
mode = 'char';
}
break;
case 'char':
if (isStartOfTag(char)){
if (currentWord){
words.push(createToken(currentWord));
}
currentWord = '<';
mode = 'tag';
} else if (/\s/.test(char)){
if (currentWord){
words.push(createToken(currentWord));
}
currentWord = char;
mode = 'whitespace';
} else if (/[\w\d#@]/.test(char)){
currentWord += char;
} else if (/&/.test(char)){
if (currentWord){
words.push(createToken(currentWord));
}
currentWord = char;
} else {
currentWord += char;
words.push(createToken(currentWord));
currentWord = '';
}
break;
case 'whitespace':
if (isStartOfTag(char)){
if (currentWord){
words.push(createToken(currentWord));
}
currentWord = '<';
mode = 'tag';
} else if (isWhitespace(char)){
currentWord += char;
} else {
if (currentWord){
words.push(createToken(currentWord));
}
currentWord = char;
mode = 'char';
}
break;
default:
throw new Error('Unknown mode ' + mode);
}
}
if (currentWord){
words.push(createToken(currentWord));
}
return words;
}
/**
* Creates a key that should be used to match tokens. This is useful, for example, if we want
* to consider two open tag tokens as equal, even if they don't have the same attributes. We
* use a key instead of overwriting the token because we may want to render the original string
* without losing the attributes.
*
* @param {string} token The token to create the key for.
*
* @return {string} The identifying key that should be used to match before and after tokens.
*/
function getKeyForToken(token: string){
// If the token is an image element, grab it's src attribute to include in the key.
var img = /^<img.*src=['"]([^"']*)['"].*>$/.exec(token);
if (img) {
return '<img src="' + img[1] + '">';
}
// If the token is an object element, grab it's data attribute to include in the key.
var object = /^<object.*data=['"]([^"']*)['"]/.exec(token);
if (object) {
return '<object src="' + object[1] + '"></object>';
}
// If it's a video, math or svg element, the entire token should be compared except the
// data-uuid.
if(/^<(svg|math|video)[\s>]/.test(token)) {
var uuid = token.indexOf('data-uuid="');
if (uuid !== -1) {
var start = token.slice(0, uuid);
var end = token.slice(uuid + 44);
return start + end;
} else {
return token;
}
}
// If the token is an iframe element, grab it's src attribute to include in it's key.
var iframe = /^<iframe.*src=['"]([^"']*)['"].*>/.exec(token);
if (iframe) {
return '<iframe src="' + iframe[1] + '"></iframe>';
}
// If the token is any other element, just grab the tag name.
var tagName = /<([^\s>]+)[\s>]/.exec(token);
if (tagName){
return '<' + (tagName[1].toLowerCase()) + '>';
}
// Otherwise, the token is text, collapse the whitespace.
if (token) {
return token.replace(/(\s+| | )/g, ' ');
}
return token;
}
/**
* Creates a map from token key to an array of indices of locations of the matching token in
* the list of all tokens.
*
* @param {Array.<string>} tokens The list of tokens to be mapped.
*
* @return {Object} A mapping that can be used to search for tokens.
*/
function createMap(tokens: any[]){
return tokens.reduce(function(map: any, token: any, index: number){
if (map[token.key]){
map[token.key].push(index);
} else {
map[token.key] = [index];
}
return map;
}, Object.create(null));
}
/**
* Compares two match objects to determine if the second match object comes before or after the
* first match object. Returns -1 if the m2 should come before m1. Returns 1 if m1 should come
* before m2. If the two matches criss-cross each other, a null is returned.
*
* @param {Match} m1 The first match object to compare.
* @param {Match} m2 The second match object to compare.
*
* @return {number} Returns -1 if the m2 should come before m1. Returns 1 if m1 should come
* before m2. If the two matches criss-cross each other, 0 is returned.
*/
function compareMatches(m1: any, m2: any){
if (m2.endInBefore < m1.startInBefore && m2.endInAfter < m1.startInAfter){
return -1;
} else if (m2.startInBefore > m1.endInBefore && m2.startInAfter > m1.endInAfter){
return 1;
} else {
return 0;
}
}
/**
* A constructor for a binary search tree used to keep match objects in the proper order as
* they're found.
*
* @constructor
*/
function MatchBinarySearchTree(this: any){
this._root = null;
}
MatchBinarySearchTree.prototype = {
/**
* Adds matches to the binary search tree.
*
* @param {Match} value The match to add to the binary search tree.
*/
add: function (value: any){
// Create the node to hold the match value.
var node = {
value: value,
left: null,
right: null
};
var current = this._root;
if(current){
// eslint-disable-next-line no-constant-condition
while (true){
// Determine if the match value should go to the left or right of the current
// node.
var position = compareMatches(current.value, value);
if (position === -1){
// The position of the match is to the left of this node.
if (current.left){
current = current.left;
} else {
current.left = node;
break;
}
} else if (position === 1){
// The position of the match is to the right of this node.
if (current.right){
current = current.right;
} else {
current.right = node;
break;
}
} else {
// If 0 was returned from compareMatches, that means the node cannot
// be inserted because it overlaps an existing node.
break;
}
}
} else {
// If no nodes exist in the tree, make this the root node.
this._root = node;
}
},
/**
* Converts the binary search tree into an array using an in-order traversal.
*
* @return {Array.<Match>} An array containing the matches in the binary search tree.
*/
toArray: function(){
function inOrder(node: any, nodes: any){
if (node){
inOrder(node.left, nodes);
nodes.push(node.value);
inOrder(node.right, nodes);
}
return nodes;
}
return inOrder(this._root, []);
}
};
/**
* Finds and returns the best match between the before and after arrays contained in the segment
* provided.
*
* @param {Segment} segment The segment in which to look for a match.
*
* @return {Match} The best match.
*/
function findBestMatch(segment: any){
var beforeTokens = segment.beforeTokens;
var afterMap = segment.afterMap;
var lastSpace: any = null;
var bestMatch: any = null;
// Iterate through the entirety of the beforeTokens to find the best match.
for (var beforeIndex = 0; beforeIndex < beforeTokens.length; beforeIndex++){
var lookBehind = false;
// If the current best match is longer than the remaining tokens, we can bail because we
// won't find a better match.
var remainingTokens = beforeTokens.length - beforeIndex;
if (bestMatch && remainingTokens < bestMatch.length){
break;
}
// If the current token is whitespace, make a note of it and move on. Trying to start a
// set of matches with whitespace is not efficient because it's too prevelant in most
// documents. Instead, if the next token yields a match, we'll see if the whitespace can
// be included in that match.
var beforeToken = beforeTokens[beforeIndex];
if (beforeToken.key === ' '){
lastSpace = beforeIndex;
continue;
}
// Check to see if we just skipped a space, if so, we'll ask getFullMatch to look behind
// by one token to see if it can include the whitespace.
if (lastSpace === beforeIndex - 1){
lookBehind = true;
}
// If the current token is not found in the afterTokens, it won't match and we can move
// on.
var afterTokenLocations = afterMap[beforeToken.key];
if(!afterTokenLocations){
continue;
}
// For each instance of the current token in afterTokens, let's see how big of a match
// we can build.
afterTokenLocations.forEach(function(afterIndex: number){
// getFullMatch will see how far the current token match will go in both
// beforeTokens and afterTokens.
var bestMatchLength = bestMatch ? bestMatch.length : 0;
var match = getFullMatch(
segment, beforeIndex, afterIndex, bestMatchLength, lookBehind);
// If we got a new best match, we'll save it aside.
if (match && match.length > bestMatchLength){
bestMatch = match;
}
});
}
return bestMatch;
}
/**
* Takes the start of a match, and expands it in the beforeTokens and afterTokens of the
* current segment as far as it can go.
*
* @param {Segment} segment The segment object to search within when expanding the match.
* @param {number} beforeStart The offset within beforeTokens to start looking.
* @param {number} afterStart The offset within afterTokens to start looking.
* @param {number} minLength The minimum length match that must be found.
* @param {boolean} lookBehind If true, attempt to match a whitespace token just before the
* beforeStart and afterStart tokens.
*
* @return {Match} The full match.
*/
function getFullMatch(segment: any, beforeStart: number, afterStart: number, minLength: number, lookBehind: boolean){
var beforeTokens = segment.beforeTokens;
var afterTokens = segment.afterTokens;
// If we already have a match that goes to the end of the document, no need to keep looking.
var minBeforeIndex = beforeStart + minLength;
var minAfterIndex = afterStart + minLength;
if(minBeforeIndex >= beforeTokens.length || minAfterIndex >= afterTokens.length){
return;
}
// If a minLength was provided, we can do a quick check to see if the tokens after that
// length match. If not, we won't be beating the previous best match, and we can bail out
// early.
if (minLength){
var nextBeforeWord = beforeTokens[minBeforeIndex].key;
var nextAfterWord = afterTokens[minAfterIndex].key;
if (nextBeforeWord !== nextAfterWord){
return;
}
}
// Extend the current match as far foward as it can go, without overflowing beforeTokens or
// afterTokens.
var searching = true;
var currentLength = 1;
var beforeIndex = beforeStart + currentLength;
var afterIndex = afterStart + currentLength;
while (searching && beforeIndex < beforeTokens.length && afterIndex < afterTokens.length){
var beforeWord = beforeTokens[beforeIndex].key;
var afterWord = afterTokens[afterIndex].key;
if (beforeWord === afterWord){
currentLength++;
beforeIndex = beforeStart + currentLength;
afterIndex = afterStart + currentLength;
} else {
searching = false;
}
}
// If we've been asked to look behind, it's because both beforeTokens and afterTokens may
// have a whitespace token just behind the current match that was previously ignored. If so,
// we'll expand the current match to include it.
if (lookBehind && beforeStart > 0 && afterStart > 0){
var prevBeforeKey = beforeTokens[beforeStart - 1].key;
var prevAfterKey = afterTokens[afterStart - 1].key;
if (prevBeforeKey === ' ' && prevAfterKey === ' '){
beforeStart--;
afterStart--;
currentLength++;
}
}
return new Match(beforeStart, afterStart, currentLength, segment);
}
/**
* Creates segment objects from the original document that can be used to restrict the area that
* findBestMatch and it's helper functions search to increase performance.
*
* @param {Array.<Token>} beforeTokens Tokens from the before document.
* @param {Array.<Token>} afterTokens Tokens from the after document.
* @param {number} beforeIndex The index within the before document where this segment begins.
* @param {number} afterIndex The index within the after document where this segment behinds.
*
* @return {Segment} The segment object.
*/
function createSegment(beforeTokens: any[], afterTokens: any[], beforeIndex: number, afterIndex: number){
return {
beforeTokens: beforeTokens,
afterTokens: afterTokens,
beforeMap: createMap(beforeTokens),
afterMap: createMap(afterTokens),
beforeIndex: beforeIndex,
afterIndex: afterIndex
};
}
/**
* Finds all the matching blocks within the given segment in the before and after lists of
* tokens.
*
* @param {Segment} The segment that should be searched for matching blocks.
*
* @return {Array.<Match>} The list of matching blocks in this range.
*/
function findMatchingBlocks(segment: any){
// Create a binary search tree to hold the matches we find in order.
var matches = new MatchBinarySearchTree();
var match;
var segments = [segment];
// Each time the best match is found in a segment, zero, one or two new segments may be
// created from the parts of the original segment not included in the match. We will
// continue to iterate until all segments have been processed.
while(segments.length){
segment = segments.pop();
match = findBestMatch(segment);
if (match && match.length){
// If there's an unmatched area at the start of the segment, create a new segment
// from that area and throw it into the segments array to get processed.
if (match.segmentStartInBefore > 0 && match.segmentStartInAfter > 0){
var leftBeforeTokens = segment.beforeTokens.slice(
0, match.segmentStartInBefore);
var leftAfterTokens = segment.afterTokens.slice(0, match.segmentStartInAfter);
segments.push(createSegment(leftBeforeTokens, leftAfterTokens,
segment.beforeIndex, segment.afterIndex));
}
// If there's an unmatched area at the end of the segment, create a new segment from that
// area and throw it into the segments array to get processed.
var rightBeforeTokens = segment.beforeTokens.slice(match.segmentEndInBefore + 1);
var rightAfterTokens = segment.afterTokens.slice(match.segmentEndInAfter + 1);
var rightBeforeIndex = segment.beforeIndex + match.segmentEndInBefore + 1;
var rightAfterIndex = segment.afterIndex + match.segmentEndInAfter + 1;
if (rightBeforeTokens.length && rightAfterTokens.length){
segments.push(createSegment(rightBeforeTokens, rightAfterTokens,
rightBeforeIndex, rightAfterIndex));
}
matches.add(match);
}
}
return matches.toArray();
}
/**
* Gets a list of operations required to transform the before list of tokens into the
* after list of tokens. An operation describes whether a particular list of consecutive
* tokens are equal, replaced, inserted, or deleted.
*
* @param {Array.<string>} beforeTokens The before list of tokens.
* @param {Array.<string>} afterTokens The after list of tokens.
*
* @return {Array.<Object>} The list of operations to transform the before list of
* tokens into the after list of tokens, where each operation has the following
* keys:
* - {string} action One of {'replace', 'insert', 'delete', 'equal'}.
* - {number} startInBefore The beginning of the range in the list of before tokens.
* - {number} endInBefore The end of the range in the list of before tokens.
* - {number} startInAfter The beginning of the range in the list of after tokens.
* - {number} endInAfter The end of the range in the list of after tokens.
*/
function calculateOperations(beforeTokens: string[], afterTokens: string[]): Array<any> {
if (!beforeTokens) throw new Error('Missing beforeTokens');
if (!afterTokens) throw new Error('Missing afterTokens');
var positionInBefore = 0;
var positionInAfter = 0;
var operations: Array<any> = [];
var segment = createSegment(beforeTokens, afterTokens, 0, 0);
var matches = findMatchingBlocks(segment);
matches.push(new Match(beforeTokens.length, afterTokens.length, 0, segment));
for (var index = 0; index < matches.length; index++){
var match = matches[index];
var actionUpToMatchPositions = 'none';
if (positionInBefore === match.startInBefore){
if (positionInAfter !== match.startInAfter){
actionUpToMatchPositions = 'insert';
}
} else {
actionUpToMatchPositions = 'delete';
if (positionInAfter !== match.startInAfter){
actionUpToMatchPositions = 'replace';
}
}
if (actionUpToMatchPositions !== 'none'){
operations.push({
action: actionUpToMatchPositions,
startInBefore: positionInBefore,
endInBefore: (actionUpToMatchPositions !== 'insert' ?
match.startInBefore - 1 : null),
startInAfter: positionInAfter,
endInAfter: (actionUpToMatchPositions !== 'delete' ?
match.startInAfter - 1 : null)
});
}
if (match.length !== 0){
operations.push({
action: 'equal',
startInBefore: match.startInBefore,
endInBefore: match.endInBefore,
startInAfter: match.startInAfter,
endInAfter: match.endInAfter
});
}
positionInBefore = match.endInBefore + 1;
positionInAfter = match.endInAfter + 1;
}
var postProcessed: Array<any> = [];
var lastOp: any = {action: 'none'};
function isSingleWhitespace(op: any){
if (op.action !== 'equal'){
return false;
}
if (op.endInBefore - op.startInBefore !== 0){
return false;
}
// Fails typecheck, maybe a real bug? --Jim
// @ts-ignore
return /^\s$/.test(beforeTokens.slice(op.startInBefore, op.endInBefore + 1));
}
for (var i = 0; i < operations.length; i++){
var op = operations[i];
if ((isSingleWhitespace(op) && lastOp.action === 'replace') ||
(op.action === 'replace' && lastOp.action === 'replace')){
lastOp.endInBefore = op.endInBefore;
lastOp.endInAfter = op.endInAfter;
} else {
postProcessed.push(op);
lastOp = op;
}
}
return postProcessed;
}
/**
* A TokenWrapper provides a utility for grouping segments of tokens based on whether they're
* wrappable or not. A tag is considered wrappable if it is closed within the given set of
* tokens. For example, given the following tokens:
*
* ['</b>', 'this', ' ', 'is', ' ', 'a', ' ', '<b>', 'test', '</b>', '!']
*
* The first '</b>' is not considered wrappable since the tag is not fully contained within the
* array of tokens. The '<b>', 'test', and '</b>' would be a part of the same wrappable segment
* since the entire bold tag is within the set of tokens.
*
* TokenWrapper has a method 'combine' which allows walking over the segments to wrap them in
* tags.
*/
function TokenWrapper(this: any, tokens: any[]){
this.tokens = tokens;
this.notes = tokens.reduce(function(data, token, index){
data.notes.push({
isWrappable: isWrappable(token),
insertedTag: false
});
var tag = !isVoidTag(token) && isTag(token);
var lastEntry = data.tagStack[data.tagStack.length - 1];
if (tag){
if (lastEntry && '/' + lastEntry.tag === tag){
data.notes[lastEntry.position].insertedTag = true;
data.tagStack.pop();
} else {
data.tagStack.push({
tag: tag,
position: index
});
}
}
return data;
}, {notes: [], tagStack: []}).notes;
}
/**
* Wraps the contained tokens in tags based on output given by a map function. Each segment of
* tokens will be visited. A segment is a continuous run of either all wrappable
* tokens or unwrappable tokens. The given map function will be called with each segment of
* tokens and the resulting strings will be combined to form the wrapped HTML.
*
* @param {function(boolean, Array.<string>)} mapFn A function called with an array of tokens
* and whether those tokens are wrappable or not. The result should be a string.
*/
TokenWrapper.prototype.combine = function(mapFn: any, tagFn: any){
var notes = this.notes;
var tokens = this.tokens.slice();
var segments = tokens.reduce(function(data: any, token: any, index: number){
if (notes[index].insertedTag){
tokens[index] = tagFn(tokens[index]);
}
if (data.status === null){
data.status = notes[index].isWrappable;
}
var status = notes[index].isWrappable;
if (status !== data.status){
data.list.push({
isWrappable: data.status,
tokens: tokens.slice(data.lastIndex, index)
});
data.lastIndex = index;
data.status = status;
}
if (index === tokens.length - 1){
data.list.push({
isWrappable: data.status,
tokens: tokens.slice(data.lastIndex, index + 1)
});
}
return data;
}, {list: [], status: null, lastIndex: 0}).list;
return segments.map(mapFn).join('');
};
/**
* Wraps and concatenates a list of tokens with a tag. Does not wrap tag tokens,
* unless they are wrappable (i.e. void and atomic tags).
*
* @param {sting} tag The tag name of the wrapper tags.
* @param {Array.<string>} content The list of tokens to wrap.
* @param {string} dataPrefix (Optional) The prefix to use in data attributes.
* @param {string} className (Optional) The class name to include in the wrapper tag.
*/
function wrap(tag: string, content: string[], opIndex: number, dataPrefix?: string, className?: string){
var wrapper = new TokenWrapper(content);
dataPrefix = dataPrefix ? dataPrefix + '-' : '';
var attrs = ' data-' + dataPrefix + 'operation-index="' + opIndex + '"';
if (className){
attrs += ' class="' + className + '"';
}
return wrapper.combine(function(segment: any){
if (segment.isWrappable){
var val = segment.tokens.join('');
if (val.trim()){
return '<' + tag + attrs + '>' + val + '</' + tag + '>';
}
} else {
return segment.tokens.join('');
}
return '';
}, function(openingTag: any){
var dataAttrs = ' data-diff-node="' + tag + '"';
dataAttrs += ' data-' + dataPrefix + 'operation-index="' + opIndex + '"';
return openingTag.replace(/>\s*$/, dataAttrs + '$&');
});
}
/**
* OPS.equal/insert/delete/replace are functions that render an operation into
* HTML content.
*
* @param {Object} op The operation that applies to a prticular list of tokens. Has the
* following keys:
* - {string} action One of ['replace', 'insert', 'delete', 'equal'].
* - {number} startInBefore The beginning of the range in the list of before tokens.
* - {number} endInBefore The end of the range in the list of before tokens.
* - {number} startInAfter The beginning of the range in the list of after tokens.
* - {number} endInAfter The end of the range in the list of after tokens.
* @param {Array.<string>} beforeTokens The before list of tokens.
* @param {Array.<string>} afterTokens The after list of tokens.
* @param {number} opIndex The index into the list of operations that identifies the change to
* be rendered. This is used to mark wrapped HTML as part of the same operation.
* @param {string} dataPrefix (Optional) The prefix to use in data attributes.
* @param {string} className (Optional) The class name to include in the wrapper tag.
*
* @return {string} The rendering of that operation.
*/
var OPS: any = {
'equal': function(op: any, beforeTokens: any, afterTokens: any, opIndex: number, dataPrefix?: string, className?: string){
var tokens = afterTokens.slice(op.startInAfter, op.endInAfter + 1);
return tokens.reduce(function(prev: any, curr: any){
return prev + curr.string;
}, '');
},
'insert': function(op: any, beforeTokens: any, afterTokens: any, opIndex: number, dataPrefix?: string, className?: string){
var tokens = afterTokens.slice(op.startInAfter, op.endInAfter + 1);
var val = tokens.map(function(token: any){
return token.string;
});
return wrap('ins', val, opIndex, dataPrefix, className);
},
'delete': function(op: any, beforeTokens: any, afterTokens: any, opIndex: number, dataPrefix?: string, className?: string){
var tokens = beforeTokens.slice(op.startInBefore, op.endInBefore + 1);
var val = tokens.map(function(token: any){
return token.string;
});
return wrap('del', val, opIndex, dataPrefix, className);
},
'replace': function(){
return OPS['delete'].apply(null, arguments) + OPS['insert'].apply(null, arguments);
}
};
/**
* Renders a list of operations into HTML content. The result is the combined version
* of the before and after tokens with the differences wrapped in tags.
*
* @param {Array.<string>} beforeTokens The before list of tokens.
* @param {Array.<string>} afterTokens The after list of tokens.
* @param {Array.<Object>} operations The list of operations to transform the before
* list of tokens into the after list of tokens, where each operation has the
* following keys:
* - {string} action One of {'replace', 'insert', 'delete', 'equal'}.
* - {number} startInBefore The beginning of the range in the list of before tokens.
* - {number} endInBefore The end of the range in the list of before tokens.
* - {number} startInAfter The beginning of the range in the list of after tokens.
* - {number} endInAfter The end of the range in the list of after tokens.
* @param {string} dataPrefix (Optional) The prefix to use in data attributes.
* @param {string} className (Optional) The class name to include in the wrapper tag.
*
* @return {string} The rendering of the list of operations.
*/
function renderOperations(beforeTokens: string[], afterTokens: string[], operations: any[], dataPrefix?: string, className?: string) {
return operations.reduce(function(rendering, op, index){
return rendering + OPS[op.action](
op, beforeTokens, afterTokens, index, dataPrefix, className);
}, '');
}
/**
* Compares two pieces of HTML content and returns the combined content with differences
* wrapped in <ins> and <del> tags.
*
* @param {string} before The HTML content before the changes.
* @param {string} after The HTML content after the changes.
* @param {string} className (Optional) The class attribute to include in <ins> and <del> tags.
* @param {string} dataPrefix (Optional) The data prefix to use for data attributes. The
* operation index data attribute will be named `data-${dataPrefix-}operation-index`.
* @param {string} atomicTags (Optional) Comma separated list of atomic tag names. The
* list has to be in the form `tag1,tag2,...` e. g. `head,script,style`. If not used,
* the default list `iframe,object,math,svg,script,video,head,style` will be used.
*
* @return {string} The combined HTML content with differences wrapped in <ins> and <del> tags.
*/
export function diff(before: string, after: string, className?: string, dataPrefix?: string, atomicTags?: string): string {
if (before === after) return before;
// Enable user provided atomic tag list.
atomicTags ?
(atomicTagsRegExp = new RegExp('^<(' + atomicTags.replace(/\s*/g, '').replace(/,/g, '|') + ')'))
: (atomicTagsRegExp = defaultAtomicTagsRegExp);
var beforeTokens = htmlToTokens(before);
var afterTokens = htmlToTokens(after);
var ops = calculateOperations(beforeTokens, afterTokens);
return renderOperations(beforeTokens, afterTokens, ops, dataPrefix, className);
}
diff.htmlToTokens = htmlToTokens;
diff.findMatchingBlocks = findMatchingBlocks;
findMatchingBlocks.findBestMatch = findBestMatch;
findMatchingBlocks.createMap = createMap;
findMatchingBlocks.createToken = createToken;
findMatchingBlocks.createSegment = createSegment;
findMatchingBlocks.getKeyForToken = getKeyForToken;
diff.calculateOperations = calculateOperations;
diff.renderOperations = renderOperations; | the_stack |
import {
getDateFormatter,
getDateFormatterSource
} from '@messageformat/date-skeleton';
import {
getNumberFormatter,
getNumberFormatterSource
} from '@messageformat/number-skeleton';
import { parse, FunctionArg, Select, Token } from '@messageformat/parser';
import * as Runtime from '@messageformat/runtime';
import * as Formatters from '@messageformat/runtime/lib/formatters';
import { identifier, property } from 'safe-identifier';
import { biDiMarkText } from './bidi-mark-text';
import { MessageFormatOptions } from './messageformat';
import { PluralObject } from './plurals';
const RUNTIME_MODULE = '@messageformat/runtime';
const CARDINAL_MODULE = '@messageformat/runtime/lib/cardinals';
const PLURAL_MODULE = '@messageformat/runtime/lib/plurals';
const FORMATTER_MODULE = '@messageformat/runtime/lib/formatters';
type RuntimeType = 'formatter' | 'locale' | 'runtime';
interface RuntimeEntry {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(...args: any[]): unknown;
id?: string | null;
module?: string | null;
toString?: () => string;
type?: RuntimeType;
}
export interface RuntimeMap {
[key: string]: Required<RuntimeEntry>;
}
/**
* A hierarchical structure of ICU MessageFormat strings
*
* @public
* @remarks
* Used in {@link compileModule} arguments
*/
export interface StringStructure {
[key: string]: StringStructure | string;
}
export default class Compiler {
arguments: string[] = [];
options: Required<MessageFormatOptions>;
declare plural: PluralObject; // Always set in compile()
runtime: RuntimeMap = {};
constructor(options: Required<MessageFormatOptions>) {
this.options = options;
}
/**
* Recursively compile a string or a tree of strings to JavaScript function
* sources
*
* If `src` is an object with a key that is also present in `plurals`, the key
* in question will be used as the locale identifier for its value. To disable
* the compile-time checks for plural & selectordinal keys while maintaining
* multi-locale support, use falsy values in `plurals`.
*
* @param src - The source for which the JS code should be generated
* @param plural - The default locale
* @param plurals - A map of pluralization keys for all available locales
*/
compile(
src: string | StringStructure,
plural: PluralObject,
plurals?: { [key: string]: PluralObject }
) {
if (typeof src === 'object') {
const result: StringStructure = {};
for (const key of Object.keys(src)) {
const pl = (plurals && plurals[key]) || plural;
result[key] = this.compile(src[key], pl, plurals);
}
return result;
}
this.plural = plural;
const parserOptions = {
cardinal: plural.cardinals,
ordinal: plural.ordinals,
strict: this.options.strict
};
this.arguments = [];
const r = parse(src, parserOptions).map(token => this.token(token, null));
const hasArgs = this.arguments.length > 0;
const res = this.concatenate(r, true);
if (this.options.requireAllArguments && hasArgs) {
this.setRuntimeFn('reqArgs');
const reqArgs = JSON.stringify(this.arguments);
return `(d) => { reqArgs(${reqArgs}, d); return ${res}; }`;
}
return `(${hasArgs ? 'd' : ''}) => ${res}`;
}
cases(token: Select, pluralToken: Select | null) {
let needOther = true;
const r = token.cases.map(({ key, tokens }) => {
if (key === 'other') needOther = false;
const s = tokens.map(tok => this.token(tok, pluralToken));
return `${property(null, key.replace(/^=/, ''))}: ${this.concatenate(
s,
false
)}`;
});
if (needOther) {
const { type } = token;
const { cardinals, ordinals } = this.plural;
if (
type === 'select' ||
(type === 'plural' && cardinals.includes('other')) ||
(type === 'selectordinal' && ordinals.includes('other'))
)
throw new Error(`No 'other' form found in ${JSON.stringify(token)}`);
}
return `{ ${r.join(', ')} }`;
}
concatenate(tokens: string[], root: boolean) {
const asValues = this.options.returnType === 'values';
return asValues && (root || tokens.length > 1)
? '[' + tokens.join(', ') + ']'
: tokens.join(' + ') || '""';
}
token(token: Token, pluralToken: Select | null) {
if (token.type === 'content') return JSON.stringify(token.value);
const { id, lc } = this.plural;
let args: (number | string)[], fn: string;
if ('arg' in token) {
this.arguments.push(token.arg);
args = [property('d', token.arg)];
} else args = [];
switch (token.type) {
case 'argument':
return this.options.biDiSupport
? biDiMarkText(String(args[0]), lc)
: String(args[0]);
case 'select':
fn = 'select';
if (pluralToken && this.options.strict) pluralToken = null;
args.push(this.cases(token, pluralToken));
this.setRuntimeFn('select');
break;
case 'selectordinal':
fn = 'plural';
args.push(token.pluralOffset || 0, id, this.cases(token, token), 1);
this.setLocale(id, true);
this.setRuntimeFn('plural');
break;
case 'plural':
fn = 'plural';
args.push(token.pluralOffset || 0, id, this.cases(token, token));
this.setLocale(id, false);
this.setRuntimeFn('plural');
break;
case 'function':
if (!this.options.customFormatters[token.key]) {
if (token.key === 'date') {
fn = this.setDateFormatter(token, args, pluralToken);
break;
} else if (token.key === 'number') {
fn = this.setNumberFormatter(token, args, pluralToken);
break;
}
}
args.push(JSON.stringify(this.plural.locale));
if (token.param) {
if (pluralToken && this.options.strict) pluralToken = null;
const arg = this.getFormatterArg(token, pluralToken);
if (arg) args.push(arg);
}
fn = token.key;
this.setFormatter(fn);
break;
case 'octothorpe':
/* istanbul ignore if: never happens */
if (!pluralToken) return '"#"';
args = [
JSON.stringify(this.plural.locale),
property('d', pluralToken.arg),
pluralToken.pluralOffset || 0
];
if (this.options.strict) {
fn = 'strictNumber';
args.push(JSON.stringify(pluralToken.arg));
this.setRuntimeFn('strictNumber');
} else {
fn = 'number';
this.setRuntimeFn('number');
}
break;
}
/* istanbul ignore if: never happens */
if (!fn) throw new Error('Parser error for token ' + JSON.stringify(token));
return `${fn}(${args.join(', ')})`;
}
runtimeIncludes(key: string, type: RuntimeType) {
if (identifier(key) !== key)
throw new SyntaxError(`Reserved word used as ${type} identifier: ${key}`);
const prev = this.runtime[key];
if (!prev || prev.type === type) return prev;
throw new TypeError(
`Cannot override ${prev.type} runtime function as ${type}: ${key}`
);
}
setLocale(key: string, ord: boolean) {
const prev = this.runtimeIncludes(key, 'locale');
const { getCardinal, getPlural, isDefault } = this.plural;
let pf: RuntimeEntry, module, toString;
if (!ord && isDefault && getCardinal) {
if (prev) return;
pf = (n: string | number) => getCardinal(n);
module = CARDINAL_MODULE;
/* istanbul ignore next: never actually called */
toString = () => String(getCardinal);
} else {
// overwrite a previous cardinal-only locale function
if (prev && (!isDefault || prev.module === PLURAL_MODULE)) return;
pf = (n: string | number, ord?: boolean) => getPlural(n, ord);
module = isDefault ? PLURAL_MODULE : getPlural.module || null;
toString = () => String(getPlural);
}
this.runtime[key] = Object.assign(pf, {
id: key,
module,
toString,
type: 'locale'
});
}
setRuntimeFn(
key: 'number' | 'plural' | 'select' | 'strictNumber' | 'reqArgs'
) {
if (this.runtimeIncludes(key, 'runtime')) return;
this.runtime[key] = Object.assign(Runtime[key], {
id: key,
module: RUNTIME_MODULE,
type: 'runtime'
} as const);
}
getFormatterArg({ key, param }: FunctionArg, pluralToken: Select | null) {
const fmt =
this.options.customFormatters[key] ||
(isFormatterKey(key) && Formatters[key]);
/* istanbul ignore if: never happens */
if (!fmt || !param) return null;
const argShape = ('arg' in fmt && fmt.arg) || 'string';
if (argShape === 'options') {
let value = '';
for (const tok of param) {
if (tok.type === 'content') value += tok.value;
else
throw new SyntaxError(
`Expected literal options for ${key} formatter`
);
}
const options: Record<string, string | number | boolean | null> = {};
for (const pair of value.split(',')) {
const keyEnd = pair.indexOf(':');
if (keyEnd === -1) options[pair.trim()] = null;
else {
const k = pair.substring(0, keyEnd).trim();
const v = pair.substring(keyEnd + 1).trim();
if (v === 'true') options[k] = true;
else if (v === 'false') options[k] = false;
else if (v === 'null') options[k] = null;
else {
const n = Number(v);
options[k] = Number.isFinite(n) ? n : v;
}
}
}
return JSON.stringify(options);
} else {
const parts = param.map(tok => this.token(tok, pluralToken));
if (argShape === 'raw') return `[${parts.join(', ')}]`;
const s = parts.join(' + ');
return s ? `(${s}).trim()` : '""';
}
}
setFormatter(key: string) {
if (this.runtimeIncludes(key, 'formatter')) return;
let cf = this.options.customFormatters[key];
if (cf) {
if (typeof cf === 'function') cf = { formatter: cf };
this.runtime[key] = Object.assign(
cf.formatter,
{ type: 'formatter' } as const,
'module' in cf && cf.module && cf.id
? { id: identifier(cf.id), module: cf.module }
: { id: null, module: null }
);
} else if (isFormatterKey(key)) {
this.runtime[key] = Object.assign(
Formatters[key],
{ type: 'formatter' } as const,
{ id: key, module: FORMATTER_MODULE }
);
} else {
throw new Error(`Formatting function not found: ${key}`);
}
}
setDateFormatter(
{ param }: FunctionArg,
args: (number | string)[],
plural: Select | null
) {
const { locale } = this.plural;
const argStyle = param && param.length === 1 && param[0];
if (
argStyle &&
argStyle.type === 'content' &&
/^\s*::/.test(argStyle.value)
) {
const argSkeletonText = argStyle.value.trim().substr(2);
const key = identifier(`date_${locale}_${argSkeletonText}`, true);
if (!this.runtimeIncludes(key, 'formatter')) {
const fmt: RuntimeEntry = getDateFormatter(locale, argSkeletonText);
this.runtime[key] = Object.assign(fmt, {
id: key,
module: null,
toString: () => getDateFormatterSource(locale, argSkeletonText),
type: 'formatter'
});
}
return key;
}
args.push(JSON.stringify(locale));
if (param && param.length > 0) {
if (plural && this.options.strict) plural = null;
const s = param.map(tok => this.token(tok, plural));
args.push('(' + (s.join(' + ') || '""') + ').trim()');
}
this.setFormatter('date');
return 'date';
}
setNumberFormatter(
{ param }: FunctionArg,
args: (number | string)[],
plural: Select | null
) {
const { locale } = this.plural;
if (!param || param.length === 0) {
// {var, number} can use runtime number(lc, var, offset)
args.unshift(JSON.stringify(locale));
args.push('0');
this.setRuntimeFn('number');
return 'number';
}
args.push(JSON.stringify(locale));
if (param.length === 1 && param[0].type === 'content') {
const fmtArg = param[0].value.trim();
switch (fmtArg) {
case 'currency':
args.push(JSON.stringify(this.options.currency));
this.setFormatter('numberCurrency');
return 'numberCurrency';
case 'integer':
this.setFormatter('numberInteger');
return 'numberInteger';
case 'percent':
this.setFormatter('numberPercent');
return 'numberPercent';
}
// TODO: Deprecate
const cm = fmtArg.match(/^currency:([A-Z]+)$/);
if (cm) {
args.push(JSON.stringify(cm[1]));
this.setFormatter('numberCurrency');
return 'numberCurrency';
}
const key = identifier(`number_${locale}_${fmtArg}`, true);
/* istanbul ignore else */
if (!this.runtimeIncludes(key, 'formatter')) {
const { currency } = this.options;
const fmt: RuntimeEntry = getNumberFormatter(locale, fmtArg, currency);
this.runtime[key] = Object.assign(fmt, {
id: null,
module: null,
toString: () => getNumberFormatterSource(locale, fmtArg, currency),
type: 'formatter'
});
}
return key;
}
/* istanbul ignore next: never happens */
if (plural && this.options.strict) plural = null;
const s = param.map(tok => this.token(tok, plural));
args.push('(' + (s.join(' + ') || '""') + ').trim()');
args.push(JSON.stringify(this.options.currency));
this.setFormatter('numberFmt');
return 'numberFmt';
}
}
function isFormatterKey(key: string): key is keyof typeof Formatters {
return key in Formatters;
} | the_stack |
import { AmbientLight, Box3, BufferGeometry, DirectionalLight, Group, Line, Material, Object3D, Raycaster, Scene, Vector3 } from "three"
import { CodeMapMesh } from "../rendering/codeMapMesh"
import { CodeMapBuilding } from "../rendering/codeMapBuilding"
import { CodeMapPreRenderService, CodeMapPreRenderServiceSubscriber } from "../codeMap.preRender.service"
import { IRootScopeService } from "angular"
import { StoreService } from "../../../state/store.service"
import { CodeMapNode, LayoutAlgorithm, MapColors, Node } from "../../../codeCharta.model"
import { hierarchy } from "d3-hierarchy"
import { ColorConverter } from "../../../util/color/colorConverter"
import { MapColorsService, MapColorsSubscriber } from "../../../state/store/appSettings/mapColors/mapColors.service"
import { FloorLabelDrawer } from "./floorLabels/floorLabelDrawer"
import { setSelectedBuildingId } from "../../../state/store/appStatus/selectedBuildingId/selectedBuildingId.actions"
export interface BuildingSelectedEventSubscriber {
onBuildingSelected(selectedBuilding?: CodeMapBuilding)
}
export interface BuildingDeselectedEventSubscriber {
onBuildingDeselected()
}
export interface CodeMapMeshChangedSubscriber {
onCodeMapMeshChanged(mapMesh: CodeMapMesh)
}
export class ThreeSceneService implements CodeMapPreRenderServiceSubscriber, MapColorsSubscriber {
private static readonly BUILDING_SELECTED_EVENT = "building-selected"
private static readonly BUILDING_DESELECTED_EVENT = "building-deselected"
private static readonly CODE_MAP_MESH_CHANGED_EVENT = "code-map-mesh-changed"
scene: Scene
labels: Group
floorLabelPlanes: Group
edgeArrows: Group
mapGeometry: Group
private readonly lights: Group
private mapMesh: CodeMapMesh
private selected: CodeMapBuilding = null
private highlighted: CodeMapBuilding[] = []
private constantHighlight: Map<number, CodeMapBuilding> = new Map()
private folderLabelColorHighlighted = ColorConverter.convertHexToNumber("#FFFFFF")
private folderLabelColorNotHighlighted = ColorConverter.convertHexToNumber("#7A7777")
private folderLabelColorSelected = this.storeService.getState().appSettings.mapColors.selected
private numberSelectionColor = ColorConverter.convertHexToNumber(this.folderLabelColorSelected)
private rayPoint = new Vector3(0, 0, 0)
private normedTransformVector = new Vector3(0, 0, 0)
private highlightedLabel = null
private highlightedLineIndex = -1
private highlightedLine = null
private mapLabelColors = this.storeService.getState().appSettings.mapColors.labelColorAndAlpha
constructor(private $rootScope: IRootScopeService, private storeService: StoreService) {
"ngInject"
MapColorsService.subscribe(this.$rootScope, this)
CodeMapPreRenderService.subscribe(this.$rootScope, this)
this.scene = new Scene()
this.mapGeometry = new Group()
this.lights = new Group()
this.labels = new Group()
this.floorLabelPlanes = new Group()
this.edgeArrows = new Group()
this.initLights()
this.scene.add(this.mapGeometry)
this.scene.add(this.edgeArrows)
this.scene.add(this.labels)
this.scene.add(this.lights)
this.scene.add(this.floorLabelPlanes)
}
private initFloorLabels(nodes: Node[]) {
this.floorLabelPlanes.clear()
const { layoutAlgorithm } = this.storeService.getState().appSettings
if (layoutAlgorithm !== LayoutAlgorithm.SquarifiedTreeMap) {
return
}
const rootNode = this.getRootNode(nodes)
if (!rootNode) {
return
}
const { mapSize } = this.storeService.getState().treeMap
const scaling = this.storeService.getState().appSettings.scaling
const floorLabelDrawer = new FloorLabelDrawer(this.mapMesh.getNodes(), rootNode, mapSize, scaling)
const floorLabels = floorLabelDrawer.draw()
if (floorLabels.length > 0) {
this.floorLabelPlanes.add(...floorLabels)
this.scene.add(this.floorLabelPlanes)
}
}
private getRootNode(nodes: Node[]) {
return nodes.find(node => node.id === 0)
}
onMapColorsChanged(mapColors: MapColors) {
this.folderLabelColorSelected = mapColors.selected
this.numberSelectionColor = ColorConverter.convertHexToNumber(this.folderLabelColorSelected)
}
onRenderMapChanged() {
this.reselectBuilding()
}
getConstantHighlight() {
return this.constantHighlight
}
highlightBuildings() {
const state = this.storeService.getState()
this.getMapMesh().highlightBuilding(this.highlighted, this.selected, state, this.constantHighlight)
if (this.mapGeometry.children[0]) {
this.highlightMaterial(this.mapGeometry.children[0]["material"])
}
}
private selectMaterial(materials: Material[]) {
const selectedMaterial = materials.find(({ userData }) => userData.id === this.selected.node.id)
selectedMaterial?.["color"].setHex(this.numberSelectionColor)
}
private resetMaterial(materials: Material[]) {
const selectedID = this.selected ? this.selected.node.id : -1
for (const material of materials) {
const materialNodeId = material.userData.id
if (materialNodeId !== selectedID) {
material["color"]?.setHex(this.folderLabelColorHighlighted)
}
}
}
scaleHeight() {
const { mapSize } = this.storeService.getState().treeMap
const scale = this.storeService.getState().appSettings.scaling
this.mapGeometry.scale.set(scale.x, scale.y, scale.z)
this.mapGeometry.position.set(-mapSize * scale.x, 0, -mapSize * scale.z)
this.mapMesh.setScale(scale)
}
private highlightMaterial(materials: Material[]) {
const highlightedNodeIds = new Set(this.highlighted.map(({ node }) => node.id))
const constantHighlightedNodes = new Set<number>()
for (const { node } of this.constantHighlight.values()) {
constantHighlightedNodes.add(node.id)
}
for (const material of materials) {
const materialNodeId = material.userData.id
if (this.selected && materialNodeId === this.selected.node.id) {
material["color"].setHex(this.numberSelectionColor)
} else if (highlightedNodeIds.has(materialNodeId) || constantHighlightedNodes.has(materialNodeId)) {
material["color"].setHex(this.folderLabelColorHighlighted)
} else {
material["color"]?.setHex(this.folderLabelColorNotHighlighted)
}
}
}
highlightSingleBuilding(building: CodeMapBuilding) {
this.highlighted = []
this.addBuildingToHighlightingList(building)
this.highlightBuildings()
}
addBuildingToHighlightingList(building: CodeMapBuilding) {
this.highlighted.push(building)
}
clearHoverHighlight() {
this.highlighted = []
this.highlightBuildings()
}
clearHighlight() {
if (this.getMapMesh()) {
this.getMapMesh().clearHighlight(this.selected)
this.highlighted = []
this.constantHighlight.clear()
if (this.mapGeometry.children[0]) {
this.resetMaterial(this.mapGeometry.children[0]["material"])
}
}
}
selectBuilding(building: CodeMapBuilding) {
// TODO this check shouldn't be necessary. When investing into model we should investigate why and remove the need.
if (building.id !== this.selected?.id) {
this.storeService.dispatch(setSelectedBuildingId(building.id))
}
this.getMapMesh().selectBuilding(building, this.folderLabelColorSelected)
this.selected = building
this.highlightBuildings()
this.$rootScope.$broadcast(ThreeSceneService.BUILDING_SELECTED_EVENT, this.selected)
if (this.mapGeometry.children[0]) {
this.selectMaterial(this.mapGeometry.children[0]["material"])
}
}
animateLabel(hoveredLabel: Object3D, raycaster: Raycaster, labels: Object3D[]) {
if (hoveredLabel !== null && raycaster !== null) {
this.resetLabel()
if (hoveredLabel["material"]) {
hoveredLabel["material"].opacity = 1
}
this.highlightedLineIndex = this.getHoveredLabelLineIndex(labels, hoveredLabel)
this.highlightedLine = labels[this.highlightedLineIndex]
this.rayPoint = new Vector3()
this.rayPoint.subVectors(raycaster.ray.origin, hoveredLabel.position)
const norm = Math.sqrt(this.rayPoint.x ** 2 + this.rayPoint.y ** 2 + this.rayPoint.z ** 2)
const cameraPoint = raycaster.ray.origin
const maxDistance = this.calculateMaxDistance(hoveredLabel, labels, cameraPoint, norm)
this.normedTransformVector = new Vector3(this.rayPoint.x / norm, this.rayPoint.y / norm, this.rayPoint.z / norm)
this.normedTransformVector.multiplyScalar(maxDistance)
hoveredLabel.position.add(this.normedTransformVector)
this.toggleLineAnimation(hoveredLabel)
this.highlightedLabel = hoveredLabel
}
}
resetLineHighlight() {
this.highlightedLineIndex = -1
this.highlightedLine = null
}
resetLabel() {
if (this.highlightedLabel !== null) {
this.highlightedLabel.position.sub(this.normedTransformVector)
this.highlightedLabel.material.opacity = this.mapLabelColors.alpha
if (this.highlightedLine) {
this.toggleLineAnimation(this.highlightedLabel)
}
this.highlightedLabel = null
}
}
getHoveredLabelLineIndex(labels: Object3D[], label: Object3D) {
const index = labels.findIndex(({ uuid }) => uuid === label.uuid)
if (index >= 0) {
return index + 1
}
}
toggleLineAnimation(hoveredLabel: Object3D) {
const endPoint = new Vector3(hoveredLabel.position.x, hoveredLabel.position.y, hoveredLabel.position.z)
const pointsBufferGeometry = this.highlightedLine.geometry as BufferGeometry
const pointsArray = pointsBufferGeometry.attributes.position.array as Array<number>
const geometry = new BufferGeometry().setFromPoints([new Vector3(pointsArray[0], pointsArray[1], pointsArray[2]), endPoint])
const newLineForHighlightedLabel = new Line(geometry, this.highlightedLine.material)
this.labels.children.splice(this.highlightedLineIndex, 1, newLineForHighlightedLabel)
}
getLabelForHoveredNode(hoveredBuilding: CodeMapBuilding, labels: Object3D[]) {
if (!labels) {
return null
}
// 2-step: the labels array consists of alternating label and the corresponding label antennae
for (let counter = 0; counter < labels.length; counter += 2) {
if (labels[counter].userData.node === hoveredBuilding.node) {
return labels[counter]
}
}
return null
}
private isOverlapping(a: Box3, b: Box3, dimension: string) {
return Number(a.max[dimension] >= b.min[dimension] && b.max[dimension] >= a.min[dimension])
}
private getIntersectionDistance(bboxHoveredLabel: Box3, bboxObstructingLabel: Box3, normedVector: Vector3, distance: number) {
normedVector.multiplyScalar(distance)
bboxHoveredLabel.translate(normedVector)
const count =
this.isOverlapping(bboxObstructingLabel, bboxHoveredLabel, "x") +
this.isOverlapping(bboxObstructingLabel, bboxHoveredLabel, "y")
if (count === 2 || (count === 1 && this.isOverlapping(bboxObstructingLabel, bboxHoveredLabel, "z"))) {
return distance
}
return 0
}
private calculateMaxDistance(hoveredLabel: Object3D, labels: Object3D[], cameraPoint: Vector3, norm: number) {
let maxDistance = 0
const bboxHoveredLabel = new Box3().setFromObject(hoveredLabel)
const centerPoint = new Vector3()
bboxHoveredLabel.getCenter(centerPoint)
const distanceLabelCenterToCamera = cameraPoint.distanceTo(centerPoint)
let maxDistanceForLabel = distanceLabelCenterToCamera / 20
for (let counter = 0; counter < labels.length; counter += 2) {
//creates a nice small highlighting for hovered, unobstructed labels, empirically gathered value
const bboxHoveredLabelWorkingCopy = bboxHoveredLabel.clone()
if (labels[counter] !== hoveredLabel) {
const bboxObstructingLabel = new Box3().setFromObject(labels[counter])
const centerPoint2 = new Vector3()
bboxObstructingLabel.getCenter(centerPoint2)
maxDistanceForLabel = Math.max(
this.getIntersectionDistance(
bboxHoveredLabelWorkingCopy,
bboxObstructingLabel,
new Vector3(this.rayPoint.x / norm, this.rayPoint.y / norm, this.rayPoint.z / norm),
distanceLabelCenterToCamera - cameraPoint.distanceTo(centerPoint2)
),
this.getIntersectionDistance(
bboxHoveredLabelWorkingCopy,
bboxObstructingLabel,
new Vector3(this.rayPoint.x / norm, this.rayPoint.y / norm, this.rayPoint.z / norm),
distanceLabelCenterToCamera - cameraPoint.distanceTo(bboxObstructingLabel.max)
),
this.getIntersectionDistance(
bboxHoveredLabelWorkingCopy,
bboxObstructingLabel,
new Vector3(this.rayPoint.x / norm, this.rayPoint.y / norm, this.rayPoint.z / norm),
distanceLabelCenterToCamera - cameraPoint.distanceTo(bboxObstructingLabel.min)
)
)
}
maxDistance = Math.max(maxDistance, maxDistanceForLabel)
}
return maxDistance
}
addNodeAndChildrenToConstantHighlight(codeMapNode: CodeMapNode) {
const { lookUp } = this.storeService.getState()
const codeMapBuilding = lookUp.idToNode.get(codeMapNode.id)
for (const { data } of hierarchy(codeMapBuilding)) {
const building = lookUp.idToBuilding.get(data.id)
if (building) {
this.constantHighlight.set(building.id, building)
}
}
}
removeNodeAndChildrenFromConstantHighlight(codeMapNode: CodeMapNode) {
const { lookUp } = this.storeService.getState()
const codeMapBuilding = lookUp.idToNode.get(codeMapNode.id)
for (const { data } of hierarchy(codeMapBuilding)) {
const building = lookUp.idToBuilding.get(data.id)
if (building) {
this.constantHighlight.delete(building.id)
}
}
}
clearConstantHighlight() {
if (this.constantHighlight.size > 0) {
this.clearHighlight()
}
}
clearSelection() {
if (this.selected) {
this.getMapMesh().clearSelection(this.selected)
this.storeService.dispatch(setSelectedBuildingId(null))
this.$rootScope.$broadcast(ThreeSceneService.BUILDING_DESELECTED_EVENT)
}
if (this.highlighted.length > 0) {
this.highlightBuildings()
}
this.selected = null
if (this.mapGeometry.children[0]) {
this.resetMaterial(this.mapGeometry.children[0]["material"])
}
}
initLights() {
const ambilight = new AmbientLight(0x70_70_70) // soft white light
const light1 = new DirectionalLight(0xe0_e0_e0, 1)
light1.position.set(50, 10, 8).normalize()
const light2 = new DirectionalLight(0xe0_e0_e0, 1)
light2.position.set(-50, 10, -8).normalize()
this.lights.add(ambilight)
this.lights.add(light1)
this.lights.add(light2)
}
setMapMesh(nodes: Node[], mesh: CodeMapMesh) {
const { mapSize } = this.storeService.getState().treeMap
this.mapMesh = mesh
this.initFloorLabels(nodes)
// Reset children
this.mapGeometry.children.length = 0
this.mapGeometry.position.x = -mapSize
this.mapGeometry.position.y = 0
this.mapGeometry.position.z = -mapSize
this.mapGeometry.add(this.mapMesh.getThreeMesh())
this.notifyMapMeshChanged()
}
getMapMesh() {
return this.mapMesh
}
getSelectedBuilding() {
return this.selected
}
getHighlightedBuilding() {
return this.highlighted[0]
}
getHighlightedNode() {
if (this.getHighlightedBuilding()) {
return this.getHighlightedBuilding().node
}
return null
}
private reselectBuilding() {
if (this.selected) {
const buildingToSelect: CodeMapBuilding = this.getMapMesh().getBuildingByPath(this.selected.node.path)
if (buildingToSelect) {
this.selectBuilding(buildingToSelect)
}
}
}
private notifyMapMeshChanged() {
this.$rootScope.$broadcast(ThreeSceneService.CODE_MAP_MESH_CHANGED_EVENT, this.mapMesh)
}
dispose() {
this.mapMesh?.dispose()
}
static subscribeToBuildingDeselectedEvents($rootScope: IRootScopeService, subscriber: BuildingDeselectedEventSubscriber) {
$rootScope.$on(this.BUILDING_DESELECTED_EVENT, () => {
subscriber.onBuildingDeselected()
})
}
static subscribeToBuildingSelectedEvents($rootScope: IRootScopeService, subscriber: BuildingSelectedEventSubscriber) {
$rootScope.$on(this.BUILDING_SELECTED_EVENT, (_event, selectedBuilding: CodeMapBuilding) => {
subscriber.onBuildingSelected(selectedBuilding)
})
}
static subscribeToCodeMapMeshChangedEvent($rootScope: IRootScopeService, subscriber: CodeMapMeshChangedSubscriber) {
$rootScope.$on(this.CODE_MAP_MESH_CHANGED_EVENT, (_event, mapMesh: CodeMapMesh) => {
subscriber.onCodeMapMeshChanged(mapMesh)
})
}
} | the_stack |
import { MetadataSource } from '../metadata-source'
import { Metadata } from '../metadata'
import Axios from 'axios'
import { JSDOM } from 'jsdom'
import { log } from '../../debug'
import { MetadataConfig } from '../../core-config'
import { altNames } from './alt-names'
type TrackParseInfo = { name: string, result: string | string[] }
export class THBWiki extends MetadataSource {
cache = new Map<string, { document: Document, cover: Buffer | undefined }>()
// https://thwiki.cc/api.php?action=opensearch&format=json&search=kappa&limit=20&suggest=true
async resolveAlbumName(albumName: string) {
// const url = `https://thwiki.cc/index.php?search=${encodeURIComponent(albumName)}`
// const document = new JSDOM((await Axios.get(url)).data).window.document
// const header = document.querySelector('#firstHeading')
// // 未找到精确匹配, 返回搜索结果
// if (header && header.textContent === '搜索结果') {
// return [...document.querySelectorAll('.mw-search-result-heading a')]
// .map(it => it.textContent!)
// .filter(it => !it.startsWith('歌词:'))
// } else {
// return albumName
// }
const url = `https://thwiki.cc/api.php?action=opensearch&format=json&search=${encodeURIComponent(albumName)}&limit=20&suggest=true`
const response = await Axios.get(url, {
responseType: 'json',
timeout: this.config.timeout * 1000,
})
if (response.status === 200) {
const [, names] = response.data
const [name] = (names as string[]).filter(it => !it.startsWith('歌词:'))
if (name === albumName) {
return name
} else {
return names as string[]
}
} else {
return []
}
}
private async getAlbumCover(img: HTMLImageElement) {
const src = img.src.replace('/thumb/', '/')
const url = src.substring(0, src.lastIndexOf('/'))
const response = await Axios.get(url, {
responseType: 'arraybuffer',
timeout: this.config.timeout * 1000,
})
return response.data as Buffer
}
private getAlbumData(infoTable: Element) {
function getTableItem(labelName: string): string
function getTableItem(labelName: string, multiple: true): string[]
function getTableItem(labelName: string, multiple = false) {
const labelElements = [...infoTable.querySelectorAll('.label')]
.filter(it => it.innerHTML.trim() === labelName)
if (labelElements.length === 0) {
return ''
}
const [item] = labelElements.map(it => {
const nextElement = it.nextElementSibling as HTMLElement
if (multiple) {
return [...nextElement.querySelectorAll('a')]
.map(element => element.textContent)
} else {
return nextElement.textContent!.trim()
}
})
return item
}
const album = getTableItem('名称')
const albumOrder = getTableItem('编号')
const albumArtists = getTableItem('制作方', true)
const genres = getTableItem('风格类型').split(',')
const year = parseInt(getTableItem('首发日期')).toString()
return {
album,
albumOrder,
albumArtists,
genres,
year
}
}
private getRelatedRows(trackNumberRow: Element): Element[] {
const nextElement = trackNumberRow.nextElementSibling
if (nextElement === null || nextElement.querySelector('.left') === null) {
return []
}
return [nextElement, ...this.getRelatedRows(nextElement)]
}
private parseRelatedRowInfo(trackInfoRow: Element): TrackParseInfo {
const defaultInfoParser = (name: string): (data: Element) => TrackParseInfo => {
return (data: Element) => {
const children = [...data.children]
const brIndex = children.findIndex(it => it.tagName.toLowerCase() === 'br')
if (brIndex !== -1) {
children.slice(brIndex).forEach(e => e.remove())
}
let textContent = data.textContent!
/*
要是这个值就是一个_, THBWiki 会转成一个警告...
例如疯帽子茶会'千年战争'中出现的编曲者就有一个_ (现已更名为'底线')
https://thwiki.cc/%E5%8D%83%E5%B9%B4%E6%88%98%E4%BA%89%EF%BD%9Eiek_loin_staim_haf_il_dis_o-del_al
*/
const warningMatch = textContent.match(/包含无效字符或不完整,并因此在查询或注释过程期间导致意外结果。\[\[(.+)\]\]/)
if (warningMatch) {
textContent = warningMatch[1]
}
return {
name,
result: textContent.trim().split(',')
}
}
}
const label = trackInfoRow.querySelector('.label')!.textContent!.trim()
const data = trackInfoRow.querySelector('.text') as HTMLElement
const actions: { [infoName: string]: (data: HTMLElement) => TrackParseInfo } = {
编曲: defaultInfoParser('arrangers'),
再编曲: defaultInfoParser('remix'),
作曲: defaultInfoParser('composers'),
剧本: defaultInfoParser('scripts'),
演唱: defaultInfoParser('vocals'),
翻唱: defaultInfoParser('coverVocals'),
和声: defaultInfoParser('harmonyVocals'),
伴唱: defaultInfoParser('accompanyVocals'),
合唱: defaultInfoParser('chorusVocals'),
// 演奏: defaultInfoParser('instruments'),
作词: defaultInfoParser('lyricists'),
配音: (data) => {
const name = 'voices'
const rows = data.innerHTML.split('<br>').map(it => {
const document = new JSDOM(it).window.document
const anchors = [...document.querySelectorAll('a:not(.external)')]
const artists = anchors.map(a => {
const isRealArtist = a.previousSibling && a.previousSibling.textContent === '('
&& a.nextSibling && a.nextSibling.textContent === ')'
if (isRealArtist) {
return a.textContent!
}
return ''
})
if (artists.every(a => a === '')) {
return anchors.map(a => a.textContent!)
}
return artists.filter(a => a !== '')
})
// log(rows.flat())
return {
name,
result: rows.flat(),
}
},
演奏: (data) => {
const name = 'instruments'
const rows = data.innerHTML.split('<br>').map(it => {
const [instrument, performer] = it.trim().split(':').map(row => {
return new JSDOM(row).window.document.body.textContent!
})
return performer ? performer : instrument
})
return {
name,
result: rows,
}
},
原曲: (data) => {
let result = `原曲: `
const sources = [...data.querySelectorAll('.ogmusic,.source')] as Element[]
sources.forEach((element, index) => {
const comma = ', '
if (element.classList.contains('ogmusic')) {
result += element.textContent!.trim()
// 后面还有原曲时加逗号
if (index < sources.length - 1 && sources[index + 1].classList.contains('ogmusic')) {
result += comma
}
} else { // .source
result += ` (${element.textContent!.trim()})`
// 不是最后一个source时加逗号
if (index !== sources.length - 1) {
result += comma
}
}
})
return {
name: 'comments',
result,
}
}
}
const action = actions[label]
if (!action) {
return { name: 'other', result: '' }
}
return action(data)
}
private rowDataNormalize(rowData: Record<string, string | string[] | undefined>) {
const normalizeAction = (str: string) => {
if (altNames.has(str)) {
return altNames.get(str)!
}
return str
.replace(/\u200b/g, '') // zero-width space
.replace(/ /g, ' ')
.replace(/(人物)$/, '')
.replace(/(现实人物)$/, '')
.replace(/(作曲家)$/, '')
.replace(/([^\s])([\(])/g, '$1 $2')
.replace(/([\)])([^\s])/g, '$1 $2')
.replace(/([^\s]) ([(])/g, '$1$2')
.replace(/([)]) ([^\s])/g, '$1$2')
.replace(/’/g, "'")
.trim()
}
for (const [key, value] of Object.entries(rowData)) {
if (typeof value === 'string') {
rowData[key] = normalizeAction(value)
}
if (Array.isArray(value)) {
rowData[key] = value.map(v => normalizeAction(v))
}
}
}
private async parseRow(trackNumberElement: Element) {
const trackNumber = parseInt(trackNumberElement.textContent!, 10).toString()
const trackNumberRow = trackNumberElement.parentElement as HTMLTableRowElement
const title = trackNumberRow.querySelector('.title')!.textContent!.trim()
const { lyricLanguage, lyric } = await (async () => {
const lyricLink = trackNumberRow.querySelector(':not(.new) > a:not(.external)') as HTMLAnchorElement
if (this.config.lyric && lyricLink) {
const { downloadLyrics } = await import('./lyrics/thb-wiki-lyrics')
return await downloadLyrics('https://thwiki.cc' + lyricLink.href, title, this.config as Required<MetadataConfig>)
} else {
return {
lyric: undefined,
lyricLanguage: undefined
}
}
})()
const relatedInfoRows = this.getRelatedRows(trackNumberRow)
const infos = relatedInfoRows.map(it => this.parseRelatedRowInfo(it))
const [lyricists] = infos
.filter(it => it.name === 'lyricists')
.map(it => it.result as string[])
const [comments] = infos
.filter(it => it.name === 'comments')
.map(it => it.result as string)
const arrangers = ['remix', 'arrangers', 'scripts']
.flatMap(name => infos
.filter(it => it.name === name)
.map(it => it.result as string[])
.flat()
)
const performers = [
'vocals',
'coverVocals',
'harmonyVocals',
'accompanyVocals',
'chorusVocals',
'instruments',
'voices',
].flatMap(name => infos
.filter(it => it.name === name)
.map(it => it.result as string[])
.flat()
)
const [composers] = infos
.filter(it => it.name === 'composers')
.map(it => it.result as string[])
// log('artists:', artists)
if (arrangers.length === 0 && composers) {
arrangers.push(...composers)
}
const artists = [...new Set(performers.concat(arrangers))]
const rowData = {
title,
artists,
trackNumber,
comments,
lyricists,
composers,
lyric,
lyricLanguage,
}
this.rowDataNormalize(rowData)
log(rowData)
return rowData
}
async getMetadata(albumName: string, cover?: Buffer) {
const url = `https://thwiki.cc/index.php?search=${encodeURIComponent(albumName)}`
const response = await Axios.get(url, { timeout: this.config.timeout * 1000 })
const dom = new JSDOM(response.data)
const document = dom.window.document
const infoTable = document.querySelector('.doujininfo') as HTMLTableElement
if (!infoTable) {
throw new Error('页面不是同人专辑词条')
}
const {
album,
albumOrder,
albumArtists,
genres,
year
} = this.getAlbumData(infoTable)
const coverImageElement = document.querySelector('.cover-artwork img') as HTMLImageElement
const coverImage = await (async () => {
if (cover) {
return cover
}
if (coverImageElement) {
return this.getAlbumCover(coverImageElement)
}
return undefined
})()
const musicTables = [...document.querySelectorAll('.musicTable')] as HTMLTableElement[]
let discNumber = 1
const metadatas = [] as Metadata[]
for (const table of musicTables) {
const trackNumbers = [...table.querySelectorAll('tr > td[class^="info"]')] as HTMLTableDataCellElement[]
for (const trackNumberElement of trackNumbers) {
const metadata: Metadata = {
discNumber: discNumber.toString(),
album,
albumOrder,
albumArtists,
genres,
year,
coverImage,
...(await this.parseRow(trackNumberElement))
}
metadatas.push(metadata)
}
discNumber++
}
return metadatas
}
}
export const thbWiki = new THBWiki() | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Manages a VPN Gateway Connection.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleVirtualWan = new azure.network.VirtualWan("exampleVirtualWan", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* });
* const exampleVirtualHub = new azure.network.VirtualHub("exampleVirtualHub", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* virtualWanId: exampleVirtualWan.id,
* addressPrefix: "10.0.0.0/24",
* });
* const exampleVpnGateway = new azure.network.VpnGateway("exampleVpnGateway", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* virtualHubId: exampleVirtualHub.id,
* });
* const exampleVpnSite = new azure.network.VpnSite("exampleVpnSite", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* virtualWanId: exampleVirtualWan.id,
* links: [
* {
* name: "link1",
* ipAddress: "10.1.0.0",
* },
* {
* name: "link2",
* ipAddress: "10.2.0.0",
* },
* ],
* });
* const exampleVpnGatewayConnection = new azure.network.VpnGatewayConnection("exampleVpnGatewayConnection", {
* vpnGatewayId: exampleVpnGateway.id,
* remoteVpnSiteId: exampleVpnSite.id,
* vpnLinks: [
* {
* name: "link1",
* vpnSiteLinkId: exampleVpnSite.links.apply(links => links?[0]?.id),
* },
* {
* name: "link2",
* vpnSiteLinkId: exampleVpnSite.links.apply(links => links?[1]?.id),
* },
* ],
* });
* ```
*
* ## Import
*
* VPN Gateway Connections can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:network/vpnGatewayConnection:VpnGatewayConnection example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Network/vpnGateways/gateway1/vpnConnections/conn1
* ```
*/
export class VpnGatewayConnection extends pulumi.CustomResource {
/**
* Get an existing VpnGatewayConnection 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?: VpnGatewayConnectionState, opts?: pulumi.CustomResourceOptions): VpnGatewayConnection {
return new VpnGatewayConnection(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:network/vpnGatewayConnection:VpnGatewayConnection';
/**
* Returns true if the given object is an instance of VpnGatewayConnection. 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 VpnGatewayConnection {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === VpnGatewayConnection.__pulumiType;
}
/**
* Whether Internet Security is enabled for this VPN Connection. Defaults to `false`.
*/
public readonly internetSecurityEnabled!: pulumi.Output<boolean | undefined>;
/**
* The name which should be used for this VPN Gateway Connection. Changing this forces a new VPN Gateway Connection to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* The ID of the remote VPN Site, which will connect to the VPN Gateway. Changing this forces a new VPN Gateway Connection to be created.
*/
public readonly remoteVpnSiteId!: pulumi.Output<string>;
/**
* A `routing` block as defined below. If this is not specified, there will be a default route table created implicitly.
*/
public readonly routings!: pulumi.Output<outputs.network.VpnGatewayConnectionRouting[]>;
/**
* One or more `trafficSelectorPolicy` blocks as defined below.
*/
public readonly trafficSelectorPolicies!: pulumi.Output<outputs.network.VpnGatewayConnectionTrafficSelectorPolicy[] | undefined>;
/**
* The ID of the VPN Gateway that this VPN Gateway Connection belongs to. Changing this forces a new VPN Gateway Connection to be created.
*/
public readonly vpnGatewayId!: pulumi.Output<string>;
/**
* One or more `vpnLink` blocks as defined below.
*/
public readonly vpnLinks!: pulumi.Output<outputs.network.VpnGatewayConnectionVpnLink[]>;
/**
* Create a VpnGatewayConnection 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: VpnGatewayConnectionArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: VpnGatewayConnectionArgs | VpnGatewayConnectionState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as VpnGatewayConnectionState | undefined;
inputs["internetSecurityEnabled"] = state ? state.internetSecurityEnabled : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["remoteVpnSiteId"] = state ? state.remoteVpnSiteId : undefined;
inputs["routings"] = state ? state.routings : undefined;
inputs["trafficSelectorPolicies"] = state ? state.trafficSelectorPolicies : undefined;
inputs["vpnGatewayId"] = state ? state.vpnGatewayId : undefined;
inputs["vpnLinks"] = state ? state.vpnLinks : undefined;
} else {
const args = argsOrState as VpnGatewayConnectionArgs | undefined;
if ((!args || args.remoteVpnSiteId === undefined) && !opts.urn) {
throw new Error("Missing required property 'remoteVpnSiteId'");
}
if ((!args || args.vpnGatewayId === undefined) && !opts.urn) {
throw new Error("Missing required property 'vpnGatewayId'");
}
if ((!args || args.vpnLinks === undefined) && !opts.urn) {
throw new Error("Missing required property 'vpnLinks'");
}
inputs["internetSecurityEnabled"] = args ? args.internetSecurityEnabled : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["remoteVpnSiteId"] = args ? args.remoteVpnSiteId : undefined;
inputs["routings"] = args ? args.routings : undefined;
inputs["trafficSelectorPolicies"] = args ? args.trafficSelectorPolicies : undefined;
inputs["vpnGatewayId"] = args ? args.vpnGatewayId : undefined;
inputs["vpnLinks"] = args ? args.vpnLinks : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(VpnGatewayConnection.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering VpnGatewayConnection resources.
*/
export interface VpnGatewayConnectionState {
/**
* Whether Internet Security is enabled for this VPN Connection. Defaults to `false`.
*/
internetSecurityEnabled?: pulumi.Input<boolean>;
/**
* The name which should be used for this VPN Gateway Connection. Changing this forces a new VPN Gateway Connection to be created.
*/
name?: pulumi.Input<string>;
/**
* The ID of the remote VPN Site, which will connect to the VPN Gateway. Changing this forces a new VPN Gateway Connection to be created.
*/
remoteVpnSiteId?: pulumi.Input<string>;
/**
* A `routing` block as defined below. If this is not specified, there will be a default route table created implicitly.
*/
routings?: pulumi.Input<pulumi.Input<inputs.network.VpnGatewayConnectionRouting>[]>;
/**
* One or more `trafficSelectorPolicy` blocks as defined below.
*/
trafficSelectorPolicies?: pulumi.Input<pulumi.Input<inputs.network.VpnGatewayConnectionTrafficSelectorPolicy>[]>;
/**
* The ID of the VPN Gateway that this VPN Gateway Connection belongs to. Changing this forces a new VPN Gateway Connection to be created.
*/
vpnGatewayId?: pulumi.Input<string>;
/**
* One or more `vpnLink` blocks as defined below.
*/
vpnLinks?: pulumi.Input<pulumi.Input<inputs.network.VpnGatewayConnectionVpnLink>[]>;
}
/**
* The set of arguments for constructing a VpnGatewayConnection resource.
*/
export interface VpnGatewayConnectionArgs {
/**
* Whether Internet Security is enabled for this VPN Connection. Defaults to `false`.
*/
internetSecurityEnabled?: pulumi.Input<boolean>;
/**
* The name which should be used for this VPN Gateway Connection. Changing this forces a new VPN Gateway Connection to be created.
*/
name?: pulumi.Input<string>;
/**
* The ID of the remote VPN Site, which will connect to the VPN Gateway. Changing this forces a new VPN Gateway Connection to be created.
*/
remoteVpnSiteId: pulumi.Input<string>;
/**
* A `routing` block as defined below. If this is not specified, there will be a default route table created implicitly.
*/
routings?: pulumi.Input<pulumi.Input<inputs.network.VpnGatewayConnectionRouting>[]>;
/**
* One or more `trafficSelectorPolicy` blocks as defined below.
*/
trafficSelectorPolicies?: pulumi.Input<pulumi.Input<inputs.network.VpnGatewayConnectionTrafficSelectorPolicy>[]>;
/**
* The ID of the VPN Gateway that this VPN Gateway Connection belongs to. Changing this forces a new VPN Gateway Connection to be created.
*/
vpnGatewayId: pulumi.Input<string>;
/**
* One or more `vpnLink` blocks as defined below.
*/
vpnLinks: pulumi.Input<pulumi.Input<inputs.network.VpnGatewayConnectionVpnLink>[]>;
} | the_stack |
import { IAppsyncFunction } from './appsync-function';
import { BaseDataSource } from './data-source';
import { AuthorizationType } from './graphqlapi';
import { MappingTemplate } from './mapping-template';
import { Type, IField, IIntermediateType, Directive } from './schema-base';
/**
* Base options for GraphQL Types
*
* @option isList - is this attribute a list
* @option isRequired - is this attribute non-nullable
* @option isRequiredList - is this attribute a non-nullable list
*
*/
export interface BaseTypeOptions {
/**
* property determining if this attribute is a list
* i.e. if true, attribute would be [Type]
*
* @default - false
*/
readonly isList?: boolean;
/**
* property determining if this attribute is non-nullable
* i.e. if true, attribute would be Type!
*
* @default - false
*/
readonly isRequired?: boolean;
/**
* property determining if this attribute is a non-nullable list
* i.e. if true, attribute would be [ Type ]!
* or if isRequired true, attribe would be [ Type! ]!
*
* @default - false
*/
readonly isRequiredList?: boolean;
}
/**
* Options for GraphQL Types
*
* @option isList - is this attribute a list
* @option isRequired - is this attribute non-nullable
* @option isRequiredList - is this attribute a non-nullable list
* @option objectType - the object type linked to this attribute
*
*/
export interface GraphqlTypeOptions extends BaseTypeOptions {
/**
* the intermediate type linked to this attribute
* @default - no intermediate type
*/
readonly intermediateType?: IIntermediateType;
}
/**
* The GraphQL Types in AppSync's GraphQL. GraphQL Types are the
* building blocks for object types, queries, mutations, etc. They are
* types like String, Int, Id or even Object Types you create.
*
* i.e. `String`, `String!`, `[String]`, `[String!]`, `[String]!`
*
* GraphQL Types are used to define the entirety of schema.
*/
export class GraphqlType implements IField {
/**
* `ID` scalar type is a unique identifier. `ID` type is serialized similar to `String`.
*
* Often used as a key for a cache and not intended to be human-readable.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static id(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.ID, options);
}
/**
* `String` scalar type is a free-form human-readable text.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static string(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.STRING, options);
}
/**
* `Int` scalar type is a signed non-fractional numerical value.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static int(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.INT, options);
}
/**
* `Float` scalar type is a signed double-precision fractional value.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static float(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.FLOAT, options);
}
/**
* `Boolean` scalar type is a boolean value: true or false.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static boolean(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.BOOLEAN, options);
}
/**
* `AWSDate` scalar type represents a valid extended `ISO 8601 Date` string.
*
* In other words, accepts date strings in the form of `YYYY-MM-DD`. It accepts time zone offsets.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static awsDate(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.AWS_DATE, options);
}
/**
* `AWSTime` scalar type represents a valid extended `ISO 8601 Time` string.
*
* In other words, accepts date strings in the form of `hh:mm:ss.sss`. It accepts time zone offsets.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static awsTime(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.AWS_TIME, options);
}
/**
* `AWSDateTime` scalar type represents a valid extended `ISO 8601 DateTime` string.
*
* In other words, accepts date strings in the form of `YYYY-MM-DDThh:mm:ss.sssZ`. It accepts time zone offsets.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static awsDateTime(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.AWS_DATE_TIME, options);
}
/**
* `AWSTimestamp` scalar type represents the number of seconds since `1970-01-01T00:00Z`.
*
* Timestamps are serialized and deserialized as numbers.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static awsTimestamp(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.AWS_TIMESTAMP, options);
}
/**
* `AWSEmail` scalar type represents an email address string (i.e.`username@example.com`)
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static awsEmail(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.AWS_EMAIL, options);
}
/**
* `AWSJson` scalar type represents a JSON string.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static awsJson(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.AWS_JSON, options);
}
/**
* `AWSURL` scalar type represetns a valid URL string.
*
* URLs wihtout schemes or contain double slashes are considered invalid.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static awsUrl(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.AWS_URL, options);
}
/**
* `AWSPhone` scalar type represents a valid phone number. Phone numbers maybe be whitespace delimited or hyphenated.
*
* The number can specify a country code at the beginning, but is not required for US phone numbers.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static awsPhone(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.AWS_PHONE, options);
}
/**
* `AWSIPAddress` scalar type respresents a valid `IPv4` of `IPv6` address string.
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
*/
public static awsIpAddress(options?: BaseTypeOptions): GraphqlType {
return new GraphqlType(Type.AWS_IP_ADDRESS, options);
}
/**
* an intermediate type to be added as an attribute
* (i.e. an interface or an object type)
*
* @param options the options to configure this attribute
* - isList
* - isRequired
* - isRequiredList
* - intermediateType
*/
public static intermediate(options?: GraphqlTypeOptions): GraphqlType {
if (!options?.intermediateType) {
throw new Error('GraphQL Type of interface must be configured with corresponding Intermediate Type');
}
return new GraphqlType(Type.INTERMEDIATE, options);
}
/**
* the type of attribute
*/
public readonly type: Type;
/**
* property determining if this attribute is a list
* i.e. if true, attribute would be `[Type]`
*
* @default - false
*/
public readonly isList: boolean;
/**
* property determining if this attribute is non-nullable
* i.e. if true, attribute would be `Type!` and this attribute
* must always have a value
*
* @default - false
*/
public readonly isRequired: boolean;
/**
* property determining if this attribute is a non-nullable list
* i.e. if true, attribute would be `[ Type ]!` and this attribute's
* list must always have a value
*
* @default - false
*/
public readonly isRequiredList: boolean;
/**
* the intermediate type linked to this attribute
* (i.e. an interface or an object)
*
* @default - no intermediate type
*/
public readonly intermediateType?: IIntermediateType;
protected constructor(type: Type, options?: GraphqlTypeOptions) {
this.type = type;
this.isList = options?.isList ?? false;
this.isRequired = options?.isRequired ?? false;
this.isRequiredList = options?.isRequiredList ?? false;
this.intermediateType = options?.intermediateType;
}
/**
* Generate the string for this attribute
*/
public toString(): string {
// If an Object Type, we use the name of the Object Type
let type = this.intermediateType ? this.intermediateType?.name : this.type;
// If configured as required, the GraphQL Type becomes required
type = this.isRequired ? `${type}!` : type;
// If configured with isXxxList, the GraphQL Type becomes a list
type = this.isList || this.isRequiredList ? `[${type}]` : type;
// If configured with isRequiredList, the list becomes required
type = this.isRequiredList ? `${type}!` : type;
return type;
}
/**
* Generate the arguments for this field
*/
public argsToString(): string {
return '';
}
/**
* Generate the directives for this field
*/
public directivesToString(_modes?: AuthorizationType[]): string {
return '';
}
}
/**
* Properties for configuring a field
*
* @options args - the variables and types that define the arguments
*
* i.e. { string: GraphqlType, string: GraphqlType }
*/
export interface FieldOptions {
/**
* The return type for this field
*/
readonly returnType: GraphqlType;
/**
* The arguments for this field.
*
* i.e. type Example (first: String second: String) {}
* - where 'first' and 'second' are key values for args
* and 'String' is the GraphqlType
*
* @default - no arguments
*/
readonly args?: { [key: string]: GraphqlType };
/**
* the directives for this field
*
* @default - no directives
*/
readonly directives?: Directive[];
}
/**
* Fields build upon Graphql Types and provide typing
* and arguments.
*/
export class Field extends GraphqlType implements IField {
/**
* The options for this field
*
* @default - no arguments
*/
public readonly fieldOptions?: ResolvableFieldOptions;
public constructor(options: FieldOptions) {
const props = {
isList: options.returnType.isList,
isRequired: options.returnType.isRequired,
isRequiredList: options.returnType.isRequiredList,
intermediateType: options.returnType.intermediateType,
};
super(options.returnType.type, props);
this.fieldOptions = options;
}
/**
* Generate the args string of this resolvable field
*/
public argsToString(): string {
if (!this.fieldOptions || !this.fieldOptions.args) { return ''; }
return Object.keys(this.fieldOptions.args).reduce((acc, key) =>
`${acc}${key}: ${this.fieldOptions?.args?.[key].toString()} `, '(').slice(0, -1) + ')';
}
/**
* Generate the directives for this field
*/
public directivesToString(modes?: AuthorizationType[]): string {
if (!this.fieldOptions || !this.fieldOptions.directives) { return ''; }
return this.fieldOptions.directives.reduce((acc, directive) =>
`${acc}${directive._bindToAuthModes(modes).toString()} `, '\n ').slice(0, -1);
}
}
/**
* Properties for configuring a resolvable field
*
* @options dataSource - the data source linked to this resolvable field
* @options requestMappingTemplate - the mapping template for requests to this resolver
* @options responseMappingTemplate - the mapping template for responses from this resolver
*/
export interface ResolvableFieldOptions extends FieldOptions {
/**
* The data source creating linked to this resolvable field
*
* @default - no data source
*/
readonly dataSource?: BaseDataSource;
/**
* configuration of the pipeline resolver
*
* @default - no pipeline resolver configuration
* An empty array or undefined prop will set resolver to be of type unit
*/
readonly pipelineConfig?: IAppsyncFunction[];
/**
* The request mapping template for this resolver
*
* @default - No mapping template
*/
readonly requestMappingTemplate?: MappingTemplate;
/**
* The response mapping template for this resolver
*
* @default - No mapping template
*/
readonly responseMappingTemplate?: MappingTemplate;
}
/**
* Resolvable Fields build upon Graphql Types and provide fields
* that can resolve into operations on a data source.
*/
export class ResolvableField extends Field implements IField {
/**
* The options to make this field resolvable
*
* @default - not a resolvable field
*/
public readonly fieldOptions?: ResolvableFieldOptions;
public constructor(options: ResolvableFieldOptions) {
const props = {
returnType: options.returnType,
args: options.args,
};
super(props);
this.fieldOptions = options;
}
} | the_stack |
import * as React from 'react'
import {withRouter} from 'react-router'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import {nextStep, selectExample} from '../../../actions/gettingStarted'
import {classnames} from '../../../utils/classnames'
import Loading from '../../Loading/Loading'
import {GettingStartedState} from '../../../types/gettingStarted'
import {Example} from '../../../types/types'
const classes: any = require('./PlaygroundCPopup.scss')
import {$p} from 'graphcool-styles'
import * as cx from 'classnames'
interface Tutorial {
title: string
description: string
image: string
link: string
}
const guides: Tutorial[] = [
{
title: 'Learnrelay.org',
description: 'A comprehensive, interactive introduction to Relay',
link: 'https://learnrelay.org/',
image: require('../../../assets/graphics/relay.png'),
},
{
title: 'GraphQL and the amazing Apollo Client',
description: 'Explore an Application built using React and Angular 2',
link: 'https://medium.com/google-developer-experts/graphql-and-the-amazing-apollo-client-fe57e162a70c',
image: require('../../../assets/graphics/apollo.png'),
},
{
title: 'Introducing Lokka',
description: 'A Simple JavaScript Client for GraphQL',
link: 'https://voice.kadira.io/introducing-lokka-a-simple-javascript-client-for-graphql-e0802695648c',
image: require('../../../assets/graphics/lokka.png'),
},
]
const examples = {
ReactRelay: {
path: 'react-relay-instagram-example',
description: 'React + Relay',
},
ReactApollo: {
path: 'react-apollo-instagram-example',
description: 'React + Apollo',
},
ReactNativeApollo: {
path: 'react-native-apollo-instagram-example',
description: 'React Native + Apollo',
},
AngularApollo: {
path: 'angular-apollo-instagram-example',
description: 'Angular + Apollo',
},
}
interface Props {
id: string
projectId: string
nextStep: () => Promise<void>
selectExample: (selectedExample: Example) => any
gettingStartedState: GettingStartedState
}
interface State {
mouseOver: boolean
}
class PlaygroundCPopup extends React.Component<Props, State> {
state = {
mouseOver: false,
}
refs: {
[key: string]: any
exampleAnchor: HTMLDivElement
congratsAnchor: HTMLDivElement
scroller: HTMLDivElement,
}
componentDidUpdate(prevProps: Props, prevState: State) {
if (prevProps.gettingStartedState.selectedExample !== this.props.gettingStartedState.selectedExample) {
this.refs.scroller.scrollTop += this.refs.exampleAnchor.getBoundingClientRect().top
}
if (prevProps.gettingStartedState.isCurrentStep('STEP5_WAITING')
&& this.props.gettingStartedState.isCurrentStep('STEP5_DONE')) {
this.refs.scroller.scrollTop += this.refs.congratsAnchor.getBoundingClientRect().top
const snd = new Audio(require('../../../assets/success.mp3') as string)
snd.volume = 0.5
snd.play()
}
}
render() {
const {mouseOver} = this.state
const {selectedExample} = this.props.gettingStartedState
const hovering = !this.props.gettingStartedState.isCurrentStep('STEP4_CLICK_TEASER_STEP5')
const downloadUrl = (example) => `${__BACKEND_ADDR__}/resources/getting-started-example?repository=${examples[example].path}&project_id=${this.props.projectId}&user=graphcool-examples` // tslint:disable-line
return (
<div
className='flex justify-center items-start w-100 h-100'
style={{
transition: 'background-color 0.3s ease',
backgroundColor: hovering ? 'rgba(255,255,255,0.7)' : 'transparent',
width: 'calc(100% - 266px)',
pointerEvents: 'none',
overflow: 'hidden',
}}
>
<div
ref='scroller'
className='flex justify-center w-100'
style={{
transition: 'height 0.5s ease',
height: hovering ? '100%' : mouseOver ? '190%' : '210%',
pointerEvents: hovering ? 'all' : 'none',
cursor: hovering ? 'auto' : 'pointer',
overflow: hovering ? 'auto' : 'hidden',
alignItems: selectedExample ? 'flex-start' : 'center',
}}
>
<div
className='bg-white br-2 shadow-2 mv-96'
style={{
minWidth: 600,
maxWidth: 800,
pointerEvents: 'all',
}}
onMouseLeave={() => this.setState({ mouseOver: false })}
onMouseEnter={() => {
this.setState({ mouseOver: true })
}}
onMouseOver={(e: any) => {
if (this.props.gettingStartedState.isCurrentStep('STEP4_CLICK_TEASER_STEP5')) {
this.props.nextStep()
}
}}
>
<div className='ma-16 tc pb-25'>
<div className='fw3 ma-38 f-38'>
You did it! Time to run an example.
</div>
<div className='fw2 f-16 mh-96 lh-1-4'>
You have successfully set up your own Instagram backend.{' '}
When building an app with Graphcool you can easily explore queries in the{' '}
playground and "copy & paste" selected queries into your code.{' '}
Of course, to do so, you need to implement the frontend first.
</div>
<div className='fw2 f-16 mh-96 lh-1-4 mt-16'>
<div>We put together a simple app to show and add posts</div>
<div>using the backend you just built, to test and run it locally.</div>
</div>
</div>
<div className='ma-16 tc pb-25'>
<div className='fw3 ma-38 f-25'>
Select your preferred technology to download the example.
</div>
<div className='flex justify-between items-center w-100' ref='exampleAnchor'>
<div
className={classnames(
classes.exampleButton,
selectedExample === 'ReactRelay' ? classes.active : '',
)}
onClick={() => this.props.selectExample('ReactRelay')}
>
React + Relay
</div>
<div
className={classnames(
classes.exampleButton,
selectedExample === 'ReactApollo' ? classes.active : '',
)}
onClick={() => this.props.selectExample('ReactApollo')}
>
React + Apollo
</div>
<div
className={classnames(
classes.exampleButton,
selectedExample === 'ReactNativeApollo' ? classes.active : '',
)}
onClick={() => this.props.selectExample('ReactNativeApollo')}
>
React Native + Apollo
</div>
<div
className={classnames(
classes.exampleButton,
selectedExample === 'AngularApollo' ? classes.active : '',
)}
onClick={() => this.props.selectExample('AngularApollo')}
>
Angular + Apollo
</div>
</div>
</div>
{selectedExample &&
<div>
<div className='w-100'>
<iframe
className='w-100'
height='480'
allowFullScreen
frameBorder='0'
src={`https://www.youtube.com/embed/${this.getExampleVideoUrl(selectedExample)}`}
/>
</div>
<div
className='w-100 pa-25'
style={{
backgroundColor: '#FEF5D2',
}}
>
<div className='mt-25 mb-38 w-100 flex justify-center'>
<a
href={downloadUrl(selectedExample)}
className='pa-16 white'
style={{
backgroundColor: '#4A90E2',
}}
>
Download example
</a>
</div>
<div className='code dark-gray'>
<div className='black-50'>
# To see the example in action, run the following commands:
</div>
<div className='mv-16'>
<div className='black'>
npm install
</div>
<div className='black'>
npm start
</div>
</div>
<div className='black-50'>
# You can now open the app on localhost:3000
</div>
<div className='black-50'>
# Please come back to this page once you're done. We're waiting here. 💤
</div>
<div className={cx($p.w100, $p.flex, $p.flexRow, $p.justifyCenter, $p.mt25)}>
<a href='#' onClick={
(e: any) => {
e.preventDefault()
// we need to skip the 'STEP5_WAITING' step
this.props.nextStep()
this.props.nextStep()
this.props.nextStep()
}
}>
Skip
</a>
</div>
</div>
{this.props.gettingStartedState.isCurrentStep('STEP5_WAITING') &&
<div className='w-100 mv-96 flex justify-center'>
<Loading />
</div>
}
</div>
</div>
}
{this.props.gettingStartedState.isCurrentStep('STEP5_DONE') &&
<div className='w-100 mb-96' ref='congratsAnchor'>
<div className='flex items-center flex-column pv-60 fw1'>
<div className='f-96'>
🎉
</div>
<div className='f-38 mt-38'>
Congratulations!
</div>
<div className='f-38 mt-16'>
We knew you had it in you.
</div>
<div className='f-16 mv-38'>
Now go out there and build amazing things!
</div>
</div>
<div className='flex justify-between ph-25 pv-16'>
<div className='w-50 pr-16'>
<div className='ttu ls-2 f-16 fw1 lh-1-4'>
Get started on your own<br />with those excellent tutorials
</div>
<div className='mv-38'>
{guides.map(guide => this.renderBox(guide))}
</div>
</div>
<div className='w-50 pl-16'>
<div className='ttu ls-2 f-16 fw1 lh-1-4'>
Get more out of Graphcool<br />with our guides
</div>
<div className={`h-100 justify-start flex flex-column mv-38 ${classes.guides}`}>
<a
href='https://graph.cool/docs/tutorials/quickstart-2-daisheeb9x'
className={`${classes.one} fw4 black db flex items-center mb-25`}
target='_blank'
>
Declaring Relations
</a>
<a
href='https://graph.cool/docs/tutorials/quickstart-3-saigai7cha'
className={`${classes.two} fw4 black db flex items-center mb-25`}
target='_blank'
>
Implementing Business Logic
</a>
<a
href='https://graph.cool/docs/tutorials/thinking-in-terms-of-graphs-ahsoow1ool'
target='_blank'
className={`${classes.three} fw4 black db flex items-center mb-25`}
>
Thinking in terms of graphs
</a>
</div>
</div>
</div>
<div className='flex w-100 justify-center'>
<div
className='f-25 mv-16 pv-16 ph-60 ls-1 ttu pointer bg-accent white dim'
onClick={this.props.nextStep}
>
Finish Onboarding
</div>
</div>
</div>
}
</div>
</div>
</div>
)
}
private renderBox = (tutorial: Tutorial) => {
return (
<div key={tutorial.title} className='pa-16 mb-16 lh-1-4' style={{background: 'rgba(0,0,0,0.03)'}}>
<a className='flex items-center' href={tutorial.link} target='_blank'>
<div className='flex items-center justify-center' style={{ flex: '0 0 60px', height: 60 }}>
<img src={tutorial.image}/>
</div>
<div className='flex flex-column space-between ml-38'>
<div className='mb-6 dark-gray f-16'>
{tutorial.title}
</div>
<div className='fw1 mid-gray'>
{tutorial.description}
</div>
</div>
</a>
</div>
)
}
private getExampleVideoUrl = (example: Example): string => {
switch (example) {
case 'ReactRelay': return '_dj9Os2ev4M'
case 'ReactApollo': return '9nlwyPUPXjQ'
case 'ReactNativeApollo': return '9nlwyPUPXjQ'
case 'AngularApollo': return 'EzD5fJ-uniI'
}
}
}
const mapStateToProps = (state) => {
return {
gettingStartedState: state.gettingStarted.gettingStartedState,
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({nextStep, selectExample}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(PlaygroundCPopup)) | the_stack |
import { SplitterBar } from "./SplitterBar.js";
import { Utils } from "./Utils.js";
import { IDockContainer } from "./interfaces/IDockContainer.js";
/**
* A splitter panel manages the child containers inside it with splitter bars.
* It can be stacked horizontally or vertically
*/
export class SplitterPanel {
panelElement: HTMLDivElement;
spiltterBars: SplitterBar[];
stackedVertical: boolean;
childContainers: IDockContainer[];
constructor(childContainers: IDockContainer[], stackedVertical: boolean) {
this.childContainers = childContainers;
this.stackedVertical = stackedVertical;
this.panelElement = document.createElement('div');
this.spiltterBars = [];
this._buildSplitterDOMAndAddElements();
}
_buildSplitterDOMAndAddElements() {
if (this.childContainers.length <= 1)
throw new Error('Splitter panel should contain atleast 2 panels');
this.spiltterBars = [];
let afterElement: HTMLElement = null;
for (let i = 0; i < this.childContainers.length - 1; i++) {
let previousContainer = this.childContainers[i];
let nextContainer = this.childContainers[i + 1];
let splitterBar = new SplitterBar(previousContainer, nextContainer, this.stackedVertical);
this.spiltterBars.push(splitterBar);
// Add the container and split bar to the panel's base div element
if (!Array.from(this.panelElement.children).includes(previousContainer.containerElement))
this._insertContainerIntoPanel(previousContainer, afterElement);
this.panelElement.insertBefore(splitterBar.barElement, previousContainer.containerElement.nextSibling);
afterElement = splitterBar.barElement;
}
let last = this.childContainers.slice(-1)[0];
if (!Array.from(this.panelElement.children).includes(last.containerElement))
this._insertContainerIntoPanel(last, afterElement);
}
performLayout(children: IDockContainer[], relayoutEvenIfEqual: boolean) {
let containersEqual = Utils.arrayEqual(this.childContainers, children);
if (!containersEqual || relayoutEvenIfEqual) {
this.childContainers.forEach((container) => {
if (!children.some((item) => item == container)) {
if (container.containerElement) {
container.containerElement.classList.remove('splitter-container-vertical');
container.containerElement.classList.remove('splitter-container-horizontal');
Utils.removeNode(container.containerElement);
}
}
});
this.spiltterBars.forEach((bar) => { Utils.removeNode(bar.barElement); });
// rebuild
this.childContainers = children;
this._buildSplitterDOMAndAddElements();
}
}
removeFromDOM() {
this.childContainers.forEach((container) => {
if (container.containerElement) {
container.containerElement.classList.remove('splitter-container-vertical');
container.containerElement.classList.remove('splitter-container-horizontal');
Utils.removeNode(container.containerElement);
}
});
this.spiltterBars.forEach((bar) => { Utils.removeNode(bar.barElement); });
}
destroy() {
this.removeFromDOM();
this.panelElement.parentNode.removeChild(this.panelElement);
}
_insertContainerIntoPanel(container: IDockContainer, afterElement: HTMLElement) {
if (!container) {
console.error('container is undefined');
return;
}
if (container.containerElement.parentNode != this.panelElement) {
Utils.removeNode(container.containerElement);
if (afterElement)
this.panelElement.insertBefore(container.containerElement, afterElement.nextSibling);
else {
if (this.panelElement.children.length > 0)
this.panelElement.insertBefore(container.containerElement, this.panelElement.children[0]);
else
this.panelElement.appendChild(container.containerElement);
}
}
container.containerElement.classList.add(
this.stackedVertical ? 'splitter-container-vertical' : 'splitter-container-horizontal'
);
}
/**
* Sets the percentage of space the specified [container] takes in the split panel
* The percentage is specified in [ratio] and is between 0..1
*/
setContainerRatio(container: IDockContainer, ratio: number) {
let splitPanelSize = this.stackedVertical ? this.panelElement.clientHeight : this.panelElement.clientWidth;
let newContainerSize = splitPanelSize * ratio;
let barSize = this.stackedVertical ? this.spiltterBars[0].barElement.clientHeight : this.spiltterBars[0].barElement.clientWidth;
let otherPanelSizeQuota = splitPanelSize - newContainerSize - barSize * this.spiltterBars.length;
let otherPanelScaleMultipler = otherPanelSizeQuota / splitPanelSize;
for (let i = 0; i < this.childContainers.length; i++) {
let child = this.childContainers[i];
let size;
if (child !== container) {
size = this.stackedVertical ? child.containerElement.parentElement.clientHeight : child.containerElement.parentElement.clientWidth;
size *= otherPanelScaleMultipler;
}
else
size = newContainerSize;
if (this.stackedVertical)
child.resize(child.width, Math.floor(size));
else
child.resize(Math.floor(size), child.height);
}
}
getRatios(): number[] {
let barSize = this.stackedVertical ? this.spiltterBars[0].barElement.clientHeight : this.spiltterBars[0].barElement.clientWidth;
let splitPanelSize = (this.stackedVertical ? this.panelElement.clientHeight : this.panelElement.clientWidth) - barSize * this.spiltterBars.length;
let result: number[] = [];
for (let i = 0; i < this.childContainers.length; i++) {
let child = this.childContainers[i];
let sizeOld = this.stackedVertical ? child.containerElement.clientHeight : child.containerElement.clientWidth;
result.push(sizeOld / splitPanelSize);
}
return result;
}
setRatios(ratios: number[]) {
let barSize = this.stackedVertical ? this.spiltterBars[0].barElement.clientHeight : this.spiltterBars[0].barElement.clientWidth;
let splitPanelSize = (this.stackedVertical ? this.panelElement.clientHeight : this.panelElement.clientWidth) - barSize * this.spiltterBars.length;
for (let i = 0; i < this.childContainers.length; i++) {
let child = this.childContainers[i];
let size = splitPanelSize * ratios[i];
if (this.stackedVertical)
child.resize(child.width, Math.floor(size));
else
child.resize(Math.floor(size), child.height);
}
}
resize(width: number, height: number) {
if (this.childContainers.length <= 1)
return;
let i;
// Adjust the fixed dimension that is common to all (i.e. width, if stacked vertical; height, if stacked horizontally)
for (i = 0; i < this.childContainers.length; i++) {
let childContainer = this.childContainers[i];
if (this.stackedVertical)
childContainer.resize(width, !childContainer.height ? height : childContainer.height);
else
childContainer.resize(!childContainer.width ? width : childContainer.width, height);
if (i < this.spiltterBars.length) {
let splitBar = this.spiltterBars[i];
if (this.stackedVertical)
splitBar.barElement.style.width = width + 'px';
else
splitBar.barElement.style.height = height + 'px';
}
}
// Adjust the varying dimension
let totalChildPanelSize = 0;
// Find out how much space existing child containers take up (excluding the splitter bars)
this.childContainers.forEach((container) => {
let size = this.stackedVertical ?
container.height :
container.width;
totalChildPanelSize += size;
});
const barRect = this.spiltterBars[0].barElement.getBoundingClientRect();
// Get the thickness of the bar
let barSize = this.stackedVertical ? barRect.height : barRect.width;
// Find out how much space existing child containers will take after being resized (excluding the splitter bars)
let targetTotalChildPanelSize = this.stackedVertical ? height : width;
targetTotalChildPanelSize -= barSize * this.spiltterBars.length;
// Get the scale multiplier
totalChildPanelSize = Math.max(totalChildPanelSize, 1);
let scaleMultiplier = targetTotalChildPanelSize / totalChildPanelSize;
// Update the size with this multiplier
let updatedTotalChildPanelSize = 0;
for (i = 0; i < this.childContainers.length; i++) {
let child = this.childContainers[i];
if (child.containerElement.style.display == 'none')
child.containerElement.style.display = 'block';
let original = this.stackedVertical ? child.containerElement.clientHeight : child.containerElement.clientWidth;
let newSize = scaleMultiplier > 1 ? Math.floor(original * scaleMultiplier) : Math.ceil(original * scaleMultiplier);
updatedTotalChildPanelSize += newSize;
// If this is the last node, add any extra pixels to fix the rounding off errors and match the requested size
if (i === this.childContainers.length - 1)
newSize += targetTotalChildPanelSize - updatedTotalChildPanelSize;
// Set the size of the panel
if (this.stackedVertical)
child.resize(child.width, newSize);
else
child.resize(newSize, child.height);
}
this.panelElement.style.width = width + 'px';
this.panelElement.style.height = height + 'px';
}
} | the_stack |
import { AssertionError, deepStrictEqual } from 'assert'
import { QuickInputButton } from '../../../shared/ui/buttons'
import { DataQuickPickItem, QuickPickPrompter } from '../../../shared/ui/pickerPrompter'
import { PromptResult } from '../../../shared/ui/prompter'
import { exposeEmitters } from '../vscode/testUtils'
type QuickPickTesterMethods<T> = {
/**
* Presses a button.
* Can either use the exact button object or pass in a string to search for a tooltip.
* The tooltip string must be an exact match.
*/
pressButton(button: string | QuickInputButton<T>): void
/**
* Attempts to accept the given item.
* If a string is given, then the item will be matched based off label. Otherwise a deep compare will be performed.
* Only exact matches will be accepted.
*/
acceptItem(item: string | DataQuickPickItem<T>): void
/**
* Asserts that the given items are loaded in the QuickPick, in the given order.
* Must include all visible items. Filtered items will not be considered.
*/
assertItems(items: string[] | DataQuickPickItem<T>[]): void
/**
* Asserts that the given items are loaded in the QuickPick, in the given order.
* This can be a subset of the currently visible items.
*/
assertContainsItems(...items: (string | DataQuickPickItem<T>)[]): void
/**
* Asserts that the items are currently selected. Not applicable to single-item pickers.
* Order does not matter, but it must be the same items. Filtering is not applied.
*/
assertSelectedItems(...items: (string | DataQuickPickItem<T>)[]): void
/**
* Asserts that the items are currently active.
* Order does not matter, but it must be the same items.
*/
assertActiveItems(...items: (string | DataQuickPickItem<T>)[]): void
/**
* Hides the picker.
*/
hide(): void
/**
* Runs the given inputs and waits for the result or timeout.
* Can optionally pass in an expected return value.
*
* This **must** be called and awaited, otherwise errors will not be surfaced correctly.
*/
result(exptected?: PromptResult<T>): Promise<PromptResult<T>>
/**
* Executes the callback with a snapshot of the prompter in a given moment.
*
* This can be used for things such as setting up external state, asserting side-effects, or
* inspecting the picker at test time.
*/
addCallback(callback: (prompter?: QuickPickPrompter<T>) => Promise<any> | any): void
/**
* Sets the Quick Pick's filter. `undefined` removes any applied filters.
*
* This will affect what items are considered 'visible' by the tester depending on which
* 'matchOn___' fields have been set in the picker.
*/
setFilter(value?: string): void
}
export type QuickPickTester<T> = QuickPickTesterMethods<T> & QuickPickPrompter<T>
type Action<T> = {
[P in keyof QuickPickTesterMethods<T>]: [P, Parameters<QuickPickTesterMethods<T>[P]>]
}[keyof QuickPickTesterMethods<T>]
interface TestOptions {
/** Amount of time to wait per action before stopping the test. */
timeout?: number
// TODO: add formatting options?
}
const TEST_DEFAULTS: Required<TestOptions> = {
timeout: 5000,
}
/**
* Creates a tester for quick picks.
*
* Tests are constructed as a series of 'actions' that are executed sequentially. Any action that
* fails will immediately stop the test. The first action will always occur after the prompter is
* both visible and enabled. Actions will always wait until the prompter is not busy/disabled before
* continuing.
*
* @param prompter Prompter to test.
* @param options Additional test options.
*
* @returns A {@link QuickPickTester}
*/
export function createQuickPickTester<T>(
prompter: QuickPickPrompter<T>,
options: TestOptions = {}
): QuickPickTester<T> {
const actions: Action<T>[] = []
const errors: Error[] = []
const traces: AssertionError[] = []
const testPicker = exposeEmitters(prompter.quickPick, ['onDidAccept', 'onDidTriggerButton'])
const resolvedOptions = { ...TEST_DEFAULTS, ...options }
/* Waits until the picker is both enabled and not busy. */
function whenReady(): Promise<void[]> {
return Promise.all([
new Promise(r => {
if (testPicker.enabled) {
return r()
}
const d = prompter.onDidChangeEnablement(e => e && d.dispose(), r())
}),
new Promise(r => {
if (!testPicker.busy) {
return r()
}
const d = prompter.onDidChangeBusy(e => !e && (d.dispose(), r()))
}),
])
}
// 'activeItems' will change twice after applying a filter
/* Waits until the filter has been applied to the picker */
async function whenAppliedFilter(): Promise<void> {
await new Promise<void>(r => {
const d = testPicker.onDidChangeActive(() => (d.dispose(), r()))
})
await new Promise(r => setImmediate(r))
await new Promise<void>(r => {
const d = testPicker.onDidChangeActive(() => (d.dispose(), r()))
})
}
/* Simulates the filtering of items. We do not have access to the picker's internal representation */
function filterItems(): DataQuickPickItem<T>[] {
const val = testPicker.value
const filter = (item: DataQuickPickItem<T>) => {
if (!item.label.match(val)) {
return (
(testPicker.matchOnDescription && (item.description ?? '').match(val)) ||
(testPicker.matchOnDetail && (item.detail ?? '').match(val))
)
}
return true
}
return testPicker.items.filter(filter)
}
/* Returns all items from source that are in target. Strings are matched based off label. Items are only matched once. */
function matchItems(
source: DataQuickPickItem<T>[],
target: (string | DataQuickPickItem<T>)[]
): DataQuickPickItem<T>[] {
return source.filter(item => {
const index = target.findIndex(t =>
typeof t === 'string' ? item.label === t : JSON.stringify(item) === JSON.stringify(t)
)
if (index !== -1) {
return (target = target.slice(0, index).concat(target.slice(index + 1)))
}
})
}
function throwErrorWithTrace(trace: AssertionError, message: string, actual?: any, expected?: any) {
errors.push(Object.assign(trace, { message, actual, expected }))
testPicker.hide()
}
/* Executes a test action. Immediately hides the picker on any error */
async function executeAction(action: Action<T>, trace: AssertionError): Promise<void> {
const throwError = throwErrorWithTrace.bind(undefined, trace)
function assertItems(actual: DataQuickPickItem<T>[], expected: (string | DataQuickPickItem<T>)[]): void {
if (actual.length !== expected.length) {
return throwError('Picker had different number of items')
}
actual.forEach((actualItem, index) => {
const expectedItem = expected[index]
const type = typeof expectedItem === 'string' ? 'label' : 'item'
if (
(type === 'label' && actualItem.label !== expectedItem) ||
(type === 'item' && JSON.stringify(actualItem) !== JSON.stringify(expectedItem))
) {
const actual = type === 'item' ? actualItem : actualItem.label
throwError(`Unexpected ${type} found at index ${index}`, actual, expectedItem)
}
})
}
switch (action[0]) {
case 'pressButton': {
const target =
typeof action[1][0] === 'string'
? testPicker.buttons.filter(b => b.tooltip === action[1][0])[0]
: action[1][0]
if (target === undefined) {
throwError(`Unable to find button: ${action[1][0]}`)
}
testPicker.fireOnDidTriggerButton(target)
break
}
case 'acceptItem': {
const filteredItems = filterItems()
const match = matchItems(filteredItems, [action[1][0]])
if (match.length === 0) {
throwError(`Unable to find item: ${JSON.stringify(action[1][0])}`) // TODO: add ways to format
}
testPicker.selectedItems = match
break
}
case 'assertItems': {
const filteredItems = filterItems()
assertItems(filteredItems, action[1][0])
break
}
case 'assertContainsItems': {
const filteredItems = filterItems()
const match = matchItems(filteredItems, action[1])
// Check length here first for better error output
if (match.length !== action[1].length) {
return throwError(`Did not find all items`, match, action[1])
}
assertItems(match, action[1])
break
}
case 'assertSelectedItems': {
// Filtered items can still be selected for multi-item pickers
const sortedSelected = [...testPicker.selectedItems].sort((a, b) => a.label.localeCompare(b.label))
const sortedExpected = [...action[1]].sort((a, b) => {
const labelA = typeof a === 'string' ? a : a.label
const labelB = typeof b === 'string' ? b : b.label
return labelA.localeCompare(labelB)
})
assertItems(sortedSelected, sortedExpected)
break
}
case 'assertActiveItems': {
const filteredActive = filterItems().filter(i => testPicker.activeItems.includes(i))
const sortedActive = [...filteredActive].sort((a, b) => a.label.localeCompare(b.label))
const sortedExpected = [...action[1]].sort((a, b) => {
const labelA = typeof a === 'string' ? a : a.label
const labelB = typeof b === 'string' ? b : b.label
return labelA.localeCompare(labelB)
})
assertItems(sortedActive, sortedExpected)
break
}
case 'addCallback': {
try {
await action[1][0](prompter)
} catch (err) {
throwError(`Callback threw: ${(err as Error).message}`)
}
break
}
case 'setFilter':
testPicker.value = action[1][0] ?? ''
await whenAppliedFilter()
break
case 'hide': {
testPicker.hide()
break
}
}
}
async function start(): Promise<void> {
while (actions.length > 0) {
const trace = traces.shift()!
const timeout = setTimeout(() => throwErrorWithTrace(trace, 'Timed out'), resolvedOptions.timeout)
await whenReady()
await executeAction(actions.shift()!, trace)
clearTimeout(timeout)
}
}
async function result(expected?: PromptResult<T>): Promise<PromptResult<T>> {
const result = await prompter.prompt()
if (errors.length > 0) {
// TODO: combine errors into a single one
throw errors[0]
}
if (arguments.length > 0) {
deepStrictEqual(result, expected)
}
return result
}
const withTrace = <T extends (...args: any[]) => any>(f: T, name: string) => {
const traceWrapper = (...args: any[]) => {
traces.push(new AssertionError({ stackStartFn: traceWrapper, operator: name, message: name }))
f(...args)
}
return Object.defineProperty(traceWrapper, 'name', { value: name, configurable: true, writable: false })
}
/**
* Remaps stack traces to point to the action that caused the test to fail.
*/
function wrapTraces<T extends { [key: string]: any }>(obj: T, exclude: (keyof T)[] = []): T {
Object.keys(obj).forEach(key => {
if (obj[key] instanceof Function && exclude.indexOf(key) === -1) {
Object.assign(obj, { [key]: withTrace(obj[key], key) })
}
})
return obj
}
// initialize prompter
prompter.onDidShow(start)
return Object.assign(
prompter,
wrapTraces(
{
pressButton: button => actions.push(['pressButton', [button]]),
acceptItem: item => actions.push(['acceptItem', [item]]),
assertItems: items => actions.push(['assertItems', [items]]),
assertContainsItems: (...items) => actions.push(['assertContainsItems', items]),
assertSelectedItems: (...items) => actions.push(['assertSelectedItems', items]),
assertActiveItems: (...items) => actions.push(['assertActiveItems', items]),
addCallback: callback => actions.push(['addCallback', [callback]]),
setFilter: value => actions.push(['setFilter', [value]]),
hide: () => actions.push(['hide', []]),
result,
} as QuickPickTesterMethods<T>,
['result', 'hide']
)
)
} | the_stack |
import { BasicAccessory, ServiceCreator, ServiceHandler } from './interfaces';
import {
exposesCanBeGet, exposesCanBeSet, ExposesEntry, ExposesEntryWithFeatures, ExposesEntryWithNumericRangeProperty, exposesHasFeatures,
exposesHasNumericRangeProperty, exposesIsPublished, ExposesKnownTypes,
} from '../z2mModels';
import { hap } from '../hap';
import { getOrAddCharacteristic } from '../helpers';
import { CharacteristicSetCallback, CharacteristicValue, Service } from 'homebridge';
import { ExtendedTimer } from '../timer';
import { CharacteristicMonitor, NumericCharacteristicMonitor } from './monitor';
export class CoverCreator implements ServiceCreator {
createServicesFromExposes(accessory: BasicAccessory, exposes: ExposesEntry[]): void {
exposes.filter(e => e.type === ExposesKnownTypes.COVER && exposesHasFeatures(e)
&& !accessory.isServiceHandlerIdKnown(CoverHandler.generateIdentifier(e.endpoint)))
.forEach(e => this.createService(e as ExposesEntryWithFeatures, accessory));
}
private createService(expose: ExposesEntryWithFeatures, accessory: BasicAccessory): void {
try {
const handler = new CoverHandler(expose, accessory);
accessory.registerServiceHandler(handler);
} catch (error) {
accessory.log.warn(`Failed to setup cover for accessory ${accessory.displayName} from expose "${JSON.stringify(expose)}": ${error}`);
}
}
}
class CoverHandler implements ServiceHandler {
private readonly positionExpose: ExposesEntryWithNumericRangeProperty;
private readonly tiltExpose: ExposesEntryWithNumericRangeProperty | undefined;
private readonly service: Service;
private readonly updateTimer: ExtendedTimer | undefined;
private readonly target_min: number;
private readonly target_max: number;
private readonly current_min: number;
private readonly current_max: number;
private readonly target_tilt_min: number;
private readonly target_tilt_max: number;
private monitors: CharacteristicMonitor[] = [];
private waitingForUpdate: boolean;
private ignoreNextUpdateIfEqualToTarget: boolean;
private lastPositionSet = -1;
private positionCurrent = -1;
constructor(expose: ExposesEntryWithFeatures, private readonly accessory: BasicAccessory) {
const endpoint = expose.endpoint;
this.identifier = CoverHandler.generateIdentifier(endpoint);
let positionExpose = expose.features.find(e => exposesHasNumericRangeProperty(e) && !accessory.isPropertyExcluded(e.property)
&& e.name === 'position' && exposesCanBeSet(e) && exposesIsPublished(e)) as ExposesEntryWithNumericRangeProperty;
this.tiltExpose = expose.features.find(e => exposesHasNumericRangeProperty(e) && !accessory.isPropertyExcluded(e.property)
&& e.name === 'tilt' && exposesCanBeSet(e) && exposesIsPublished(e)) as ExposesEntryWithNumericRangeProperty | undefined;
if (positionExpose === undefined) {
if (this.tiltExpose !== undefined) {
// Tilt only device
positionExpose = this.tiltExpose;
this.tiltExpose = undefined;
} else {
throw new Error('Required "position" property not found for WindowCovering and no "tilt" as backup.');
}
}
this.positionExpose = positionExpose;
const serviceName = accessory.getDefaultServiceDisplayName(endpoint);
accessory.log.debug(`Configuring WindowCovering for ${serviceName}`);
this.service = accessory.getOrAddService(new hap.Service.WindowCovering(serviceName, endpoint));
const current = getOrAddCharacteristic(this.service, hap.Characteristic.CurrentPosition);
if (current.props.minValue === undefined || current.props.maxValue === undefined) {
throw new Error('CurrentPosition for Cover does not hav a rang (minValue, maxValue) defined.');
}
this.current_min = current.props.minValue;
this.current_max = current.props.maxValue;
getOrAddCharacteristic(this.service, hap.Characteristic.PositionState);
const target = getOrAddCharacteristic(this.service, hap.Characteristic.TargetPosition);
if (target.props.minValue === undefined || target.props.maxValue === undefined) {
throw new Error('TargetPosition for Cover does not have a rang (minValue, maxValue) defined.');
}
this.target_min = target.props.minValue;
this.target_max = target.props.maxValue;
target.on('set', this.handleSetTargetPosition.bind(this));
if (this.target_min !== this.current_min || this.target_max !== this.current_max) {
this.accessory.log.error(accessory.displayName + ': cover: TargetPosition and CurrentPosition do not have the same range!');
}
// Tilt
if (this.tiltExpose !== undefined) {
getOrAddCharacteristic(this.service, hap.Characteristic.CurrentHorizontalTiltAngle);
this.monitors.push(new NumericCharacteristicMonitor(this.tiltExpose.property, this.service,
hap.Characteristic.CurrentHorizontalTiltAngle, this.tiltExpose.value_min, this.tiltExpose.value_max));
const target_tilt = getOrAddCharacteristic(this.service, hap.Characteristic.TargetHorizontalTiltAngle);
if (target_tilt.props.minValue === undefined || target_tilt.props.maxValue === undefined) {
throw new Error('TargetHorizontalTiltAngle for Cover does not have a rang (minValue, maxValue) defined.');
}
this.target_tilt_min = target_tilt.props.minValue;
this.target_tilt_max = target_tilt.props.maxValue;
target_tilt.on('set', this.handleSetTargetHorizontalTilt.bind(this));
} else {
this.target_tilt_min = -90;
this.target_tilt_max = 90;
}
if (exposesCanBeGet(this.positionExpose)) {
this.updateTimer = new ExtendedTimer(this.requestPositionUpdate.bind(this), 4000);
}
this.waitingForUpdate = false;
this.ignoreNextUpdateIfEqualToTarget = false;
}
identifier: string;
get getableKeys(): string[] {
const keys: string[] = [];
if (exposesCanBeGet(this.positionExpose)) {
keys.push(this.positionExpose.property);
}
if (this.tiltExpose !== undefined && exposesCanBeGet(this.tiltExpose)) {
keys.push(this.tiltExpose.property);
}
return keys;
}
updateState(state: Record<string, unknown>): void {
this.monitors.forEach(m => m.callback(state));
if (this.positionExpose.property in state) {
const latestPosition = state[this.positionExpose.property] as number;
// Received an update: Reset flag
this.waitingForUpdate = false;
// Ignore "first" update?
const doIgnoreIfEqual = this.ignoreNextUpdateIfEqualToTarget;
this.ignoreNextUpdateIfEqualToTarget = false;
if (latestPosition === this.lastPositionSet && doIgnoreIfEqual) {
this.accessory.log.debug(`${this.accessory.displayName}: cover: ignore position update (equal to last target)`);
return;
}
// If we cannot retrieve the position or we were not expecting an update,
// always assume the state is "stopped".
let didStop = true;
// As long as the update timer is running, we are expecting updates.
if (this.updateTimer !== undefined && this.updateTimer.isActive) {
if (latestPosition === this.positionCurrent) {
// Stop requesting frequent updates if no change is detected.
this.updateTimer.stop();
} else {
// Assume cover is still moving as the position is still changing
didStop = false;
this.startOrRestartUpdateTimer();
}
}
// Update current position
this.positionCurrent = latestPosition;
this.scaleAndUpdateCurrentPosition(this.positionCurrent, didStop);
}
}
private startOrRestartUpdateTimer(): void {
if (this.updateTimer === undefined) {
return;
}
this.waitingForUpdate = true;
if (this.updateTimer.isActive) {
this.updateTimer.restart();
} else {
this.updateTimer.start();
}
}
private requestPositionUpdate() {
if (!exposesCanBeGet(this.positionExpose)) {
return;
}
if (this.waitingForUpdate) {
// Manually polling for the state, as we have not yet received an update.
this.accessory.queueKeyForGetAction(this.positionExpose.property);
}
}
private scaleNumber(value: number, input_min: number, input_max: number, output_min: number, output_max: number): number {
if (value <= input_min) {
return output_min;
}
if (value >= input_max) {
return output_max;
}
const percentage = (value - input_min) / (input_max - input_min);
return output_min + (percentage * (output_max - output_min));
}
private scaleAndUpdateCurrentPosition(value: number, isStopped: boolean): void {
const characteristicValue = this.scaleNumber(value,
this.positionExpose.value_min, this.positionExpose.value_max,
this.current_min, this.current_max);
this.service.updateCharacteristic(hap.Characteristic.CurrentPosition, characteristicValue);
if (isStopped) {
// Update target position and position state
// This should improve the UX in the Home.app
this.accessory.log.debug(`${this.accessory.displayName}: cover: assume movement stopped`);
this.service.updateCharacteristic(hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED);
this.service.updateCharacteristic(hap.Characteristic.TargetPosition, characteristicValue);
}
}
private handleSetTargetPosition(value: CharacteristicValue, callback: CharacteristicSetCallback): void {
const target = this.scaleNumber(value as number,
this.target_min, this.target_max,
this.positionExpose.value_min, this.positionExpose.value_max);
const data = {};
data[this.positionExpose.property] = target;
this.accessory.queueDataForSetAction(data);
// Assume position state based on new target
if (target > this.positionCurrent) {
this.service.updateCharacteristic(hap.Characteristic.PositionState, hap.Characteristic.PositionState.INCREASING);
} else if (target < this.positionCurrent) {
this.service.updateCharacteristic(hap.Characteristic.PositionState, hap.Characteristic.PositionState.DECREASING);
} else {
this.service.updateCharacteristic(hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED);
}
// Store last sent position for future reference
this.lastPositionSet = target;
// Ignore next status update if it is equal to the target position set here
// and the position can be get.
// This was needed for my Swedish blinds when reporting was enabled.
// (First update would contain the target position that was sent, followed by the actual position.)
if (exposesCanBeGet(this.positionExpose)) {
this.ignoreNextUpdateIfEqualToTarget = true;
}
// Start requesting frequent updates (if we do not receive them automatically)
this.startOrRestartUpdateTimer();
callback(null);
}
private handleSetTargetHorizontalTilt(value: CharacteristicValue, callback: CharacteristicSetCallback): void {
if (this.tiltExpose) {
// map value: angle back to target: percentage
// must be rounded for set action
const targetTilt = Math.round(this.scaleNumber(value as number,
this.target_tilt_min, this.target_tilt_max,
this.tiltExpose.value_min, this.tiltExpose.value_max));
const data = {};
data[this.tiltExpose.property] = targetTilt;
this.accessory.queueDataForSetAction(data);
callback(null);
} else {
callback(new Error('tilt not supported'));
}
}
static generateIdentifier(endpoint: string | undefined) {
let identifier = hap.Service.WindowCovering.UUID;
if (endpoint !== undefined) {
identifier += '_' + endpoint.trim();
}
return identifier;
}
} | the_stack |
import { actionApi, fileApi } from "@/service/modules/upload";
export default class Utils {
constructor() {}
public wtmFormItem = this.generateWtmFormItemComponent;
public input = this.generateInputComponent;
public select = this.generateSelectComponent;
public button = this.generateButtonComponent;
public radio = this.generateRadioComponent;
public radioGroup = this.generateRadioGroupComponent;
public checkbox = this.generateCheckboxComponent;
public checkboxGroup = this.generateCheckboxGroupComponent;
public switch = this.generateSwitchComponent;
public upload = this.generateUploadComponent;
public wtmUploadImg = this.generateWtmUploadImgComponent;
public wtmSlot = this.generateWtmSlotComponent;
public label = this.generateLabelComponent;
public datePicker = this.generateDatePickerComponent;
public transfer = this.generateTransferComponent;
/**
* formItem 继承vue组件this
* @param h
* @param option
* @param component
* @param vm
*/
private generateWtmFormItemComponent(h, option, component, vm?) {
const _t = vm || this;
const isDetail = _t.status === _t.$actionType.detail;
const attrs = {
label: _t.getLanguageByKey(option) + (isDetail ? ":" : ""), // multi-language
rules: option.rules,
prop: option.key ? option.key : "",
error: option.error,
"label-width": option["label-width"] || option["labelWidth"],
span: option.span,
isShow: option.isShow,
value: option.value,
isImg: option.isImg,
};
// 展示状态 需要操作的组件
if (isDetail) {
const value = _.get(_t.sourceFormData || _t.formData, option.key);
delete attrs.rules;
// 图片
if (["wtmUploadImg", "upload"].includes(option.type) && value) {
const imgs = _.isArray(value) ? value : [value];
const imgComponents = imgs.map(item => {
const url = _.isString(item) && !option.mapKey ? item : item[option.mapKey];
return (
<el-image
style={option.props.imageStyle}
src={fileApi + url}
preview-src-list={[fileApi + url]}
fit={option.props.fit || "contain"}
></el-image>
)
})
if (imgComponents) {
return (
<wtm-form-item ref={option.key} {...{ attrs, props: attrs }}>
{imgComponents}
</wtm-form-item>
);
}
}
}
return (
<wtm-form-item ref={option.key} {...{ attrs, props: attrs }}>
{component}
</wtm-form-item>
);
}
private generateInputComponent(h, option, vm?) {
const _t = vm || this;
const { style, props, slot, key } = option;
const on = translateEvents(option.events, _t);
const compData = {
directives: [...(option.directives || []), vEdit(_t)],
on,
props: { ...displayProp(_t), ...props },
style,
slot,
};
let placeholder = `${_t.$t('form.pleaseEnter')}${option.label}`;
if (props && props.placeholder) {
placeholder = props.placeholder;
}
let vmodelData = sourceItem(_t.sourceFormData || _t.formData, key);
return (
<el-input
v-model={vmodelData[key]}
{...compData}
placeholder={placeholder}
>
{slot}
</el-input>
);
}
private generateSelectComponent(h, option, vm?) {
const _t = vm || this;
const { style, props, key, mapKey } = option;
let components = [];
if (option.children && _.isArray(option.children)) {
components = option.children.map((child) => {
const value = child.Value;
const label = child.Text || child.text;
let slot: any = undefined;
if (_.isString(child.slot)) {
slot = (
<wtm-render-view
hml={child.slot}
params={{ Value: value, Text: label }}
></wtm-render-view>
);
}
return (
<el-option
key={child.Value}
{...{ props: { value, label, ...child.props } }}
>
{slot}
</el-option>
);
});
}
const compData = {
directives: [...(option.directives || []), vEdit(_t, option.children)],
on: translateEvents(option.events, _t),
props: { ...displayProp(_t), ...props },
style,
};
// mapkey && 多选
if (mapKey && props.multiple) {
compData.on["input"] = function (val) {
setMapKeyModel(_t, key, val, mapKey);
};
const value = getMapKeyModel(_t, key, mapKey);
return (
<el-select value={value} {...compData}>
{components}
</el-select>
);
} else {
let vmodelData = sourceItem(_t.sourceFormData || _t.formData, key);
return (
<el-select v-model={vmodelData[key]} {...compData}>
{components}
</el-select>
);
}
}
private generateButtonComponent(h, option) {
const { style, props, slot, events: on, text } = option;
return <el-button {...{ style, props, slot, on }}>{text}</el-button>;
}
private generateRadioComponent(h, option, vm?) {
const _t = vm || this;
const { style, props, slot, key, text } = option;
const on = translateEvents(option.events, _t);
const compData = {
directives: [...(option.directives || []), vEdit(_t)],
on,
props: { ...displayProp(_t), ...props },
style,
slot,
};
let vmodelData = sourceItem(_t.sourceFormData || _t.formData, key);
return (
<el-radio v-model={vmodelData[key]} {...compData}>
{text}
</el-radio>
);
}
private generateRadioGroupComponent(h, option, vm?) {
const _t = vm || this;
const { style, props, slot, key } = option;
let components = [];
if (option.children) {
components = option.children.map((child) => {
const label = child.Value;
const text = child.Text || child.text;
return (
<el-radio {...{ props: { ...child.props, label } }}>{text}</el-radio>
);
});
}
const on = translateEvents(option.events, _t);
const compData = {
directives: [...(option.directives || []), vEdit(_t, option.children)],
on,
props: { ...displayProp(_t), ...props },
style,
slot,
};
let vmodelData = sourceItem(_t.sourceFormData || _t.formData, key);
return (
<el-radio-group v-model={vmodelData[key]} {...compData}>
{components}
</el-radio-group>
);
}
private generateCheckboxComponent(h, option, vm?) {
const _t = vm || this;
const { style, props, slot, key, text } = option;
const on = translateEvents(option.events, _t);
const compData = {
directives: [...(option.directives || []), vEdit(_t)],
on,
props: { ...displayProp(_t), ...props },
style,
slot,
};
let vmodelData = sourceItem(_t.sourceFormData || _t.formData, key);
return (
<el-checkbox v-model={vmodelData[key]} {...compData}>
{text}
</el-checkbox>
);
}
private generateCheckboxGroupComponent(h, option, vm?) {
const _t = vm || this;
const { style, props, slot, key, mapKey } = option;
let components = [];
if (option.children) {
components = option.children.map((child) => {
const label = child.Value;
const text = child.Text || child.text;
return (
<el-checkbox {...{ props: { ...child.props, label } }}>
{text}
</el-checkbox>
);
});
}
const on = translateEvents(option.events, _t);
const compData = {
directives: [...(option.directives || []), vEdit(_t)],
on,
props: { ...displayProp(_t), ...props },
style,
slot,
};
if (mapKey) {
compData.on["input"] = function (val) {
setMapKeyModel(_t, key, val, mapKey);
};
const value = getMapKeyModel(_t, key, mapKey);
return (
<el-checkbox-group value={value} {...compData}>
{components}
</el-checkbox-group>
);
} else {
let vmodelData = sourceItem(_t.sourceFormData || _t.formData, key);
return (
<el-checkbox-group v-model={vmodelData[key]} {...compData}>
{components}
</el-checkbox-group>
);
}
}
private generateSwitchComponent(h, option, vm?) {
const _t = vm || this;
const { style, props, slot, key, text } = option;
const on = translateEvents(option.events, _t);
const compData = {
directives: [...(option.directives || []), vEdit(_t)],
on,
props: { ...displayProp(_t), ...props },
style,
slot,
};
let vmodelData = sourceItem(_t.sourceFormData || _t.formData, key);
return (
<el-switch v-model={vmodelData[key]} {...compData}>
{text}
</el-switch>
);
}
private generateUploadComponent(h, option, vm?) {
const _t = vm || this;
const { style, props, slot, directives, key, events, label, mapKey } = option;
const compData = {
directives,
on: events || {},
props: { ...displayProp(_t), action: actionApi, disabled: _t.status === _t.$actionType.detail, limit: 1, ...props },
style,
};
// 上传钩子
if (!compData.props.onSuccess) {
compData.props.onSuccess = (res, file, fileList) => {
let fileIds = res.Id;
if (compData.props.limit > 1) {
fileIds = fileList.map(item => item.response ? item.response.Id : item.Id );
}
setMapKeyModel(_t, key, fileIds, mapKey);
// _.set(_t.sourceFormData || _t.formData, key, fileIds);
};
}
// 删除钩子
if (!compData.props.onRemove) {
compData.props.onRemove = (file, fileList) => {
let fileIds = "";
if(compData.props.limit > 1) {
fileIds = fileList.map(item => item.response ? item.response.Id : item.Id )
}
setMapKeyModel(_t, key, fileIds, mapKey);
// _.set(_t.sourceFormData || _t.formData, key, fileIds);
};
}
// 赋值
// const value:any = _.get(_t.sourceFormData || _t.formData, key);
const value = getMapKeyModel(_t, key, mapKey);
let dataFiles:any = [];
if (value) {
if(_.isArray(value)) {
dataFiles = value.map(item => {
return { name: label, url: fileApi + item, Id: item };
});
} else {
dataFiles = [{ name: label, url: fileApi + value, Id: value }];
}
}
compData.props["file-list"] = dataFiles;
const defaultSlot = <el-button type="primary">{_t.$t('form.clickUpload')}</el-button>;
if (slot) {
slot = slotRender(h, slot);
}
return <el-upload {...compData}>{slot || defaultSlot}</el-upload>;
}
private generateWtmUploadImgComponent(h, option, vm?) {
const _t = vm || this;
const { style, props, slot, directives, key } = option;
const on = translateEvents(option.events, _t);
on["onBackImgId"] = (event) => {
_.set(_t.sourceFormData || _t.formData, key, event);
};
const compData = {
directives,
on,
props: { ...displayProp(_t), ...props },
style,
slot,
};
const imgID = _.get(_t.sourceFormData || _t.formData, key);
return (
<wtm-upload-img imgId={imgID} {...compData}>
{option.children}
</wtm-upload-img>
);
}
/**
* 自定义位置
* @param h
* @param option
* @param vm
*/
private generateWtmSlotComponent(h, option, vm?) {
const _t = vm || this;
const { key } = option;
if (option.components) {
return option.components;
} else {
const data = {
data: _.get(_t.sourceFormData || _t.formData, key),
status: _t.status,
};
return _t.$scopedSlots[option.slotKey](data);
}
}
private generateLabelComponent(h, option, vm?) {
const _t = vm || this;
const { directives, style, key } = option;
const on = translateEvents(option.events, _t);
const compData = {
directives,
on,
style,
};
const value = _.get(_t.sourceFormData || _t.formData, key);
return <label {...compData}>{value}</label>;
}
private generateDatePickerComponent(h, option, vm?) {
const _t = vm || this;
const { directives, props, style, key } = option;
const on = translateEvents(option.events, _t);
const compData = {
directives: [...(directives || []), vEdit(_t)],
on,
props: { ...displayProp(_t), ...props },
style,
};
let vmodelData = sourceItem(_t.sourceFormData || _t.formData, key);
return (
<el-date-picker v-model={vmodelData[key]} {...compData}></el-date-picker>
);
}
private generateTransferComponent(h, option, vm?) {
const _t = vm || this;
const { directives, props, style, key, mapKey } = option;
const on = {
...translateEvents(option.events, _t),
input: function (val) {
setMapKeyModel(_t, key, val, mapKey);
},
};
// 结构 Text,Value
const editData = props.data.map((item) => ({
Text: item.label,
Value: item.key,
}));
const compData = {
directives: [...(directives || []), vEdit(_t, editData)],
on,
props: { ...displayProp(_t), ...props },
style,
};
const value = getMapKeyModel(_t, key, mapKey);
return <el-transfer value={value} {...compData}></el-transfer>;
}
}
/**
* 事件
* @param events
* @param vm
*/
export const translateEvents = (events = {}, vm) => {
const result = {};
for (let event in events) {
result[event] = events[event].bind(vm);
}
return result;
};
/**
* 编辑状态指令
* @param vm
* @param value 下拉框组件需要传入list
*/
export const vEdit = (vm, value: Array<any> | null = null) => {
if (!vm.elDisabled) {
return { name: "edit", arg: vm.status, value: value };
}
return {};
};
/**
* display Prop
* @param vm
* @param value 下拉框组件需要传入list
*/
export const displayProp = (vm) => {
if (vm.elDisabled) {
return { disabled: vm.status === vm.$actionType.detail };
}
return {};
};
/**
* 源数据 get,set
* 支持:'Entity.ID' => Entity: { ID }
* @param formData
* @param keyPath
*/
export const sourceItem = (formData, keyPath) => {
return {
set [keyPath](value) {
_.set(formData, keyPath, value);
},
get [keyPath]() {
return _.get(formData, keyPath);
},
};
};
/**
* 转 render
* @param hml
* @param params
*/
export const slotRender = (h, hml, params) => {
let slot: any = undefined;
if (_.isString(hml)) {
slot = (
<wtm-render-view
hml={hml}
params={{ ...params }}
></wtm-render-view>
);
}
return slot;
}
const setMapKeyModel = (_t, key, value, mapKey) => {
let val = value;
if (_.isArray(value) && mapKey) {
val = value.map(item => ({ [mapKey]: item }))
}
_.set(_t.sourceFormData || _t.formData, key, val);
}
const getMapKeyModel = (_t, key, mapKey) => {
const valueList = _.get(_t.sourceFormData || _t.formData, key) || [];
if (_.isArray(valueList)) {
const val = valueList.map(item => mapKey ? item[mapKey] : item);
return val;
} else {
return valueList;
}
} | the_stack |
import {DatePickerFieldState, DateSegment} from '@react-stately/datepicker';
import {DatePickerProps, DateValue} from '@react-types/datepicker';
import {DOMProps} from '@react-types/shared';
// @ts-ignore
import intlMessages from '../intl/*.json';
import {isIOS, mergeProps, useEvent, useId} from '@react-aria/utils';
import {labelIds} from './useDateField';
import {NumberParser} from '@internationalized/number';
import React, {HTMLAttributes, RefObject, useMemo, useRef} from 'react';
import {useDateFormatter, useFilter, useLocale, useMessageFormatter} from '@react-aria/i18n';
import {useFocusManager} from '@react-aria/focus';
import {usePress} from '@react-aria/interactions';
import {useSpinButton} from '@react-aria/spinbutton';
interface DateSegmentAria {
segmentProps: HTMLAttributes<HTMLDivElement>
}
export function useDateSegment<T extends DateValue>(props: DatePickerProps<T> & DOMProps, segment: DateSegment, state: DatePickerFieldState, ref: RefObject<HTMLElement>): DateSegmentAria {
let enteredKeys = useRef('');
let {locale, direction} = useLocale();
let messageFormatter = useMessageFormatter(intlMessages);
let focusManager = useFocusManager();
let textValue = segment.text;
let options = useMemo(() => state.dateFormatter.resolvedOptions(), [state.dateFormatter]);
let monthDateFormatter = useDateFormatter({month: 'long', timeZone: options.timeZone});
let hourDateFormatter = useDateFormatter({
hour: 'numeric',
hour12: options.hour12,
timeZone: options.timeZone
});
if (segment.type === 'month') {
let monthTextValue = monthDateFormatter.format(state.dateValue);
textValue = monthTextValue !== textValue ? `${textValue} - ${monthTextValue}` : monthTextValue;
} else if (segment.type === 'hour' || segment.type === 'dayPeriod') {
textValue = hourDateFormatter.format(state.dateValue);
}
let {spinButtonProps} = useSpinButton({
value: segment.value,
textValue,
minValue: segment.minValue,
maxValue: segment.maxValue,
isDisabled: props.isDisabled,
isReadOnly: props.isReadOnly,
isRequired: props.isRequired,
onIncrement: () => {
enteredKeys.current = '';
state.increment(segment.type);
},
onDecrement: () => {
enteredKeys.current = '';
state.decrement(segment.type);
},
onIncrementPage: () => {
enteredKeys.current = '';
state.incrementPage(segment.type);
},
onDecrementPage: () => {
enteredKeys.current = '';
state.decrementPage(segment.type);
},
onIncrementToMax: () => {
enteredKeys.current = '';
state.setSegment(segment.type, segment.maxValue);
},
onDecrementToMin: () => {
enteredKeys.current = '';
state.setSegment(segment.type, segment.minValue);
}
});
let parser = useMemo(() => new NumberParser(locale, {maximumFractionDigits: 0}), [locale]);
let onKeyDown = (e) => {
if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) {
return;
}
switch (e.key) {
case 'ArrowLeft':
e.preventDefault();
e.stopPropagation();
if (direction === 'rtl') {
focusManager.focusNext();
} else {
focusManager.focusPrevious();
}
break;
case 'ArrowRight':
e.preventDefault();
e.stopPropagation();
if (direction === 'rtl') {
focusManager.focusPrevious();
} else {
focusManager.focusNext();
}
break;
case 'Enter':
e.preventDefault();
e.stopPropagation();
if (segment.isPlaceholder && !props.isReadOnly) {
state.confirmPlaceholder(segment.type);
}
focusManager.focusNext();
break;
case 'Tab':
break;
case 'Backspace': {
// Safari on iOS does not fire beforeinput for the backspace key because the cursor is at the start.
e.preventDefault();
e.stopPropagation();
if (parser.isValidPartialNumber(segment.text) && !props.isReadOnly) {
let newValue = segment.text.slice(0, -1);
state.setSegment(segment.type, newValue.length === 0 ? segment.minValue : parser.parse(newValue));
enteredKeys.current = newValue;
}
break;
}
}
};
// Safari dayPeriod option doesn't work...
let {startsWith} = useFilter({sensitivity: 'base'});
let amPmFormatter = useDateFormatter({hour: 'numeric', hour12: true});
let am = useMemo(() => {
let date = new Date();
date.setHours(0);
return amPmFormatter.formatToParts(date).find(part => part.type === 'dayPeriod').value;
}, [amPmFormatter]);
let pm = useMemo(() => {
let date = new Date();
date.setHours(12);
return amPmFormatter.formatToParts(date).find(part => part.type === 'dayPeriod').value;
}, [amPmFormatter]);
let onInput = (key: string) => {
if (props.isDisabled || props.isReadOnly) {
return;
}
let newValue = enteredKeys.current + key;
switch (segment.type) {
case 'dayPeriod':
if (startsWith(am, key)) {
state.setSegment('dayPeriod', 0);
} else if (startsWith(pm, key)) {
state.setSegment('dayPeriod', 12);
} else {
break;
}
focusManager.focusNext();
break;
case 'day':
case 'hour':
case 'minute':
case 'second':
case 'month':
case 'year': {
if (!parser.isValidPartialNumber(newValue)) {
return;
}
let numberValue = parser.parse(newValue);
let segmentValue = numberValue;
if (segment.type === 'hour' && state.dateFormatter.resolvedOptions().hour12) {
switch (state.dateFormatter.resolvedOptions().hourCycle) {
case 'h11':
if (numberValue > 11) {
segmentValue = parser.parse(key);
}
break;
case 'h12':
if (numberValue === 0) {
return;
}
if (numberValue > 12) {
segmentValue = parser.parse(key);
}
break;
}
if (segment.value >= 12 && numberValue > 1) {
numberValue += 12;
}
} else if (numberValue > segment.maxValue) {
segmentValue = parser.parse(key);
}
if (isNaN(numberValue)) {
return;
}
state.setSegment(segment.type, segmentValue);
if (Number(numberValue + '0') > segment.maxValue) {
enteredKeys.current = '';
focusManager.focusNext();
} else {
enteredKeys.current = newValue;
}
break;
}
}
};
let onFocus = () => {
enteredKeys.current = '';
if (ref.current?.scrollIntoView) {
ref.current.scrollIntoView();
}
// Safari requires that a selection is set or it won't fire input events.
// Since usePress disables text selection, this won't happen by default.
ref.current.style.webkitUserSelect = 'text';
let selection = window.getSelection();
selection.collapse(ref.current);
ref.current.style.webkitUserSelect = '';
};
let compositionRef = useRef('');
// @ts-ignore - TODO: possibly old TS version? doesn't fail in my editor...
useEvent(ref, 'beforeinput', e => {
e.preventDefault();
switch (e.inputType) {
case 'deleteContentBackward':
case 'deleteContentForward':
if (parser.isValidPartialNumber(segment.text) && !props.isReadOnly) {
let newValue = segment.text.slice(0, -1);
state.setSegment(segment.type, newValue.length === 0 ? segment.minValue : parser.parse(newValue));
enteredKeys.current = newValue;
}
break;
case 'insertCompositionText':
// insertCompositionText cannot be canceled.
// Record the current state of the element so we can restore it in the `input` event below.
compositionRef.current = ref.current.textContent;
// Safari gets stuck in a composition state unless we also assign to the value here.
// eslint-disable-next-line no-self-assign
ref.current.textContent = ref.current.textContent;
break;
default:
if (e.data != null) {
onInput(e.data);
}
break;
}
});
useEvent(ref, 'input', (e: InputEvent) => {
let {inputType, data} = e;
switch (inputType) {
case 'insertCompositionText':
// Reset the DOM to how it was in the beforeinput event.
ref.current.textContent = compositionRef.current;
// Android sometimes fires key presses of letters as composition events. Need to handle am/pm keys here too.
// Can also happen e.g. with Pinyin keyboard on iOS.
if (startsWith(am, data) || startsWith(pm, data)) {
onInput(data);
}
break;
}
});
// Focus on mouse down/touch up to match native textfield behavior.
// usePress handles canceling text selection.
let {pressProps} = usePress({
preventFocusOnPress: true,
onPressStart: (e) => {
if (e.pointerType === 'mouse') {
e.target.focus();
}
},
onPress(e) {
if (e.pointerType !== 'mouse') {
e.target.focus();
}
}
});
// For Android: prevent selection on long press.
useEvent(ref, 'selectstart', e => {
e.preventDefault();
});
// spinbuttons cannot be focused with VoiceOver on iOS.
let touchPropOverrides = isIOS() ? {
role: 'textbox',
'aria-valuemax': null,
'aria-valuemin': null,
'aria-valuetext': null,
'aria-valuenow': null
} : {};
let fieldLabelId = labelIds.get(state);
let id = useId(props.id);
return {
segmentProps: mergeProps(spinButtonProps, pressProps, {
id,
...touchPropOverrides,
'aria-controls': props['aria-controls'],
// 'aria-haspopup': props['aria-haspopup'], // deprecated in ARIA 1.2
'aria-invalid': state.validationState === 'invalid' ? 'true' : undefined,
'aria-label': messageFormatter(segment.type),
'aria-labelledby': `${fieldLabelId} ${id}`,
contentEditable: !props.isDisabled,
suppressContentEditableWarning: !props.isDisabled,
spellCheck: 'false',
autoCapitalize: 'off',
autoCorrect: 'off',
// Capitalization was changed in React 17...
[parseInt(React.version, 10) >= 17 ? 'enterKeyHint' : 'enterkeyhint']: 'next',
inputMode: props.isDisabled || segment.type === 'dayPeriod' ? undefined : 'numeric',
tabIndex: props.isDisabled ? undefined : 0,
onKeyDown,
onFocus
})
};
} | the_stack |
///<reference path='ViewTestMediator.ts'/>
///<reference path='ViewTestMediator2.ts'/>
///<reference path='ViewTestMediator3.ts'/>
///<reference path='ViewTestMediator4.ts'/>
///<reference path='ViewTestMediator5.ts'/>
///<reference path='ViewTestMediator6.ts'/>
///<reference path='ViewTestNote.ts'/>
module test
{
"use strict";
/**
* Test the PureMVC View class.
*/
export class ViewTest
{
/**
* The name of the test case - if not provided, one is automatically generated by the
* YUITest framework.
*/
public name:string = "PureMVC View class tests";
/**
* Store the last notification name called.
*/
lastNotification:string = "";
/**
* Used by some commands to increment calls number.
*/
counter:number = 0;
/**
* Used by some commands to mark the onRegister method as called.
*/
onRegisterCalled:boolean = false;
/**
* Used by some commands to mark the onRemove method as called.
*/
onRemoveCalled:boolean = false;
/**
* A test variable that proves the viewTestMethod was invoked by the View.
*/
viewTestVar:number = 0;
/**
* Tests the View singleton Factory Method
*/
testGetInstance():void
{
// Test Factory Method
var view:puremvc.IView = puremvc.View.getInstance('ViewTestKey1');
// test assertions
YUITest.Assert.isNotNull
(
view,
"Expecting instance !== null"
);
YUITest.Assert.isInstanceOf
(
puremvc.View,
view,
"Expecting instance implements View"
);
puremvc.View.removeView('ViewTestKey1');
}
/**
* Tests registration and notification of Observers.
*
* An Observer is created to callback the viewTestMethod of
* this ViewTest instance. This Observer is registered with
* the View to be notified of 'ViewTestEvent' events. Such
* an event is created, and a value set on its payload. Then
* the View is told to notify interested observers of this
* Event.
*
* The View calls the Observer's notifyObserver method
* which calls the viewTestMethod on this instance
* of the ViewTest class. The viewTestMethod method will set
* an instance variable to the value passed in on the Event
* payload. We evaluate the instance variable to be sure
* it is the same as that passed out as the payload of the
* original 'ViewTestEvent'.
*
*/
testRegisterAndNotifyObserver():void
{
// Get the singleton View instance
var view:puremvc.IView = puremvc.View.getInstance('ViewTestKey2');
// Create observer, passing in notification method and context
var observer:puremvc.IObserver = new puremvc.Observer( this.viewTestMethod, this );
// Register Observer's interest in a particular Notification with the View
view.registerObserver(ViewTestNote.NAME, observer);
// Create a ViewTestNote, setting
// a body value, and tell the View to notify
// Observers. Since the Observer is this class
// and the notification method is viewTestMethod,
// successful notification will result in our local
// viewTestVar being set to the value we pass in
// on the notification body.
var notification:puremvc.INotification = ViewTestNote.create(10);
view.notifyObservers(notification);
// test assertions
YUITest.Assert.areEqual
(
10,
this.viewTestVar,
"Expecting viewTestVar = 10"
);
puremvc.View.removeView('ViewTestKey2');
}
/**
* A utility method to test the notification of Observers by the view.
*
* @param notification
* The notification to test.
*/
viewTestMethod( notification:puremvc.INotification )
{
// set the local viewTestVar to the number on the event payload
this.viewTestVar = notification.getBody();
}
/**
* Tests registering and retrieving a mediator with
* the View.
*/
testRegisterAndRetrieveMediator():void
{
// Get the singleton View instance
var view:puremvc.IView = puremvc.View.getInstance('ViewTestKey3');
// Create and register the test mediator
var viewTestMediator:puremvc.IMediator = new ViewTestMediator( this );
view.registerMediator( viewTestMediator );
// Retrieve the component
var mediator:puremvc.IMediator = view.retrieveMediator( ViewTestMediator.NAME );
// test assertions
YUITest.Assert.isInstanceOf
(
ViewTestMediator,
mediator,
"Expecting comp is ViewTestMediator"
);
puremvc.View.removeView('ViewTestKey3');
}
/**
* Tests the hasMediator Method
*/
testHasMediator():void
{
// register a Mediator
var view:puremvc.IView = puremvc.View.getInstance('ViewTestKey4');
// Create and register the test mediator
var mediator:puremvc.IMediator = new puremvc.Mediator( 'hasMediatorTest', this );
view.registerMediator( mediator );
// assert that the view.hasMediator method returns true
// for that mediator name
YUITest.Assert.isTrue
(
view.hasMediator('hasMediatorTest'),
"Expecting view.hasMediator('hasMediatorTest') === true"
);
view.removeMediator( 'hasMediatorTest' );
// assert that the view.hasMediator method returns false
// for that mediator name
YUITest.Assert.isFalse
(
view.hasMediator('hasMediatorTest'),
"Expecting view.hasMediator('hasMediatorTest') === false"
);
puremvc.View.removeView('ViewTestKey4');
}
/**
* Tests registering and removing a mediator
*/
testRegisterAndRemoveMediator():void
{
// Get the singleton View instance
var view:puremvc.IView = puremvc.View.getInstance('ViewTestKey5');
// Create and register the test mediator
var mediator:puremvc.IMediator = new puremvc.Mediator( 'testing', this );
view.registerMediator( mediator );
// Remove the component
var removedMediator:puremvc.IMediator = view.removeMediator( 'testing' );
// assert that we have removed the appropriate mediator
YUITest.Assert.areEqual
(
'testing',
removedMediator.getMediatorName(),
"Expecting removedMediator.getMediatorName() == 'testing'"
);
var retrievedMediator:puremvc.IMediator = view.retrieveMediator( 'testing' )
// assert that the mediator is no longer retrievable
YUITest.Assert.isNull
(
retrievedMediator,
"Expecting view.retrieveMediator( 'testing' ) === null )"
);
puremvc.View.removeView('ViewTestKey5');
}
/**
* Tests that the View callse the onRegister and onRemove methods
*/
testOnRegisterAndOnRemove():void
{
// Get the singleton View instance
var view:puremvc.IView = puremvc.View.getInstance('ViewTestKey6');
// Create and register the test mediator
var mediator:puremvc.IMediator = new ViewTestMediator4( this );
view.registerMediator( mediator );
// assert that onRegsiter was called, and the mediator responded by setting our boolean
YUITest.Assert.isTrue
(
this.onRegisterCalled,
"Expecting onRegisterCalled === true"
);
// Remove the component
view.removeMediator( ViewTestMediator4.NAME );
// assert that the mediator is no longer retrievable
YUITest.Assert.isTrue
(
this.onRemoveCalled,
"Expecting onRemoveCalled === true"
);
puremvc.View.removeView('ViewTestKey6');
}
/**
* Tests successive regster and remove of same mediator.
*/
testSuccessiveRegisterAndRemoveMediator():void
{
// Get the singleton View instance
var view:puremvc.IView = puremvc.View.getInstance('ViewTestKey7');
// Create and register the test mediator,
// but not so we have a reference to it
view.registerMediator( new ViewTestMediator( this ) );
// test that we can retrieve it
YUITest.Assert.isInstanceOf
(
ViewTestMediator,
view.retrieveMediator( ViewTestMediator.NAME ),
"Expecting view.retrieveMediator( ViewTestMediator.NAME ) isInstanceOf ViewTestMediator"
);
// Remove the Mediator
view.removeMediator( ViewTestMediator.NAME );
// test that retrieving it now returns null
YUITest.Assert.isNull
(
view.retrieveMediator( ViewTestMediator.NAME ),
"Expecting view.retrieveMediator( ViewTestMediator.NAME ) === null"
);
// test that removing the mediator again once its gone return null
YUITest.Assert.isNull
(
view.removeMediator( ViewTestMediator.NAME ),
"Expecting view.removeMediator( ViewTestMediator.NAME ) === null"
);
// Create and register another instance of the test mediator,
view.registerMediator( new ViewTestMediator( this ) );
YUITest.Assert.isInstanceOf
(
ViewTestMediator,
view.retrieveMediator( ViewTestMediator.NAME ),
"Expecting view.retrieveMediator( ViewTestMediator.NAME ) is ViewTestMediator"
);
// Remove the Mediator
view.removeMediator( ViewTestMediator.NAME );
// test that retrieving it now returns null
YUITest.Assert.isNull
(
view.retrieveMediator( ViewTestMediator.NAME ),
"Expecting view.retrieveMediator( ViewTestMediator.NAME ) === null"
);
puremvc.View.removeView('ViewTestKey7');
}
/**
* Tests registering a Mediator for 2 different notifications, removing the
* Mediator from the View, and seeing that neither notification causes the
* Mediator to be notified. Added for the fix deployed in version 1.7
*/
testRemoveMediatorAndSubsequentNotify():void
{
// Get the singleton View instance
var view:puremvc.IView = puremvc.View.getInstance('ViewTestKey8');
// Create and register the test mediator to be removed.
view.registerMediator( new ViewTestMediator2( this ) );
// test that notifications work
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE1) );
YUITest.Assert.areEqual
(
ViewTest.NOTE1,
this.lastNotification,
"Expecting lastNotification == NOTE1"
);
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE2) );
YUITest.Assert.areEqual
(
ViewTest.NOTE2,
this.lastNotification,
"Expecting lastNotification == NOTE2"
);
// Remove the Mediator
view.removeMediator( ViewTestMediator2.NAME );
// test that retrieving it now returns null
YUITest.Assert.isNull
(
view.retrieveMediator( ViewTestMediator2.NAME ),
"Expecting view.retrieveMediator( ViewTestMediator2.NAME ) === null"
);
// test that notifications no longer work
// (ViewTestMediator2 is the one that sets lastNotification
// on this component, and ViewTestMediator)
this.lastNotification = null;
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE1) );
YUITest.Assert.areNotEqual
(
ViewTest.NOTE1,
this.lastNotification,
"Expecting lastNotification != NOTE1"
);
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE2) );
YUITest.Assert.areNotEqual
(
ViewTest.NOTE2,
this.lastNotification,
"Expecting lastNotification != NOTE2"
);
puremvc.View.removeView('ViewTestKey8');
}
/**
* Tests registering one of two registered Mediators and seeing
* that the remaining one still responds.
* Added for the fix deployed in version 1.7.1
*/
testRemoveOneOfTwoMediatorsAndSubsequentNotify():void
{
// Get the singleton View instance
var view:puremvc.IView = puremvc.View.getInstance('ViewTestKey9');
// Create and register that responds to notifications 1 and 2
view.registerMediator( new ViewTestMediator2( this ) );
// Create and register that responds to notification 3
view.registerMediator( new ViewTestMediator3( this ) );
// test that all notifications work
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE1) );
YUITest.Assert.areEqual
(
ViewTest.NOTE1,
this.lastNotification,
"Expecting lastNotification == NOTE1"
);
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE2) );
YUITest.Assert.areEqual
(
ViewTest.NOTE2,
this.lastNotification,
"Expecting lastNotification == NOTE2"
);
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE3) );
YUITest.Assert.areEqual
(
ViewTest.NOTE3,
this.lastNotification,
"Expecting lastNotification == NOTE3"
);
// Remove the Mediator that responds to 1 and 2
view.removeMediator( ViewTestMediator2.NAME );
// test that retrieving it now returns null
YUITest.Assert.isNull
(
view.retrieveMediator( ViewTestMediator2.NAME ),
"Expecting view.retrieveMediator( ViewTestMediator2.NAME ) === null"
);
// test that notifications no longer work
// for notifications 1 and 2, but still work for 3
this.lastNotification = null;
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE1) );
YUITest.Assert.areNotEqual
(
ViewTest.NOTE1,
this.lastNotification,
"Expecting lastNotification != NOTE1"
);
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE2) );
YUITest.Assert.areNotEqual
(
ViewTest.NOTE2,
this.lastNotification,
"Expecting lastNotification != NOTE2"
);
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE3) );
YUITest.Assert.areEqual
(
ViewTest.NOTE3,
this.lastNotification,
"Expecting lastNotification == NOTE3"
);
puremvc.View.removeView('ViewTestKey9');
}
/**
* Tests registering the same mediator twice.
* A subsequent notification should only illicit
* one response. Also, since reregistration
* was causing 2 observers to be created, ensure
* that after removal of the mediator there will
* be no further response.
*
* Added for the fix deployed in version 2.0.4
*/
testMediatorReregistration():void
{
// Get the singleton View instance
var view:puremvc.IView = puremvc.View.getInstance('ViewTestKey10');
// Create and register that responds to notification 5
view.registerMediator( new ViewTestMediator5( this ) );
// try to register another instance of that mediator (uses the same NAME constant).
view.registerMediator( new ViewTestMediator5( this ) );
// test that the counter is only incremented once (mediator 5's response)
this.counter=0;
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE5) );
YUITest.Assert.areEqual
(
1,
this.counter,
"Expecting counter == 1"
);
// Remove the Mediator
view.removeMediator( ViewTestMediator5.NAME );
// test that retrieving it now returns null
YUITest.Assert.isNull
(
view.retrieveMediator( ViewTestMediator5.NAME ),
"Expecting view.retrieveMediator( ViewTestMediator5.NAME ) === null"
);
// test that the counter is no longer incremented
this.counter=0;
view.notifyObservers( new puremvc.Notification(ViewTest.NOTE5) );
YUITest.Assert.areEqual
(
0,
this.counter,
"Expecting counter == 0"
);
puremvc.View.removeView('ViewTestKey10');
}
/**
* Tests the ability for the observer list to
* be modified during the process of notification,
* and all observers be properly notified. This
* happens most often when multiple Mediators
* respond to the same notification by removing
* themselves.
*
* Added for the fix deployed in version 2.0.4
*/
testModifyObserverListDuringNotification():void
{
// Get the singleton View instance
var view:puremvc.IView = puremvc.View.getInstance('ViewTestKey11');
// Create and register several mediator instances that respond to notification 6
// by removing themselves, which will cause the observer list for that notification
// to change.
view.registerMediator( new ViewTestMediator6( ViewTestMediator6.NAME+"/1", this ) );
view.registerMediator( new ViewTestMediator6( ViewTestMediator6.NAME+"/2", this ) );
view.registerMediator( new ViewTestMediator6( ViewTestMediator6.NAME+"/3", this ) );
view.registerMediator( new ViewTestMediator6( ViewTestMediator6.NAME+"/4", this ) );
view.registerMediator( new ViewTestMediator6( ViewTestMediator6.NAME+"/5", this ) );
view.registerMediator( new ViewTestMediator6( ViewTestMediator6.NAME+"/6", this ) );
view.registerMediator( new ViewTestMediator6( ViewTestMediator6.NAME+"/7", this ) );
view.registerMediator( new ViewTestMediator6( ViewTestMediator6.NAME+"/8", this ) );
// clear the counter
this.counter=0;
// send the notification. each of the above mediators will respond by removing
// themselves and incrementing the counter by 1. This should leave us with a
// count of 8, since 8 mediators will respond.
view.notifyObservers( new puremvc.Notification( ViewTest.NOTE6 ) );
// verify the count is correct
YUITest.Assert.areEqual
(
8,
this.counter,
"Expecting counter == 8"
);
// clear the counter
this.counter=0;
view.notifyObservers( new puremvc.Notification( ViewTest.NOTE6 ) );
// verify the count is 0
YUITest.Assert.areEqual
(
0,
this.counter,
"Expecting counter == 0"
);
puremvc.View.removeView('ViewTestKey11');
}
/**
* @constant
*/
static NOTE1:string = "Notification1";
/**
* @constant
*/
static NOTE2:string = "Notification2";
/**
* @constant
*/
static NOTE3:string = "Notification3";
/**
* @constant
*/
static NOTE4:string = "Notification4";
/**
* @constant
*/
static NOTE5:string = "Notification5";
/**
* @constant
*/
static NOTE6:string = "Notification6";
}
} | the_stack |
import * as AlgebraicType from '../algebraic-type';
import * as AlgebraicTypeUtils from '../algebraic-type-utils';
import * as Code from '../code';
import * as Error from '../error';
import * as FileWriter from '../file-writer';
import * as FunctionUtils from '../function-utils';
import * as Maybe from '../maybe';
import * as ObjC from '../objc';
import * as ObjectGeneration from '../object-generation';
import * as ObjCTypeUtils from '../objc-type-utils';
import * as StringUtils from '../string-utils';
import * as ObjectSpec from '../object-spec';
import * as ObjectSpecCodeUtils from '../object-spec-code-utils';
import * as CodingUtils from './coding-utils';
function underscored(str: string): string {
return str
.replace(/([a-z\d])([A-Z]+)/g, '$1_$2')
.replace(/[-\s]+/g, '_')
.toLowerCase();
}
export interface CodeableAttribute {
name: string;
valueAccessor: string;
constantName: string;
constantValue: string;
legacyKeyNames: string[];
type: ObjC.Type;
originalType: ObjC.Type;
}
// We only support a single non-legacy coding key, but it's possible to write the annotation
// multiple times per-property. We catch this as a validation error, so that it won't affect
// code generation.
function codingKeysFromAnnotations(
annotationMap: ObjectGeneration.AnnotationMap,
): string[] {
const codingKeyAnnotations = annotationMap['codingKey'];
if (codingKeyAnnotations == null) {
return [];
}
return Maybe.catMaybes(
codingKeyAnnotations.map((annotation) => annotation.properties['name']),
);
}
function getKeyValue(
annotations: ObjectGeneration.AnnotationMap,
annotation: string,
key: string,
): string | null {
const jsonCodingAnnotation = annotations[annotation];
if (jsonCodingAnnotation) {
const propertiesDict = jsonCodingAnnotation[0];
if (propertiesDict) {
const property = propertiesDict['properties'];
if (property) {
const value = property[key];
if (value) {
return value;
}
}
}
}
return null;
}
function legacyCodingKeyNameForAnnotation(
legacyKeyAnnotation: ObjectGeneration.Annotation,
): string {
const legacyKey: string = legacyKeyAnnotation.properties['name'];
return legacyKey === undefined ? '' : legacyKey;
}
function legacyCodingKeyNamesForAttribute(
attribute: ObjectSpec.BaseAttribute,
): string[] {
const legacyKeyAnnotations = attribute.annotations['codingLegacyKey'];
if (legacyKeyAnnotations && legacyKeyAnnotations.length > 0) {
return legacyKeyAnnotations.map(legacyCodingKeyNameForAnnotation);
} else {
return [];
}
}
export function codingAttributeForValueAttribute(
attribute: ObjectSpec.BaseAttribute,
): CodeableAttribute {
const codingKeys = codingKeysFromAnnotations(attribute.annotations);
const constantValue =
codingKeys.length === 1
? `@"${codingKeys[0]}"`
: constantValueForAttributeName(attribute.name);
return {
name: attribute.name,
valueAccessor: ObjectSpecCodeUtils.ivarForAttribute(attribute),
constantName: nameOfConstantForValueName(attribute.name),
constantValue: constantValue,
legacyKeyNames: legacyCodingKeyNamesForAttribute(attribute),
type: ObjectSpecCodeUtils.computeTypeOfAttribute(attribute),
originalType: ObjectSpecCodeUtils.computeOriginalTypeOfAttribute(attribute),
};
}
function legacyKeyRespectingDecodeStatementForAttribute(
attribute: CodeableAttribute,
secureCoding: boolean,
): string[] {
const defaultDecodeStatement: string = decodeStatementForAttribute(
attribute,
secureCoding,
);
const decodeStatements: string[] = [defaultDecodeStatement];
if (attribute.legacyKeyNames.length > 0) {
const nilValueForAttribute: string = nilValueForType(attribute.type);
if (nilValueForAttribute.length > 0) {
const legacyDecodeStatements: string[] = FunctionUtils.flatMap(
attribute.legacyKeyNames,
(legacyKeyName) => {
return decodeStatementForAttributeAndLegacyKey(
attribute,
nilValueForAttribute,
legacyKeyName,
secureCoding,
);
},
);
if (legacyDecodeStatements.length > 0) {
return decodeStatements.concat(legacyDecodeStatements);
}
}
}
return decodeStatements;
}
function decodeStatementForAttributeAndLegacyKey(
attribute: CodeableAttribute,
nilValueForAttribute: string,
legacyKeyName: string,
secureCoding: boolean,
): string[] {
if (legacyKeyName.length > 0) {
const legacyDecodeStatement: string =
decodeStatementForTypeValueAccessorAndCodingKey(
attribute.type,
attribute.originalType,
attribute.valueAccessor,
'@"' + legacyKeyName + '"',
secureCoding,
);
const conditionalStatement: string[] = [
'if (' + attribute.valueAccessor + ' == ' + nilValueForAttribute + ') {',
StringUtils.indent(2)(legacyDecodeStatement),
'}',
];
return conditionalStatement;
} else {
return [];
}
}
export function decodeStatementForAttribute(
attribute: CodeableAttribute,
secureCoding: boolean,
): string {
return decodeStatementForTypeValueAccessorAndCodingKey(
attribute.type,
attribute.originalType,
attribute.valueAccessor,
attribute.constantName,
secureCoding,
);
}
function decodeStatementForTypeValueAccessorAndCodingKey(
type: ObjC.Type,
originalType: ObjC.Type,
valueAccessor: string,
codingKey: string,
secureCoding: boolean,
): string {
const codingStatements: CodingUtils.CodingStatements =
CodingUtils.codingStatementsForType(type);
// we cast over to the id type to silence -Wnullable-to-nonnull-conversion errors, otherwise the flag
// needs to be disabled for the entire target. This is better than using the valueObjectConfig, as it
// allows the flag to remain on for the rest of the generated code, in case there are bugs in any other
// plugins that lead to unsafe nullability issues.
const cast = ObjCTypeUtils.isNSObject(type)
? `(id)`
: type.name != originalType.name
? '(' + originalType.name + ')'
: '';
const decodedRawValuePart: string = `${cast}${codingStatements.decodeStatementGenerator(
type,
codingKey,
secureCoding,
)}`;
const decodedValuePart =
codingStatements.decodeValueStatementGenerator(decodedRawValuePart);
return valueAccessor + ' = ' + decodedValuePart + ';';
}
function decodeStatementForSubtype(
attribute: CodeableAttribute,
secureCoding: boolean,
): string {
const codingStatements: CodingUtils.CodingStatements =
CodingUtils.codingStatementsForType(attribute.type);
const decodedRawValuePart: string = codingStatements.decodeStatementGenerator(
attribute.type,
attribute.constantName,
secureCoding,
);
const decodedValuePart =
codingStatements.decodeValueStatementGenerator(decodedRawValuePart);
return (
'NSString *' + attribute.valueAccessor + ' = ' + decodedValuePart + ';'
);
}
export function encodeStatementForAttribute(
attribute: CodeableAttribute,
): string {
const codingStatements: CodingUtils.CodingStatements =
CodingUtils.codingStatementsForType(attribute.type);
const encodeValuePart = codingStatements.encodeValueStatementGenerator(
attribute.valueAccessor,
);
return (
'[aCoder ' +
codingStatements.encodeStatement +
':' +
encodeValuePart +
' forKey:' +
attribute.constantName +
'];'
);
}
function nameOfConstantForValueName(valueName: string): string {
return 'k' + StringUtils.capitalize(valueName) + 'Key';
}
function constantValueForAttributeName(attributeName: string): string {
return '@"' + underscored(attributeName).toUpperCase() + '"';
}
function staticConstantForAttribute(
attribute: CodeableAttribute,
): ObjC.Constant {
return {
type: {
name: 'NSString',
reference: 'NSString *',
},
comments: [],
name: attribute.constantName,
value: attribute.constantValue,
memorySemantic: ObjC.MemorySemantic.UnsafeUnretained(),
};
}
function initBlockWithInternalCode(internalCode: string[]): string[] {
const returnStatement: string = 'return self;';
return ['if ((self = [super init])) {']
.concat(internalCode.map(StringUtils.indent(2)))
.concat('}')
.concat(returnStatement);
}
function decodeMethodWithCode(code: string[]): ObjC.Method {
return {
preprocessors: [],
belongsToProtocol: 'NSCoding',
code: initBlockWithInternalCode(code),
comments: [],
compilerAttributes: [],
keywords: [
{
name: 'initWithCoder',
argument: {
name: 'aDecoder',
modifiers: [],
type: {
name: 'NSCoder',
reference: 'NSCoder *',
},
},
},
],
returnType: {
type: {
name: 'instancetype',
reference: 'instancetype',
},
modifiers: [ObjC.KeywordArgumentModifier.Nullable()],
},
};
}
function encodeMethodWithCode(code: string[]): ObjC.Method {
return {
preprocessors: [],
belongsToProtocol: 'NSCoding',
code: code,
comments: [],
compilerAttributes: [],
keywords: [
{
name: 'encodeWithCoder',
argument: {
name: 'aCoder',
modifiers: [],
type: {
name: 'NSCoder',
reference: 'NSCoder *',
},
},
},
],
returnType: {
type: null,
modifiers: [],
},
};
}
function isTypeNSCodingCompliant(type: ObjC.Type): boolean {
return ObjCTypeUtils.matchType(
{
id: function () {
return true;
},
NSObject: function () {
return true;
},
BOOL: function () {
return true;
},
NSInteger: function () {
return true;
},
NSUInteger: function () {
return true;
},
double: function () {
return true;
},
float: function () {
return true;
},
CGFloat: function () {
return true;
},
NSTimeInterval: function () {
return true;
},
uintptr_t: function () {
return true;
},
uint32_t: function () {
return true;
},
uint64_t: function () {
return true;
},
int32_t: function () {
return true;
},
int64_t: function () {
return true;
},
SEL: function () {
return true;
},
NSRange: function () {
return true;
},
CGRect: function () {
return true;
},
CGPoint: function () {
return true;
},
CGSize: function () {
return true;
},
UIEdgeInsets: function () {
return true;
},
Class: function () {
return false;
},
dispatch_block_t: function () {
return false;
},
unmatchedType: function () {
return true;
},
},
type,
);
}
function nilValueForType(type: ObjC.Type): string {
return ObjCTypeUtils.matchType(
{
id: function () {
return 'nil';
},
NSObject: function () {
return 'nil';
},
BOOL: function () {
return 'NO';
},
NSInteger: function () {
return '0';
},
NSUInteger: function () {
return '0';
},
double: function () {
return '0';
},
float: function () {
return '0';
},
CGFloat: function () {
return '0';
},
NSTimeInterval: function () {
return '0';
},
uintptr_t: function () {
return '0';
},
uint32_t: function () {
return '0';
},
uint64_t: function () {
return '0';
},
int32_t: function () {
return '0';
},
int64_t: function () {
return '0';
},
SEL: function () {
return '';
},
NSRange: function () {
return '';
},
CGRect: function () {
return '';
},
CGPoint: function () {
return '';
},
CGSize: function () {
return '';
},
UIEdgeInsets: function () {
return '';
},
Class: function () {
return 'nil';
},
dispatch_block_t: function () {
return '';
},
unmatchedType: function () {
return '';
},
},
type,
);
}
function doesValueAttributeContainAnUnknownType(
attribute: ObjectSpec.Attribute,
): boolean {
const codeableAttribute: CodeableAttribute =
codingAttributeForValueAttribute(attribute);
const codingStatements: CodingUtils.CodingStatements =
CodingUtils.codingStatementsForType(codeableAttribute.type);
return codingStatements == null;
}
function doesValueAttributeContainAnUnsupportedType(
attribute: ObjectSpec.Attribute,
): boolean {
return (
isTypeNSCodingCompliant(
ObjectSpecCodeUtils.computeTypeOfAttribute(attribute),
) === false
);
}
function doesValueAttributeContainAnLegacyKeyForUnsupportedType(
attribute: ObjectSpec.Attribute,
): boolean {
return (
legacyCodingKeyNamesForAttribute(attribute).length > 0 &&
nilValueForType(ObjectSpecCodeUtils.computeTypeOfAttribute(attribute))
.length == 0
);
}
function valueAttributeToUnknownTypeError(
objectType: ObjectSpec.Type,
attribute: ObjectSpec.Attribute,
): Error.Error {
return Maybe.match(
function (underlyingType: string): Error.Error {
return Error.Error(
'The Coding plugin does not know how to decode and encode the backing type "' +
underlyingType +
'" from ' +
objectType.typeName +
'.' +
attribute.name +
'. Did you declare the wrong backing type?',
);
},
function (): Error.Error {
return Error.Error(
'The Coding plugin does not know how to decode and encode the type "' +
attribute.type.name +
'" from ' +
objectType.typeName +
'.' +
attribute.name +
'. Did you forget to declare a backing type?',
);
},
attribute.type.underlyingType,
);
}
function valueAttributeToUnsupportedTypeError(
objectType: ObjectSpec.Type,
attribute: ObjectSpec.Attribute,
): Error.Error {
return Maybe.match(
function (underlyingType: string): Error.Error {
return Error.Error(
'The Coding plugin does not know how to decode and encode the backing type "' +
underlyingType +
'" from ' +
objectType.typeName +
'.' +
attribute.name +
'. ' +
attribute.type.name +
' is not NSCoding-compilant.',
);
},
function (): Error.Error {
return Error.Error(
'The Coding plugin does not know how to decode and encode the type "' +
attribute.type.name +
'" from ' +
objectType.typeName +
'.' +
attribute.name +
'. ' +
attribute.type.name +
' is not NSCoding-compilant.',
);
},
attribute.type.underlyingType,
);
}
function valueAttributeToUnsupportedLegacyKeyTypeError(
objectType: ObjectSpec.Type,
attribute: ObjectSpec.Attribute,
): Error.Error {
return Maybe.match(
function (underlyingType: string): Error.Error {
return Error.Error(
'%codingLegacyKey can\'t be used with "' +
underlyingType +
'" at ' +
objectType.typeName +
'.' +
attribute.name +
'.',
);
},
function (): Error.Error {
return Error.Error(
'%codingLegacyKey can\'t be used with "' +
attribute.type.name +
'" at ' +
objectType.typeName +
'.' +
attribute.name +
'.',
);
},
attribute.type.underlyingType,
);
}
function multipleCodingKeyAnnotationErrorForValueAttribute(
objectType: ObjectSpec.Type,
attribute: ObjectSpec.Attribute,
): Error.Error | null {
const length = codingKeysFromAnnotations(attribute.annotations).length;
return length > 1
? Error.Error(
`Only one %codingKey name is supported: ${objectType.typeName}.${attribute.name} has ${length}.`,
)
: null;
}
function importForAttributeCodingMethod(
attribute: ObjectSpec.Attribute,
): ObjC.Import | null {
const codeableAttribute: CodeableAttribute =
codingAttributeForValueAttribute(attribute);
const codingStatements: CodingUtils.CodingStatements =
CodingUtils.codingStatementsForType(codeableAttribute.type);
return codingStatements.codingFunctionImport;
}
export function createPlugin(): ObjectSpec.Plugin {
return {
additionalFiles: function (objectType: ObjectSpec.Type): Code.File[] {
return [];
},
transformBaseFile: function (
objectType: ObjectSpec.Type,
baseFile: Code.File,
): Code.File {
return baseFile;
},
additionalTypes: function (objectType: ObjectSpec.Type): ObjectSpec.Type[] {
return [];
},
classMethods: function (objectType: ObjectSpec.Type): ObjC.Method[] {
const secureCoding = objectType.includes.indexOf('NSSecureCoding') >= 0;
return secureCoding ? [CodingUtils.supportsSecureCodingMethod] : [];
},
attributes: function (objectType: ObjectSpec.Type): ObjectSpec.Attribute[] {
return [];
},
transformFileRequest: function (
request: FileWriter.Request,
): FileWriter.Request {
return request;
},
fileType: function (objectType: ObjectSpec.Type): Code.FileType | null {
return null;
},
forwardDeclarations: function (
objectType: ObjectSpec.Type,
): ObjC.ForwardDeclaration[] {
return [];
},
functions: function (objectType: ObjectSpec.Type): ObjC.Function[] {
return [];
},
headerComments: function (objectType: ObjectSpec.Type): ObjC.Comment[] {
return [];
},
implementedProtocols: function (
objectType: ObjectSpec.Type,
): ObjC.ImplementedProtocol[] {
const secureCoding = objectType.includes.indexOf('NSSecureCoding') >= 0;
if (secureCoding) {
return [
{
name: 'NSSecureCoding',
},
];
} else {
return [
{
name: 'NSCoding',
},
];
}
},
imports: function (objectType: ObjectSpec.Type): ObjC.Import[] {
const codingImportMaybes = objectType.attributes.map(
importForAttributeCodingMethod,
);
return Maybe.catMaybes(codingImportMaybes);
},
instanceMethods: function (objectType: ObjectSpec.Type): ObjC.Method[] {
const secureCoding = objectType.includes.indexOf('NSSecureCoding') >= 0;
if (objectType.attributes.length > 0) {
const codingAttributes: CodeableAttribute[] = objectType.attributes.map(
codingAttributeForValueAttribute,
);
const decodeCode: string[] = FunctionUtils.flatMap(
codingAttributes,
(codingAttribute) => {
return legacyKeyRespectingDecodeStatementForAttribute(
codingAttribute,
secureCoding,
);
},
);
const encodeCode: string[] = codingAttributes.map(
encodeStatementForAttribute,
);
return [
decodeMethodWithCode(decodeCode),
encodeMethodWithCode(encodeCode),
];
} else {
return [];
}
},
macros: function (valueType: ObjectSpec.Type): ObjC.Macro[] {
return [];
},
properties: function (objectType: ObjectSpec.Type): ObjC.Property[] {
return [];
},
requiredIncludesToRun: ['RMCoding'],
staticConstants: function (objectType: ObjectSpec.Type): ObjC.Constant[] {
return objectType.attributes
.map(codingAttributeForValueAttribute)
.map(staticConstantForAttribute);
},
validationErrors: function (objectType: ObjectSpec.Type): Error.Error[] {
const unknownTypeErrors = objectType.attributes
.filter(doesValueAttributeContainAnUnknownType)
.map((attribute) =>
valueAttributeToUnknownTypeError(objectType, attribute),
);
const unsupportedTypeErrors = objectType.attributes
.filter(doesValueAttributeContainAnUnsupportedType)
.map((attribute) =>
valueAttributeToUnsupportedTypeError(objectType, attribute),
);
const unsupportedLegacyKeyTypeErrors = objectType.attributes
.filter(doesValueAttributeContainAnLegacyKeyForUnsupportedType)
.map((attribute) =>
valueAttributeToUnsupportedLegacyKeyTypeError(objectType, attribute),
);
const multipleCodingKeyErrors = Maybe.catMaybes(
objectType.attributes.map((attribute) =>
multipleCodingKeyAnnotationErrorForValueAttribute(
objectType,
attribute,
),
),
);
return unknownTypeErrors.concat(
unsupportedTypeErrors,
unsupportedLegacyKeyTypeErrors,
multipleCodingKeyErrors,
);
},
nullability: function (
objectType: ObjectSpec.Type,
): ObjC.ClassNullability | null {
return null;
},
subclassingRestricted: function (objectType: ObjectSpec.Type): boolean {
return false;
},
};
}
function codeableAttributeForSubtypePropertyOfAlgebraicType(): CodeableAttribute {
return {
name: 'codedSubtype',
valueAccessor: 'codedSubtype',
constantName: nameOfConstantForValueName('codedSubtype'),
constantValue: constantValueForAttributeName('codedSubtype'),
legacyKeyNames: [],
type: {
name: 'NSObject',
reference: 'NSObject',
},
originalType: {
name: 'NSObject',
reference: 'NSObject',
},
};
}
function codeableAttributeForAlgebraicSubtypeAttribute(
subtype: AlgebraicType.Subtype,
attribute: AlgebraicType.SubtypeAttribute,
): CodeableAttribute {
const valueName: string = subtype.match(
function (
namedAttributeCollectionSubtype: AlgebraicType.NamedAttributeCollectionSubtype,
) {
return (
StringUtils.capitalize(namedAttributeCollectionSubtype.name) +
StringUtils.capitalize(attribute.name)
);
},
function (attribute: AlgebraicType.SubtypeAttribute) {
return StringUtils.capitalize(attribute.name);
},
);
const name = AlgebraicTypeUtils.nameOfInstanceVariableForAttribute(
subtype,
attribute,
);
return {
name: name,
valueAccessor:
AlgebraicTypeUtils.valueAccessorForInstanceVariableForAttribute(
subtype,
attribute,
),
constantName: nameOfConstantForValueName(valueName),
constantValue: constantValueForAttributeName(name),
legacyKeyNames: legacyCodingKeyNamesForAttribute(attribute),
type: AlgebraicTypeUtils.computeTypeOfAttribute(attribute),
originalType: AlgebraicTypeUtils.computeOriginalTypeOfAttribute(attribute),
};
}
function decodeStatementForAlgebraicSubtypeAttribute(
subtype: AlgebraicType.Subtype,
attribute: AlgebraicType.SubtypeAttribute,
secureCoding: boolean,
): string {
const codeableAttribute: CodeableAttribute =
codeableAttributeForAlgebraicSubtypeAttribute(subtype, attribute);
return decodeStatementForAttribute(codeableAttribute, secureCoding);
}
function decodeStatementsForAlgebraicSubtype(
algebraicType: AlgebraicType.Type,
subtype: AlgebraicType.Subtype,
secureCoding: boolean,
): string[] {
const decodeAttributes: string[] = AlgebraicTypeUtils.attributesFromSubtype(
subtype,
).map((attribute) => {
return decodeStatementForAlgebraicSubtypeAttribute(
subtype,
attribute,
secureCoding,
);
});
return decodeAttributes.concat(
decodedStatementForSubtypeProperty(algebraicType, subtype),
);
}
function decodedStatementForSubtypeProperty(
algebraicType: AlgebraicType.Type,
subtype: AlgebraicType.Subtype,
): string {
return (
AlgebraicTypeUtils.valueAccessorForInstanceVariableStoringSubtype() +
' = ' +
AlgebraicTypeUtils.EnumerationValueNameForSubtype(algebraicType, subtype) +
';'
);
}
function decodeCodeForAlgebraicType(
algebraicType: AlgebraicType.Type,
secureCoding: boolean,
fallbackDecodingFunction: string | null,
): string[] {
const codeableAttributeForSubtypeProperty: CodeableAttribute =
codeableAttributeForSubtypePropertyOfAlgebraicType();
const switchStatement: string[] = codeForBranchingOnSubtypeWithSubtypeMapper(
algebraicType,
codeableAttributeForSubtypeProperty.valueAccessor,
(algebraicType, subtype) =>
decodeStatementsForAlgebraicSubtype(algebraicType, subtype, secureCoding),
fallbackDecodingFunction,
);
return [
decodeStatementForSubtype(
codeableAttributeForSubtypeProperty,
secureCoding,
),
].concat(switchStatement);
}
function encodeStatementForAlgebraicSubtypeAttribute(
subtype: AlgebraicType.Subtype,
attribute: AlgebraicType.SubtypeAttribute,
): string {
const codeableAttribute: CodeableAttribute =
codeableAttributeForAlgebraicSubtypeAttribute(subtype, attribute);
return encodeStatementForAttribute(codeableAttribute);
}
function encodedStatementForSubtypeProperty(
subtype: AlgebraicType.Subtype,
): string {
const subtypeAttribute: CodeableAttribute =
codeableAttributeForSubtypePropertyOfAlgebraicType();
const codingStatements: CodingUtils.CodingStatements =
CodingUtils.codingStatementsForType(subtypeAttribute.type);
return (
'[aCoder ' +
codingStatements.encodeStatement +
':' +
CodingNameForSubtype(subtype) +
' forKey:' +
subtypeAttribute.constantName +
'];'
);
}
function encodeStatementsForAlgebraicSubtype(
algebraicType: AlgebraicType.Type,
subtype: AlgebraicType.Subtype,
): string[] {
const encodeAttributes: string[] = AlgebraicTypeUtils.attributesFromSubtype(
subtype,
).map((attribute) =>
encodeStatementForAlgebraicSubtypeAttribute(subtype, attribute),
);
return encodeAttributes.concat(encodedStatementForSubtypeProperty(subtype));
}
function encodeCodeForAlgebraicType(
algebraicType: AlgebraicType.Type,
): string[] {
return AlgebraicTypeUtils.codeForSwitchingOnSubtypeWithSubtypeMapper(
algebraicType,
AlgebraicTypeUtils.valueAccessorForInstanceVariableStoringSubtype(),
encodeStatementsForAlgebraicSubtype,
);
}
function doesAlgebraicAttributeContainAnUnknownType(
attribute: AlgebraicType.SubtypeAttribute,
): boolean {
const codingStatements: CodingUtils.CodingStatements =
CodingUtils.codingStatementsForType(
AlgebraicTypeUtils.computeTypeOfAttribute(attribute),
);
return codingStatements == null;
}
function doesAlgebraicAttributeContainAnUnsupportedType(
attribute: AlgebraicType.SubtypeAttribute,
): boolean {
return (
isTypeNSCodingCompliant(
AlgebraicTypeUtils.computeTypeOfAttribute(attribute),
) === false
);
}
function algebraicAttributeToUnknownTypeError(
algebraicType: AlgebraicType.Type,
attribute: AlgebraicType.SubtypeAttribute,
): Error.Error {
return Maybe.match(
function (underlyingType: string): Error.Error {
return Error.Error(
'The Coding plugin does not know how to decode and encode the backing type "' +
underlyingType +
'" from ' +
algebraicType.name +
'.' +
attribute.name +
'. Did you declare the wrong backing type?',
);
},
function (): Error.Error {
return Error.Error(
'The Coding plugin does not know how to decode and encode the type "' +
attribute.type.name +
'" from ' +
algebraicType.name +
'.' +
attribute.name +
'. Did you forget to declare a backing type?',
);
},
attribute.type.underlyingType,
);
}
function algebraicAttributeToUnsupportedTypeError(
algebraicType: AlgebraicType.Type,
attribute: AlgebraicType.SubtypeAttribute,
): Error.Error {
return Maybe.match(
function (underlyingType: string): Error.Error {
return Error.Error(
'The Coding plugin does not know how to decode and encode the backing type "' +
underlyingType +
'" from ' +
algebraicType.name +
'.' +
attribute.name +
'. ' +
attribute.type.name +
' is not NSCoding-compilant.',
);
},
function (): Error.Error {
return Error.Error(
'The Coding plugin does not know how to decode and encode the type "' +
attribute.type.name +
'" from ' +
algebraicType.name +
'.' +
attribute.name +
'. ' +
attribute.type.name +
' is not NSCoding-compilant.',
);
},
attribute.type.underlyingType,
);
}
function unsupportedAnnotationErrorForAlgebraicAttribute(
attribute: AlgebraicType.SubtypeAttribute,
): Error.Error | null {
return codingKeysFromAnnotations(attribute.annotations).length != 0
? Error.Error(
'Custom coding keys are not supported for algebraic type attributes',
)
: null;
}
export function CodingNameForSubtype(subtype: AlgebraicType.Subtype): string {
return constantValueForAttributeName(
'SUBTYPE_' + AlgebraicTypeUtils.subtypeNameFromSubtype(subtype),
);
}
function codeForSubtypeBranchesWithSubtypeMapper(
algebraicType: AlgebraicType.Type,
subtypeValueAccessor: string,
subtypeMapper: (
algebraicType: AlgebraicType.Type,
subtype: AlgebraicType.Subtype,
) => string[],
soFar: string[],
subtype: AlgebraicType.Subtype,
): string[] {
const internalCode: string[] = subtypeMapper(algebraicType, subtype);
const code: string[] = [
(soFar.length ? 'else if([' : 'if([') +
subtypeValueAccessor +
' isEqualToString:' +
CodingNameForSubtype(subtype) +
']) {',
]
.concat(internalCode.map(StringUtils.indent(2)))
.concat(['}']);
return soFar.concat(code);
}
function codeForBranchingOnSubtypeWithSubtypeMapper(
algebraicType: AlgebraicType.Type,
subtypeValueAccessor: string,
subtypeMapper: (
algebraicType: AlgebraicType.Type,
subtype: AlgebraicType.Subtype,
) => string[],
fallbackDecodingFunction: string | null,
): string[] {
const subtypeBranches: string[] = algebraicType.subtypes.reduce(
(soFar, subtype) =>
codeForSubtypeBranchesWithSubtypeMapper(
algebraicType,
subtypeValueAccessor,
subtypeMapper,
soFar,
subtype,
),
[],
);
if (fallbackDecodingFunction != null) {
const fallbackDecodingFunctionInvocation: string[] = [
'else {',
StringUtils.indent(2)(
'return ' + fallbackDecodingFunction + '(aDecoder);',
),
'}',
];
return subtypeBranches.concat(fallbackDecodingFunctionInvocation);
} else {
const failureCase: string[] = [
'else {',
StringUtils.indent(2)(
'[aDecoder failWithError:[NSError errorWithDomain:NSCocoaErrorDomain code:NSCoderReadCorruptError ' +
'userInfo:@{NSDebugDescriptionErrorKey:[NSString stringWithFormat:@"*** [%@ %@]: Invalid subtype provided: %@", ' +
'[self class], NSStringFromSelector(_cmd), ' +
codeableAttributeForSubtypePropertyOfAlgebraicType().valueAccessor +
']}]];',
),
StringUtils.indent(2)('return nil;'),
'}',
];
return subtypeBranches.concat(failureCase);
}
}
export function createAlgebraicTypePlugin(): AlgebraicType.Plugin {
return {
additionalFiles: function (algebraicType: AlgebraicType.Type): Code.File[] {
return [];
},
transformBaseFile: function (
algebraicType: AlgebraicType.Type,
baseFile: Code.File,
): Code.File {
return baseFile;
},
blockTypes: function (algebraicType: AlgebraicType.Type): ObjC.BlockType[] {
return [];
},
classMethods: function (algebraicType: AlgebraicType.Type): ObjC.Method[] {
const secureCoding =
algebraicType.includes.indexOf('NSSecureCoding') >= 0;
return secureCoding ? [CodingUtils.supportsSecureCodingMethod] : [];
},
enumerations: function (
algebraicType: AlgebraicType.Type,
): ObjC.Enumeration[] {
return [];
},
transformFileRequest: function (
request: FileWriter.Request,
): FileWriter.Request {
return request;
},
fileType: function (
algebraicType: AlgebraicType.Type,
): Code.FileType | null {
return null;
},
forwardDeclarations: function (
algebraicType: AlgebraicType.Type,
): ObjC.ForwardDeclaration[] {
return [];
},
functions: function (algebraicType: AlgebraicType.Type): ObjC.Function[] {
return [];
},
headerComments: function (
algebraicType: AlgebraicType.Type,
): ObjC.Comment[] {
return [];
},
implementedProtocols: function (
algebraicType: AlgebraicType.Type,
): ObjC.ImplementedProtocol[] {
const secureCoding =
algebraicType.includes.indexOf('NSSecureCoding') >= 0;
if (secureCoding) {
return [
{
name: 'NSSecureCoding',
},
];
} else {
return [
{
name: 'NSCoding',
},
];
}
},
imports: function (algebraicType: AlgebraicType.Type): ObjC.Import[] {
const file = getKeyValue(
algebraicType.annotations,
'fallbackDecoding',
'file',
);
return file == null
? []
: [
{
file: `${file}.h`,
library: getKeyValue(
algebraicType.annotations,
'fallbackDecoding',
'library',
),
requiresCPlusPlus: false,
isPublic: false,
},
];
},
instanceMethods: function (
algebraicType: AlgebraicType.Type,
): ObjC.Method[] {
const secureCoding =
algebraicType.includes.indexOf('NSSecureCoding') >= 0;
const decodeCode: string[] = decodeCodeForAlgebraicType(
algebraicType,
secureCoding,
getKeyValue(algebraicType.annotations, 'fallbackDecoding', 'name'),
);
const encodeCode: string[] = encodeCodeForAlgebraicType(algebraicType);
return [
decodeMethodWithCode(decodeCode),
encodeMethodWithCode(encodeCode),
];
},
instanceVariables: function (
algebraicType: AlgebraicType.Type,
): ObjC.InstanceVariable[] {
return [];
},
macros: function (algebraicType: AlgebraicType.Type): ObjC.Macro[] {
return [];
},
requiredIncludesToRun: ['RMCoding'],
staticConstants: function (
algebraicType: AlgebraicType.Type,
): ObjC.Constant[] {
const codeableAttributeForSubtypeProperty: CodeableAttribute =
codeableAttributeForSubtypePropertyOfAlgebraicType();
const codeableAttributeForSubtypeAttributes: CodeableAttribute[] =
AlgebraicTypeUtils.mapAttributesWithSubtypeFromSubtypes(
algebraicType.subtypes,
codeableAttributeForAlgebraicSubtypeAttribute,
);
const codeableAttributes: CodeableAttribute[] = [
codeableAttributeForSubtypeProperty,
].concat(codeableAttributeForSubtypeAttributes);
return codeableAttributes.map(staticConstantForAttribute);
},
validationErrors: function (
algebraicType: AlgebraicType.Type,
): Error.Error[] {
const attributes = AlgebraicTypeUtils.allAttributesFromSubtypes(
algebraicType.subtypes,
);
const unknownTypeErrors = attributes
.filter(doesAlgebraicAttributeContainAnUnknownType)
.map((attribute) =>
algebraicAttributeToUnknownTypeError(algebraicType, attribute),
);
const unsupportedTypeErrors = attributes
.filter(doesAlgebraicAttributeContainAnUnsupportedType)
.map((attribute) =>
algebraicAttributeToUnsupportedTypeError(algebraicType, attribute),
);
const unsupportedAnnotationErrors = Maybe.catMaybes(
attributes.map(unsupportedAnnotationErrorForAlgebraicAttribute),
);
return unknownTypeErrors
.concat(unsupportedTypeErrors)
.concat(unsupportedAnnotationErrors);
},
nullability: function (
algebraicType: AlgebraicType.Type,
): ObjC.ClassNullability | null {
return null;
},
subclassingRestricted: function (
algebraicType: AlgebraicType.Type,
): boolean {
return false;
},
};
} | the_stack |
declare namespace LocalizeJS.Context {
interface Options {
/**
* Required. Your project key.
*/
key: string;
/**
* Defaults to false.
* If true and you have machine translations enabled, any new phrases found in your website will be automatically
* moved to the Published bin, and a machine translation will be generated.
*/
autoApprove: boolean;
/**
* Language to translate your website to.
*/
targetLanguage: string;
/**
* Defaults to false. If true, Localize will translate your website to the last selected language on subsequent page views.
*/
rememberLanguage: boolean;
/**
* Defaults to true. If true, translations will be fetched from Localize if not bootstrapped.
*/
fetchTranslations: boolean;
/**
* Defaults to true. If true, "alt" attributes will be translated.
*/
translateAlt: boolean;
/**
* Defaults to true. If true, aria-label attributes within HTML elements will be found by Localize and brought into the dashboard, allowing you to translate them.
*/
translateAriaLabels: boolean;
/**
* Defaults to false. Set to true to prefetch all active languages, or pass a language code or an array of codes to.
*/
prefetch: boolean;
/**
* Array of class names for which Localize will ignore.
*/
blockedClasses: string[];
/**
* Array of CSS ID selectors.
*/
blockedIds: string[];
/**
* Defaults to false. When true, the default Localize widget is disabled.
*/
disableWidget: boolean;
/**
* Defaults to false. If true, the image URLs used in your website will appear in your phrases bin to allow for image replacement based on language.
*/
localizeImages: boolean;
/**
* Array of class names for which Localize will translate. If you use this option, Localize will only translate content
* contained in these classes and will ignore all other content in the body of the page.
*/
translateClasses: string[];
/**
* Defaults to true. Automatically default the page language to the user's preferred language. The first path segment
* in the URL is used to check to detect the language, ie. www.localize.com/fr. If no language dictionary exists for that
* segment then the language setting in their browser is used.
*/
autodetectLanguage: boolean;
/**
* Defaults to false. When true, Localize will attempt to translate the entire body of the page.
* If false, Localize will only translate content contained with a "localizejs" class name.
*/
translateBody: boolean;
/**
* The default language your website will be in when no language has been selected. Defaults to the source language of your website.
*/
defaultLanguage: string;
/**
* The base path will be stripped from the URL of the phrase as seen in the "Filter by pages" feature.
*/
basePath: string;
/**
* Defaults to true. If true, the <title> of the page will translate.
*/
translateTitle: boolean;
/**
* Defaults to false. Allows users to turn on meta tag translation. This optimizes your site for SEO.
*/
translateMetaTags: boolean;
/**
* Defaults to true. If true, unrecognized phrases will be added to your Localize account. Disable this in development.
*/
saveNewPhrases: boolean;
/**
* Defaults to false. If true, Localize will detect phrases only when the page is not translated.
* Please contact support@localizejs.com prior to updating this option.
*/
saveNewPhrasesFromSource: boolean;
/**
* Defaults to false. Automatically translate content that is added dynamically to your webpage.
* For example, if your webpage dynamically adds html into the source of the page, our library
* will translate it once the translations have been generated. Behind the scenes this means the
* dictionary file with all your translated content is available for use with Localize.translate().
* However, translations are not generated instantly, so use with our library event updatedDictionary is recommended.
*/
retranslateOnNewPhrases: boolean;
/**
* Defaults to false. If true, the Localize library will not send additional metadata to our servers.
* This metadata includes the surrounding HTML of the phrases detected on your website.
*/
enhancedContentSecurity: boolean;
/**
* Defaults to false. If true, the Localize library will pick up phrases in the <time> elements.
*/
translateTimeElement: boolean;
/**
* Defaults to false. If true, the Localize library will pick up numbers as phrases.
*/
translateNumbers: boolean;
/**
* Defaults to true. If true, text contained within SVGs will be found by Localize and brought into the dashboard,
* allowing you to translate the text. (SVG files are not supported)
*/
translateSVGElement: boolean;
}
interface RateData {
fromCurrency: string;
toCurrency: string;
rate: string;
}
}
declare var Localize: {
/**
* Initializes LocalizeJS with the supplied options.
* @param options An object containing the supplied options.
*/
initialize(options: LocalizeJS.Context.Options): void;
/**
* Translates the page into the given language.
* @param language Required. Language codes can be found on your Languages page.
*/
setLanguage(language: string): void;
/**
* Returns the current language of the page. If a language hasn't been set, source is returned.
*/
getLanguage(): string;
/**
* Returns the language code for the source language of the current project.
*/
getSourceLanguage(): string;
/**
* Returns the visitor's list of preferred languages, based on the browser's "accept-language" header.
* @param callback Required.
*/
detectLanguage(callback: (error: any, languages: string[]) => void): void;
/**
* Returns all available languages for the project.
* @param callback Required.
*/
getAvailableLanguages(callback: (error: any, languages: string[]) => void): void;
/**
* Calling this function will hide the widget if it's currently visible.
* You can use this function to hide the widget on certain pages.
*/
hideWidget(): void;
/**
* Calling this function will show the widget if it's currently hidden.
*/
showWidget(): void;
/**
* Translates text or text within html.
*
* If the Localize.translate() input is a string, instances of %{variable} will be replaced with the given value in the variables object.
* You may also use HTML <var> tags in the string
*
* If the active language is the source language of the page, Localize.translate will return the untranslated phrase.
* Localize.translate can be used with or without a callback. We highly recommend using the callback approach if you're calling
* Localize.translate in the first 10 seconds of page load to ensure that the latest translations are available. The callback will
* allow the translation to delay until translations have been fully loaded into the browser. If the translations are already
* loaded, the callback is executed immediately.
*
* @param input Required. Can be text, html or native DOM elements
* @param variables Optional. Object of variables that will be replaced in the input, if it's a string
* @param callback Optional. Callback will trigger once translations have been fetched from Localize.
*/
translate(
input: string | HTMLElement,
variables?: any,
callback?: (translation: string | HTMLElement) => void,
): void;
/**
* Translates all text on the page
*/
translatePage(): void;
/**
* Untranslates all text on the page
*/
untranslatePage(): void;
/**
* Untranslates a specified element on the page. Use Localize.untranslatePage() if untranslating the whole page.
* @param element Required. A DOM node to untranslate
*/
untranslate(element: string): void;
/**
* Speed up language switching by prefetching
* @param languages Required. Accepts a string or an array or languages (ex. 'zh-CN')
*/
prefetch(languages: string | string[]): void;
/**
* Saves the phrase, if unrecognized, to your Localize project. Useful for ensuring rarely printed text
* (ie. an obscure error message) is translated. Returns the phrase it was passed.
* @param phrase Required. A string or an array of strings
*/
phrase(phrase: string | string[]): string | string[];
/**
* Attach an event handler to Localize events.
* @param eventName Required. Name of event to bind to. Can optionally be namespaced: "setLanguage.ns"
* @param fn Required. Event handler.
*/
on(
eventName: 'initialize' | 'setLanguage' | 'pluralize' | 'translate' | 'untranslatePage' | 'updatedDictionary',
fn: (event: Event) => void,
): void;
/**
* Remove an event handler.
* @param eventName Required. Name of event to unbind to. Can optionally be namespaced: "setLanguage.ns"
* @param fn Optional. The function to unbind from the event.
*/
off(
eventName: 'initialize' | 'setLanguage' | 'pluralize' | 'translate' | 'untranslatePage' | 'updatedDictionary',
fn?: (event: Event) => void,
): void;
/**
* Returns exchange rate for provided currencies.
*
* @param fromCurrency Required. The default source currency, to be converted from.
* @param toCurrency Required. The new currency, to be converted to.
* @param callback Required. Receives err and rateData arguments.
*/
getExchangeRate(
fromCurrency: string,
toCurrency: string,
callback: (error: any, rateData: LocalizeJS.Context.RateData) => void,
): void;
}; | the_stack |
import { ARIADefinitions } from "./ARIADefinitions";
import { CommonMapper } from "../common/CommonMapper";
import { IMapResult} from "../api/IMapper";
import { DOMUtil } from "../dom/DOMUtil";
import { RPTUtil } from "../checker/accessibility/util/legacy"
import { FragmentUtil } from "../checker/accessibility/util/fragment";
type ElemCalc = (elem: Element) => string;
type NodeCalc = (node: Node) => string;
export class ARIAMapper extends CommonMapper {
//dom-defined relationship overridden by aria-owns: elemId : parentRolePath
private ariaHierarchy: Array<{
id: string,
hierarchyRole : string[],
hierarchyChildrenHaveRole: boolean[],
hierarchyPath: Array<{
rolePath: string,
roleCount: {
[role: string]: number
}
}>,
hierarchyResults: IMapResult[],
node:Node | null,
shadowRoot: Node | null
}> = null;
private hierarchyCache: {
hierarchyRole : string[],
hierarchyChildrenHaveRole: boolean[],
hierarchyPath: Array<{
rolePath: string,
roleCount: {
[role: string]: number
}
}>,
hierarchyResults: IMapResult[]
};
childrenHaveRole(node: Node, role: string) : boolean {
// if (node.nodeType === 1 /* Node.ELEMENT_NODE */) {
// const elem = node as Element;
// if (elem.getAttribute("aria-hidden") === "true") {
// return false;
// }
// }
return !(role in ARIADefinitions.designPatterns && ARIADefinitions.designPatterns[role].presentationalChildren);
}
getRole(node: Node) : string {
const role = ARIAMapper.nodeToRole(node);
return role;
}
getNamespace(): string {
return "aria"
}
getAttributes(node: Node) : { [key:string]: string } {
let retVal = {};
if (node.nodeType === 1 /* Node.ELEMENT_NODE */) {
const elem = node as Element;
for (let idx=0; idx<elem.attributes.length; ++idx) {
const attrInfo = elem.attributes[idx];
const name = attrInfo.name.toLowerCase();
if (name.startsWith("aria-")) {
retVal[name.substring(5)] = attrInfo.nodeValue;
}
}
let applyAttrRole= function(nodeName:string) {
if (!(nodeName in ARIAMapper.elemAttrValueCalculators)) return;
for (const attr in ARIAMapper.elemAttrValueCalculators[nodeName]) {
if (!(attr in retVal)) {
let value = ARIAMapper.elemAttrValueCalculators[nodeName][attr];
if (typeof value != "undefined" && value !== null) {
if (typeof value !== typeof "") {
value = (value as NodeCalc)(elem);
}
retVal[attr] = value;
}
}
}
}
applyAttrRole("global");
applyAttrRole(node.nodeName.toLowerCase());
} else if (node.nodeType === 3 /* Node.TEXT_NODE */) {
for (const attr in ARIAMapper.textAttrValueCalculators) {
let val = ARIAMapper.textAttrValueCalculators[attr](node);
if (typeof val != "undefined" && val !== null) {
retVal[attr] = val;
}
}
}
return retVal;
}
reset(node: Node) {
if (this.ariaHierarchy === null) {
let parent = DOMUtil.parentNode(node);
if (parent && parent.nodeType === 9 /* Node.DOCUMENT_NODE */) {
let top = (parent as Document).documentElement;
let list = top.querySelectorAll('[aria-owns]');
if (list !== null) {
this.ariaHierarchy = [];
list.forEach((elem) => {
let hierarchies : IMapResult[] = this.openScope(elem);
let hierarchyRole : string[] = JSON.parse(JSON.stringify(this.hierarchyRole));
let hierarchyChildrenHaveRole: boolean[] = JSON.parse(JSON.stringify(this.hierarchyChildrenHaveRole));
let hierarchyPath: Array<{
rolePath: string,
roleCount: {
[role: string]: number
}
}> = JSON.parse(JSON.stringify(this.hierarchyPath));
let hierarchyResults: IMapResult[] = JSON.parse(JSON.stringify(this.hierarchyResults));
let attrValue = elem.getAttribute("aria-owns");
let ids = attrValue.trim().split(" ");
ids.forEach((id) => {
this.ariaHierarchy.push({
id: id.trim(),
hierarchyRole: hierarchyRole,
hierarchyChildrenHaveRole: hierarchyChildrenHaveRole,
hierarchyPath: hierarchyPath,
hierarchyResults: hierarchyResults,
node: null,
shadowRoot: DOMUtil.shadowRootNode(elem)
});
});
//clear the hierarchies
this.hierarchyRole = [];
this.hierarchyResults = [];
this.hierarchyChildrenHaveRole = [];
this.hierarchyPath = [{
rolePath: "",
roleCount: {}
}];
});
}
}
}
ARIAMapper.nameComputationId = 0;
super.reset(node);
}
pushHierarchy(node: Node) {
if (this.switchParentHierarchies(node)) {
//cache the original hierarchies
this.hierarchyCache = {
hierarchyRole: JSON.parse(JSON.stringify(this.hierarchyRole)),
hierarchyChildrenHaveRole: JSON.parse(JSON.stringify(this.hierarchyChildrenHaveRole)),
hierarchyPath: JSON.parse(JSON.stringify(this.hierarchyPath)),
hierarchyResults: JSON.parse(JSON.stringify(this.hierarchyResults))
};
//rewrite parent hierarchy to the element with aria-owns
const value = (node as Element).getAttribute("id");
const hierarchyItem = this.ariaHierarchy.find(aria => aria.id === value);
this.hierarchyRole = hierarchyItem.hierarchyRole;
this.hierarchyChildrenHaveRole = hierarchyItem.hierarchyChildrenHaveRole;
this.hierarchyPath = hierarchyItem.hierarchyPath;
this.hierarchyResults = hierarchyItem.hierarchyResults;
//set the current node
hierarchyItem.node = node;
}
super.pushHierarchy(node);
}
closeScope(node: Node): IMapResult[] {
const results : IMapResult[] = super.closeScope(node);
if (node.nodeType === Node.ELEMENT_NODE && this.ariaHierarchy != null && this.ariaHierarchy.length > 0) {
const value = (node as Element).getAttribute("id");
let hierarchyItem = this.ariaHierarchy.find(aria => aria.id === value);
if (hierarchyItem) {
if (DOMUtil.sameNode(node, hierarchyItem.node)) {
//rewrite competed, restore original hierarchies
this.hierarchyRole = this.hierarchyCache.hierarchyRole;
this.hierarchyChildrenHaveRole = this.hierarchyCache.hierarchyChildrenHaveRole;
this.hierarchyPath = this.hierarchyCache.hierarchyPath;
this.hierarchyResults = this.hierarchyCache.hierarchyResults;
//set rewrite parent node to null
hierarchyItem.node = null;
}
}
}
return results;
}
//rewrite aria role path for aria-owns
switchParentHierarchies(node : Node) : boolean {
if (this.ariaHierarchy === null || this.ariaHierarchy.length === 0 || node.nodeType !== node.ELEMENT_NODE) return false;
const value : string = (node as Element).getAttribute("id");
if (value === null) return false;
const ariaMap = this.ariaHierarchy.find(aria => aria.id === value);
if (!ariaMap) return false;
//aria-owns doesn't cross doms
const shadowRoot = DOMUtil.shadowRootNode(node);
if ((shadowRoot && !ariaMap.shadowRoot)
|| (!shadowRoot && ariaMap.shadowRoot)
|| (shadowRoot && ariaMap.shadowRoot && !DOMUtil.sameNode(shadowRoot, ariaMap.shadowRoot)))
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////
// Helper functions
////
// https://www.w3.org/TR/html-aam-1.0/#mapping-html-to-accessibility-apis
public static elemAttrValueCalculators: { [nodeName:string]: { [attr:string]: string | ElemCalc }} = {
"global": {
"name": ARIAMapper.computeName
}
, "datalist": {
// set to "true" if the datalist's selection model allows multiple option elements to be
// selected at a time, and "false" otherwise
"multiselectable": elem => {
const id = elem.getAttribute("id");
if (id && id.length > 0) {
let input = elem.ownerDocument.querySelector("input[list='"+id+"']");
return ""+(elem.getAttribute("multiple")
&& (elem.getAttribute("multiple")=="true" || elem.getAttribute("multiple")==""))
}
return null;
}
}
, "h1": {
"level": "1"
}
, "h2": {
"level": "2"
}
, "h3": {
"level": "3"
}
, "h4": {
"level": "4"
}
, "h5": {
"level": "5"
}
, "h6": {
"level": "6"
}
, "input": {
// - type="checkbox" state set to "mixed" if the element's indeterminate IDL attribute
// is true, or "true" if the element's checkedness is true, or "false" otherwise
// - type="radio" state set to "true" if the element's checkedness is true, or "false"
// otherwise.
"checked": elem => {
if (elem.getAttribute("type") === "checkbox" || elem.getAttribute("type") === "radio") {
return ""+(elem as HTMLInputElement).checked;
}
return null;
}
// - type="radio" and not in menu reflecting number of type=radio input elements
// within the radio button group
, "setsize": elem => { return null; throw new Error("NOT IMPLEMENTED"); }
// - type="radio" and not in menu value reflecting the elements position
// within the radio button group."
, "posinset": elem => { return null; throw new Error("NOT IMPLEMENTED"); }
// input (type attribute in the Text, Search, Telephone, URL, or E-mail states with a
// suggestions source element) combobox role, with the aria-owns property set to the same
// value as the list attribute
, "owns": elem => { return null; throw new Error("NOT IMPLEMENTED"); }
}
, "keygen": {
"multiselectable": "false"
}
, "li": {
// Number of li elements within the ol, ul, menu
"setsize": elem => {
let parent = DOMUtil.getAncestor(elem, ["ol", "ul", "menu"]);
if (!parent) return null;
let lis = parent.querySelectorAll("li");
let otherlis = parent.querySelectorAll("ol li, ul li, menu li");
return ""+(lis.length-otherlis.length);
}
// Position of li element within the ol, ul, menu
, "posinset": elem => {
let parent = DOMUtil.getAncestor(elem, ["ol", "ul", "menu"])
if (!parent) return null;
let lis = parent.querySelectorAll("li");
let num = 0;
for (let idx=0; idx<lis.length; ++idx) {
const li = lis[idx];
if (DOMUtil.sameNode(parent, DOMUtil.getAncestor(li, ["ol", "ul", "menu"]))) {
return ""+num;
}
++num;
}
return null;
}
}
, "menuitem": {
// type = checkbox or radio, set to "true" if the checked attribute
// is present, and "false" otherwise
"checked": elem => ""+!!(elem.getAttribute("checked")
&& (elem.getAttribute("checked")=="true" || elem.getAttribute("checked")==""))
}
, "option": {
// set to "true" if the element's selectedness is true, or "false" otherwise.
"selected": elem => ""+!!(elem.getAttribute("selected")
&& (elem.getAttribute("selected")=="true" || elem.getAttribute("selected")==""))
}
, "progress": {
"valuemax": elem => elem.getAttribute("max") || "1"
, "valuemin": elem => "0"
, "valuenow": elem => elem.getAttribute("value")
}
}
public static textAttrValueCalculators: { [attr:string]: NodeCalc } = {
"name": node => node.nodeValue
}
private static nameComputationId = 0;
public static computeName(cur: Node) : string {
++ARIAMapper.nameComputationId;
return ARIAMapper.computeNameHelp(ARIAMapper.nameComputationId, cur, false, false);
}
public static computeNameHelp(walkId: number, cur: Node, labelledbyTraverse: boolean, walkTraverse: boolean) : string {
// 2g. None of the other content applies to text nodes, so just do this first
if (cur.nodeType === 3 /* Node.TEXT_NODE */) return cur.nodeValue;
if (cur.nodeType === 11) return "";
if (cur.nodeType !== 1 /* Node.ELEMENT_NODE */) {
if (walkTraverse || labelledbyTraverse) return "";
throw new Error ("Can only compute name on Element and Text" + cur.nodeType);
}
const elem = cur as Element;
// We've been here before - prevent recursion
if (RPTUtil.getCache(elem, "data-namewalk", null) === ""+walkId) return "";
RPTUtil.setCache(elem, "data-namewalk", ""+walkId);
// See https://www.w3.org/TR/html-aam-1.0/#input-type-text-input-type-password-input-type-search-input-type-tel-input-type-url-and-textarea-element
// 2a. Only show hidden content if it's referenced by a labelledby
if (!labelledbyTraverse && !DOMUtil.isNodeVisible(cur)) {
return "";
}
// 2b. collect valid id references
if (!labelledbyTraverse && elem.hasAttribute("aria-labelledby")) {
let labelledby = elem.getAttribute("aria-labelledby").split(" ");
let validElems = [];
for (const ref of labelledby) {
const refElem = FragmentUtil.getById(cur, ref);
if (refElem) {
validElems.push(refElem);
}
}
if (validElems.length > 0) {
let accumulated = "";
for (const elem of validElems) {
accumulated += " " + this.computeNameHelp(walkId, elem, true, false);
}
return accumulated.trim();
}
}
// 2c. If label or walk, and this is a control, skip to the value, otherwise provide the label
const role = ARIAMapper.nodeToRole(cur);
let isEmbeddedControl = [
"textbox", "button", "combobox", "listbox",
"progressbar", "scrollbar", "slider", "spinbutton"
].includes(role);
if (elem.hasAttribute("aria-label") && elem.getAttribute("aria-label").trim().length > 0) {
// If I'm not an embedded control or I'm not recursing, return the aria-label
if (!labelledbyTraverse && !walkTraverse || !isEmbeddedControl) {
return elem.getAttribute("aria-label").trim();
}
}
// 2d.
if (role !== "presentation" && role !== "none") {
if ((cur.nodeName.toLowerCase() === "img" || cur.nodeName.toLowerCase() === "area") && elem.hasAttribute("alt")) {
return DOMUtil.cleanWhitespace(elem.getAttribute("alt")).trim();
}
if (cur.nodeName.toLowerCase() === "input" && elem.hasAttribute("id") && elem.getAttribute("id").length > 0) {
let label = elem.ownerDocument.querySelector("label[for='"+elem.getAttribute("id")+"']");
if (label) {
return this.computeNameHelp(walkId, label, false, false);
}
}
}
// 2e.
if ((walkTraverse || labelledbyTraverse) && isEmbeddedControl) {
// If the embedded control has role textbox, return its value.
if (role === "textbox") {
if (elem.nodeName.toLowerCase() === "input") {
if (elem.hasAttribute("value")) return elem.getAttribute("value");
} else {
walkTraverse = false;
}
}
// If the embedded control has role button, return the text alternative of the button.
if (role === "button") {
if (elem.nodeName.toLowerCase() === "input") {
let type = elem.getAttribute("type").toLowerCase();
if (["button", "submit", "reset"].includes(type)) {
if (elem.hasAttribute("value")) return elem.getAttribute("value");
if (type === "submit") return "Submit";
if (type === "reset") return "Reset";
}
} else {
walkTraverse = false;
}
}
// TODO: If the embedded control has role combobox or listbox, return the text alternative of the chosen option.
if (role === "combobox") {
if (elem.hasAttribute("aria-activedescendant")) {
let selected = FragmentUtil.getById(elem, "aria-activedescendant");
if (selected) {
return ARIAMapper.computeNameHelp(walkId, selected, false, false);
}
}
}
// If the embedded control has role range (e.g., a spinbutton or slider):
if (["progressbar", "scrollbar", "slider", "spinbutton"].includes(role)) {
// If the aria-valuetext property is present, return its value,
if (elem.hasAttribute("aria-valuetext")) return elem.getAttribute("aria-valuetext");
// Otherwise, if the aria-valuenow property is present, return its value,
if (elem.hasAttribute("aria-valuenow")) return elem.getAttribute("aria-valuenow");
// TODO: Otherwise, use the value as specified by a host language attribute.
}
}
// 2f. 2h.
if (walkTraverse || ARIADefinitions.nameFromContent(role) || labelledbyTraverse) {
// 2fi. Set the accumulated text to the empty string.
let accumulated = "";
// 2fii. Check for CSS generated textual content associated with the current node and
// include it in the accumulated text. The CSS :before and :after pseudo elements [CSS2]
// can provide textual content for elements that have a content model.
// For :before pseudo elements, User agents MUST prepend CSS textual content, without
// a space, to the textual content of the current node.
// For :after pseudo elements, User agents MUST append CSS textual content, without a
// space, to the textual content of the current node.
let before = null;
before = elem.ownerDocument.defaultView.getComputedStyle(elem,"before").content;
if (before && before !== "none") {
before = before.replace(/^"/,"").replace(/"$/,"");
accumulated += before;
}
// 2fiii. For each child node of the current node:
// Set the current node to the child node.
// Compute the text alternative of the current node beginning with step 2. Set the result
// to that text alternative.
// Append the result to the accumulated text.
let walkChild = elem.firstChild;
while (walkChild) {
accumulated += " " + ARIAMapper.computeNameHelp(walkId, walkChild, labelledbyTraverse, true);
walkChild = walkChild.nextSibling;
}
let after = null;
try {
after = elem.ownerDocument.defaultView.getComputedStyle(elem,"after").content;
} catch (e) {}
if (after && after !== "none") {
after = after.replace(/^"/,"").replace(/"$/,"");
accumulated += after;
}
// 2fiv. Return the accumulated text.
accumulated = accumulated.replace(/\s+/g," ").trim();
if (accumulated.trim().length > 0) {
return accumulated;
}
}
// 2i. Otherwise, if the current node has a Tooltip attribute, return its value.
if (elem.hasAttribute("title")) {
return elem.getAttribute("title");
}
if (elem.tagName.toLowerCase() === "svg") {
let title = elem.querySelector("title");
if (title) {
return title.textContent || title.innerText;
}
}
return "";
}
/* if (role in ARIADefinitions.designPatterns
&& ARIADefinitions.designPatterns[role].nameFrom
&& ARIADefinitions.designPatterns[role].nameFrom.includes("contents"))
{
name = elem.textContent;
}
if (elem.nodeName.toLowerCase() === "input" && elem.hasAttribute("id") && elem.getAttribute("id").trim().length > 0) {
name = elem.ownerDocument.querySelector("label[for='"+elem.getAttribute("id").trim()+"']").textContent;
}
if (elem.hasAttribute("aria-label")) {
name = elem.getAttribute("aria-label");
}
if (elem.hasAttribute("aria-labelledby")) {
name = "";
const ids = elem.getAttribute("aria-labelledby").split(" ");
for (const id of ids) {
name += FragmentUtil.getById(elem, id).textContent + " ";
}
name = name.trim();
}
return name;
}*/
public static nodeToRole(node : Node) {
if (node.nodeType === 3 /* Node.TEXT_NODE */) {
return "text";
} else if (node.nodeType !== 1 /* Node.ELEMENT_NODE */) {
return null;
}
const elem = node as Element;
if (!elem || elem.nodeType !== 1 /* Node.ELEMENT_NODE */) {
return null;
}
if (elem.hasAttribute("role") && elem.getAttribute("role").trim().length > 0) {
let roleStr = elem.getAttribute("role").trim();
let roles = roleStr.split(" ");
for (const role of roles) {
if (role === "presentation" || role === "none") {
// If element is focusable, then presentation roles are to be ignored
if (!RPTUtil.isFocusable(elem)) {
return null;
}
} else if (role in ARIADefinitions.designPatterns) {
return role;
}
}
}
return this.elemToImplicitRole(elem);
}
public static elemToImplicitRole(elem : Element) {
let nodeName = elem.nodeName.toLowerCase();
if (!(nodeName in ARIAMapper.elemToRoleMap)) {
return null;
}
let role = ARIAMapper.elemToRoleMap[nodeName];
if (typeof role === "string") {
return role;
} else if (typeof role === "function") {
return role(elem);
} else {
return null;
}
}
public static hasParentRole(element, role) : boolean {
let parent = DOMUtil.parentNode(element);
// If link is in a menu, it's a menuitem
while (parent) {
if (ARIAMapper.nodeToRole(parent) === role)
return true;
parent = DOMUtil.parentNode(parent);
}
return false;
}
private static inputToRoleMap = (function() {
let menuButtonCheck = function(element) {
return ARIAMapper.hasParentRole(element, "menu") ? "menuitem" : "button";
};
let textSuggestions = function(element) {
if (element.hasAttribute("list")) {
let id = element.getAttribute("list");
let idRef = FragmentUtil.getById(element, id);
if (idRef && idRef.nodeName.toLowerCase() === "datalist") {
return "combobox";
}
}
return "textbox";
}
return {
"button": menuButtonCheck,
"image": menuButtonCheck,
"checkbox": function(element) {
return ARIAMapper.hasParentRole(element, "menu") ? "menuitemcheckbox" : "checkbox";
},
"radio": function(element) {
return ARIAMapper.hasParentRole(element, "menu") ? "menuitemradio" : "radio";
},
"email": textSuggestions,
"search": textSuggestions,
"tel": textSuggestions,
"text": textSuggestions,
"url": textSuggestions,
"password": "textbox",
"number": "spinbutton",
"range": "slider",
"reset": "button",
"submit": "button"
}
})();
private static inputToRole(element) {
if (!element) {
return null;
}
let eType = "text";
if (element.hasAttribute("type") && element.getAttribute("type").toLowerCase().trim().length > 0) {
eType = element.getAttribute("type").toLowerCase().trim();
}
if (!(eType in ARIAMapper.inputToRoleMap)) {
return null;
}
let role = ARIAMapper.inputToRoleMap[eType];
if (typeof role === "string") {
return role;
} else if (typeof role === "function") {
return role(element);
} else {
return null;
}
}
private static elemToRoleMap = (function() {
let sectioningRoots = {
"blockquote": true,
"body": true,
"details": true,
"dialog": true,
"fieldset": true,
"figure": true,
"td": true
};
let sectioningContent = {
"article": true,
"aside": true,
"nav": true,
"section": true
};
let inputToRole = function(element) {
return ARIAMapper.inputToRole(element);
}
return {
"a": function(element) {
// If it doesn't represent a hyperlink, no corresponding role
if (!element.hasAttribute("href")) return null;
// If link is in a menu, it's a menuitem, otherwise it's a link
return ARIAMapper.hasParentRole(element, "menu") ? "menuitem" : "link";
},
"area": function(element) {
// If it doesn't represent a hyperlink, no corresponding role
if (!element.hasAttribute("href")) return null;
return "link";
},
"article": "article",
"aside": "complementary",
"body": "document",
"button": "button",
"datalist": "listbox",
"dd": "definition",
"details": "group",
"dialog": "dialog",
"footer": function(element) {
let parent = DOMUtil.parentNode(element);
let nodeName = parent.nodeName.toLowerCase();
// If nearest sectioningRoot or sectioningContent is body
while (parent) {
if (sectioningRoots[nodeName] || sectioningContent[nodeName]) {
return (nodeName === "body") ? "contentinfo" : null;
}
parent = DOMUtil.parentNode(parent);
nodeName = parent.nodeName.toLowerCase();
}
return null;
},
"form": "form",
"h1": "heading",
"h2": "heading",
"h3": "heading",
"h4": "heading",
"h5": "heading",
"h6": "heading",
"header": function(element) {
let parent = DOMUtil.parentNode(element);
// If nearest sectioningRoot or sectioningContent is body
while (parent && parent.nodeType === 1) {
let nodeName = parent.nodeName.toLowerCase();
if (sectioningRoots[nodeName] || sectioningContent[nodeName]) {
return (nodeName === "body") ? "banner" : null;
}
parent = DOMUtil.parentNode(parent);
}
return null;
},
"hr": "separator",
"img": function(element) {
if (element.hasAttribute("alt") && element.getAttribute("alt").length === 0) {
return "presentation";
} else {
return "img";
}
},
"input": inputToRole,
"keygen": "listbox",
"li": "listitem",
"main": "main",
"math": "math",
"menu": function(element) {
if (!element.hasAttribute("type")) return null;
let eType = element.getAttribute("type").toLowerCase();
if (eType === "context") return "menu";
if (eType === "toolbar") return "toolbar";
return null;
},
"menuitem": function(element) {
// Default type is command
if (!element.hasAttribute("type")) return "menuitem";
let eType = element.getAttribute("type").toLowerCase();
if (eType.trim().length === 0) return "menuitem";
if (eType === "command") return "menuitem";
if (eType === "checkbox") return "menuitemcheckbox";
if (eType === "radio") return "menuitemradio";
return null;
},
"meter": "progressbar",
"nav": "navigation",
"ol": "list",
"optgroup": "group",
"option": "option",
"output": "status",
"progress": "progressbar",
"section": "region",
"select": function(element) {
if (element.hasAttribute("multiple") || (element.hasAttribute("size") && parseInt(element.getAttribute("size")) > 1)) {
return "listbox";
} else {
return "combobox";
}
},
"table": "table",
"textarea": "textbox",
"tbody": "rowgroup",
"td": function(element) {
let parent = DOMUtil.parentNode(element);
while (parent) {
let role = ARIAMapper.nodeToRole(parent);
if (role === "table") return "cell";
if (role === "grid") return "gridcell";
parent = DOMUtil.parentNode(parent);
}
return null;
},
"th": function(element) {
/** https://www.w3.org/TR/html5/tabular-data.html#header-and-data-cell-semantics
* A header cell anchored at the slot with coordinate (x, y) with width width and height height is
* said to be a column header if any of the following conditions are true:
* * The cell's scope attribute is in the column state, or
* * The cell's scope attribute is in the auto state, and there are no data cells in any of
* the cells covering slots with y-coordinates y .. y+height-1.
* A header cell anchored at the slot with coordinate (x, y) with width width and height height is
* said to be a row header if any of the following conditions are true:
* * The cell's scope attribute is in the row state, or
* * The cell's scope attribute is in the auto state, the cell is not a column header, and there are
* no data cells in any of the cells covering slots with x-coordinates x .. x+width-1.
*/
// Note: auto is default scope
let parent = DOMUtil.parentNode(element);
while (parent) {
let role = ARIAMapper.nodeToRole(parent);
if (role !== "table" && role !== "grid" && role !== "treegrid") {
parent = DOMUtil.parentNode(parent);
continue;
}
// Easiest answer is if scope is specified
if (element.hasAttribute("scope")) {
let scope = element.getAttribute("scope").toLowerCase();
if (scope === "row" || scope === 'rowgroup') return "rowheader";
if (scope === "col" || scope === 'colgroup') return "columnheader";
}
// scope is auto, default (without a scope) or invalid value.
// if all the sibling elements are th, then return "columnheader"
var siblings = element => [...element.parentElement.children].filter(node=>node.nodeType == 1 && node.tagName != "TH");
if (siblings == null || siblings.length == 0)
return "columnheader";
else return "rowheader";
/**
* dead code here
if (role === "table") return "cell";
if (role === "grid" || role === "treegrid") return "gridcell";
*/
}
return null;
},
"tfoot": "rowgroup",
"thead": "rowgroup",
"tr": "row",
"ul": "list"
}
})()
} | the_stack |
*/
import * as ns from './ns'
import { Namespace, NamedNode, st, IndexedFormula } from 'rdflib'
import { newThing, errorMessageBlock } from './widgets'
import { beep } from './utils'
import { log } from './debug'
import { solidLogicSingleton } from './logic'
export { renderPartipants, participationObject, manageParticipation, recordParticipation } from './participation'
const store = solidLogicSingleton.store
const PAD = Namespace('http://www.w3.org/ns/pim/pad#')
type notepadOptions = {
statusArea?: HTMLDivElement
exists?: boolean
}
/**
* @ignore
*/
class NotepadElement extends HTMLElement {
subject?: NamedNode
}
/**
* @ignore
*/
class NotepadPart extends HTMLElement {
subject?: NamedNode | string
value?: string
state?: Number
lastSent?: String
}
/** Figure out a random color from my webid
*
* @param {NamedNode} author - The author of text being displayed
* @returns {String} The CSS color generated, constrained to be light for a background color
*/
export function lightColorHash (author?: NamedNode): string {
const hash = function (x) {
return x.split('').reduce(function (a, b) {
a = (a << 5) - a + b.charCodeAt(0)
return a & a
}, 0)
}
return author && author.uri
? '#' + ((hash(author.uri) & 0xffffff) | 0xc0c0c0).toString(16)
: '#ffffff' // c0c0c0 forces pale
} // no id -> white
/** notepad
*
* @param {HTMLDocument} dom - the web page of the browser
* @param {NamedNode} padDoc - the document into which the particpation should be shown
* @param {NamedNode} subject - the thing in which participation is happening
* @param {NamedNode} me - person who is logged into the pod
* @param {notepadOptions} options - the options that can be passed in consist of statusArea, exists
*/
export function notepad (dom: HTMLDocument, padDoc: NamedNode, subject: NamedNode, me: NamedNode, options?: notepadOptions) {
options = options || {}
const exists = options.exists
const table: any = dom.createElement('table')
const kb = store
if (me && !me.uri) throw new Error('UI.pad.notepad: Invalid userid')
const updater = store.updater
const PAD = Namespace('http://www.w3.org/ns/pim/pad#')
table.setAttribute(
'style',
'padding: 1em; overflow: auto; resize: horizontal; min-width: 40em;'
)
let upstreamStatus: HTMLElement | null = null
let downstreamStatus: HTMLElement | null = null
if (options.statusArea) {
const t = options.statusArea.appendChild(dom.createElement('table'))
const tr = t.appendChild(dom.createElement('tr'))
upstreamStatus = tr.appendChild(dom.createElement('td'))
downstreamStatus = tr.appendChild(dom.createElement('td'))
if (upstreamStatus) {
upstreamStatus.setAttribute('style', 'width:50%')
}
if (downstreamStatus) {
downstreamStatus.setAttribute('style', 'width:50%')
}
}
/* @@ TODO want to look into this, it seems upstream should be a boolean and default to false ?
*
*/
const complain = function (message: string, upstream: boolean = false) {
log(message)
if ((options as notepadOptions).statusArea) {
; (upstream ? upstreamStatus as HTMLElement : downstreamStatus as HTMLElement).appendChild(errorMessageBlock(dom, message, 'pink'))
}
}
// @@ TODO need to refactor so that we don't have to type cast
const clearStatus = function (_upsteam?: any) {
if ((options as notepadOptions).statusArea) {
((options as notepadOptions).statusArea as HTMLElement).innerHTML = ''
}
}
const setPartStyle = function (part: NotepadPart, colors?: string, pending?: any) {
const chunk = part.subject
colors = colors || ''
const baseStyle =
'font-size: 100%; font-family: monospace; width: 100%; border: none; white-space: pre-wrap;'
const headingCore =
'font-family: sans-serif; font-weight: bold; border: none;'
const headingStyle = [
'font-size: 110%; padding-top: 0.5em; padding-bottom: 0.5em; width: 100%;',
'font-size: 120%; padding-top: 1em; padding-bottom: 1em; width: 100%;',
'font-size: 150%; padding-top: 1em; padding-bottom: 1em; width: 100%;'
]
const author = kb.any(chunk as any, ns.dc('author'))
if (!colors && author) {
// Hash the user webid for now -- later allow user selection!
const bgcolor = lightColorHash(author as any)
colors =
'color: ' +
(pending ? '#888' : 'black') +
'; background-color: ' +
bgcolor +
';'
}
// @@ TODO Need to research when this can be an object with the indent stored in value
// and when the indent is stored as a Number itself, not in an object.
let indent: any = kb.any(chunk as any, PAD('indent'))
indent = indent ? indent.value : 0
const style =
indent >= 0
? baseStyle + 'text-indent: ' + indent * 3 + 'em;'
: headingCore + headingStyle[-1 - indent]
// ? baseStyle + 'padding-left: ' + (indent * 3) + 'em;'
part.setAttribute('style', style + colors)
}
const removePart = function (part: NotepadPart) {
const chunk = part.subject
if (!chunk) throw new Error('No chunk for line to be deleted!') // just in case
const prev: any = kb.any(undefined, PAD('next'), chunk as any)
const next: any = kb.any(chunk as any, PAD('next'))
if (prev.sameTerm(subject) && next.sameTerm(subject)) {
// Last one
log("You can't delete the only line.")
return
}
const del = kb
.statementsMatching(chunk as any, undefined, undefined, padDoc)
.concat(kb.statementsMatching(undefined, undefined, chunk as any, padDoc))
const ins = [st(prev, PAD('next'), next, padDoc)]
// @@ TODO what should we do if chunk is not a NamedNode should we
// assume then it is a string?
if (chunk instanceof NamedNode) {
const label = chunk.uri.slice(-4)
log('Deleting line ' + label)
}
if (!updater) {
throw new Error('have no updater')
}
// @@ TODO below you can see that before is redefined and not a boolean
updater.update(del, ins, function (uri, ok, errorMessage, response) {
if (ok) {
const row = part.parentNode
if (row) {
const before: any = row.previousSibling
if (row.parentNode) {
row.parentNode.removeChild(row)
}
// console.log(' deleted line ' + label + ' ok ' + part.value)
if (before && before.firstChild) {
// @@ TODO IMPORTANT FOCUS ISN'T A PROPERTY ON A CHILDNODE
before.firstChild.focus()
}
}
} else if (response && (response as any).status === 409) {
// Conflict
setPartStyle(part, 'color: black; background-color: #ffd;') // yellow
part.state = 0 // Needs downstream refresh
beep(0.5, 512) // Ooops clash with other person
setTimeout(function () {
// Ideally, beep! @@
reloadAndSync() // Throw away our changes and
// updater.requestDownstreamAction(padDoc, reloadAndSync)
}, 1000)
} else {
log(' removePart FAILED ' + chunk + ': ' + errorMessage)
log(" removePart was deleteing :'" + del)
setPartStyle(part, 'color: black; background-color: #fdd;') // failed
const res = response ? (response as any).status : ' [no response field] '
complain('Error ' + res + ' saving changes: ' + (errorMessage as any).true) // upstream,
// updater.requestDownstreamAction(padDoc, reloadAndSync);
}
})
} // removePart
const changeIndent = function (part: NotepadPart, chunk: string, delta) {
const del = kb.statementsMatching(chunk as any, PAD('indent'))
const current = del.length ? Number(del[0].object.value) : 0
if (current + delta < -3) return // limit negative indent
const newIndent = current + delta
const ins = st(chunk as any, PAD('indent'), newIndent, padDoc)
if (!updater) {
throw new Error('no updater')
}
updater.update(del, ins as any, function (uri, ok, errorBody) {
if (!ok) {
log(
"Indent change FAILED '" +
newIndent +
"' for " +
padDoc +
': ' +
errorBody
)
setPartStyle(part, 'color: black; background-color: #fdd;') // failed
updater.requestDownstreamAction(padDoc, reloadAndSync)
} else {
setPartStyle(part) // Implement the indent
}
})
}
// Use this sort of code to split the line when return pressed in the middle @@
/*
function doGetCaretPosition doGetCaretPosition (oField) {
var iCaretPos = 0
// IE Support
if (document.selection) {
// Set focus on the element to avoid IE bug
oField.focus()
// To get cursor position, get empty selection range
var oSel = document.selection.createRange()
// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length)
// The caret position is selection length
iCaretPos = oSel.text.length
// Firefox suppor
} else if (oField.selectionStart || oField.selectionStart === '0') {
iCaretPos = oField.selectionStart
}
// Return results
return (iCaretPos)
}
*/
const addListeners = function (part: any, chunk: any) {
part.addEventListener('keydown', function (event) {
if (!updater) {
throw new Error('no updater')
}
let queueProperty, queue
// up 38; down 40; left 37; right 39 tab 9; shift 16; escape 27
switch (event.keyCode) {
case 13: // Return
{
const before: NotepadElement = event.shiftKey
log('enter') // Shift-return inserts before -- only way to add to top of pad.
if (before) {
queue = kb.any(undefined, PAD('next'), chunk)
queueProperty = 'newlinesAfter'
} else {
queue = kb.any(chunk, PAD('next'))
queueProperty = 'newlinesBefore'
}
queue[queueProperty] = queue[queueProperty] || 0
queue[queueProperty] += 1
if (queue[queueProperty] > 1) {
log(' queueing newline queue = ' + queue[queueProperty])
return
}
log(' go ahead line before ' + queue[queueProperty])
newChunk(part, before) // was document.activeElement
break
}
case 8: // Delete
if (part.value.length === 0) {
log(
'Delete key line ' + chunk.uri.slice(-4) + ' state ' + part.state
)
switch (part.state) {
case 1: // contents being sent
case 2: // contents need to be sent again
part.state = 4 // delete me
return
case 3: // being deleted already
case 4: // already deleme state
return
case undefined:
case 0:
part.state = 3 // being deleted
removePart(part)
event.preventDefault()
break // continue
default:
throw new Error('pad: Unexpected state ' + part)
}
}
break
case 9: // Tab
{
const delta = event.shiftKey ? -1 : 1
changeIndent(part, chunk, delta)
event.preventDefault() // default is to highlight next field
break
}
case 27: // ESC
log('escape')
updater.requestDownstreamAction(padDoc, reloadAndSync)
event.preventDefault()
break
case 38: // Up
if (part.parentNode.previousSibling) {
part.parentNode.previousSibling.firstChild.focus()
event.preventDefault()
}
break
case 40: // Down
if (part.parentNode.nextSibling) {
part.parentNode.nextSibling.firstChild.focus()
event.preventDefault()
}
break
default:
}
})
const updateStore = function (part: NotepadPart) {
const chunk: any = part.subject
setPartStyle(part, undefined, true)
const old = (kb.any(chunk, ns.sioc('content')) as any).value
const del = [st(chunk, ns.sioc('content'), old, padDoc)]
let ins
if (part.value) {
ins = [st(chunk, ns.sioc('content'), part.value as any, padDoc)]
}
const newOne = part.value
// DEBUGGING ONLY
if (part.lastSent) {
if (old !== part.lastSent) {
throw new Error(
"Out of order, last sent expected '" +
old +
"' but found '" +
part.lastSent +
"'"
)
}
}
part.lastSent = newOne
/* console.log(
' Patch proposed to ' +
chunk.uri.slice(-4) +
" '" +
old +
"' -> '" +
newOne +
"' "
) */
if (!updater) {
throw new Error('no updater')
}
updater.update(del, ins, function (uri, ok, errorBody, xhr) {
if (!ok) {
// alert("clash " + errorBody);
log(
' patch FAILED ' +
(xhr as any).status +
" for '" +
old +
"' -> '" +
newOne +
"': " +
errorBody
)
if ((xhr as any).status === 409) {
// Conflict - @@ we assume someone else
setPartStyle(part, 'color: black; background-color: #fdd;')
part.state = 0 // Needs downstream refresh
beep(0.5, 512) // Ooops clash with other person
setTimeout(function () {
updater.requestDownstreamAction(padDoc, reloadAndSync)
}, 1000)
} else {
setPartStyle(part, 'color: black; background-color: #fdd;') // failed pink
part.state = 0
complain(
' Error ' + (xhr as any).status + ' sending data: ' + errorBody,
true
)
beep(1.0, 128) // Other
// @@@ Do soemthing more serious with other errors eg auth, etc
}
} else {
clearStatus(true) // upstream
setPartStyle(part) // synced
log(" Patch ok '" + old + "' -> '" + newOne + "' ")
if (part.state === 4) {
// delete me
part.state = 3
removePart(part)
} else if (part.state === 3) {
// being deleted
// pass
} else if (part.state === 2) {
part.state = 1 // pending: lock
updateStore(part)
} else {
part.state = 0 // clear lock
}
}
})
}
part.addEventListener('input', function inputChangeListener (_event) {
// debug.log("input changed "+part.value);
setPartStyle(part, undefined, true) // grey out - not synced
log(
'Input event state ' + part.state + " value '" + part.value + "'"
)
switch (part.state) {
case 3: // being deleted
return
case 4: // needs to be deleted
return
case 2: // needs content updating, we know
return
case 1:
part.state = 2 // lag we need another patch
return
case 0:
case undefined:
part.state = 1 // being upadted
updateStore(part)
}
}) // listener
} // addlisteners
// @@ TODO Need to research before as it appears to be used as an Element and a boolean
const newPartAfter = function (tr1: HTMLTableElement, chunk: String, before?: NotepadElement | boolean) {
// @@ take chunk and add listeners
let text: any = kb.any(chunk as any, ns.sioc('content'))
text = text ? text.value : ''
const tr = dom.createElement('tr')
if (before) {
table.insertBefore(tr, tr1)
} else {
// after
if (tr1 && tr1.nextSibling) {
table.insertBefore(tr, tr1.nextSibling)
} else {
table.appendChild(tr)
}
}
const part: any = tr.appendChild(dom.createElement('input'))
part.subject = chunk
part.setAttribute('type', 'text')
part.value = text
if (me) {
setPartStyle(part, '')
addListeners(part, chunk)
} else {
setPartStyle(part, 'color: #222; background-color: #fff')
log("Note can't add listeners - not logged in")
}
return part
}
/* @@ TODO we need to look at indent, it can be a Number or an Object this doesn't seem correct.
*/
const newChunk = function (ele?: NotepadElement, before?: NotepadElement) {
// element of chunk being split
const kb = store
let indent: any = 0
let queueProperty: string | null = null
let here, prev, next, queue, tr1: any
if (ele) {
if (ele.tagName.toLowerCase() !== 'input') {
log('return pressed when current document is: ' + ele.tagName)
}
here = ele.subject
indent = kb.any(here, PAD('indent'))
indent = indent ? Number(indent.value) : 0
if (before) {
prev = kb.any(undefined, PAD('next'), here)
next = here
queue = prev
queueProperty = 'newlinesAfter'
} else {
prev = here
next = kb.any(here, PAD('next'))
queue = next
queueProperty = 'newlinesBefore'
}
tr1 = ele.parentNode
} else {
prev = subject
next = subject
tr1 = undefined
}
const chunk = newThing(padDoc)
const label = chunk.uri.slice(-4)
const del = [st(prev, PAD('next'), next, padDoc)]
const ins = [
st(prev, PAD('next'), chunk, padDoc),
st(chunk, PAD('next'), next, padDoc),
st(chunk, ns.dc('author'), me, padDoc),
st(chunk, ns.sioc('content'), '' as any, padDoc)
]
if (indent > 0) {
// Do not inherit
ins.push(st(chunk, PAD('indent'), indent, padDoc))
}
log(' Fresh chunk ' + label + ' proposed')
if (!updater) {
throw new Error('no updater')
}
updater.update(del, ins, function (uri, ok, errorBody, _xhr) {
if (!ok) {
// alert("Error writing new line " + label + ": " + errorBody);
log(' ERROR writing new line ' + label + ': ' + errorBody)
} else {
const newPart = newPartAfter(tr1, chunk, before)
setPartStyle(newPart)
newPart.focus() // Note this is delayed
if (queueProperty) {
log(
' Fresh chunk ' +
label +
' updated, queue = ' +
queue[queueProperty]
)
queue[queueProperty] -= 1
if (queue[queueProperty] > 0) {
log(
' Implementing queued newlines = ' + next.newLinesBefore
)
newChunk(newPart, before)
}
}
}
})
}
const consistencyCheck = function () {
const found: { [uri: string]: boolean } = {}
let failed = 0
function complain2 (msg) {
complain(msg)
failed++
}
if (!kb.the(subject, PAD('next'))) {
complain2('No initial next pointer')
return false // can't do linked list
}
// var chunk = kb.the(subject, PAD('next'))
let prev = subject
let chunk
for (; ;) {
chunk = kb.the(prev, PAD('next'))
if (!chunk) {
complain2('No next pointer from ' + prev)
}
if (chunk.sameTerm(subject)) {
break
}
prev = chunk
const label = chunk.uri.split('#')[1]
if (found[chunk.uri]) {
complain2('Loop!')
return false
}
found[chunk.uri] = true
let k = kb.each(chunk, PAD('next')).length
if (k !== 1) {
complain2('Should be 1 not ' + k + ' next pointer for ' + label)
}
k = kb.each(chunk, PAD('indent')).length
if (k > 1) {
complain2('Should be 0 or 1 not ' + k + ' indent for ' + label)
}
k = kb.each(chunk, ns.sioc('content')).length
if (k !== 1) {
complain2('Should be 1 not ' + k + ' contents for ' + label)
}
k = kb.each(chunk, ns.dc('author')).length
if (k !== 1) {
complain2('Should be 1 not ' + k + ' author for ' + label)
}
const sts = kb.statementsMatching(undefined, ns.sioc('contents'))
sts.forEach(function (st) {
if (!found[st.subject.value]) {
complain2('Loose chunk! ' + st.subject.value)
}
})
}
return !failed
}
// Ensure that the display matches the current state of the
// @@ TODO really need to refactor this so that we don't need to cast types
const sync = function () {
// var first = kb.the(subject, PAD('next'))
if (kb.each(subject, PAD('next')).length !== 1) {
const msg =
'Pad: Inconsistent data - NEXT pointers: ' +
kb.each(subject, PAD('next')).length
log(msg)
if ((options as notepadOptions).statusArea) {
((options as notepadOptions).statusArea as HTMLElement).textContent += msg
}
return
}
// var last = kb.the(undefined, PAD('previous'), subject)
// var chunk = first // = kb.the(subject, PAD('next'));
let row
// First see which of the logical chunks have existing physical manifestations
const manif: any = []
// Find which lines correspond to existing chunks
for (
let chunk = kb.the(subject, PAD('next')) as unknown as any;
!chunk.sameTerm(subject);
chunk = kb.the(chunk, PAD('next'))
) {
for (let i = 0; i < table.children.length; i++) {
const tr: any = table.children[i]
if (tr.firstChild) {
if (tr.firstChild.subject.sameTerm(chunk)) {
manif[chunk.uri] = tr.firstChild
}
}
}
}
// Remove any deleted lines
for (let i = table.children.length - 1; i >= 0; i--) {
row = table.children[i]
if (!manif[row.firstChild.subject.uri]) {
table.removeChild(row)
}
}
// Insert any new lines and update old ones
row = table.firstChild // might be null
for (
let chunk = kb.the(subject, PAD('next')) as unknown as any;
!chunk.sameTerm(subject);
chunk = kb.the(chunk, PAD('next'))
) {
const text = (kb.any(chunk, ns.sioc('content')) as any).value
// superstitious -- don't mess with unchanged input fields
// which may be selected by the user
if (row && manif[chunk.uri]) {
const part = row.firstChild
if (text !== part.value) {
part.value = text
}
setPartStyle(part)
part.state = 0 // Clear the state machine
delete part.lastSent // DEBUG ONLY
row = row.nextSibling
} else {
newPartAfter(row, chunk, true) // actually before
}
}
}
// Refresh the DOM tree
const refreshTree = function (root) {
if (root.refresh) {
root.refresh()
return
}
for (let i = 0; i < root.children.length; i++) {
refreshTree(root.children[i])
}
}
let reloading = false
const checkAndSync = function () {
log(' reloaded OK')
clearStatus()
if (!consistencyCheck()) {
complain('CONSITENCY CHECK FAILED')
} else {
refreshTree(table)
}
}
const reloadAndSync = function () {
if (reloading) {
log(' Already reloading - stop')
return // once only needed
}
reloading = true
let retryTimeout = 1000 // ms
const tryReload = function () {
log('try reload - timeout = ' + retryTimeout)
if (!updater) {
throw new Error('no updater')
}
updater.reload(updater.store, padDoc, function (ok, message, xhr) {
reloading = false
if (ok) {
checkAndSync()
} else {
if ((xhr as any).status === 0) {
complain(
'Network error refreshing the pad. Retrying in ' +
retryTimeout / 1000
)
reloading = true
retryTimeout = retryTimeout * 2
setTimeout(tryReload, retryTimeout)
} else {
complain(
'Error ' +
(xhr as any).status +
'refreshing the pad:' +
message +
'. Stopped. ' +
padDoc
)
}
}
})
}
tryReload()
}
table.refresh = sync // Catch downward propagating refresh events
table.reloadAndSync = reloadAndSync
if (!me) log('Warning: must be logged in for pad to be edited')
if (exists) {
log('Existing pad.')
if (consistencyCheck()) {
sync()
if (kb.holds(subject, PAD('next'), subject)) {
// Empty list untenable
newChunk() // require at least one line
}
} else {
log((table.textContent = 'Inconsistent data. Abort'))
}
} else {
// Make new pad
log('No pad exists - making new one.')
const insertables = [
st(subject, ns.rdf('type'), PAD('Notepad'), padDoc),
st(subject, ns.dc('author'), me, padDoc),
st(subject, ns.dc('created'), new Date() as any, padDoc),
st(subject, PAD('next'), subject, padDoc)
]
if (!updater) {
throw new Error('no updater')
}
updater.update([], insertables, function (uri: string | null | undefined, ok: boolean, errorBody?: string) {
if (!ok) {
complain(errorBody || '')
} else {
log('Initial pad created')
newChunk() // Add a first chunck
// getResults();
}
})
}
return table
}
/**
* Get the chunks of the notepad
* They are stored in a RDF linked list
*/
// @ignore exporting this only for the unit test
export function getChunks (subject: NamedNode, kb: IndexedFormula) {
const chunks: any[] = []
for (
let chunk: any = kb.the(subject, PAD('next'));
!chunk.sameTerm(subject);
chunk = kb.the(chunk, PAD('next'))
) {
chunks.push(chunk)
}
return chunks
}
/**
* Encode content to be put in XML or HTML elements
*/
// @ignore exporting this only for the unit test
export function xmlEncode (str) {
return str.replace('&', '&').replace('<', '<').replace('>', '>')
}
/**
* Convert a notepad to HTML
* @param { } pad - the notepad
* @param {store} pad - the data store
*/
export function notepadToHTML (pad: any, kb: IndexedFormula) {
const chunks = getChunks(pad, kb)
let html = '<html>\n <head>\n'
const title = kb.anyValue(pad, ns.dct('title'))
if (title) {
html += ` <title>${xmlEncode(title)}</title>\n`
}
html += ' </head>\n <body>\n'
let level = 0
function increaseLevel (indent) {
for (; level < indent; level++) {
html += '<ul>\n'
}
}
function decreaseLevel (indent) {
for (; level > indent; level--) {
html += '</ul>\n'
}
}
chunks.forEach(chunk => {
const indent = kb.anyJS(chunk, PAD('indent'))
const rawContent = kb.anyJS(chunk, ns.sioc('content'))
if (!rawContent) return // seed chunk is dummy
const content = xmlEncode(rawContent)
if (indent < 0) { // negative indent levels represent heading levels
decreaseLevel(0)
const h = indent >= -3 ? 4 + indent : 1 // -1 -> h4, -2 -> h3
html += `\n<h${h}>${content}</h${h}>\n`
} else { // >= 0
if (indent > 0) { // Lists
decreaseLevel(indent)
increaseLevel(indent)
html += `<li>${content}</li>\n`
} else { // indent 0
decreaseLevel(indent)
html += `<p>${content}</p>\n`
}
}
}) // foreach chunk
// At the end decreaseLevel any open ULs
decreaseLevel(0)
html += ' </body>\n</html>\n'
return html
} | the_stack |
import {
ChangeDetectorRef,
Component,
ComponentFactory,
ComponentFactoryResolver,
ComponentRef,
Input,
OnInit,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import { FormGroup } from '@angular/forms';
import { SFObjectWidgetSchema, SFSelectWidgetSchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzDrawerRef } from 'ng-zorro-antd/drawer';
import { concat } from 'rxjs';
import { map } from 'rxjs/operators';
import { UIDataType } from 'src/app/routes/common/UIDataType';
import { FieldpartComponent, FormField } from '../fieldpart/fieldpart.component';
import { fielddirective } from '../fieldpartdirective';
@Component({
selector: 'app-dynamicformfieldeditor',
templateUrl: './dynamicformfieldeditor.component.html',
styleUrls: ['./dynamicformfieldeditor.component.less'],
})
export class DynamicformfieldeditorComponent implements OnInit {
@Input() id: Number = -1;
@ViewChild(fielddirective, { static: true })
propertitycontainer: fielddirective;
form!: FormGroup;
componentFactory: ComponentFactory<FieldpartComponent>;
viewContainerRef: ViewContainerRef;
FieldDatas: FieldData[] = [];
SuportType: UIDataType[] = [];
AllControlType: any = [];
AllSuportType: any = [];
constructor(private componentFactoryResolver: ComponentFactoryResolver, private http: _HttpClient, private cd: ChangeDetectorRef, private drawerRef: NzDrawerRef<string>) {}
ngOnDestroy(): void {}
ngOnInit(): void {
this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(FieldpartComponent);
this.viewContainerRef = this.propertitycontainer.viewContainerRef;
//一定要顺序发射指令
concat(
this.http.post('api/dictionary/index', { DictionaryGroupId: 2, pi: 0, ps: 20, limit: 20, offset: 0 }).pipe(
map((x) => {
this.AllSuportType = x.data.rows.map((x) => {
return { label: x.dictionaryName, value: x.dictionaryValue };
});
}),
),
this.http.post('api/dictionary/index', { DictionaryGroupId: 1, pi: 0, ps: 20, limit: 20, offset: 0 }).pipe(
map((x) => {
this.AllControlType = x.data.rows.map((x) => {
return { label: x.dictionaryName, value: x.dictionaryValue };
});
}),
),
this.http.get('api/dynamicforminfo/getParams?id=' + this.id).pipe(
map((x) => {
if (x.data.propdata) {
x.data.propdata = x.data.propdata.map((x) => {
return {
FieldId: x.fieldId,
FieldName: x.fieldName,
FieldValue: x.fieldValue,
FieldValueType: x.fieldValueType,
FieldValueDataSource: x.fieldValueDataSource,
FieldUIElementSchema: x.fieldUIElementSchema,
FieldUIElement: x.fieldUIElement,
FieldCode: x.fieldCode,
FieldUnit: x.fieldUnit,
IsRequired: x.isRequired,
};
});
for (var i = 0; i < x.data.propdata.length; i++) {
//始终从头插入
const componentRef = this.viewContainerRef.createComponent<FieldpartComponent>(this.componentFactory, 0);
let key = this.makeString();
componentRef.instance.AllSuportType = this.AllSuportType;
componentRef.instance.AllControlType = this.AllControlType;
let field = new FormField(
key,
x.data.propdata[i].FieldId,
x.data.propdata[i].FieldName,
x.data.propdata[i].FieldValue,
x.data.propdata[i].FieldValueType,
x.data.propdata[i].FieldValueDataSource,
x.data.propdata[i].FieldUIElementSchema,
x.data.propdata[i].FieldUIElement + '',
x.data.propdata[i].FieldUnit,
{
properties: this.createschema(x.data.propdata[i].FieldUIElement, x.data.propdata[i].FieldUIElementSchema),
},
{},
// () => {},
x.data.propdata[i].FieldCode,
x.data.propdata[i].IsRequired,
);
console.log( field)
componentRef.instance.FormField = field;
componentRef.instance.OnRemove.subscribe((x) => {
var index = this.FieldDatas.findIndex((c) => c.Key == x.Key);
if (index > -1) {
this.viewContainerRef.remove(index);
this.FieldDatas.splice(index, 1);
this.cd.detectChanges();
}
});
this.FieldDatas = [new FieldData(field, componentRef, key), ...this.FieldDatas];
}
}
this.cd.detectChanges();
}),
),
).subscribe();
}
creat() {
let key = this.makeString();
const componentRef = this.viewContainerRef.createComponent<FieldpartComponent>(this.componentFactory, 0);
let e = new FormField(
key,
0,
'',
'',
'0',
'',
'',
'0',
'',
{
properties: {},
},
{},
// () => {},
'',
false,
);
componentRef.instance.AllSuportType = this.AllSuportType;
componentRef.instance.FormField = e;
componentRef.instance.AllControlType = this.AllControlType;
componentRef.instance.OnRemove.subscribe((x) => {
var index = this.FieldDatas.findIndex((c) => c.Key == x.Key);
if (index > -1) {
this.viewContainerRef.remove(index);
this.FieldDatas.splice(index, 1);
this.cd.detectChanges();
}
});
this.FieldDatas = [new FieldData(e, componentRef, key), ...this.FieldDatas];
}
saveData() {
var keys: string[] = [];
for (let item of this.FieldDatas) {
if (!item.prop.FieldName) {
item.prop.FieldCodenzValidatingTip = '参数名称不能为空';
item.prop.FieldCodenzValidateStatus = 'error';
item.componentRef.location.nativeElement.scrollIntoView();
return;
}
if (!item.prop.FieldCode) {
item.prop.FieldCodenzValidatingTip = '索引不能为空';
item.prop.FieldCodenzValidateStatus = 'error';
item.componentRef.location.nativeElement.scrollIntoView();
return;
}
if (keys.filter((x) => x == item.prop.FieldCode).length > 0) {
item.prop.FieldCodenzValidatingTip = '索引重复';
item.prop.FieldCodenzValidateStatus = 'error';
item.componentRef.location.nativeElement.scrollIntoView();
return;
} else {
keys = [...keys, item.prop.FieldCode];
}
item.componentRef.instance.submit();
}
// of(...this.ParamDatas)
// .pipe(
// groupBy((x) => x.prop.DeviceTypeParamCode),
// mergeMap((group$) => group$.pipe(reduce((acc, cur) => [...acc, cur], []))),
// )
// .subscribe((x) => {
// });
this.http
.post('api/dynamicforminfo/saveparams', {
Id: this.id,
propdata: this.FieldDatas.map((x) => {
return {
FieldId: x.prop.FieldId,
FieldName: x.prop.FieldName,
FieldUIElementSchema: JSON.stringify(x.prop.formdata),
FieldValue: x.prop.FieldValue,
FieldValueDataSource: x.prop.FieldValueDataSource,
FieldValueType: x.prop.FieldValueType,
FieldUIElement: x.prop.FieldUIElement,
FieldCode: x.prop.FieldCode,
FieldUnit: x.prop.FieldUnit,
IsRequired: x.prop.IsRequired,
};
}),
})
.subscribe(
(x) => {},
(y) => {},
() => { this.drawerRef.close(this.id);},
);
}
makeString(): string {
let outString: string = '';
let inOptions: string = 'abcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 32; i++) {
outString += inOptions.charAt(Math.floor(Math.random() * inOptions.length));
}
return outString;
}
private createschema(type: Number, schema: string): any {
let Schema = JSON.parse(schema);
switch (type) {
case 1:
return {
exclusiveMinimum: {
type: 'boolean',
title: '是否有最小值限制',
default: Schema.exclusiveMinimum,
},
exclusiveMaximum: {
type: 'boolean',
title: '是否有最大值限制',
default: Schema.exclusiveMaximum,
},
minimum: {
type: 'number',
title: '最小值',
maxLength: 20,
minLength: 1,
default: Schema.minimum,
},
maximum: {
type: 'number',
title: '最大值',
maxLength: 20,
minLength: 1,
default: Schema.maximum,
},
ui: {
title: 'UI属性',
type: 'object',
properties: {
widgetWidth: {
type: 'number',
title: '宽度',
default: Schema.ui.widgetWidth,
},
},
ui: {
type: 'card',
} as SFObjectWidgetSchema,
},
};
break;
case 2:
return {
maxLength: {
type: 'number',
title: '字符长度限制',
default: Schema.maxLength,
},
pattern: {
type: 'string',
title: '校验正则表达式',
maxLength: 50,
minLength: 1,
default: Schema.pattern,
},
ui: {
title: 'UI属性',
type: 'object',
properties: {
addOnAfter: {
type: 'string',
title: '后缀',
maxLength: 20,
minLength: 1,
default: Schema.ui.addOnAfter,
},
placeholder: {
type: 'string',
title: 'placeholder',
maxLength: 20,
minLength: 1,
default: Schema.ui.placeholder,
},
},
ui: {
type: 'card',
} as SFObjectWidgetSchema,
},
};
break;
case 3:
return {};
break;
case 4:
return {};
break;
case 5:
return {
ui: {
title: 'UI属性',
type: 'object',
properties: {
checkedChildren: {
type: 'string',
title: '打开值',
maxLength: 20,
minLength: 1,
default: Schema.ui.checkedChildren,
},
unCheckedChildren: {
type: 'string',
title: '关闭值',
maxLength: 20,
minLength: 1,
default: Schema.ui.unCheckedChildren,
},
},
ui: {
type: 'card',
} as SFObjectWidgetSchema,
},
};
break;
case 6:
return {
ui: {
title: 'UI属性',
type: 'object',
properties: {
span: {
type: 'number',
title: '每个选框单元格数量',
default: Schema.ui.span,
},
styleType: {
type: 'string',
title: 'radio的样式',
default: Schema.ui.styleType,
enum: [
{ label: '默认', value: 'default' },
{ label: '按钮', value: 'button' },
],
},
checkAll: {
type: 'boolean',
title: '是否需要全选',
default: Schema.ui.checkAll,
},
},
ui: {
type: 'card',
} as SFObjectWidgetSchema,
},
// IotSharp: {
// title: '扩展属性',
// type: 'object',
// ui: {
// type: 'card',
// } as SFObjectWidgetSchema,
// properties: {
// key: {
// type: 'string',
// title: '值',
// default: Schema.IotSharp.key,
// },
// value: {
// type: 'string',
// title: '名称',
// default: Schema.IotSharp.value,
// },
// },
// },
};
break;
case 7:
return {
ui: {
title: 'UI属性',
type: 'object',
properties: {
format: {
type: 'string',
title: '时间格式',
default: Schema.ui.format,
},
use12Hours: {
type: 'boolean',
title: '是否使用12小时',
default: Schema.ui.use12Hours,
},
size: {
type: 'number',
title: '尺寸',
default: Schema.ui.size,
},
},
ui: {
type: 'card',
} as SFObjectWidgetSchema,
},
};
break;
case 8:
return {
ui: {
title: 'UI属性',
type: 'object',
properties: {
styleType: {
type: 'string',
title: 'radio 的样式',
default: Schema.ui.styleType,
enum: [
{ label: '默认', value: 'default' },
{ label: '按钮', value: 'button' },
],
},
buttonStyle: {
type: 'boolean',
title: 'Button风格样式',
default: Schema.ui.buttonStyle,
enum: [
{ label: 'outline', value: 'outline' },
{ label: 'solid', value: 'solid' },
],
},
},
ui: {
type: 'card',
} as SFObjectWidgetSchema,
},
// IotSharp: {
// title: '扩展属性',
// type: 'object',
// ui: {
// type: 'card',
// } as SFObjectWidgetSchema,
// properties: {
// key: {
// default: Schema.IotSharp.key,
// type: 'string',
// title: '值',
// },
// value: {
// default: Schema.IotSharp.value,
// type: 'string',
// title: '名称',
// },
// },
// },
};
break;
case 9:
return {
IotSharp: {
title: '扩展属性',
type: 'object',
ui: {
change: (item) => {
this.GetTargetType('9', item);
},
type: 'card',
} as SFObjectWidgetSchema,
properties: {
format: {
default: Schema.IotSharp.format,
type: 'string',
title: '格式',
enum: [
{ label: '时间日期', value: 'date-time' },
{ label: '日期', value: 'date' },
{ label: '年月', value: 'month' },
{ label: '年', value: 'yyyy' },
{ label: '周', value: 'week' },
{ label: '区间', value: 'range' },
{ label: 'Inline显示', value: 'Inline' },
],
},
},
},
};
break;
case 10:
return {
ui: {
title: 'UI属性',
type: 'object',
properties: {
placeholder: {
default: Schema.ui.placeholder,
type: 'string',
title: 'placeholder',
},
format: {
default: Schema.ui.format,
type: 'string',
title: '数据格式化',
},
utcEpoch: { default: Schema.ui.utcEpoch, type: 'boolean', title: '是否UTC' },
allowEmpty: { default: Schema.ui.allowEmpty, type: 'boolean', title: '否展示清除按钮' },
use12Hours: { default: Schema.ui.use12Hours, type: 'boolean', title: '使用12小时' },
},
ui: {
type: 'card',
} as SFObjectWidgetSchema,
},
};
break;
case 11:
if (!Schema.ui) {
Schema.ui = {};
}
return {
minimum: {
type: 'number',
title: '最小值',
default: Schema.minimum,
},
maximum: {
type: 'number',
title: '最大值',
default: Schema.maximum,
},
multipleOf: {
type: 'number',
title: '值',
default: Schema.multipleOf ? Schema.multipleOf : 1,
},
ui: {
title: 'UI属性',
type: 'object',
properties: {
range: {
//布尔值开关没有Change事件
type: 'boolean',
title: '开启双滑块',
default: Schema.ui.range ? Schema.ui.range : false,
enum: [
{ label: '是', value: true },
{ label: '否', value: false },
],
ui: {
widget: 'select',
change: (value, orgData) => {
if (value) {
} else {
}
},
} as SFSelectWidgetSchema,
},
vertical: {
type: 'boolean',
title: '是否垂直',
default: Schema.ui.vertical ? Schema.ui.vertical : false,
},
},
ui: {
type: 'card',
} as SFObjectWidgetSchema,
},
};
break;
case 12:
return {
IotSharp: {
title: '扩展属性',
type: 'object',
ui: {
type: 'card',
} as SFObjectWidgetSchema,
properties: {
// key: {
// type: 'string',
// title: '值',
// default: Schema.IotSharp.key,
// },
// value: {
// type: 'string',
// title: '名称',
// default: Schema.IotSharp.value,
// },
allowsearch: {
type: 'boolean',
title: '是否支持搜索',
default: Schema.IotSharp ? Schema.IotSharp.allowsearch : false,
},
},
},
};
break;
case 13:
return {};
break;
case 14:
return {
// IotSharp: {
// title: '扩展属性',
// type: 'object',
// ui: {
// type: 'card',
// } as SFObjectWidgetSchema,
// properties: {
// key: {
// type: 'string',
// title: '值',
// default: Schema.IotSharp.key,
// },
// value: {
// type: 'string',
// title: '名称',
// default: Schema.IotSharp.value,
// },
// parent: {
// type: 'string',
// title: '父级Id',
// default: Schema.IotSharp.parent,
// },
// },
// },
};
break;
case 15:
return {
// IotSharp: {
// title: '扩展属性',
// type: 'object',
// ui: {
// type: 'card',
// } as SFObjectWidgetSchema,
// properties: {
// key: {
// type: 'string',
// title: '值',
// default: Schema.IotSharp.key,
// },
// value: {
// type: 'string',
// title: '名称',
// default: Schema.IotSharp.value,
// },
// parent: {
// type: 'string',
// title: '名称',
// default: Schema.IotSharp.parent,
// },
// },
// },
};
break;
case 16:
return {
ui: {
title: 'UI属性',
type: 'object',
properties: {
format: {
type: 'string',
title: '上传方式',
default: Schema.ui.format,
enum: [
{ label: '选择', value: 'select' },
{ label: '拖放', value: 'drag' },
],
},
action: {
type: 'string',
title: '上传地址',
default: Schema.ui.action ? Schema.ui.action : 'api/common/attachment/upLoaderFile',
},
text: {
type: 'string',
title: '按钮文本',
default: Schema.ui.text,
},
fileSize: {
type: 'number',
title: '文件大小限制(kb)',
default: Schema.ui.fileSize,
},
fileType: {
type: 'string',
title: '文件类型',
default: Schema.ui.fileType,
enum: [
{ label: '不限', value: '' },
{ label: 'png', value: 'image/png' },
{ label: 'jpeg', value: 'image/jpeg' },
{ label: 'gif', value: 'image/gif' },
{ label: 'bmp', value: 'image/bmp' },
],
},
multiple: {
type: 'boolean',
title: '允许多上传',
default: Schema.ui.multiple,
},
},
ui: {
type: 'card',
} as SFObjectWidgetSchema,
},
};
break;
case 17:
return {
maxLength: {
title: '表单最大长度',
type: 'number',
default: Schema.maxLength,
},
ui: {
title: 'UI属性',
type: 'object',
properties: {
borderless: {
title: '隐藏边框',
type: 'boolean',
default: Schema.ui.borderless,
},
placeholder: {
title: 'placeholder',
type: 'string',
default: Schema.ui.placeholder,
},
autosize: {
type: 'object',
title: '自适应内容高度',
properties: {
minRows: {
type: 'number',
title: '最小行',
default: Schema.ui.autosize.minRows,
},
maxRows: {
type: 'number',
title: '最大行',
default: Schema.ui.autosize.maxRows,
},
},
},
},
ui: {
type: 'card',
} as SFObjectWidgetSchema,
},
};
break;
case 18:
return {};
break;
case 19:
return {
maximum: {
type: 'number',
title: '最大值',
default: Schema.maximum,
},
multipleOf: {
type: 'number',
title: '允许半星',
default: Schema.multipleOf,
enum: [
{ label: '是', value: 0.5 },
{ label: '否', value: 1 },
],
},
};
break;
}
}
GetTargetType(type: string, format: string) {
switch (type) {
case '1':
this.SuportType = this.AllSuportType.filter((c) => c.value === '1' || c.value === '2' || c.value === '3' || c.value === '9');
break;
case '2':
this.SuportType = this.AllSuportType.filter((c) => c.value === '4');
break;
case '3':
this.SuportType = this.AllSuportType.filter((c) => c.value === '4');
break;
case '4':
this.SuportType = this.AllSuportType.filter((c) => c.value === '4');
break;
case '5':
this.SuportType = this.AllSuportType.filter((c) => c.value === '13');
break;
case '6':
this.SuportType = this.AllSuportType.filter(
(c) => c.value === '6' || c.value === '7' || c.value === '8' || c.value === '10' || c.value === '12',
);
break;
case '7':
this.SuportType = this.AllSuportType.filter((c) => c.value === '4');
break;
case '8':
this.SuportType = this.AllSuportType.filter(
(c) => c.value === '1' || c.value === '2' || c.value === '3' || c.value === '4' || c.value === '9',
);
break;
case '9':
switch (format) {
case 'date-time':
this.SuportType = this.AllSuportType.filter((c) => c.value === '5' || c.value === '15');
break;
case 'date':
this.SuportType = this.AllSuportType.filter((c) => c.value === '5' || c.value === '4' || c.value === '15');
break;
case 'month':
this.SuportType = this.AllSuportType.filter((c) => c.value === '5' || c.value === '4' || c.value === '15');
break;
case 'yyyy':
this.SuportType = this.AllSuportType.filter((c) => c.value === '1');
break;
case 'week':
this.SuportType = this.AllSuportType.filter((c) => c.value === '4');
break;
case 'range':
this.SuportType = this.AllSuportType.filter((c) => c.value === '11' || c.value === '7'); //ranger暂时支持 DataTime和String,
break;
case 'Inline':
this.SuportType = this.AllSuportType.filter((c) => c.value === '5' || c.value === '4' || c.value === '15');
break;
}
break;
case '10':
this.SuportType = this.AllSuportType.filter((c) => c.value === '4');
break;
case '11':
switch (format) {
case 'true':
this.SuportType = this.AllSuportType.filter((c) => c.value === '6' || c.value === '8' || c.value === '10' || c.value === '12');
break;
case 'false':
this.SuportType = this.AllSuportType.filter((c) => c.value === '1' || c.value === '2' || c.value === '3' || c.value === '9');
break;
}
break;
case '12':
this.SuportType = this.AllSuportType.filter(
(c) => c.value === '1' || c.value === '2' || c.value === '3' || c.value === '4' || c.value === '9',
);
break;
case '13':
this.SuportType = this.AllSuportType.filter((c) => c.value === '6' || c.value === '8' || c.value === '7' || c.value === '12');
break;
case '14':
this.SuportType = this.AllSuportType.filter((c) => c.value === '6' || c.value === '8' || c.value === '7' || c.value === '12');
break;
case '15':
this.SuportType = this.AllSuportType.filter((c) => c.value === '6' || c.value === '8' || c.value === '7' || c.value === '12');
break;
case '16':
this.SuportType = this.AllSuportType.filter((c) => c.value === '14');
break;
case '17':
this.SuportType = this.AllSuportType.filter((c) => c.value === '4');
break;
case '18':
this.SuportType = this.AllSuportType.filter((c) => c.value === '4');
break;
case '19':
this.SuportType = this.AllSuportType.filter((c) => c.value === '1' || c.value === '2' || c.value === '3' || c.value === '9');
break;
}
// this.AllSuportType.filter(c=>c.value===)
// this.http.get('api/common/dictionaryservice/gettargettype?id=' + type + '&format=' + format).subscribe(
// (x) => {
// this.AllSuportType = x.data;
// },
// (y) => {},
// () => {},
// );
}
}
export class FieldData {
constructor(public prop: FormField, public componentRef: ComponentRef<FieldpartComponent>, public Key: string) {}
} | the_stack |
import File = require("fs");
import Path = require("path");
import ChildProcess = require("child_process");
import Process = require("process");
// Note: The 'import * as Foo from "./Foo' syntax avoids the "compiler re-write problem" that breaks debugger hover inspection
import * as AmbrosiaStorage from "./Storage";
import * as IC from "./ICProcess";
import * as Messages from "./Messages"
import * as Streams from "./Streams";
import * as StringEncoding from "./StringEncoding";
import * as Utils from "./Utils/Utils-Index";
import { RejectedPromise } from "./ICProcess"; // There is no re-write issue here as this is just a type
const LBOPTIONS_SECTION: string = "lbOptions"; // The section name for language binding options in ambrosiaConfig.json
/** The Ambrosia configuration settings loaded from ambrosiaConfig.json (or alternate config file). */
let _loadedConfigFile: AmbrosiaConfigFile;
/** The name of the loaded Ambrosia configuration file (eg. "ambrosiaConfig.json"). */
let _loadedConfigFileName: string = "";
/** The locations where language-binding output can be written. */
export enum OutputLogDestination
{
/** Log to the console. Use this during development/debugging only (it's too slow for production). */
Console = 1,
/** Log to a file in the 'outputLogFolder' specified in ambrosiaConfig.json. use this setting in production (for performance). */
File = 2,
/** Log to both the console and a file. */
ConsoleAndFile = Console | File
}
/** The available hosting modes for the IC. */
export enum ICHostingMode
{
/**
* The IC runs on the same machine as the LB, but without its own console window; the LB automatically starts/stops the IC,
* and the LB output includes the IC output. This is the most commonly used mode.
*/
Integrated,
/**
* The IC runs on the machine specified by icIPv4Address (which can be the local machine) or the local machine if icIPv4Address is omitted,
* in its own console window; the IC must be started explicitly.
* This mode is a rarely used, and renders many options in ambrosiaConfig.json unavailable (ie. they have to be omitted).
*/
Separated
}
/** Class representing IC registration settings, obtained from Azure, that the LB also needs to know. */
export class RegistrationSettings
{
icLogFolder: string | undefined;
icSendPort: number | undefined;
icReceivePort: number | undefined;
/** Note: This registered setting cannot be overridden locally, except when doing 'time-travel debugging' (TTD). */
appVersion: number | undefined;
/** Note: This registered setting can be overridden locally, but only to trigger an upgrade (via re-registration). */
upgradeVersion: number | undefined;
/** Note: This registered setting cannot be overridden locally. */
activeActive: boolean | undefined;
};
/**
* Returns the settings from the loaded configuration file.\
* Throws if called before initialize()/initializeAsync().
*/
export function loadedConfig(): AmbrosiaConfigFile
{
if (!_loadedConfigFile)
{
throw new Error("Ambrosia.initialize() / initializeAsync() has not been called");
}
return (_loadedConfigFile);
}
/**
* Returns the name of the loaded configuration file, which may include a path.\
* Will return null if called before initialize()/initializeAsync().
*/
export function loadedConfigFileName(): string | null
{
return (_loadedConfigFileName || null);
}
/** The storage types that IC logs can be persisted in. */
export enum LogStorageType
{
/** OS file storage. */
Files = 0,
/** Azure blob storage. Uses the same storage account as CRA (the AZURE_STORAGE_CONN_STRING environment variable). */
Blobs = 1
}
/** The types of application code that can be active (in use). */
export enum ActiveCodeType
{
/** Pre-upgrade application code. */
VCurrent = 0,
/** Post-upgrade application code. */
VNext = 1
}
/** The additional types (other than true or false) of instance auto-registration that can be performed (at startup). */
export enum AutoRegisterType
{
/** Perform auto-registration, and then immediately exit the program. */
TrueAndExit = 0
}
/** Class representing the configuration settings loaded from ambrosiaConfig.json (or alternate config file). */
export class AmbrosiaConfigFile
{
// Indexer (for 'noImplicitAny' compliance), although this does end up hiding ts(2551): "Property 'xxxxx' does not exist on type 'AmbrosiaConfigFile'"
[key: string]: unknown;
public static readonly DEFAULT_FILENAME: string = "ambrosiaConfig.json";
private _requiredProperties: string[] = ["instanceName", "icCraPort"];
private _propertiesOnlyForIntegratedIC: string[] = ["icLogStorageType", "icLogFolder", "icBinFolder", "useNetCore", "debugStartCheckpoint", "debugTestUpgrade",
"logTriggerSizeInMB", "secureNetworkAssemblyName", "secureNetworkClassName",
"appVersion", "upgradeVersion", "autoRegister", "lbOptions.deleteLogs"];
private _inConstructor: boolean = false; // Whether the AmbrosiaConfigFile constructor is currently executing
private _allRegistrationOverridesSet: boolean = false; // Whether all the registration settings [that the LB also needs to know about] have been set in ambrosiaConfig.json
private _configuredProperties: string[] = []; // The list of properties that have been set in ambrosiConfig.json
private _isFirstStartAfterInitialRegistration: boolean = false; // Computed at runtime, not a setting in ambrosiaConfig.json
private _instanceName: string = "";
private _icCraPort: number = -1;
private _icReceivePort: number = -1;
private _icSendPort: number = -1;
private _icLogFolder: string = "";
private _icLogStorageType: keyof typeof LogStorageType = LogStorageType[LogStorageType.Files] as keyof typeof LogStorageType;
private _icBinFolder: string = "";
private _icIPv4Address: string = "";
private _icHostingMode: ICHostingMode = ICHostingMode.Integrated;
private _useNetCore: boolean = false;
private _debugStartCheckpoint: number = 0;
private _debugTestUpgrade: boolean = false;
private _logTriggerSizeInMB: number = 0;
private _isActiveActive: boolean = false;
private _replicaNumber: number = 0;
private _appVersion: number = 0;
private _upgradeVersion: number = 0;
private _activeCode: ActiveCodeType = ActiveCodeType.VCurrent;
private _autoRegister: boolean | AutoRegisterType = false;
private _secureNetworkAssemblyName: string = "";
private _secureNetworkClassName: string = "";
private _lbOptions: LanguageBindingOptions = new LanguageBindingOptions(this); // In case the the LBOPTIONS_SECTION is omitted from ambrosiaConfig.json
/** [ReadOnly] Whether this is the first run of the instance following its initial registration. Note: This is computed at runtime, and the property setter is for internal use only. */
get isFirstStartAfterInitialRegistration(): boolean { return (this._isFirstStartAfterInitialRegistration); }
set isFirstStartAfterInitialRegistration(value: boolean) { this._isFirstStartAfterInitialRegistration = value; }
/** [ReadOnly][Required] The name this Ambrosia Immortal instance will be referred to by all instances (including itself). MUST match the value used during 'RegisterInstance'. */
get instanceName(): string { return (this._instanceName); }
/** [ReadOnly][Required] The port number that the Common Runtime for Applications (CRA) layer uses. */
get icCraPort(): number { return (this._icCraPort); }
/** [ReadOnly] The port number that the Immortal Coordinator (IC) receives on. If not provided, it will be read from the registration. */
get icReceivePort(): number { return (this._icReceivePort); }
/** [ReadOnly] The port number that the Immortal Coordinator (IC) sends on. If not provided, it will be read from the registration. */
get icSendPort(): number { return (this._icSendPort); }
/** [ReadOnly] The folder where the Immortal Coordinator (IC) will write its logs (or read logs from if doing "time-travel debugging"). If not provided, it will be read from the registration. */
get icLogFolder(): string { return (this._icLogFolder); }
/**
* [ReadOnly] The storage type that the Immortal Coordinator (IC) logs will be persisted in.\
* When set to "Blobs", the logs are written to Azure storage (using AZURE_STORAGE_CONN_STRING) in the "Blob Containers\ambrosialogs" container.
* The icLogFolder can either be set to an empty string, or (rarely) to a desired sub-path under "ambrosialogs", eg. "TestLogs/Group1".
*/
get icLogStorageType(): keyof typeof LogStorageType { this.onlyAppliesToIntegratedICHostingMode(); return (this._icLogStorageType); }
/** [ReadOnly] The folder where the Immortal Coordinator (IC) binaries exist. If not specified, the 'AMBROSIATOOLS' environment variable will be used. */
get icBinFolder(): string { this.onlyAppliesToIntegratedICHostingMode(); return (this._icBinFolder); }
/** An override IPv4 address for the Immortal Coordinator (IC) to use instead of the local IPv4 address. */
get icIPv4Address(): string { return (this._icIPv4Address); }
/**
* [ReadOnly] The hosting mode for the Immortal Coordinator (IC), which affects where and how the IC runs. Defaults to ICHostingMode.Integrated.\
* If not explicitly set, the value will be computed based on the value provided for 'icIPv4Address'.
*/
get icHostingMode(): ICHostingMode { return (this._icHostingMode); }
/** [ReadOnly] Whether to use .NET Core (instead of .Net Framework) to run the Immortal Coordinator (IC) [this is a Windows-only option]. Defaults to false. */
get useNetCore(): boolean { this.onlyAppliesToIntegratedICHostingMode(); return (Utils.isWindows() ? this._useNetCore : false); }
/** [ReadOnly] The checkpoint number to start "time-travel debugging" from. */
get debugStartCheckpoint(): number { this.onlyAppliesToIntegratedICHostingMode(); return (this._debugStartCheckpoint); }
/** [ReadOnly] Whether to perform a test upgrade (for debugging/testing purposes). Defaults to false. */
get debugTestUpgrade(): boolean { this.onlyAppliesToIntegratedICHostingMode(); return (this._debugTestUpgrade); }
/** [ReadOnly] The size (in MB) the log must reach before the IC will take a checkpoint and start a new log. */
get logTriggerSizeInMB(): number { this.onlyAppliesToIntegratedICHostingMode(); return (this._logTriggerSizeInMB); }
/** [ReadOnly] Whether this [primary] instance will run in an active/active configuration. MUST be set to true when 'replicaNumber' is greater than 0, and MUST match the value used when the instance/replica was registered. */
get isActiveActive(): boolean { return (this._isActiveActive); }
/** [ReadOnly] The replica (secondary) ID this instance will use in an active/active configuration. MUST match the value used when the replica was registered. */
get replicaNumber(): number { return (this._replicaNumber); }
/** [ReadOnly] The name of the .NET assembly used to establish a secure network channel between ICs. */
get secureNetworkAssemblyName(): string { this.onlyAppliesToIntegratedICHostingMode(); return (this._secureNetworkAssemblyName); }
/** [ReadOnly] The name of the .NET class (that implements ISecureStreamConnectionDescriptor) in 'secureNetworkAssemblyName'. */
get secureNetworkClassName(): string { this.onlyAppliesToIntegratedICHostingMode(); return (this._secureNetworkClassName); }
/**
* [ReadOnly] The nominal version of this Immortal instance.\
* Used to identify the log sub-folder name (ie. <icInstanceName>_<appVersion>) that will be logged to (or read from, if debugStartCheckpoint is specified).
*/
// Note: Although 'appVersion' is included in the _propertiesOnlyForIntegratedIC list, we don't call onlyAppliesToIntegratedICHostingMode()
// in its getter because even though it won't be set locally it will still be set by reading from the registration.
get appVersion(): number { return (this._appVersion); }
/** [ReadOnly] The nominal version this Immortal instance should upgrade to at startup. */
// Note: Although 'upgradeVersion' is included in the _propertiesOnlyForIntegratedIC list, we don't call onlyAppliesToIntegratedICHostingMode()
// in its getter because even though it won't be set locally it will still be set by reading from the registration.
get upgradeVersion(): number { return (this._upgradeVersion); }
/** [ReadOnly] The currently active (in use) application code: pre-upgrade is 'VCurrent', post-upgrade is 'VNext'. */
get activeCode(): ActiveCodeType { return (this._activeCode); }
/** [ReadOnly] How to automatically [re]register this Immortal instance at startup. See also: isAutoRegister. */
get autoRegister(): boolean | AutoRegisterType { this.onlyAppliesToIntegratedICHostingMode(); return (this._autoRegister); }
/** [ReadOnly] Options for how the language-binding behaves. */
get lbOptions(): LanguageBindingOptions { return (this._lbOptions); }
/** [Readonly] Whether a "live" upgrade has been requested (by the local configuration). This is a computed setting. */
get isLiveUpgradeRequested(): boolean { return (this.isConfiguredProperty("appVersion") && this.isConfiguredProperty("upgradeVersion") && (this.upgradeVersion > this.appVersion)); }
/**
* [ReadOnly] Whether the icHostingMode setting is 'Integrated'.\
* Note: This computed setting is just for brevity.
*/
get isIntegratedIC(): boolean { return (this.icHostingMode === ICHostingMode.Integrated); }
/** [ReadOnly] Whether Ambrosia is running in 'time-travel debugging' mode. */
get isTimeTravelDebugging(): boolean { return (this.debugStartCheckpoint > 0); }
/** [Readonly] Whether to automatically [re]register this Immortal instance at startup. This is a computed setting. */
get isAutoRegister(): boolean { return ((this.autoRegister === true) || (this.autoRegister === AutoRegisterType.TrueAndExit)); }
constructor(configFileName: string)
{
try
{
this._inConstructor = true;
if (File.existsSync(configFileName))
{
let fileContents: string = File.readFileSync(configFileName, { encoding: "utf8" });
let jsonObj: Utils.SimpleObject = JSON.parse(fileContents);
_loadedConfigFileName = configFileName;
_loadedConfigFile = this;
for (let requiredPropName of this._requiredProperties)
{
if (!jsonObj.hasOwnProperty(requiredPropName))
{
throw new Error(`Required setting '${requiredPropName}' is missing`);
}
}
for (let propName in jsonObj)
{
if (this.hasOwnProperty("_" + propName))
{
if (propName === LBOPTIONS_SECTION)
{
this["_" + propName] = new LanguageBindingOptions(this, jsonObj[propName], true);
Object.keys(jsonObj[propName]).forEach(childPropName => this._configuredProperties.push(`${propName}.${childPropName}`));
}
else
{
this["_" + propName] = jsonObj[propName];
if (typeof jsonObj[propName] === "string")
{
switch (propName)
{
case "icLogStorageType":
// Validate the string enum value
let logStorageType: keyof typeof LogStorageType = jsonObj[propName] as any;
if (LogStorageType[logStorageType] === undefined)
{
throw new Error(`Option '${propName}' has an invalid value ('${logStorageType}'); valid values are: ${Utils.getEnumKeys("LogStorageType", LogStorageType).join(", ")}`);
}
break;
case "icHostingMode":
// Validate the string enum value
let hostingMode: keyof typeof ICHostingMode = jsonObj[propName] as any;
if (ICHostingMode[hostingMode] === undefined)
{
throw new Error(`Option '${propName}' has an invalid value ('${hostingMode}'); valid values are: ${Utils.getEnumKeys("ICHostingMode", ICHostingMode).join(", ")}`);
}
// Note: Unlike _icLogStorageType, we need the actual integer enum value, not the string name of the enum value
this["_" + propName] = ICHostingMode[hostingMode];
break;
case "icIPv4Address":
// Validate the IP address format
let ipAddress: string = jsonObj[propName];
if (!RegExp("^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$").test(ipAddress))
{
throw new Error(`Option '${propName}' has an invalid value ('${ipAddress}')`);
}
break;
case "activeCode":
// Validate the string enum value
let activeCode: keyof typeof ActiveCodeType = jsonObj[propName] as any;
if (ActiveCodeType[activeCode] === undefined)
{
throw new Error(`Option '${propName}' has an invalid value ('${activeCode}'); valid values are: ${Utils.getEnumKeys("ActiveCodeType", ActiveCodeType).join(", ")}`);
}
// Note: Unlike _icLogStorageType, we need the actual integer enum value, not the string name of the enum value
this["_" + propName] = ActiveCodeType[activeCode];
break;
case "autoRegister":
let autoRegisterType: keyof typeof AutoRegisterType = jsonObj[propName] as any;
if (AutoRegisterType[autoRegisterType] === undefined)
{
throw new Error(`Option '${propName}' has an invalid value ('${autoRegisterType}'); valid values are: true, false, "${Utils.getEnumKeys("AutoRegisterType", AutoRegisterType).join("\", \"")}"`);
}
// Note: Unlike _icLogStorageType, we need the actual integer enum value, not the string name of the enum value
this["_" + propName] = AutoRegisterType[autoRegisterType];
break;
}
}
this._configuredProperties.push(propName);
}
}
else
{
// See https://code.visualstudio.com/docs/languages/json.
// for an example, see https://json.schemastore.org/tsconfig. See more examples at https://github.com/SchemaStore/schemastore/blob/master/src/api/json/catalog.json.
if (propName !== "$schema")
{
throw new Error(`'${propName}' is not a valid setting name`)
}
}
}
// Initialize _icHostingMode (if not explicitly provided)
if (!this.isConfiguredProperty("icHostingMode"))
{
if (this.isConfiguredProperty("icIPv4Address"))
{
this._icHostingMode = Utils.isLocalIPAddress(this._icIPv4Address) ? ICHostingMode.Integrated : ICHostingMode.Separated;
}
else
{
this._icHostingMode = ICHostingMode.Integrated;
}
}
if (this.isIntegratedIC && this.icIPv4Address && !Utils.isLocalIPAddress(this.icIPv4Address))
{
throw new Error(`When 'icHostingMode' is set to "${ICHostingMode[ICHostingMode.Integrated]}", the configured 'icIPv4Address' must be a local address (or should be left unspecfied); valid local addresses are: ${Utils.getLocalIPAddresses().join(", ")}`);
}
if (!this.isIntegratedIC)
{
// Disallow settings that only apply when icHostingMode is 'Integrated'.
// Forcing these settings out of ambrosiaConfig.json reduces confusion for the user, and helps simplify our code.
for (const propName of this._configuredProperties)
{
if (this._propertiesOnlyForIntegratedIC.indexOf(propName) !== -1)
{
throw new Error(`The '${propName}' setting must be omitted when 'icHostingMode' is \"${ICHostingMode[this._icHostingMode]}\"`);
}
}
}
if (this.debugStartCheckpoint !== 0)
{
if (this.lbOptions.deleteLogs)
{
throw new Error(`A non-zero 'debugStartCheckpoint' is invalid when 'lbOptions.deleteLogs' is true`);
}
// Verify that the requested checkpoint file exists
let checkpointFileName: string = Path.join(this.icLogFolder, `${this.instanceName}_${this.appVersion}`, `serverchkpt${this.debugStartCheckpoint}`);
if (!File.existsSync(checkpointFileName))
{
throw new Error(`'debugStartCheckpoint' (${this.debugStartCheckpoint}) does not exist (${checkpointFileName})`);
}
}
if (this.debugTestUpgrade && (this.debugStartCheckpoint === 0))
{
throw new Error(`When 'debugTestUpgrade' is true, a non-zero 'debugStartCheckpoint' must also be specified`);
}
if ((this.debugStartCheckpoint !== 0) && !this.isConfiguredProperty("appVersion"))
{
throw new Error(`When a non-zero 'debugStartCheckpoint' is specified, 'appVersion' must also be specified`);
}
if (this.isConfiguredProperty("upgradeVersion") && (this.upgradeVersion < this.appVersion))
{
// "Downgrade" is supported by including the downgraded code (and state downgrade conversion) as VNext, while still using an INCREASED upgradeVersion number
// in RegisterInstance to prepare for the downgrade. If we don't check for this, RegisterInstance will fail with "Current version # exceeds upgrade version #."
throw new Error(`'upgradeVersion' (${this.upgradeVersion}) must be greater than or equal to 'appVersion' (${this.appVersion})`);
}
if (this.isLiveUpgradeRequested)
{
if (!this.isConfiguredProperty("autoRegister") || !this.isConfiguredProperty("appVersion") || !this.isConfiguredProperty("activeCode") || // We're going to update these properties [using updateSetting()] when the upgrade completes, so they need to exist in the config file
this.isAutoRegister || this.debugTestUpgrade || (this.debugStartCheckpoint !== 0) || (this.activeCode !== ActiveCodeType.VCurrent) || this.lbOptions.deleteLogs)
{
throw new Error(`When requesting a "live" upgrade ('upgradeVersion' > 'appVersion') the following settings must be configured: 'autoRegister' to false, 'debugTestUpgrade' to false, 'debugStartCheckpoint' to 0, 'activeCode' to "VCurrent", and 'lbOptions.deleteLogs' to false`);
}
}
if (this.instanceName.trim().length === 0)
{
throw new Error("'instanceName' cannot be empty");
}
if (this.icLogFolder)
{
this._icLogFolder = Utils.ensurePathEndsWithSeparator(this.icLogFolder);
if (this.icLogStorageType === LogStorageType[LogStorageType.Blobs])
{
if (File.existsSync(this.icLogFolder))
{
throw new Error(`When 'icLogStorageType' is "Blobs", the 'icLogFolder' should either be empty or a name of the form "name1/[name2/...]"`);
}
this._icLogFolder = this.icLogFolder.replace(/\/+|[\\]+/g, "/");
}
}
if ((this.secureNetworkAssemblyName && !this.secureNetworkClassName) || (this.secureNetworkClassName && !this.secureNetworkAssemblyName))
{
throw new Error("'secureNetworkAssemblyName' and 'secureNetworkClassName' must be provided together or not at all");
}
if (this.secureNetworkAssemblyName && !File.existsSync(this.secureNetworkAssemblyName))
{
throw new Error(`The specified 'secureNetworkAssemblyName' (${Path.resolve(this.secureNetworkAssemblyName)}) does not exist`);
}
this._allRegistrationOverridesSet = this.isConfiguredProperty("icReceivePort") && this.isConfiguredProperty("icSendPort") && this.isConfiguredProperty("icLogFolder");
if (this.isAutoRegister && !this._allRegistrationOverridesSet)
{
throw new Error(`When 'autoRegister' is true (or "${AutoRegisterType[AutoRegisterType.TrueAndExit]}"), the following settings must also be explicitly set: icReceivePort, icSendPort, icLogFolder`);
}
if ((this.replicaNumber > 0) && !this.isActiveActive)
{
throw new Error(`When 'replicaNumber' (${this.replicaNumber}) is greater than 0, 'isActiveActive' must be set to true`);
}
// This is for convenience, and to provide command-line symmetry with "eraseInstance"
if (Utils.hasCommandLineArg("autoRegister") || Utils.hasCommandLineArg("registerInstance"))
{
if (!this.isIntegratedIC)
{
throw new Error(`The '${Utils.hasCommandLineArg("autoRegister") ? "autoRegister" : "registerInstance"}' command-line parameter can only be used when icHostingMode is '${ICHostingMode[ICHostingMode.Integrated]}'`);
}
if (Utils.hasCommandLineArg("autoRegister")) { this._autoRegister = true; }
if (Utils.hasCommandLineArg("registerInstance")) { this._autoRegister = AutoRegisterType.TrueAndExit; }
}
}
else
{
let howToGetFile: string = Utils.equalIgnoringCase(configFileName, AmbrosiaConfigFile.DEFAULT_FILENAME) ?
"; you can copy this file from .\\node_modules\\ambrosia-node\\ambrosiaConfig.json, and then edit it to match your IC registration. " +
"If using VS2019+ or VSCode to edit the file, copy ambrosiaConfig-schema.json too." : "";
throw new Error(`The file does not exist${howToGetFile}`);
}
}
finally
{
this._inConstructor = false;
}
}
/**
* [Internal] This method should be called by the getter for every setting in the _propertiesOnlyForIntegratedIC list.
* It throws if the getter being called [from outside the constructor] is for a setting that only applies when icHostingMode is 'Integrated'.
* The purpose of throwing is to detect the places [primarily] in the LB code where we need a "if (this.isIntegratedIC)" check.
*/
onlyAppliesToIntegratedICHostingMode(sectionName?: string): void
{
if ((this.icHostingMode !== ICHostingMode.Integrated) && !this._inConstructor)
{
const settingName: string | undefined = new Error().stack?.split("\n")[2].trim().split(" ")[2]; // TODO: Is there a better way?
// Typically, these are settings that we (the LB) need to provide to an Ambrosia binary (eg. ImmortalCoordinator.exe / Ambrosia.exe)
// when we start it; since we don't start the binary when using 'Separated' mode, the setting doesn't apply.
throw new Error(`The '${sectionName ? sectionName + "." : ""}${settingName || "N/A"}' setting only applies when icHostingMode is '${ICHostingMode[ICHostingMode.Integrated]}'`);
}
}
/** Returns true if the specified property name (eg. "logTriggerSizeInMB" or "lbOptions.outputLoggingLevel") has been set in ambrosiaConfig.json. */
isConfiguredProperty(propName: string): boolean
{
for (const configuredPropName of this._configuredProperties)
{
if (Utils.equalIgnoringCase(propName, configuredPropName))
{
return (true);
}
}
return (false);
}
/**
* If needed, updates the [local] configuration settings corresponding to the settings specified at registration (icLogFolder, icSendPort, icReceivePort)
* by asynchronously reading them from Azure, but only if they have NOT been specified locally (via ambrosiaConfig.json).
*/
async initializeAsync(): Promise<void>
{
const connStr: string | undefined = Process.env["AZURE_STORAGE_CONN_STRING"];
if (!connStr || (connStr.trim().length === 0))
{
throw new Error("The 'AZURE_STORAGE_CONN_STRING' environment variable is missing or empty");
}
// If not all of the "primary" registration settings (sendPort/receivePort/logFolder) have been overridden (configured) locally, then we need to query
// the registration settings from Azure so that we know what values to use [so that we can connect to the IC, and to do - if needed - log deletion].
// Additionally, if we're not doing TTD, then we need to either check the locally configured appVersion against the registration settings, or - if
// appVersion has not been configured locally - acquire the appVersion value from the registration settings. We also need to acquire the registered isActiveActive.
// Note: Without checking/acquiring appVersion, we could end up [optionally] deleting from a different log folder (the configured version folder) than
// the one that will actually be used (the registered currentVersion folder), and then reading/writing logs from an unexpected log folder (the
// registered currentVersion folder).
// Note: If we decide to abandon AmbrosiaStorage.getRegistrationSettingsAsync(), then when _allRegistrationOverridesSet is false we'd instead have to
// throw a "Not all required settings have been specified" error here, along with adding all the RegistrationSettings members (including appVersion
// and isActiveActive) to the "required" setting of ambrosiaConfig-schema.json. We'd also have to forego the 'appVersion' checks below, which would
// likely also mean abandoning the lbOptions.deleteLogs feature due to the resulting risks.
Utils.log("Reading registration settings...");
const registrationSettings: RegistrationSettings = await AmbrosiaStorage.getRegistrationSettingsAsync(this.instanceName, this.replicaNumber);
const checkAppVersion: boolean = (this.isIntegratedIC && !this.isTimeTravelDebugging && this.isConfiguredProperty("appVersion")) || !this.isConfiguredProperty("appVersion");
if (checkAppVersion)
{
if (this.isConfiguredProperty("appVersion"))
{
// Check appVersion
// Note: The 'autoRegister' flag gets reset when the re-registration occurs, so if it's true we know that re-registration has not yet happened (but will)
if ((registrationSettings.appVersion !== this.appVersion) && !(this.isIntegratedIC && this.isAutoRegister))
{
// Check if the version mismatch is because of an upgrade. We do this by comparing against the 'value' column of the <InstanceTable>
// where PartitionKey = "(Default)" and RowKey = "CurrentVersion", which gets updated (by the IC) after an upgrade.
const instanceTableCurrentVersion: number = parseInt(await AmbrosiaStorage.readAzureTableColumn(this.instanceName, "value", "(Default)", "CurrentVersion") as string);
if (this.appVersion === instanceTableCurrentVersion)
{
// Note: Typically, this condition won't happen because we set the 'autoRegister' flag to true when the upgrade succeeds
throw new Error(`The instance has been upgraded to version ${instanceTableCurrentVersion}; you must re-register the instance`);
}
else
{
throw new Error(`The configured 'appVersion' (${this.appVersion}) differs from the registered version (${registrationSettings.appVersion}); change 'appVersion' to ${registrationSettings.appVersion}`);
}
}
}
else
{
// Acquire appVersion [so that we can 'autoRegister' (if needed) with the correct value]
this._appVersion = Utils.assertDefined(registrationSettings.appVersion);
}
if (!this.isConfiguredProperty("upgradeVersion"))
{
// Acquire upgradeVersion [so that we can 'autoRegister' (if needed) with the correct value]
this._upgradeVersion = Utils.assertDefined(registrationSettings.upgradeVersion);
}
}
if (this.isIntegratedIC && !this.isTimeTravelDebugging)
{
// We need to know if this the "first start of the instance after initial registration" because in this scenario the IC always throws 2 "informational exceptions".
// TODO: Is there a better (cleaner/faster) way to detect this?
this._isFirstStartAfterInitialRegistration = await AmbrosiaStorage.isFirstStartAfterInitialRegistration(this.instanceName, this.replicaNumber);
}
// Note: These local settings (if set) take precedence over the corresponding registration settings
if (!this.isConfiguredProperty("icLogFolder") && (registrationSettings.icLogFolder !== undefined))
{
this._icLogFolder = registrationSettings.icLogFolder;
}
if (!this.isConfiguredProperty("icSendPort") && (registrationSettings.icSendPort !== undefined))
{
this._icSendPort = registrationSettings.icSendPort;
}
if (!this.isConfiguredProperty("icReceivePort") && (registrationSettings.icReceivePort !== undefined))
{
this._icReceivePort = registrationSettings.icReceivePort;
}
// Because the "activeActive" IC parameter works by its presence or absence (rather than being an overridable "activeActive=" parameter),
// if we omit it (ie. when "isActiveActive: false", or when the setting is omitted) then the registered value will be used [by the IC].
// If the registered value is true, the result (running in active/active when the local config indicates not to) would be unexpected.
// Note that the converse, ("isActiveActive: true" locally but activeActive false in the registration) is not a problem (this override
// would work). But because of this asymmetrical overriding, we simplify and don't allow the configured value to differ from the registered value.
if (registrationSettings.activeActive !== this._isActiveActive)
{
throw new Error(`The configured 'isActiveActive' (${this._isActiveActive}${!this.isConfiguredProperty("isActiveActive") ? " [by omission]" : ""}) does not match the registered value (${registrationSettings.activeActive}); ` +
`you must either change the configured value (to ${registrationSettings.activeActive}) or re-register the instance`);
}
// The ability to have local overrides for icSendPort and/or icReceivePort increases the likelihood of port collisions
if ((this.icCraPort === this.icReceivePort) || (this.icCraPort === this.icSendPort) || (this.icSendPort === this.icReceivePort))
{
throw new Error(`The icCraPort (${this.icCraPort}), icReceivePort (${this.icReceivePort}), and icSendPort (${this.icSendPort}) must all be different`);
}
}
/**
* [Internal] Updates the specified config file setting. The change is applied to both the in-memory setting and the on-disk file.
* The setting MUST already exist in the config file; this method will not add a missing setting to the file.\
* If the 'settingName' requires a path, use '.' as the separator character, eg. "lbOptions.deleteLogs".\
* Note: Many settings are only used at startup, so changing them after calling IC.start() may have no effect until the next restart.\
* **WARNING:** For internal use only. This method does NOT check that the type of 'value' is correct for the setting.
*/
updateSetting(settingName: string, value: number | boolean | string): void
{
const parts: string[] = settingName.split(".");
const targetSettingName: string = parts[parts.length - 1];
let settingGroup: Utils.SimpleObject = this;
// Navigate to the parent setting group
for (let i = 0; i < parts.length - 1; i++)
{
const subGroup: Utils.SimpleObject = settingGroup["_" + parts[i]];
if (subGroup !== undefined)
{
settingGroup = subGroup;
}
else
{
throw new Error(`Unknown AmbrosiaConfigFile setting group '${parts.slice(0, i + 1).join(".")}'`);
}
}
// Update the setting
if (settingGroup["_" + targetSettingName] !== undefined)
{
settingGroup["_" + targetSettingName] = value;
// Update the file
const lines: string[] = File.readFileSync(_loadedConfigFileName, { encoding: "utf8" }).split(Utils.NEW_LINE);
let foundInFile: boolean = false;
for (let i = 0; i < lines.length; i++)
{
// TODO: This assumes setting names are unique across all setting groups
if (lines[i].indexOf(`"${targetSettingName}"`) !== -1)
{
const quote: string = (typeof value === "string") ? "\"" : "";
const endsWithComma: boolean = lines[i].trim().endsWith(",");
lines[i] = lines[i].split(":")[0] + ": " + quote + value.toString() + quote + (endsWithComma ? "," : "");
File.writeFileSync(_loadedConfigFileName, lines.join(Utils.NEW_LINE));
foundInFile = true;
break;
}
}
// Should not happen [any setting we need to update must be checked in advance that it already exists in the config file using isConfiguredProperty()]
if (!foundInFile)
{
Utils.log(`Error: AmbrosiaConfigFile update failed (reason: Setting '${settingName}' could not be found in ${_loadedConfigFile})`);
}
}
else
{
throw new Error(`Unknown AmbrosiaConfigFile setting '${settingName}'`);
}
}
}
/** The Ambrosia configuration (settings and event handlers) for the app. */
export class AmbrosiaConfig
{
private _dispatcher: Messages.MessageDispatcher; // Initialized in constructor
private _checkpointProducer: Streams.CheckpointProducer; // Initialized in constructor
private _checkpointConsumer: Streams.CheckpointConsumer; // Initialized in constructor
private _postResultDispatcher: Messages.PostResultDispatcher | null; // Initialized in constructor
private _configFile: AmbrosiaConfigFile; // The config file that was used to initialize the configuration; Initialized in constructor
/** [ReadOnly] This handler will be called each time a [dispatchable] message is received. Set via constructor. */
get dispatcher(): Messages.MessageDispatcher { return (this._dispatcher); }
/** Note: The property setter is for internal use only. */
set dispatcher(value: Messages.MessageDispatcher) { this._dispatcher = value; } // Note: Settable so that the IC can wrap the user-supplied dispatcher
/** [ReadOnly] This method will be called to generate (write) a checkpoint - a binary seralization of application state. Set via constructor. */
get checkpointProducer(): Streams.CheckpointProducer { return (this._checkpointProducer); }
/** [ReadOnly] This method will be called to load (read) a checkpoint - a binary seralization of application state. Set via constructor. */
get checkpointConsumer(): Streams.CheckpointConsumer { return (this._checkpointConsumer); }
/** [ReadOnly] This handler will be called each time the result (or error) of a post method is received. Set via constructor. */
get postResultDispatcher(): Messages.PostResultDispatcher | null { return (this._postResultDispatcher); }
/** [ReadOnly] Whether this is the first run of the instance following its initial registration. Note: This is computed at runtime. */
get isFirstStartAfterInitialRegistration(): boolean { return (this._configFile.isFirstStartAfterInitialRegistration); }
/** [ReadOnly] The folder where the Immortal Coordinator (IC) will write its logs (or read logs from if doing "time-travel debugging"). */
get icLogFolder(): string { return (this._configFile.icLogFolder); }
/**
* [ReadOnly] The storage type that the Immortal Coordinator (IC) logs will be persisted in.\
* When set to "Blobs", the logs are written to Azure storage (using AZURE_STORAGE_CONN_STRING) in the "Blob Containers\ambrosialogs" container.
* The icLogFolder can either be set to an empty string, or (rarely) to a desired sub-path under "ambrosialogs", eg. "TestLogs/Group1".
*/
get icLogStorageType(): keyof typeof LogStorageType { return (this._configFile.icLogStorageType ); }
/** [ReadOnly] The folder where the Immortal Coordinator (IC) binaries exist. If not specified, the 'AMBROSIATOOLS' environment variable will be used. */
get icBinFolder(): string { return (this._configFile.icBinFolder); }
/** [ReadOnly] The name this Ambrosia Immortal instance will be referred to by all instances (including itself). */
get icInstanceName(): string { return (this._configFile.instanceName); }
/** [ReadOnly] The port number that the Common Runtime for Applications (CRA) layer uses. */
get icCraPort(): number { return (this._configFile.icCraPort); }
/** [ReadOnly] The port number that the Immortal Coordinator (IC) receives on. */
get icReceivePort(): number { return (this._configFile.icReceivePort); }
/** [ReadOnly] The port number that the Immortal Coordinator (IC) sends on. */
get icSendPort(): number { return (this._configFile.icSendPort); }
/** An override IPv4 address for the Immortal Coordinator (IC) to use instead of the local IPv4 address. */
get icIPv4Address(): string { return (this._configFile.icIPv4Address); }
/**
* [ReadOnly] The hosting mode for the Immortal Coordinator (IC), which affects where and how the IC runs. Defaults to ICHostingMode.Integrated.\
* If not explicitly set, the value will be computed based on the value provided for 'icIPv4Address'.
*/
get icHostingMode(): ICHostingMode { return (this._configFile.icHostingMode); }
/** [ReadOnly] Whether to use .NET Core (instead of .Net Framework) to run the Immortal Coordinator (IC) [this is a Windows-only option]. */
get useNetCore(): boolean { return (this._configFile.useNetCore); }
/** [ReadOnly] The checkpoint number to start "time-travel debugging" from. */
get debugStartCheckpoint(): number { return (this._configFile.debugStartCheckpoint); }
/** [ReadOnly] Whether to perform a test upgrade (for debugging/testing purposes). Causes the IC to send a MessageType.upgradeService message. */
get debugTestUpgrade(): boolean { return (this._configFile.debugTestUpgrade); }
/** [ReadOnly] The size (in MB) the log must reach before the IC will take a checkpoint and start a new log. */
get logTriggerSizeInMB(): number { return (this._configFile.logTriggerSizeInMB); }
/** [ReadOnly] Whether this [primary] instance will run in an active/active configuration. */
get isActiveActive(): boolean { return (this._configFile.isActiveActive); }
/** [ReadOnly] The replica (secondary) ID this instance will use in an active/active configuration. */
get replicaNumber(): number { return (this._configFile.replicaNumber); }
/** [ReadOnly] The name of the .NET assembly used to establish a secure network channel between ICs. */
get secureNetworkAssemblyName() { return (this._configFile.secureNetworkAssemblyName); }
/** [ReadOnly] The name of the .NET class (that implements ISecureStreamConnectionDescriptor) in 'secureNetworkAssemblyName'. */
get secureNetworkClassName() { return (this._configFile.secureNetworkClassName); }
/**
* [ReadOnly] The nominal version of this Immortal instance.\
* Used to identify the log sub-folder name (ie. <icInstanceName>_<appVersion>) that will be logged to (or read from, if debugStartCheckpoint is specified).
*/
get appVersion(): number { return (this._configFile.appVersion); }
/** [ReadOnly] The nominal version this Immortal instance should upgrade to at startup. */
get upgradeVersion(): number { return (this._configFile.upgradeVersion); }
/** [ReadOnly] The currently active (in use) application code: pre-upgrade is 'VCurrent', post-upgrade is 'VNext'. */
get activeCode(): ActiveCodeType { return (this._configFile.activeCode); }
/** [ReadOnly] How to automatically [re]register this Immortal instance at startup. See also: isAutoRegister. */
get autoRegister(): boolean | AutoRegisterType { return (this._configFile.autoRegister); }
/** [ReadOnly] Options for how the language-binding behaves. */
get lbOptions(): LanguageBindingOptions { return (this._configFile.lbOptions); }
/**
* [ReadOnly] Whether the icHostingMode setting is 'Integrated'.\
* Note: This computed setting is just for brevity.
*/
get isIntegratedIC(): boolean { return (this._configFile.isIntegratedIC); }
/** [ReadOnly] Whether Ambrosia is running in 'time-travel debugging' mode. */
get isTimeTravelDebugging(): boolean { return (this._configFile.isTimeTravelDebugging); }
/** [Readonly] Whether to automatically [re]register this Immortal instance at startup. This is a computed setting. */
get isAutoRegister(): boolean { return (this._configFile.isAutoRegister); }
/**
* Specifies the core Ambrosia event handlers.
* @param messageDispatcher Function that handles incoming calls to published methods by dispatching them to their implementation.
* Also dispatches [locally generated] app events to their respective event handlers (if implemented).
* @param checkpointProducer Function that returns a Streams.OutgoingCheckpoint object used to serialize app state to a checkpoint.
* @param checkpointConsumer Function that returns a Streams.IncomingCheckpoint object used to receive a checkpoint of app state.
* @param postResultDispatcher [Optional] Function that handles the results (and errors) of all post method calls. If post methods are not used, this parameter can be omitted.
*/
constructor(messageDispatcher: Messages.MessageDispatcher, checkpointProducer: Streams.CheckpointProducer, checkpointConsumer: Streams.CheckpointConsumer, postResultDispatcher?: Messages.PostResultDispatcher)
{
this._configFile = loadedConfig();
this._dispatcher = messageDispatcher;
this._checkpointConsumer = checkpointConsumer;
this._checkpointProducer = checkpointProducer;
this._postResultDispatcher = postResultDispatcher || null;
}
/** Returns true if the specified property name has been configured locally (in ambrosiaConfig.json). */
isConfiguredLocally(propName: string): boolean
{
return (this._configFile.isConfiguredProperty(propName));
}
/**
* [Internal] For internal use only.\
* Updates the handlers of the configuration (when performing an upgrade).
*/
updateHandlers(messageDispatcher: Messages.MessageDispatcher, checkpointProducer: Streams.CheckpointProducer, checkpointConsumer: Streams.CheckpointConsumer, postResultDispatcher?: Messages.PostResultDispatcher): void
{
this._dispatcher = messageDispatcher;
this._checkpointConsumer = checkpointConsumer;
this._checkpointProducer = checkpointProducer;
this._postResultDispatcher = postResultDispatcher || null;
}
}
/** Class representing options for how the language-binding behaves. */
export class LanguageBindingOptions
{
// Indexer (for 'noImplicitAny' compliance), although this does end up hiding ts(2551): "Property 'xxxxx' does not exist on type 'LanguageBindingOptions'"
[key: string]: unknown;
private _parent: AmbrosiaConfigFile; // Initialized in constructor
private _deleteLogs: boolean = false;
private _deleteRemoteCRAConnections: boolean = false;
private _allowCustomJSONSerialization: boolean = true;
private _typeCheckIncomingPostMethodParameters: boolean = true;
private _outputLoggingLevel: Utils.LoggingLevel = Utils.LoggingLevel.Minimal;
private _outputLogFolder: string = "./outputLogs";
private _outputLogDestination: OutputLogDestination = OutputLogDestination.Console;
private _outputLogAllowColor: boolean = true;
private _traceFlags: string = "";
private _allowDisplayOfRpcParams: boolean = false;
private _allowPostMethodTimeouts: boolean = true;
private _allowPostMethodErrorStacks: boolean = false;
private _enableTypeScriptStackTraces: boolean = true;
private _maxInFlightPostMethods: number = -1;
private _messageBytePoolSizeInMB: number = 2;
private _maxMessageQueueSizeInMB: number = 256;
/** [ReadOnly] Whether to clear the IC logs (all prior checkpoints and logged state changes will be permanently lost, and recovery will not run). Defaults to false. */
get deleteLogs(): boolean { this._parent.onlyAppliesToIntegratedICHostingMode(LBOPTIONS_SECTION); return (this._deleteLogs); }
/** [ReadOnly] [Debug] Whether to delete any previously created non-loopback CRA connections [from (or to) this instance] at startup. Defaults to false. */
get deleteRemoteCRAConnections(): boolean {return ( this._deleteRemoteCRAConnections); }
/** [ReadOnly] Whether to disable the specialized JSON serialization of BigInt and typed-arrays (eg. Uint8Array). Defaults to true. */
get allowCustomJSONSerialization(): boolean { return (this._allowCustomJSONSerialization); }
/** [ReadOnly] Whether to skip type-checking the parameters of incoming post methods for correctness against published methods/types. Defaults to true.*/
get typeCheckIncomingPostMethodParameters(): boolean { return (this._typeCheckIncomingPostMethodParameters); }
/** [ReadOnly] The level of detail to include in the output log. Defaults to 'Minimal'. */
get outputLoggingLevel(): Utils.LoggingLevel { return (this._outputLoggingLevel); }
/** [ReadOnly] The folder where the language-binding will write output log files (when outputLogDestination is 'File' or 'ConsoleAndFile'). Defaults to "./outputLogs". */
get outputLogFolder(): string { return (this._outputLogFolder); }
/** [ReadOnly] Location(s) where the language-binding will log output. Defaults to 'Console'. */
get outputLogDestination(): OutputLogDestination { return (this._outputLogDestination); }
/** [ReadOnly] Whether to allow the use of color when logging to the console. Defaults to true. */
get outputLogAllowColor(): boolean { return (this._outputLogAllowColor); }
/** [ReadOnly] A semi-colon separated list of trace flag names (case-sensitive). Defaults to "". */
get traceFlags(): string { return (this._traceFlags); }
/** [ReadOnly] Whether to allow incoming RPC parameters [which can contain privacy/security related content] to be displayed/logged. */
get allowDisplayOfRpcParams(): boolean { return (this._allowDisplayOfRpcParams); }
/** [ReadOnly] Whether to enable the timeout feature of post methods. Defaults to true. */
get allowPostMethodTimeouts(): boolean { return (this._allowPostMethodTimeouts); }
/** [ReadOnly] Whether to allow sending a full stack trace in the result (as the 'originalError' parameter) if a post method fails. Defaults to false. */
get allowPostMethodErrorStacks(): boolean { return (this._allowPostMethodErrorStacks); }
/** [ReadOnly] Whether Error stack trace will refer to TypeScript files/locations (when available) instead of JavaScript files/locations. Defaults to true. */
get enableTypeScriptStackTraces(): boolean { return (this._enableTypeScriptStackTraces); }
/** [ReadOnly] Whether to generate a warning whenever the number of in-flight post methods reaches this threshold. Defaults to -1 (no limit). */
get maxInFlightPostMethods(): number { return (this._maxInFlightPostMethods); }
/** [ReadOnly] The size (in MB) of the message byte pool used for optimizing message construction. Defaults to 2 MB. */
get messageBytePoolSizeInMB(): number { return (this._messageBytePoolSizeInMB); }
/** [ReadOnly] Whether 'outputLoggingLevel' is currently set to 'Debug'. */
get debugOutputLogging(): boolean { return ( this.outputLoggingLevel === Utils.LoggingLevel.Debug); }
/** [ReadOnly] The maximum size (in MB) of the message queue for outgoing messages. Defaults to 256 MB. */
get maxMessageQueueSizeInMB(): number { return (this._maxMessageQueueSizeInMB); }
// Note: We allow a LanguageBindingOptions instance to be initialized from a "partial" LanguageBindingOptions object, like { deleteLogs: true }
constructor(parent: AmbrosiaConfigFile, partialOptions?: LanguageBindingOptions, throwOnUnknownOption: boolean = false)
{
this._parent = parent;
for (let optionName in partialOptions)
{
if (this["_" + optionName] !== undefined)
{
if (optionName === "maxMessageQueueSizeInMB")
{
const maxMessageQueueSizeInMB: number = partialOptions[optionName];
const maxMessageQueueSizeInBytes: number = maxMessageQueueSizeInMB * 1024 * 1024;
const heapSizeInBytes: number = Utils.getNodeLongTermHeapSizeInBytes();
const messageQueueLimitInBytes: number = heapSizeInBytes / 4;
if ((maxMessageQueueSizeInBytes < 32 * 1024 * 1024) || (maxMessageQueueSizeInBytes > messageQueueLimitInBytes))
{
throw new Error(`Option 'maxMessageQueueSizeInMB' (${maxMessageQueueSizeInMB}) must be between 32 and ${Math.floor(messageQueueLimitInBytes / ( 1024 * 1024))}; if needed, set the node.js V8 parameter '--max-old-space-size' to raise the upper limit (see https://nodejs.org/api/cli.html)`);
}
}
if (typeof partialOptions[optionName] === "string")
{
// Handle the cases where we have the name of the an enum (eg. "Verbose") instead of the [numerical] value.
// This can happen when parsing ambrosiaConfig.json.
switch (optionName)
{
case "outputLoggingLevel":
let level: keyof typeof Utils.LoggingLevel = partialOptions[optionName] as any;
if (Utils.LoggingLevel[level] !== undefined)
{
this["_" + optionName] = Utils.LoggingLevel[level];
}
else
{
throw new Error(`Option '${optionName}' has an invalid value ('${level}')`);
}
break;
case "outputLogDestination":
let destination: keyof typeof OutputLogDestination = partialOptions[optionName] as any;
if (OutputLogDestination[destination] !== undefined)
{
this["_" + optionName] = OutputLogDestination[destination];
}
else
{
throw new Error(`Option '${optionName}' has an invalid value ('${destination}')`);
}
break;
case "traceFlags":
const traceFlagNames: string[] = partialOptions[optionName].split(";").map(traceFlagName => traceFlagName.trim()).filter(traceFlagName => traceFlagName.length > 0);
for (let i = 0; i < traceFlagNames.length; i++)
{
const traceFlagName: keyof typeof Utils.TraceFlag = traceFlagNames[i] as keyof typeof Utils.TraceFlag;
if (Utils.TraceFlag[traceFlagName] === undefined)
{
throw new Error(`Option '${optionName}' contains an invalid value ('${traceFlagName}'); valid values are one or more of "${Utils.getEnumKeys("TraceFlag", Utils.TraceFlag).join("\" or \"")}" separated by semi-colons`);
}
}
this["_" + optionName] = traceFlagNames.join(";");
break;
default:
// A non-enum
this["_" + optionName] = partialOptions[optionName];
break;
}
}
else
{
this["_" + optionName] = partialOptions[optionName];
}
}
else
{
if (throwOnUnknownOption)
{
throw new Error(`'${optionName}' is not a valid option name`);
}
}
}
}
}
/**
* [Internal] Asynchronously [re]registers the configured Immortal instance (for example, to prepare it for an upgrade to the configured 'upgradeVersion').\
* Note: This can take several (3+) seconds to complete.
*/
export async function registerInstanceAsync(isNewRegistration: boolean): Promise<void>
{
let promise: Promise<void> = new Promise<void>((resolve, reject: RejectedPromise) =>
{
// Run "Ambrosia.exe RegisterInstance"
try
{
const config: AmbrosiaConfigFile = _loadedConfigFile;
// Note: We want to get Ambrosia.exe/dll, so we specify 'isTimeTravelDebugging' as true
const registrationExecutable: string = Utils.getICExecutable(config.icBinFolder, config.useNetCore, true);
const memStream: Streams.MemoryStream = new Streams.MemoryStream();
const args: string[] = [];
const isAddReplica: boolean = config.isActiveActive && (config.replicaNumber > 0);
const registrationTypePrefix: string = !isNewRegistration ? "Re-" : "";
// Populate command-line args [we have to re-specify all required args, not just those related to
// the upgrade; if not configured locally, these values MUST come from the existing registration]
args.push(isAddReplica ? "AddReplica" : "RegisterInstance");
if (isAddReplica)
{
// Note: There is no requirement to EVER add replica 0 [see bug #175].
args.push(`--replicaNum=${config.replicaNumber}`);
}
args.push(`--instanceName=${config.instanceName}`);
args.push(`--receivePort=${config.icReceivePort}`);
args.push(`--sendPort=${config.icSendPort}`);
args.push(`--log=${config.icLogFolder}`); // Not a required arg for Ambrosia.exe, but we consider it to be required (see AmbrosiaConfigFile._allRegistrationOverridesSet)
// Any arbitrary [and previously unused] --currentVersion number can be registered, and the IC will start using that version.
// After the IC starts using the new version, it will update <instanceTable>.CurrentVersion to that version.
// However, if the --currentVersion has been used before (as determined [by the IC] by the existence of a log folder for that version), and if the --currentVersion
// does not match <instanceTable>.CurrentVersion, then the IC will fail with "FATAL Error 1: Version mismatch on process start" when it starts. This behavior is
// designed to prevent accidental use of a previously upgraded-from version (the correct way to "downgrade" is to upgrade to an older version of the code).
args.push(`--currentVersion=${config.appVersion}`);
// If --upgradeVersion is not supplied, RegisterInstance will default it to the supplied --currentVersion.
// After an upgrade completes, the IC will update <instanceTable>.CurrentVersion to --upgradeVersion, but it will not update the registered 'currentVersion' (which must be done manually via re-registration).
const canOmitUpgradeVersion: boolean = (isNewRegistration && !config.isConfiguredProperty("upgradeVersion"));
if (!canOmitUpgradeVersion)
{
args.push(`--upgradeVersion=${config.upgradeVersion}`);
}
// Include "optional" args [if these are not set, they will revert to their default values]
// TODO: Do we need to handle these 2 RegisterInstance settings? They're for testing only.
// Further, because these ONLY apply to RegisterInstance (and therefore cannot be provided
// to the IC as "local overrides") it would be misleading to allow them in ambrosiaConfig.json.
// --pauseAtStart
// --noPersistLogs
if (config.isConfiguredProperty("logTriggerSizeInMB"))
{
args.push(`--logTriggerSize=${config.logTriggerSizeInMB}`);
}
// Note: We enforce [in AmbrosiaConfigFile.initializeAsync()] that the locally configured 'isActiveActive' MUST match the
// registered value (to prevent it being overridable locally, even though the IC will allow this).
// See AmbrosiaConfigFile.initializeAsync() for details.
if (config.isConfiguredProperty("isActiveActive") && config.isActiveActive)
{
args.push(`--activeActive`);
}
Utils.log(`${registrationTypePrefix}Registering instance '${config.instanceName}'${isAddReplica ? ` (replica #${config.replicaNumber})` : ""}...`);
Utils.log(`Args: ${args.join(" ").replace(/--/g, "")}`);
// Start the process (with no visible console) and pipe both stdout/stderr to memStream
const registrationProcess: ChildProcess.ChildProcess = ChildProcess.spawn(config.useNetCore ? "dotnet" : registrationExecutable,
(config.useNetCore ? [registrationExecutable] : []).concat(args),
{ stdio: ["ignore", "pipe", "pipe"], shell: false, detached: false });
if (!registrationProcess.stdout || !registrationProcess.stderr)
{
throw new Error(`Unable to redirect stdout/stderr for registration executable (${registrationExecutable})`);
}
registrationProcess.stdout.pipe(memStream);
registrationProcess.stderr.pipe(memStream);
registrationProcess.on("exit", (code: number, signal: NodeJS.Signals) =>
{
const buf: Buffer = memStream.readAll();
// Note: In the case of a successful registration, the output will contain this [somewhat misleading] message:
// "The CRA instance appears to be down. Restart it and this vertex will be instantiated automatically".
const output: string = StringEncoding.fromUTF8Bytes(buf);
const registrationFailed: boolean = (code !== 0) || (output.indexOf("Usage:") !== -1) || (output.indexOf("Exception") !== -1);
let suffix: string = "";
memStream.end();
if (registrationFailed)
{
const lines: string[] = output.split("\n").filter(l => l.trim().length > 0);
const reason: string = (lines[0].indexOf("Usage:") === -1) ? Utils.trimTrailingChar(lines[0], ".") : "Invalid command-line syntax";
reject(new Error(`Unable to ${registrationTypePrefix.toLowerCase()}register instance (reason: ${reason} ('${args.join(" ")}'))`));
}
else
{
const exitAfterRegistering: boolean = (config.autoRegister === AutoRegisterType.TrueAndExit);
// If needed, turn off 'autoRegister'
if (config.isAutoRegister)
{
suffix = ` (auto-register${exitAfterRegistering ? " and exit" : ""})`;
config.updateSetting("autoRegister", false);
}
if (config.isLiveUpgradeRequested)
{
suffix = ` (for upgrade: v${config.appVersion} to v${config.upgradeVersion})`;
}
Utils.log(`Instance successfully ${registrationTypePrefix.toLowerCase()}registered${suffix}`);
if (exitAfterRegistering)
{
Process.exit(0);
}
else
{
resolve(); // Success
}
}
});
}
catch (error: unknown)
{
reject(Utils.makeError(error));
}
});
return (promise);
}
/**
* Asynchronously erases the specified Immortal instance and all of its replicas (this includes all Azure data, and all log/checkpoint files).
*
* **WARNING:** Data removed by erasing is **permanently lost**.\
* This method should **never** be called for a live/production instance.\
* Only use it during the development and testing phases.\
* **WARNING:** This method also deletes all log folders for the instance.\
* **WARNING:** Do not attempt to re-register / restart the erased instance within 30 seconds of running this method, otherwise you may encounter error 409 (Conflict) from Azure.
*/
export async function eraseInstanceAndReplicasAsync(instanceName: string, verboseOutput: boolean = false): Promise<void>
{
const replicaNumbers: number[] = await AmbrosiaStorage.getReplicaNumbersAsync(instanceName);
if (replicaNumbers.length === 0)
{
Utils.log(`Error: Unable to erase (reason: no instance/replicas named '${instanceName}' found)`);
return;
}
for (let i = 0; i < replicaNumbers.length; i++)
{
const replicaNumber: number = replicaNumbers[i];
await eraseInstanceAsync(instanceName, replicaNumber, verboseOutput);
}
}
/**
* Asynchronously erases the specified Immortal instance (this includes all Azure data, and all log/checkpoint files).
*
* **WARNING:** Data removed by erasing is **permanently lost**.\
* This method should **never** be called for a live/production instance.\
* Only use it during the development and testing phases.\
* **WARNING:** This method also deletes all log folders for the instance.\
* **WARNING:** Do not attempt to re-register / restart the erased instance within 30 seconds of running this method, otherwise you may encounter error 409 (Conflict) from Azure.
*
* Note: Typically, this executes in under a second, but it can take several seconds.
*/
export async function eraseInstanceAsync(instanceName: string, replicaNumber: number = 0, verboseOutput: boolean = false): Promise<void>
{
const config: AmbrosiaConfigFile = loadedConfig();
const usingFileSystemLogs: boolean = (config.icLogStorageType === LogStorageType[LogStorageType.Files]);
const usingAzureLogs: boolean = (config.icLogStorageType === LogStorageType[LogStorageType.Blobs]);
const fullInstanceName: string = `'${instanceName}'${replicaNumber > 0 ? ` (replica #${replicaNumber})` : ""}`;
const replicaNumbers: number[] = await AmbrosiaStorage.getReplicaNumbersAsync(instanceName);
const replicaCount: number = replicaNumbers.length;
/** [Local function] Always logs the specified message. */
function log(msg: string): void
{
Utils.log(msg, null, Utils.LoggingLevel.Minimal);
}
if (replicaNumbers.indexOf(replicaNumber) === -1)
{
Utils.log(`Error: Unable to erase (reason: instance ${fullInstanceName} not found)`);
return;
}
log(`Erasing instance ${fullInstanceName}...`);
if (!config.isConfiguredProperty("icLogFolder") || (usingFileSystemLogs && !config.icLogFolder.trim()))
{
throw new Error(`The 'icLogFolder' setting is either not specified or is empty; this setting is required for eraseInstanceAsync() when 'icLogStorageType' is \"${LogStorageType[LogStorageType.Files]}\"`);
}
// Delete Azure registration data
await AmbrosiaStorage.deleteRegisteredInstanceAsync(instanceName, replicaNumber, verboseOutput);
// Only remove log/checkpoint files when erasing the last replica
if (replicaCount === 1)
{
// Delete all '<instanceName>_<version>' log folders
// Note: To fully test this, the "deleteLogs" config setting should be set to false (otherwise AmbrosiaRoot.initializeAsync() will have already deleted the current log folder)
const logFolder: string = config.icLogFolder;
let instanceDirNames: string[] = [];
if (usingFileSystemLogs)
{
if (!File.existsSync(logFolder))
{
Utils.log(`Warning: No logs or checkpoints will be deleted because the 'icLogFolder' (${logFolder}) does not exist`);
}
else
{
instanceDirNames = File.readdirSync(logFolder, { withFileTypes: true })
.filter(dirEntity => dirEntity.isDirectory() && dirEntity.name.startsWith(instanceName + "_")) // Eg. "SomeInstance_0"
.map(dirEntity => dirEntity.name);
}
}
if (usingAzureLogs)
{
instanceDirNames = await AmbrosiaStorage.getChildLogFoldersAsync(logFolder, instanceName);
}
if (instanceDirNames.length > 0)
{
for (const dirName of instanceDirNames)
{
const instanceLogFolder: string = Path.join(logFolder, dirName);
const deletedFileCount: number = await IC.deleteInstanceLogFolderAsync(instanceLogFolder, config.icLogStorageType);
if (verboseOutput)
{
log(`Removed log folder '${instanceLogFolder}' from ${usingAzureLogs ? "Azure" : "disk"} (${deletedFileCount} files deleted)`);
}
}
}
else
{
if (verboseOutput)
{
log(`Warning: No log/checkpoint files found`);
}
}
}
log(`Instance ${fullInstanceName} successfully erased${replicaCount > 1 ? ` (${replicaCount - 1} replicas remain)` : ""}`);
// See https://docs.microsoft.com/en-us/azure/storage/common/storage-monitoring-diagnosing-troubleshooting?tabs=dotnet#the-client-is-receiving-409-messages
log(`Warning: Please wait at least 30 seconds before re-registering / starting the instance, otherwise you may encounter HTTP error 409 (Conflict) from Azure`);
} | the_stack |
import * as proxyquire from 'proxyquire';
import * as nsWebpackIndex from '../index';
import { join } from 'path';
// With noCallThru enabled, `proxyquire` will not fall back to requiring the real module to populate properties that are not mocked.
// This allows us to mock packages that are not available in node_modules.
// In case you want to enable fallback for a specific object, just add `'@noCallThru': false`.
proxyquire.noCallThru();
class EmptyClass { };
let angularCompilerOptions: any;
class AngularCompilerStub {
constructor(options) {
angularCompilerOptions = options;
}
};
let terserOptions: any;
class TerserJsStub {
constructor(options) {
terserOptions = options;
}
};
const nativeScriptDevWebpack = {
GenerateBundleStarterPlugin: EmptyClass,
GenerateNativeScriptEntryPointsPlugin: EmptyClass,
WatchStateLoggerPlugin: EmptyClass,
PlatformFSPlugin: EmptyClass,
getAppPath: () => 'app',
getEntryModule: () => 'EntryModule',
hasRootLevelScopedModules: () => false,
hasRootLevelScopedAngular: () => false,
processTsPathsForScopedModules: () => false,
processTsPathsForScopedAngular: () => false,
getResolver: () => null,
getConvertedExternals: nsWebpackIndex.getConvertedExternals,
getSourceMapFilename: nsWebpackIndex.getSourceMapFilename,
processAppComponents: nsWebpackIndex.processAppComponents,
getUserDefinedEntries: nsWebpackIndex.getUserDefinedEntries,
};
const emptyObject = {};
const FakeAotTransformerFlag = "aot";
const FakeHmrTransformerFlag = "hmr";
const FakeLazyTransformerFlag = "lazy";
const webpackConfigAngular = proxyquire('./webpack.angular', {
'nativescript-dev-webpack': nativeScriptDevWebpack,
'nativescript-dev-webpack/nativescript-target': emptyObject,
'nativescript-dev-webpack/transformers/ns-replace-bootstrap': { nsReplaceBootstrap: () => { return FakeAotTransformerFlag } },
'nativescript-dev-webpack/transformers/ns-replace-lazy-loader': { nsReplaceLazyLoader: () => { return FakeLazyTransformerFlag } },
'nativescript-dev-webpack/transformers/ns-support-hmr-ng': { nsSupportHmrNg: () => { return FakeHmrTransformerFlag } },
'nativescript-dev-webpack/utils/ast-utils': { getMainModulePath: () => { return "fakePath"; } },
'nativescript-dev-webpack/utils/tsconfig-utils': { getNoEmitOnErrorFromTSConfig: () => { return false; }, getCompilerOptionsFromTSConfig: () => { return false; } },
'nativescript-dev-webpack/plugins/NativeScriptAngularCompilerPlugin': { getAngularCompilerPlugin: () => { return AngularCompilerStub; } },
'@ngtools/webpack': {
AngularCompilerPlugin: AngularCompilerStub
},
'terser-webpack-plugin': TerserJsStub
});
const webpackConfigTypeScript = proxyquire('./webpack.typescript', {
'nativescript-dev-webpack': nativeScriptDevWebpack,
'nativescript-dev-webpack/nativescript-target': emptyObject,
'nativescript-dev-webpack/utils/tsconfig-utils': { getNoEmitOnErrorFromTSConfig: () => { return false; }, getCompilerOptionsFromTSConfig: () => { return false; } },
'terser-webpack-plugin': TerserJsStub
});
const webpackConfigJavaScript = proxyquire('./webpack.javascript', {
'nativescript-dev-webpack': nativeScriptDevWebpack,
'nativescript-dev-webpack/nativescript-target': emptyObject,
'terser-webpack-plugin': TerserJsStub
});
const webpackConfigVue = proxyquire('./webpack.vue', {
'nativescript-dev-webpack': nativeScriptDevWebpack,
'nativescript-dev-webpack/nativescript-target': emptyObject,
'vue-loader/lib/plugin': EmptyClass,
'nativescript-vue-template-compiler': emptyObject,
'terser-webpack-plugin': TerserJsStub
});
describe('webpack.config.js', () => {
const getInput = (options: { platform: string, aot?: boolean, hmr?: boolean, externals?: string[], sourceMap?: boolean, hiddenSourceMap?: boolean | string }) => {
const input: any = Object.assign({}, options);;
input[options.platform] = true;
return input;
};
[
{ type: 'javascript', webpackConfig: webpackConfigJavaScript },
{ type: 'typescript', webpackConfig: webpackConfigTypeScript },
{ type: 'angular', webpackConfig: webpackConfigAngular },
{ type: 'vue', webpackConfig: webpackConfigVue }
].forEach(element => {
const { type, webpackConfig } = element;
[
'android',
'ios'
].forEach(platform => {
describe(`verify externals for webpack.${type}.js (${platform})`, () => {
afterEach(() => {
nativeScriptDevWebpack.getConvertedExternals = nsWebpackIndex.getConvertedExternals;
});
it('returns empty array when externals are not passed', () => {
const input = getInput({ platform });
const config = webpackConfig(input);
expect(config.externals).toEqual([]);
});
it('calls getConvertedExternals to convert externals', () => {
let isCalled = false;
nativeScriptDevWebpack.getConvertedExternals = () => {
isCalled = true;
return [];
};
const input = getInput({ platform, externals: ['nativescript-vue'] });
webpackConfig(input);
expect(isCalled).toBe(true, 'Webpack.config.js must use the getConvertedExternals method');
});
if (platform === "ios") {
it('has inspector_modules entry when tns-core-modules are not externals', () => {
const input = getInput({ platform, externals: ['nativescript-vue'] });
const config = webpackConfig(input);
expect(config.entry["tns_modules/tns-core-modules/inspector_modules"]).toEqual("inspector_modules");
});
it('does not have inspector_modules entry when tns-core-modules are externals', () => {
const input = getInput({ platform, externals: ['tns-core-modules'] });
const config = webpackConfig(input);
expect(config.entry["tns_modules/tns-core-modules/inspector_modules"]).toBeUndefined();
});
}
[
{
input: ['nativescript-vue'],
expectedOutput: [/^nativescript-vue((\/.*)|$)/]
},
{
input: ['nativescript-vue', 'nativescript-angular'],
expectedOutput: [/^nativescript-vue((\/.*)|$)/, /^nativescript-angular((\/.*)|$)/]
},
].forEach(testCase => {
const input = getInput({ platform, externals: testCase.input });
it(`are correct regular expressions, for input ${testCase.input}`, () => {
const config = webpackConfig(input);
expect(config.externals).toEqual(testCase.expectedOutput);
});
});
});
if (type === 'angular') {
describe(`angular transformers for webpack.${type}.js (${platform})`, () => {
beforeEach(() => {
angularCompilerOptions = null;
});
it("should be empty by default", () => {
const input = getInput({ platform });
webpackConfig(input);
expect(angularCompilerOptions).toBeDefined();
expect(angularCompilerOptions.platformTransformers).toBeDefined();
expect(angularCompilerOptions.platformTransformers.length).toEqual(0);
});
it("should contain the AOT transformer when the AOT flag is passed", () => {
const input = getInput({ platform, aot: true });
webpackConfig(input);
expect(angularCompilerOptions).toBeDefined();
expect(angularCompilerOptions.platformTransformers).toBeDefined();
expect(angularCompilerOptions.platformTransformers.length).toEqual(1);
expect(angularCompilerOptions.platformTransformers[0]).toEqual(FakeAotTransformerFlag);
});
it("should contain the HMR transformer when the HMR flag is passed", () => {
const input = getInput({ platform, hmr: true });
webpackConfig(input);
expect(angularCompilerOptions).toBeDefined();
expect(angularCompilerOptions.platformTransformers).toBeDefined();
expect(angularCompilerOptions.platformTransformers.length).toEqual(1);
expect(angularCompilerOptions.platformTransformers[0]).toEqual(FakeHmrTransformerFlag);
});
it("should contain the Lazy transformer when the @angular/core is an external module", () => {
const input = getInput({ platform, externals: ["@angular/core"] });
webpackConfig(input);
expect(angularCompilerOptions).toBeDefined();
expect(angularCompilerOptions.platformTransformers).toBeDefined();
expect(angularCompilerOptions.platformTransformers.length).toEqual(1);
expect(angularCompilerOptions.platformTransformers[0]).toEqual(FakeLazyTransformerFlag);
});
it("should contain the AOT + HMR transformers when the AOT and HMR flags are passed", () => {
const input = getInput({ platform, aot: true, hmr: true });
webpackConfig(input);
expect(angularCompilerOptions).toBeDefined();
expect(angularCompilerOptions.platformTransformers).toBeDefined();
expect(angularCompilerOptions.platformTransformers.length).toEqual(2);
expect(angularCompilerOptions.platformTransformers).toContain(FakeAotTransformerFlag);
expect(angularCompilerOptions.platformTransformers).toContain(FakeHmrTransformerFlag);
});
it("should set the AOT transformer before the HMR one when the AOT and HMR flags are passed", () => {
const input = getInput({ platform, aot: true, hmr: true });
webpackConfig(input);
expect(angularCompilerOptions).toBeDefined();
expect(angularCompilerOptions.platformTransformers).toBeDefined();
expect(angularCompilerOptions.platformTransformers.length).toEqual(2);
expect(angularCompilerOptions.platformTransformers[0]).toEqual(FakeAotTransformerFlag);
expect(angularCompilerOptions.platformTransformers[1]).toEqual(FakeHmrTransformerFlag);
});
it("should contain the AOT + Lazy transformers when the AOT flag is passed and @angular/core is an external module", () => {
const input = getInput({ platform, aot: true, externals: ["@angular/core"] });
webpackConfig(input);
expect(angularCompilerOptions).toBeDefined();
expect(angularCompilerOptions.platformTransformers).toBeDefined();
expect(angularCompilerOptions.platformTransformers.length).toEqual(2);
expect(angularCompilerOptions.platformTransformers).toContain(FakeAotTransformerFlag);
expect(angularCompilerOptions.platformTransformers).toContain(FakeLazyTransformerFlag);
});
it("should contain the HMR + Lazy transformers when the HMR flag is passed and @angular/core is an external module", () => {
const input = getInput({ platform, hmr: true, externals: ["@angular/core"] });
webpackConfig(input);
expect(angularCompilerOptions).toBeDefined();
expect(angularCompilerOptions.platformTransformers).toBeDefined();
expect(angularCompilerOptions.platformTransformers.length).toEqual(2);
expect(angularCompilerOptions.platformTransformers).toContain(FakeHmrTransformerFlag);
expect(angularCompilerOptions.platformTransformers).toContain(FakeLazyTransformerFlag);
});
it("should contain the AOT + HMR + Lazy transformers when the AOT and HMR flags are passed and @angular/core is an external module", () => {
const input = getInput({ platform, aot: true, hmr: true, externals: ["@angular/core"] });
webpackConfig(input);
expect(angularCompilerOptions).toBeDefined();
expect(angularCompilerOptions.platformTransformers).toBeDefined();
expect(angularCompilerOptions.platformTransformers.length).toEqual(3);
expect(angularCompilerOptions.platformTransformers).toContain(FakeAotTransformerFlag);
expect(angularCompilerOptions.platformTransformers).toContain(FakeHmrTransformerFlag);
expect(angularCompilerOptions.platformTransformers).toContain(FakeLazyTransformerFlag);
});
it("should contain the AOT + HMR + Lazy transformers in the proper order when the AOT and HMR flags are passed and @angular/core is an external module", () => {
const input = getInput({ platform, aot: true, hmr: true, externals: ["@angular/core"] });
webpackConfig(input);
expect(angularCompilerOptions).toBeDefined();
expect(angularCompilerOptions.platformTransformers).toBeDefined();
expect(angularCompilerOptions.platformTransformers.length).toEqual(3);
expect(angularCompilerOptions.platformTransformers[0]).toEqual(FakeAotTransformerFlag);
expect(angularCompilerOptions.platformTransformers[1]).toEqual(FakeHmrTransformerFlag);
expect(angularCompilerOptions.platformTransformers[2]).toEqual(FakeLazyTransformerFlag);
});
});
}
describe(`source map for webpack.${type}.js (${platform})`, () => {
beforeEach(() => {
terserOptions = null;
});
it("should not set source maps without the flag", () => {
const input = getInput({ platform, sourceMap: false });
const config = webpackConfig(input);
expect(config.devtool).toEqual("none");
expect(terserOptions.sourceMap).toBeFalsy();
expect(terserOptions.terserOptions.output.semicolons).toBeTruthy();
expect(config.output.sourceMapFilename).toEqual("[file].map");
});
it("should set inline-source-map devtool", () => {
const input = getInput({ platform, sourceMap: true });
const config = webpackConfig(input);
expect(config.devtool).toEqual("inline-source-map");
expect(terserOptions.sourceMap).toBeTruthy();
expect(terserOptions.terserOptions.output.semicolons).toBeFalsy();
expect(config.output.sourceMapFilename).toEqual("[file].map");
});
});
describe(`hidden source map for webpack.${type}.js (${platform})`, () => {
beforeEach(() => {
terserOptions = null;
});
it("should not set source maps without the flag", () => {
const input = getInput({ platform, hiddenSourceMap: false });
const config = webpackConfig(input);
expect(config.devtool).toEqual("none");
expect(terserOptions.sourceMap).toBeFalsy();
expect(terserOptions.terserOptions.output.semicolons).toBeTruthy();
expect(config.output.sourceMapFilename).toEqual("[file].map");
});
it("should set hidden-source-map devtool and the default sourceMap folder", () => {
const input = getInput({ platform, hiddenSourceMap: true });
const config = webpackConfig(input);
expect(config.devtool).toEqual("hidden-source-map");
expect(terserOptions.sourceMap).toBeTruthy();
expect(terserOptions.terserOptions.output.semicolons).toBeFalsy();
expect(config.output.sourceMapFilename).toEqual(join("..", "sourceMap", "[file].map"));
});
it("should override the sourceMap property and the default sourceMap folder", () => {
const input = getInput({ platform, sourceMap: true, hiddenSourceMap: true });
const config = webpackConfig(input);
expect(config.devtool).toEqual("hidden-source-map");
expect(terserOptions.sourceMap).toBeTruthy();
expect(terserOptions.terserOptions.output.semicolons).toBeFalsy();
expect(config.output.sourceMapFilename).toEqual(join("..", "sourceMap", "[file].map"));
});
it("should set hidden-source-map devtool and override the sourceMapFilename", () => {
const newSourceMapFolder = "myCoolSourceMapFolder";
const input = getInput({ platform, sourceMap: true, hiddenSourceMap: newSourceMapFolder });
const config = webpackConfig(input);
expect(config.devtool).toEqual("hidden-source-map");
expect(terserOptions.sourceMap).toBeTruthy();
expect(terserOptions.terserOptions.output.semicolons).toBeFalsy();
expect(config.output.sourceMapFilename).toEqual(join("..", newSourceMapFolder, "[file].map"));
});
});
describe(`alias for webpack.${type}.js (${platform})`, () => {
it('should add alias when @nativescript/core is at the root of node_modules', () => {
nativeScriptDevWebpack.hasRootLevelScopedModules = () => true;
nativeScriptDevWebpack.hasRootLevelScopedAngular = () => true;
const input = getInput({ platform });
const config = webpackConfig(input);
expect(config.resolve.alias['tns-core-modules']).toBe('@nativescript/core');
if (type === 'angular') {
expect(config.resolve.alias['nativescript-angular']).toBe('@nativescript/angular');
}
});
it('shouldn\'t add alias when @nativescript/core is not at the root of node_modules', () => {
nativeScriptDevWebpack.hasRootLevelScopedModules = () => false;
nativeScriptDevWebpack.hasRootLevelScopedAngular = () => false;
const input = getInput({ platform });
const config = webpackConfig(input);
expect(config.resolve.alias['tns-core-modules']).toBeUndefined();
if (type === 'angular') {
expect(config.resolve.alias['nativescript-angular']).toBeUndefined();
}
});
});
});
});
}); | the_stack |
import invariant from "invariant";
import moment from "moment";
import {
CampaignAudienceRules,
CampaignEmailScheduling,
CampaignGraph,
CampaignNodeKind,
EdgeKind,
EntryNodeKinds,
} from "common/campaign";
import AbstractCampaignNode from "common/campaign/nodes/abstractCampaignNode";
import AudienceCampaignNode from "common/campaign/nodes/audienceCampaignNode";
import TriggerCampaignNode from "common/campaign/nodes/triggerCampaignNode";
import { deserialize } from "common/filters";
import App from "src/app";
import { AudienceBuilder } from "src/audience";
import { CampaignStateEnum } from "src/models/campaign.model";
import CampaignNodeState, {
CampaignNodeStateCreationAttributes,
} from "src/models/campaignNodeState.model";
import { buildCampaignGraph } from "./buildCampaignGraph";
import CampaignNodeEdge from "common/campaign/nodes/campaignNodeEdge";
import logger from "src/utils/logger";
import WaitCampaignNode from "common/campaign/nodes/waitCampaignNode";
import AbstractNodeExecutor from "./nodes/abstractNodeExecutor";
import EmailNodeExecutor from "./nodes/emailNodeExecutor";
import EmailCampaignNode from "common/campaign/nodes/emailCampaignNode";
import WaitNodeExecutor from "./nodes/waitNodeExecutor";
import FilterNodeExecutor from "./nodes/filterNodeExecutor";
import FilterCampaignNode from "common/campaign/nodes/filterCampaignNode";
import ExecutionResult, { ExecutionResultEnum } from "./executionResult";
import ProductUser from "src/models/productUser.model";
type EntryNode = AudienceCampaignNode | TriggerCampaignNode;
/**
* The CampaignNodeEvaluator manages the running of a `Campaign`, keeping track which `CampaignNodeState`s (which map a `ProductUser`
* to a specific `CampaignNode`) have been executed, if the `CampaignNodeState` has "timed out" (meaning that the specific step
* had not occured within the given time frame), and enqueues the next `CampaignNodeState` depending on whether the current
* step executed successfully or not.
*
*/
class CampaignNodeEvaluator {
#app: App;
graph: CampaignGraph;
userId: string;
campaignId: string;
nodes: AbstractCampaignNode[];
edges: CampaignNodeEdge[];
calledBuild = false;
constructor(app: App, userId: string, campaignId: string) {
this.#app = app;
this.userId = userId;
this.campaignId = campaignId;
}
/**
* Builds the campaign graph by querying the database for all nodes and edges. This is required to prepare for campaign node evaluation.
* @returns CampaignNodeEvaluator
*/
async build() {
if (this.calledBuild) {
return this;
}
const results = await buildCampaignGraph(
this.#app.models,
this.userId,
this.campaignId
);
this.graph = results.graph;
this.nodes = results.nodes;
this.edges = results.edges;
this.calledBuild = true;
return this;
}
/**
* Make sure to call CampaignNodeEvaluator.build() first.
* This function gets all Triggers and Audience nodes and evaluates them, beginning the Campaign.
*
* @returns Promises for evaluating entry nodes
*/
async evaluateCampaignEntryNodes() {
invariant(
this.calledBuild,
"Need to call CampaignNodeEvaluator.build() first"
);
if (!this.nodes.length) {
return;
}
const entryNodes = this.getEntryNodes();
return Promise.all(
entryNodes.map((node) => this.evaluateEntryNode(node as EntryNode))
);
}
/**
* Evaluates the Audience for the given Audience/Trigger node. It then marks this
* step as having been completed in the CampaignNodeState model. These nodes will
* be picked up by the CampaignCronJob for evaluation.
*
* @param node EntryNode
*/
async evaluateEntryNode(node: EntryNode) {
logger.info(
"[CampaignNodeEvaluator:evaluateEntryNode] Evaluating " +
node.kind +
" " +
node.getId()
);
invariant(
this.calledBuild,
"Need to call CampaignNodeEvaluator.build() first"
);
// Get product users from executing the associate Audience node
const productUsers = await this.executeAudience(node);
// Mark first campaign node as completed for these users, and queue up the next campaign node if it exists
return this.evaluateEntryNodeForProductUsers(node, productUsers);
}
/**
* Marks the list of product users as matching the EntryNode's filter, and initializes the next
* step for the campaign.
*
* @param node EntryNode Audience or Trigger Node
* @param productUsers List of product users
* @returns
*/
async evaluateEntryNodeForProductUsers(
node: EntryNode,
productUsers: ProductUser[]
) {
// mark these ProductUsers as having completed the first step
const initCampaignNodePromises = productUsers.map((p) =>
CampaignNodeState.create({
campaignNodeId: node.id,
productUserId: p.id,
state: CampaignStateEnum.COMPLETED,
runAt: new Date(),
completedAt: new Date(),
userId: this.userId,
didTimeout: false,
attempts: 1,
campaignId: this.campaignId,
timeoutAt: null,
})
);
const campaignNodeStates = await Promise.all(initCampaignNodePromises);
// get next node states
const nextNodes = this.getAssociatedDefaultNodes(node);
if (nextNodes.length === 0) {
logger.info(
"[CampaignNodeEvaluator:evaluateEntryNode] No next node found"
);
// this campaign path is over
return;
}
// Iterate through all the next default nodes for the campaign and create states for them
let nodeStatePromises: CampaignNodeStateCreationAttributes[] = [];
nextNodes.map((nextNode) => {
logger.info(
"[CampaignNodeEvaluator:evaluateEntryNode] Found next node: " +
nextNode.kind +
" " +
nextNode.getId()
);
// queue up the next nodes to run
const nextCampaignNodeStates = campaignNodeStates.map((state) => ({
campaignNodeId: nextNode.id,
productUserId: state.productUserId,
state: CampaignStateEnum.PENDING,
runAt: this.getRunAt(nextNode),
userId: this.userId,
campaignId: this.campaignId,
}));
nodeStatePromises = nodeStatePromises.concat(nextCampaignNodeStates);
});
return await CampaignNodeState.bulkCreate(nodeStatePromises);
}
/**
* Adds the product user to the campaign if it matches a trigger node.
*/
async evaluateProductUserSaved(productUser: ProductUser) {
const entryNodes = this.getEntryNodes();
const processableEntryNodes = entryNodes.filter(
(campaignNode) =>
campaignNode.getAudienceRules() === CampaignAudienceRules.New ||
campaignNode.getAudienceRules() === CampaignAudienceRules.Both
);
const promises = processableEntryNodes.map(async (node) => {
const matchedProductUsers = await this.executeAudienceForProductUser(
node,
productUser
);
// If the AudienceBuilder returns a match for this node, then the ProductUser
// continues the campaign
if (matchedProductUsers.length === 1) {
// Mark first campaign node as completed for this product user, and queue up the next campaign node if it exists
return this.evaluateEntryNodeForProductUsers(node, matchedProductUsers);
}
});
return Promise.all(promises);
}
/**
* Evaluates the given node for the campaign.
*
* @param node AbstractCampaignNode The current node in the CampaignGraph
* @param state CampaignNodeState The current instance of the CampaignNode
* @returns On error: CampaignNodeState with an error state
* If there is a next node: Returns the next CampaignNodeState
* If there are no more nodes: Returns null
*/
async evaluateCampaignNode(
node: AbstractCampaignNode,
state: CampaignNodeState
) {
let executionResult: ExecutionResult;
let executor: AbstractNodeExecutor;
logger.info(
"[CampaignNodeEvaluator:evaluateNextNode] Evaluating Node ID: " +
node.getId()
);
// this node has timed out
if (moment(state.timeoutAt).isBefore(new Date())) {
// Mark as COMPLETED. Attempts should stay the same since nothing changed.
await state
.set({
state: CampaignStateEnum.COMPLETED,
didTimeout: true,
})
.save();
return this.evaluateTimedOutCampaignNode(node, state);
}
// Mark as RUNNING
await state
.set({
state: CampaignStateEnum.RUNNING,
attempts: state.attempts + 1,
runAt: new Date(),
})
.save();
// Get node executor based on type
executor = this.getExecutor(node);
try {
// Execute
executionResult = await executor.execute(state);
} catch (error) {
logger.error(
`[CampaignNodeEvaluator:evaluateNextNode] Error processing node ${node.getId()} of kind ${
node.kind
}:` + error
);
return await state
.set({
state: CampaignStateEnum.ERROR,
completedAt: new Date(),
})
.save();
}
// Node executed successfully
await state
.set({
state: CampaignStateEnum.COMPLETED,
completedAt: new Date(),
})
.save();
logger.info(
`[CampaignNodeEvaluator:evaluateNextNode] Execution result: ${executionResult}`
);
if (executionResult.result === ExecutionResultEnum.Continue) {
// Node executed successfully, get next default node and continue campaign
return this.createNextNodeState(node, state);
} else {
if (
executionResult.result === ExecutionResultEnum.End &&
node.kind === CampaignNodeKind.Filter
) {
return this.evaluateTimedOutCampaignNode(node, state);
}
return null;
}
}
async evaluateTimedOutCampaignNode(
node: AbstractCampaignNode,
state: CampaignNodeState
) {
// Node did not execute OR filter failed, get next nodes with edge kind of "Timeout" and continue campaign
const nextNodes = this.getAssociatedTimeoutNodes(node);
if (nextNodes.length === 0) {
// Campaign is finished
return null;
}
const campaignNodeStatePromises = nextNodes.map((nextNode) =>
CampaignNodeState.create({
campaignNodeId: nextNode.id,
productUserId: state.productUserId,
state: CampaignStateEnum.PENDING,
runAt: this.getRunAt(nextNode),
userId: this.userId,
campaignId: this.campaignId,
})
);
return Promise.all(campaignNodeStatePromises);
}
/**
* Creates the next set of `CampaignNodeState`s required to continue the Campaign.
*
* @param node CampaignNode
* @param state CampaignNodeState The current state of the campaign
* @returns Promise<CampaignNodeState[]>
*/
async createNextNodeState(
node: AbstractCampaignNode,
state: CampaignNodeState
) {
// Node executed successfully, get next nodes with edge kind of "Default" and continue campaign
const nextNodes = this.getAssociatedDefaultNodes(node);
if (nextNodes.length === 0) {
// Campaign is finished
return null;
}
const campaignNodeStatePromises = nextNodes.map((nextNode) =>
CampaignNodeState.create({
campaignNodeId: nextNode.id,
productUserId: state.productUserId,
state: CampaignStateEnum.PENDING,
runAt: this.getRunAt(nextNode),
timeoutAt: this.getTimeoutAt(nextNode),
userId: this.userId,
campaignId: this.campaignId,
})
);
return Promise.all(campaignNodeStatePromises);
}
/**
* Returns the executor which will perform the action for this node.
*
* @param node CampaignNode
* @returns Executor
*/
getExecutor(node: AbstractCampaignNode): AbstractNodeExecutor {
switch (node.kind) {
case CampaignNodeKind.Email:
return new EmailNodeExecutor(this.#app, node as EmailCampaignNode);
case CampaignNodeKind.Filter:
return new FilterNodeExecutor(this.#app, node as FilterCampaignNode);
case CampaignNodeKind.Wait:
return new WaitNodeExecutor(this.#app, node as WaitCampaignNode);
}
}
async executeAudience(entryNode: EntryNode) {
// get Audience ID from CampaignAudienceNode
const audience = await this.getAudience(entryNode.getAudienceId());
// Parse Audience JSON
const audienceNode = deserialize(JSON.parse(audience.node));
// Build and execute
return new AudienceBuilder(audienceNode, this.userId).build().execute();
}
async executeAudienceForProductUser(
entryNode: EntryNode,
productUser: ProductUser
) {
// get Audience ID from CampaignAudienceNode
const audience = await this.getAudience(entryNode.getAudienceId());
// Parse Audience JSON
const audienceNode = deserialize(JSON.parse(audience.node));
// Build and execute
return new AudienceBuilder(audienceNode, this.userId, {
productUserId: productUser.id,
})
.build()
.execute();
}
/**
* When the next node should be executed. Immediately for all nodes, except for the Wait node.
*
* @param campaignNode CampaignNode
* @returns Date
*/
getRunAt(campaignNode: AbstractCampaignNode) {
invariant(
this.calledBuild,
"Need to call CampaignNodeEvaluator.build() first"
);
if (campaignNode.kind === CampaignNodeKind.Wait) {
const waitNode = campaignNode as WaitCampaignNode;
const days = waitNode.getDays();
const runAt = moment(this.getNow()).add(days, "days");
return runAt.toDate();
}
if (campaignNode.kind === CampaignNodeKind.Email) {
const emailNode = campaignNode as EmailCampaignNode;
const scheduling = emailNode.getScheduling();
if (scheduling === CampaignEmailScheduling.Immediately) {
return this.getNow();
}
if (scheduling === CampaignEmailScheduling.BusinessHours) {
return this.getNextBusinessHour();
}
// TODO
if (scheduling === CampaignEmailScheduling.SpecificTime) {
return moment(this.getNow()).hour(11).minute(30).toDate();
}
}
return this.getNow();
}
getTimeoutAt(campaignNode: AbstractCampaignNode) {
invariant(
this.calledBuild,
"Need to call CampaignNodeEvaluator.build() first"
);
if (campaignNode.kind === CampaignNodeKind.Filter) {
const filterNode = campaignNode as FilterCampaignNode;
const days = filterNode.getWaitValue();
if (days === 0) {
return null;
}
const runAt = moment(this.getNow()).add(days, "days");
return runAt.toDate();
}
return null;
}
/**
*
* @returns
*/
getNextBusinessHour() {
const hour = moment().hour();
if (hour < 9) {
return moment(this.getNow()).hour(9).minute(0).toDate();
}
if (hour > 17) {
return moment(this.getNow()).add(1, "day").hour(hour).minute(0).toDate();
}
return this.getNow();
}
/**
* The current Date.
*
* @returns Date
*/
getNow() {
return new Date();
}
/**
* Gets the list of CampaignNodes that can start a Campaign.
*
* @returns A list of AudienceNode and/or TriggerNodes.
*/
getEntryNodes(): EntryNodeKinds[] {
invariant(
this.calledBuild,
"Need to call CampaignNodeEvaluator.build() first"
);
return this.nodes.filter(
(node) =>
node.kind === CampaignNodeKind.Audience ||
node.kind === CampaignNodeKind.Trigger
) as EntryNodeKinds[];
}
/**
* Returns a list of CampaignNodes that should execute next if the current node is marked as COMPLETED.
*
* @param currentNode
* @returns
*/
getAssociatedDefaultNodes(
currentNode: AbstractCampaignNode
): AbstractCampaignNode[] {
return this.getNodesForEdgeKind(currentNode, EdgeKind.Default);
}
/**
* Returns a list of CampaignNodes that should run if the node times out.
*
* @param currentNode
* @returns
*/
getAssociatedTimeoutNodes(
currentNode: AbstractCampaignNode
): AbstractCampaignNode[] {
return this.getNodesForEdgeKind(currentNode, EdgeKind.Timeout);
}
/**
* Returns a list of CampaignNodes associated by an Edge of kind `edgeKind`.
*
* @param currentNode CampaignNode for the current step of the Campaign
* @param edgeKind The kind of outgoing edge (Default or Timeout) we'd like to find
* @returns The list of CampaignNodes connected to `currentNode` with an Edge of kind `edgeKind`
*/
getNodesForEdgeKind(
currentNode: AbstractCampaignNode,
edgeKind: EdgeKind
): AbstractCampaignNode[] {
invariant(
this.calledBuild,
"Need to call CampaignNodeEvaluator.build() first"
);
// Get edges with type Timeout
const edges = this.graph.getOutgoingEdges(currentNode);
const matchingEdges = edges.filter((e) => e.getEdgeKind() === edgeKind);
// Get nodes associated with our edge(s)
return matchingEdges.map((edge) => {
const toId = edge.getToId();
return this.graph.getNodeById(toId);
});
}
async getAudience(audienceId: string) {
return this.#app.repositories.audienceRepository.getAudience(
audienceId,
this.userId
);
}
}
export default CampaignNodeEvaluator; | the_stack |
import {
DataInterface,
DataInterfaceForEachOptions,
DataInterfaceGetIdsOptions,
DataInterfaceGetOptions,
DataInterfaceGetOptionsArray,
DataInterfaceGetOptionsObject,
DataInterfaceMapOptions,
EventCallbacksWithAny,
EventName,
EventPayloads,
FullItem,
Id,
PartItem,
RemoveEventPayload,
UpdateEventPayload,
isId,
} from "./data-interface";
import { DataSet } from "./data-set";
import { DataSetPart } from "./data-set-part";
import { DataStream } from "./data-stream";
/**
* Data view options.
*
* @typeParam Item - Item type that may or may not have an id.
* @typeParam IdProp - Name of the property that contains the id.
*/
export interface DataViewOptions<Item, 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;
/** Items can be filtered on specific properties by providing a filter function. A filter function is executed for each of the items in the DataSet, and is called with the item as parameter. The function must return a boolean. All items for which the filter function returns true will be emitted. */
filter?: (item: Item) => boolean;
}
/**
* DataView
*
* A DataView offers a filtered and/or formatted view on a DataSet. One can subscribe to changes in a DataView, and easily get filtered or formatted data without having to specify filters and field types all the time.
*
* ## Example
* ```javascript
* // create a DataSet
* var data = new vis.DataSet();
* 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'}
* ]);
*
* // create a DataView
* // the view will only contain items having a property group with value 1,
* // and will only output fields id, text, and date.
* var view = new vis.DataView(data, {
* filter: function (item) {
* return (item.group == 1);
* },
* fields: ['id', 'text', 'date']
* });
*
* // subscribe to any change in the DataView
* view.on('*', function (event, properties, senderId) {
* console.log('event', event, properties);
* });
*
* // update an item in the data set
* data.update({id: 2, group: 1});
*
* // get all ids in the view
* var ids = view.getIds();
* console.log('ids', ids); // will output [1, 2]
*
* // get all items in the view
* var items = view.get();
* ```
*
* @typeParam Item - Item type that may or may not have an id.
* @typeParam IdProp - Name of the property that contains the id.
*/
export class DataView<
Item extends PartItem<IdProp>,
IdProp extends string = "id"
>
extends DataSetPart<Item, IdProp>
implements DataInterface<Item, IdProp> {
/** @inheritDoc */
public length = 0;
/** @inheritDoc */
public get idProp(): IdProp {
return this.getDataSet().idProp;
}
private readonly _listener: EventCallbacksWithAny<Item, IdProp>["*"];
private _data!: DataInterface<Item, IdProp>; // constructor → setData
private readonly _ids: Set<Id> = new Set(); // ids of the items currently in memory (just contains a boolean true)
private readonly _options: DataViewOptions<Item, IdProp>;
/**
* Create a DataView.
*
* @param data - The instance containing data (directly or indirectly).
* @param options - Options to configure this data view.
*/
public constructor(
data: DataInterface<Item, IdProp>,
options?: DataViewOptions<Item, IdProp>
) {
super();
this._options = options || {};
this._listener = this._onEvent.bind(this);
this.setData(data);
}
// TODO: implement a function .config() to dynamically update things like configured filter
// and trigger changes accordingly
/**
* Set a data source for the view.
*
* @param data - The instance containing data (directly or indirectly).
*
* @remarks
* Note that when the data view is bound to a data set it won't be garbage
* collected unless the data set is too. Use `dataView.setData(null)` or
* `dataView.dispose()` to enable garbage collection before you lose the last
* reference.
*/
public setData(data: DataInterface<Item, IdProp>): void {
if (this._data) {
// unsubscribe from current dataset
if (this._data.off) {
this._data.off("*", this._listener);
}
// trigger a remove of all items in memory
const ids = this._data.getIds({ filter: this._options.filter });
const items = this._data.get(ids);
this._ids.clear();
this.length = 0;
this._trigger("remove", { items: ids, oldData: items });
}
if (data != null) {
this._data = data;
// trigger an add of all added items
const ids = this._data.getIds({ filter: this._options.filter });
for (let i = 0, len = ids.length; i < len; i++) {
const id = ids[i];
this._ids.add(id);
}
this.length = ids.length;
this._trigger("add", { items: ids });
} else {
this._data = new DataSet<Item, IdProp>();
}
// subscribe to new dataset
if (this._data.on) {
this._data.on("*", this._listener);
}
}
/**
* Refresh the DataView.
* Useful when the DataView has a filter function containing a variable parameter.
*/
public refresh(): void {
const ids = this._data.getIds({
filter: this._options.filter,
});
const oldIds = [...this._ids];
const newIds: Record<Id, boolean> = {};
const addedIds: Id[] = [];
const removedIds: Id[] = [];
const removedItems: FullItem<Item, IdProp>[] = [];
// check for additions
for (let i = 0, len = ids.length; i < len; i++) {
const id = ids[i];
newIds[id] = true;
if (!this._ids.has(id)) {
addedIds.push(id);
this._ids.add(id);
}
}
// check for removals
for (let i = 0, len = oldIds.length; i < len; i++) {
const id = oldIds[i];
const item = this._data.get(id);
if (item == null) {
// @TODO: Investigate.
// Doesn't happen during tests or examples.
// Is it really impossible or could it eventually happen?
// How to handle it if it does? The types guarantee non-nullable items.
console.error("If you see this, report it please.");
} else if (!newIds[id]) {
removedIds.push(id);
removedItems.push(item);
this._ids.delete(id);
}
}
this.length += addedIds.length - removedIds.length;
// trigger events
if (addedIds.length) {
this._trigger("add", { items: addedIds });
}
if (removedIds.length) {
this._trigger("remove", { items: removedIds, oldData: removedItems });
}
}
/** @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<string, FullItem<Item, IdProp>> {
if (this._data == null) {
return null;
}
// parse the arguments
let ids: Id | Id[] | null = null;
let options: any;
if (isId(first) || Array.isArray(first)) {
ids = first;
options = second;
} else {
options = first;
}
// extend the options with the default options and provided options
const viewOptions: DataInterfaceGetOptions<Item> = Object.assign(
{},
this._options,
options
);
// create a combined filter method when needed
const thisFilter = this._options.filter;
const optionsFilter = options && options.filter;
if (thisFilter && optionsFilter) {
viewOptions.filter = (item): boolean => {
return thisFilter(item) && optionsFilter(item);
};
}
if (ids == null) {
return this._data.get(viewOptions);
} else {
return this._data.get(ids, viewOptions);
}
}
/** @inheritDoc */
public getIds(options?: DataInterfaceGetIdsOptions<Item>): Id[] {
if (this._data.length) {
const defaultFilter = this._options.filter;
const optionsFilter = options != null ? options.filter : null;
let filter: DataInterfaceGetIdsOptions<Item>["filter"];
if (optionsFilter) {
if (defaultFilter) {
filter = (item): boolean => {
return defaultFilter(item) && optionsFilter(item);
};
} else {
filter = optionsFilter;
}
} else {
filter = defaultFilter;
}
return this._data.getIds({
filter: filter,
order: options && options.order,
});
} else {
return [];
}
}
/** @inheritDoc */
public forEach(
callback: (item: Item, id: Id) => void,
options?: DataInterfaceForEachOptions<Item>
): void {
if (this._data) {
const defaultFilter = this._options.filter;
const optionsFilter = options && options.filter;
let filter: undefined | ((item: Item) => boolean);
if (optionsFilter) {
if (defaultFilter) {
filter = function (item: Item): boolean {
return defaultFilter(item) && optionsFilter(item);
};
} else {
filter = optionsFilter;
}
} else {
filter = defaultFilter;
}
this._data.forEach(callback, {
filter: filter,
order: options && options.order,
});
}
}
/** @inheritDoc */
public map<T>(
callback: (item: Item, id: Id) => T,
options?: DataInterfaceMapOptions<Item, T>
): T[] {
type Filter = NonNullable<DataInterfaceMapOptions<Item, T>["filter"]>;
if (this._data) {
const defaultFilter = this._options.filter;
const optionsFilter = options && options.filter;
let filter: undefined | Filter;
if (optionsFilter) {
if (defaultFilter) {
filter = (item): ReturnType<Filter> => {
return defaultFilter(item) && optionsFilter(item);
};
} else {
filter = optionsFilter;
}
} else {
filter = defaultFilter;
}
return this._data.map(callback, {
filter: filter,
order: options && options.order,
});
} else {
return [];
}
}
/** @inheritDoc */
public getDataSet(): DataSet<Item, IdProp> {
return this._data.getDataSet();
}
/** @inheritDoc */
public stream(ids?: Iterable<Id>): DataStream<Item> {
return this._data.stream(
ids || {
[Symbol.iterator]: this._ids.keys.bind(this._ids),
}
);
}
/**
* Render the instance unusable prior to garbage collection.
*
* @remarks
* The intention of this method is to help discover scenarios where the data
* view is being used when the programmer thinks it has been garbage collected
* already. It's stricter version of `dataView.setData(null)`.
*/
public dispose(): void {
if (this._data?.off) {
this._data.off("*", this._listener);
}
const message = "This data view has already been disposed of.";
const replacement = {
get: (): void => {
throw new Error(message);
},
set: (): void => {
throw new Error(message);
},
configurable: false,
};
for (const key of Reflect.ownKeys(DataView.prototype)) {
Object.defineProperty(this, key, replacement);
}
}
/**
* Event listener. Will propagate all events from the connected data set to the subscribers of the DataView, but will filter the items and only trigger when there are changes in the filtered data set.
*
* @param event - The name of the event.
* @param params - Parameters of the event.
* @param senderId - Id supplied by the sender.
*/
private _onEvent<EN extends EventName>(
event: EN,
params: EventPayloads<Item, IdProp>[EN],
senderId?: Id | null
): void {
if (!params || !params.items || !this._data) {
return;
}
const ids = params.items;
const addedIds: Id[] = [];
const updatedIds: Id[] = [];
const removedIds: Id[] = [];
const oldItems: FullItem<Item, IdProp>[] = [];
const updatedItems: FullItem<Item, IdProp>[] = [];
const removedItems: FullItem<Item, IdProp>[] = [];
switch (event) {
case "add":
// filter the ids of the added items
for (let i = 0, len = ids.length; i < len; i++) {
const id = ids[i];
const item = this.get(id);
if (item) {
this._ids.add(id);
addedIds.push(id);
}
}
break;
case "update":
// determine the event from the views viewpoint: an updated
// item can be added, updated, or removed from this view.
for (let i = 0, len = ids.length; i < len; i++) {
const id = ids[i];
const item = this.get(id);
if (item) {
if (this._ids.has(id)) {
updatedIds.push(id);
updatedItems.push(
(params as UpdateEventPayload<Item, IdProp>).data[i]
);
oldItems.push(
(params as UpdateEventPayload<Item, IdProp>).oldData[i]
);
} else {
this._ids.add(id);
addedIds.push(id);
}
} else {
if (this._ids.has(id)) {
this._ids.delete(id);
removedIds.push(id);
removedItems.push(
(params as UpdateEventPayload<Item, IdProp>).oldData[i]
);
} else {
// nothing interesting for me :-(
}
}
}
break;
case "remove":
// filter the ids of the removed items
for (let i = 0, len = ids.length; i < len; i++) {
const id = ids[i];
if (this._ids.has(id)) {
this._ids.delete(id);
removedIds.push(id);
removedItems.push(
(params as RemoveEventPayload<Item, IdProp>).oldData[i]
);
}
}
break;
}
this.length += addedIds.length - removedIds.length;
if (addedIds.length) {
this._trigger("add", { items: addedIds }, senderId);
}
if (updatedIds.length) {
this._trigger(
"update",
{ items: updatedIds, oldData: oldItems, data: updatedItems },
senderId
);
}
if (removedIds.length) {
this._trigger(
"remove",
{ items: removedIds, oldData: removedItems },
senderId
);
}
}
} | the_stack |
import {
ConnectedPosition,
Overlay,
OverlayConfig,
OverlayRef,
ScrollStrategy,
ScrollStrategyOptions,
} from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import {
AfterViewInit,
Component,
ElementRef,
OnDestroy,
TemplateRef,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import {
NavigationEnd,
NavigationStart,
Params,
Router,
} from '@angular/router';
import { combineLatest, merge, Subscription } from 'rxjs';
import { filter, finalize, map, skip, take, takeUntil } from 'rxjs/operators';
import { ScoredItem, Tweet } from '../../common-types';
import { ClearReportDialogComponent } from '../clear-report-dialog/clear-report-dialog.component';
import { TOXICITY_FILTER_NAME_QUERY_PARAM } from '../create-report/create-report.component';
import { DateFilterService } from '../date-filter.service';
import { applyCommentFilters, buildDateFilterForNDays } from '../filter_utils';
import {
EventAction,
EventCategory,
GoogleAnalyticsService,
} from '../google_analytics.service';
import { LoadingDialogComponent } from '../loading-dialog/loading-dialog.component';
import { OauthApiService } from '../oauth_api.service';
import { OnboardingService } from '../onboarding.service';
import {
RecommendedReportData,
RECOMMENDED_REPORT_TEMPLATES,
TOXICITY_RANGE_TEMPLATES,
} from '../recommended-report-card/recommended-report-card.component';
import { getRouterLinkForReportStep, ReportService } from '../report.service';
import { SocialMediaItemService } from '../social-media-item.service';
// Width of a card + padding.
const SCROLL_INCREMENT = 444;
// This needs to be long enough for a screenreader to be able to read the dialog
// title and say that we've entered a dialog.
const MIN_LOADING_DIALOG_OPEN_TIME_MS = 8000;
// How many times to reload the RecommendedReportCards if there's an error
const RELOAD_ATTEMPTS = 3;
enum OnboardingStep {
NONE,
INTRO_STEPPER,
HIGHLIGHT_CARD,
}
@Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.scss'],
})
export class HomePageComponent implements AfterViewInit, OnDestroy {
// Copy of enum for use in the template.
readonly OnboardingStep = OnboardingStep;
currentOnboardingStep = OnboardingStep.NONE;
overlayScrollStrategy: ScrollStrategy;
routeSubscription: Subscription = new Subscription();
// This describes how the overlay should be connected to the origin element.
// We want it centered below the card.
connectedOverlayPositions: ConnectedPosition[] = [
{
originX: 'center',
originY: 'bottom',
overlayX: 'center',
overlayY: 'top',
offsetY: 24,
},
// Alternate position if the first doesn't fit onscreen.
{
originX: 'center',
originY: 'top',
overlayX: 'center',
overlayY: 'bottom',
offsetY: -24,
},
];
@ViewChild('templatePortalContent')
templatePortalContent!: TemplateRef<unknown>;
private overlayRef: OverlayRef | null = null;
private comments?: Array<ScoredItem<Tweet>>;
recommendedReports: RecommendedReportData[] = RECOMMENDED_REPORT_TEMPLATES.map(
template => ({
toxicityRangeFilter: template.toxicityRangeFilter,
name: template.name,
routing_name: template.routing_name,
description: template.description,
icon: template.icon,
comments: [],
})
);
loadingRecommendedReports = false;
loadingRecommendedReportsAttempts = 0;
loadingDialogOpen = false;
loadingDialogOpenTime: number | null = null;
errorRecommendedReports = true;
shouldShowWelcomeBackCard = false;
@ViewChild('cardsContainer') cardsContainer!: ElementRef;
clearReportDialogOpen = false;
name = '';
onboardingComplete = false;
reportDraftCommentCount = 0;
snackBarSubscription?: Subscription;
// Set to true when the user has clicked the "add all to report" button on one
// of the priority cards.
userClickedAddAllToReport = false;
constructor(
private readonly dateFilterService: DateFilterService,
private readonly dialog: MatDialog,
private readonly oauthApiService: OauthApiService,
private readonly onboardingService: OnboardingService,
private readonly overlay: Overlay,
private readonly reportService: ReportService,
private readonly router: Router,
private readonly scrollStrategyOptions: ScrollStrategyOptions,
private readonly socialMediaItemService: SocialMediaItemService,
private readonly viewContainerRef: ViewContainerRef,
private readonly snackBar: MatSnackBar,
private readonly googleAnalyticsService: GoogleAnalyticsService
) {
this.overlayScrollStrategy = this.scrollStrategyOptions.block();
// If there's an error loading the RecommendedReportCards attempt
// to reload them each time the user renavigates to the home page
// until the max RELOAD_ATTEMPTS is reached.
this.routeSubscription = this.router.events
.pipe(
filter(event => event instanceof NavigationEnd && event.url === '/home')
)
.subscribe(event => {
if (
this.errorRecommendedReports &&
this.loadingRecommendedReportsAttempts < RELOAD_ATTEMPTS
) {
this.getRecommendedReports();
} else {
this.routeSubscription.unsubscribe();
}
});
this.reportService.reportCommentsChanged.subscribe(reportComments => {
const reportNotificationCommentCount = Math.max(
0,
reportComments.length - this.reportDraftCommentCount
);
// Without this guard this shows up when the user re-logs in; it should
// only show up after the user has directly triggered the event via
// clicking the "Add all to report" button.
if (this.userClickedAddAllToReport) {
const singular = reportNotificationCommentCount === 1;
const message =
reportNotificationCommentCount > 0
? `${reportNotificationCommentCount} ${
singular ? 'comment' : 'comments'
} added to report`
: 'Comments already added to report';
const snackBarRef = snackBar.open(message, 'Edit Details', {
duration: 10000,
});
// Navigate to the review report (edit details) page when the user
// clicks on the action on the snackbar.
this.snackBarSubscription = snackBarRef
.onAction()
.pipe(take(1))
.subscribe(() => {
snackBarRef.dismiss();
snackBarRef
.afterDismissed()
.pipe(take(1))
.subscribe(() => {
this.router.navigate(['/review-report']);
});
});
this.userClickedAddAllToReport = false;
}
this.reportDraftCommentCount = reportComments.length;
});
this.showWelcomeBackCard();
}
ngOnDestroy() {
if (this.snackBarSubscription) {
this.snackBarSubscription.unsubscribe();
}
}
openLoadingDialog() {
if (this.comments || this.loadingDialogOpen) {
return;
}
const dialogRef = this.dialog.open(LoadingDialogComponent, {
panelClass: 'loading-dialog-container',
});
this.loadingDialogOpen = true;
this.loadingDialogOpenTime = Date.now();
dialogRef
.afterClosed()
.pipe(take(1))
.subscribe(() => {
this.loadingDialogOpen = false;
});
}
closeLoadingDialog() {
if (!this.loadingDialogOpen || !this.loadingDialogOpenTime) {
return;
}
const timeSinceLoadingDialogOpen = Date.now() - this.loadingDialogOpenTime;
const timeToCloseLoadingDialog = Math.max(
0,
MIN_LOADING_DIALOG_OPEN_TIME_MS - timeSinceLoadingDialogOpen
);
setTimeout(() => {
this.dialog.closeAll();
this.loadingDialogOpen = false;
}, timeToCloseLoadingDialog);
}
handleAddAllToReportClicked() {
this.userClickedAddAllToReport = true;
}
/** Navigate to the page where the user left off on the report. */
continueReport() {
this.router.navigate([
getRouterLinkForReportStep(this.reportService.getReportStep()),
]);
}
openClearReportDialog() {
// Open confirmation dialog.
if (this.clearReportDialogOpen) {
return;
}
const dialogRef = this.dialog.open(ClearReportDialogComponent, {
panelClass: 'clear-report-dialog-container',
});
this.clearReportDialogOpen = true;
dialogRef
.afterClosed()
.pipe(take(1))
.subscribe(result => {
this.clearReportDialogOpen = false;
if (result) {
this.reportService.clearReport();
}
});
}
getRecommendedReports() {
const dateFilter = buildDateFilterForNDays(
new Date(this.dateFilterService.getStartTimeMs()),
1
);
this.loadingRecommendedReports = true;
this.socialMediaItemService
.fetchItems(dateFilter.startDateTimeMs, dateFilter.endDateTimeMs)
.subscribe(
comments => {
this.closeLoadingDialog();
this.comments = comments;
this.generateRecommendedReports();
this.loadingRecommendedReports = false;
this.errorRecommendedReports = false;
},
error => {
this.closeLoadingDialog();
this.loadingRecommendedReportsAttempts++;
this.errorRecommendedReports = true;
this.loadingRecommendedReports = false;
}
);
}
ngAfterViewInit() {
// We have to wait for the ViewChild to load to start onboarding, so we do
// this in ngAfterViewInit.
this.onboardingService
.getHomePageOnboardingComplete()
.subscribe((onboarded: boolean) => {
if (onboarded) {
this.onboardingComplete = true;
this.openLoadingDialog();
} else {
this.nextOnboardingStep();
}
});
}
openStepper() {
const overlayConfig = new OverlayConfig({
positionStrategy: this.overlay
.position()
.global()
.centerHorizontally()
.centerVertically(),
scrollStrategy: this.overlayScrollStrategy,
hasBackdrop: true,
backdropClass: 'onboarding-backdrop',
minWidth: 748,
minHeight: 582,
});
this.overlayRef = this.overlay.create(overlayConfig);
const introStepperPortal = new TemplatePortal(
this.templatePortalContent,
this.viewContainerRef
);
this.overlayRef.attach(introStepperPortal);
}
closeStepper() {
if (!this.overlayRef) {
throw new Error('Requesting to close a null overlayRef');
}
this.overlayRef.detach();
this.overlayRef.dispose();
this.overlayRef = null;
this.nextOnboardingStep();
}
async nextOnboardingStep() {
if (this.onboardingComplete) {
return;
}
if (this.currentOnboardingStep === OnboardingStep.NONE) {
this.currentOnboardingStep = OnboardingStep.INTRO_STEPPER;
this.openStepper();
} else if (this.currentOnboardingStep === OnboardingStep.INTRO_STEPPER) {
this.currentOnboardingStep = OnboardingStep.HIGHLIGHT_CARD;
} else if (this.currentOnboardingStep === OnboardingStep.HIGHLIGHT_CARD) {
this.currentOnboardingStep = OnboardingStep.NONE;
await this.onboardingService.setHomePageOnboardingComplete();
this.onboardingComplete = true;
this.openLoadingDialog();
}
}
async handleHighlightedCardViewCommentsClick() {
// We need to await the completion of nextOnboardingStep() before
// navigating, otherwise we can end up in a buggy state where the overlay is
// still visible.
await this.nextOnboardingStep();
this.viewCommentsWithToxicityFilter(this.recommendedReports[1]);
}
viewCommentsWithToxicityFilter(filter: RecommendedReportData) {
const queryParams: Params = {};
if (filter.name === 'Unknown') {
queryParams[TOXICITY_FILTER_NAME_QUERY_PARAM] = [
// Unsure
TOXICITY_RANGE_TEMPLATES[2].name,
// Unable to score
TOXICITY_RANGE_TEMPLATES[4].name,
];
} else {
queryParams[TOXICITY_FILTER_NAME_QUERY_PARAM] =
filter.routing_name || filter.name;
}
if (filter.name === 'All') {
this.googleAnalyticsService.emitEvent(
EventCategory.VIEW_ALL_COMMENTS_BUTTON,
EventAction.CLICK
);
}
this.router.navigate(['/create-report'], { queryParams });
}
generateRecommendedReports() {
if (this.comments) {
for (const report of this.recommendedReports) {
report.comments = applyCommentFilters(this.comments, {
toxicityRangeFilters: [report.toxicityRangeFilter],
});
}
}
}
private showWelcomeBackCard() {
// Listen for the initial data load for all report fields and emit a boolean
// indicating whether the field has any data. We `skip(1)` because the
// Observables exposed by ReportService always emit once for the default
// (empty) value of the underlying BehaviorSubjects. We then `take(1)`
// because the second emission should occur only if/when any data is
// actually loaded from an in-progress report.
const reportHasComments = this.reportService.reportCommentsChanged.pipe(
skip(1),
take(1),
map(comments => comments.length > 0)
);
const reportHasContext = this.reportService.reportContextChanged.pipe(
skip(1),
take(1),
map(context => !!context.length)
);
const reportHasReasons = this.reportService.reportReasonsChanged.pipe(
skip(1),
take(1),
map(reasons => !!reasons.length)
);
// Emit whenever any of the report data fields emit.
const reportFieldsHaveData = merge(
reportHasComments,
reportHasContext,
reportHasReasons
);
// Listen for when a user navigates away from the home page.
const userNavigatedAway = this.router.events.pipe(
filter(event => event instanceof NavigationStart && event.url !== '/home')
);
// Listen for when a user signs in and any in-progress report data is
// loaded. We display the welcome back tile if the user has signed in and
// the user has an existing report with non-empty actions, comments, or
// reasons.
//
// We stop listening if:
// 1) The user navigates away from the home page, or
// 2) The user clears the report on the home page
//
// We finally hide the card whenever we stop listening.
combineLatest([
this.oauthApiService.twitterSignInChange,
reportFieldsHaveData,
])
.pipe(
filter(
([signedIn, reportFieldsHaveData]) => signedIn && reportFieldsHaveData
),
takeUntil(userNavigatedAway),
takeUntil(this.reportService.reportCleared),
finalize(() => {
this.shouldShowWelcomeBackCard = false;
})
)
.subscribe(() => {
this.shouldShowWelcomeBackCard = true;
this.name =
this.oauthApiService.getTwitterCredentials()?.user?.displayName ?? '';
});
}
} | the_stack |
import { Component, State, Element, h } from '@stencil/core';
import '@visa/visa-charts-data-table';
import '@visa/keyboard-instructions';
@Component({
tag: 'app-pie-chart',
styleUrl: 'app-pie-chart.scss'
})
export class AppPieChart {
@State() data: any;
@State() stateTrigger: any = 1;
@State() animations: any = { disabled: false };
@State() refStateTrigger: any = 0;
@State() hoverElement: any = '';
@State() chartUpdates: string;
@State() width: any = 500;
@State() height: any = 500;
@State() padding: any = {
top: 50,
left: 50,
right: 50,
bottom: 50
};
@State() clickElement: any = [
// { label: 'Competitor 2', value: '1000', otherValue: '4126000' }
];
@State() colorPalette: any = 'single_suppPink';
@State() edge: any = true;
@State() valueAccessor: any = 'value';
@State() refData: any;
@State() edgeline: any = true;
@State() access: any = {
includeDataKeyNames: true,
longDescription:
'This is a chart template that was made to showcase some of the capabilities of Visa Chart Components',
contextExplanation:
'This chart current data is determined by the Change Data button above while the props used are set in the props controls below.',
purpose:
'The purpose of this chart template is to provide an example of how to build a basic pie chart using the chart library',
statisticalNotes: 'This chart is using dummy data.',
disableValidation: false,
keyboardNavConfig: { disabled: false }
};
@State() suppressEvents: boolean = false;
@State() annotations: any = [
{
note: {
label: '2018',
bgPadding: 0,
align: 'middle',
wrap: 210
},
accessibilityDescription: '2018 High Spend band total is 5,596',
x: '8%',
y: '40%',
disable: ['connector', 'subject'],
// dy: '-1%',
color: '#000000',
className: 'testing1 testing2 testing3',
collisionHideOnly: true
},
{
note: {
label: 'oasijfoiajsf',
bgPadding: 0,
align: 'middle',
wrap: 210
},
accessibilityDescription: '2018 High Spend band total is 5,596',
x: '8%',
y: '40%',
disable: ['connector', 'subject'],
// dy: '-1%',
color: '#000000',
className: 'testing1 testing2 testing3',
collisionHideOnly: false
}
];
refDataStorage: any = [
[{ label: 'Dining', value: '6931260' }],
[{ label: 'Dining', value: '2931260' }],
[{ label: '', value: false }]
];
startData: any = [
{ label: '2018 Share', value: '3126000', otherValue: '4226000' },
{ label: 'Total', value: '4324500', otherValue: '5126000' }
];
dataStorage: any = [
this.startData,
[
{ label: '2018 Share', value: '1000', otherValue: '6126000' },
{ label: 'Competitor 1', value: '1000', otherValue: '5126000' },
{ label: 'Competitor 2', value: '1000', otherValue: '4126000' },
{ label: 'Competitor 3', value: '6000', otherValue: '3126000' },
{ label: 'Competitor 4', value: '26000', otherValue: '1126000' }
],
[
{ label: '2018 Share', value: '3126000', otherValue: '8126000' },
{ label: 'Total', value: '4324500', otherValue: '5126000' }
],
[
{ label: '2018 Share', value: '2126000', otherValue: '2126000' },
{ label: 'Total', value: '4324500', otherValue: '5126000' }
],
[
{ label: '2018 Share', value: '2126000', otherValue: '4226000' },
{ label: 'Total', value: '2324500', otherValue: '5126000' }
],
[
{ label: '2018 Share', value: '20149000', otherValue: '9126000' },
{ label: 'Total', value: '4324500', otherValue: '5126000' }
]
];
dataLabel: any = {
visible: true,
placement: 'inside',
labelAccessor: 'value',
format: '$0[.][0]a',
collisionHideOnly: true
}; // format: 'normalized' };
ref = [{ label: 'PY Share', value: '3396000' }];
style = { color: 'supp_purple' };
@Element()
appEl: HTMLElement;
componentWillLoad() {
this.data = this.dataStorage[this.stateTrigger];
}
// componentWillUpdate() {
// // console.log('will update', this.clickElement);
// }
onClickFunc(evt) {
const d = evt.detail;
const index = this.clickElement.indexOf(d);
const newClicks = [...this.clickElement];
if (index > -1) {
newClicks.splice(index, 1);
} else {
newClicks.push(d);
}
this.clickElement = newClicks;
}
onHoverFunc(d) {
this.hoverElement = d.detail;
}
onMouseOut() {
this.hoverElement = '';
}
onChangeFunc(d) {
if (d.updated && (d.removed || d.added)) {
let updates = 'The pie chart has ';
if (d.removed) {
updates += 'removed ' + d.removed + ' bar' + (d.removed > 1 ? 's ' : ' ');
}
if (d.added) {
updates += (d.removed ? 'and ' : '') + 'added ' + d.added + (d.removed ? '' : d.added > 1 ? ' bars' : ' bar');
}
this.chartUpdates = updates;
} else if (d.updated) {
const newUpdate = "The chart's data has changed, but no bars were removed or added.";
this.chartUpdates =
newUpdate !== this.chartUpdates
? newUpdate
: "The chart's data has changed again, but no bars were removed or added.";
}
}
changeData() {
this.stateTrigger = this.stateTrigger < this.dataStorage.length - 1 ? this.stateTrigger + 1 : 0;
this.data = this.dataStorage[this.stateTrigger];
}
changeAccessElements() {
this.access = {
...this.access,
elementsAreInterface: !this.access.elementsAreInterface
};
}
changeKeyNav() {
const keyboardNavConfig = {
disabled: !this.access.keyboardNavConfig.disabled
};
this.access = {
...this.access,
keyboardNavConfig
};
}
toggleSuppress() {
this.suppressEvents = !this.suppressEvents;
}
changeDimension() {
if (this.width !== 200) {
this.width = 200;
this.height = 200;
} else {
this.width = 300;
this.height = 300;
}
}
changePadding() {
if (this.padding.top !== 80) {
this.padding = {
top: 80,
left: 60,
right: 30,
bottom: 40
};
} else {
this.padding = {
top: 180,
left: 160,
right: 130,
bottom: 140
};
}
}
changeCP() {
this.colorPalette !== 'single_suppPink'
? (this.colorPalette = 'single_suppPink')
: (this.colorPalette = 'single_compGreen');
}
changeEdgeline() {
this.edgeline = this.edgeline ? false : true;
console.log('showEdgeline is now set to ', this.edgeline);
}
changeValueAccessor() {
// this.valueAccessor !== 'value' ? (this.valueAccessor = 'value') : (this.valueAccessor = 'otherValue');
this.valueAccessor = this.valueAccessor !== 'value' ? 'value' : 'otherValue';
}
changeRefData() {
this.refStateTrigger = this.refStateTrigger < this.refDataStorage.length - 1 ? this.refStateTrigger + 1 : 0;
this.refData = this.refDataStorage[this.refStateTrigger];
}
toggleAnimations() {
this.animations = { disabled: !this.animations.disabled };
}
render() {
console.log('loaded!', this.chartUpdates);
this.data = this.dataStorage[this.stateTrigger];
this.refData = this.refDataStorage[this.refStateTrigger];
return (
<div>
<button
onClick={() => {
this.changeAccessElements();
}}
>
change elementsAreInterface
</button>
<button
onClick={() => {
this.toggleSuppress();
}}
>
toggle event suppression
</button>
<button
onClick={() => {
this.changeKeyNav();
}}
>
toggle keyboard nav
</button>
<button
onClick={() => {
this.changeData();
}}
>
change data
</button>
<button
onClick={() => {
this.changeDimension();
}}
>
change dimension
</button>
<button
onClick={() => {
this.changePadding();
}}
>
change padding
</button>
<button
onClick={() => {
this.changeValueAccessor();
}}
>
valueAccessor
</button>
<button
onClick={() => {
this.changeCP();
}}
>
change color palette
</button>
<button
onClick={() => {
this.changeRefData();
}}
>
remove ref data
</button>
<button
onClick={() => {
this.changeEdgeline();
}}
>
toggle showEdgeLine
</button>
<button
onClick={() => {
this.toggleAnimations();
}}
>
toggle animations
</button>
<div>
<pie-chart
data={this.data}
animationConfig={this.animations}
mainTitle={'test'}
subTitle={''}
centerSubTitle={''}
centerTitle={'Pie'}
accessibility={this.access}
suppressEvents={this.suppressEvents}
height={this.height}
width={this.width}
padding={this.padding}
ordinalAccessor={'label'}
valueAccessor={this.valueAccessor}
innerRatio={0.1} // {0.0000000001}
dataLabel={this.dataLabel}
labelOffset={25}
showLabelNote={true}
// colors={['blue','grey','brown','darkgreen','#eeeeee']}
colorPalette={'categorical'}
hoverOpacity={0.15}
cursor={'pointer'}
sortOrder={'default'}
showTooltip={true}
showPercentage={false}
showEdgeLine={this.edgeline}
// annotations={this.annotations}
// referenceData={this.refData}
// referenceStyle={{ color: 'supp_purple' }}
// interactionKeys={['category']}
hoverHighlight={this.hoverElement}
clickHighlight={this.clickElement}
onClickFunc={d => this.onClickFunc(d)}
onHoverFunc={d => this.onHoverFunc(d)}
onMouseOutFunc={() => this.onMouseOut()}
/>
</div>
<div>
{/* <pie-chart
centerSubTitle={'United States'}
centerTitle={'42%'}
colorPalette={this.colorPalette}
data={[{ label: 'United States', value: 3126000 }, { label: 'Others', value: 4324500 }]}
// data={this.data}
ordinalAccessor={'label'}
valueAccessor={'value'}
dataLabel={{ visible: true, placement: 'outside', labelAccessor: 'value', format: '$0.0[a]' }}
height={325}
accessibility={{
includeDataKeyNames: true,
longDescription:
'This is a chart template that was made to showcase some of the capabilities of Visa Chart Components',
contextExplanation:
'This chart current data is determined by the Change Data button above while the props used are set in the props controls below.',
purpose:
'The purpose of this chart template is to provide an example of how to build a basic pie chart using the chart library',
statisticalNotes: 'This chart is using dummy data.',
disableValidation: true
}}
innerRatio={0.8}
mainTitle={'Emphasis'}
showEdgeLine={true}
showLabelNote={true}
showPercentage={false}
subTitle={''}
referenceData={this.refData}
referenceStyle={{ color: 'supp_purple' }}
tooltipLabel={{
labelAccessor: ['label', 'value'],
labelTitle: ['', 'Count'],
format: ['', '0,0.0[a]']
}}
width={600}
/> */}
</div>
</div>
);
}
} | the_stack |
*
* ## Penumbra Type Definitions
* Common type definitions used throughout penumbra functions.
*
* @module penumbra/types
* @see module:penumbra
*/
// local
import penumbra from './API';
import { PenumbraSupportLevel } from './enums';
import { PenumbraError } from './error';
import { PenumbraZipWriter } from './zip';
export { PenumbraZipWriter } from './zip';
/**
* Make selected object keys defined by K optional in type T
*/
type Optionalize<T, K extends keyof T> = Omit<T, K> & Partial<T>;
/**
* penumbra.encrypt() encryption options config (buffers or base64-encoded strings)
*/
export type PenumbraEncryptionOptions = {
/** Encryption key */
key: string | Buffer;
};
/**
* Parameters (buffers or base64-encoded strings) to decrypt content encrypted with penumbra.encrypt()
*/
export type PenumbraDecryptionInfo = PenumbraEncryptionOptions & {
/** Initialization vector */
iv: string | Buffer;
/** Authentication tag (for AES GCM) */
authTag: string | Buffer;
};
/**
* Buffers only plz
*/
export type PenumbraDecryptionInfoAsBuffer = Omit<
PenumbraDecryptionInfo,
'iv'
> & {
/** Iv is a buffer */
iv: Buffer;
};
/**
* A file to download from a remote resource, that is optionally encrypted
*/
export type RemoteResource = {
/** The URL to fetch the encrypted or unencrypted file from */
url: string;
/** The mimetype of the resulting file */
mimetype?: string;
/** The name of the underlying file without the extension */
filePrefix?: string;
/** If the file is encrypted, these are the required params */
decryptionOptions?: PenumbraDecryptionInfo;
/** Relative file path (needed for zipping) */
path?: string;
/** Fetch options */
requestInit?: RequestInit;
/** Last modified date */
lastModified?: Date;
/** Expected file size */
size?: number;
/**
* Disable calling .final() to validate the authTag.
*
* This is useful when providing x-penumbra-iv which is used
* when the iv is not known
*/
ignoreAuthTag?: boolean;
};
/** Penumbra file composition */
export type PenumbraFile = Omit<RemoteResource, 'url'> & {
/** Backing stream */
stream: ReadableStream;
/** File size (if backed by a ReadableStream) */
size?: number;
/** Optional ID for tracking encryption completion */
id?: number | string;
/** Last modified date */
lastModified?: Date;
};
/** Penumbra file that is currently being encrypted */
export type PenumbraFileWithID = PenumbraFile & {
/** ID for tracking encryption completion */
id: number;
};
/** penumbra file (internal) */
export type PenumbraEncryptedFile = Omit<PenumbraFileWithID, 'stream'> & {
/** Encrypted output stream */
stream: ReadableStream;
};
/** Penumbra event types */
export type PenumbraEventType = 'decrypt' | 'encrypt' | 'zip';
/**
* Progress event details
*/
export type ProgressDetails = {
/** The job ID # or URL being downloaded from for decryption */
id: string | number;
/** The ID of the worker thread that is processing this job */
worker?: number | null;
/** Event type */
type: PenumbraEventType;
/** Percentage completed */
percent: number;
/** Total bytes read */
totalBytesRead: number;
/** Total number of bytes to read */
contentLength: number;
};
/**
* The type that is emitted as progress continuesZipWrite
*/
export type ProgressEmit = CustomEvent<ProgressDetails>;
/**
* Zip progress event details
*/
export type ZipProgressDetails = {
/** Percentage completed. `null` indicates indetermination */
percent: number | null;
/** The number of bytes or items written so far */
written: number;
/** The total number of bytes or items to write. `null` indicates indetermination */
size: number | null;
};
/**
* The type that is emitted as zip writes progresses
*/
export type ZipProgressEmit = CustomEvent<ZipProgressDetails>;
/**
* Zip completion event details
*/
export type ZipCompletionDetails = {};
/**
* The type that is emitted as progress continues
*/
export type ZipCompletionEmit = CustomEvent<ZipCompletionDetails>;
/**
* Penumbra error event details
*/
export type PenumbraErrorDetails = PenumbraError;
/** Penumbra error event */
export type PenumbraErrorEmit = CustomEvent<PenumbraErrorDetails>;
/**
* Encryption/decryption job completion event details
*/
export type JobCompletion = {
/** Worker ID */
worker?: number | null;
/** Job ID */
id: string | number;
/** Decryption config info */
decryptionInfo: PenumbraDecryptionInfo;
};
/**
* The type that is emitted as progress continues
*/
export type JobCompletionEmit = CustomEvent<JobCompletion>;
/**
* The type that is emitted when penumbra is ready
* to be used
*/
export type PenumbraReady = CustomEvent<{
/** Penumbra API object */
penumbra: PenumbraAPI;
}>;
/** Data returned by penumbra.getTextOrURI() */
export type PenumbraTextOrURI = {
/** Data type */
type: 'text' | 'uri';
/** Data */
data: string;
/** MIME type */
mimetype?: string;
};
/** Penumbra API */
export type PenumbraAPI = typeof penumbra;
/**
* Penumbra Worker API
*/
export type PenumbraWorkerAPI = {
/** Worker ID */
id: number;
/**
* Initializes Penumbra worker progress event forwarding
* to the main thread
*/
setup: (id: number, eventListener: (event: Event) => void) => Promise<void>;
/**
* Fetches a remote files, deciphers them (if encrypted), and returns ReadableStream[]
*
* @param writablePorts - The RemoteWritableStream MessagePorts corresponding to each resource
* @param resources - The remote resources to download
* @returns A readable stream of the deciphered file
*/
get: (
writablePorts: MessagePort[],
resources: RemoteResource[],
) => Promise<ReadableStream[]>;
/**
* Fetches remote files, deciphers them (if encrypted), and returns ArrayBuffer[]
*
* @param resources - The remote resources to download
* @returns A readable stream of the deciphered file
*/
getBuffers: (resources: RemoteResource[]) => Promise<ArrayBuffer[]>;
/**
* Streaming encryption of ReadableStreams
*
* @param ids - Unique identifier for tracking encryption completion
* @param sizes - Size of each file to encrypt (in bytes)
* @param writablePorts - Remote Web Stream writable ports (for emitting encrypted files)
* @param readablePorts - Remote Web Stream readable ports (for processing unencrypted files)
* @returns ReadableStream[] of the encrypted files
*/
encrypt: (
options: PenumbraEncryptionOptions | null,
ids: number[],
sizes: number[],
readablePorts: MessagePort[],
writablePorts: MessagePort[],
) => Promise<PenumbraDecryptionInfoAsBuffer[]>;
/**
* Buffered (non-streaming) encryption of ArrayBuffers
*
* @param buffers - The file buffers to encrypt
* @returns ArrayBuffer[] of the encrypted files
*/
encryptBuffers: (
options: PenumbraEncryptionOptions | null,
files: PenumbraFile[],
) => Promise<ArrayBuffer[]>;
/**
* Streaming decryption of ReadableStreams
*
* @param ids - Unique identifier for tracking decryption completion
* @param sizes - Size of each file to decrypt (in bytes)
* @param writablePorts - Remote Web Stream writable ports (for emitting encrypted files)
* @param readablePorts - Remote Web Stream readable ports (for processing unencrypted files)
* @returns ReadableStream[] of the decrypted files
*/
decrypt: (
options: PenumbraDecryptionInfo,
ids: number[],
sizes: number[],
readablePorts: MessagePort[],
writablePorts: MessagePort[],
) => Promise<void>;
/**
* Buffered (non-streaming) encryption of ArrayBuffers
*
* @param buffers - The file buffers to encrypt
* @returns ArrayBuffer[] of the encrypted files
*/
decryptBuffers: (
options: PenumbraDecryptionInfo,
files: PenumbraFile[],
) => Promise<ArrayBuffer[]>;
/**
* Creates a zip writer for saving PenumbraFiles which keeps
* their path data in-tact.
*
* @returns PenumbraZipWriter
*/
saveZip: () => PenumbraZipWriter;
/**
* Query Penumbra's level of support for the current browser.
*/
supported: () => PenumbraSupportLevel;
};
/**
* Worker location URLs. All fields are absolute URLs.
*/
export type WorkerLocation = {
/** The directory where the workers scripts are available */
base: URL;
/** The location of the Penumbra Worker script */
penumbra: URL;
/** The location of the StreamSaver ServiceWorker script */
StreamSaver: URL;
};
/**
* Worker location options. All options support relative URLs.
*/
export type WorkerLocationOptions = Partial<WorkerLocation>;
/**
* An individual Penumbra Worker's interfaces
*/
export type PenumbraWorker = {
/** Worker ID */
id: number;
/** PenumbraWorker's Worker interface */
worker: Worker;
/** PenumbraWorker's Comlink interface */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
comlink: any;
/** Busy status (currently processing jobs) */
busy: boolean;
};
/**
* An individual Penumbra ServiceWorker's interfaces
*/
export type PenumbraServiceWorker = {
/** PenumbraWorker's Worker interface */
worker: ServiceWorker;
/** PenumbraWorker's Comlink interface */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
comlink: any;
};
/** The penumbra workers themselves */
export type PenumbraWorkers = {
/** The decryption Worker */
decrypt: PenumbraWorker;
/** The encryption Worker */
encrypt: PenumbraWorker;
/** The zip Worker */
zip: PenumbraWorker;
/** The StreamSaver ServiceWorker */
StreamSaver?: PenumbraServiceWorker;
};
/** Worker->main thread progress forwarder */
export type EventForwarder = {
/** Comlink-proxied main thread progress event transfer handler */
handler?: (event: Event) => void;
};
/** PenumbraZipWriter constructor options */
export type ZipOptions = Partial<{
/** Filename to save to (.zip is optional) */
name?: string;
/** Total size of archive (if known ahead of time, for 'store' compression level) */
size?: number;
/** Files (in-memory & remote) to add to zip archive */
files: PenumbraFile[];
/** Abort controller for cancelling zip generation and saving */
controller: AbortController;
/** Allow & auto-rename duplicate files sent to writer. Defaults to on */
allowDuplicates: boolean;
/** Zip archive compression level */
compressionLevel: number;
/** Store a copy of the resultant zip file in-memory for inspection & testing */
saveBuffer: boolean;
/**
* Auto-registered `'progress'` event listener. This is equivalent to calling
* `PenumbraZipWriter.addEventListener('progress', onProgress)`
*/
onProgress?(event: ZipProgressEmit): void;
/**
* Auto-registered `'write-complete'` event listener. This is equivalent to calling
* `PenumbraZipWriter.addEventListener('complete', onComplete)`
*/
onComplete?(event: ZipCompletionEmit): void;
}>; | the_stack |
import ModbusServer from './modbus-server'
import {
ExceptionResponseBody,
ReadCoilsResponseBody,
ReadDiscreteInputsResponseBody,
ReadHoldingRegistersResponseBody,
ReadInputRegistersResponseBody,
WriteMultipleCoilsResponseBody,
WriteMultipleRegistersResponseBody,
WriteSingleCoilResponseBody,
WriteSingleRegisterResponseBody
} from './response'
import {
isExceptionRequestBody,
isReadCoilsRequestBody,
isReadDiscreteInputsRequestBody,
isReadHoldingRegistersRequestBody,
isReadInputRegistersRequestBody,
isWriteMultipleCoilsRequestBody,
isWriteMultipleRegistersRequestBody,
isWriteSingleCoilRequestBody,
isWriteSingleRegisterRequestBody
} from './request'
import ModbusAbstractRequest from './abstract-request'
import { ModbusAbstractResponseFromRequest } from './abstract-response'
import BufferUtils from './buffer-utils.js'
import { FC, isFunctionCode } from './codes'
const {
bufferToArrayStatus,
arrayStatusToBuffer
} = BufferUtils
import Debug = require('debug'); const debug = Debug('modbus tcp response handler')
export default class ModbusServerResponseHandler<FR extends ModbusAbstractResponseFromRequest> {
public _server: ModbusServer
public _fromRequest: FR
constructor (server: ModbusServer, fromRequest: FR) {
this._server = server
this._fromRequest = fromRequest
}
public handle (request: ModbusAbstractRequest, cb: (buffer: Buffer) => void) {
if (!request) {
return null
}
// Check for exception request body
if (isExceptionRequestBody(request.body)) {
/* exception request */
const responseBody = ExceptionResponseBody.fromRequest(request.body)
const response = this._fromRequest(request, responseBody)
cb(response.createPayload())
return response
}
const fc = request.body.fc
if (isFunctionCode(fc)) {
switch (fc) {
case FC.READ_COIL:
return this._handleReadCoil(request, cb)
case FC.READ_DISCRETE_INPUT:
return this._handleDiscreteInput(request, cb)
case FC.READ_HOLDING_REGISTERS:
return this._handleReadHoldingRegisters(request, cb)
case FC.READ_INPUT_REGISTERS:
return this._handleReadInputRegisters(request, cb)
case FC.WRITE_SINGLE_COIL:
return this._handleWriteSingleCoil(request, cb)
case FC.WRITE_SINGLE_HOLDING_REGISTER:
return this._handleWriteSingleHoldingRegister(request, cb)
case FC.WRITE_MULTIPLE_COILS:
return this._handleWriteMultipleCoils(request, cb)
case FC.WRITE_MULTIPLE_HOLDING_REGISTERS:
return this._handleWriteMultipleHoldingRegisters(request, cb)
}
}
return
}
private _handleReadCoil (request: ModbusAbstractRequest, cb: (buffer: Buffer) => void) {
if (!isReadCoilsRequestBody(request.body)) {
throw new Error(`InvalidRequestClass - Expected ReadCoilsRequestBody but received ${request.body.name}`)
}
if (!this._server.coils) {
debug('no coils buffer on server, trying readCoils handler')
this._server.emit('readCoils', request, cb)
return
}
this._server.emit('preReadCoils', request, cb)
const responseBody = ReadCoilsResponseBody.fromRequest(request.body, this._server.coils)
const response = this._fromRequest(request, responseBody)
const payload = response.createPayload()
cb(payload)
this._server.emit('postReadCoils', request, cb)
return response
}
private _handleDiscreteInput (request: ModbusAbstractRequest, cb: (buffer: Buffer) => void) {
if (!isReadDiscreteInputsRequestBody(request.body)) {
throw new Error(`InvalidRequestClass - Expected ReadDiscreteInputsRequestBody but received ${request.body.name}`)
}
if (!this._server.discrete) {
debug('no discrete input buffer on server, trying readDiscreteInputs handler')
this._server.emit('readDiscreteInputs', request, cb)
return
}
this._server.emit('preReadDiscreteInputs', request, cb)
const responseBody = ReadDiscreteInputsResponseBody.fromRequest(request.body, this._server.discrete)
const response = this._fromRequest(request, responseBody)
const payload = response.createPayload()
cb(payload)
this._server.emit('postReadDiscreteInputs', request, cb)
return response
}
private _handleReadHoldingRegisters (request: ModbusAbstractRequest, cb: (buffer: Buffer) => void) {
if (!isReadHoldingRegistersRequestBody(request.body)) {
const msg = `InvalidRequestClass - Expected ReadHoldingRegistersRequestBody but received ${request.body.name}`
throw new Error(msg)
}
if (!this._server.holding) {
debug('no holding register buffer on server, trying readHoldingRegisters handler')
this._server.emit('readHoldingRegisters', request, cb)
return
}
this._server.emit('preReadHoldingRegisters', request, cb)
const responseBody = ReadHoldingRegistersResponseBody.fromRequest(request.body, this._server.holding)
const response = this._fromRequest(request, responseBody)
const payload = response.createPayload()
cb(payload)
this._server.emit('postReadHoldingRegisters', request, cb)
return response
}
private _handleReadInputRegisters (request: ModbusAbstractRequest, cb: (buffer: Buffer) => void) {
if (!isReadInputRegistersRequestBody(request.body)) {
throw new Error(`InvalidRequestClass - Expected ReadInputRegistersRequestBody but received ${request.body.name}`)
}
if (!this._server.input) {
debug('no input register buffer on server, trying readInputRegisters handler')
this._server.emit('readInputRegisters', request, cb)
return
}
this._server.emit('preReadInputRegisters', request, cb)
const responseBody = ReadInputRegistersResponseBody.fromRequest(request.body, this._server.input)
const response = this._fromRequest(request, responseBody)
const payload = response.createPayload()
cb(payload)
this._server.emit('postReadInputRegisters', request, cb)
return response
}
private _handleWriteSingleCoil (request: ModbusAbstractRequest, cb: (buffer: Buffer) => void) {
if (!isWriteSingleCoilRequestBody(request.body)) {
throw new Error(`InvalidRequestClass - Expected WriteSingleCoilRequestBody but received ${request.body.name}`)
}
if (!this._server.coils) {
debug('no coils buffer on server, trying writeSingleCoil handler')
this._server.emit('writeSingleCoil', request, cb)
return
}
this._server.emit('preWriteSingleCoil', request, cb)
const responseBody = WriteSingleCoilResponseBody.fromRequest(request.body)
const address = request.body.address
debug('Writing value %d to address %d', request.body.value, address)
// find the byte that contains the coil to be written
const oldValue = this._server.coils.readUInt8(Math.floor(address / 8))
let newValue
if (request.body.value !== 0xFF00 && request.body.value !== 0x0000) {
debug('illegal data value')
/* illegal data value */
const exceptionBody = new ExceptionResponseBody(request.body.fc, 0x03)
const exceptionResponse = this._fromRequest(request, exceptionBody)
cb(exceptionResponse.createPayload())
return exceptionResponse
}
// write the correct bit
// if the value is true, the bit is set using bitwise or
if (request.body.value === 0xFF00) {
newValue = oldValue | Math.pow(2, address % 8)
} else {
newValue = oldValue & ~Math.pow(2, address % 8)
}
if (responseBody.address / 8 > this._server.coils.length) {
debug('illegal data address')
/* illegal data address */
const exceptionBody = new ExceptionResponseBody(request.body.fc, 0x02)
const exceptionResponse = this._fromRequest(request, exceptionBody)
cb(exceptionResponse.createPayload())
return exceptionResponse
} else {
this._server.coils.writeUInt8(newValue, Math.floor(address / 8))
}
const response = this._fromRequest(request, responseBody)
const payload = response.createPayload()
cb(payload)
this._server.emit('postWriteSingleCoil', request, cb)
return response
}
private _handleWriteSingleHoldingRegister (request: ModbusAbstractRequest, cb: (buffer: Buffer) => void) {
if (!isWriteSingleRegisterRequestBody(request.body)) {
throw new Error(`InvalidRequestClass - Expected WriteSingleRegisterRequestBody but received ${request.body.name}`)
}
if (!this._server.holding) {
debug('no register buffer on server, trying writeSingleRegister handler')
this._server.emit('writeSingleRegister', request, cb)
return
}
this._server.emit('preWriteSingleRegister', request, cb)
const responseBody = WriteSingleRegisterResponseBody.fromRequest(request.body)
if (responseBody.address * 2 > this._server.holding.length) {
debug('illegal data address')
/* illegal data address */
const exceptionBody = new ExceptionResponseBody(request.body.fc, 0x02)
const exceptionResponse = this._fromRequest(request, exceptionBody)
cb(exceptionResponse.createPayload())
return exceptionResponse
} else {
this._server.holding.writeUInt16BE(responseBody.value, responseBody.address * 2)
}
const response = this._fromRequest(request, responseBody)
const payload = response.createPayload()
cb(payload)
this._server.emit('postWriteSingleRegister', request, cb)
return response
}
private _handleWriteMultipleCoils (request: ModbusAbstractRequest, cb: (buffer: Buffer) => void) {
if (!isWriteMultipleCoilsRequestBody(request.body)) {
throw new Error(`InvalidRequestClass - Expected WriteMultipleCoilsRequestBody but received ${request.body.name}`)
}
if (!this._server.coils) {
debug('no coils buffer on server, trying writeMultipleCoils handler')
this._server.emit('writeMultipleCoils', request, cb)
return
}
this._server.emit('preWriteMultipleCoils', request, cb)
const responseBody = WriteMultipleCoilsResponseBody.fromRequest(request.body)
const oldStatus = bufferToArrayStatus(this._server.coils)
const requestCoilValues = bufferToArrayStatus(request.body.valuesAsBuffer)
const start = request.body.address
const end = start + request.body.quantity
const newStatus = oldStatus.map((byte, i) => {
let value = byte
const inRange = (i >= start && i < end)
if (inRange) {
const newValue = requestCoilValues.shift()
value = newValue !== undefined ? newValue : byte
}
return value
})
this._server.emit('writeMultipleCoils', this._server.coils, oldStatus)
this._server.coils.fill(arrayStatusToBuffer(newStatus))
this._server.emit('postWriteMultipleCoils', this._server.coils, newStatus)
const response = this._fromRequest(request, responseBody)
const payload = response.createPayload()
cb(payload)
this._server.emit('postWriteMultipleCoils', request, cb)
return response
}
private _handleWriteMultipleHoldingRegisters (request: ModbusAbstractRequest, cb: (buffer: Buffer) => void) {
if (!isWriteMultipleRegistersRequestBody(request.body)) {
throw new Error(`InvalidRequestClass - Expected WriteMultipleRegistersRequestBody but received ${request.body.name}`)
}
if (!this._server.holding) {
debug('no register buffer on server, trying writeMultipleRegisters handler')
this._server.emit('writeMultipleRegisters', request, cb)
return
}
this._server.emit('preWriteMultipleRegisters', request, cb)
const responseBody = WriteMultipleRegistersResponseBody.fromRequest(request.body)
if (((request.body.address * 2) + request.body.values.length) > this._server.holding.length) {
debug('illegal data address')
/* illegal data address */
const exceptionBody = new ExceptionResponseBody(request.body.fc, 0x02)
const exceptionResponse = this._fromRequest(request, exceptionBody)
cb(exceptionResponse.createPayload())
return exceptionResponse
} else {
this._server.emit('writeMultipleRegisters', this._server.holding)
debug('Request Body: ', request.body)
this._server.holding.fill(new Uint8Array(request.body.values),
request.body.address * 2,
request.body.address * 2 + request.body.values.length)
this._server.emit('postWriteMultipleRegisters', this._server.holding)
}
const response = this._fromRequest(request, responseBody)
const payload = response.createPayload()
cb(payload)
this._server.emit('postWriteMultipleRegisters', request, cb)
return response
}
} | the_stack |
import { expect } from "chai";
import * as crypto from "crypto";
import "mocha";
import {
checkForLeaks,
checkMemory,
commonExportsFromInstance,
CommonTestExports,
createString,
getString,
loadWasm,
} from "./common";
interface MpTestExports extends CommonTestExports {
mp10Pow: (pow: number) => number;
mpAdd: (a: number, b: number) => number;
mpSub: (a: number, b: number) => number;
mpDiv: (dividend: number, divisor: number) => bigint;
mpShl: (a: number, shift: number) => number;
mpShrIp: (a: number, shift: number) => void;
mpEq: (a: number, b: number) => number;
mpGt: (a: number, b: number) => number;
mpGe: (a: number, b: number) => number;
mpLt: (a: number, b: number) => number;
mpLe: (a: number, b: number) => number;
mpStringToMp: (str: number, strLen: number, base: number) => number;
mpMpToString: (ptr: number, base: number) => number;
mpIsZero: (pow: number) => number;
mpCleanup: () => void;
}
function createExportsFromInstance(
instance: WebAssembly.Instance
): MpTestExports {
return {
...commonExportsFromInstance(instance),
mp10Pow: instance.exports.mp10Pow as (pow: number) => number,
mpAdd: instance.exports.mpAdd as (a: number, b: number) => number,
mpSub: instance.exports.mpSub as (a: number, b: number) => number,
mpDiv: instance.exports.mpDiv as (
dividend: number,
divisor: number
) => bigint,
mpShl: instance.exports.mpShl as (a: number, shift: number) => number,
mpShrIp: instance.exports.mpShrIp as (a: number, shift: number) => void,
mpEq: instance.exports.mpEq as (a: number, b: number) => number,
mpGt: instance.exports.mpGt as (a: number, b: number) => number,
mpGe: instance.exports.mpGe as (a: number, b: number) => number,
mpLt: instance.exports.mpLt as (a: number, b: number) => number,
mpLe: instance.exports.mpLe as (a: number, b: number) => number,
mpStringToMp: instance.exports.mpStringToMp as (
str: number,
strLen: number,
base: number
) => number,
mpMpToString: instance.exports.mpMpToString as (
ptr: number,
base: number
) => number,
mpIsZero: instance.exports.mpIsZero as (pow: number) => number,
mpCleanup: instance.exports.mpCleanup as () => void,
};
}
describe("mp wasm", () => {
const wasm = loadWasm();
let exports: MpTestExports;
before(async () => {
const instance = await wasm;
exports = createExportsFromInstance(instance);
exports.mallocInit();
});
after(() => {
exports.mpCleanup();
checkForLeaks(exports);
});
afterEach(() => {
checkMemory(exports);
});
const ptrToBigInt = (ptr: number) => {
const words = new Uint32Array(exports.memory.buffer);
const widx = ptr / 4;
const len = words[widx] & 0x7fff_ffff;
const sign = words[widx] & 0x8000_0000;
let accum = 0n;
for (let didx = 1; didx <= len; didx++) {
accum *= 0x1_0000_0000n;
accum |= BigInt(words[didx + widx]);
}
return sign === 0 ? accum : -accum;
};
const bigIntToPtr = (num: bigint) => {
const words: number[] = [];
const neg = num < 0n ? true : false;
if (num < 0) {
num = -num;
}
while (num !== 0n) {
words.unshift(Number(BigInt.asUintN(32, num)));
num >>= 32n;
}
const ptr = exports.malloc((words.length + 1) * 4);
const view = new Uint32Array(exports.memory.buffer);
const widx = ptr / 4;
view[widx] = words.length | (neg ? 0x8000_0000 : 0x0000_0000);
words.forEach((el, i) => (view[widx + i + 1] = el));
return ptr;
};
const randomBigInt = (bits: number, maybeSigned?: boolean) => {
const len = (bits + 0x3f) >> 6;
const arr = new BigUint64Array(len);
crypto.randomFillSync(arr);
let val = arr.reduce((acc, el) => (acc << 64n) | el);
const shift = BigInt((len << 6) - bits);
if (shift > 0n) {
val = val >> shift;
}
return maybeSigned && Math.random() >= 0.5 ? -val : val;
};
it("generates small powers of 10 correctly", () => {
let pow10 = 1n;
for (let i = 0; i <= 19; i++) {
const val = exports.mp10Pow(i);
const bigVal = ptrToBigInt(val);
expect(bigVal).to.equal(pow10, `computing 10^${i}`);
pow10 *= 10n;
}
});
it("generates larger powers of 10 correctly", () => {
let pow10 = 100_000_000_000_000_000_000n;
for (let i = 20; i <= 40; i += 5) {
const val = exports.mp10Pow(i);
const bigVal = ptrToBigInt(val);
expect(bigVal).to.equal(pow10, `computing 10^${i}`);
pow10 *= 100_000n;
checkMemory(exports);
}
});
it("adds positive numbers", () => {
for (let i = 0; i < 20; i++) {
const a = randomBigInt(128);
const b = randomBigInt(128);
const a_ptr = bigIntToPtr(a);
const b_ptr = bigIntToPtr(b);
const val = exports.mpAdd(a_ptr, b_ptr);
const bigVal = ptrToBigInt(val);
expect(bigVal).to.equal(a + b, `computing ${a} + ${b}`);
exports.mallocFree(a_ptr);
exports.mallocFree(b_ptr);
exports.mallocFree(val);
}
});
it("subtracts numbers", () => {
const a = 267197213709374958260730313680667588572n;
const b = 44926186424055215012510765029051707353n;
const c = 222271027285319743248219548651615881219n;
const a_ptr = bigIntToPtr(a);
const b_ptr = bigIntToPtr(b);
const val = exports.mpSub(a_ptr, b_ptr);
const bigVal = ptrToBigInt(val);
expect(bigVal).to.equal(a - b, `computing ${a} - ${b}`);
exports.mallocFree(a_ptr);
exports.mallocFree(b_ptr);
exports.mallocFree(val);
});
it("adds positive and negative numbers", () => {
for (let i = 0; i < 20; i++) {
const a = randomBigInt(128, true);
const b = randomBigInt(128, true);
const a_ptr = bigIntToPtr(a);
const b_ptr = bigIntToPtr(b);
const val = exports.mpAdd(a_ptr, b_ptr);
const bigVal = ptrToBigInt(val);
expect(bigVal).to.equal(a + b, `computing ${a} + ${b}`);
exports.mallocFree(a_ptr);
exports.mallocFree(b_ptr);
exports.mallocFree(val);
}
});
it("converts base-10 strings to numbers", () => {
for (let i = 0; i < 20; i++) {
const a = randomBigInt(128, true);
const a_str = a.toString();
const a_str_ptr = createString(exports, a_str);
const val = exports.mpStringToMp(a_str_ptr + 4, a_str.length, 10);
const bigVal = ptrToBigInt(val);
expect(bigVal).to.equal(a);
exports.mallocFree(a_str_ptr);
exports.mallocFree(val);
}
});
it("converts numbers to base-10 strings", () => {
for (let i = 0; i < 20; i++) {
const a = randomBigInt(128, true);
const a_ptr = bigIntToPtr(a);
const val = exports.mpMpToString(a_ptr, 10);
expect(getString(exports, val)).to.equal(a.toString());
exports.mallocFree(a_ptr);
exports.mallocFree(val);
}
});
it("converts base-16 strings to numbers", () => {
for (let i = 0; i < 20; i++) {
const a = randomBigInt(128, true);
const a_str = a.toString(16);
const a_str_ptr = createString(exports, a_str);
const val = exports.mpStringToMp(a_str_ptr + 4, a_str.length, 16);
const bigVal = ptrToBigInt(val);
expect(bigVal).to.equal(
a,
`Converting ${a_str}, got ${bigVal.toString(16)}`
);
exports.mallocFree(a_str_ptr);
exports.mallocFree(val);
}
});
it("converts numbers to base-16 strings", () => {
for (let i = 0; i < 20; i++) {
const a = randomBigInt(128, true);
const a_ptr = bigIntToPtr(a);
const val = exports.mpMpToString(a_ptr, 16);
expect(getString(exports, val).toLowerCase()).to.equal(a.toString(16));
exports.mallocFree(a_ptr);
exports.mallocFree(val);
}
});
it("converts base-8 strings to numbers", () => {
for (let i = 0; i < 20; i++) {
const a = randomBigInt(128, true);
const a_str = a.toString(8);
const a_str_ptr = createString(exports, a_str);
const val = exports.mpStringToMp(a_str_ptr + 4, a_str.length, 8);
const bigVal = ptrToBigInt(val);
expect(bigVal).to.equal(
a,
`Converting ${a_str}, got ${bigVal.toString(8)}`
);
exports.mallocFree(a_str_ptr);
exports.mallocFree(val);
}
});
it("converts numbers to base-8 strings", () => {
for (let i = 0; i < 20; i++) {
const a = randomBigInt(128, true);
const a_ptr = bigIntToPtr(a);
const val = exports.mpMpToString(a_ptr, 8);
expect(getString(exports, val).toLowerCase()).to.equal(a.toString(8));
exports.mallocFree(a_ptr);
exports.mallocFree(val);
}
});
it("converts base-2 strings to numbers", () => {
for (let i = 0; i < 20; i++) {
const a = randomBigInt(128, true);
const a_str = a.toString(2);
const a_str_ptr = createString(exports, a_str);
const val = exports.mpStringToMp(a_str_ptr + 4, a_str.length, 2);
const bigVal = ptrToBigInt(val);
expect(bigVal).to.equal(
a,
`Converting ${a_str}, got ${bigVal.toString(2)}`
);
exports.mallocFree(a_str_ptr);
exports.mallocFree(val);
}
});
it("converts numbers to base-2 strings", () => {
for (let i = 0; i < 20; i++) {
const a = randomBigInt(128, true);
const a_ptr = bigIntToPtr(a);
const val = exports.mpMpToString(a_ptr, 2);
expect(getString(exports, val).toLowerCase()).to.equal(a.toString(2));
exports.mallocFree(a_ptr);
exports.mallocFree(val);
}
});
it("can check if a number is zero", () => {
const zero = bigIntToPtr(0n);
const one = bigIntToPtr(1n);
const minus_one = bigIntToPtr(-1n);
const rand = bigIntToPtr(randomBigInt(128));
expect(exports.mpIsZero(zero)).to.equal(
1,
`(mp-zero? ${zero}) should be 1`
);
expect(exports.mpIsZero(one)).to.equal(0, `(mp-zero? ${one}) should be 0`);
expect(exports.mpIsZero(minus_one)).to.equal(
0,
`(mp-zero? ${minus_one}) should be 0`
);
expect(exports.mpIsZero(rand)).to.equal(
0,
`(mp-zero? ${rand}) should be 0`
);
exports.mallocFree(zero);
exports.mallocFree(one);
exports.mallocFree(minus_one);
exports.mallocFree(rand);
});
it("won't divide by zero", () => {
const zero = bigIntToPtr(0n);
const rand = bigIntToPtr(randomBigInt(128));
expect(exports.mpDiv(rand, zero)).to.equal(0n);
exports.mallocFree(zero);
exports.mallocFree(rand);
});
it("can divide smaller numbers by bigger numbers", () => {
const large = randomBigInt(128);
const small = randomBigInt(64);
const large_ptr = bigIntToPtr(large);
const small_ptr = bigIntToPtr(small);
const divRes = exports.mpDiv(small_ptr, large_ptr);
expect(divRes).to.not.equal(0n);
const temp = new BigUint64Array([divRes]);
const words = new Uint32Array(temp.buffer);
const quot = ptrToBigInt(words[1]);
const rem = ptrToBigInt(words[0]);
expect(quot).to.equal(0n, "quotient should be zero");
expect(rem).to.equal(small, "remainder should be dividend");
exports.mallocFree(words[0]);
exports.mallocFree(small_ptr);
exports.mallocFree(large_ptr);
});
it("can divide 64-bit numbers", () => {
for (let i = 0; i != 20; i++) {
const large = randomBigInt(64, true);
const small = randomBigInt(48, true);
const large_ptr = bigIntToPtr(large);
const small_ptr = bigIntToPtr(small);
const divRes = exports.mpDiv(large_ptr, small_ptr);
expect(divRes).to.not.equal(0n);
const temp = new BigUint64Array([divRes]);
// const words = new Uint32Array(temp.buffer);
const quot_ptr = Number(BigInt.asUintN(32, temp[0] >> 32n));
const rem_ptr = Number(BigInt.asUintN(32, temp[0]));
const quot = ptrToBigInt(quot_ptr);
const rem = ptrToBigInt(rem_ptr);
expect(quot).to.equal(
large / small,
`${i}: (quotient ${large} ${small})`
);
expect(rem).to.equal(
large % small,
`${i}: (remainder ${large} ${small})`
);
if (quot != 0n) {
exports.mallocFree(quot_ptr);
}
exports.mallocFree(rem_ptr);
exports.mallocFree(small_ptr);
exports.mallocFree(large_ptr);
}
});
it("can divide large-bit numbers by 1", () => {
for (let i = 0; i != 20; i++) {
const large = randomBigInt(256, true);
const large_ptr = bigIntToPtr(large);
const small_ptr = bigIntToPtr(1n);
const divRes = exports.mpDiv(large_ptr, small_ptr);
expect(divRes).to.not.equal(0n);
const temp = new BigUint64Array([divRes]);
// const words = new Uint32Array(temp.buffer);
const quot_ptr = Number(BigInt.asUintN(32, temp[0] >> 32n));
const rem_ptr = Number(BigInt.asUintN(32, temp[0]));
const quot = ptrToBigInt(quot_ptr);
const rem = ptrToBigInt(rem_ptr);
expect(quot).to.equal(large, `${i}: (quotient ${large} 1)`);
expect(rem).to.equal(0n, `${i}: (remainder ${large} 1)`);
if (quot != 0n) {
exports.mallocFree(quot_ptr);
}
exports.mallocFree(rem_ptr);
exports.mallocFree(small_ptr);
exports.mallocFree(large_ptr);
}
});
it("can divide large-bit +ve numbers by 64-bit +ve numbers", () => {
for (let i = 0; i != 20; i++) {
const large = randomBigInt(256);
const small = randomBigInt(48);
const large_ptr = bigIntToPtr(large);
const small_ptr = bigIntToPtr(small);
const divRes = exports.mpDiv(large_ptr, small_ptr);
expect(divRes).to.not.equal(0n);
const temp = new BigUint64Array([divRes]);
// const words = new Uint32Array(temp.buffer);
const quot_ptr = Number(BigInt.asUintN(32, temp[0] >> 32n));
const rem_ptr = Number(BigInt.asUintN(32, temp[0]));
const quot = ptrToBigInt(quot_ptr);
const rem = ptrToBigInt(rem_ptr);
expect(quot).to.equal(
large / small,
`${i}: (quotient ${large} ${small})`
);
expect(rem).to.equal(
large % small,
`${i}: (remainder ${large} ${small})`
);
if (quot != 0n) {
exports.mallocFree(quot_ptr);
}
exports.mallocFree(rem_ptr);
exports.mallocFree(small_ptr);
exports.mallocFree(large_ptr);
}
});
it("can divide large-bit numbers by 64-bit numbers", () => {
for (let i = 0; i != 20; i++) {
const large = randomBigInt(256, true);
const small = randomBigInt(48, true);
const large_ptr = bigIntToPtr(large);
const small_ptr = bigIntToPtr(small);
const divRes = exports.mpDiv(large_ptr, small_ptr);
expect(divRes).to.not.equal(0n);
const temp = new BigUint64Array([divRes]);
// const words = new Uint32Array(temp.buffer);
const quot_ptr = Number(BigInt.asUintN(32, temp[0] >> 32n));
const rem_ptr = Number(BigInt.asUintN(32, temp[0]));
const quot = ptrToBigInt(quot_ptr);
const rem = ptrToBigInt(rem_ptr);
expect(quot).to.equal(
large / small,
`${i}: (quotient ${large} ${small})`
);
expect(rem).to.equal(
large % small,
`${i}: (remainder ${large} ${small})`
);
if (quot != 0n) {
exports.mallocFree(quot_ptr);
}
exports.mallocFree(rem_ptr);
exports.mallocFree(small_ptr);
exports.mallocFree(large_ptr);
}
});
it("can shift numbers left", () => {
for (let i = 0; i != 32; i++) {
const small = randomBigInt(48, true);
const small_ptr = bigIntToPtr(small);
const val_ptr = exports.mpShl(small_ptr, i);
const val = ptrToBigInt(val_ptr);
expect(val).to.equal(
small << BigInt(i),
`${small.toString(16)} << ${i} == ${(small << BigInt(i)).toString(16)}`
);
exports.mallocFree(small_ptr);
exports.mallocFree(val_ptr);
}
});
it("can shift numbers left by multiples of word-size", () => {
for (let i = 0; i <= 256; i += 32) {
const small = randomBigInt(48, true);
const small_ptr = bigIntToPtr(small);
const val_ptr = exports.mpShl(small_ptr, i);
const val = ptrToBigInt(val_ptr);
expect(val).to.equal(
small << BigInt(i),
`${small.toString(16)} << ${i} == ${(small << BigInt(i)).toString(16)}`
);
exports.mallocFree(small_ptr);
exports.mallocFree(val_ptr);
}
});
it("can shift numbers right in place", () => {
for (let i = 0; i != 32; i++) {
const small = randomBigInt(48);
const small_ptr = bigIntToPtr(small);
exports.mpShrIp(small_ptr, i);
const val = ptrToBigInt(small_ptr);
expect(val).to.equal(
small >> BigInt(i),
`${small.toString(16)} >> ${i} == ${(small >> BigInt(i)).toString(
16
)} got ${val.toString(16)}`
);
exports.mallocFree(small_ptr);
}
});
const checkCompare = (
mpCmp: (left_ptr: number, right_ptr: number) => number,
refCmp: (left: bigint, right: bigint) => boolean,
description: string
) => {
const numbers = [
randomBigInt(48),
randomBigInt(64),
randomBigInt(128),
-randomBigInt(48),
-randomBigInt(64),
-randomBigInt(128),
];
for (const left of numbers) {
const left_ptr = bigIntToPtr(left);
try {
expect(mpCmp(left_ptr, left_ptr) == 1).to.equal(
refCmp(left, left),
`(${description} ${left} ${left})`
);
for (const right of numbers) {
const right_ptr = bigIntToPtr(right);
try {
expect(mpCmp(left_ptr, right_ptr) == 1).to.equal(
refCmp(left, right),
`(${description} ${left} ${right})`
);
} finally {
exports.mallocFree(right_ptr);
}
}
} finally {
exports.mallocFree(left_ptr);
}
}
};
it("can compare numbers", () => {
checkCompare(exports.mpEq, (a, b) => a == b, "=");
checkCompare(exports.mpGt, (a, b) => a > b, ">");
checkCompare(exports.mpGe, (a, b) => a >= b, ">=");
checkCompare(exports.mpLt, (a, b) => a < b, "<");
checkCompare(exports.mpLe, (a, b) => a <= b, "<=");
});
}); | the_stack |
export function registerTool(t: typeof import("@itwin/core-frontend").Tool): Promise<void>
// these types are needed for ExtensionHost
import type {
ToolAdmin,
NotificationManager,
ViewManager,
ElementLocateManager,
AccuSnap,
RenderSystem
} from "@itwin/core-frontend";
// ExtensionHost must always be in the API
export declare class ExtensionHost {
public static get toolAdmin(): ToolAdmin;
public static get notifications(): NotificationManager;
public static get viewManager(): ViewManager;
public static get locateManager(): ElementLocateManager;
public static get accuSnap(): AccuSnap;
public static get renderSystem(): RenderSystem;
}
// BEGIN GENERATED CODE
export {
ACSDisplayOptions,
ACSType,
AccuDrawHintBuilder,
AccuSnap,
ActivityMessageDetails,
ActivityMessageEndReason,
AuxCoordSystem2dState,
AuxCoordSystem3dState,
AuxCoordSystemSpatialState,
AuxCoordSystemState,
BeButton,
BeButtonEvent,
BeButtonState,
BeModifierKeys,
BeTouchEvent,
BeWheelEvent,
BingElevationProvider,
BingLocationProvider,
CategorySelectorState,
ChangeFlags,
ClipEventType,
Cluster,
ContextRealityModelState,
ContextRotationId,
CoordSource,
CoordSystem,
CoordinateLockOverrides,
Decorations,
DisclosedTileTreeSet,
DisplayStyle2dState,
DisplayStyle3dState,
DisplayStyleState,
DrawingModelState,
DrawingViewState,
EditManipulator,
ElementLocateManager,
ElementPicker,
ElementState,
EmphasizeElements,
EntityState,
EventController,
EventHandled,
FeatureSymbology,
FlashMode,
FlashSettings,
FrontendLoggerCategory,
FrustumAnimator,
GeometricModel2dState,
GeometricModel3dState,
GeometricModelState,
GlobeAnimator,
GraphicBranch,
GraphicBuilder,
GraphicType,
HiliteSet,
HitDetail,
HitDetailType,
HitGeomType,
HitList,
HitParentGeomType,
HitPriority,
HitSource,
IModelConnection,
IconSprites,
InputCollector,
InputSource,
InteractiveTool,
IntersectDetail,
KeyinParseError,
LocateAction,
LocateFilterStatus,
LocateOptions,
LocateResponse,
ManipulatorToolEvent,
MarginPercent,
Marker,
MarkerSet,
MessageBoxIconType,
MessageBoxType,
MessageBoxValue,
ModelSelectorState,
ModelState,
NotificationHandler,
NotificationManager,
NotifyMessageDetails,
OrthographicViewState,
OutputMessageAlert,
OutputMessagePriority,
OutputMessageType,
ParseAndRunResult,
PerModelCategoryVisibility,
PhysicalModelState,
Pixel,
PrimitiveTool,
RenderClipVolume,
RenderGraphic,
RenderGraphicOwner,
RenderSystem,
Scene,
SectionDrawingModelState,
SelectionMethod,
SelectionMode,
SelectionProcessing,
SelectionSet,
SelectionSetEventType,
SheetModelState,
SheetViewState,
SnapDetail,
SnapHeat,
SnapMode,
SnapStatus,
SpatialLocationModelState,
SpatialModelState,
SpatialViewState,
Sprite,
SpriteLocation,
StandardViewId,
StartOrResume,
TentativePoint,
Tile,
TileAdmin,
TileBoundingBoxes,
TileDrawArgs,
TileGraphicType,
TileLoadPriority,
TileLoadStatus,
TileRequest,
TileRequestChannel,
TileRequestChannelStatistics,
TileRequestChannels,
TileTree,
TileTreeLoadStatus,
TileTreeReference,
TileUsageMarker,
TileVisibility,
Tiles,
Tool,
ToolAdmin,
ToolAssistance,
ToolAssistanceImage,
ToolAssistanceInputMethod,
ToolSettings,
TwoWayViewportFrustumSync,
TwoWayViewportSync,
UniformType,
VaryingType,
ViewClipClearTool,
ViewClipDecorationProvider,
ViewClipTool,
ViewCreator2d,
ViewCreator3d,
ViewManager,
ViewManip,
ViewPose,
ViewRect,
ViewState,
ViewState2d,
ViewState3d,
ViewStatus,
ViewTool,
ViewingSpace,
canvasToImageBuffer,
canvasToResizedCanvasWithBars,
connectViewportFrusta,
connectViewportViews,
connectViewports,
extractImageSourceDimensions,
getCompressedJpegFromCanvas,
getImageSourceFormatForMimeType,
getImageSourceMimeType,
imageBufferToBase64EncodedPng,
imageBufferToCanvas,
imageBufferToPngDataUrl,
imageElementFromImageSource,
imageElementFromUrl,
queryTerrainElevationOffset,
readElementGraphics,
synchronizeViewportFrusta,
synchronizeViewportViews
} from "@itwin/core-frontend";
export type {
Animator,
BatchOptions,
BeButtonEventProps,
BeTouchEventProps,
BeWheelEventProps,
CanvasDecoration,
CanvasDecorationList,
ComputeChordToleranceArgs,
CreateTextureArgs,
CreateTextureFromSourceArgs,
CustomGraphicBuilderOptions,
Decorator,
ExtentLimits,
FeatureOverrideProvider,
FlashSettingsOptions,
FrontendSecurityOptions,
FuzzySearchResult,
GlobalAlignmentOptions,
GlobalLocation,
GlobalLocationArea,
GpuMemoryLimit,
GpuMemoryLimits,
GraphicArc,
GraphicArc2d,
GraphicBranchOptions,
GraphicBuilderOptions,
GraphicLineString,
GraphicLineString2d,
GraphicList,
GraphicLoop,
GraphicPath,
GraphicPointString,
GraphicPointString2d,
GraphicPolyface,
GraphicPrimitive,
GraphicPrimitive2d,
GraphicShape,
GraphicShape2d,
GraphicSolidPrimitive,
HitListHolder,
IModelIdArg,
MarginOptions,
MarkerFillStyle,
MarkerImage,
MarkerTextAlign,
MarkerTextBaseline,
OnViewExtentsError,
OsmBuildingDisplayOptions,
ParseKeyinError,
ParseKeyinResult,
ParsedKeyin,
ParticleCollectionBuilder,
ParticleCollectionBuilderParams,
ParticleProps,
PickableGraphicOptions,
ScreenSpaceEffectBuilder,
ScreenSpaceEffectBuilderParams,
ScreenSpaceEffectContext,
ScreenSpaceEffectSource,
SelectAddEvent,
SelectRemoveEvent,
SelectReplaceEvent,
SelectedViewportChangedArgs,
SelectionSetEvent,
SynchronizeViewports,
TextureCacheKey,
TextureCacheOwnership,
TextureImage,
TextureImageSource,
TextureOwnership,
TileContent,
TileDrawArgParams,
TileParams,
TileTreeDiscloser,
TileTreeOwner,
TileTreeParams,
TileTreeSupplier,
TiledGraphicsProvider,
ToolAssistanceInstruction,
ToolAssistanceInstructions,
ToolAssistanceKeyboardInfo,
ToolAssistanceSection,
ToolList,
ToolTipOptions,
ToolType,
Uniform,
UniformArrayParams,
UniformContext,
UniformParams,
ViewAnimationOptions,
ViewChangeOptions,
ViewClipEventHandler,
ViewCreator2dOptions,
ViewCreator3dOptions,
ViewportGraphicBuilderOptions
} from "@itwin/core-frontend";
export {
BackgroundFill,
BackgroundMapType,
BatchType,
BisCodeSpec,
BriefcaseIdValue,
ChangeOpCode,
ChangedValueState,
ChangesetType,
ColorByName,
ColorDef,
CommonLoggerCategory,
ECSqlSystemProperty,
ECSqlValueType,
ElementGeometryOpcode,
FeatureOverrideType,
FillDisplay,
FillFlags,
FontType,
GeoCoordStatus,
GeometryClass,
GeometryStreamFlags,
GeometrySummaryVerbosity,
GlobeMode,
GridOrientationType,
HSVConstants,
ImageBufferFormat,
ImageSourceFormat,
LinePixels,
MassPropertiesOperation,
MonochromeMode,
Npc,
PlanarClipMaskMode,
PlanarClipMaskPriority,
QueryRowFormat,
Rank,
RenderMode,
SectionType,
SkyBoxImageType,
SpatialClassifierInsideDisplay,
SpatialClassifierOutsideDisplay,
SyncMode,
TerrainHeightOriginMode,
TextureMapUnits,
ThematicDisplayMode,
ThematicGradientColorScheme,
ThematicGradientMode,
TxnAction,
TypeOfChange
} from "@itwin/core-common";
export type {
AdditionalTransformProps,
AffineTransformProps,
AmbientLightProps,
AnalysisStyleDisplacementProps,
AnalysisStyleProps,
AnalysisStyleThematicProps,
AppearanceOverrideProps,
AreaFillProps,
AuxCoordSystem2dProps,
AuxCoordSystem3dProps,
AuxCoordSystemProps,
AxisAlignedBox3d,
AxisAlignedBox3dProps,
BRepPrimitive,
BackgroundMapProps,
BackgroundMapProviderName,
Base64EncodedString,
BaseReaderOptions,
BriefcaseId,
CalloutProps,
CameraProps,
Carto2DDegreesProps,
CartographicProps,
CategoryProps,
CategorySelectorProps,
ChangedElements,
ChangedEntities,
ChangesetId,
ChangesetIdWithIndex,
ChangesetIndex,
ChangesetIndexAndId,
ChangesetIndexOrId,
ChangesetRange,
ChannelRootAspectProps,
ClipStyleProps,
CodeProps,
CodeScopeProps,
ColorDefProps,
ContextRealityModelProps,
ContextRealityModelsContainer,
CutStyleProps,
DanishSystem34Region,
DefinitionElementProps,
DeletedElementGeometryChange,
DeprecatedBackgroundMapProps,
DisplayStyle3dProps,
DisplayStyle3dSettingsProps,
DisplayStyleLoadProps,
DisplayStyleModelAppearanceProps,
DisplayStyleOverridesOptions,
DisplayStylePlanarClipMaskProps,
DisplayStyleProps,
DisplayStyleSettingsOptions,
DisplayStyleSettingsProps,
DisplayStyleSubCategoryProps,
DynamicGraphicsRequest2dProps,
DynamicGraphicsRequest3dProps,
DynamicGraphicsRequestProps,
EasingFunction,
EcefLocationProps,
ElementAlignedBox2d,
ElementAlignedBox3d,
ElementAspectProps,
ElementGeometryChange,
ElementGeometryDataEntry,
ElementGraphicsRequestProps,
ElementIdsAndRangesProps,
ElementLoadOptions,
ElementLoadProps,
ElementProps,
EmphasizeElementsProps,
EntityIdAndClassId,
EntityIdAndClassIdIterable,
EntityProps,
EntityQueryParams,
EnvironmentProps,
ExtantElementGeometryChange,
ExternalSourceAspectProps,
FeatureAppearanceProps,
FeatureAppearanceProvider,
FeatureAppearanceSource,
FilePropertyProps,
FlatBufferGeometryStream,
FontId,
FontMapProps,
FresnelSettingsProps,
FunctionalElementProps,
GeocentricTransformProps,
GeodeticDatumProps,
GeodeticEllipsoidProps,
GeodeticTransformMethod,
GeodeticTransformProps,
GeographicCRSProps,
GeometricElement2dProps,
GeometricElement3dProps,
GeometricElementProps,
GeometricModel2dProps,
GeometricModel3dProps,
GeometricModelProps,
GeometryAppearanceProps,
GeometryContainmentRequestProps,
GeometryContainmentResponseProps,
GeometryPartInstanceProps,
GeometryPartProps,
GeometryPrimitive,
GeometryStreamEntryProps,
GeometryStreamHeaderProps,
GeometryStreamIteratorEntry,
GeometryStreamPrimitive,
GeometryStreamProps,
GeometrySummaryOptions,
GeometrySummaryRequestProps,
GraphicsRequestProps,
GridFileDefinitionProps,
GridFileDirection,
GridFileFormat,
GridFileTransformProps,
GroundPlaneProps,
Helmert2DWithZOffsetProps,
HemisphereEnum,
HemisphereLightsProps,
HorizontalCRSExtentProps,
HorizontalCRSProps,
ImageGraphicCornersProps,
ImageGraphicProps,
ImagePrimitive,
InformationPartitionElementProps,
InterpolationFunction,
JsonGeometryStream,
LightSettingsProps,
LineStyleProps,
LocalAlignedBox3d,
LocalBriefcaseProps,
Localization,
MassPropertiesRequestProps,
MassPropertiesResponseProps,
MaterialProps,
ModelClipGroupProps,
ModelGeometryChanges,
ModelGeometryChangesProps,
ModelIdAndGeometryGuid,
ModelLoadProps,
ModelProps,
ModelQueryParams,
ModelSelectorProps,
NavigationBindingValue,
NavigationValue,
PartReference,
PersistentBackgroundMapProps,
PersistentGraphicsRequestProps,
PhysicalElementProps,
PhysicalTypeProps,
Placement,
Placement2dProps,
Placement3dProps,
PlacementProps,
PlanProjectionSettingsProps,
PlanarClipMaskProps,
Point2dProps,
PositionalVectorTransformProps,
ProjectionMethod,
ProjectionProps,
QueryLimit,
QueryOptions,
QueryQuota,
RelatedElementProps,
RelationshipProps,
RemoveFunction,
RenderMaterialAssetProps,
RenderMaterialProps,
RenderTimelineLoadProps,
RenderTimelineProps,
RepositoryLinkProps,
RequestNewBriefcaseProps,
RgbColorProps,
RgbFactorProps,
RootSubjectProps,
RpcActivity,
SectionDrawingLocationProps,
SectionDrawingProps,
SectionDrawingViewProps,
SessionProps,
SheetProps,
SkyBoxImageProps,
SkyBoxProps,
SkyCubeProps,
SolarLightProps,
SolarShadowSettingsProps,
SourceAndTarget,
SpatialClassifierFlagsProps,
SpatialClassifierProps,
SpatialClassifiersContainer,
SpatialViewDefinitionProps,
SubCategoryProps,
SubjectProps,
TerrainProps,
TerrainProviderName,
TextStringPrimitive,
TextStringProps,
TextureData,
TextureLoadProps,
TextureMapProps,
TextureProps,
ThematicDisplayProps,
ThematicDisplaySensorProps,
ThematicDisplaySensorSettingsProps,
ThematicGradientSettingsProps,
ThumbnailFormatProps,
ThumbnailProps,
TileVersionInfo,
TweenCallback,
TypeDefinitionElementProps,
UnitType,
UpdateCallback,
UrlLinkProps,
VerticalCRSProps,
ViewAttachmentLabelProps,
ViewAttachmentProps,
ViewDefinition2dProps,
ViewDefinition3dProps,
ViewDefinitionProps,
ViewDetails3dProps,
ViewDetailsProps,
ViewFlagOverrides,
ViewFlagProps,
ViewFlagsProperties,
ViewQueryParams,
ViewStateLoadProps,
ViewStateProps,
WhiteOnWhiteReversalProps,
XyzRotationProps
} from "@itwin/core-common";
// END GENERATED CODE | the_stack |
* @group unit/balance
*/
import { BN } from '@polkadot/util'
import type {
BalanceNumber,
BalanceOptions,
MetricPrefix,
} from '@kiltprotocol/types'
import {
formatKiltBalance,
convertToTxUnit,
toFemtoKilt,
TRANSACTION_FEE,
fromFemtoKilt,
balanceNumberToString,
} from './Balance.utils'
const TESTVALUE = new BN('123456789000')
describe('formatKiltBalance', () => {
const alterExistingOptions: BalanceOptions = {
decimals: 17,
withUnit: 'KIL',
}
const addingOptions: BalanceOptions = {
// When enables displays the full unit - micro KILT
withSiFull: false,
}
const baseValue = new BN('1')
it('formats the given balance', async () => {
expect(formatKiltBalance(TESTVALUE)).toEqual('123.4567 micro KILT')
expect(formatKiltBalance(baseValue.mul(new BN(10).pow(new BN(3))))).toEqual(
'1.0000 pico KILT'
)
expect(formatKiltBalance(baseValue.mul(new BN(10).pow(new BN(6))))).toEqual(
'1.0000 nano KILT'
)
expect(formatKiltBalance(baseValue.mul(new BN(10).pow(new BN(9))))).toEqual(
'1.0000 micro KILT'
)
expect(
formatKiltBalance(baseValue.mul(new BN(10).pow(new BN(12))))
).toEqual('1.0000 milli KILT')
expect(
formatKiltBalance(baseValue.mul(new BN(10).pow(new BN(15))))
).toEqual('1.0000 KILT')
expect(
formatKiltBalance(baseValue.mul(new BN(10).pow(new BN(18))))
).toEqual('1.0000 Kilo KILT')
expect(
formatKiltBalance(baseValue.mul(new BN(10).pow(new BN(21))))
).toEqual('1.0000 Mill KILT')
expect(
formatKiltBalance(baseValue.mul(new BN(10).pow(new BN(24))))
).toEqual('1.0000 Bill KILT')
expect(
formatKiltBalance(baseValue.mul(new BN(10).pow(new BN(27))))
).toEqual('1.0000 Tril KILT')
})
it('changes formatting options for given balances', () => {
expect(
formatKiltBalance(
baseValue.mul(new BN(10).pow(new BN(12))),
alterExistingOptions
)
).toEqual('10.0000 micro KIL')
expect(
formatKiltBalance(
baseValue.mul(new BN(10).pow(new BN(12))),
alterExistingOptions
)
).not.toEqual('1.0000 micro KILT')
expect(
formatKiltBalance(
baseValue.mul(new BN(10).pow(new BN(12))),
addingOptions
)
).toEqual('1.0000 mKILT')
expect(
formatKiltBalance(
baseValue.mul(new BN(10).pow(new BN(18))),
addingOptions
)
).toEqual('1.0000 kKILT')
expect(
formatKiltBalance(
baseValue.mul(new BN(10).pow(new BN(21))),
addingOptions
)
).toEqual('1.0000 MKILT')
})
})
describe('convertToTxUnit', () => {
it('converts given value with given power to femto KILT', () => {
expect(new BN(convertToTxUnit(new BN(1), -15).toString())).toEqual(
new BN(1)
)
expect(new BN(convertToTxUnit(new BN(1), -12).toString())).toEqual(
new BN('1000')
)
expect(new BN(convertToTxUnit(new BN(1), -9).toString())).toEqual(
new BN('1000000')
)
expect(new BN(convertToTxUnit(new BN(1), -6).toString())).toEqual(
new BN('1000000000')
)
expect(new BN(convertToTxUnit(new BN(1), -3).toString())).toEqual(
new BN('1000000000000')
)
expect(new BN(convertToTxUnit(new BN(1), 0).toString())).toEqual(
new BN('1000000000000000')
)
expect(new BN(convertToTxUnit(new BN(1), 3).toString())).toEqual(
new BN('1000000000000000000')
)
expect(new BN(convertToTxUnit(new BN(-1), 6).toString())).toEqual(
new BN('-1000000000000000000000')
)
expect(new BN(convertToTxUnit(new BN(1), 9).toString())).toEqual(
new BN('1000000000000000000000000')
)
expect(new BN(convertToTxUnit(new BN(1), 12).toString())).toEqual(
new BN('1000000000000000000000000000')
)
expect(new BN(convertToTxUnit(new BN(1), 15).toString())).toEqual(
new BN('1000000000000000000000000000000')
)
expect(new BN(convertToTxUnit(new BN(1), 18).toString())).toEqual(
new BN('1000000000000000000000000000000000')
)
})
})
describe('balanceNumberToString', () => {
it('verifies string input for valid number representation', () => {
expect(() => balanceNumberToString('1.1')).not.toThrowError()
expect(() => balanceNumberToString('.1')).not.toThrowError()
expect(() => balanceNumberToString('-.1')).not.toThrowError()
expect(() => balanceNumberToString('462246261.14462264')).not.toThrowError()
expect(() =>
balanceNumberToString('-462246261.14462264')
).not.toThrowError()
})
it('string input negative tests', () => {
expect(() => balanceNumberToString('1.')).toThrowError()
expect(() => balanceNumberToString('1.1.1')).toThrowError()
expect(() => balanceNumberToString('462246261..14462264')).toThrowError()
expect(() => balanceNumberToString('.462246261.14462264')).toThrowError()
expect(() => balanceNumberToString('.')).toThrowError()
expect(() => balanceNumberToString('dewf')).toThrowError()
expect(() => balanceNumberToString('1.24e15')).toThrowError()
expect(() => balanceNumberToString('-.462246261.14462264')).toThrowError()
expect(() => balanceNumberToString('.')).toThrowError()
expect(() => balanceNumberToString('313145314.d')).toThrowError()
expect(() => balanceNumberToString('1.24e15')).toThrowError()
expect(() => balanceNumberToString('-.462246261.14462264')).toThrowError()
})
it('verifies BN and BigInt', () => {
expect(() => balanceNumberToString({} as BN)).toThrowError()
expect(() => balanceNumberToString([] as unknown as BN)).toThrowError()
expect(() =>
balanceNumberToString({ toString: 'blurt' } as unknown as BN)
).toThrowError()
expect(() => balanceNumberToString({} as bigint)).toThrowError()
expect(() => balanceNumberToString([] as unknown as bigint)).toThrowError()
expect(() =>
balanceNumberToString({ toLocaleString: 'blurt' } as unknown as bigint)
).toThrowError()
expect(balanceNumberToString(BigInt('12345678900'))).toEqual('12345678900')
})
})
describe('toFemtoKilt', () => {
it('converts whole KILT', () => {
expect(toFemtoKilt(new BN(1000)).toString()).toEqual(
new BN('1000000000000000000').toString()
)
})
it('converts any metric amount', () => {
expect(new BN(toFemtoKilt('123456789', 'femto').toString())).toEqual(
new BN('123456789')
)
expect(new BN(toFemtoKilt('123456.789', 'pico').toString())).toEqual(
new BN('123456789')
)
expect(new BN(toFemtoKilt('123456.789', 'nano').toString())).toEqual(
new BN('123456789000')
)
expect(new BN(toFemtoKilt('123456.789', 'micro').toString())).toEqual(
new BN('123456789000000')
)
expect(new BN(toFemtoKilt('123456.789', 'milli').toString())).toEqual(
new BN('123456789000000000')
)
expect(new BN(toFemtoKilt('123456.789', 'kilo').toString())).toEqual(
new BN('123456789000000000000000')
)
expect(new BN(toFemtoKilt('123456.789', 'mega').toString())).toEqual(
new BN('123456789000000000000000000')
)
expect(new BN(toFemtoKilt('123456.789', 'mill').toString())).toEqual(
new BN('123456789000000000000000000')
)
expect(new BN(toFemtoKilt('123456.789', 'giga').toString())).toEqual(
new BN('123456789000000000000000000000')
)
expect(new BN(toFemtoKilt('123456.789', 'bill').toString())).toEqual(
new BN('123456789000000000000000000000')
)
expect(new BN(toFemtoKilt('123456.789', 'tera').toString())).toEqual(
new BN('123456789000000000000000000000000')
)
expect(new BN(toFemtoKilt('123456.789', 'tril').toString())).toEqual(
new BN('123456789000000000000000000000000')
)
expect(new BN(toFemtoKilt('123456.789', 'peta').toString())).toEqual(
new BN('123456789000000000000000000000000000')
)
expect(new BN(toFemtoKilt('123456.789', 'exa').toString())).toEqual(
new BN('123456789000000000000000000000000000000')
)
expect(new BN(toFemtoKilt('123.456789', 'zetta').toString())).toEqual(
new BN('123456789000000000000000000000000000000')
)
expect(new BN(toFemtoKilt('0.123456789', 'yotta').toString())).toEqual(
new BN('123456789000000000000000000000000000000')
)
})
it('handles too many decimal places', () => {
expect(toFemtoKilt('-0.000001', 'nano').toString()).toEqual(
new BN('-1').toString()
)
expect(() => toFemtoKilt('-0.0000001', 'nano').toString()).toThrowError()
})
it('handles invalid input', () => {
expect(() => toFemtoKilt(undefined!).toString()).toThrowError()
expect(() => toFemtoKilt({} as BalanceNumber).toString()).toThrowError()
expect(() =>
toFemtoKilt([] as unknown as BalanceNumber).toString()
).toThrowError()
expect(() =>
toFemtoKilt(1, 'nono' as MetricPrefix).toString()
).toThrowError()
})
it('handles edge cases', () => {
expect(() => toFemtoKilt('-2412d.3411').toString()).toThrowError()
expect(() => toFemtoKilt('-24.1.2').toString()).toThrowError()
expect(() => toFemtoKilt('1e12').toString()).toThrowError()
expect(() => toFemtoKilt('').toString()).toThrowError()
expect(() => toFemtoKilt('.').toString()).toThrowError()
expect(() => toFemtoKilt('1.').toString()).toThrowError()
expect(toFemtoKilt('-0').toString()).toEqual(new BN('0').toString())
expect(toFemtoKilt('-0.000001', 'nano').toString()).toEqual(
new BN('-1').toString()
)
expect(toFemtoKilt('-.25', 'pico').toString()).toEqual(
new BN('-250').toString()
)
})
})
describe('fromFemtoKilt', () => {
it('converts femtoKilt to whole KILT using convertToTxUnit', () => {
expect(fromFemtoKilt(new BN('1'))).toEqual(`1.0000 femto KILT`)
expect(fromFemtoKilt(new BN('1000'))).toEqual(`1.0000 pico KILT`)
expect(fromFemtoKilt(new BN('1000000'))).toEqual(`1.0000 nano KILT`)
expect(fromFemtoKilt(new BN('1000000000'))).toEqual(`1.0000 micro KILT`)
expect(fromFemtoKilt(new BN('1000000000000'))).toEqual(`1.0000 milli KILT`)
expect(fromFemtoKilt(new BN('1000000000000000'))).toEqual(`1.0000 KILT`)
expect(fromFemtoKilt(new BN('1000000000000000000'))).toEqual(
`1.0000 Kilo KILT`
)
expect(fromFemtoKilt(new BN('1000000000000000000000'))).toEqual(
`1.0000 Mill KILT`
)
expect(fromFemtoKilt(new BN('1000000000000000000000000'))).toEqual(
`1.0000 Bill KILT`
)
expect(fromFemtoKilt(new BN('1000000000000000000000000000'))).toEqual(
`1.0000 Tril KILT`
)
expect(fromFemtoKilt(new BN('1000000000000000000000000000000'))).toEqual(
`1.0000 Peta KILT`
)
expect(fromFemtoKilt(new BN('1234'), 3)).toEqual(`1.234 pico KILT`)
expect(fromFemtoKilt(new BN('1234567'))).toEqual(`1.2345 nano KILT`)
expect(fromFemtoKilt(new BN('1234567890'), 3)).toEqual(`1.234 micro KILT`)
expect(fromFemtoKilt(new BN('1234567890000'))).toEqual(`1.2345 milli KILT`)
expect(fromFemtoKilt(new BN('1234567890000000'))).toEqual(`1.2345 KILT`)
expect(fromFemtoKilt(new BN('1234567890000000000'))).toEqual(
`1.2345 Kilo KILT`
)
expect(fromFemtoKilt(new BN('1234567890000000000000'))).toEqual(
`1.2345 Mill KILT`
)
expect(fromFemtoKilt(new BN('1234567890000000000000000'))).toEqual(
`1.2345 Bill KILT`
)
expect(fromFemtoKilt(new BN('1234567890000000000000000000'))).toEqual(
`1.2345 Tril KILT`
)
expect(fromFemtoKilt(new BN('1234567890000000000000000000000'))).toEqual(
`1.2345 Peta KILT`
)
})
it('returns localized number string', () => {
expect(
fromFemtoKilt(new BN('1000000000000000000'), 3, { locale: 'ar-EG' })
).toEqual(`١٫٠٠٠ Kilo KILT`)
expect(
fromFemtoKilt(new BN('1000000000000000000'), 3, { locale: 'de-DE' })
).toEqual(`1,000 Kilo KILT`)
})
it('Does not round, as especially balances should not be portrayed larger than they are', () => {
expect(fromFemtoKilt(new BN('1234560000000000000'), 3)).toEqual(
`1.234 Kilo KILT`
)
expect(fromFemtoKilt(new BN('12345600000000000000'), 3)).toEqual(
`12.345 Kilo KILT`
)
})
it('Accepts decimal as argument to set minimum amount of decimal places', () => {
expect(fromFemtoKilt(new BN('12000000000000000000'), 1)).toEqual(
`12.0 Kilo KILT`
)
expect(fromFemtoKilt(new BN('12300000000000000000'), 2)).toEqual(
`12.30 Kilo KILT`
)
expect(fromFemtoKilt(new BN('12345000000000000000'), 4)).toEqual(
`12.3450 Kilo KILT`
)
})
it('converts negative femtoKilt to whole KILT using convertToTxUnit', () => {
expect(fromFemtoKilt(new BN('-1000000000000000000'), 3)).toEqual(
`-1.000 Kilo KILT`
)
})
it('handles invalid input', () => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expect(() => fromFemtoKilt(undefined!)).toThrowError()
expect(() => fromFemtoKilt({} as BN)).toThrowError()
expect(() => fromFemtoKilt([] as unknown as BN)).toThrowError()
expect(() => fromFemtoKilt({} as bigint)).toThrowError()
expect(() => fromFemtoKilt([] as unknown as bigint)).toThrowError()
})
})
describe('TRANSACTION_FEE', () => {
it('equals 125 nano KILT', () => {
expect(formatKiltBalance(TRANSACTION_FEE)).toEqual('125.0000 nano KILT')
})
}) | the_stack |
import * as b2 from "@box2d";
import * as testbed from "@testbed";
export class DrawingParticles extends testbed.Test {
/**
* Set bit 31 to distiguish these values from particle flags.
*/
public static readonly Parameters = {
e_parameterBegin: (1 << 31), // Start of this parameter namespace.
e_parameterMove: (1 << 31) | (1 << 0),
e_parameterRigid: (1 << 31) | (1 << 1),
e_parameterRigidBarrier: (1 << 31) | (1 << 2),
e_parameterElasticBarrier: (1 << 31) | (1 << 3),
e_parameterSpringBarrier: (1 << 31) | (1 << 4),
e_parameterRepulsive: (1 << 31) | (1 << 5),
};
public m_lastGroup: b2.ParticleGroup | null;
public m_drawing = true;
public m_particleFlags = 0;
public m_groupFlags = 0;
public m_colorIndex = 0;
public static readonly k_paramValues = [
new testbed.ParticleParameterValue(b2.ParticleFlag.b2_zombieParticle, testbed.ParticleParameter.k_DefaultOptions, "erase"),
new testbed.ParticleParameterValue(DrawingParticles.Parameters.e_parameterMove, testbed.ParticleParameter.k_DefaultOptions, "move"),
new testbed.ParticleParameterValue(DrawingParticles.Parameters.e_parameterRigid, testbed.ParticleParameter.k_DefaultOptions, "rigid"),
new testbed.ParticleParameterValue(DrawingParticles.Parameters.e_parameterRigidBarrier, testbed.ParticleParameter.k_DefaultOptions, "rigid barrier"),
new testbed.ParticleParameterValue(DrawingParticles.Parameters.e_parameterElasticBarrier, testbed.ParticleParameter.k_DefaultOptions, "elastic barrier"),
new testbed.ParticleParameterValue(DrawingParticles.Parameters.e_parameterSpringBarrier, testbed.ParticleParameter.k_DefaultOptions, "spring barrier"),
new testbed.ParticleParameterValue(DrawingParticles.Parameters.e_parameterRepulsive, testbed.ParticleParameter.k_DefaultOptions, "repulsive wall"),
];
public static readonly k_paramDef = [
new testbed.ParticleParameterDefinition(testbed.ParticleParameter.k_particleTypes),
new testbed.ParticleParameterDefinition(DrawingParticles.k_paramValues),
];
public static readonly k_paramDefCount = DrawingParticles.k_paramDef.length;
constructor() {
super();
{
const bd = new b2.BodyDef();
const ground = this.m_world.CreateBody(bd);
{
const shape = new b2.PolygonShape();
const vertices = [
new b2.Vec2(-4, -2),
new b2.Vec2(4, -2),
new b2.Vec2(4, 0),
new b2.Vec2(-4, 0),
];
shape.Set(vertices, 4);
ground.CreateFixture(shape, 0.0);
}
{
const shape = new b2.PolygonShape();
const vertices = [
new b2.Vec2(-4, -2),
new b2.Vec2(-2, -2),
new b2.Vec2(-2, 6),
new b2.Vec2(-4, 6),
];
shape.Set(vertices, 4);
ground.CreateFixture(shape, 0.0);
}
{
const shape = new b2.PolygonShape();
const vertices = [
new b2.Vec2(2, -2),
new b2.Vec2(4, -2),
new b2.Vec2(4, 6),
new b2.Vec2(2, 6),
];
shape.Set(vertices, 4);
ground.CreateFixture(shape, 0.0);
}
{
const shape = new b2.PolygonShape();
const vertices = [
new b2.Vec2(-4, 4),
new b2.Vec2(4, 4),
new b2.Vec2(4, 6),
new b2.Vec2(-4, 6),
];
shape.Set(vertices, 4);
ground.CreateFixture(shape, 0.0);
}
}
this.m_colorIndex = 0;
this.m_particleSystem.SetRadius(0.05 * 2);
this.m_lastGroup = null;
this.m_drawing = true;
// DEBUG: b2.Assert((DrawingParticles.k_paramDef[0].CalculateValueMask() & DrawingParticles.Parameters.e_parameterBegin) === 0);
testbed.Test.SetParticleParameters(DrawingParticles.k_paramDef, DrawingParticles.k_paramDefCount);
testbed.Test.SetRestartOnParticleParameterChange(false);
this.m_particleFlags = testbed.Test.GetParticleParameterValue();
this.m_groupFlags = 0;
}
// Determine the current particle parameter from the drawing state and
// group flags.
public DetermineParticleParameter() {
if (this.m_drawing) {
if (this.m_groupFlags === (b2.ParticleGroupFlag.b2_rigidParticleGroup | b2.ParticleGroupFlag.b2_solidParticleGroup)) {
return DrawingParticles.Parameters.e_parameterRigid;
}
if (this.m_groupFlags === b2.ParticleGroupFlag.b2_rigidParticleGroup && this.m_particleFlags === b2.ParticleFlag.b2_barrierParticle) {
return DrawingParticles.Parameters.e_parameterRigidBarrier;
}
if (this.m_particleFlags === (b2.ParticleFlag.b2_elasticParticle | b2.ParticleFlag.b2_barrierParticle)) {
return DrawingParticles.Parameters.e_parameterElasticBarrier;
}
if (this.m_particleFlags === (b2.ParticleFlag.b2_springParticle | b2.ParticleFlag.b2_barrierParticle)) {
return DrawingParticles.Parameters.e_parameterSpringBarrier;
}
if (this.m_particleFlags === (b2.ParticleFlag.b2_wallParticle | b2.ParticleFlag.b2_repulsiveParticle)) {
return DrawingParticles.Parameters.e_parameterRepulsive;
}
return this.m_particleFlags;
}
return DrawingParticles.Parameters.e_parameterMove;
}
public Keyboard(key: string) {
this.m_drawing = key !== "x";
this.m_particleFlags = 0;
this.m_groupFlags = 0;
switch (key) {
case "e":
this.m_particleFlags = b2.ParticleFlag.b2_elasticParticle;
this.m_groupFlags = b2.ParticleGroupFlag.b2_solidParticleGroup;
break;
case "p":
this.m_particleFlags = b2.ParticleFlag.b2_powderParticle;
break;
case "r":
this.m_groupFlags = b2.ParticleGroupFlag.b2_rigidParticleGroup | b2.ParticleGroupFlag.b2_solidParticleGroup;
break;
case "s":
this.m_particleFlags = b2.ParticleFlag.b2_springParticle;
this.m_groupFlags = b2.ParticleGroupFlag.b2_solidParticleGroup;
break;
case "t":
this.m_particleFlags = b2.ParticleFlag.b2_tensileParticle;
break;
case "v":
this.m_particleFlags = b2.ParticleFlag.b2_viscousParticle;
break;
case "w":
this.m_particleFlags = b2.ParticleFlag.b2_wallParticle;
this.m_groupFlags = b2.ParticleGroupFlag.b2_solidParticleGroup;
break;
case "b":
this.m_particleFlags = b2.ParticleFlag.b2_barrierParticle | b2.ParticleFlag.b2_wallParticle;
break;
case "h":
this.m_particleFlags = b2.ParticleFlag.b2_barrierParticle;
this.m_groupFlags = b2.ParticleGroupFlag.b2_rigidParticleGroup;
break;
case "n":
this.m_particleFlags = b2.ParticleFlag.b2_barrierParticle | b2.ParticleFlag.b2_elasticParticle;
this.m_groupFlags = b2.ParticleGroupFlag.b2_solidParticleGroup;
break;
case "m":
this.m_particleFlags = b2.ParticleFlag.b2_barrierParticle | b2.ParticleFlag.b2_springParticle;
this.m_groupFlags = b2.ParticleGroupFlag.b2_solidParticleGroup;
break;
case "f":
this.m_particleFlags = b2.ParticleFlag.b2_wallParticle | b2.ParticleFlag.b2_repulsiveParticle;
break;
case "c":
this.m_particleFlags = b2.ParticleFlag.b2_colorMixingParticle;
break;
case "z":
this.m_particleFlags = b2.ParticleFlag.b2_zombieParticle;
break;
default:
break;
}
testbed.Test.SetParticleParameterValue(this.DetermineParticleParameter());
}
public MouseMove(p: b2.Vec2) {
super.MouseMove(p);
if (this.m_drawing) {
const shape = new b2.CircleShape();
shape.m_p.Copy(p);
shape.m_radius = 0.2;
/// b2Transform xf;
/// xf.SetIdentity();
const xf = b2.Transform.IDENTITY;
this.m_particleSystem.DestroyParticlesInShape(shape, xf);
const joinGroup = this.m_lastGroup && this.m_groupFlags === this.m_lastGroup.GetGroupFlags();
if (!joinGroup) {
this.m_colorIndex = (this.m_colorIndex + 1) % testbed.Test.k_ParticleColorsCount;
}
const pd = new b2.ParticleGroupDef();
pd.shape = shape;
pd.flags = this.m_particleFlags;
if ((this.m_particleFlags & (b2.ParticleFlag.b2_wallParticle | b2.ParticleFlag.b2_springParticle | b2.ParticleFlag.b2_elasticParticle)) ||
(this.m_particleFlags === (b2.ParticleFlag.b2_wallParticle | b2.ParticleFlag.b2_barrierParticle))) {
pd.flags |= b2.ParticleFlag.b2_reactiveParticle;
}
pd.groupFlags = this.m_groupFlags;
pd.color.Copy(testbed.Test.k_ParticleColors[this.m_colorIndex]);
pd.group = this.m_lastGroup;
this.m_lastGroup = this.m_particleSystem.CreateParticleGroup(pd);
this.m_mouseTracing = false;
}
}
public MouseUp(p: b2.Vec2) {
super.MouseUp(p);
this.m_lastGroup = null;
}
public ParticleGroupDestroyed(group: b2.ParticleGroup) {
super.ParticleGroupDestroyed(group);
if (group === this.m_lastGroup) {
this.m_lastGroup = null;
}
}
public SplitParticleGroups() {
for (let group = this.m_particleSystem.GetParticleGroupList(); group; group = group.GetNext()) {
if (group !== this.m_lastGroup &&
(group.GetGroupFlags() & b2.ParticleGroupFlag.b2_rigidParticleGroup) &&
(group.GetAllParticleFlags() & b2.ParticleFlag.b2_zombieParticle)) {
// Split a rigid particle group which may be disconnected
// by destroying particles.
this.m_particleSystem.SplitParticleGroup(group);
}
}
}
public Step(settings: testbed.Settings) {
const parameterValue = testbed.Test.GetParticleParameterValue();
this.m_drawing = (parameterValue & DrawingParticles.Parameters.e_parameterMove) !== DrawingParticles.Parameters.e_parameterMove;
if (this.m_drawing) {
switch (parameterValue) {
case b2.ParticleFlag.b2_elasticParticle:
case b2.ParticleFlag.b2_springParticle:
case b2.ParticleFlag.b2_wallParticle:
this.m_particleFlags = parameterValue;
this.m_groupFlags = b2.ParticleGroupFlag.b2_solidParticleGroup;
break;
case DrawingParticles.Parameters.e_parameterRigid:
// b2_waterParticle is the default particle type in
// LiquidFun.
this.m_particleFlags = b2.ParticleFlag.b2_waterParticle;
this.m_groupFlags = b2.ParticleGroupFlag.b2_rigidParticleGroup | b2.ParticleGroupFlag.b2_solidParticleGroup;
break;
case DrawingParticles.Parameters.e_parameterRigidBarrier:
this.m_particleFlags = b2.ParticleFlag.b2_barrierParticle;
this.m_groupFlags = b2.ParticleGroupFlag.b2_rigidParticleGroup;
break;
case DrawingParticles.Parameters.e_parameterElasticBarrier:
this.m_particleFlags = b2.ParticleFlag.b2_barrierParticle | b2.ParticleFlag.b2_elasticParticle;
this.m_groupFlags = 0;
break;
case DrawingParticles.Parameters.e_parameterSpringBarrier:
this.m_particleFlags = b2.ParticleFlag.b2_barrierParticle | b2.ParticleFlag.b2_springParticle;
this.m_groupFlags = 0;
break;
case DrawingParticles.Parameters.e_parameterRepulsive:
this.m_particleFlags = b2.ParticleFlag.b2_repulsiveParticle | b2.ParticleFlag.b2_wallParticle;
this.m_groupFlags = b2.ParticleGroupFlag.b2_solidParticleGroup;
break;
default:
this.m_particleFlags = parameterValue;
this.m_groupFlags = 0;
break;
}
}
if (this.m_particleSystem.GetAllParticleFlags() & b2.ParticleFlag.b2_zombieParticle) {
this.SplitParticleGroups();
}
super.Step(settings);
testbed.g_debugDraw.DrawString(5, this.m_textLine, "Keys: (L) liquid, (E) elastic, (S) spring");
this.m_textLine += testbed.DRAW_STRING_NEW_LINE;
testbed.g_debugDraw.DrawString(5, this.m_textLine, "(R) rigid, (W) wall, (V) viscous, (T) tensile");
this.m_textLine += testbed.DRAW_STRING_NEW_LINE;
testbed.g_debugDraw.DrawString(5, this.m_textLine, "(F) repulsive wall, (B) wall barrier");
this.m_textLine += testbed.DRAW_STRING_NEW_LINE;
testbed.g_debugDraw.DrawString(5, this.m_textLine, "(H) rigid barrier, (N) elastic barrier, (M) spring barrier");
this.m_textLine += testbed.DRAW_STRING_NEW_LINE;
testbed.g_debugDraw.DrawString(5, this.m_textLine, "(C) color mixing, (Z) erase, (X) move");
this.m_textLine += testbed.DRAW_STRING_NEW_LINE;
}
public GetDefaultViewZoom() {
return 0.1;
}
public static Create() {
return new DrawingParticles();
}
}
export const testIndex: number = testbed.RegisterTest("Particles", "Drawing Particles", DrawingParticles.Create);
// #endif | the_stack |
import * as GObject from "@gi-types/gobject";
import * as Gck from "@gi-types/gck";
import * as Gio from "@gi-types/gio";
import * as GLib from "@gi-types/glib";
export const ICON_CERTIFICATE: string;
export const ICON_GNUPG: string;
export const ICON_HOME_DIRECTORY: string;
export const ICON_KEY: string;
export const ICON_KEY_PAIR: string;
export const ICON_PASSWORD: string;
export const ICON_SMART_CARD: string;
export const MAJOR_VERSION: number;
export const MICRO_VERSION: number;
export const MINOR_VERSION: number;
export const PURPOSE_CLIENT_AUTH: string;
export const PURPOSE_CODE_SIGNING: string;
export const PURPOSE_EMAIL: string;
export const PURPOSE_SERVER_AUTH: string;
export const SECRET_EXCHANGE_PROTOCOL_1: string;
export const UNLOCK_OPTION_ALWAYS: string;
export const UNLOCK_OPTION_IDLE: string;
export const UNLOCK_OPTION_SESSION: string;
export const UNLOCK_OPTION_TIMEOUT: string;
export function certificate_compare(first?: Comparable | null, other?: Comparable | null): number;
export function data_error_get_domain(): GLib.Quark;
export function fingerprint_from_attributes(attrs: Gck.Attributes, checksum_type: GLib.ChecksumType): Uint8Array | null;
export function fingerprint_from_subject_public_key_info(
key_info: Uint8Array | string,
checksum_type: GLib.ChecksumType
): Uint8Array | null;
export function icon_for_token(token_info: Gck.TokenInfo): Gio.Icon;
export function importer_create_for_parsed(parsed: Parsed): Importer[];
export function importer_queue_and_filter_for_parsed(importers: Importer[], parsed: Parsed): Importer[];
export function importer_register(importer_type: GObject.GType, attrs: Gck.Attributes): void;
export function importer_register_well_known(): void;
export function mock_prompter_disconnect(): void;
export function mock_prompter_expect_close(): void;
export function mock_prompter_expect_confirm_cancel(): void;
export function mock_prompter_expect_password_cancel(): void;
export function mock_prompter_get_delay_msec(): number;
export function mock_prompter_is_expecting(): boolean;
export function mock_prompter_is_prompting(): boolean;
export function mock_prompter_set_delay_msec(delay_msec: number): void;
export function mock_prompter_start(): string;
export function mock_prompter_stop(): void;
export function parsed_unref(parsed?: any | null): void;
export function pkcs11_add_module(module: Gck.Module): void;
export function pkcs11_add_module_from_file(module_path: string, unused?: any | null): boolean;
export function pkcs11_get_modules(): Gck.Module[];
export function pkcs11_get_trust_lookup_slots(): Gck.Slot[];
export function pkcs11_get_trust_lookup_uris(): string[] | null;
export function pkcs11_get_trust_store_slot(): Gck.Slot | null;
export function pkcs11_get_trust_store_uri(): string | null;
export function pkcs11_initialize(cancellable?: Gio.Cancellable | null): boolean;
export function pkcs11_initialize_async(cancellable?: Gio.Cancellable | null): Promise<boolean>;
export function pkcs11_initialize_async(
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<Gio.Cancellable | null> | null
): void;
export function pkcs11_initialize_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<Gio.Cancellable | null> | null
): Promise<boolean> | void;
export function pkcs11_initialize_finish(result: Gio.AsyncResult): boolean;
export function pkcs11_set_modules(modules: Gck.Module[]): void;
export function pkcs11_set_trust_lookup_uris(pkcs11_uris?: string | null): void;
export function pkcs11_set_trust_store_uri(pkcs11_uri?: string | null): void;
export function trust_add_pinned_certificate(
certificate: Certificate,
purpose: string,
peer: string,
cancellable?: Gio.Cancellable | null
): boolean;
export function trust_add_pinned_certificate_async(
certificate: Certificate,
purpose: string,
peer: string,
cancellable?: Gio.Cancellable | null
): Promise<boolean>;
export function trust_add_pinned_certificate_async(
certificate: Certificate,
purpose: string,
peer: string,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<Certificate> | null
): void;
export function trust_add_pinned_certificate_async(
certificate: Certificate,
purpose: string,
peer: string,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<Certificate> | null
): Promise<boolean> | void;
export function trust_add_pinned_certificate_finish(result: Gio.AsyncResult): boolean;
export function trust_is_certificate_anchored(
certificate: Certificate,
purpose: string,
cancellable?: Gio.Cancellable | null
): boolean;
export function trust_is_certificate_anchored_async(
certificate: Certificate,
purpose: string,
cancellable?: Gio.Cancellable | null
): Promise<boolean>;
export function trust_is_certificate_anchored_async(
certificate: Certificate,
purpose: string,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<Certificate> | null
): void;
export function trust_is_certificate_anchored_async(
certificate: Certificate,
purpose: string,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<Certificate> | null
): Promise<boolean> | void;
export function trust_is_certificate_anchored_finish(result: Gio.AsyncResult): boolean;
export function trust_is_certificate_pinned(
certificate: Certificate,
purpose: string,
peer: string,
cancellable?: Gio.Cancellable | null
): boolean;
export function trust_is_certificate_pinned_async(
certificate: Certificate,
purpose: string,
peer: string,
cancellable?: Gio.Cancellable | null
): Promise<boolean>;
export function trust_is_certificate_pinned_async(
certificate: Certificate,
purpose: string,
peer: string,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<Certificate> | null
): void;
export function trust_is_certificate_pinned_async(
certificate: Certificate,
purpose: string,
peer: string,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<Certificate> | null
): Promise<boolean> | void;
export function trust_is_certificate_pinned_finish(result: Gio.AsyncResult): boolean;
export function trust_remove_pinned_certificate(
certificate: Certificate,
purpose: string,
peer: string,
cancellable?: Gio.Cancellable | null
): boolean;
export function trust_remove_pinned_certificate_async(
certificate: Certificate,
purpose: string,
peer: string,
cancellable?: Gio.Cancellable | null
): Promise<boolean>;
export function trust_remove_pinned_certificate_async(
certificate: Certificate,
purpose: string,
peer: string,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<Certificate> | null
): void;
export function trust_remove_pinned_certificate_async(
certificate: Certificate,
purpose: string,
peer: string,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<Certificate> | null
): Promise<boolean> | void;
export function trust_remove_pinned_certificate_finish(result: Gio.AsyncResult): boolean;
export type FilterCollectionFunc<A = GObject.Object> = (object: A) => boolean;
export namespace CertificateChainStatus {
export const $gtype: GObject.GType<CertificateChainStatus>;
}
export enum CertificateChainStatus {
UNKNOWN = 0,
INCOMPLETE = 1,
DISTRUSTED = 2,
SELFSIGNED = 3,
PINNED = 4,
ANCHORED = 5,
}
export namespace CertificateRequestFormat {
export const $gtype: GObject.GType<CertificateRequestFormat>;
}
export enum CertificateRequestFormat {
CERTIFICATE_REQUEST_PKCS10 = 1,
}
export namespace DataError {
export const $gtype: GObject.GType<DataError>;
}
export enum DataError {
FAILURE = -1,
UNRECOGNIZED = 1,
CANCELLED = 2,
LOCKED = 3,
}
export namespace DataFormat {
export const $gtype: GObject.GType<DataFormat>;
}
export enum DataFormat {
ALL = -1,
INVALID = 0,
DER_PRIVATE_KEY = 100,
DER_PRIVATE_KEY_RSA = 101,
DER_PRIVATE_KEY_DSA = 102,
DER_PRIVATE_KEY_EC = 103,
DER_SUBJECT_PUBLIC_KEY = 150,
DER_CERTIFICATE_X509 = 200,
DER_PKCS7 = 300,
DER_PKCS8 = 400,
DER_PKCS8_PLAIN = 401,
DER_PKCS8_ENCRYPTED = 402,
DER_PKCS10 = 450,
DER_SPKAC = 455,
BASE64_SPKAC = 456,
DER_PKCS12 = 500,
OPENSSH_PUBLIC = 600,
OPENPGP_PACKET = 700,
OPENPGP_ARMOR = 701,
PEM = 1000,
PEM_PRIVATE_KEY_RSA = 1001,
PEM_PRIVATE_KEY_DSA = 1002,
PEM_CERTIFICATE_X509 = 1003,
PEM_PKCS7 = 1004,
PEM_PKCS8_PLAIN = 1005,
PEM_PKCS8_ENCRYPTED = 1006,
PEM_PKCS12 = 1007,
PEM_PRIVATE_KEY = 1008,
PEM_PKCS10 = 1009,
PEM_PRIVATE_KEY_EC = 1010,
PEM_PUBLIC_KEY = 1011,
}
export namespace PromptReply {
export const $gtype: GObject.GType<PromptReply>;
}
export enum PromptReply {
CANCEL = 0,
CONTINUE = 1,
}
export namespace SystemPromptError {
export const $gtype: GObject.GType<SystemPromptError>;
}
export enum SystemPromptError {
SYSTEM_PROMPT_IN_PROGRESS = 1,
}
export namespace SystemPrompterMode {
export const $gtype: GObject.GType<SystemPrompterMode>;
}
export enum SystemPrompterMode {
SINGLE = 0,
MULTIPLE = 1,
}
export namespace CertificateChainFlags {
export const $gtype: GObject.GType<CertificateChainFlags>;
}
export enum CertificateChainFlags {
NONE = 0,
NO_LOOKUPS = 1,
}
export namespace ColumnFlags {
export const $gtype: GObject.GType<ColumnFlags>;
}
export enum ColumnFlags {
NONE = 0,
HIDDEN = 2,
SORTABLE = 4,
}
export module CertificateChain {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
length: number;
}
}
export class CertificateChain extends GObject.Object {
static $gtype: GObject.GType<CertificateChain>;
constructor(properties?: Partial<CertificateChain.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<CertificateChain.ConstructorProperties>, ...args: any[]): void;
// Properties
length: number;
// Constructors
static ["new"](): CertificateChain;
// Members
add(certificate: Certificate): void;
build(
purpose: string,
peer: string | null,
flags: CertificateChainFlags,
cancellable?: Gio.Cancellable | null
): boolean;
build_async(
purpose: string,
peer: string | null,
flags: CertificateChainFlags,
cancellable?: Gio.Cancellable | null
): Promise<boolean>;
build_async(
purpose: string,
peer: string | null,
flags: CertificateChainFlags,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
build_async(
purpose: string,
peer: string | null,
flags: CertificateChainFlags,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<boolean> | void;
build_finish(result: Gio.AsyncResult): boolean;
get_anchor(): Certificate;
get_certificate(index: number): Certificate;
get_endpoint(): Certificate;
get_length(): number;
get_status(): CertificateChainStatus;
}
export module CertificateRequest {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
private_key: Gck.Object;
privateKey: Gck.Object;
}
}
export class CertificateRequest extends GObject.Object {
static $gtype: GObject.GType<CertificateRequest>;
constructor(properties?: Partial<CertificateRequest.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<CertificateRequest.ConstructorProperties>, ...args: any[]): void;
// Properties
private_key: Gck.Object;
privateKey: Gck.Object;
// Members
complete(cancellable?: Gio.Cancellable | null): boolean;
complete_async(cancellable?: Gio.Cancellable | null): Promise<boolean>;
complete_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void;
complete_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<boolean> | void;
complete_finish(result: Gio.AsyncResult): boolean;
encode(textual: boolean): Uint8Array;
get_format(): CertificateRequestFormat;
get_private_key(): Gck.Object;
set_cn(cn: string): void;
static capable(private_key: Gck.Object, cancellable?: Gio.Cancellable | null): boolean;
static capable_async(private_key: Gck.Object, cancellable?: Gio.Cancellable | null): Promise<boolean>;
static capable_async(
private_key: Gck.Object,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<CertificateRequest> | null
): void;
static capable_async(
private_key: Gck.Object,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<CertificateRequest> | null
): Promise<boolean> | void;
static capable_finish(result: Gio.AsyncResult): boolean;
static prepare(format: CertificateRequestFormat, private_key: Gck.Object): CertificateRequest;
}
export module FilterCollection {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
underlying: Collection;
}
}
export class FilterCollection extends GObject.Object implements Collection {
static $gtype: GObject.GType<FilterCollection>;
constructor(properties?: Partial<FilterCollection.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<FilterCollection.ConstructorProperties>, ...args: any[]): void;
// Properties
underlying: Collection;
// Constructors
static new_with_callback(underlying: Collection, callback?: FilterCollectionFunc | null): FilterCollection;
// Members
get_underlying(): Collection;
refilter(): void;
set_callback(callback?: FilterCollectionFunc | null): void;
// Implemented Members
contains(object: GObject.Object): boolean;
emit_added(object: GObject.Object): void;
emit_removed(object: GObject.Object): void;
get_length(): number;
get_objects(): GObject.Object[];
vfunc_added(object: GObject.Object): void;
vfunc_contains(object: GObject.Object): boolean;
vfunc_get_length(): number;
vfunc_get_objects(): GObject.Object[];
vfunc_removed(object: GObject.Object): void;
}
export module Parser {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
parsed_attributes: Gck.Attributes;
parsedAttributes: Gck.Attributes;
parsed_description: string;
parsedDescription: string;
parsed_label: string;
parsedLabel: string;
}
}
export class Parser extends GObject.Object {
static $gtype: GObject.GType<Parser>;
constructor(properties?: Partial<Parser.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Parser.ConstructorProperties>, ...args: any[]): void;
// Properties
parsed_attributes: Gck.Attributes;
parsedAttributes: Gck.Attributes;
parsed_description: string;
parsedDescription: string;
parsed_label: string;
parsedLabel: string;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "authenticate", callback: (_source: this, count: number) => boolean): number;
connect_after(signal: "authenticate", callback: (_source: this, count: number) => boolean): number;
emit(signal: "authenticate", count: number): void;
connect(signal: "parsed", callback: (_source: this) => void): number;
connect_after(signal: "parsed", callback: (_source: this) => void): number;
emit(signal: "parsed"): void;
// Constructors
static ["new"](): Parser;
// Members
add_password(password?: string | null): void;
format_disable(format: DataFormat): void;
format_enable(format: DataFormat): void;
format_supported(format: DataFormat): boolean;
get_filename(): string;
get_parsed(): Parsed;
get_parsed_attributes(): Gck.Attributes | null;
get_parsed_block(): Uint8Array | null;
get_parsed_bytes(): GLib.Bytes;
get_parsed_description(): string | null;
get_parsed_format(): DataFormat;
get_parsed_label(): string | null;
parse_bytes(data: GLib.Bytes | Uint8Array): boolean;
parse_data(data: Uint8Array | string): boolean;
parse_stream(input: Gio.InputStream, cancellable?: Gio.Cancellable | null): boolean;
parse_stream_async(input: Gio.InputStream, cancellable?: Gio.Cancellable | null): Promise<boolean>;
parse_stream_async(
input: Gio.InputStream,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
parse_stream_async(
input: Gio.InputStream,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<boolean> | void;
parse_stream_finish(result: Gio.AsyncResult): boolean;
set_filename(filename?: string | null): void;
vfunc_authenticate(count: number): boolean;
vfunc_parsed(): void;
}
export module Pkcs11Certificate {
export interface ConstructorProperties extends Gck.Object.ConstructorProperties {
[key: string]: any;
attributes: Gck.Attributes;
}
}
export class Pkcs11Certificate extends Gck.Object implements Certificate, Comparable {
static $gtype: GObject.GType<Pkcs11Certificate>;
constructor(properties?: Partial<Pkcs11Certificate.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Pkcs11Certificate.ConstructorProperties>, ...args: any[]): void;
// Properties
attributes: Gck.Attributes;
// Implemented Properties
description: string;
expiry: GLib.Date;
icon: Gio.Icon;
issuer: string;
label: string;
markup: string;
subject: string;
// Members
get_attributes(): Gck.Attributes;
static lookup_issuer(certificate: Certificate, cancellable?: Gio.Cancellable | null): Certificate;
static lookup_issuer_async(certificate: Certificate, cancellable?: Gio.Cancellable | null): Promise<Certificate>;
static lookup_issuer_async(
certificate: Certificate,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<Pkcs11Certificate> | null
): void;
static lookup_issuer_async(
certificate: Certificate,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<Pkcs11Certificate> | null
): Promise<Certificate> | void;
static lookup_issuer_finish(result: Gio.AsyncResult): Certificate;
// Implemented Members
get_basic_constraints(): [boolean, boolean | null, number | null];
get_der_data(): Uint8Array;
get_expiry_date(): GLib.Date;
get_fingerprint(type: GLib.ChecksumType): Uint8Array;
get_fingerprint_hex(type: GLib.ChecksumType): string;
get_issued_date(): GLib.Date;
get_issuer_cn(): string;
get_issuer_dn(): string;
get_issuer_name(): string;
get_issuer_part(part: string): string | null;
get_issuer_raw(): Uint8Array;
get_key_size(): number;
get_markup_text(): string;
get_serial_number(): Uint8Array;
get_serial_number_hex(): string;
get_subject_cn(): string;
get_subject_dn(): string;
get_subject_name(): string;
get_subject_part(part: string): string | null;
get_subject_raw(): Uint8Array;
is_issuer(issuer: Certificate): boolean;
mixin_emit_notify(): void;
vfunc_get_der_data(): Uint8Array;
compare(other?: Comparable | null): number;
compare(...args: never[]): never;
vfunc_compare(other?: Comparable | null): number;
}
export module SecretExchange {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
protocol: string;
}
}
export class SecretExchange extends GObject.Object {
static $gtype: GObject.GType<SecretExchange>;
constructor(properties?: Partial<SecretExchange.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<SecretExchange.ConstructorProperties>, ...args: any[]): void;
// Properties
protocol: string;
// Constructors
static ["new"](protocol?: string | null): SecretExchange;
// Members
begin(): string;
get_protocol(): string;
get_secret(): string[];
receive(exchange: string): boolean;
send(secret: string | null, secret_len: number): string;
vfunc_derive_transport_key(peer: number, n_peer: number): boolean;
vfunc_generate_exchange_key(scheme: string, public_key: number, n_public_key: number): boolean;
}
export module SimpleCertificate {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
}
}
export class SimpleCertificate extends GObject.Object implements Certificate, Comparable {
static $gtype: GObject.GType<SimpleCertificate>;
constructor(properties?: Partial<SimpleCertificate.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<SimpleCertificate.ConstructorProperties>, ...args: any[]): void;
// Implemented Properties
description: string;
expiry: GLib.Date;
icon: Gio.Icon;
issuer: string;
label: string;
markup: string;
subject: string;
// Constructors
static ["new"](data: Uint8Array | string): SimpleCertificate;
// Implemented Members
get_basic_constraints(): [boolean, boolean | null, number | null];
get_der_data(): Uint8Array;
get_expiry_date(): GLib.Date;
get_fingerprint(type: GLib.ChecksumType): Uint8Array;
get_fingerprint_hex(type: GLib.ChecksumType): string;
get_issued_date(): GLib.Date;
get_issuer_cn(): string;
get_issuer_dn(): string;
get_issuer_name(): string;
get_issuer_part(part: string): string | null;
get_issuer_raw(): Uint8Array;
get_key_size(): number;
get_markup_text(): string;
get_serial_number(): Uint8Array;
get_serial_number_hex(): string;
get_subject_cn(): string;
get_subject_dn(): string;
get_subject_name(): string;
get_subject_part(part: string): string | null;
get_subject_raw(): Uint8Array;
is_issuer(issuer: Certificate): boolean;
mixin_emit_notify(): void;
vfunc_get_der_data(): Uint8Array;
compare(other?: Comparable | null): number;
compare(...args: never[]): never;
vfunc_compare(other?: Comparable | null): number;
}
export module SimpleCollection {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
}
}
export class SimpleCollection extends GObject.Object implements Collection {
static $gtype: GObject.GType<SimpleCollection>;
constructor(properties?: Partial<SimpleCollection.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<SimpleCollection.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](): SimpleCollection;
// Members
add(object: GObject.Object): void;
remove(object: GObject.Object): void;
// Implemented Members
contains(object: GObject.Object): boolean;
emit_added(object: GObject.Object): void;
emit_removed(object: GObject.Object): void;
get_length(): number;
get_objects(): GObject.Object[];
vfunc_added(object: GObject.Object): void;
vfunc_contains(object: GObject.Object): boolean;
vfunc_get_length(): number;
vfunc_get_objects(): GObject.Object[];
vfunc_removed(object: GObject.Object): void;
}
export module SshAskpass {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
interaction: Gio.TlsInteraction;
}
}
export class SshAskpass extends GObject.Object {
static $gtype: GObject.GType<SshAskpass>;
constructor(properties?: Partial<SshAskpass.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<SshAskpass.ConstructorProperties>, ...args: any[]): void;
// Properties
interaction: Gio.TlsInteraction;
// Constructors
static ["new"](interaction: Gio.TlsInteraction): SshAskpass;
// Members
get_interaction(): Gio.TlsInteraction;
static child_setup(askpass?: any | null): void;
}
export module SystemPrompt {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
bus_name: string;
busName: string;
secret_exchange: SecretExchange;
secretExchange: SecretExchange;
timeout_seconds: number;
timeoutSeconds: number;
}
}
export class SystemPrompt extends GObject.Object implements Prompt, Gio.AsyncInitable<SystemPrompt>, Gio.Initable {
static $gtype: GObject.GType<SystemPrompt>;
constructor(properties?: Partial<SystemPrompt.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<SystemPrompt.ConstructorProperties>, ...args: any[]): void;
// Properties
bus_name: string;
busName: string;
secret_exchange: SecretExchange;
secretExchange: SecretExchange;
timeout_seconds: number;
timeoutSeconds: number;
// Implemented Properties
caller_window: string;
callerWindow: string;
cancel_label: string;
cancelLabel: string;
choice_chosen: boolean;
choiceChosen: boolean;
choice_label: string;
choiceLabel: string;
continue_label: string;
continueLabel: string;
description: string;
message: string;
password_new: boolean;
passwordNew: boolean;
password_strength: number;
passwordStrength: number;
title: string;
warning: string;
// Members
close(cancellable?: Gio.Cancellable | null): boolean;
close(...args: never[]): never;
close_async(cancellable?: Gio.Cancellable | null): Promise<boolean>;
close_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void;
close_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<boolean> | void;
close_finish(result: Gio.AsyncResult): boolean;
get_secret_exchange(): SecretExchange;
static error_get_domain(): GLib.Quark;
static open(timeout_seconds: number, cancellable?: Gio.Cancellable | null): SystemPrompt;
static open_async(timeout_seconds: number, cancellable?: Gio.Cancellable | null): Promise<SystemPrompt>;
static open_async(
timeout_seconds: number,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<SystemPrompt> | null
): void;
static open_async(
timeout_seconds: number,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<SystemPrompt> | null
): Promise<SystemPrompt> | void;
static open_finish(result: Gio.AsyncResult): SystemPrompt;
static open_for_prompter(
prompter_name: string | null,
timeout_seconds: number,
cancellable?: Gio.Cancellable | null
): SystemPrompt;
static open_for_prompter_async(
prompter_name: string | null,
timeout_seconds: number,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<SystemPrompt> | null
): void;
// Implemented Members
confirm(cancellable?: Gio.Cancellable | null): PromptReply;
confirm_async(cancellable?: Gio.Cancellable | null): Promise<PromptReply>;
confirm_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void;
confirm_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<PromptReply> | void;
confirm_finish(result: Gio.AsyncResult): PromptReply;
confirm_run(cancellable?: Gio.Cancellable | null): PromptReply;
get_caller_window(): string;
get_cancel_label(): string;
get_choice_chosen(): boolean;
get_choice_label(): string;
get_continue_label(): string;
get_description(): string;
get_message(): string;
get_password_new(): boolean;
get_password_strength(): number;
get_title(): string;
get_warning(): string;
password(cancellable?: Gio.Cancellable | null): string;
password_async(cancellable?: Gio.Cancellable | null): Promise<string>;
password_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void;
password_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<string> | void;
password_finish(result: Gio.AsyncResult): string;
password_run(cancellable?: Gio.Cancellable | null): string;
reset(): void;
set_caller_window(window_id: string): void;
set_cancel_label(cancel_label: string): void;
set_choice_chosen(chosen: boolean): void;
set_choice_label(choice_label?: string | null): void;
set_continue_label(continue_label: string): void;
set_description(description: string): void;
set_message(message: string): void;
set_password_new(new_password: boolean): void;
set_title(title: string): void;
set_warning(warning?: string | null): void;
vfunc_prompt_close(): void;
vfunc_prompt_confirm_async(cancellable?: Gio.Cancellable | null): Promise<PromptReply>;
vfunc_prompt_confirm_async(
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
vfunc_prompt_confirm_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<PromptReply> | void;
vfunc_prompt_confirm_finish(result: Gio.AsyncResult): PromptReply;
vfunc_prompt_password_async(cancellable?: Gio.Cancellable | null): Promise<string>;
vfunc_prompt_password_async(
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
vfunc_prompt_password_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<string> | void;
vfunc_prompt_password_finish(result: Gio.AsyncResult): string;
init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>;
init_async(
io_priority: number,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
init_async(
io_priority: number,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<boolean> | void;
init_finish(res: Gio.AsyncResult): boolean;
new_finish(res: Gio.AsyncResult): SystemPrompt;
vfunc_init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>;
vfunc_init_async(
io_priority: number,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
vfunc_init_async(
io_priority: number,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<boolean> | void;
vfunc_init_finish(res: Gio.AsyncResult): boolean;
init(cancellable?: Gio.Cancellable | null): boolean;
vfunc_init(cancellable?: Gio.Cancellable | null): boolean;
}
export module SystemPrompter {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
prompt_type: GObject.GType;
promptType: GObject.GType;
prompting: boolean;
}
}
export class SystemPrompter extends GObject.Object {
static $gtype: GObject.GType<SystemPrompter>;
constructor(properties?: Partial<SystemPrompter.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<SystemPrompter.ConstructorProperties>, ...args: any[]): void;
// Properties
prompt_type: GObject.GType;
promptType: GObject.GType;
prompting: boolean;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "new-prompt", callback: (_source: this) => Prompt): number;
connect_after(signal: "new-prompt", callback: (_source: this) => Prompt): number;
emit(signal: "new-prompt"): void;
// Constructors
static ["new"](mode: SystemPrompterMode, prompt_type: GObject.GType): SystemPrompter;
// Members
get_mode(): SystemPrompterMode;
get_prompt_type(): GObject.GType;
get_prompting(): boolean;
register(connection: Gio.DBusConnection): void;
unregister(wait: boolean): void;
}
export module UnionCollection {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
}
}
export class UnionCollection extends GObject.Object implements Collection {
static $gtype: GObject.GType<UnionCollection>;
constructor(properties?: Partial<UnionCollection.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<UnionCollection.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](): UnionCollection;
// Members
add(collection: Collection): void;
elements(): Collection[];
have(collection: Collection): boolean;
remove(collection: Collection): void;
size(): number;
take(collection: Collection): void;
// Implemented Members
contains(object: GObject.Object): boolean;
emit_added(object: GObject.Object): void;
emit_removed(object: GObject.Object): void;
get_length(): number;
get_objects(): GObject.Object[];
vfunc_added(object: GObject.Object): void;
vfunc_contains(object: GObject.Object): boolean;
vfunc_get_length(): number;
vfunc_get_objects(): GObject.Object[];
vfunc_removed(object: GObject.Object): void;
}
export class CertificateChainPrivate {
static $gtype: GObject.GType<CertificateChainPrivate>;
constructor(copy: CertificateChainPrivate);
}
export class Column {
static $gtype: GObject.GType<Column>;
constructor(copy: Column);
// Fields
property_name: string;
property_type: GObject.GType;
column_type: GObject.GType;
label: string;
flags: ColumnFlags;
transformer: GObject.ValueTransform;
user_data: any;
reserved: any;
}
export class FilterCollectionPrivate {
static $gtype: GObject.GType<FilterCollectionPrivate>;
constructor(copy: FilterCollectionPrivate);
}
export class Parsed {
static $gtype: GObject.GType<Parsed>;
constructor(copy: Parsed);
// Members
get_attributes(): Gck.Attributes | null;
get_bytes(): GLib.Bytes;
get_data(): Uint8Array | null;
get_description(): string | null;
get_filename(): string;
get_format(): DataFormat;
get_label(): string | null;
ref(): Parsed;
static unref(parsed?: any | null): void;
}
export class ParserPrivate {
static $gtype: GObject.GType<ParserPrivate>;
constructor(copy: ParserPrivate);
}
export class Pkcs11CertificatePrivate {
static $gtype: GObject.GType<Pkcs11CertificatePrivate>;
constructor(copy: Pkcs11CertificatePrivate);
}
export class SecretExchangePrivate {
static $gtype: GObject.GType<SecretExchangePrivate>;
constructor(copy: SecretExchangePrivate);
}
export class SimpleCertificatePrivate {
static $gtype: GObject.GType<SimpleCertificatePrivate>;
constructor(copy: SimpleCertificatePrivate);
}
export class SimpleCollectionPrivate {
static $gtype: GObject.GType<SimpleCollectionPrivate>;
constructor(copy: SimpleCollectionPrivate);
}
export class SystemPromptPrivate {
static $gtype: GObject.GType<SystemPromptPrivate>;
constructor(copy: SystemPromptPrivate);
}
export class SystemPrompterPrivate {
static $gtype: GObject.GType<SystemPrompterPrivate>;
constructor(copy: SystemPrompterPrivate);
}
export class UnionCollectionPrivate {
static $gtype: GObject.GType<UnionCollectionPrivate>;
constructor(copy: UnionCollectionPrivate);
}
export interface CertificateNamespace {
$gtype: GObject.GType<Certificate>;
prototype: CertificatePrototype;
compare(first?: Comparable | null, other?: Comparable | null): number;
compare(...args: never[]): never;
}
export type Certificate = CertificatePrototype;
export interface CertificatePrototype extends Comparable {
// Properties
description: string;
expiry: GLib.Date;
icon: Gio.Icon;
issuer: string;
label: string;
markup: string;
subject: string;
// Members
get_basic_constraints(): [boolean, boolean | null, number | null];
get_der_data(): Uint8Array;
get_expiry_date(): GLib.Date;
get_fingerprint(type: GLib.ChecksumType): Uint8Array;
get_fingerprint_hex(type: GLib.ChecksumType): string;
get_issued_date(): GLib.Date;
get_issuer_cn(): string;
get_issuer_dn(): string;
get_issuer_name(): string;
get_issuer_part(part: string): string | null;
get_issuer_raw(): Uint8Array;
get_key_size(): number;
get_markup_text(): string;
get_serial_number(): Uint8Array;
get_serial_number_hex(): string;
get_subject_cn(): string;
get_subject_dn(): string;
get_subject_name(): string;
get_subject_part(part: string): string | null;
get_subject_raw(): Uint8Array;
is_issuer(issuer: Certificate): boolean;
mixin_emit_notify(): void;
vfunc_get_der_data(): Uint8Array;
}
export const Certificate: CertificateNamespace;
export interface CollectionNamespace {
$gtype: GObject.GType<Collection>;
prototype: CollectionPrototype;
}
export type Collection = CollectionPrototype;
export interface CollectionPrototype extends GObject.Object {
// Members
contains(object: GObject.Object): boolean;
emit_added(object: GObject.Object): void;
emit_removed(object: GObject.Object): void;
get_length(): number;
get_objects(): GObject.Object[];
vfunc_added(object: GObject.Object): void;
vfunc_contains(object: GObject.Object): boolean;
vfunc_get_length(): number;
vfunc_get_objects(): GObject.Object[];
vfunc_removed(object: GObject.Object): void;
}
export const Collection: CollectionNamespace;
export interface ComparableNamespace {
$gtype: GObject.GType<Comparable>;
prototype: ComparablePrototype;
}
export type Comparable = ComparablePrototype;
export interface ComparablePrototype extends GObject.Object {
// Members
compare(other?: Comparable | null): number;
vfunc_compare(other?: Comparable | null): number;
}
export const Comparable: ComparableNamespace;
export interface ImportInteractionNamespace {
$gtype: GObject.GType<ImportInteraction>;
prototype: ImportInteractionPrototype;
}
export type ImportInteraction = ImportInteractionPrototype;
export interface ImportInteractionPrototype extends Gio.TlsInteraction {
// Members
supplement(builder: Gck.Builder, cancellable?: Gio.Cancellable | null): Gio.TlsInteractionResult;
supplement_async(builder: Gck.Builder, cancellable?: Gio.Cancellable | null): Promise<Gio.TlsInteractionResult>;
supplement_async(
builder: Gck.Builder,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
supplement_async(
builder: Gck.Builder,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<Gio.TlsInteractionResult> | void;
supplement_finish(result: Gio.AsyncResult): Gio.TlsInteractionResult;
supplement_prep(builder: Gck.Builder): void;
vfunc_supplement(builder: Gck.Builder, cancellable?: Gio.Cancellable | null): Gio.TlsInteractionResult;
vfunc_supplement_async(
builder: Gck.Builder,
cancellable?: Gio.Cancellable | null
): Promise<Gio.TlsInteractionResult>;
vfunc_supplement_async(
builder: Gck.Builder,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
vfunc_supplement_async(
builder: Gck.Builder,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<Gio.TlsInteractionResult> | void;
vfunc_supplement_finish(result: Gio.AsyncResult): Gio.TlsInteractionResult;
vfunc_supplement_prep(builder: Gck.Builder): void;
}
export const ImportInteraction: ImportInteractionNamespace;
export interface ImporterNamespace {
$gtype: GObject.GType<Importer>;
prototype: ImporterPrototype;
create_for_parsed(parsed: Parsed): Importer[];
queue_and_filter_for_parsed(importers: Importer[], parsed: Parsed): Importer[];
register(importer_type: GObject.GType, attrs: Gck.Attributes): void;
register_well_known(): void;
}
export type Importer = ImporterPrototype;
export interface ImporterPrototype extends GObject.Object {
// Properties
icon: Gio.Icon;
interaction: Gio.TlsInteraction;
label: string;
uri: string;
// Members
get_interaction(): Gio.TlsInteraction | null;
["import"](cancellable?: Gio.Cancellable | null): boolean;
import_async(cancellable?: Gio.Cancellable | null): Promise<boolean>;
import_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void;
import_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<boolean> | void;
import_finish(result: Gio.AsyncResult): boolean;
queue_for_parsed(parsed: Parsed): boolean;
set_interaction(interaction: Gio.TlsInteraction): void;
vfunc_import_async(cancellable?: Gio.Cancellable | null): Promise<boolean>;
vfunc_import_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void;
vfunc_import_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<boolean> | void;
vfunc_import_finish(result: Gio.AsyncResult): boolean;
vfunc_import_sync(cancellable?: Gio.Cancellable | null): boolean;
vfunc_queue_for_parsed(parsed: Parsed): boolean;
}
export const Importer: ImporterNamespace;
export interface PromptNamespace {
$gtype: GObject.GType<Prompt>;
prototype: PromptPrototype;
}
export type Prompt = PromptPrototype;
export interface PromptPrototype extends GObject.Object {
// Properties
caller_window: string;
callerWindow: string;
cancel_label: string;
cancelLabel: string;
choice_chosen: boolean;
choiceChosen: boolean;
choice_label: string;
choiceLabel: string;
continue_label: string;
continueLabel: string;
description: string;
message: string;
password_new: boolean;
passwordNew: boolean;
password_strength: number;
passwordStrength: number;
title: string;
warning: string;
// Members
close(): void;
confirm(cancellable?: Gio.Cancellable | null): PromptReply;
confirm_async(cancellable?: Gio.Cancellable | null): Promise<PromptReply>;
confirm_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void;
confirm_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<PromptReply> | void;
confirm_finish(result: Gio.AsyncResult): PromptReply;
confirm_run(cancellable?: Gio.Cancellable | null): PromptReply;
get_caller_window(): string;
get_cancel_label(): string;
get_choice_chosen(): boolean;
get_choice_label(): string;
get_continue_label(): string;
get_description(): string;
get_message(): string;
get_password_new(): boolean;
get_password_strength(): number;
get_title(): string;
get_warning(): string;
password(cancellable?: Gio.Cancellable | null): string;
password_async(cancellable?: Gio.Cancellable | null): Promise<string>;
password_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void;
password_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<string> | void;
password_finish(result: Gio.AsyncResult): string;
password_run(cancellable?: Gio.Cancellable | null): string;
reset(): void;
set_caller_window(window_id: string): void;
set_cancel_label(cancel_label: string): void;
set_choice_chosen(chosen: boolean): void;
set_choice_label(choice_label?: string | null): void;
set_continue_label(continue_label: string): void;
set_description(description: string): void;
set_message(message: string): void;
set_password_new(new_password: boolean): void;
set_title(title: string): void;
set_warning(warning?: string | null): void;
vfunc_prompt_close(): void;
vfunc_prompt_confirm_async(cancellable?: Gio.Cancellable | null): Promise<PromptReply>;
vfunc_prompt_confirm_async(
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
vfunc_prompt_confirm_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<PromptReply> | void;
vfunc_prompt_confirm_finish(result: Gio.AsyncResult): PromptReply;
vfunc_prompt_password_async(cancellable?: Gio.Cancellable | null): Promise<string>;
vfunc_prompt_password_async(
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
vfunc_prompt_password_async(
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<string> | void;
vfunc_prompt_password_finish(result: Gio.AsyncResult): string;
}
export const Prompt: PromptNamespace; | the_stack |
import { Range } from "vscode-languageserver-types";
import {
CodemarkPlus,
FetchAssignableUsersRequestType,
GetRangeScmInfoRequestType,
GetRangeScmInfoResponse,
CreateDocumentMarkerPermalinkRequestType,
ThirdPartyProviderBoard,
ThirdPartyProviderConfig,
CrossPostIssueValues,
GetReviewRequestType,
BlameAuthor,
GetShaDiffsRangesRequestType,
GetShaDiffsRangesResponse
} from "@codestream/protocols/agent";
import {
CodemarkType,
CSChannelStream,
CSCodemark,
CSStream,
CSUser,
StreamType,
CSMe
} from "@codestream/protocols/api";
import cx from "classnames";
import * as paths from "path-browserify";
import React from "react";
import { connect } from "react-redux";
import Select from "react-select";
import {
getStreamForId,
getStreamForTeam,
getChannelStreamsForTeam
} from "../store/streams/reducer";
import {
mapFilter,
arrayToRange,
forceAsLine,
isRangeEmpty,
replaceHtml,
keyFilter,
safe
} from "../utils";
import { HostApi } from "../webview-api";
import Button from "./Button";
import CrossPostIssueControls from "./CrossPostIssueControls";
import Tag from "./Tag";
import Icon from "./Icon";
import Menu from "./Menu";
import Tooltip from "./Tooltip";
import {
EditorSelectRangeRequestType,
EditorSelection,
EditorHighlightRangeRequestType,
WebviewPanels
} from "@codestream/protocols/webview";
import { getCurrentSelection } from "../store/editorContext/reducer";
import Headshot from "./Headshot";
import {
getTeamMembers,
getTeamTagsArray,
getTeamMates,
getActiveMemberIds
} from "../store/users/reducer";
import MessageInput, { AttachmentField } from "./MessageInput";
import { getCurrentTeamProvider } from "../store/teams/reducer";
import { getCodemark } from "../store/codemarks/reducer";
import { CodemarksState } from "../store/codemarks/types";
import { setCurrentStream } from "../store/context/actions";
import ContainerAtEditorLine from "./SpatialView/ContainerAtEditorLine";
import ContainerAtEditorSelection from "./SpatialView/ContainerAtEditorSelection";
import { prettyPrintOne } from "code-prettify";
import { escapeHtml } from "../utils";
import { CodeStreamState } from "../store";
import { LabeledSwitch } from "../src/components/controls/LabeledSwitch";
import { CSText } from "../src/components/CSText";
import { NewCodemarkAttributes, parseCodeStreamDiffUri } from "../store/codemarks/actions";
import { SharingControls, SharingAttributes } from "./SharingControls";
import { SmartFormattedList } from "./SmartFormattedList";
import { Modal } from "./Modal";
import { Checkbox } from "../src/components/Checkbox";
import { isFeatureEnabled } from "../store/apiVersioning/reducer";
import { FormattedMessage } from "react-intl";
import { Link } from "./Link";
import { confirmPopup } from "./Confirm";
import { openPanel, openModal, setUserPreference, markItemRead } from "./actions";
import { fetchCodeError, upgradePendingCodeError } from "../store/codeErrors/actions";
import CancelButton from "./CancelButton";
import { VideoLink } from "./Flow";
import { PanelHeader } from "../src/components/PanelHeader";
import { ReposState } from "../store/repos/types";
import { getDocumentFromMarker } from "./api-functions";
import { getPRLabel, LabelHash } from "../store/providers/reducer";
import { contextType } from "react-gravatar";
import { CodeErrorsState } from "../store/codeErrors/types";
export interface ICrossPostIssueContext {
setSelectedAssignees(any: any): void;
setValues(values: any): void;
selectedAssignees: any[];
assigneesInputTarget?: HTMLElement;
codeBlock?: GetRangeScmInfoResponse;
}
export const CrossPostIssueContext = React.createContext<ICrossPostIssueContext>({
selectedAssignees: [],
setSelectedAssignees: () => {},
setValues: () => {}
});
interface Props extends ConnectedProps {
streamId: string;
collapseForm?: Function;
onSubmit: (attributes: NewCodemarkAttributes, event?: React.SyntheticEvent) => any;
onClickClose(e?: Event): any;
openCodemarkForm?(type: string): any;
slackInfo?: {};
codeBlock?: GetRangeScmInfoResponse;
commentType?: string;
collapsed: boolean;
isEditing?: boolean;
editingCodemark?: CodemarkPlus;
placeholder?: string;
onDidChangeSelection?(location: EditorSelection): void;
positionAtLocation?: boolean;
multiLocation?: boolean;
setMultiLocation?: Function;
dontAutoSelectLine?: boolean;
error?: string;
openPanel: Function;
openModal: Function;
setUserPreference: Function;
markItemRead(
...args: Parameters<typeof markItemRead>
): ReturnType<ReturnType<typeof markItemRead>>;
upgradePendingCodeError(
codeErrorId: string,
source: "Comment" | "Status Change" | "Assignee Change"
);
}
interface ConnectedProps {
teamMates: CSUser[];
teamMembers: CSUser[];
activeMemberIds: string[];
channelStreams: CSChannelStream[];
channel: CSStream;
issueProvider?: ThirdPartyProviderConfig;
providerInfo: {
[service: string]: {};
};
currentUser: CSUser;
skipPostCreationModal?: boolean;
skipEmailingAuthors?: boolean;
selectedStreams: {};
showChannels: string;
textEditorUri?: string;
textEditorGitSha?: string;
textEditorSelection?: EditorSelection;
teamProvider: "codestream" | "slack" | "msteams" | string;
teamTagsArray: any;
codemarkState: CodemarksState;
multipleMarkersEnabled: boolean;
shouldShare: boolean;
currentTeamId: string;
currentReviewId?: string;
currentCodeErrorId?: string;
isCurrentUserAdmin?: boolean;
blameMap?: { [email: string]: string };
activePanel?: WebviewPanels;
inviteUsersOnTheFly: boolean;
currentPullRequestId?: string;
textEditorUriContext: any;
textEditorUriHasPullRequestContext: boolean;
repos: ReposState;
prLabel: LabelHash;
codeErrors: CodeErrorsState;
}
interface State {
text: string;
touchedText: boolean;
formatCode: boolean;
type: string;
codeBlocks: GetRangeScmInfoResponse[];
scmError: string;
assignees: { value: any; label: string }[] | { value: any; label: string };
assigneesRequired: boolean;
assigneesDisabled: boolean;
singleAssignee: boolean;
isPermalinkPublic: boolean;
privacyMembers: { value: string; label: string }[];
notify: boolean;
isLoading: boolean;
isReviewLoading: boolean;
crossPostMessage: boolean;
crossPostIssueValues: Partial<CrossPostIssueValues>;
assignableUsers: { value: any; label: string }[];
channelMenuOpen: boolean;
channelMenuTarget: any;
labelMenuOpen: boolean;
labelMenuTarget: any;
locationMenuOpen: number | "header" | "closed";
locationMenuTarget: any;
sharingDisabled?: boolean;
selectedChannelName?: string;
selectedChannelId?: string;
title?: string;
codeBlockInvalid?: boolean;
titleInvalid?: boolean;
textInvalid?: boolean;
assigneesInvalid?: boolean;
sharingAttributesInvalid?: boolean;
showAllChannels?: boolean;
linkURI?: string;
copied: boolean;
selectedTags?: any;
deleteMarkerLocations: {
[index: number]: boolean;
};
relatedCodemarkIds?: any;
attachments: AttachmentField[];
addingLocation?: boolean;
editingLocation: number;
liveLocation: number;
isChangeRequest: boolean;
unregisteredAuthors: BlameAuthor[];
emailAuthors: { [email: string]: boolean };
currentPullRequestId?: string;
isProviderReview?: boolean;
isInsidePrChangeSet: boolean;
changedPrLines: GetShaDiffsRangesResponse[];
isPreviewing?: boolean;
isDragging: number;
currentCodeErrorId?: string;
}
function merge(defaults: Partial<State>, codemark: CSCodemark): State {
return Object.entries(defaults).reduce((object, entry) => {
const [key, value] = entry;
object[key] = codemark[key] !== undefined ? codemark[key] : value;
return object;
}, Object.create(null));
}
class CodemarkForm extends React.Component<Props, State> {
static defaultProps = {
commentType: "comment",
isEditing: false
};
_titleInput: HTMLElement | null = null;
insertTextAtCursor?: Function;
focusOnMessageInput?: Function;
permalinkRef = React.createRef<HTMLTextAreaElement>();
permalinkWithCodeRef = React.createRef<HTMLTextAreaElement>();
private _assigneesContainerRef = React.createRef<HTMLDivElement>();
private _sharingAttributes?: SharingAttributes;
private renderedCodeBlocks = {};
constructor(props: Props) {
super(props);
const defaultType = props.commentType;
const defaultState: Partial<State> = {
crossPostIssueValues: {},
title: "",
text: "",
touchedText: false,
formatCode: false,
type: defaultType,
codeBlocks: props.codeBlock ? [props.codeBlock] : [],
assignees: [],
assigneesDisabled: false,
assigneesRequired: false,
singleAssignee: false,
selectedChannelName: (props.channel as any).name,
selectedChannelId: props.channel.id,
assignableUsers: this.getAssignableCSUsers(),
isPermalinkPublic: false,
privacyMembers: [],
selectedTags: {},
relatedCodemarkIds: {},
locationMenuOpen: "closed",
editingLocation: -1,
addingLocation: false,
liveLocation: -1,
isChangeRequest: false,
scmError: "",
unregisteredAuthors: [],
emailAuthors: {},
isReviewLoading: false,
isInsidePrChangeSet: false,
changedPrLines: [],
deleteMarkerLocations: {},
attachments: [],
isDragging: 0
};
const state = props.editingCodemark
? merge(defaultState, props.editingCodemark)
: ({
isLoading: false,
notify: false,
...defaultState
} as State);
let assignees: any;
if (props.isEditing) {
const externalAssignees = this.props.editingCodemark!.externalAssignees || [];
assignees = externalAssignees
.map(a => ({
value: a.displayName,
label: a.displayName
}))
.concat(
mapFilter(this.props.editingCodemark!.assignees || [], a =>
state.assignableUsers.find((au: any) => au.value === a)
)
);
} else if (state.assignees === undefined) {
assignees = undefined;
} else if (Array.isArray(state.assignees)) {
assignees = state.assignees.map(a => state.assignableUsers.find((au: any) => au.value === a));
} else {
assignees = state.assignableUsers.find((au: any) => au.value === state.assignees);
}
this.state = {
...state,
assignees
};
if (props.isEditing && props.editingCodemark) {
const selectedTags = {};
(props.editingCodemark.tags || []).forEach(tag => {
selectedTags[tag] = true;
});
const relatedCodemarkIds = {};
(props.editingCodemark.relatedCodemarkIds || []).forEach(id => {
relatedCodemarkIds[id] = getCodemark(props.codemarkState, id);
});
this.state = {
...this.state,
selectedTags,
relatedCodemarkIds
};
}
if (props.isEditing && props.editingCodemark) {
this.state = {
...this.state,
text: escapeHtml(this.state.text)
};
}
}
static getDerivedStateFromProps(props: Props, state: State) {
// revisit this if the ability to change the type is added back to the form
// TODO: this should call ComposeBox.repositionIfNecessary()
if (props.commentType !== state.type) {
return { type: props.commentType };
}
return null;
}
async componentDidMount() {
const {
multiLocation,
dontAutoSelectLine,
textEditorUriHasPullRequestContext,
textEditorUriContext,
isEditing
} = this.props;
const { codeBlocks } = this.state;
if (textEditorUriHasPullRequestContext) {
const changedPrLines = await HostApi.instance.send(GetShaDiffsRangesRequestType, {
repoId: textEditorUriContext.repoId,
filePath: textEditorUriContext.path,
baseSha: textEditorUriContext.leftSha,
headSha: textEditorUriContext.rightSha
});
this.setState({ changedPrLines });
}
if (codeBlocks.length === 1) {
if (isRangeEmpty(codeBlocks[0].range)) {
this.selectRangeInEditor(codeBlocks[0].uri, forceAsLine(codeBlocks[0].range));
}
this.handleScmChange();
} else if (!isEditing) {
const { textEditorSelection, textEditorUri, textEditorGitSha } = this.props;
if (textEditorSelection && textEditorUri) {
// In case there isn't already a range selection by user, change the selection to be the line the cursor is on
const isEmpty = isRangeEmpty(textEditorSelection);
if (isEmpty && dontAutoSelectLine) {
this.focus();
this.setState({ liveLocation: 0 });
} else {
const range = isEmpty ? forceAsLine(textEditorSelection) : textEditorSelection;
if (isEmpty) this.selectRangeInEditor(textEditorUri, range);
this.getScmInfoForSelection(textEditorUri, textEditorGitSha, range, () => {
// if (multiLocation) this.setState({ addingLocation: true, liveLocation: 1 });
this.focus();
});
}
}
}
// if (!multiLocation) this.focus();
}
rangesAreEqual(range1?: Range, range2?: Range) {
if ((range1 && !range2) || (!range1 && range2)) return false;
if (range1 && range2) {
if (
range1.start.line !== range2.start.line ||
range1.start.character !== range2.start.character ||
range1.end.line !== range2.end.line ||
range1.end.character !== range2.end.character
)
return false;
}
return true;
}
isNonzeroSelection(range?: Range) {
if (!range) return false;
if (range.start.line === range.end.line && range.start.character === range.end.character)
return false;
return true;
}
componentDidUpdate(prevProps: Props) {
const { isEditing, textEditorSelection, textEditorUri, textEditorGitSha } = this.props;
const commentType = this.getCommentType();
// this if statement, if true, will update the selection that the
// compose form is pointing to
if (
// make sure there an actual selection, not just a cursor
this.isNonzeroSelection(textEditorSelection) &&
// if the range didn't change, don't do anything
!this.rangesAreEqual(prevProps.textEditorSelection, textEditorSelection) &&
// make sure the range didn't change because we switched editors(files)
prevProps.textEditorUri == textEditorUri &&
// if we're editing, do nothing
// !isEditing &&
// if we are doing a permalink, do nothing
!this.state.linkURI &&
commentType !== "link" &&
// only update if we have a live location
this.state.liveLocation >= 0
) {
this.getScmInfoForSelection(
textEditorUri!,
textEditorGitSha,
forceAsLine(textEditorSelection!)
);
this.props.onDidChangeSelection && this.props.onDidChangeSelection(textEditorSelection!);
// this.setState({ addingLocation: false });
}
if (prevProps.commentType !== this.props.commentType) {
this.setState({});
}
// if you switch files while the compose form is open, make
// it clear that you are not commenting in the new file by
// switching to multi-location mode, which shows the codeblock
// and exactly what you're commenting on
if (prevProps.textEditorUri !== textEditorUri) {
// if you're creating a permalink, just cancel it and move on
// otherwise, go to multi-location mode
if (commentType === "link") this.cancelCompose();
else this.addLocation();
}
const prevProviderHost = prevProps.issueProvider ? prevProps.issueProvider.host : undefined;
const providerHost = this.props.issueProvider ? this.props.issueProvider.host : undefined;
if (prevProviderHost !== providerHost) {
this.setState({ assignees: [], crossPostIssueValues: {} });
}
}
private selectRangeInEditor(uri: string, range: Range) {
HostApi.instance.send(EditorSelectRangeRequestType, {
uri: uri,
selection: { ...range, cursor: range.end },
preserveFocus: true
});
}
private async getScmInfoForSelection(
uri: string,
gitSha?: string,
range: Range,
callback?: Function
) {
const scmInfo = await HostApi.instance.send(GetRangeScmInfoRequestType, {
uri: uri,
gitSha: gitSha,
range: range,
dirty: true // should this be determined here? using true to be safe
});
let newCodeBlocks = [...this.state.codeBlocks];
if (this.state.liveLocation >= 0) newCodeBlocks[this.state.liveLocation] = scmInfo;
else newCodeBlocks.push(scmInfo);
if (scmInfo.error) {
this.setState({ scmError: scmInfo.error });
} else {
this.setState({ codeBlocks: newCodeBlocks, addingLocation: false }, () => {
this.handleScmChange();
this.handlePrIntersection();
if (callback) callback();
});
}
}
getAssignableCSUsers() {
return mapFilter(this.props.teamMembers, user => {
if (!user.isRegistered) return;
return {
value: user.id,
label: user.username
};
});
}
async loadAssignableUsers(providerId: string, board: ThirdPartyProviderBoard) {
if (board.assigneesDisabled) return this.setState({ assigneesDisabled: true });
if (board.assigneesRequired) {
this.setState(state => (state.assigneesRequired ? null : { assigneesRequired: true }));
}
if (board.singleAssignee) {
this.setState(state => (state.singleAssignee ? null : { singleAssignee: true }));
}
try {
const { users } = await HostApi.instance.send(FetchAssignableUsersRequestType, {
providerId,
boardId: board.apiIdentifier || board.id
});
this.setState({
assignableUsers: users.map(u => ({
value: u,
label: u.displayName
}))
});
} catch (error) {
this.setState({ assignableUsers: [] });
}
}
// this doesn't appear to be used anywhere -Pez
handleSelectionChange = () => {
const { textEditorSelection, textEditorUri, textEditorGitSha } = this.props;
if (textEditorSelection) {
this.getScmInfoForSelection(
textEditorUri!,
textEditorGitSha,
forceAsLine(textEditorSelection)
);
}
};
handlePrIntersection = () => {
const { changedPrLines, codeBlocks } = this.state;
const { textEditorUriHasPullRequestContext, textEditorUriContext } = this.props;
if (textEditorUriHasPullRequestContext) {
const isInsidePrChangeSet = changedPrLines.some(changedPrLine => {
return codeBlocks.some(codeBlock => {
const codeBlockStart = codeBlock.range.start.line + 1;
const codeBlockEnd = codeBlock.range.end.line + 1;
if (!codeBlock.scm) {
return false;
}
let prRange;
switch (codeBlock.scm.branch) {
case textEditorUriContext.headBranch:
prRange = changedPrLine.headLinesChanged;
break;
case textEditorUriContext.baseBranch:
prRange = changedPrLine.baseLinesChanged;
break;
default:
return false;
}
if (prRange.start > prRange.end) {
return false;
}
return (
(prRange.start <= codeBlockStart && codeBlockStart <= prRange.end) ||
(prRange.start <= codeBlockEnd && codeBlockEnd <= prRange.end) ||
(codeBlockStart <= prRange.start && prRange.end <= codeBlockEnd)
);
});
});
this.setState({ isInsidePrChangeSet });
}
};
handleScmChange = () => {
const { codeBlocks } = this.state;
const { blameMap = {}, inviteUsersOnTheFly, activeMemberIds } = this.props;
this.setState({ codeBlockInvalid: false });
if (!codeBlocks.length) return;
const codeBlock =
this.state.liveLocation >= 0 ? codeBlocks[this.state.liveLocation] : codeBlocks[0];
if (!codeBlock) return;
let unregisteredAuthors: BlameAuthor[] = [];
let emailAuthors: { [email: string]: boolean } = {};
let mentionAuthors: BlameAuthor[] = [];
if (codeBlock.scm && codeBlock.scm.authors) {
codeBlock.scm.authors.forEach(author => {
// don't mention yourself
if (author.id && author.id === this.props.currentUser.id) return;
// see if this email address' code has been assigned to someone else
// @ts-ignore
const mappedId = blameMap[author.email.replace(".", "*")];
const mappedPerson = mappedId && this.props.teamMembers.find(t => t.id === mappedId);
// found a mapped person, so mention them
if (mappedPerson) {
mentionAuthors.push({
email: mappedPerson.email,
id: mappedPerson.id,
username: mappedPerson.username
});
} else if (author.id) {
// if it's a registered teammate who has not been explicitly removed from the team, mention them
if (activeMemberIds.includes(author.id)) mentionAuthors.push(author);
} else if (inviteUsersOnTheFly) {
// else offer to send the person an email
unregisteredAuthors.push(author);
// @ts-ignore
emailAuthors[author.email] = !this.props.skipEmailingAuthors;
}
});
}
this.setState({ unregisteredAuthors, emailAuthors });
if (mentionAuthors.length > 0) {
// TODO handle users with no username
const usernames: string[] = mentionAuthors.map(u => `@${u.username}`);
// if there's text in the compose area, return without
// adding the suggestion
if (this.state.text.length > 0) return;
// the reason for this unicode space is that chrome will
// not render a space at the end of a contenteditable div
// unless it is a , which is difficult to insert
// so we insert this unicode character instead
this.focusOnMessageInput &&
this.focusOnMessageInput(() => {
this.insertTextAtCursor && this.insertTextAtCursor(usernames.join(", ") + ":\u00A0");
});
}
};
// TODO: remove this
tabIndex = () => {
return 0;
};
// TODO: work on this from initial mount
focus = (forceMainInput = false) => {
// if (forceMainInput && this._contentEditable) return this._contentEditable.htmlEl.focus();
switch (this.state.type) {
case "question":
case "issue":
case "bookmark":
this._titleInput && this._titleInput.focus();
break;
case "snippet":
case "comment":
default:
this.focusOnMessageInput && this.focusOnMessageInput();
}
};
// onSelectCodemarkType = (type?: string) => {
// this.setState({ menuOpen: false });
// if (type) this.setCommentType(type);
// }
getCommentType = () => {
const { editingCodemark } = this.props;
return editingCodemark ? editingCodemark.type : this.props.commentType || "comment";
};
setCommentType = (type: string) => {
if (this.props.editingCodemark) return;
this.setState({
type,
codeBlockInvalid: false,
titleInvalid: false,
textInvalid: false
});
// setTimeout(() => {
// // this.focus();
// }, 20);
};
togglePermalinkPrivacy = (isPermalinkPublic: boolean) => {
this.setState({
isPermalinkPublic
});
};
// toggleCodemarkPrivacy = (isCodemarkPublic: boolean) => {
// this.setState(state => {
// const sharingDisabled = !isCodemarkPublic;
// const shouldShare = sharingDisabled ? false : state.shouldShare;
// return { sharingDisabled, shouldShare };
// });
// };
toggleNotify = () => {
this.setState({ notify: !this.state.notify });
};
toggleCrossPostMessage = () => {
this.setState(state => ({ crossPostMessage: !state.crossPostMessage }));
};
handlePullRequestKeyboardSubmit = async (e?: React.SyntheticEvent) => {
if (this.props.error != null && this.props.error !== "") {
return;
}
const hasExistingPullRequestReview = !!(
this.state.codeBlocks && !!this.state.codeBlocks[0]?.context?.pullRequest?.pullRequestReviewId
);
if (!hasExistingPullRequestReview || !this.state.isInsidePrChangeSet) {
this.handleClickSubmit(e);
} else if (this.props.textEditorUriHasPullRequestContext && this.state.isInsidePrChangeSet) {
this.setState({ isProviderReview: true }, () => {
this.handleClickSubmit(e);
});
}
};
handleClickSubmit = async (event?: React.SyntheticEvent) => {
event && event.preventDefault();
if (this.state.isLoading || this.state.isReviewLoading) return;
if (this.isFormInvalid()) return;
const {
codeBlocks,
deleteMarkerLocations,
isPermalinkPublic,
type,
title,
text,
selectedChannelId,
selectedTags,
relatedCodemarkIds,
attachments
} = this.state;
// FIXME
const codeBlock = codeBlocks[0];
if (type === "link") {
let request;
const privacy = isPermalinkPublic ? "public" : "private";
if (codeBlock) {
request = {
uri: codeBlock.uri,
range: codeBlock.range,
privacy: privacy
};
} else {
request = {
uri: this.props.textEditorUri,
range: this.props.textEditorSelection,
privacy: privacy
};
}
this.setState({ isLoading: true });
const response = await HostApi.instance.send(
CreateDocumentMarkerPermalinkRequestType,
request
);
this.setState({ linkURI: response.linkUrl, isLoading: false });
return;
}
const crossPostIssueValues = { ...this.state.crossPostIssueValues };
const crossPostIssueEnabled =
type === CodemarkType.Issue && this.props.issueProvider != undefined;
let csAssignees: string[] = [];
if (crossPostIssueEnabled) {
const assignees = Array.isArray(this.state.assignees)
? this.state.assignees
: [this.state.assignees];
csAssignees = mapFilter(assignees, a => {
const user = a.value;
const codestreamUser = this.props.teamMembers.find(
t => Boolean(user.email) && t.email === user.email
);
if (codestreamUser) return codestreamUser.id;
return undefined;
});
crossPostIssueValues.assignees = assignees.map(a => a.value);
crossPostIssueValues.issueProvider = this.props.issueProvider;
} else
csAssignees = this.props.isEditing
? this.props.editingCodemark!.assignees
: (this.state.assignees as any[]).map(a => a.value);
if (this.props.currentPullRequestId && this.state.isProviderReview) {
this.setState({ isReviewLoading: true });
} else {
this.setState({ isLoading: true });
}
if (this.props.currentPullRequestId) {
const { textEditorUriContext } = this.props;
const providerId =
textEditorUriContext &&
textEditorUriContext.context &&
textEditorUriContext.context.pullRequest
? textEditorUriContext.context.pullRequest.providerId
: "";
HostApi.instance.track("PR Comment Added", {
Host: providerId,
"Comment Type": this.state.isProviderReview ? "Review Comment" : "Single Comment"
});
}
let parentPostId: string | undefined = undefined;
// all codemarks created while in a review are attached to that review
if (this.props.currentReviewId) {
try {
const response = await HostApi.instance.send(GetReviewRequestType, {
reviewId: this.props.currentReviewId
});
const { review } = response;
parentPostId = review.postId;
this.props.markItemRead(review.id, review.numReplies + 1);
} catch (error) {
// FIXME what do we do if we don't find the review?
}
}
if (this.props.currentCodeErrorId) {
try {
const codeErrorResponse = await this.props.upgradePendingCodeError(
this.props.currentCodeErrorId,
"Comment"
);
if (codeErrorResponse.wasPending) {
// if this codeError was pending, we know that we just created one, use the codeError
// that was created
parentPostId = codeErrorResponse.codeError.postId;
} else {
fetchCodeError(this.props.currentCodeErrorId);
const codeError = this.props.codeErrors.codeErrors[this.props.currentCodeErrorId];
parentPostId = codeError.postId;
}
//this.props.markItemRead(review.id, review.numReplies + 1);
} catch (error) {
// FIXME what do we do if we don't find the code error?
}
}
try {
const baseAttributes = {
codeBlocks,
deleteMarkerLocations,
text: replaceHtml(text)!,
type: type as CodemarkType,
assignees: csAssignees,
title,
crossPostIssueValues: crossPostIssueEnabled
? (crossPostIssueValues as CrossPostIssueValues)
: undefined,
tags: keyFilter(selectedTags),
relatedCodemarkIds: keyFilter(relatedCodemarkIds),
parentPostId,
isChangeRequest: this.state.isChangeRequest,
addedUsers: keyFilter(this.state.emailAuthors),
isProviderReview: this.state.isProviderReview
};
if (this.props.teamProvider === "codestream") {
const retVal = await this.props.onSubmit({
...baseAttributes,
sharingAttributes: this.props.shouldShare ? this._sharingAttributes : undefined,
accessMemberIds: this.state.privacyMembers.map(m => m.value),
files: attachments
});
// if you're making a markerless codemark it won't appear on spatial view, the form
// will just kind of disappear. similarly, if you prior panel was *not* spatial view
// the form will just disappear. in these cases, we want to show the user where the
// codemark ends up -- the actiivty feed and spatial view
if (
retVal &&
((codeBlocks.length == 0 && this.props.activePanel !== WebviewPanels.Activity) ||
this.props.activePanel !== WebviewPanels.CodemarksForFile)
)
this.showConfirmationForCodemarkLocation(type, codeBlocks.length);
} else {
await this.props.onSubmit({ ...baseAttributes, streamId: selectedChannelId! }, event);
(this.props as any).dispatch(setCurrentStream(selectedChannelId));
}
} catch (error) {
console.error(error);
} finally {
this.setState({ isLoading: false });
this.setState({ isProviderReview: false });
this.setState({ isReviewLoading: false });
}
};
showConfirmationForCodemarkLocation = (type, numCodeblocks: number) => {
// we're going to turn this off since we have a consistent place to see comments
return;
if (this.props.skipPostCreationModal) return;
confirmPopup({
title: `${type === CodemarkType.Issue ? "Issue" : "Comment"} Submitted`,
closeOnClickA: true,
message: (
<div style={{ textAlign: "left" }}>
You can see the {type === CodemarkType.Issue ? "issue" : "comment"} in your{" "}
<a onClick={() => this.props.openPanel(WebviewPanels.Activity)}>activity feed</a>
{numCodeblocks > 0 && (
<>
{" "}
and next to the code on{" "}
<a onClick={() => this.props.openPanel(WebviewPanels.CodemarksForFile)}>
codemarks in current file
</a>
</>
)}
.
<br />
<br />
<div style={{ textAlign: "center", margin: 0, padding: 0 }}>
<div
style={{
textAlign: "left",
fontSize: "12px",
display: "inline-block",
margin: "0 auto",
padding: 0
}}
>
<Checkbox
name="skipPostCreationModal"
onChange={() => {
this.props.setUserPreference(
["skipPostCreationModal"],
!this.props.skipPostCreationModal
);
}}
>
Don't show this again
</Checkbox>
</div>
</div>
</div>
),
centered: true,
buttons: [
{
label: "OK",
action: () => {}
}
]
});
};
isFormInvalid = () => {
const { codeBlocks } = this.state;
const { text, title, assignees, crossPostIssueValues, type } = this.state;
if (this.props.error != null && this.props.error !== "") return true;
if (type === CodemarkType.Link) return false;
// FIXME
const codeBlock = codeBlocks[0];
const validationState: Partial<State> = {
codeBlockInvalid: false,
titleInvalid: false,
textInvalid: false,
assigneesInvalid: false,
sharingAttributesInvalid: false
};
let invalid = false;
if (type === "trap" || type === "bookmark") {
if (!codeBlock) {
validationState.codeBlockInvalid = true;
invalid = true;
}
}
if (type === "question" || type === "issue") {
if (!title || title.length === 0) {
validationState.titleInvalid = true;
invalid = true;
}
if (
crossPostIssueValues.assigneesRequired &&
(!assignees || (Array.isArray(assignees) && assignees.length === 0))
) {
invalid = validationState.assigneesInvalid = true;
}
}
if (type === "comment" || type === "trap") {
if (text.length === 0) {
validationState.textInvalid = true;
invalid = true;
}
}
if (this.props.currentCodeErrorId) {
// do something cool?
} else if (this.props.textEditorUriHasPullRequestContext) {
// do something cool?
} else if (
!this.props.isEditing &&
this.props.shouldShare &&
!this._sharingAttributes &&
!this.props.currentReviewId
) {
invalid = true;
validationState.sharingAttributesInvalid = true;
}
if (invalid) console.log("invalid form: ", validationState);
this.setState(validationState as State);
return invalid;
};
showAlertHelp = event => {
event.stopPropagation();
};
renderTitleHelp = () => {
const { titleInvalid } = this.state;
if (titleInvalid) {
return <small className="error-message">Required</small>;
} else return null;
};
renderTextHelp = () => {
const { textInvalid } = this.state;
if (textInvalid) {
return <small className="error-message">Required</small>;
} else return null;
};
renderSharingHelp = () => {
const { sharingAttributesInvalid } = this.state;
if (sharingAttributesInvalid) {
return <small className="error-message">Select channel, or deselect sharing</small>;
} else return null;
};
switchChannel = (event: React.SyntheticEvent) => {
if (this.props.isEditing) return;
event.stopPropagation();
if (!this.state.channelMenuOpen) {
const target = event.target;
this.setState(state => ({
channelMenuOpen: !state.channelMenuOpen,
channelMenuTarget: target,
crossPostMessage: true
}));
}
};
selectChannel = (stream: CSStream | "show-all") => {
if (stream === "show-all") {
this.setState({ showAllChannels: true });
return;
} else if (stream && stream.id) {
const channelName = (stream.type === StreamType.Direct ? "@" : "#") + (stream as any).name;
this.setState({ selectedChannelName: channelName, selectedChannelId: stream.id });
}
this.setState({ channelMenuOpen: false });
this.focus();
};
switchLocation = (event: React.SyntheticEvent, index: number | "header") => {
if (this.props.isEditing) return;
const target = event.target;
this.setState({
liveLocation: -1,
locationMenuOpen: index,
locationMenuTarget: target
});
};
editLocation = (index: number, event?: React.SyntheticEvent) => {
if (event) event.stopPropagation();
this.setState({ locationMenuOpen: "closed", liveLocation: index, addingLocation: false });
};
deleteLocation = (index: number, event?: React.SyntheticEvent) => {
const { editingCodemark } = this.props;
if (event) event.stopPropagation();
let newCodeBlocks = [...this.state.codeBlocks];
newCodeBlocks.splice(index, 1);
this.setState(
{
locationMenuOpen: "closed",
codeBlocks: newCodeBlocks
},
() => {
this.handlePrIntersection();
}
);
if (editingCodemark) {
this.setState({
deleteMarkerLocations: { ...this.state.deleteMarkerLocations, [index]: true }
});
}
this.addLocation();
this.focus();
};
addLocation = () => {
const { editingCodemark } = this.props;
const markersLength = editingCodemark ? (editingCodemark.markers || []).length : 0;
this.setState(state => ({
locationMenuOpen: "closed",
addingLocation: true,
liveLocation: Math.max(state.codeBlocks.length, markersLength)
}));
if (this.props.setMultiLocation && !this.props.multiLocation) this.props.setMultiLocation(true);
};
cementLocation = (event: React.SyntheticEvent) => {
const { codeBlocks, liveLocation } = this.state;
event.stopPropagation();
try {
const { file: newFile, repoPath: newRepoPath } = codeBlocks[liveLocation].scm!;
const { file, repoPath } = codeBlocks[0].scm!;
let location = "Same File";
if (repoPath !== newRepoPath) location = "Different Repo";
else if (file !== newFile) location = "Different File";
} catch (e) {}
this.setState(state => ({
locationMenuOpen: "closed",
addingLocation: false,
liveLocation: -1
}));
// this.addLocation();
this.focus();
};
jumpToLocation = (index: number, event?: React.SyntheticEvent) => {
if (event) event.stopPropagation();
this.toggleCodeHighlightInTextEditor(true, index);
};
pinLocation = (index: number, event?: React.SyntheticEvent) => {
this.insertTextAtCursor && this.insertTextAtCursor(`[#${index + 1}]`);
};
pinImage = (filename: string, url: string, event?: React.SyntheticEvent) => {
this.insertTextAtCursor &&
this.insertTextAtCursor(`})`);
};
selectLocation = (action: "add" | "edit" | "delete") => {
this.setState({ locationMenuOpen: "closed" });
};
switchLabel = (event: React.SyntheticEvent) => {
event.stopPropagation();
const target = event.target;
this.setState(state => ({
labelMenuOpen: !state.labelMenuOpen,
labelMenuTarget: target
}));
};
// selectLabel = (color: string) => {
// this.setState({ color: color, labelMenuOpen: false });
// };
// handleClickConnectSlack = async event => {
// event.preventDefault();
// this.setState({ isLoading: true });
// await HostApi.instance.send(GoToSlackSignin); // TODO: use the provider api
// this.setState({ isLoading: false });
// }
renderTags = () => {
const { selectedTags } = this.state;
const keys = Object.keys(selectedTags);
if (keys.length === 0) return null;
return (
<div className="related">
<div className="related-label">Tags</div>
<div style={{ marginBottom: "-5px" }}>
{this.props.teamTagsArray.map(tag => {
return selectedTags[tag.id] ? <Tag tag={tag} /> : null;
})}
<div style={{ clear: "both" }} />
</div>
</div>
);
};
/*
Sharing model v1 will only be public codemarks
see https://trello.com/c/M3KV7p4g/2728-make-all-codemarks-in-sharing-model-team-accessible
*/
/*
renderPrivacyControls = () => {
if (
!this.props.isEditing &&
this.props.teamProvider === "codestream" &&
this.props.commentType !== CodemarkType.Link
) {
return (
<>
<Spacer />
<div style={{ display: "flex", alignItems: "center", minHeight: "40px" }}>
<div style={{ display: "inline-flex", width: "100%", alignItems: "center" }}>
<span style={{ minWidth: "max-content" }}>
<CSText muted as="div">
Who can see this?
</CSText>
</span>
<span style={{ marginLeft: "10px", width: "100%" }}>
<Select
id="input-assignees"
classNamePrefix="react-select"
isMulti
defaultValue={this.state.privacyMembers}
options={this.props.teamMates.map(u => ({
label: u.username,
value: u.id
}))}
closeMenuOnSelect={false}
isClearable
placeholder="Entire Team"
onChange={(value: any, meta: any) => {
this.setState({
privacyMembers: value,
sharingDisabled: meta.action === "select-option"
});
}}
/>
</span>
</div>
</div>
</>
);
}
return null;
};
*/
renderRequireChange = () => {
return (
<div style={{ float: "left", paddingTop: "10px" }}>
<Checkbox
name="change-request"
checked={this.state.isChangeRequest}
onChange={value => this.setState({ isChangeRequest: value })}
>
Change Request (require for approval)
</Checkbox>
</div>
);
};
renderSharingControls = () => {
if (this.state.isPreviewing) return null;
if (this.props.isEditing) return null;
if (this.props.currentReviewId) return null;
if (this.props.currentCodeErrorId) return null;
// don't show the sharing controls for these types of diffs
if (this.props.textEditorUri && this.props.textEditorUri.match("codestream-diff://-[0-9]+-"))
return null;
const { codeBlocks } = this.state;
// we only look at the first code range here because we're using it to default
// the channel based on the selected repo -- so we look at the first one
const repoId = codeBlocks[0] && codeBlocks[0].scm && codeBlocks[0].scm.repoId;
return (
<div className="checkbox-row" style={{ float: "left" }}>
{this.renderSharingHelp()}
{this.state.sharingDisabled ? (
<CSText muted>
<SmartFormattedList value={this.state.privacyMembers.map(m => m.label)} /> will be
notified via email
</CSText>
) : (
<SharingControls
showToggle
onChangeValues={values => {
this._sharingAttributes = values;
}}
repoId={repoId}
/>
)}
</div>
);
};
renderRelatedCodemarks = () => {
const { relatedCodemarkIds } = this.state;
const keys = keyFilter(relatedCodemarkIds);
if (keys.length === 0) return null;
return (
<div className="related" key="related-codemarks">
<div className="related-label">Related</div>
<div className="related-codemarks" key="related-codemarks" style={{ margin: "0 0 0 0" }}>
{keys.map(key => {
const codemark = relatedCodemarkIds[key];
if (!codemark) return null;
const title = codemark.title || codemark.text;
const icon = (
<Icon
name={codemark.type || "comment"}
className={`${codemark.color}-color type-icon`}
/>
);
const file = codemark.markers && codemark.markers[0] && codemark.markers[0].file;
return (
<div key={key} className="related-codemark">
{icon} {title} <span className="codemark-file">{file}</span>
<span style={{ marginLeft: 5 }}>
<Icon name="x" onClick={() => this.handleToggleCodemark(codemark)} />
</span>
</div>
);
})}
<div style={{ clear: "both" }} />
</div>
</div>
);
};
handleKeyPress = (event: React.KeyboardEvent) => {
if (event.key == "Enter") return this.switchChannel(event);
};
handleChange = (text, formatCode) => {
// track newPostText as the user types
this.setState({ text, formatCode });
};
handleChangeTag = newTag => {
const newTagCopy = { ...newTag };
if (newTag.id) {
// TAGS.forEach((tag, index) => {
// if (tag.id === newTag.id) TAGS[index] = newTagCopy;
// });
} else {
// newTagCopy.id = TAGS.length + 1;
// TAGS = TAGS.concat(newTagCopy);
}
};
handleToggleTag = tagId => {
if (!tagId) return;
let selectedTags = this.state.selectedTags;
selectedTags[tagId] = !selectedTags[tagId];
this.setState({ selectedTags });
};
handleToggleCodemark = codemark => {
if (!codemark || !codemark.id) return;
let relatedCodemarkIds = this.state.relatedCodemarkIds;
if (relatedCodemarkIds[codemark.id]) delete relatedCodemarkIds[codemark.id];
else {
relatedCodemarkIds[codemark.id] = codemark;
HostApi.instance.track("Related Codemark Added", {
"Codemark ID": this.props.editingCodemark ? this.props.editingCodemark.id : undefined,
"Sibling Status": this.props.isEditing ? "Existing Codemark" : "New Codemark"
});
}
this.setState({ relatedCodemarkIds });
};
handleChangeRelated = codemarkIds => {
this.setState({ relatedCodemarkIds: codemarkIds });
};
// renderCodeblock(marker) {
// if (marker === undefined) return;
// const path = marker.file || "";
// let extension = paths.extname(path).toLowerCase();
// if (extension.startsWith(".")) {
// extension = extension.substring(1);
// }
// let startLine = 1;
// // `range` is not a property of CSMarker
// /* if (marker.range) {
// startLine = marker.range.start.line;
// } else if (marker.location) {
// startLine = marker.location[0];
// } else */ if (
// marker.locationWhenCreated
// ) {
// startLine = marker.locationWhenCreated[0];
// }
// const codeHTML = prettyPrintOne(escapeHtml(marker.code), extension, startLine);
// return [
// <div className="related" style={{ padding: "0 10px", marginBottom: 0, position: "relative" }}>
// <div className="file-info">
// <span className="monospace" style={{ paddingRight: "20px" }}>
// <Icon name="file"></Icon> {marker.file}
// </span>{" "}
// {marker.branchWhenCreated && (
// <>
// <span className="monospace" style={{ paddingRight: "20px" }}>
// <Icon name="git-branch"></Icon> {marker.branchWhenCreated}
// </span>{" "}
// </>
// )}
// <span className="monospace">
// <Icon name="git-commit"></Icon> {marker.commitHashWhenCreated.substring(0, 7)}
// </span>
// </div>
// <pre
// className="code prettyprint"
// data-scrollable="true"
// dangerouslySetInnerHTML={{ __html: codeHTML }}
// />
// </div>
// ];
// }
getTitleLabel() {
const commentType = this.getCommentType();
return commentType === "issue"
? "issue in "
: commentType === "question"
? "question in "
: commentType === "bookmark"
? "bookmark in "
: commentType === "link"
? "permalink for "
: commentType === "comment"
? "comment in "
: "";
}
getCodeBlockHint() {
const { editingCodemark } = this.props;
const { codeBlocks, liveLocation } = this.state;
if (!codeBlocks.length) return this.renderAddLocation();
if (this.props.multiLocation) {
const numLocations = codeBlocks.length; // + (this.state.addingLocation ? 1 : 0);
return (
<>
<span className="subhead">{this.getTitleLabel()} </span>
<span className="channel-label" style={{ display: "inline-block" }}>
<div className="location">
{numLocations} location{numLocations > 1 ? "s" : ""}
</div>
</span>
{this.state.addingLocation || liveLocation >= 0 || this.renderAddLocation()}
</>
);
} else {
const codeBlock = codeBlocks[0];
if (!codeBlock) return null;
if (liveLocation == 0 && !codeBlock.range)
return <span className="add-range">Select a range to add a code location</span>;
if (!codeBlock.range) return null;
const scm = codeBlock.scm;
let file = scm && scm.file ? paths.basename(scm.file) : "";
let range: any = codeBlock.range;
if (editingCodemark) {
if (editingCodemark.markers && editingCodemark.markers.length > 0) {
const marker = editingCodemark.markers[0];
if (marker.locationWhenCreated) {
// TODO: location is likely invalid
range = arrayToRange(marker.locationWhenCreated as any);
} else {
range = undefined;
}
file = marker.file || "";
} else {
return this.renderAddLocation();
}
}
let lines: string;
if (range === undefined) lines = "";
else if (range.start.line === range.end.line) {
lines = `(Line ${range.start.line + 1})`;
} else {
lines = `(Lines ${range.start.line + 1}-${range.end.line + 1})`;
}
return (
<>
{this.renderAddLocation()}
<span className="subhead">{this.getTitleLabel()} </span>
<span className="channel-label" style={{ display: "inline-block" }}>
<div
className={cx("location", { live: liveLocation == 0 })}
onClick={e => this.switchLocation(e, "header")}
>
{file} {lines}
</div>
</span>
</>
);
}
}
renderAddLocation() {
return null;
if (
!this.props.multipleMarkersEnabled ||
this.props.currentPullRequestId ||
this.props.isEditing ||
this.props.commentType === "link"
)
return null;
return (
<div className="add-location">
<Tooltip
placement="topRight"
title="Comments can refer to multiple blocks of code, even across files."
delay={1}
>
<span onClick={e => this.addLocation()}>
<Icon name="plus" />
add range
</span>
</Tooltip>
</div>
);
}
async toggleCodeHighlightInTextEditor(highlight: boolean, index: number) {
const { editingCodemark } = this.props;
const codeBlock = this.state.codeBlocks[index];
let uri;
let range;
if (codeBlock) {
if (!codeBlock.range || !codeBlock.uri) return;
uri = codeBlock.uri;
range = codeBlock.range;
} else if (editingCodemark && editingCodemark.markers) {
const marker = editingCodemark.markers[index];
if (!marker) return;
const response = await getDocumentFromMarker(marker.id);
if (!response) return;
uri = response.textDocument.uri;
range = response.range;
} else {
return;
}
HostApi.instance.send(EditorHighlightRangeRequestType, { uri, range, highlight });
}
renderMessageInput = () => {
const { codeBlocks, type, text } = this.state;
let placeholder = this.props.placeholder;
if (codeBlocks.length) {
// const range = codeBlock ? arrayToRange(codeBlock.location) : null;
// let rangeText = "";
// if (range && codeBlock && codeBlock.file) {
// rangeText += "Add comment for " + codeBlock.file;
// const endLine = range.end.col == 0 ? range.end.row : range.end.row + 1;
// if (range.start.row + 1 === endLine) {
// rangeText += " line " + (range.start.row + 1);
// } else {
// rangeText += " lines " + (range.start.row + 1) + "-" + endLine;
// }
// // placeholder = rangeText;
// }
if (type === "question") placeholder = "Answer (optional)";
else if (type === "issue") placeholder = "Description (optional)";
else placeholder = "";
}
const __onDidRender = ({ insertTextAtCursor, focus }) => {
this.insertTextAtCursor = insertTextAtCursor;
this.focusOnMessageInput = focus;
};
return (
<MessageInput
onKeypress={() => this.setState({ touchedText: true })}
teamProvider={this.props.teamProvider}
isDirectMessage={this.props.channel.type === StreamType.Direct}
text={text}
placeholder={placeholder}
multiCompose
onChange={this.handleChange}
withTags={!this.props.textEditorUriHasPullRequestContext}
toggleTag={this.handleToggleTag}
toggleCodemark={this.handleToggleCodemark}
shouldShowRelatableCodemark={codemark =>
this.props.editingCodemark ? codemark.id !== this.props.editingCodemark.id : true
}
onSubmit={
this.props.currentPullRequestId
? this.handlePullRequestKeyboardSubmit
: this.handleClickSubmit
}
selectedTags={this.state.selectedTags}
relatedCodemarkIds={
this.props.textEditorUriHasPullRequestContext ? undefined : this.state.relatedCodemarkIds
}
setIsPreviewing={isPreviewing => this.setState({ isPreviewing })}
renderCodeBlock={this.renderCodeBlock}
renderCodeBlocks={this.renderCodeBlocks}
attachments={this.state.attachments}
attachmentContainerType="codemark"
setAttachments={this.setAttachments}
__onDidRender={__onDidRender}
/>
);
};
setAttachments = (attachments: AttachmentField[]) => this.setState({ attachments });
copyPermalink = (event: React.SyntheticEvent) => {
event.preventDefault();
if (this.permalinkRef.current) {
this.permalinkRef.current.select();
document.execCommand("copy");
this.setState({ copied: true });
}
};
copyPermalinkWithCode = (event: React.SyntheticEvent) => {
event.preventDefault();
if (this.permalinkWithCodeRef.current) {
this.permalinkWithCodeRef.current.select();
document.execCommand("copy");
this.setState({ copied: true });
}
};
renderEditingMarker = (marker, index, force) => {
const { liveLocation, text, isPreviewing } = this.state;
const { editingCodemark } = this.props;
if (!marker) return null;
// if (liveLocation == index && !codeBlock.range)
// return <span className="add-range">Select a range to add a code location</span>;
const blockInjected = text.includes(`[#${index + 1}]`);
if (isPreviewing && blockInjected && !force) return null;
let range: any = undefined;
if (marker.locationWhenCreated) {
range = arrayToRange(marker.locationWhenCreated as any);
} else {
range = arrayToRange(marker.referenceLocations[0].location);
}
const file = marker.file || "";
let extension = paths.extname(file).toLowerCase();
if (extension.startsWith(".")) extension = extension.substring(1);
const codeHTML = prettyPrintOne(escapeHtml(marker.code), extension, range.start.line + 1);
return (
<div
key={index}
className={cx("related", { live: liveLocation == index })}
style={{ padding: "0", marginBottom: 0, position: "relative" }}
>
<div className="file-info">
{file && (
<>
<span className="monospace" style={{ paddingRight: "20px" }}>
<Icon name="file" /> {file}
</span>{" "}
</>
)}
{marker.branch && (
<>
<span className="monospace" style={{ paddingRight: "20px" }}>
<Icon name="git-branch" /> {marker.branch}
</span>{" "}
</>
)}
{/* scm && scm.revision && (
<span className="monospace">
<Icon name="git-commit" /> {scm.revision.substring(0, 7)}
</span>
) */}
</div>
<pre
className="code prettyprint"
data-scrollable="true"
dangerouslySetInnerHTML={{ __html: codeHTML }}
/>
{liveLocation == index && (
<div className="code-buttons live">
<div className="codemark-actions-button ok" onClick={this.cementLocation}>
OK
</div>
<div className="codemark-actions-button" onClick={e => this.deleteLocation(index, e)}>
Cancel
</div>
</div>
)}
{liveLocation != index && !isPreviewing && (
<div className="code-buttons">
<Icon
title={
blockInjected
? `This code block [#${index + 1}] is in the markdown above`
: `Insert code block #${index + 1} in markdown`
}
placement="bottomRight"
name="pin"
className={blockInjected ? "clickable selected" : "clickable"}
onMouseDown={e => this.pinLocation(index, e)}
/>
<Icon
title={"Jump to this range in " + file}
placement="bottomRight"
name="link-external"
className="clickable"
onClick={e => this.jumpToLocation(index, e)}
/>
<Icon
title="Select new range"
placement="bottomRight"
name="select"
className="clickable"
onClick={e => this.editLocation(index, e)}
/>
<Icon
title="Remove Range"
placement="bottomRight"
name="x"
className="clickable"
onClick={e => this.deleteLocation(index, e)}
/>
</div>
)}
<div style={{ clear: "both" }}></div>
</div>
);
};
renderCodeBlock = (index, force) => {
const { codeBlocks, liveLocation, text, isPreviewing } = this.state;
const { editingCodemark } = this.props;
const codeBlock = codeBlocks[index];
if (!codeBlock) return null;
if (liveLocation == index && !codeBlock.range)
return <span className="add-range">Select a range to add a code location</span>;
if (!codeBlock.range) return null;
const blockInjected = text.includes(`[#${index + 1}]`);
if (isPreviewing && blockInjected && !force) return null;
const scm = codeBlock.scm;
let file = scm && scm.file ? paths.basename(scm.file) : "";
let range: any = codeBlock.range;
// if (editingCodemark) {
// if (editingCodemark.markers) {
// const marker = editingCodemark.markers[0];
// if (marker.locationWhenCreated) {
// // TODO: location is likely invalid
// range = arrayToRange(marker.locationWhenCreated as any);
// } else {
// range = undefined;
// }
// file = marker.file || "";
// }
// }
let extension = paths.extname(file).toLowerCase();
if (extension.startsWith(".")) extension = extension.substring(1);
const codeHTML = prettyPrintOne(
escapeHtml(codeBlock.contents),
extension,
range.start.line + 1
);
return (
<div
key={index}
className={cx("related", { live: liveLocation == index })}
style={{ padding: "0", marginBottom: 0, position: "relative" }}
>
<div className="file-info">
{file && (
<>
<span className="monospace" style={{ paddingRight: "20px" }}>
<Icon name="file" /> {file}
</span>{" "}
</>
)}
{scm && scm.branch && (
<>
<span className="monospace" style={{ paddingRight: "20px" }}>
<Icon name="git-branch" /> {scm.branch}
</span>{" "}
</>
)}
{scm && scm.revision && (
<span className="monospace">
<Icon name="git-commit" /> {scm.revision.substring(0, 7)}
</span>
)}
</div>
<pre
className="code prettyprint"
data-scrollable="true"
dangerouslySetInnerHTML={{ __html: codeHTML }}
/>
{liveLocation == index && (
<div className="code-buttons live">
<div className="codemark-actions-button ok" onClick={this.cementLocation}>
OK
</div>
<div className="codemark-actions-button" onClick={e => this.deleteLocation(index, e)}>
Cancel
</div>
</div>
)}
{liveLocation != index && !isPreviewing && (
<div className="code-buttons">
<Icon
title={
blockInjected
? `This code block [#${index + 1}] is in the markdown above`
: `Insert code block #${index + 1} in markdown`
}
placement="bottomRight"
name="pin"
className={blockInjected ? "clickable selected" : "clickable"}
onMouseDown={e => this.pinLocation(index, e)}
/>
<Icon
title={"Jump to this range in " + file}
placement="bottomRight"
name="link-external"
className="clickable"
onClick={e => this.jumpToLocation(index, e)}
/>
<Icon
title="Select new range"
placement="bottomRight"
name="select"
className="clickable"
onClick={e => this.editLocation(index, e)}
/>
<Icon
title="Remove Range"
placement="bottomRight"
name="x"
className="clickable"
onClick={e => this.deleteLocation(index, e)}
/>
</div>
)}
<div style={{ clear: "both" }}></div>
</div>
);
};
renderCodeBlocks = () => {
const { codeBlocks, liveLocation, isPreviewing } = this.state;
const { editingCodemark, multiLocation, commentType } = this.props;
const addLocationDiv = (
<Tooltip
placement="topLeft"
title="Comments can refer to multiple blocks of code, even across files."
delay={1}
>
<div
className="clickable"
style={{ margin: "15px 0 5px 3px", cursor: "pointer" }}
onClick={this.addLocation}
>
<Icon name="plus" className="clickable margin-right" />
Add Code Block
</div>
</Tooltip>
);
if (editingCodemark) {
const { deleteMarkerLocations } = this.state;
const { markers = [] } = editingCodemark;
const numMarkers = markers.length;
return (
<>
{markers.map((marker, index) => {
if (deleteMarkerLocations[index]) return null;
if (codeBlocks[index]) return this.renderCodeBlock(index, false);
else return this.renderEditingMarker(marker, index, false);
})}
{codeBlocks.map((codeBlock, index) => {
if (deleteMarkerLocations[index]) return null;
if (codeBlock && index >= numMarkers) return this.renderCodeBlock(index, false);
else return null;
})}
{isPreviewing || commentType === "link" ? null : this.state.addingLocation ? (
<div className="add-range" style={{ clear: "both", position: "relative" }}>
Select code from any file to add a range
<div className="code-buttons live">
<div
className="codemark-actions-button"
style={{ margin: "2px 0" }}
onClick={e => {
this.setState({ addingLocation: false, liveLocation: -1 });
this.focus();
}}
>
Done
</div>
</div>
</div>
) : (
addLocationDiv
)}
</>
);
}
return (
<>
{codeBlocks.map((codeBlock, index) => this.renderCodeBlock(index, false))}
{isPreviewing || commentType === "link" ? null : this.state.addingLocation ? (
<div className="add-range" style={{ clear: "both", position: "relative" }}>
Select code from any file to add a range
<div className="code-buttons live">
<div
className="codemark-actions-button"
style={{ margin: "2px 0" }}
onClick={e => {
this.setState({ addingLocation: false, liveLocation: -1 });
this.focus();
}}
>
Done
</div>
</div>
</div>
) : (
addLocationDiv
)}
</>
);
};
private _getCrossPostIssueContext(): ICrossPostIssueContext {
return {
setSelectedAssignees: assignees => this.setState({ assignees }),
selectedAssignees: this.state.assignees as any,
assigneesInputTarget:
this._assigneesContainerRef.current ||
(document.querySelector("#members-controls")! as any) ||
document.createElement("span"),
setValues: values => {
this.setState(state => ({
crossPostIssueValues: { ...state.crossPostIssueValues, ...values }
}));
},
codeBlock: this.state.codeBlocks[0]
};
}
cancelCompose = (e?: Event) => {
this.props.onClickClose && this.props.onClickClose(e);
};
render() {
const { codeBlocks, scmError } = this.state;
const { editingCodemark, currentReviewId } = this.props;
const commentType = this.getCommentType();
this.renderedCodeBlocks = {};
// if you are conducting a review, and somehow are able to try to
// create an issue or a permalink, stop the user from doing that
if (commentType !== "comment" && currentReviewId) {
return (
<Modal translucent onClose={this.cancelCompose} verticallyCenter>
<div style={{ width: "20em", fontSize: "larger", margin: "0 auto" }}>
Sorry, you can't add an issue while doing a review. Mark your a comment as a "change
request" instead.
<div className="button-group one-button">
<Button className="control-button" onClick={this.cancelCompose}>
OK
</Button>
</div>
</div>
</Modal>
);
}
if (scmError) {
return (
<Modal translucent onClose={this.cancelCompose} verticallyCenter>
<div style={{ width: "20em", fontSize: "larger", margin: "0 auto" }}>
Sorry, we encountered a git error: {scmError}
<br />
<br />
<FormattedMessage id="contactSupport" defaultMessage="contact support">
{text => <Link href="https://help.codestream.com">{text}</Link>}
</FormattedMessage>
<div className="button-group one-button">
<Button className="control-button" onClick={this.cancelCompose}>
Close
</Button>
</div>
</div>
</Modal>
);
}
if (this.props.multiLocation || !editingCodemark) {
return (
<div className="full-height-codemark-form">
<CancelButton onClick={this.cancelCompose} incrementKeystrokeLevel={true} />
<PanelHeader
title={
this.props.currentCodeErrorId
? "Add Comment to Error"
: this.props.currentReviewId
? "Add Comment to Review"
: this.props.textEditorUriHasPullRequestContext
? "Add Comment to Pull Request"
: commentType === "comment"
? "Add a Comment"
: commentType === "link"
? "Grab a Permalink"
: "Open an Issue"
}
></PanelHeader>
<span className="plane-container">
<div className="codemark-form-container">{this.renderCodemarkForm()}</div>
{false && commentType === "comment" && !codeBlocks[0] && (
<VideoLink href={"https://youtu.be/RPaIIZgaFK8"}>
<img src="https://i.imgur.com/9IKqpzf.png" />
<span>Discussing Code with CodeStream</span>
</VideoLink>
)}
{false && commentType === "issue" && !codeBlocks[0] && (
<VideoLink href={"https://youtu.be/lUI110T_SHY"}>
<img src="https://i.imgur.com/9IKqpzf.png" />
<span>Ad-hoc Code Review</span>
</VideoLink>
)}
</span>
</div>
);
} else if (this.props.positionAtLocation) {
if (codeBlocks[0]) {
const lineNumber = codeBlocks[0].range.start.line;
return (
<ContainerAtEditorLine repositionToFit lineNumber={lineNumber} className="cs-has-form">
<div className="codemark-form-container">{this.renderCodemarkForm()}</div>
</ContainerAtEditorLine>
);
} else {
return (
<ContainerAtEditorSelection className="cs-has-form">
<div className="codemark-form-container">{this.renderCodemarkForm()}</div>
</ContainerAtEditorSelection>
);
}
} else {
return this.renderCodemarkForm();
}
}
renderNotificationMessage = () => {
// @ts-ignore
const emails = keyFilter(this.state.emailAuthors);
if (emails.length === 0) return null;
return (
<>
<div style={{ height: "10px" }}></div>
<CSText muted>
<SmartFormattedList value={emails} /> will be notified via email
</CSText>
</>
);
};
cancelCodemarkCompose = (e?) => {
const { touchedText, type } = this.state;
if (!this.props.onClickClose) return;
// if there is codemark text, confirm the user actually wants to cancel
if (touchedText && (type === "comment" || type === "issue")) {
confirmPopup({
title: "Are you sure?",
message: "Changes will not be saved.",
centered: true,
buttons: [
{ label: "Go Back", className: "control-button" },
{
label: `Discard ${type === "issue" ? "Issue" : "Comment"}`,
wait: true,
action: this.props.onClickClose,
className: "delete"
}
]
});
} else {
this.props.onClickClose(e);
}
};
toggleEmail = (email: string) => {
const { emailAuthors } = this.state;
this.props.setUserPreference(["skipEmailingAuthors"], emailAuthors[email]);
this.setState({ emailAuthors: { ...emailAuthors, [email]: !emailAuthors[email] } });
};
renderEmailAuthors = () => {
const { unregisteredAuthors, emailAuthors, isPreviewing } = this.state;
const { isCurrentUserAdmin } = this.props;
if (isPreviewing) return null;
if (unregisteredAuthors.length === 0) return null;
return unregisteredAuthors.map(author => {
return (
<div className="checkbox-row">
<Checkbox
name={"email-" + author.email}
checked={emailAuthors[author.email]}
onChange={() => this.toggleEmail(author.email)}
>
Send to {author.username || author.email}
<Icon
name="info"
title={
<>
Retrieved from git blame.
{isCurrentUserAdmin && <p>Configure Blame Map under MY TEAM.</p>}
</>
}
placement="top"
delay={1}
align={{ offset: [0, 5] }}
/>
</Checkbox>
</div>
);
});
};
handleDragEnter = () => this.setState({ isDragging: this.state.isDragging + 1 });
handleDragLeave = () => this.setState({ isDragging: this.state.isDragging - 1 });
handleDrop = () => this.setState({ isDragging: 0 });
renderCodemarkForm() {
const { editingCodemark, currentUser } = this.props;
const commentType = this.getCommentType();
const titlePlaceholder =
commentType === "issue"
? "Title (required)"
: commentType === "question"
? "Question (required)"
: commentType === "bookmark"
? "Bookmark Name (optional)"
: "Title (optional)";
const modifier = navigator.appVersion.includes("Macintosh") ? "⌘" : "Ctrl";
const submitTip =
commentType === "link" ? (
this.state.copied ? (
"Copied!"
) : this.state.linkURI ? (
"Copy Link"
) : (
"Create Link"
)
) : commentType === "issue" ? (
"Create Issue"
) : commentType === "bookmark" ? (
"Create Bookmark"
) : (
<span>
Submit Comment<span className="keybinding extra-pad">{modifier} ENTER</span>
</span>
);
const cancelTip = (
<span>
Discard Comment<span className="keybinding extra-pad">ESC</span>
</span>
);
const locationItems: any[] = [];
if (this.props.multipleMarkersEnabled && this.props.commentType !== "link")
locationItems.push({ label: "Add Range", action: () => this.addLocation() });
// { label: "Change Location", action: () => this.editLocation(0) }
if (!this.props.multiLocation)
locationItems.push({ label: "Select New Range", action: () => this.editLocation(0) });
if (this.state.codeBlocks.length == 1)
locationItems.push({ label: "Remove Location", action: () => this.deleteLocation(0) });
const hasError = this.props.error != null && this.props.error !== "";
const hasExistingPullRequestReview = !!(
this.state.codeBlocks &&
this.state.codeBlocks[0] &&
this.state.codeBlocks[0].context &&
this.state.codeBlocks[0].context.pullRequest &&
!!this.state.codeBlocks[0].context.pullRequest.pullRequestReviewId
);
// default to "add comment" having the keyboard shortcut when both buttons are enabled
const reviewTooltip = hasExistingPullRequestReview ? (
<span>
Add to review<span className="keybinding extra-pad">{modifier} ENTER</span>
</span>
) : (
<span>Start a review</span>
);
let linkWithCodeBlock = "";
if (this.state.linkURI) {
linkWithCodeBlock += this.state.linkURI + "\n\n*";
const codeBlock = this.state.codeBlocks[0];
if (codeBlock) {
const { scm, uri } = codeBlock;
if (scm && scm.repoId) {
const repo = this.props.repos[scm.repoId];
if (repo) linkWithCodeBlock += "[" + repo.name + "] ";
}
if (scm && scm.file) {
linkWithCodeBlock += scm.file;
}
linkWithCodeBlock += "*\n```\n" + codeBlock.contents + "\n```\n";
}
}
const commentIsDisabled =
hasError || (this.state.isInsidePrChangeSet && !!hasExistingPullRequestReview);
return [
<form
id="code-comment-form"
className={cx("codemark-form", "standard-form", {
"active-drag": this.state.isDragging > 0
})}
key="two"
onDragEnter={this.handleDragEnter}
onDrop={this.handleDrop}
onDragOver={e => e.preventDefault()}
onDragLeave={this.handleDragLeave}
>
<fieldset className="form-body">
{hasError && (
<div className="error-message" style={{ marginTop: 10 }}>
{this.props.error}
</div>
)}
<div id="controls" className="control-group" key="controls1">
<div key="headshot" className="headline">
<Headshot person={currentUser} />
<b>{currentUser.username}</b>
{this.getCodeBlockHint()}
{this.state.locationMenuOpen == "header" && (
<Menu
align="center"
target={this.state.locationMenuTarget}
items={locationItems}
action={this.selectLocation}
/>
)}
</div>
{/* false && commentType === "bookmark" && (
<div className="hint frame control-group" style={{ marginBottom: "10px" }}>
{bookmarkTip}
</div>
) */}
{commentType === "issue" && !this.props.isEditing && (
<CrossPostIssueContext.Provider value={this._getCrossPostIssueContext()}>
<CrossPostIssueControls />
</CrossPostIssueContext.Provider>
)}
{(commentType === "issue" ||
commentType === "question" ||
commentType === "bookmark" ||
commentType === "snippet") && (
<div key="title" className="control-group">
{this.renderTitleHelp()}
<input
key="title-text"
type="text"
name="title"
className="input-text control"
tabIndex={this.tabIndex()}
value={this.state.title}
onChange={e => this.setState({ title: e.target.value })}
placeholder={titlePlaceholder}
ref={ref => (this._titleInput = ref)}
/>
</div>
)}
{commentType === "issue" && (
<div
ref={this._assigneesContainerRef}
key="members"
id="members-controls"
className="control-group"
style={{ marginBottom: "10px" }}
>
{/*
There's some magic here. The specific control components for the issue provider,
will render the input for assignees in here. And since those components aren't used
while editing, a disabled input will be rendered here.
*/}
{this.props.isEditing && (
<Select
key="input-assignees2"
id="input-assignees"
name="assignees"
classNamePrefix="react-select"
isMulti
isDisabled
value={this.state.assignees}
/>
)}
</div>
)}
{this.renderTextHelp()}
{commentType === "link" &&
this.state.linkURI &&
this.state.isPermalinkPublic && [
<div key="permalink-warning" className="permalink-warning">
<Icon name="alert" />
Note that this is a public URL. Anyone with the link will be able to see the
quoted code snippet.
</div>
]}
{commentType === "link" &&
this.state.linkURI && [
<textarea
key="link-offscreen"
ref={this.permalinkRef}
value={this.state.linkURI}
style={{ position: "absolute", left: "-9999px" }}
/>,
<input type="text" className="permalink" value={this.state.linkURI} />,
<textarea
key="link-offscreen-2"
ref={this.permalinkWithCodeRef}
value={linkWithCodeBlock}
style={{ position: "absolute", left: "-9999px" }}
/>
]}
{commentType === "link" && !this.state.linkURI && (
<div id="privacy-controls" className="control-group" key="1">
<div className="public-private-hint" key="privacy-hint">
{this.state.isPermalinkPublic
? "Anyone can view this link, including the quoted codeblock."
: "Only members of your team can access this link."}
</div>
<LabeledSwitch
key="privacy"
colored
on={this.state.isPermalinkPublic}
offLabel="Private"
onLabel="Public"
onChange={this.togglePermalinkPrivacy}
height={28}
width={90}
/>
</div>
)}
{commentType !== "bookmark" && commentType !== "link" && this.renderMessageInput()}
</div>
{false && (commentType === "comment" || commentType === "question") && (
<div key="alert" className="checkbox-row" onClick={this.toggleNotify}>
<input type="checkbox" checked={this.state.notify} /> Alert me if someone edits code
in this range{" "}
<Tooltip title="Click to learn more">
<span>
<Icon className="clickable" onClick={this.showAlertHelp} name="info" />
</span>
</Tooltip>
</div>
)}
<div style={{ clear: "both" }} />
{/* this.renderPrivacyControls() */}
{this.renderRelatedCodemarks()}
{this.renderTags()}
{!this.state.isPreviewing && this.renderCodeBlocks()}
{this.props.multiLocation && <div style={{ height: "10px" }} />}
{commentType !== "link" && this.renderEmailAuthors()}
{commentType !== "link" && this.renderSharingControls()}
{this.props.currentReviewId && this.renderRequireChange()}
{!this.state.isPreviewing && (
<div key="buttons" className="button-group float-wrap">
<CancelButton
toolTip={cancelTip}
onClick={this.cancelCodemarkCompose}
title={this.state.copied ? "Close" : "Cancel"}
mode="button"
incrementKeystrokeLevel={true}
/>
{commentType === "link" && this.state.linkURI && !this.state.copied && (
<Tooltip title={"Copy Link and Code Block (Markdown)"} placement="bottom" delay={1}>
<Button
key="copy-with-block"
style={{
paddingLeft: "10px",
paddingRight: "10px",
marginRight: 0
}}
className="control-button"
type="submit"
onClick={this.copyPermalinkWithCode}
>
Copy Link w/ Code Block
</Button>
</Tooltip>
)}
<Tooltip title={commentIsDisabled ? null : submitTip} placement="bottom" delay={1}>
<Button
key="submit"
style={{
paddingLeft: "10px",
paddingRight: "10px",
// fixed width to handle the isLoading case
width:
this.props.currentReviewId ||
this.props.textEditorUriHasPullRequestContext ||
this.props.currentCodeErrorId
? "auto"
: "80px",
marginRight: 0
}}
className="control-button"
type="submit"
loading={this.state.isLoading}
onClick={
commentType === "link" && this.state.linkURI
? this.copyPermalink
: this.handleClickSubmit
}
disabled={commentIsDisabled}
>
{commentType === "link"
? this.state.copied
? "Copied!"
: this.state.linkURI
? "Copy Link"
: "Create Link"
: this.state.isChangeRequest
? "Add Comment & Request Change"
: this.props.currentReviewId
? "Add Comment to Review"
: this.props.textEditorUriHasPullRequestContext
? this.props.prLabel.AddSingleComment
: this.props.editingCodemark
? "Save"
: this.props.currentCodeErrorId
? "Add Comment to Error"
: "Submit"}
</Button>
</Tooltip>
{this.props.textEditorUriHasPullRequestContext && this.state.isInsidePrChangeSet && (
<Tooltip title={hasError ? null : reviewTooltip} placement="bottom" delay={1}>
<Button
key="submit-review"
loading={this.state.isReviewLoading}
disabled={hasError}
onClick={e => {
this.setState({ isProviderReview: true }, () => {
this.handleClickSubmit(e);
});
}}
style={{
paddingLeft: "10px",
paddingRight: "10px",
// fixed width to handle the isReviewLoading case
width: "auto",
marginRight: 0
}}
className="control-button"
type="submit"
>
{hasExistingPullRequestReview && <>Add to review</>}
{!hasExistingPullRequestReview && <>Start a review</>}
</Button>
</Tooltip>
)}
{/*
<span className="hint">Styling with Markdown is supported</span>
*/}
</div>
)}
<div key="clear" style={{ clear: "both" }} />
</fieldset>
</form>
];
// <span className="hixnt" style={{ grid: "none" }}>
// <input type="checkbox" />
// Open automatically on selection
// </span>
// <input
// id="radio-comment-type-snippet"
// type="radio"
// name="comment-type"
// checked={commentType === "snippet"}
// onChange={e => this.setCommentType("snippet")}
// />
// <label
// htmlFor="radio-comment-type-snippet"
// className={createClassString({
// checked: commentType === "snippet"
// })}
// >
// <Icon name="code" /> <span>Snippet</span>
// </label>
}
}
const EMPTY_OBJECT = {};
const EMPTY_ARRAY = [];
const mapStateToProps = (state: CodeStreamState): ConnectedProps => {
const {
context,
editorContext,
users,
teams,
session,
preferences,
providers,
codemarks,
repos,
codeErrors
} = state;
const user = users[session.userId!] as CSMe;
const channel = context.currentStreamId
? getStreamForId(state.streams, context.currentTeamId, context.currentStreamId) ||
getStreamForTeam(state.streams, context.currentTeamId)
: getStreamForTeam(state.streams, context.currentTeamId);
const teamMates = getTeamMates(state);
const teamMembers = getTeamMembers(state);
const teamTagsArray = getTeamTagsArray(state);
const channelStreams = getChannelStreamsForTeam(state, context.currentTeamId);
const skipPostCreationModal = preferences ? preferences.skipPostCreationModal : false;
const skipEmailingAuthors = preferences ? preferences.skipEmailingAuthors : false;
const team = teams[context.currentTeamId];
const adminIds = team.adminIds || EMPTY_ARRAY;
const activeMemberIds = getActiveMemberIds(team);
const isCurrentUserAdmin = adminIds.includes(session.userId || "");
const blameMap = team.settings ? team.settings.blameMap : EMPTY_OBJECT;
const inviteUsersOnTheFly =
isFeatureEnabled(state, "emailSupport") && isFeatureEnabled(state, "inviteUsersOnTheFly");
const textEditorUriContext = parseCodeStreamDiffUri(editorContext.textEditorUri!);
return {
repos,
channel,
teamMates,
teamMembers,
activeMemberIds,
currentTeamId: state.context.currentTeamId,
blameMap: blameMap || EMPTY_OBJECT,
isCurrentUserAdmin,
activePanel: context.panelStack[0] as WebviewPanels,
shouldShare:
safe(() => state.preferences[state.context.currentTeamId].shareCodemarkEnabled) || false,
channelStreams: channelStreams,
issueProvider: providers[context.issueProvider!],
currentPullRequestId: state.context.currentPullRequest
? state.context.currentPullRequest.id
: undefined,
providerInfo: (user.providerInfo && user.providerInfo[context.currentTeamId]) || EMPTY_OBJECT,
teamProvider: getCurrentTeamProvider(state),
currentUser: user,
skipPostCreationModal,
skipEmailingAuthors,
selectedStreams: preferences.selectedStreams || EMPTY_OBJECT,
showChannels: context.channelFilter,
textEditorUri: editorContext.textEditorUri,
textEditorGitSha: editorContext.textEditorGitSha,
textEditorSelection: getCurrentSelection(editorContext),
textEditorUriContext: textEditorUriContext,
textEditorUriHasPullRequestContext: !!(
textEditorUriContext &&
textEditorUriContext.context &&
textEditorUriContext.context.pullRequest &&
textEditorUriContext.context.pullRequest.id
),
teamTagsArray,
codemarkState: codemarks,
multipleMarkersEnabled: isFeatureEnabled(state, "multipleMarkers"),
currentReviewId: context.currentReviewId,
currentCodeErrorId: context.currentCodeErrorId,
inviteUsersOnTheFly,
prLabel: getPRLabel(state),
codeErrors: codeErrors
};
};
const ConnectedCodemarkForm = connect(mapStateToProps, {
openPanel,
openModal,
markItemRead,
setUserPreference,
fetchCodeError,
upgradePendingCodeError
})(CodemarkForm);
export { ConnectedCodemarkForm as CodemarkForm }; | the_stack |
import * as express from "express";
import * as fastify from 'fastify'
import * as glob from 'glob'
import * as http from 'http'
import * as http2 from 'http2'
import { ApplicationRegistry } from "./ApplicationRegistry";
import { DependencyRegistry } from "../di/DependencyRegistry";
import { InitializerRegistry } from "../initializer/InitializerRegistry";
import { Klass } from "../core/Klass";
import { IHandlerAdapter, ILoaderAdapter } from "../server-adapters/IAdapter";
import { FastifyHandlerAdapter, FastifyLoaderAdapter } from "../server-adapters/FastifyAdapter";
import { ConverterService } from "../converter";
import { ExpressHandlerAdapter, ExpressLoaderAdapter } from "../server-adapters/ExpressAdapter";
import { SettingOptions } from "./SettingOptions";
const debug = require('debug')('loon:ApplicationLoader');
export class ApplicationLoader {
private _server: fastify.FastifyInstance|express.Application
private _handlerAdapter: IHandlerAdapter
private _loaderAdapter: ILoaderAdapter
private _env: string;
private _rootDir?: string
private _files?: string
private _port: string;
private _host: string
private _backlog: number
private _ext: string
private _lazyInit: boolean;
private _closeTimeout: number;
get server() {
return this._server;
}
get env() {
return this._env;
}
get rootDir() {
return this._rootDir;
}
get files() {
return this._files;
}
get port() {
return this._port;
}
get host() {
return this._host;
}
get backlog() {
return this._backlog;
}
get lazyInit() {
return this._lazyInit;
}
get closeTimeout() {
return this._closeTimeout;
}
/**
* Load user defined settings into ApplicationLoader
* Initialize settings
*/
constructor(typeOrServer: string|fastify.FastifyInstance|express.Application, settings?: SettingOptions) {
const _settings = Object.assign({}, ApplicationRegistry.settings, settings)
if (typeOrServer === 'express') {
debug('built in express server');
this._server = express() as express.Application
this._server.use(require('body-parser').text())
this._server.use(require('body-parser').json())
this._server.use(require('body-parser').urlencoded({ extended: true }))
this._server.use(require('method-override')())
} else if (typeOrServer === 'fastify') {
debug('built in fastify server');
if (settings && settings.serverOpts) {
this._server = fastify(settings.serverOpts) as fastify.FastifyInstance
} else {
this._server = fastify() as fastify.FastifyInstance
}
this._server.register(require('fastify-formbody'))
this._server.addContentTypeParser('text/plain', {parseAs: 'string'}, async (req, body) => {
return body
})
} else {
debug('custom express or fastify server');
this._server = <fastify.FastifyInstance|express.Application>typeOrServer
}
if (this._isFastify()) {
debug('is fastify server');
this._handlerAdapter = new FastifyHandlerAdapter(new ConverterService())
this._loaderAdapter = new FastifyLoaderAdapter(this._server as fastify.FastifyInstance, this._handlerAdapter)
} else if (this._isExpress()) {
debug('is express server');
this._handlerAdapter = new ExpressHandlerAdapter(new ConverterService())
this._loaderAdapter = new ExpressLoaderAdapter(this._server as express.Application, this._handlerAdapter)
} else {
throw 'server is not supported, use express and fastify'
}
this._env = process.env.NODE_ENV || _settings.env || 'development';
debug(`env: ${this._env}`);
this._port = process.env.PORT || _settings.port || '9000';
debug(`port: ${this._port}`);
this._host = process.env.HOST || _settings.host || '0.0.0.0'
debug(`host: ${this._host}`);
this._backlog = process.env.BACKLOG as any || _settings.backlog || 511
debug(`backlog: ${this._backlog}`);
this._ext = process.env.EXT || _settings.ext || 'js'
this._lazyInit = _settings.lazyInit === true ? true : false;
this._closeTimeout = _settings.closeTimeout || 10 * 1000;
this._rootDir = _settings.rootDir;
this._files = _settings.files
DependencyRegistry.set(<Klass> ApplicationLoader, this);
}
private async _loadComponents() {
debug('_loadComponents');
if (this._files) {
debug('files load mode');
glob.sync(this._files).forEach(file => {
debug(file);
require(file)
})
}
if (this._rootDir) {
debug('rootDir load mode');
glob.sync(`${this._rootDir}/**/*.${this._ext}`).forEach(file => {
debug(file);
require(file)
})
}
return this;
}
private async _initializeComponents() {
// by default, after load all components, do initialization
// if set as lazyInit, initialize component when being used
if (!this._lazyInit) {
debug('_initializeComponents');
DependencyRegistry.components.forEach(component => {
debug(`initialize component: ${component.klass.name}`);
DependencyRegistry.init(component.klass)
});
}
return this;
}
private async _init() {
debug('_init');
'$beforeInit' in this ? await (<any> this).$beforeInit() : null;
InitializerRegistry
.getInitializers()
.forEach(async initializer => {
const instance = DependencyRegistry.get(<Klass>initializer.type);
await instance['init'].apply(instance);
});
'$afterInit' in this ? await (<any> this).$afterInit() : null;
return this;
}
private async _loadMiddlewares() {
debug('_loadMiddlewares');
'$beforeLoadMiddlewares' in this ? await (<any> this).$beforeLoadMiddlewares() : null;
this._loaderAdapter.loadMiddlewares()
'$afterLoadMiddlewares' in this ? await (<any> this).$afterLoadMiddlewares() : null;
return this;
}
private async _loadControllers() {
debug('_loadControllers');
'$beforeLoadControllers' in this ? await (<any> this).$beforeLoadControllers() : null;
this._loaderAdapter.loadControllers()
'$afterLoadControllers' in this ? await (<any> this).$afterLoadControllers() : null;
return this;
}
private async _loadErrorMiddlewares() {
debug('_loadErrorMiddlewares');
'$beforeLoadErrorMiddlewares' in this ? await (<any> this).$beforeLoadErrorMiddlewares() : null;
this._loaderAdapter.loadErrorMiddlewares()
'$afterLoadErrorMiddlewares' in this ? await (<any> this).$afterLoadErrorMiddlewares() : null;
return this;
}
public async start() {
debug('start');
try {
await this._loadComponents()
await this._initializeComponents()
await this._init()
await this._loadMiddlewares()
await this._loadControllers()
await this._loadErrorMiddlewares()
} catch (e) {
throw e
}
return new Promise((resolve, reject) => {
if (this._isExpress()) {
const server = (this._server as any).listen(this._port, this._host, this._backlog, (err) => {
if (err) reject(err)
resolve(server)
})
} else if (this._isFastify()) {
(this._server as any).listen(this._port, this._host, this._backlog, (err) => {
if (err) reject(err)
resolve((this._server as fastify.FastifyInstance).server)
})
} else {
throw 'server type unsupported error';
}
}).then((server: http.Server) => {
const SIG = ['SIGINT', 'SIGTERM'];
SIG.forEach(signal => {
process.on(signal as any, () => {
console.log(`receiving signal: ${signal}`);
server.close(err => {
if (err) {
console.error(err.message);
process.exit(1);
}
const closeServer = () => {
if ('$onClose' in this) {
const onClose = (<any> this).$onClose();
if (onClose.then && typeof onClose.then === 'function') {
onClose.then(() => {
process.exit(0);
})
} else {
process.exit(0);
}
} else {
process.exit(0);
}
};
closeServer();
setTimeout(() => {
console.error('could not close http/resource connection in time, force shuting down');
closeServer();
}, this._closeTimeout);
});
});
});
return server;
});
}
private _isExpress() {
return !!(this._server as express.Application)['m-search']
}
private _isFastify() {
return !!(this._server as fastify.FastifyInstance).setErrorHandler
}
} | the_stack |
declare function require(arg: string): string;
import {
IMALSearchAnime,
IMALUserListAnime,
Intent,
} from "../common";
import {cleanAnimeName, loadSettings} from "../utils";
let animeName = "";
let animeId = "";
let animeInUserList = false;
let currentAnime: IMALSearchAnime;
// holds the amount of episodes user has watches as per their MAL
let malWatchedEpisodes = 0;
let autoUpdate = true;
let statusIconTimeout = 0;
let userList: IMALUserListAnime[];
enum StatusType {
InProgress,
Success,
Fail,
}
const selectors = {
add: "#nac__mal__add",
incrementEp: "#nac__mal__increment-ep",
quickAccess: "#nac__mal__quick-access",
sectionAdd: "#nac__mal__section-add",
sectionUpdate: "#nac__mal__section-update",
statusIcon: "#nac__mal__status-icon",
totalEp: "#nac__mal__total-ep",
update: "#nac__mal__update",
watchedEp: "#nac__mal__watched-ep", /* textbox */
};
interface ISetupOptions {
animeName: string;
}
// Setup
export function setup(options: ISetupOptions): void {
loadSettings("malAutoUpdate").then(resp => {
resp.malAutoUpdate = resp.malAutoUpdate === undefined ? true : resp.malAutoUpdate;
autoUpdate = resp.malAutoUpdate;
animeName = cleanAnimeName(options.animeName);
// The actual setup
$("#player").parent().append(quickAccess());
initialize();
});
}
// Hides the loader in the quick access widget.
function hideLoader(): void {
$(selectors.quickAccess).find(".loader").fadeOut(300);
}
function showStatusIcon(statusType: StatusType = StatusType.InProgress): void {
// Clear the timeout to make sure we dont
// accidentally hide a icon when its needed.
clearTimeout(statusIconTimeout);
let statusIcon = $(selectors.statusIcon);
switch (statusType) {
case StatusType.Success:
statusIcon.attr("src", chrome.extension.getURL("images/check-mark.png"));
break;
case StatusType.Fail:
statusIcon.attr("src", chrome.extension.getURL("images/x-mark.png"));
break;
default: /* StatusType.InProgress */
statusIcon.attr("src", chrome.extension.getURL("images/tail-spin.svg"));
break;
}
statusIcon.show();
}
function hideStatusIcon(): void {
// Clear the timeout to make sure we dont
// accidentally hide a icon when its needed.
clearTimeout(statusIconTimeout);
statusIconTimeout = setTimeout(() => {
$(selectors.statusIcon).fadeOut(500);
// FIXME: glitch where on showing status icon the previous icon is temporarily visible.
// $(selectors.statusIcon).attr("src", "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=");
}, 5000);
}
function showSectionAdd(): void {
$(selectors.sectionAdd).show();
$(selectors.sectionUpdate).hide();
}
function showSectionUpdate(): void {
$(selectors.sectionAdd).hide();
$(selectors.sectionUpdate).show();
}
/**
* Callback function for {@link epChangeCallbacks}. This function helps
* implement the auto mal sync behaviour.
* @param newEpId
* @param newEpNum
*/
export function epTracker(newEpId: string, newEpNum: number): void {
// We need to make sure that the newEpNum is actually a episode
// number and not stuff like tv, full, movie etc. The last
// condition makes sure we dont spam the MAL API when 9anime
// auto switches servers if it doesn't find anime in a server.
if (!isNaN(Number(newEpNum)) && autoUpdate && animeInUserList && newEpNum > malWatchedEpisodes) {
// update watched box and trigger auto sync
$(selectors.watchedEp).val(newEpNum);
malWatchedEpisodes = newEpNum;
$(selectors.update).click();
}
}
/**
* Checks if the current anime is in users MAL List. If it
* exists, then the MAL entry is returned which is used for
* getting information like watched episodes etc. If the
* current anime does not exist, then null is returned.
*/
function findAnimeInUserList(): IMALUserListAnime | null {
for (let entry of userList) {
if (currentAnime.id === entry.series_animedb_id) {
return entry;
}
}
return null;
}
/**
* Searches MAL and returns current anime. It does this by regex
* matching the items on the returned MAL search list with the
* anime name that we get from the title.
*/
function getCurrentAnime(): Promise<IMALSearchAnime> {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({
animeName,
intent: Intent.MAL_Search,
}, resp => {
if (resp.success) {
// We need the actual brackets in the regex for anime's
// like Little Witch Academia (TV). So we escape them.
let fixed = animeName
.replace("(", "\\(")
.replace(")", "\\)");
let titleRe = new RegExp(`^${fixed}$`, "i");
// console.log(resp);
for (let entry of (resp.data as IMALSearchAnime[])) {
if (entry.title.match(titleRe)) {
// Why return? because we need to break away
// here without executing any more code in
// this block.
return resolve(entry);
}
}
}
// If there were no match,
// we reject this promise :<
reject(resp.err);
});
});
}
/**
* Returns users MAL Anime List.
*/
function getUserList(): Promise<IMALUserListAnime[]> {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({
intent: Intent.MAL_Userlist,
}, resp => {
if (resp.success) {
resolve(resp.data as IMALUserListAnime[]);
} else {
reject(resp.err);
}
});
});
}
export function initialize(): void {
Promise.all([getCurrentAnime(), getUserList()])
.then(value => {
currentAnime = value[0];
userList = value[1];
animeId = currentAnime.id;
// console.log(currentAnime, userList);
let entry = findAnimeInUserList();
if (entry) { /* --- Update Anime --- */
animeInUserList = true;
showSectionUpdate();
$(selectors.totalEp).text(currentAnime.episodes);
$(selectors.watchedEp).val(entry.my_watched_episodes);
malWatchedEpisodes = Number(entry.my_watched_episodes) || 0;
} else { /* --- Add Anime --- */
showSectionAdd();
}
hideLoader();
})
.catch(err => {
// console.log(err);
let qa = $(selectors.quickAccess);
qa.find(".loader > img").hide();
switch (err) {
case 204:
qa.find(".loader > .status").show().text("Anime not found in MAL :(");
break;
case 401:
qa.find(".loader > .status").show().text("Invalid MAL credentials");
break;
default:
qa.find(".loader > .status").show().text("Oops! Something went wrong");
break;
}
});
}
/**
* Returns the MyAnimeList quick access widget. This widget
* allows a user to quickly add/update anime to their MAL.
*/
export function quickAccess(): JQuery<HTMLElement> {
let template = require("html-loader!../../templates/mal_quickAccess.html");
let qa = $(template);
// Set the default images. For the statusIcon, we embed a
// blank 1x1 gif because a img tag with no source is not
// valid and will cause a unwanted server hit.
qa.find(".loader > img").attr("src", chrome.extension.getURL("images/puff.svg"));
qa.find(selectors.statusIcon).attr("src", "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=");
// Hide the status icon. Its only visible
// during a ongoing operations.
qa.find(selectors.statusIcon).hide();
// --- Attach functionality ---
// watchedEp textbox should only allow numbers
qa.find(selectors.watchedEp).on("keydown", e => {
if (e.keyCode) {
// Backspace is allowed
if (!(e.keyCode === 8 || (e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105))) {
return false;
}
}
});
qa.find(selectors.incrementEp).on("click", () => {
let c = $(selectors.watchedEp).val();
$(selectors.watchedEp).val(Number(c) + 1);
});
qa.find(selectors.add).on("click", () => {
showStatusIcon();
chrome.runtime.sendMessage({
animeId,
intent: Intent.MAL_QuickAdd,
}, resp => {
if (resp.success) {
animeInUserList = true;
showStatusIcon(StatusType.Success);
showSectionUpdate();
$(selectors.totalEp).text(currentAnime.episodes);
$(selectors.watchedEp).val(1);
} else {
showStatusIcon(StatusType.Fail);
}
// Hide the status icon after 5 seconds
hideStatusIcon();
});
});
qa.find(selectors.update).on("click", () => {
showStatusIcon();
chrome.runtime.sendMessage({
animeId,
episode: $(selectors.watchedEp).val(),
intent: Intent.MAL_QuickUpdate,
}, resp => {
if (resp.success) {
showStatusIcon(StatusType.Success);
} else {
showStatusIcon(StatusType.Fail);
}
// Hide the status icon after 5 seconds
hideStatusIcon();
});
});
// Hide the status span since we only show
// it if loading the mal widget fails for
// some reason.
qa.find(".loader > .status").hide();
return qa;
} | the_stack |
import {
DIFF_DELETE,
DIFF_EQUAL,
DIFF_INSERT,
diff_match_patch,
patch_obj,
} from 'diff-match-patch';
import { EventEmitter2 } from 'eventemitter2';
import { Doc, Path, StringDeleteOp, StringInsertOp } from 'sharedb';
import isEqual from 'lodash/isEqual';
import { DocInterface, EngineInterface, TargetOp } from '../types';
import {
findFromDoc,
isTransientAttribute,
toJSON0,
isTransientElement,
} from './utils';
import { CARD_LOADING_KEY, CARD_KEY, CARD_TYPE_KEY } from './../constants/card';
import { DATA_ID, JSON0_INDEX } from '../constants';
import { $ } from '../node';
import { isRoot } from '../node/utils';
export default class Producer extends EventEmitter2 {
private engine: EngineInterface;
private doc?: DocInterface | Doc;
private dmp: diff_match_patch;
timer: NodeJS.Timeout | null = null;
lineStart: boolean = false;
constructor(
engine: EngineInterface,
options: { doc?: DocInterface | Doc },
) {
super();
this.engine = engine;
this.doc = options.doc;
this.dmp = new diff_match_patch();
}
setDoc(doc: DocInterface | Doc) {
this.doc = doc;
}
textToOps(path: Path, text1: string, text2: string) {
const ops: (StringDeleteOp | StringInsertOp)[] = [];
const patches = this.dmp.patch_make(text1, text2);
Object.keys(patches).forEach((key) => {
const patch: patch_obj = patches[key];
if (patch.start1 === null) return;
let offset: number = patch.start1;
patch.diffs.forEach((diff) => {
const [type, data] = diff;
if (type !== DIFF_DELETE) {
if (type !== DIFF_INSERT) {
if (type === DIFF_EQUAL) {
offset += data.length;
}
} else {
const p: Path = [];
ops.push({
si: data,
p: p.concat([...path], [offset]),
});
}
} else {
const p: Path = [];
ops.unshift({
sd: data,
p: p.concat([...path], [offset]),
});
}
});
});
return ops;
}
/**
* 生成属性ops
* @param id
* @param oldAttributes
* @param path
* @param newAttributes
* @returns
*/
handleAttributes(
id: string,
beginIndex: number,
path: Path,
oldAttributes: Record<string, any>,
newAttributes: Record<string, any>,
) {
const ops: TargetOp[] = [];
const oId = id === 'root' ? '' : id;
const oBi = id === 'root' ? -1 : beginIndex;
Object.keys(newAttributes).forEach((key) => {
const newAttr = newAttributes[key];
const newPath = [...path, JSON0_INDEX.ATTRIBUTE, key];
// 旧属性没有,新增属性
if (!oldAttributes.hasOwnProperty(key)) {
if (newAttr !== oldAttributes[key]) {
ops.push({
id: oId,
bi: oBi,
p: newPath,
oi: newAttr,
});
return;
}
}
const oldAttr = oldAttributes[key];
// 旧属性有,修改属性
if (newAttr !== oldAttr) {
ops.push({
id: oId,
bi: oBi,
p: newPath,
od: oldAttr,
oi: newAttr,
});
}
});
Object.keys(oldAttributes).forEach((key) => {
// 旧属性有,新增没有,删除
if (!newAttributes.hasOwnProperty(key)) {
ops.push({
id: oId,
bi: oBi,
p: path.concat(JSON0_INDEX.ATTRIBUTE, key),
od: oldAttributes[key],
});
}
});
return ops;
}
/**
* 处理新数据只有一行文本的时候
* @param id
* @param path
* @param newText
* @param oldValue
* @returns
*/
handleFirstLineText = (
id: string,
beginIndex: number,
path: Path,
newText: string,
oldChildren: any[],
) => {
const ops: TargetOp[] = [];
const oldText = oldChildren[0];
const isText = typeof oldText === 'string';
const oId = id === 'root' ? '' : id;
const oBi = id === 'root' ? -1 : beginIndex;
// 都是文本
if (isText) {
if (newText !== oldText) {
const tOps = this.textToOps(path, oldText, newText);
for (let i = 0; i < tOps.length; i++) {
ops.push(
Object.assign({}, tOps[i], {
id: oId,
bi: oBi,
}),
);
}
}
}
for (let c = oldChildren.length - 1; c >= (isText ? 1 : 0); c--) {
const oldChild = oldChildren[c];
const newPath = path.concat();
newPath[newPath.length - 1] = c + JSON0_INDEX.ELEMENT;
ops.push({
id: oId,
bi: oBi,
p: newPath,
ld: oldChild,
});
}
if (!isText)
ops.push({
id: oId,
bi: oBi,
p: path,
li: newText,
});
return ops;
};
isLoadingCard = (child: any) => {
if (
child.length > JSON0_INDEX.ATTRIBUTE &&
!Array.isArray(child[1]) &&
typeof child[1] === 'object'
) {
const attributes = child[JSON0_INDEX.ATTRIBUTE];
const cardKey = attributes[CARD_KEY];
const cardType = attributes[CARD_TYPE_KEY];
const dataId = attributes[DATA_ID];
if (cardKey && cardType && dataId) {
const cardNode = this.engine.container
.get<Element>()
?.querySelector(`[${DATA_ID}="${dataId}"]`);
if (cardNode?.getAttribute(CARD_LOADING_KEY)) {
return true;
}
}
}
return false;
};
handleChildren = (
id: string,
beginIndex: number,
path: Path,
oldChildren: any[],
newChildren: any[],
) => {
const ops: TargetOp[] = [];
const oId = id === 'root' ? '' : id;
const oBi = id === 'root' ? -1 : beginIndex;
if (this.isLoadingCard(newChildren)) return [];
// 2.1 旧节点没有子节点数据
if (oldChildren.length === 0) {
// 全部插入
for (let c = 0; c < newChildren.length; c++) {
ops.push({
id,
bi: oBi,
p: path.concat(c + JSON0_INDEX.ELEMENT),
li: newChildren[c],
});
}
}
// 2.2 旧节点有子节点数据
else {
// 2.2.1 新节点没有子节点数据
if (newChildren.length === 0) {
// 全部删除
for (let c = oldChildren.length - 1; c >= 0; c--) {
ops.push({
id: oId,
bi: oBi,
p: path.concat(c + JSON0_INDEX.ELEMENT),
ld: oldChildren[c],
});
}
}
// 2.2.2 新节点有子节点数据,并且是字符
else if (
newChildren.length === 1 &&
typeof newChildren[0] === 'string'
) {
ops.push(
...this.handleFirstLineText(
id,
oBi,
path.concat(JSON0_INDEX.ELEMENT),
newChildren[0],
oldChildren,
),
);
}
// 2.2.3 新节点有子节点数据,并且不是字符
else {
// 2.2.3.1 如果子节点都有 id,则比较 id
if (
newChildren.every((child) =>
Array.isArray(child)
? child[JSON0_INDEX.ATTRIBUTE][DATA_ID]
: false,
) &&
oldChildren.every((child) =>
Array.isArray(child)
? child[JSON0_INDEX.ATTRIBUTE][DATA_ID]
: false,
)
) {
// 先找出需要删除的旧节点
for (let c = oldChildren.length - 1; c >= 0; c--) {
const oldChild = oldChildren[c];
const newChild = newChildren.find(
(child) =>
child[JSON0_INDEX.ATTRIBUTE][DATA_ID] ===
oldChild[JSON0_INDEX.ATTRIBUTE][DATA_ID],
);
if (!newChild) {
ops.push({
id: oId,
bi: oBi,
p: path.concat(c + JSON0_INDEX.ELEMENT),
ld: oldChild,
});
oldChildren.splice(c, 1);
}
}
// 再找出需要插入的新节点
for (let c = 0; c < newChildren.length; c++) {
const newChild = newChildren[c];
const oldChild = oldChildren.find(
(child) =>
child[JSON0_INDEX.ATTRIBUTE][DATA_ID] ===
newChild[JSON0_INDEX.ATTRIBUTE][DATA_ID],
);
if (!oldChild) {
ops.push({
id,
bi: oBi,
p: path.concat(c + JSON0_INDEX.ELEMENT),
li: newChild,
});
oldChildren.splice(c, 0, newChild);
}
// 对比有差异的子节点
else if (!isEqual(newChild, oldChild)) {
// 比较属性
const newAttributes = newChild[
JSON0_INDEX.ATTRIBUTE
] as Record<string, any>;
const oldAttributes = oldChild[
JSON0_INDEX.ATTRIBUTE
] as Record<string, any>;
const newPath = path.concat(
c + JSON0_INDEX.ELEMENT,
);
ops.push(
...this.handleAttributes(
id,
oBi,
newPath,
oldAttributes,
newAttributes,
),
);
// 过滤掉正在渲染的卡片,不再遍历子节点
if (this.isLoadingCard(newChild)) continue;
// 比较子节点
ops.push(
...this.handleChildren(
id,
oBi,
newPath,
oldChild.slice(JSON0_INDEX.ELEMENT),
newChild.slice(JSON0_INDEX.ELEMENT),
),
);
}
}
}
// 2.2.3.2 如果子节点都没有 id,则先删后插
else {
// 删除多余的旧节点
if (oldChildren.length > newChildren.length) {
for (
let c = oldChildren.length - 1;
c >= newChildren.length;
c--
) {
ops.push({
id: oId,
bi: oBi,
p: path.concat(c + JSON0_INDEX.ELEMENT),
ld: oldChildren[c],
});
}
}
// 对比节点是替换还是插入
for (let c = 0; c < newChildren.length; c++) {
const newChild = newChildren[c];
const oldChild = oldChildren[c];
// 没有旧节点,就插入
if (!oldChild) {
ops.push({
id,
bi: oBi,
p: path.concat(c + JSON0_INDEX.ELEMENT),
li: newChild,
});
} else if (!isEqual(newChild, oldChild)) {
// 如果是一样的标签和一样的类型,则比较属性和子节点
if (
typeof newChild !== 'string' &&
typeof newChild === typeof oldChild &&
newChild[JSON0_INDEX.TAG_NAME] ===
oldChild[JSON0_INDEX.TAG_NAME]
) {
// 比较属性
const newAttributes = newChild[
JSON0_INDEX.ATTRIBUTE
] as Record<string, any>;
const oldAttributes = oldChild[
JSON0_INDEX.ATTRIBUTE
] as Record<string, any>;
const newPath = path.concat(
c + JSON0_INDEX.ELEMENT,
);
ops.push(
...this.handleAttributes(
id,
oBi,
newPath,
oldAttributes,
newAttributes,
),
);
// 过滤掉正在渲染的卡片,不再遍历子节点
if (this.isLoadingCard(newChild)) continue;
// 比较子节点
ops.push(
...this.handleChildren(
id,
oBi,
newPath,
oldChild.slice(JSON0_INDEX.ELEMENT),
newChild.slice(JSON0_INDEX.ELEMENT),
),
);
} else {
// 直接替换旧节点
ops.push({
id: oId,
bi: oBi,
p: path.concat(c + JSON0_INDEX.ELEMENT),
ld: oldChild,
});
ops.push({
id,
bi: oBi,
p: path.concat(c + JSON0_INDEX.ELEMENT),
li: newChild,
});
}
}
}
}
}
}
return ops;
};
/**
* 处理DOM节点变更记录
* @param records 记录集合
*/
handleMutations(records: MutationRecord[]) {
let targetRoots: Element[] = [];
const data = this.doc?.data;
if (!data || records.length === 0) return;
if (data.length === 0) {
targetRoots.push(this.engine.container.get<Element>()!);
} else {
for (let r = 0; r < records.length; r++) {
const record = records[r];
if (!record) continue;
const { type } = record;
let target: Node | null = record.target;
// 根节点直接跳出
const isRT = target instanceof Element && isRoot(target);
// 根节点属性变化不处理
if (
type === 'attributes' &&
((record.attributeName &&
isTransientAttribute(target, record.attributeName)) ||
isRT)
) {
continue;
}
if (target instanceof Text) target = target.parentElement;
if (
!target ||
!target.isConnected ||
!(target instanceof Element) ||
isTransientElement(target)
)
continue;
if (isRT) {
targetRoots = [target];
break;
}
// 判断不能是已有的节点或者已有节点的子节点
if (
targetRoots.length === 0 ||
(!targetRoots.includes(target) &&
targetRoots.every((root) => !root.contains(target)))
) {
let len = targetRoots.length;
for (let t = 0; t < len; t++) {
// 如果当前节点包含已有的节点就把已有的节点删除
if (target.contains(targetRoots[t])) {
targetRoots.splice(t, 1);
len--;
t--;
}
}
targetRoots.push(target);
}
}
}
if (targetRoots.length === 0) return;
const ops: TargetOp[] = [];
targetRoots.forEach((root) => {
ops.push(...this.diff(root, data));
});
if (ops.length > 0) {
this.emit('ops', ops);
}
}
diff(root: Element, data: any = this.doc?.data || []) {
const ops: TargetOp[] = [];
if (!root.isConnected) return [];
let id = isRoot(root) ? 'root' : root.getAttribute(DATA_ID);
if (!id) {
const cRoot = this.engine.block
.closest($(root), (node) => !!node.attributes(DATA_ID))
.get<Element>();
if (!(cRoot instanceof Element)) return [];
root = cRoot;
id = root.getAttribute(DATA_ID);
}
if (!id) return [];
const newJson = toJSON0(root) as any[];
if (!newJson) return [];
const isRootId = id === 'root';
const oldValue = isRootId
? data
: findFromDoc(data, (attributes) => attributes[DATA_ID] === id);
if (!oldValue) return [];
// 比较新旧数据
const { path } = oldValue;
// 1. 根节点属性变更
if (id !== 'root') {
const newAttributes = newJson[JSON0_INDEX.ATTRIBUTE] as Record<
string,
any
>;
const oldAttributes = oldValue.attributes;
ops.push(
...this.handleAttributes(
id,
path.length,
path,
oldAttributes,
newAttributes,
),
);
}
if (this.isLoadingCard(newJson)) return ops;
// 2. 子节点变更
const newChildren = newJson.slice(2);
const oldChildren = Array.isArray(oldValue)
? oldValue.slice(2)
: oldValue.children;
ops.push(
...this.handleChildren(
isRootId ? '' : id,
isRootId ? -1 : path.length,
path ?? [],
oldChildren,
newChildren,
),
);
return ops;
}
/**
* 从 doc 中查找目标卡片
* @param data
* @param name
* @param callback
* @returns 返回卡片属性,以及是否已渲染
*/
findCardForDoc = (
data: any,
name: string,
callback?: (attributes: { [key: string]: string }) => boolean,
): { attributes: any; rendered: boolean } | void => {
const result = findFromDoc(data, (attributes) => {
if (attributes['data-card-key'] === name) {
if (callback) {
return callback(attributes);
}
return true;
}
return false;
});
if (result) {
const { attributes, children } = result;
return {
attributes,
rendered:
Array.isArray(children) &&
Array.isArray(children[2]) &&
Array.isArray(children[2][2]),
};
}
};
} | the_stack |
"use strict";
// uuid: e27ba4bb-dcde-4cb8-8b9e-f67a989ed33a
// ------------------------------------------------------------------------
// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
// Licensed under the MIT License+uuid License. See License.txt for details
// ------------------------------------------------------------------------
// Implements a list of built-in functions
/** @module end-user | The lines bellow convey information for the end-user */
/**
* ## Description
*
* A **function** transforms zero or more textual or numerical parameters
* into another value.
* Functions are used inside an expression, and support remote rendering.
* The user can create its own custom functions but only built-in functions
* and official plugins can create functions that support [teleportation](teleporter.md).
*
* ## Core functions
* **WARNING!** In the ABeamer 2.x these core functions will move `core-functions` plugin.
* To prevent breaking changes include now the js script `core-functions.js` on the html file.
*
* ABeamer has the following core functions:
*
* - `sin` - 'sine' trigonometric function.
* - `cos` - 'cosine' trigonometric function.
* - `tan` - 'tangent' trigonometric function.
*
* - `exp` - 2^x
* - `log` - ln
* - `log10` - base 10 logarithm.
*
* - `abs` - absolute value.
* - `sign` - sign function `v != 0 ? v / |v| : 0`.
*
* - `random` - random number between [0, 1].
* - `ceil`- always rounds up.
* - `floor`- always rounds down.
* - `sqrt` - square root.
* - `round` - round to the nearest integer value.
* - `downRound` - similar to round, but it guaranties that if fractional
* part is 0.5, it will always round down.
*
* - `toNumber` - converts a textual parameter into a numerical parameter.
* - `toString` - converts a numerical parameter into a textual parameter.
*
* - `uppercase` - returns the uppercase of the textual parameter.
* - `lowercase` - returns the lowercase of the textual parameter.
* - `capitalize` -returns the uppercase of the first letter of each word
* - `substr` - returns the a section of the 1st parameter.
* The 2nd parameter is the start value and the 3rd parameter is the length.
* If the 3rd parameter is less than 0, than is considered until the end.
*
* - `iff` - if the 1st numerical parameter is different from 0,
* it returns the 2nd parameter, otherwise it returns the 3rd paramter.
* This function doesn't supports [lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation).
*
* - `case` - the 1st numerical parameter is a zero index to select which
* parameters to return.
* This function doesn't supports [lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation).
*
* - `get` - returns the numerical N-value of a 0-base array.
*
* - `slice` - returns a subarray starting from `start` to `end-1` of a 0-base array.
*
* ## Examples
*
* @example = substr('ABeamer', 4, 4)
* @example = round(12.4)
* @example = get([10,30,15],1)
* it returns `30`
* @example = slice([10,30,15,40],1, 3)
* it returns `[30, 15]`
*
* ## Arrays
*
* Since ABeamer 1.6 that single numerical argument functions also support arrays.
* The operation is perform for each element, and it returns an array.
* The array functions can be composed.
*
* @example = round(sqrt([12.4, 75, 10]))
*
*/
namespace ABeamer {
// #generate-group-section
// ------------------------------------------------------------------------
// Functions
// ------------------------------------------------------------------------
// The following section contains data for the end-user
// generated by `gulp build-definition-files`
// -------------------------------
// #export-section-start: release
export const enum ExFuncParamType {
Any,
Number,
String,
Array,
}
export interface ExFuncParam {
paType?: ExFuncParamType;
sValue?: string;
numValue?: number;
arrayValue?: number[];
}
export type _CheckParamFunc = (req: ExFuncReq, paramCount: uint,
paramTypes?: ExFuncParamType[]) => void;
export interface ExFuncReq {
args: ABeamerArgs;
req?: ExFuncReq;
res?: ExFuncParam;
checkParams: _CheckParamFunc;
}
export type ExprFuncParams = ExFuncParam[];
export type ExFunction = (params: ExprFuncParams, req?: ExFuncReq) => void;
// #export-section-end: release
// -------------------------------
export const _exFunctions: { [name: string]: ExFunction } = {};
// ------------------------------------------------------------------------
// Built-in functions
// ------------------------------------------------------------------------
/**
* Generic handler for math functions that have 1 numerical input
* and 1 numerical output.
*/
function _math1ParamFunc(params: ExprFuncParams, req: ExFuncReq,
f: (param1: number) => number) {
arrayInputHelper(params, req, 1, undefined, f);
}
/**
* Generic handler for string functions that have 1 textual input
* and 1 textual output.
*/
function _str1ParamFunc(params: ExprFuncParams, req: ExFuncReq,
f: (param1: string) => string) {
req.checkParams(req, 1, [ExFuncParamType.String]);
req.res.paType = ExFuncParamType.String;
req.res.sValue = f(params[0].sValue);
}
_exFunctions['sin'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, Math.sin);
};
_exFunctions['cos'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, Math.cos);
};
_exFunctions['tan'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, Math.tan);
};
_exFunctions['round'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, Math.round);
};
_exFunctions['downRound'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, downRound);
};
_exFunctions['ceil'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, Math.ceil);
};
_exFunctions['floor'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, Math.floor);
};
_exFunctions['sqrt'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, Math.sqrt);
};
_exFunctions['exp'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, Math.exp);
};
_exFunctions['log'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, Math.log);
};
_exFunctions['log10'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, Math.log10);
};
_exFunctions['abs'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, Math.abs);
};
_exFunctions['sign'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_math1ParamFunc(params, req, (v: number) => v < 0 ? -1 : (v > 0 ? 1 : 0));
};
_exFunctions['random'] = (_params: ExprFuncParams, req?: ExFuncReq) => {
req.checkParams(req, 0);
req.res.paType = ExFuncParamType.Number;
req.res.numValue = Math.random();
};
_exFunctions['toNumber'] = (params: ExprFuncParams, req?: ExFuncReq) => {
req.checkParams(req, 1, [ExFuncParamType.String]);
req.res.paType = ExFuncParamType.Number;
req.res.numValue = parseFloat(params[0].sValue);
};
// @ts-ignore TypeScript bug :-(
_exFunctions['toString'] = (params: ExprFuncParams, req?: ExFuncReq) => {
req.checkParams(req, 1, [ExFuncParamType.Number]);
req.res.paType = ExFuncParamType.String;
req.res.sValue = params[0].numValue.toString();
};
_exFunctions['uppercase'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_str1ParamFunc(params, req, (s) => s.toUpperCase());
};
_exFunctions['lowercase'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_str1ParamFunc(params, req, (s) => s.toUpperCase());
};
_exFunctions['capitalize'] = (params: ExprFuncParams, req?: ExFuncReq) => {
_str1ParamFunc(params, req, (s) => s.replace(/\b(\w)/, (_all, p) => p.toUpperCase()));
};
_exFunctions['substr'] = (params: ExprFuncParams, req?: ExFuncReq) => {
req.checkParams(req, 3, [ExFuncParamType.String, ExFuncParamType.Number, ExFuncParamType.Number]);
req.res.paType = ExFuncParamType.String;
req.res.sValue = params[0].sValue.substr(params[1].numValue,
params[2].numValue < 0 ? undefined : params[2].numValue);
};
_exFunctions['iff'] = (params: ExprFuncParams, req?: ExFuncReq) => {
req.checkParams(req, 3, [ExFuncParamType.Number, ExFuncParamType.Any, ExFuncParamType.Any]);
const res = params[params[0].numValue ? 1 : 2];
req.res.paType = res.paType;
req.res.sValue = res.sValue;
req.res.numValue = res.numValue;
};
_exFunctions['case'] = (params: ExprFuncParams, req?: ExFuncReq) => {
// @TODO: check params
const res = params[Math.round(params[0].numValue) + 1];
req.res.paType = res.paType;
req.res.sValue = res.sValue;
req.res.numValue = res.numValue;
};
_exFunctions['get'] = (params: ExprFuncParams, req?: ExFuncReq) => {
req.checkParams(req, 2, [ExFuncParamType.Array, ExFuncParamType.Number]);
const index = Math.round(params[1].numValue);
const arr = params[0].arrayValue;
if (index < 0 || index >= arr.length) {
throwErr('Invalid indexing');
}
req.res.paType = ExFuncParamType.Number;
req.res.numValue = arr[index];
};
_exFunctions['slice'] = (params: ExprFuncParams, req?: ExFuncReq) => {
req.checkParams(req, 3, [ExFuncParamType.Array, ExFuncParamType.Number, ExFuncParamType.Number]);
const start = Math.round(params[1].numValue);
const end = Math.round(params[2].numValue);
const arr = params[0].arrayValue;
if (start < 0 || start >= arr.length || end < 0 || end >= arr.length) {
throwErr('Invalid indexing');
}
req.res.paType = ExFuncParamType.Array;
req.res.arrayValue = arr.slice(start, end);
};
} | the_stack |
import { renderHook, act } from '@testing-library/react-hooks';
import { cleanup } from '@testing-library/react';
import { useStateful } from './useStateful';
import { useNumber } from './useNumber';
import { useArray } from './useArray';
import { useBoolean } from './useBoolean';
import { useInput } from './useInput';
import { useSetState } from './useSetState';
import { useMap } from './useMap';
import { useSet } from './useSet';
afterEach(cleanup);
describe('useStateful', () => {
it('should change value', () => {
const { result } = renderHook(() => useStateful('initial'));
expect(result.current.value).toBe('initial');
act(() => result.current.setValue('changed'));
expect(result.current.value).toBe('changed');
});
});
describe('useNumber', () => {
it('should increase value with concrete value', () => {
// given
const { result } = renderHook(() => useNumber(5));
const { increase } = result.current;
// when
act(() => increase(5));
// then
expect(result.current.value).toBe(10);
});
it('should increase value with concrete value with respect to upperLimit', () => {
// given
const { result } = renderHook(() => useNumber(5, { upperLimit: 10 }));
const { increase } = result.current;
// when
act(() => increase(10));
// then
expect(result.current.value).toBe(10);
});
it('should increase value by default step', () => {
// given
const { result } = renderHook(() => useNumber(5));
const { increase } = result.current;
// when
act(() => increase());
// then
expect(result.current.value).toBe(6);
});
it('should increase value by default step with respect to upperLimit', () => {
// given
const { result } = renderHook(() => useNumber(5, { upperLimit: 5 }));
const { increase } = result.current;
// when
act(() => increase());
// then
expect(result.current.value).toBe(5);
});
it('should increase value by predefined step', () => {
// given
const { result } = renderHook(() => useNumber(5, { step: 3 }));
const { increase } = result.current;
// when
act(() => increase());
// then
expect(result.current.value).toBe(8);
});
it('should increase value by predefined step with respect to upperLimit', () => {
// given
const { result } = renderHook(() => useNumber(5, { step: 3, upperLimit: 7 }));
const { increase } = result.current;
// when
act(() => increase());
// then
expect(result.current.value).toBe(7);
});
it('should decrease value with concrete value with', () => {
// given
const { result } = renderHook(() => useNumber(5));
const { decrease } = result.current;
// when
act(() => decrease(5));
// then
expect(result.current.value).toBe(0);
});
it('should decrease value with concrete value with respect to lowerLimit', () => {
// given
const { result } = renderHook(() => useNumber(5, { lowerLimit: 0 }));
const { decrease } = result.current;
// when
act(() => decrease(10));
// then
expect(result.current.value).toBe(0);
});
it('should decrease value by default step', () => {
// given
const { result } = renderHook(() => useNumber(5));
const { decrease } = result.current;
// when
act(() => decrease());
// then
expect(result.current.value).toBe(4);
});
it('should decrease value by default step with respect to lowerLimit', () => {
// given
const { result } = renderHook(() => useNumber(5, { lowerLimit: 5 }));
const { decrease } = result.current;
// when
act(() => decrease());
// then
expect(result.current.value).toBe(5);
});
it('should decrease value by predefined step', () => {
// given
const { result } = renderHook(() => useNumber(5, { step: 3 }));
const { decrease } = result.current;
// when
act(() => decrease());
// then
expect(result.current.value).toBe(2);
});
it('should decrease value by predefined step with respect to lowerLimit', () => {
// given
const { result } = renderHook(() => useNumber(5, { step: 3, lowerLimit: 3 }));
const { decrease } = result.current;
// when
act(() => decrease());
// then
expect(result.current.value).toBe(3);
});
describe('hooks optimizations', () => {
it('should keep actions reference equality after value change', () => {
// given
const { result } = renderHook(() => useNumber(5));
const { increase } = result.current;
expect(result.current.increase).toBe(increase);
// when
act(() => increase(5));
// then
expect(increase).toBe(result.current.increase);
});
});
});
describe('useInput', () => {
describe('hooks optimizations', () => {
it('should keep actions reference equality after value change', () => {
// given
const { result } = renderHook(() => useInput(5));
const { setValue } = result.current;
expect(result.current.setValue).toBe(setValue);
// when
act(() => setValue('1'));
// then
expect(setValue).toBe(result.current.setValue);
});
});
});
describe('useSetState', () => {
it('should change and merge state', () => {
type State = {
field: number;
field2: number;
field3?: number;
};
const { result } = renderHook(() => useSetState<State>({ field: 1, field2: 2 }));
const { setState } = result.current;
expect(result.current.state).toEqual({ field: 1, field2: 2 });
act(() => setState({ field: 2, field3: 3 }));
expect(result.current.state).toEqual({ field: 2, field2: 2, field3: 3 });
});
it('should reset state to initial state', () => {
type State = {
field: number;
field2: number;
field3?: number;
};
const { result } = renderHook(() => useSetState<State>({ field: 1, field2: 2 }));
const { setState, resetState } = result.current;
expect(result.current.state).toEqual({ field: 1, field2: 2 });
act(() => setState({ field: 2, field3: 3 }));
expect(result.current.state).toEqual({ field: 2, field2: 2, field3: 3 });
act(() => resetState());
expect(result.current.state).toEqual({ field: 1, field2: 2 });
});
describe('hooks optimizations', () => {
it('should keep actions reference equality after value change', () => {
// given
const { result } = renderHook(() => useSetState<{}>({}));
const { setState, resetState } = result.current;
expect(result.current.setState).toBe(setState);
// when
act(() => setState([1]));
// then
expect(setState).toBe(result.current.setState);
// when
act(() => resetState());
// then
expect(resetState).toBe(result.current.resetState);
});
});
});
describe('useArray', () => {
it('should push item', () => {
const { result } = renderHook(() => useArray<string>([]));
const { push } = result.current;
expect(result.current.value.length).toBe(0);
act(() => {
push('test');
});
expect(result.current.value.length).toBe(1);
});
it('should remove item by index', () => {
const { result } = renderHook(() => useArray(['test', 'test1', 'test2']));
const { removeIndex } = result.current;
expect(result.current.value.length).toBe(3);
act(() => removeIndex(1));
expect(result.current.value.length).toBe(2);
expect(result.current.value[1]).toBe('test2');
});
it('should remove item by id', () => {
const { result } = renderHook(() => useArray([{ id: 1 }, { id: 2 }]));
const { removeById } = result.current;
expect(result.current.value.length).toBe(2);
act(() => removeById(2));
expect(result.current.value.length).toBe(1);
});
it('should modify item by id', () => {
const { result } = renderHook(() =>
useArray([
{ id: 1, foo: true },
{ id: 2, foo: false },
]),
);
const { modifyById } = result.current;
expect(result.current.value.length).toBe(2);
act(() => modifyById(2, { foo: true }));
const modifiedElement = result.current.value.find(
(element: { id: number; foo: boolean }) => element.id === 2,
);
expect(modifiedElement?.foo).toBe(true);
});
it('should clear the array', () => {
const { result } = renderHook(() => useArray([1, 2, 3, 4, 5]));
const { clear } = result.current;
expect(result.current.value.length).toBe(5);
act(() => clear());
expect(result.current.value.length).toBe(0);
});
it('should change array', () => {
const { result } = renderHook(() => useArray([1, 2, 3, 4, 5]));
const { setValue } = result.current;
expect(result.current.value.length).toBe(5);
act(() => setValue((it) => [...it, 6]));
expect(result.current.value.length).toBe(6);
expect(result.current.value[5]).toBe(6);
});
it.each`
from | to | expected
${3} | ${0} | ${[4, 1, 2, 3, 5]}
${-1} | ${0} | ${[5, 1, 2, 3, 4]}
${1} | ${-2} | ${[1, 3, 4, 2, 5]}
${-3} | ${-4} | ${[1, 3, 2, 4, 5]}
`('should move items in the array from: $from to: $to expected: $expected', ({ from, to, expected }) => {
const { result } = renderHook(() => useArray([1, 2, 3, 4, 5]));
const { move } = result.current;
expect(result.current.value).toEqual([1, 2, 3, 4, 5]);
act(() => move(from, to));
expect(result.current.value).toEqual(expected);
});
describe('hooks optimizations', () => {
it('should keep actions reference equality after value change', () => {
// given
const { result } = renderHook(() => useArray<any>([]));
const { push } = result.current;
expect(result.current.push).toBe(push);
// when
act(() => {
push(1);
});
// then
expect(push).toBe(result.current.push);
});
});
});
describe('useBoolean', () => {
it('should set true', () => {
const { result } = renderHook(() => useBoolean(false));
const { setTrue } = result.current;
expect(result.current.value).toBe(false);
act(() => setTrue());
expect(result.current.value).toBe(true);
});
it('should set false', () => {
const { result } = renderHook(() => useBoolean(true));
const { setFalse } = result.current;
expect(result.current.value).toBe(true);
act(() => setFalse());
expect(result.current.value).toBe(false);
});
it('should toggle', () => {
const { result } = renderHook(() => useBoolean(true));
const { toggle } = result.current;
expect(result.current.value).toBe(true);
act(() => toggle());
expect(result.current.value).toBe(false);
act(() => toggle());
expect(result.current.value).toBe(true);
});
describe('hooks optimizations', () => {
it('should keep actions reference equality after value change', () => {
// given
const { result } = renderHook(() => useBoolean(true));
const { setFalse } = result.current;
expect(result.current.setFalse).toBe(setFalse);
// when
act(() => setFalse());
// then
expect(setFalse).toBe(result.current.setFalse);
});
});
});
describe('useSet', () => {
const initial = new Set([1, 2, 3]);
describe('hooks optimizations', () => {
it('should change value reference equality after change', () => {
// given
const { result } = renderHook(() => useSet<number>());
const value = result.current;
// when
act(() => value.setValue(initial));
// then
expect(value).not.toBe(result.current);
});
it('should keep actions reference equality after value change', () => {
// given
const { result } = renderHook(() => useSet<number>());
const { setValue } = result.current;
expect(result.current.setValue).toBe(setValue);
// when
act(() => setValue(new Set([1, 1])));
// then
expect(setValue).toBe(result.current.setValue);
});
});
});
describe('useMap', () => {
describe('set', () => {
it('should update old value', () => {
// given
const { result } = renderHook(() => useMap<number, string>([[1, 'default']]));
const { set } = result.current;
expect(result.current.value.get(1)).toBe('default');
// when
act(() => set(1, 'changed'));
// then
expect(result.current.value.get(1)).toBe('changed');
});
it('should add new value', () => {
// given
const { result } = renderHook(() => useMap<number, string>());
const { set } = result.current;
expect(result.current.value.get(1)).toBeUndefined();
// when
act(() => set(1, 'added'));
// then
expect(result.current.value.get(1)).toBe('added');
});
});
describe('delete', () => {
it('should delete existing value', () => {
// given
const { result } = renderHook(() => useMap<number, string>([[1, 'existing']]));
const { delete: aDelete } = result.current;
expect(result.current.value.get(1)).toBe('existing');
// when
act(() => aDelete(1));
// then
expect(result.current.value.get(1)).toBeUndefined();
});
});
describe('initialize', () => {
it.each`
message | input
${'map'} | ${new Map([[1, 'initialized']])}
${'tuple'} | ${[[1, 'initialized']]}
`('initializes with $message', ({ input }) => {
// given
const { result } = renderHook(() => useMap<number, string>());
const { initialize } = result.current;
expect(result.current.value.get(1)).toBeUndefined();
// when
act(() => initialize(input));
// then
expect(result.current.value.get(1)).toBe('initialized');
});
});
describe('clear', () => {
it('clears the map state and gets values', () => {
// given
const { result } = renderHook(() => useMap<number, string>([[1, 'initialized']]));
const { clear } = result.current;
expect(result.current.value.get(1)).toBe('initialized');
// when
act(() => clear());
// then
expect(result.current.value.get(1)).toBeUndefined();
});
});
describe('hooks optimizations', () => {
it('should change value reference equality after change', () => {
// given
const { result } = renderHook(() => useMap<number, number>());
const { value, set } = result.current;
expect(result.current.value).toBe(value);
// when
act(() => set(1, 1));
// then
expect(value).not.toBe(result.current.value);
expect(value.get(1)).toBeUndefined();
expect(result.current.value.get(1)).toBe(1);
});
it('should keep actions reference equality after value change', () => {
// given
const { result } = renderHook(() => useMap<number, number>());
const { set } = result.current;
expect(result.current.set).toBe(set);
// when
act(() => set(1, 1));
// then
expect(set).toBe(result.current.set);
});
});
}); | the_stack |
module RongIMLib {
export class RongIMEmoji {
static emojis: any[] = [];
private static emojiFactory: { [s: string]: any } = {
"u1F600": { "en": "grinning", "zh": "\u5927\u7B11", "tag": "\uD83D\uDE00", "bp": "0px 0px" },
"u1F601": { "en": "grin", "zh": "\u9732\u9F7F\u800C\u7B11", "tag": "\uD83D\uDE01", "bp": "-25px 0px" },
"u1F602": { "en": "joy", "zh": "\u6B22\u4E50", "tag": "\uD83D\uDE02", "bp": "-50px 0px" },
"u1F603": { "en": "smile", "zh": "\u5FAE\u7B11", "tag": "\uD83D\uDE03", "bp": "-75px 0px" },
"u1F605": { "en": "sweat_smile", "zh": "\u8D54\u7B11", "tag": "\uD83D\uDE05", "bp": "-100px 0px" },
"u1F606": { "en": "satisfied", "zh": "\u6EE1\u610F", "tag": "\uD83D\uDE06", "bp": "-125px 0px" },
"u1F607": { "en": "innocent", "zh": "\u65E0\u8F9C", "tag": "\uD83D\uDE07", "bp": "-150px 0px" },
"u1F608": { "en": "smiling_imp", "zh": "\u574F\u7B11", "tag": "\uD83D\uDE08", "bp": "-175px 0px" },
"u1F609": { "en": "wink", "zh": "\u7728\u773C", "tag": "\uD83D\uDE09", "bp": "-200px 0px" },
"u1F611": { "en": "expressionless", "zh": "\u9762\u65E0\u8868\u60C5", "tag": "\uD83D\uDE11", "bp": "-225px 0px" },
"u1F612": { "en": "unamused", "zh": "\u4E00\u8138\u4E0D\u5FEB", "tag": "\uD83D\uDE12", "bp": "-250px 0px" },
"u1F613": { "en": "sweat", "zh": "\u6C57", "tag": "\uD83D\uDE13", "bp": "-275px 0px" },
"u1F614": { "en": "pensive", "zh": "\u54C0\u601D", "tag": "\uD83D\uDE14", "bp": "-300px 0px" },
"u1F615": { "en": "confused", "zh": "\u8FF7\u832B", "tag": "\uD83D\uDE15", "bp": "-325px 0px" },
"u1F616": { "en": "confounded", "zh": "\u56F0\u60D1\u7684", "tag": "\uD83D\uDE16", "bp": "-350px 0px" },
"u1F618": { "en": "kissing_heart", "zh": "\u4EB2\u4E00\u4E2A", "tag": "\uD83D\uDE18", "bp": "-375px 0px" },
"u1F621": { "en": "rage", "zh": "\u6124\u6012", "tag": "\uD83D\uDE21", "bp": "-400px 0px" },
"u1F622": { "en": "cry", "zh": "\u54ED", "tag": "\uD83D\uDE22", "bp": "-2075px 0px" },
"u1F623": { "en": "persevere", "zh": "\u4F7F\u52B2", "tag": "\uD83D\uDE23", "bp": "-450px 0px" },
"u1F624": { "en": "triumph", "zh": "\u751F\u6C14", "tag": "\uD83D\uDE24", "bp": "-475px 0px" },
"u1F628": { "en": "fearful", "zh": "\u53EF\u6015", "tag": "\uD83D\uDE28", "bp": "-500px 0px" },
"u1F629": { "en": "weary", "zh": "\u538C\u5026", "tag": "\uD83D\uDE29", "bp": "-525px 0px" },
"u1F630": { "en": "cold_sweat", "zh": "\u51B7\u6C57", "tag": "\uD83D\uDE30", "bp": "-550px 0px" },
"u1F631": { "en": "scream", "zh": "\u60CA\u53EB", "tag": "\uD83D\uDE31", "bp": "-575px 0px" },
"u1F632": { "en": "astonished", "zh": "\u60CA\u8BB6", "tag": "\uD83D\uDE32", "bp": "-600px 0px" },
"u1F633": { "en": "flushed", "zh": "\u5446\u4F4F", "tag": "\uD83D\uDE33", "bp": "-625px 0px" },
"u1F634": { "en": "sleeping", "zh": "\u7761\u7720", "tag": "\uD83D\uDE34", "bp": "-650px 0px" },
"u1F635": { "en": "dizzy_face", "zh": "\u65AD\u7535\u4E86", "tag": "\uD83D\uDE35", "bp": "-675px 0px" },
"u1F636": { "en": "no_mouth", "zh": "\u65E0\u53E3", "tag": "\uD83D\uDE36", "bp": "-700px 0px" },
"u1F637": { "en": "mask", "zh": "\u75C5\u4E86", "tag": "\uD83D\uDE37", "bp": "-725px 0px" },
"u1F3A4": { "en": "microphone", "zh": "KTV", "tag": "\uD83C\uDFA4", "bp": "-750px 0px" },
"u1F3B2": { "en": "game_die", "zh": "\u8272\u5B50", "tag": "\uD83C\uDFB2", "bp": "-775px 0px" },
"u1F3B5": { "en": "musical_note", "zh": "\u97F3\u4E50", "tag": "\uD83C\uDFB5", "bp": "-800px 0px" },
"u1F3C0": { "en": "basketball", "zh": "\u7BEE\u7403", "tag": "\uD83C\uDFC0", "bp": "-825px 0px" },
"u1F3C2": { "en": "snowboarder", "zh": "\u5355\u677F\u6ED1\u96EA", "tag": "\uD83C\uDFC2", "bp": "-850px 0px" },
"u1F3E1": { "en": "house_with_garden", "zh": "\u623F\u5B50", "tag": "\uD83C\uDFE1", "bp": "-875px 0px" },
"u1F004": { "en": "mahjong", "zh": "\u9EBB\u5C06", "tag": "\uD83C\uDC04", "bp": "-900px 0px" },
"u1F4A1": { "en": "bulb", "zh": "\u706F\u6CE1", "tag": "\uD83D\uDCA1", "bp": "-925px 0px" },
"u1F4A2": { "en": "anger", "zh": "\u7206\u7B4B", "tag": "\uD83D\uDCA2", "bp": "-950px 0px" },
"u1F4A3": { "en": "bomb", "zh": "\u70B8\u5F39", "tag": "\uD83D\uDCA3", "bp": "-975px 0px" },
"u1F4A4": { "en": "zzz", "zh": "ZZZ", "tag": "\uD83D\uDCA4", "bp": "-1000px 0px" },
"u1F4A9": { "en": "shit", "zh": "\u72D7\u5C41", "tag": "\uD83D\uDCA9", "bp": "-1025px 0px" },
"u1F4AA": { "en": "muscle", "zh": "\u808C\u8089", "tag": "\uD83D\uDCAA", "bp": "-1050px 0px" },
"u1F4B0": { "en": "moneybag", "zh": "\u94B1\u888B", "tag": "\uD83D\uDCB0", "bp": "-1075px 0px" },
"u1F4DA": { "en": "books", "zh": "\u4E66\u7C4D", "tag": "\uD83D\uDCDA", "bp": "-1100px 0px" },
"u1F4DE": { "en": "telephone_receiver", "zh": "\u7535\u8BDD", "tag": "\uD83D\uDCDE", "bp": "-1125px 0px" },
"u1F4E2": { "en": "loudspeaker", "zh": "\u6269\u97F3\u5668", "tag": "\uD83D\uDCE2", "bp": "-1150px 0px" },
"u1F6AB": { "en": "stop", "zh": "\u505C\u6B62", "tag": "\uD83D\uDEAB", "bp": "-1175px 0px" },
"u1F6BF": { "en": "shower", "zh": "\u6DCB\u6D74", "tag": "\uD83D\uDEBF", "bp": "-1200px 0px" },
"u1F30F": { "en": "earth_asia", "zh": "\u571F", "tag": "\uD83C\uDF0F", "bp": "-1225px 0px" },
"u1F33B": { "en": "sunflower", "zh": "\u5411\u65E5\u8475", "tag": "\uD83C\uDF3B", "bp": "-1250px 0px" },
"u1F35A": { "en": "rice", "zh": "\u996D", "tag": "\uD83C\uDF5A", "bp": "-1275px 0px" },
"u1F36B": { "en": "chocolate_bar", "zh": "\u5DE7\u514B\u529B", "tag": "\uD83C\uDF6B", "bp": "-1300px 0px" },
"u1F37B": { "en": "beers", "zh": "\u5564\u9152", "tag": "\uD83C\uDF7B", "bp": "-1325px 0px" },
"u270A": { "en": "fist", "zh": "\u62F3\u5934", "tag": "\u270A", "bp": "-1350px 0px" },
"u1F44C": { "en": "ok_hand", "zh": "\u6CA1\u95EE\u9898", "tag": "\uD83D\uDC4C", "bp": "-1375px 0px" },
"u1F44D": { "en": "1", "zh": "1", "tag": "\uD83D\uDC4D", "bp": "-1400px 0px" },
"u1F44E": { "en": "-1", "zh": "-1", "tag": "\uD83D\uDC4E", "bp": "-1425px 0px" },
"u1F44F": { "en": "clap", "zh": "\u62CD", "tag": "\uD83D\uDC4F", "bp": "-1450px 0px" },
"u1F46A": { "en": "family", "zh": "\u5BB6\u5EAD", "tag": "\uD83D\uDC6A", "bp": "-1475px 0px" },
"u1F46B": { "en": "couple", "zh": "\u60C5\u4FA3", "tag": "\uD83D\uDC6B", "bp": "-1500px 0px" },
"u1F47B": { "en": "ghost", "zh": "\u9B3C", "tag": "\uD83D\uDC7B", "bp": "-2050px 0px" },
"u1F62C": { "en": "grimacing", "zh": "\u9B3C\u8138", "tag": "\uD83D\uDE2C", "bp": "-1525px 0px" },
"u1F47C": { "en": "angel", "zh": "\u5929\u4F7F", "tag": "\uD83D\uDC7C", "bp": "-1550px 0px" },
"u1F47D": { "en": "alien", "zh": "\u5916\u661F\u4EBA", "tag": "\uD83D\uDC7D", "bp": "-1575px 0px" },
"u1F47F": { "en": "imp", "zh": "\u6076\u9B54", "tag": "\uD83D\uDC7F", "bp": "-1600px 0px" },
"u1F48A": { "en": "pill", "zh": "\u836F", "tag": "\uD83D\uDC8A", "bp": "-1625px 0px" },
"u1F48B": { "en": "kiss", "zh": "\u543B", "tag": "\uD83D\uDC8B", "bp": "-1650px 0px" },
"u1F48D": { "en": "ring", "zh": "\u6212\u6307", "tag": "\uD83D\uDC8D", "bp": "-1675px 0px" },
"u1F52B": { "en": "gun", "zh": "\u67AA", "tag": "\uD83D\uDD2B", "bp": "-1700px 0px" },
"u1F60A": { "en": "blush", "zh": "\u8138\u7EA2", "tag": "\uD83D\uDE0A", "bp": "-1725px 0px" },
"u1F60B": { "en": "yum", "zh": "\u998B", "tag": "\uD83D\uDE0B", "bp": "-1750px 0px" },
"u1F60C": { "en": "relieved", "zh": "\u5B89\u5FC3", "tag": "\uD83D\uDE0C", "bp": "-1775px 0px" },
"u1F60D": { "en": "heart_eyes", "zh": "\u8272\u8272", "tag": "\uD83D\uDE0D", "bp": "-1800px 0px" },
"u1F60E": { "en": "sunglasses", "zh": "\u58A8\u955C", "tag": "\uD83D\uDE0E", "bp": "-1825px 0px" },
"u1F60F": { "en": "smirk", "zh": "\u50BB\u7B11", "tag": "\uD83D\uDE0F", "bp": "-1850px 0px" },
"u1F61A": { "en": "kissing_closed_eyes", "zh": "\u63A5\u543B", "tag": "\uD83D\uDE1A", "bp": "-1875px 0px" },
"u1F61C": { "en": "stuck_out_tongue_winking_eye", "zh": "\u641E\u602A", "tag": "\uD83D\uDE1C", "bp": "-1900px 0px" },
"u1F61D": { "en": "stuck_out_tongue_closed_eyes", "zh": "\u6076\u4F5C\u5267", "tag": "\uD83D\uDE1D", "bp": "-1925px 0px" },
"u1F61E": { "en": "disappointed", "zh": "\u5931\u671B\u7684", "tag": "\uD83D\uDE1E", "bp": "-1950px 0px" },
"u1F61F": { "en": "anguished", "zh": "\u82E6\u6DA9", "tag": "\uD83D\uDE1F", "bp": "-1975px 0px" },
"u1F62A": { "en": "sleepy", "zh": "\u56F0", "tag": "\uD83D\uDE2A", "bp": "-2000px 0px" },
"u1F62B": { "en": "tired_face", "zh": "\u6293\u72C2", "tag": "\uD83D\uDE2B", "bp": "-2025px 0px" },
"u1F62D": { "en": "sob", "zh": "\u54ED\u6CE3", "tag": "\uD83D\uDE2D", "bp": "-425px 0px" },
"u1F62F": { "en": "hushed", "zh": "\u5BC2\u9759", "tag": "\uD83D\uDE2F", "bp": "-2100px 0px" },
"u1F64A": { "en": "speak_no_evil", "zh": "\u4E0D\u8BF4\u8BDD", "tag": "\uD83D\uDE4A", "bp": "-2125px 0px" },
"u1F64F": { "en": "pray", "zh": "\u7948\u7977", "tag": "\uD83D\uDE4F", "bp": "-2150px 0px" },
"u1F319": { "en": "moon", "zh": "\u6708\u4EAE", "tag": "\uD83C\uDF19", "bp": "-2175px 0px" },
"u1F332": { "en": "evergreen_tree", "zh": "\u6811", "tag": "\uD83C\uDF32", "bp": "-2200px 0px" },
"u1F339": { "en": "rose", "zh": "\u73AB\u7470", "tag": "\uD83C\uDF39", "bp": "-2225px 0px" },
"u1F349": { "en": "watermelon", "zh": "\u897F\u74DC", "tag": "\uD83C\uDF49", "bp": "-2250px 0px" },
"u1F356": { "en": "meat_on_bone", "zh": "\u8089", "tag": "\uD83C\uDF56", "bp": "-2275px 0px" },
"u1F366": { "en": "icecream", "zh": "\u51B0\u6DC7\u6DCB", "tag": "\uD83C\uDF66", "bp": "-2300px 0px" },
"u1F377": { "en": "wine_glass", "zh": "\u9152", "tag": "\uD83C\uDF77", "bp": "-2325px 0px" },
"u1F381": { "en": "gift", "zh": "\u793C\u7269", "tag": "\uD83C\uDF81", "bp": "-2350px 0px" },
"u1F382": { "en": "birthday", "zh": "\u751F\u65E5", "tag": "\uD83C\uDF82", "bp": "-2375px 0px" },
"u1F384": { "en": "christmas_tree", "zh": "\u5723\u8BDE", "tag": "\uD83C\uDF84", "bp": "-2400px 0px" },
"u1F389": { "en": "tada", "zh": "\u793C\u82B1", "tag": "\uD83C\uDF89", "bp": "-2425px 0px" },
"u1F393": { "en": "mortar_board", "zh": "\u6BD5\u4E1A", "tag": "\uD83C\uDF93", "bp": "-2450px 0px" },
"u1F434": { "en": "horse", "zh": "\u9A6C", "tag": "\uD83D\uDC34", "bp": "-2475px 0px" },
"u1F436": { "en": "dog", "zh": "\u72D7", "tag": "\uD83D\uDC36", "bp": "-2500px 0px" },
"u1F437": { "en": "pig", "zh": "\u732A", "tag": "\uD83D\uDC37", "bp": "-2525px 0px" },
"u1F451": { "en": "crown", "zh": "\u738B\u51A0", "tag": "\uD83D\uDC51", "bp": "-2550px 0px" },
"u1F484": { "en": "lipstick", "zh": "\u53E3\u7EA2", "tag": "\uD83D\uDC84", "bp": "-2575px 0px" },
"u1F494": { "en": "broken_heart", "zh": "\u4F24\u5FC3", "tag": "\uD83D\uDC94", "bp": "-2600px 0px" },
"u1F525": { "en": "fire", "zh": "\u706B\u4E86", "tag": "\uD83D\uDD25", "bp": "-2625px 0px" },
"u1F556": { "en": "time", "zh": "\u65F6\u95F4", "tag": "\uD83D\uDD56", "bp": "-2650px 0px" },
"u1F648": { "en": "see_no_evil", "zh": "\u4E0D\u770B", "tag": "\uD83D\uDE48", "bp": "-2675px 0px" },
"u1F649": { "en": "hear_no_evil", "zh": "\u4E0D\u542C", "tag": "\uD83D\uDE49", "bp": "-2700px 0px" },
"u1F680": { "en": "rocket", "zh": "\u706B\u7BAD", "tag": "\uD83D\uDE80", "bp": "-2725px 0px" },
"u2B50": { "en": "star", "zh": "\u661F\u661F", "tag": "\u2B50", "bp": "-2750px 0px" },
"u23F0": { "en": "alarm_clock", "zh": "\u949F\u8868", "tag": "\u23F0", "bp": "-2775px 0px" },
"u23F3": { "en": "hourglass_flowing_sand", "zh": "\u6C99\u6F0F", "tag": "\u23F3", "bp": "-2800px 0px" },
"u26A1": { "en": "zap", "zh": "\u95EA\u7535", "tag": "\u26A1", "bp": "-2825px 0px" },
"u26BD": { "en": "soccer", "zh": "\u8DB3\u7403", "tag": "\u26BD", "bp": "-2850px 0px" },
"u26C4": { "en": "snowman", "zh": "\u96EA\u4EBA", "tag": "\u26C4", "bp": "-2875px 0px" },
"u26C5": { "en": "partly_sunny", "zh": "\u591A\u4E91", "tag": "\u26C5", "bp": "-2900px 0px" },
"u261D": { "en": "point_up", "zh": "\u7B2C\u4E00", "tag": "\u261D", "bp": "-2925px 0px" },
"u263A": { "en": "relaxed", "zh": "\u8F7B\u677E", "tag": "\u263A", "bp": "-2950px 0px" },
"u1F44A": { "en": "punch", "zh": "\u62F3", "tag": "\uD83D\uDC4A", "bp": "-2975px 0px" },
"u270B": { "en": "hand", "zh": "\u624B", "tag": "\u270B", "bp": "-3000px 0px" },
"u270C": { "en": "v", "zh": "v", "tag": "\u270C", "bp": "-3025px 0px" },
"u270F": { "en": "pencil2", "zh": "\u7B14", "tag": "\u270F", "bp": "-3050px 0px" },
"u2600": { "en": "sunny", "zh": "\u6674\u6717", "tag": "\u2600", "bp": "-3075px 0px" },
"u2601": { "en": "cloud", "zh": "\u4E91", "tag": "\u2601", "bp": "-3100px 0px" },
"u2614": { "en": "umbrella", "zh": "\u4F1E", "tag": "\u2614", "bp": "-3125px 0px" },
"u2615": { "en": "coffee", "zh": "\u5496\u5561", "tag": "\u2615", "bp": "-3150px 0px" },
"u2744": { "en": "snowflake", "zh": "\u96EA\u82B1", "tag": "\u2744", "bp": "-3175px 0px" }
};
private static regExpTag: any;
private static regExpName: any;
private static size: number = 24;
private static url: string = "";
/**
* 是否支持高清屏幕
*/
private static pixelRatio: number = parseFloat(window.devicePixelRatio + "") || 1;
/**
* 判断是否支持emoji
*/
private static supportEmoji: boolean = false;
/**
* 初始化CSS
*/
private static initCSS() {
if (!document.createStyleSheet) {
var head = document.getElementsByTagName("head")[0] || document.createElement("head");
var style = document.createElement("style");
style.type = "text/css";
style.innerHTML = ".RC_Expression {width:" + this.size + "px;height:" + this.size + "px;background-image:url(" + this.url + ");display:inline-block}";
head.appendChild(style);
}
}
private static createBTag(position: string): any {
var e = document.createElement("b");
if (document.createStyleSheet) {
e.style.width = this.size + "px";
e.style.height = this.size + "px";
e.style.backgroundImage = "url(" + this.url + ")";
e.style.display = "inline";
e.style.display = "inline-block";
e.style.zoom = "1";
e.style.backgroundPosition = position;
} else {
e.className = "RC_Expression";
e.style.backgroundPosition = position;
}
return e;
}
private static createSpan(emojiObj: any): any {
var span = document.createElement("span"), p = document.createElement("span");
span.setAttribute("style", "height: " + this.size + "px; width: " + this.size + "px; display: inline-block; font-size: 20px !important; text-align: center; vertical-align: middle;overflow: hidden; line-height: 24px;");
if (this.supportEmoji) {
span.textContent = emojiObj.tag;
} else {
var img = this.createBTag(emojiObj.bp);
span.appendChild(img);
}
span.setAttribute("class", "RongIMExpression_" + emojiObj.en.substring(1, emojiObj.en.length));
span.setAttribute("name", "[" + emojiObj.zh + "]");
p.appendChild(span);
return p;
}
private static calculateUTF(d: any) {
var me = this;
if (61440 < d.charCodeAt(0)) {
var b = me.emojiFactory[escape(d).replace("%u", "u1")];
if (b) return b.tag;
}
return d;
}
static init(emoji?: any) {
var me = this;
me.url = (RongIMClient && RongIMClient._memoryStore && RongIMClient._memoryStore.depend && RongIMClient._memoryStore.depend.emojiImage) || "//cdn.ronghub.com/css-sprite_bg-2.1.10.png";
if (emoji) {
me.emojiFactory = emoji.dataSource;
me.url = emoji.url;
}
// if (me.pixelRatio > 1) {
// me.size = 48;
// //TODO 这是高清URL
// }
// if (!emoji && navigator.userAgent.match(/Mac\s+OS/i)) {
// me.supportEmoji = true;
// }
me.initCSS();
var regExp = new RegExp("%", "g"), tagStr = "", nameStr = "";
for (var key in me.emojiFactory) {
tagStr += escape(me.emojiFactory[key].tag) + "|";
nameStr += escape(me.emojiFactory[key].zh) + "|";
RongIMEmoji.emojis.push(me.createSpan(me.emojiFactory[key]));
}
tagStr = tagStr.substring(0, tagStr.length - 1);
tagStr = tagStr.replace(regExp, function(x) { return "\\"; });
me.regExpTag = new RegExp("(" + tagStr + ")", "g");
nameStr = nameStr.substring(0, nameStr.length - 1);
nameStr = nameStr.replace(regExp, function(x) { return "\\"; });
me.regExpName = new RegExp("(" + nameStr + ")", "g");
}
static emojiToSymbol(str: string) {
var me = this;
str = str.replace(/[\uf000-\uf700]/g, function(em) {
return me.calculateUTF(em) || em;
});
if (me.supportEmoji) {
return str;
}
return str.replace(me.regExpTag, function(em) {
for (var key in me.emojiFactory) {
if (me.emojiFactory[key].tag == em) {
return "[" + me.emojiFactory[key].zh + "]";
}
}
});
}
/**
* 获取Emoji对象 发送消息使用
* @param {string} name emoji名称
*/
static symbolToEmoji(str: string): string {
var me = this;
return str.replace(/\[.+?\]/g, function(s) {
var temp = s.slice(1, s.length - 1), tStr: any = temp;
if (me.regExpName.test(temp) && tStr.replace(me.regExpName) == 'undefined') {
return temp.replace(me.regExpName, function(zh) {
for (var key in me.emojiFactory) {
if (me.emojiFactory[key].zh == zh) {
return me.emojiFactory[key].tag;
}
}
});
} else {
return "[" + temp + "]";
}
});
}
/**
* @param {string} str 字符串
*/
static symbolToHTML(str: string): string {
var em = this.symbolToEmoji(str);
return this.emojiToHTML(em);
}
/**
* 转换字符串中的emoji 接收消息使用
* @param {string} str 包含emoji的字符串
*/
static emojiToHTML(str: string) {
var me = this;
str = str.replace(/[\uf000-\uf700]/g, function(em) {
return me.calculateUTF(em) || em;
});
return str.replace(me.regExpTag, function(em) {
var span: any;
for (var key in me.emojiFactory) {
if (me.emojiFactory[key].tag == em) {
span = me.createSpan(me.emojiFactory[key]);
break;
}
}
return span.innerHTML;
});
}
}
//兼容AMD CMD
if ("function" === typeof require && "object" === typeof module && module && module.id && "object" === typeof exports && exports) {
module.exports = RongIMEmoji;
} else if ("function" === typeof define && define.amd) {
define("RongIMEmoji", [], function() {
return RongIMEmoji;
});
}
} | the_stack |
import {
AnimationData, AnimationDataLike,
Asset, AssetSource,
Context,
Guid, newGuid,
log,
Material, MaterialLike,
Mesh,
MreArgumentError,
Prefab,
PrimitiveDefinition,
PrimitiveShape,
ReadonlyMap,
Sound, SoundLike,
Texture, TextureLike,
Vector3Like,
VideoStream, VideoStreamLike
} from '..';
import {
Payloads,
resolveJsonValues
} from '../internal';
/**
* The root object of the MRE SDK's asset system. Once you create an AssetContainer,
* you can create new materials, textures, or sounds from scratch, or load glTF
* files for their assets.
*/
export class AssetContainer {
private _id: Guid;
private _assets = new Map<Guid, Asset>();
/** @hidden */
public get id() { return this._id; }
/** A mapping of asset IDs to assets in this container */
public get assetsById() { return this._assets as ReadonlyMap<Guid, Asset>; }
/** A list of all assets in this container */
public get assets() { return [...this._assets.values()]; }
/** A list of all animation data in this container */
public get animationData() { return this.assets.filter(a => a instanceof AnimationData) as AnimationData[]; }
/** A list of all materials in this container */
public get materials() { return this.assets.filter(a => a instanceof Material) as Material[]; }
/** A list of all meshes in this container */
public get meshes() { return this.assets.filter(a => a instanceof Mesh) as Mesh[]; }
/** A list of all prefabs in this container */
public get prefabs() { return this.assets.filter(a => a instanceof Prefab) as Prefab[]; }
/** A list of all sounds in this container */
public get sounds() { return this.assets.filter(a => a instanceof Sound) as Sound[]; }
/** A list of all textures in this container */
public get textures() { return this.assets.filter(a => a instanceof Texture) as Texture[]; }
/** Create a new asset container */
public constructor(public context: Context) {
this._id = newGuid();
context.internal.assetContainers.add(this);
}
/**
* Generate a new material
* @param name The new material's name
* @param definition The initial material properties
*/
public createMaterial(name: string, definition: Partial<MaterialLike>): Material {
const mat = new Material(this, {
id: newGuid(),
name,
material: resolveJsonValues(definition)
});
mat.setLoadedPromise(this.sendCreateAsset(mat));
return mat;
}
/**
* Load an image file and generate a new texture asset
* @param name The new texture's name
* @param definition The initial texture properties. The `uri` property is required.
*/
public createTexture(name: string, definition: Partial<TextureLike>): Texture {
const tex = new Texture(this, {
id: newGuid(),
name,
texture: resolveJsonValues(definition)
});
tex.setLoadedPromise(this.sendCreateAsset(tex));
return tex;
}
/**
* Load an audio file and generate a new sound asset
* @param name The new sound's name
* @param definition The initial sound properties. The `uri` property is required.
*/
public createSound(name: string, definition: Partial<SoundLike>): Sound {
const sound = new Sound(this, {
id: newGuid(),
name,
sound: resolveJsonValues(definition)
});
sound.setLoadedPromise(this.sendCreateAsset(sound));
return sound;
}
/**
* Preload a video stream and generate a new video stream asset
* @param name The new stream's name
* @param definition The initial video stream properties. The `uri` property is required.
*/
public createVideoStream(name: string, definition: Partial<VideoStreamLike>): VideoStream {
const video = new VideoStream(this, {
id: newGuid(),
name,
videoStream: resolveJsonValues(definition)
});
video.setLoadedPromise(this.sendCreateAsset(video));
return video;
}
/**
* Preload unbound animation keyframe data for later use.
* @param name The name of this animation
* @param data The keyframe data
* @throws [[MreValidationError]] If the provided animation data is malformed. See the error message for details.
*/
public createAnimationData(name: string, data: AnimationDataLike) {
const validationIssues = AnimationData.Validate(data);
if (validationIssues) {
throw new MreArgumentError("Cannot create animation data from bad data:\n"
+ validationIssues.map(s => '- ' + s).join('\n'));
}
const animData = new AnimationData(this, {
id: newGuid(),
name,
animationData: data
});
animData.setLoadedPromise(this.sendCreateAsset(animData));
return animData;
}
/**
* Create a new sphere-shaped mesh.
* @param name The name to give to the asset.
* @param radius The radius of the sphere.
* @param uSegments The number of longitudinal segments.
* @param vSegments The number of latitudinal segments.
*/
public createSphereMesh(name: string, radius: number, uSegments = 36, vSegments = 18): Mesh {
return this.createPrimitiveMesh(name, {
shape: PrimitiveShape.Sphere,
dimensions: { x: 2 * radius, y: 2 * radius, z: 2 * radius },
uSegments,
vSegments
});
}
/**
* Create a new box-shaped mesh.
* @param name The name to give to the asset.
* @param width The length of the box on the X axis.
* @param height The length of the box on the Y axis.
* @param depth The length of the box on the Z axis.
*/
public createBoxMesh(name: string, width: number, height: number, depth: number): Mesh {
return this.createPrimitiveMesh(name, {
shape: PrimitiveShape.Box,
dimensions: { x: width, y: height, z: depth }
});
}
/**
* Create a new capsule-shaped mesh.
* @param name The name to give to the asset.
* @param height The height of the capsule from tip to tip.
* @param radius The thickness of the capsule.
* @param direction The long axis of the capsule.
* @param uSegments The number of longitudinal segments.
* @param vSegments The number of latitudinal segments.
*/
public createCapsuleMesh(
name: string, height: number, radius: number,
direction: 'x' | 'y' | 'z' = 'y', uSegments = 36, vSegments = 18
): Mesh {
if (height < 2 * radius) {
throw new Error("Capsule height must be greater than twice the radius");
}
const dimensions = { x: 2 * radius, y: 2 * radius, z: 2 * radius } as Vector3Like;
dimensions[direction] = height;
return this.createPrimitiveMesh(name, {
shape: PrimitiveShape.Capsule,
dimensions,
uSegments,
vSegments
});
}
/**
* Create a new cylinder-shaped mesh.
* @param name The name to give to the asset.
* @param height The height of the cylinder.
* @param radius The thickness of the cylinder.
* @param direction The long axis of the cylinder.
* @param uSegments The number of longitudinal segments.
*/
public createCylinderMesh(
name: string, height: number, radius: number,
direction: 'x' | 'y' | 'z' = 'y', uSegments = 36
): Mesh {
const dimensions = { x: 2 * radius, y: 2 * radius, z: 2 * radius };
dimensions[direction] = height;
return this.createPrimitiveMesh(name, {
shape: PrimitiveShape.Cylinder,
dimensions,
uSegments
});
}
/**
* Create a flat mesh on the X-Z plane.
* @param name The name to give to the asset.
* @param width The X-axis length of the plane.
* @param height The Z-axis length of the plane.
* @param uSegments The number of X-axis segments.
* @param vSegments The number of Z-axis segments.
*/
public createPlaneMesh(name: string, width: number, height: number, uSegments = 1, vSegments = 1): Mesh {
return this.createPrimitiveMesh(name, {
shape: PrimitiveShape.Plane,
dimensions: { x: width, y: 0, z: height },
uSegments,
vSegments
});
}
/**
* Create a new mesh from the given primitive definition
* @param name The new mesh's name
* @param definition A description of the desired mesh
*/
public createPrimitiveMesh(name: string, definition: PrimitiveDefinition): Mesh {
const mesh = new Mesh(this, {
id: newGuid(),
name,
mesh: {
primitiveDefinition: definition
}
});
mesh.setLoadedPromise(this.sendCreateAsset(mesh));
return mesh;
}
/**
* Load the assets in a glTF file by URL, and this container with the result.
* @param uri The URI to a glTF model.
* @param colliderType The shape of the generated prefab collider.
* @returns A promise that resolves with the list of loaded assets.
*/
public async loadGltf(uri: string, colliderType?: 'box' | 'mesh'): Promise<Asset[]> {
if (!this._assets) {
throw new Error("Cannot load new assets into an unloaded container!");
}
const source = {
containerType: 'gltf',
uri
} as AssetSource;
const payload = {
type: 'load-assets',
containerId: this.id,
source,
colliderType
} as Payloads.LoadAssets;
const response = await this.context.internal
.sendPayloadAndGetReply<Payloads.LoadAssets, Payloads.AssetsLoaded>(payload);
if (response.failureMessage) {
throw new Error(response.failureMessage);
}
const newAssets: Asset[] = [];
for (const def of response.assets) {
def.source = source;
const asset = Asset.Parse(this, def);
this._assets.set(def.id, asset);
newAssets.push(asset);
}
return newAssets;
}
/** Break references to all assets in the container, and unload them to free memory */
public unload(): void {
for (const a of this.assets) {
a.breakAllReferences();
}
this.context.internal.assetContainers.delete(this);
this._assets = null;
// wait until after the unassignments get propagated to clients to avoid visually
// missing textures (renders black) and missing materials (renders magenta)
this.context.internal.nextUpdate().then(() => {
this.context.internal.protocol.sendPayload({
type: 'unload-assets',
containerId: this.id
} as Payloads.UnloadAssets);
})
.catch(err => log.error('app', err));
}
private async sendCreateAsset(asset: Asset): Promise<void> {
if (!this._assets) {
throw new Error("Cannot load new assets into an unloaded container!");
}
this._assets.set(asset.id, asset);
const reply = await this.context.internal.sendPayloadAndGetReply<Payloads.CreateAsset, Payloads.AssetsLoaded>({
type: 'create-asset',
containerId: this.id,
definition: resolveJsonValues(asset)
});
if (reply.failureMessage || reply.assets.length !== 1) {
throw new Error(`Creation/Loading of asset ${asset.name} failed: ${reply.failureMessage}`);
}
asset.copy(reply.assets[0]);
}
} | the_stack |
export interface Comment {
id: string;
type: 'MODIFICATION'|'ADDITION'|'CREATION'|'RESTORATION'|'DELETION';
content: string;
cleaned_content: string;
parent_id: string|null;
replyTo_id: string|null;
indentation?: number|null;
user_text: string;
timestamp: string;
page_title: string;
authors?: string[]|null;
// If == id then this comment should be highlighted.
comment_to_highlight?: string;
// Added based on conversation structure.
children?: Comment[];
isRoot?: boolean; // true iff this is starting comment of a conversation.
isLatest?:
boolean; // true iff this is the latest comment in the conversation.
isFinal?: boolean; // true iff this is the final (by DFS) comment in the
// conversation.
isPresent?: boolean; // true iff this version of the comment is present in
// the current snapshot.
latestVersion?: string | null; // id of the latest version of this comment if isPresent
// is false, otherwise id of self.
dfs_index?: number; // index according to Depth First Search of conv.
// Starting here are toxicity scores, since they don't exist in all datasets
// except in English, this fields are optional.
// TODO(yiqingh, ldixon) : decide on which scores to use, delete non-public
// ones from the spanner table.
RockV6_1_SEVERE_TOXICITY?: number | null,
RockV6_1_SEXUAL_ORIENTATION?: number | null,
RockV6_1_SEXUALLY_EXPLICIT?: number | null,
RockV6_1_TOXICITY?: number | null,
//TODO(yiqingh): change TOXICITY_IDENTITY_HATE to IDENTITY_ATTACK
RockV6_1_TOXICITY_IDENTITY_HATE?: number | null,
RockV6_1_TOXICITY_INSULT?: number | null,
RockV6_1_TOXICITY_OBSCENE?: number | null,
RockV6_1_TOXICITY_THREAT?: number | null,
Smirnoff_2_ATTACK_ON_AUTHOR?: number | null,
Smirnoff_2_ATTACK_ON_COMMENTER?: number | null,
Smirnoff_2_INCOHERENT?: number | null,
Smirnoff_2_INFLAMMATORY?: number | null,
Smirnoff_2_LIKELY_TO_REJECT?: number | null,
Smirnoff_2_OBSCENE?: number | null,
Smirnoff_2_OFF_TOPIC?: number | null,
Smirnoff_2_SPAM?: number | null,
Smirnoff_2_UNSUBSTANTIAL?: number | null,
displayScore?: string | null,
// The following fields are used in displaying comments in viz app.
isCollapsed?: boolean,
rootComment?: Comment,
currentState?: string,
// True if this comment is not modified nor deleted in the database.
isAlive?: boolean;
//TODO(yiqingh) : change this to isUnchanged in all data sources
}
export interface Conversation { [id: string]: Comment }
;
//
export function interpretId(id: string):
{revision: number; token: number; action: number}|null {
const myRegexp = /(\d+)\.(\d+)\.(\d+)/g;
const match = myRegexp.exec(id);
if (!match || match.length < 4) {
return null
}
return {
action: parseInt(match[3], 10),
revision: parseInt(match[1], 10),
token: parseInt(match[2], 10),
};
}
export function compareDateFn(da: Date, db: Date): number {
if (db < da) {
return 1;
} else if (da < db) {
return -1;
} else {
return 0;
}
}
export function compareByDateFn(a: Comment, b: Comment): number {
const db = Date.parse(b.timestamp);
const da = Date.parse(a.timestamp);
return db - da;
}
//
export function compareCommentOrder(comment1: Comment, comment2: Comment) {
const dateCmp = compareByDateFn(comment2, comment1)
if (dateCmp !== 0) {
return dateCmp;
}
const id1 = interpretId(comment1.id);
const id2 = interpretId(comment2.id);
if (id1 === null || id2 === null) {
console.warn(
'Using string comparison for comment order:' +
' comment has uninterpretable id: ',
comment1);
return comment1.id === comment2.id ? 0 :
(comment1.id > comment2.id ? 1 : -1);
}
const revisionDiff = id1.revision - id2.revision;
const tokenDiff = id1.token - id2.token;
const actionDiff = id1.action - id2.action;
return revisionDiff !== 0 ?
revisionDiff :
(tokenDiff !== 0 ? tokenDiff : (actionDiff !== 0 ? actionDiff : 0));
}
export function compareCommentOrderSmallestFirst(
comment1: Comment, comment2: Comment) {
return compareCommentOrder(comment2, comment1);
}
export function indentOfComment(
comment: Comment, conversation: Conversation): number {
if (comment.replyTo_id === '' || comment.replyTo_id === null) {
return 0;
}
let parent : Comment | null = conversation[comment.replyTo_id];
// If the conversation parent is not present, assuming the
// comment is replying to the parent's latest version.
while (parent && !parent.isPresent) {
parent = parent.latestVersion ? conversation[parent.latestVersion]: parent.replyTo_id ? conversation[parent.replyTo_id] : null
}
if (!parent) {
console.error(
'Comment lacks parent in conversation: ', comment.content);
return 0;
}
return indentOfComment(parent, conversation) + 1;
}
export function htmlForComment(
comment: Comment, conversation: Conversation): string {
let convId = '';
let sectionHeading = '';
let commentClassName = '';
if (!comment.isPresent) {
return '';
}
if (comment.isRoot) {
commentClassName = 'comment';
sectionHeading = `<div>In page: <b>${comment.page_title}</b></div>`;
convId = `<div class="convid">
<span class="convid-text">(conversation id: ${comment.id}) </span>
<span class="convid-comment-index-header">Comment Number</span>
</div>`;
} else if (comment.isLatest) {
commentClassName = 'comment finalcomment';
} else {
commentClassName = 'comment';
}
const timestamp = comment.timestamp.replace(/ UTC/g, '');
return `
${sectionHeading}
${convId}
<div class="action ${commentClassName}" style="margin-left: ${comment.indentation}em;">
<table class="action">
<tr><td class="whenandwho">
<div class="author">${comment.user_text}</div>
<div class="timestamp">${timestamp}</div>
</td>
<td class="content">${comment.cleaned_content}</td>
<td><div class="index">${comment.dfs_index}</div></td>
</tr>
</table>
<div>
`;
}
// Walk down a comment and its children depth first.
export function walkDfsComments(
rootComment: Comment, f: (c: Comment) => void): void {
const stack = [rootComment];
let nextComment: Comment|undefined = stack.pop();
while (nextComment){
f(nextComment);
if (nextComment.children){
if (nextComment.children.reverse()) {
for (const ch of nextComment.children) {
stack.push(ch)
}
}
}
nextComment = stack.pop();
}
}
// Get the last comment in the thread.
export function lastDecendentComment(rootComment: Comment): Comment {
let finalComment: Comment = rootComment;
walkDfsComments(rootComment, (c) => {
finalComment = c;
});
return finalComment;
}
// Get the last comment in the thread.
export function indexComments(rootComment: Comment) {
let index = 0;
walkDfsComments(rootComment, (c) => {
c.dfs_index = index;
index++;
});
}
export function makeParent(comment: Comment, parent: Comment) {
if (!comment.isPresent) {
return;
}
if (!parent.children) {
parent.children = [];
}
parent.children.push(comment);
parent.children.sort(compareCommentOrder);
comment.parent_id = parent.id;
comment.isRoot = false;
}
function selectRootComment(comment: Comment, rootComment: Comment|null) {
// This can happen when two comments from the same revision occur,
// and they are the first comment in the conversation.
// Both the section creation action and the comment have no parent.
// At this point, we get down to comparing offsets to choose the parent.
if (!comment.isPresent) {
return rootComment;
}
if (rootComment) {
const commentCmp = compareCommentOrder(rootComment, comment);
if (commentCmp < 0) {
makeParent(comment, rootComment);
} else if (commentCmp > 0) {
makeParent(rootComment, comment);
comment.isRoot = true;
rootComment = comment;
} else {
console.warn(`Duplicate root comment IDs (old and new):
Choosing root by comment time-stamp.
Old: ${JSON.stringify(rootComment, null, 2)}
New: ${JSON.stringify(comment, null, 2)}
`);
}
} else {
comment.isRoot = true;
rootComment = comment;
}
return rootComment;
}
// Add and sort children to each comment in a conversation.
// Also set the isRoot field of every comment, and return the
// overall root comment of the conversation.
export function structureConversaton(conversation: Conversation): Comment|null {
const keys = Object.keys(conversation);
interface ItemPair { key : string; value: Comment};
const items : ItemPair[] = [];
for (const k of keys) {
items.push({key: k, value: conversation[k]});
}
items.sort((v1, v2) => -compareByDateFn(v1.value, v2.value));
const ids = items.map((value, index) => value.key);
let rootComment: Comment|null = null;
let latestComments: Comment[] = [];
for (const i of ids) {
const comment = conversation[i];
// If the action is deletion, the content must have been deleted.
conversation[i].isPresent = true;
conversation[i].latestVersion = i;
if (comment.type === 'DELETION') {
conversation[i].isPresent = false;
conversation[i].latestVersion = null;
}
if (comment.parent_id !== null && comment.parent_id !== ''
&& conversation[comment.parent_id]) {
if (comment.type !== 'RESTORATION') {
conversation[comment.parent_id].isPresent = false;
} else {
conversation[i].isPresent = false;
conversation[comment.parent_id].isPresent = true;
conversation[comment.parent_id].latestVersion = comment.parent_id;
}
// When a modification happens, the current comment will
// be replaced by the new version.
if (comment.type === 'MODIFICATION') {
conversation[comment.parent_id].latestVersion = i;
}
}
}
for (const i of ids) {
const comment = conversation[i];
if (comment.type === "RESTORATION" || comment.type === "DELETION") {
continue;
}
comment.isFinal = false;
comment.isLatest = false;
if (latestComments.length === 0) {
latestComments = [comment];
} else {
const dtime = compareByDateFn(latestComments[0], comment);
if (dtime > 0) {
latestComments = [comment];
} else if (dtime === 0) {
latestComments.push(comment);
}
}
if (!comment.children) {
comment.children = [];
}
comment.indentation = indentOfComment(comment, conversation)
if (comment.replyTo_id !== null && comment.replyTo_id !== '') {
let parent : Comment | null = conversation[comment.replyTo_id];
// If the conversation parent is not present, assuming the
// comment is replying to the parent's latest version.
while (parent && !parent.isPresent) {
parent = parent.latestVersion ? conversation[parent.latestVersion] : parent.replyTo_id ? conversation[parent.replyTo_id] : null;
}
if (parent) {
makeParent(comment, parent);
} else {
console.error(`Parent of this comment is missing from conversation:
${JSON.stringify(rootComment, null, 2)}`);
rootComment = selectRootComment(comment, rootComment);
}
} else {
rootComment = selectRootComment(comment, rootComment);
}
} // For comments.
// Identify the final comment w.r.t. dfs. i.e. the one at the bottom.
if (rootComment) {
indexComments(rootComment);
const finalComment = lastDecendentComment(rootComment);
finalComment.isFinal = true;
}
// Idenitfy the latest action. Order by lex on time desc then index desc.
latestComments.sort((c1, c2) => {
if (c1.dfs_index === undefined || c2.dfs_index === undefined) {
return -1;
}
return c2.dfs_index - c1.dfs_index;
});
if (latestComments.length > 0) {
latestComments[0].isLatest = true;
}
return rootComment;
} | the_stack |
import '../../../test/common-test-setup-karma';
import './gr-autocomplete';
import {html} from '@polymer/polymer/lib/utils/html-tag';
import {flush as flush$0} from '@polymer/polymer/lib/legacy/polymer.dom';
import {AutocompleteSuggestion, GrAutocomplete} from './gr-autocomplete';
import * as MockInteractions from '@polymer/iron-test-helpers/mock-interactions';
import {assertIsDefined} from '../../../utils/common-util';
import {queryAll, queryAndAssert} from '../../../test/test-utils';
import {GrAutocompleteDropdown} from '../gr-autocomplete-dropdown/gr-autocomplete-dropdown';
import {PaperInputElement} from '@polymer/paper-input/paper-input';
const basicFixture = fixtureFromTemplate(
html`<gr-autocomplete no-debounce></gr-autocomplete>`
);
suite('gr-autocomplete tests', () => {
let element: GrAutocomplete;
const focusOnInput = () => {
MockInteractions.pressAndReleaseKeyOn(inputEl(), 13, null, 'enter');
};
const suggestionsEl = () =>
queryAndAssert<GrAutocompleteDropdown>(element, '#suggestions');
const inputEl = () => queryAndAssert<HTMLInputElement>(element, '#input');
setup(() => {
element = basicFixture.instantiate() as GrAutocomplete;
});
test('renders', () => {
let promise: Promise<AutocompleteSuggestion[]> = Promise.resolve([]);
const queryStub = sinon.spy(
(input: string) =>
(promise = Promise.resolve([
{name: input + ' 0', value: '0'},
{name: input + ' 1', value: '1'},
{name: input + ' 2', value: '2'},
{name: input + ' 3', value: '3'},
{name: input + ' 4', value: '4'},
] as AutocompleteSuggestion[]))
);
element.query = queryStub;
assert.isTrue(suggestionsEl().isHidden);
assert.equal(suggestionsEl().cursor.index, -1);
focusOnInput();
element.text = 'blah';
assert.isTrue(queryStub.called);
element._focused = true;
assertIsDefined(promise);
return promise.then(() => {
assert.isFalse(suggestionsEl().isHidden);
const suggestions = queryAll<HTMLElement>(suggestionsEl(), 'li');
assert.equal(suggestions.length, 5);
for (let i = 0; i < 5; i++) {
assert.equal(suggestions[i].innerText.trim(), `blah ${i}`);
}
assert.notEqual(suggestionsEl().cursor.index, -1);
});
});
test('selectAll', async () => {
await flush();
const nativeInput = element._nativeInput;
const selectionStub = sinon.stub(nativeInput, 'setSelectionRange');
element.selectAll();
assert.isFalse(selectionStub.called);
inputEl().value = 'test';
element.selectAll();
assert.isTrue(selectionStub.called);
});
test('esc key behavior', () => {
let promise: Promise<AutocompleteSuggestion[]> = Promise.resolve([]);
const queryStub = sinon.spy(
(_: string) =>
(promise = Promise.resolve([
{name: 'blah', value: '123'},
] as AutocompleteSuggestion[]))
);
element.query = queryStub;
assert.isTrue(suggestionsEl().isHidden);
element._focused = true;
element.text = 'blah';
return promise.then(() => {
assert.isFalse(suggestionsEl().isHidden);
const cancelHandler = sinon.spy();
element.addEventListener('cancel', cancelHandler);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 27, null, 'esc');
assert.isFalse(cancelHandler.called);
assert.isTrue(suggestionsEl().isHidden);
assert.equal(element._suggestions.length, 0);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 27, null, 'esc');
assert.isTrue(cancelHandler.called);
});
});
test('emits commit and handles cursor movement', () => {
let promise: Promise<AutocompleteSuggestion[]> = Promise.resolve([]);
const queryStub = sinon.spy(
(input: string) =>
(promise = Promise.resolve([
{name: input + ' 0', value: '0'},
{name: input + ' 1', value: '1'},
{name: input + ' 2', value: '2'},
{name: input + ' 3', value: '3'},
{name: input + ' 4', value: '4'},
] as AutocompleteSuggestion[]))
);
element.query = queryStub;
assert.isTrue(suggestionsEl().isHidden);
assert.equal(suggestionsEl().cursor.index, -1);
element._focused = true;
element.text = 'blah';
return promise.then(() => {
assert.isFalse(suggestionsEl().isHidden);
const commitHandler = sinon.spy();
element.addEventListener('commit', commitHandler);
assert.equal(suggestionsEl().cursor.index, 0);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 40, null, 'down');
assert.equal(suggestionsEl().cursor.index, 1);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 40, null, 'down');
assert.equal(suggestionsEl().cursor.index, 2);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 38, null, 'up');
assert.equal(suggestionsEl().cursor.index, 1);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 13, null, 'enter');
assert.equal(element.value, '1');
assert.isTrue(commitHandler.called);
assert.equal(commitHandler.getCall(0).args[0].detail.value, 1);
assert.isTrue(suggestionsEl().isHidden);
assert.isTrue(element._focused);
});
});
test('clear-on-commit behavior (off)', () => {
let promise: Promise<AutocompleteSuggestion[]> = Promise.resolve([]);
const queryStub = sinon.spy(() => {
promise = Promise.resolve([
{name: 'suggestion', value: '0'},
] as AutocompleteSuggestion[]);
return promise;
});
element.query = queryStub;
focusOnInput();
element.text = 'blah';
return promise.then(() => {
const commitHandler = sinon.spy();
element.addEventListener('commit', commitHandler);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 13, null, 'enter');
assert.isTrue(commitHandler.called);
assert.equal(element.text, 'suggestion');
});
});
test('clear-on-commit behavior (on)', () => {
let promise: Promise<AutocompleteSuggestion[]> = Promise.resolve([]);
const queryStub = sinon.spy(() => {
promise = Promise.resolve([
{name: 'suggestion', value: '0'},
] as AutocompleteSuggestion[]);
return promise;
});
element.query = queryStub;
focusOnInput();
element.text = 'blah';
element.clearOnCommit = true;
return promise.then(() => {
const commitHandler = sinon.spy();
element.addEventListener('commit', commitHandler);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 13, null, 'enter');
assert.isTrue(commitHandler.called);
assert.equal(element.text, '');
});
});
test('threshold guards the query', () => {
const queryStub = sinon.spy(() =>
Promise.resolve([] as AutocompleteSuggestion[])
);
element.query = queryStub;
element.threshold = 2;
focusOnInput();
element.text = 'a';
assert.isFalse(queryStub.called);
element.text = 'ab';
assert.isTrue(queryStub.called);
});
test('noDebounce=false debounces the query', () => {
const clock = sinon.useFakeTimers();
const queryStub = sinon.spy(() =>
Promise.resolve([] as AutocompleteSuggestion[])
);
element.query = queryStub;
element.noDebounce = false;
focusOnInput();
element.text = 'a';
// not called right away
assert.isFalse(queryStub.called);
// but called after a while
clock.tick(1000);
assert.isTrue(queryStub.called);
});
test('_computeClass respects border property', () => {
assert.equal(element._computeClass(), '');
assert.equal(element._computeClass(false), '');
assert.equal(element._computeClass(true), 'borderless');
});
test('undefined or empty text results in no suggestions', () => {
element._updateSuggestions(undefined, 0, undefined);
assert.equal(element._suggestions.length, 0);
});
test('when focused', () => {
let promise: Promise<AutocompleteSuggestion[]> = Promise.resolve([]);
const queryStub = sinon
.stub()
.returns(
(promise = Promise.resolve([
{name: 'suggestion', value: '0'},
] as AutocompleteSuggestion[]))
);
element.query = queryStub;
focusOnInput();
element.text = 'bla';
assert.equal(element._focused, true);
flush();
return promise.then(() => {
assert.equal(element._suggestions.length, 1);
assert.equal(queryStub.notCalled, false);
});
});
test('when not focused', () => {
let promise: Promise<AutocompleteSuggestion[]> = Promise.resolve([]);
const queryStub = sinon
.stub()
.returns(
(promise = Promise.resolve([
{name: 'suggestion', value: '0'},
] as AutocompleteSuggestion[]))
);
element.query = queryStub;
element.text = 'bla';
assert.equal(element._focused, false);
flush();
return promise.then(() => {
assert.equal(element._suggestions.length, 0);
});
});
test('suggestions should not carry over', () => {
let promise: Promise<AutocompleteSuggestion[]> = Promise.resolve([]);
const queryStub = sinon
.stub()
.returns(
(promise = Promise.resolve([
{name: 'suggestion', value: '0'},
] as AutocompleteSuggestion[]))
);
element.query = queryStub;
focusOnInput();
element.text = 'bla';
flush();
return promise.then(() => {
assert.equal(element._suggestions.length, 1);
element._updateSuggestions('', 0, false);
assert.equal(element._suggestions.length, 0);
});
});
test('multi completes only the last part of the query', () => {
let promise;
const queryStub = sinon
.stub()
.returns(
(promise = Promise.resolve([
{name: 'suggestion', value: '0'},
] as AutocompleteSuggestion[]))
);
element.query = queryStub;
focusOnInput();
element.text = 'blah blah';
element.multi = true;
return promise.then(() => {
const commitHandler = sinon.spy();
element.addEventListener('commit', commitHandler);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 13, null, 'enter');
assert.isTrue(commitHandler.called);
assert.equal(element.text, 'blah 0');
});
});
test('tabComplete flag functions', () => {
// commitHandler checks for the commit event, whereas commitSpy checks for
// the _commit function of the element.
const commitHandler = sinon.spy();
element.addEventListener('commit', commitHandler);
const commitSpy = sinon.spy(element, '_commit');
element._focused = true;
element._suggestions = [{text: 'tunnel snakes rule!'}];
element.tabComplete = false;
MockInteractions.pressAndReleaseKeyOn(inputEl(), 9, null, 'tab');
assert.isFalse(commitHandler.called);
assert.isFalse(commitSpy.called);
assert.isFalse(element._focused);
element.tabComplete = true;
element._focused = true;
MockInteractions.pressAndReleaseKeyOn(inputEl(), 9, null, 'tab');
assert.isFalse(commitHandler.called);
assert.isTrue(commitSpy.called);
assert.isTrue(element._focused);
});
test('_focused flag properly triggered', () => {
flush();
assert.isFalse(element._focused);
const input = queryAndAssert<PaperInputElement>(
element,
'paper-input'
).inputElement;
MockInteractions.focus(input);
assert.isTrue(element._focused);
});
test('search icon shows with showSearchIcon property', () => {
flush();
assert.equal(
getComputedStyle(queryAndAssert(element, 'iron-icon')).display,
'none'
);
element.showSearchIcon = true;
assert.notEqual(
getComputedStyle(queryAndAssert(element, 'iron-icon')).display,
'none'
);
});
test('vertical offset overridden by param if it exists', () => {
assert.equal(suggestionsEl().verticalOffset, 31);
element.verticalOffset = 30;
assert.equal(suggestionsEl().verticalOffset, 30);
});
test('_focused flag shows/hides the suggestions', () => {
const openStub = sinon.stub(suggestionsEl(), 'open');
const closedStub = sinon.stub(suggestionsEl(), 'close');
element._suggestions = [{text: 'hello'}, {text: 'its me'}];
assert.isFalse(openStub.called);
assert.isTrue(closedStub.calledOnce);
element._focused = true;
assert.isTrue(openStub.calledOnce);
element._suggestions = [];
assert.isTrue(closedStub.calledTwice);
assert.isTrue(openStub.calledOnce);
});
test(
'_handleInputCommit with autocomplete hidden does nothing without' +
'without allowNonSuggestedValues',
() => {
const commitStub = sinon.stub(element, '_commit');
suggestionsEl().isHidden = true;
element._handleInputCommit();
assert.isFalse(commitStub.called);
}
);
test(
'_handleInputCommit with autocomplete hidden with' +
'allowNonSuggestedValues',
() => {
const commitStub = sinon.stub(element, '_commit');
element.allowNonSuggestedValues = true;
suggestionsEl().isHidden = true;
element._handleInputCommit();
assert.isTrue(commitStub.called);
}
);
test('_handleInputCommit with autocomplete open calls commit', () => {
const commitStub = sinon.stub(element, '_commit');
suggestionsEl().isHidden = false;
element._handleInputCommit();
assert.isTrue(commitStub.calledOnce);
});
test(
'_handleInputCommit with autocomplete open calls commit' +
'with allowNonSuggestedValues',
() => {
const commitStub = sinon.stub(element, '_commit');
element.allowNonSuggestedValues = true;
suggestionsEl().isHidden = false;
element._handleInputCommit();
assert.isTrue(commitStub.calledOnce);
}
);
test('issue 8655', () => {
function makeSuggestion(s: string) {
return {name: s, text: s, value: s};
}
const keydownSpy = sinon.spy(element, '_handleKeydown');
element.setText('file:');
element._suggestions = [makeSuggestion('file:'), makeSuggestion('-file:')];
MockInteractions.pressAndReleaseKeyOn(inputEl(), 88, null, 'x');
// Must set the value, because the MockInteraction does not.
inputEl().value = 'file:x';
assert.isTrue(keydownSpy.calledOnce);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 13, null, 'enter');
assert.isTrue(keydownSpy.calledTwice);
assert.equal(element.text, 'file:x');
});
suite('focus', () => {
let commitSpy: sinon.SinonSpy;
let focusSpy: sinon.SinonSpy;
setup(() => {
commitSpy = sinon.spy(element, '_commit');
});
test('enter does not call focus', () => {
element._suggestions = [{text: 'sugar bombs'}];
focusSpy = sinon.spy(element, 'focus');
MockInteractions.pressAndReleaseKeyOn(inputEl(), 13, null, 'enter');
flush();
assert.isTrue(commitSpy.called);
assert.isFalse(focusSpy.called);
assert.equal(element._suggestions.length, 0);
});
test('tab in input, tabComplete = true', () => {
focusSpy = sinon.spy(element, 'focus');
const commitHandler = sinon.stub();
element.addEventListener('commit', commitHandler);
element.tabComplete = true;
element._suggestions = [{text: 'tunnel snakes drool'}];
MockInteractions.pressAndReleaseKeyOn(inputEl(), 9, null, 'tab');
flush();
assert.isTrue(commitSpy.called);
assert.isTrue(focusSpy.called);
assert.isFalse(commitHandler.called);
assert.equal(element._suggestions.length, 0);
});
test('tab in input, tabComplete = false', () => {
element._suggestions = [{text: 'sugar bombs'}];
focusSpy = sinon.spy(element, 'focus');
MockInteractions.pressAndReleaseKeyOn(inputEl(), 9, null, 'tab');
flush();
assert.isFalse(commitSpy.called);
assert.isFalse(focusSpy.called);
assert.equal(element._suggestions.length, 1);
});
test('tab on suggestion, tabComplete = false', async () => {
element._suggestions = [{name: 'sugar bombs'}];
element._focused = true;
// When tabComplete is false, do not focus.
element.tabComplete = false;
focusSpy = sinon.spy(element, 'focus');
flush$0();
assert.isFalse(suggestionsEl().isHidden);
MockInteractions.pressAndReleaseKeyOn(
queryAndAssert(suggestionsEl(), 'li:first-child'),
9,
null,
'Tab'
);
await flush();
assert.isFalse(commitSpy.called);
assert.isFalse(element._focused);
});
test('tab on suggestion, tabComplete = true', async () => {
element._suggestions = [{name: 'sugar bombs'}];
element._focused = true;
// When tabComplete is true, focus.
element.tabComplete = true;
focusSpy = sinon.spy(element, 'focus');
flush$0();
assert.isFalse(suggestionsEl().isHidden);
MockInteractions.pressAndReleaseKeyOn(
queryAndAssert(suggestionsEl(), 'li:first-child'),
9,
null,
'Tab'
);
await flush();
assert.isTrue(commitSpy.called);
assert.isTrue(element._focused);
});
test('tap on suggestion commits, does not call focus', () => {
focusSpy = sinon.spy(element, 'focus');
element._focused = true;
element._suggestions = [{name: 'first suggestion'}];
flush$0();
assert.isFalse(suggestionsEl().isHidden);
MockInteractions.tap(queryAndAssert(suggestionsEl(), 'li:first-child'));
flush();
assert.isFalse(focusSpy.called);
assert.isTrue(commitSpy.called);
assert.isTrue(suggestionsEl().isHidden);
});
});
test('input-keydown event fired', () => {
const listener = sinon.spy();
element.addEventListener('input-keydown', listener);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 9, null, 'tab');
flush();
assert.isTrue(listener.called);
});
test('enter with modifier does not complete', () => {
const handleSpy = sinon.spy(element, '_handleKeydown');
const commitStub = sinon.stub(element, '_handleInputCommit');
MockInteractions.pressAndReleaseKeyOn(inputEl(), 13, 'ctrl', 'enter');
assert.isTrue(handleSpy.called);
assert.isFalse(commitStub.called);
MockInteractions.pressAndReleaseKeyOn(inputEl(), 13, null, 'enter');
assert.isTrue(commitStub.called);
});
suite('warnUncommitted', () => {
let inputClassList: DOMTokenList;
setup(() => {
inputClassList = inputEl().classList;
});
test('enabled', () => {
element.warnUncommitted = true;
element.text = 'blah blah blah';
MockInteractions.blur(inputEl());
assert.isTrue(inputClassList.contains('warnUncommitted'));
MockInteractions.focus(inputEl());
assert.isFalse(inputClassList.contains('warnUncommitted'));
});
test('disabled', () => {
element.warnUncommitted = false;
element.text = 'blah blah blah';
MockInteractions.blur(inputEl());
assert.isFalse(inputClassList.contains('warnUncommitted'));
});
test('no text', () => {
element.warnUncommitted = true;
element.text = '';
MockInteractions.blur(inputEl());
assert.isFalse(inputClassList.contains('warnUncommitted'));
});
});
}); | the_stack |
declare class TNSTwitter extends NSObject implements ASWebAuthenticationPresentationContextProviding, SFSafariViewControllerDelegate {
static alloc(): TNSTwitter; // inherited from NSObject
static handleOpenURL(url: string, callbackURL: string, isSSO: boolean): boolean;
static new(): TNSTwitter; // inherited from NSObject
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor();
authorizeWithBrowser(controller: UIViewController, callbackURL: string, callback: (p1: string, p2: NSError) => void): void;
authorizeWithSSO(callback: (p1: string, p2: NSError) => void): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
init(consumerKey: string, consumerSecret: string): this;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
presentationAnchorForWebAuthenticationSession(session: ASWebAuthenticationSession): UIWindow;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
safariViewControllerActivityItemsForURLTitle(controller: SFSafariViewController, URL: NSURL, title: string): NSArray<UIActivity>;
safariViewControllerDidCompleteInitialLoad(controller: SFSafariViewController, didLoadSuccessfully: boolean): void;
safariViewControllerDidFinish(controller: SFSafariViewController): void;
safariViewControllerExcludedActivityTypesForURLTitle(controller: SFSafariViewController, URL: NSURL, title: string): NSArray<string>;
safariViewControllerInitialLoadDidRedirectToURL(controller: SFSafariViewController, URL: NSURL): void;
safariViewControllerWillOpenInBrowser(controller: SFSafariViewController): void;
self(): this;
verifyUser(includeEntities: boolean, skipStatus: boolean, includeEmail: boolean, callback: (p1: string, p2: NSError) => void): void;
}
declare class TNSTwitterAppDelegate extends UIResponder implements UIApplicationDelegate {
static alloc(): TNSTwitterAppDelegate; // inherited from NSObject
static new(): TNSTwitterAppDelegate; // inherited from NSObject
callback: string;
ssoCallback: string;
useSSO: boolean;
static readonly sharedInstance: TNSTwitterAppDelegate;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
window: UIWindow; // inherited from UIApplicationDelegate
readonly // inherited from NSObjectProtocol
applicationConfigurationForConnectingOptions(application: UIApplication, connectingSceneSession: UISceneSession, options: UISceneConnectionOptions): UISceneConfiguration;
applicationConfigurationForConnectingSceneSessionOptions(application: UIApplication, connectingSceneSession: UISceneSession, options: UISceneConnectionOptions): UISceneConfiguration;
applicationContinueUserActivityRestorationHandler(application: UIApplication, userActivity: NSUserActivity, restorationHandler: (p1: NSArray<UIUserActivityRestoring>) => void): boolean;
applicationDidBecomeActive(application: UIApplication): void;
applicationDidChangeStatusBarFrame(application: UIApplication, oldStatusBarFrame: CGRect): void;
applicationDidChangeStatusBarOrientation(application: UIApplication, oldStatusBarOrientation: UIInterfaceOrientation): void;
applicationDidDecodeRestorableStateWithCoder(application: UIApplication, coder: NSCoder): void;
applicationDidDiscardSceneSessions(application: UIApplication, sceneSessions: NSSet<UISceneSession>): void;
applicationDidEnterBackground(application: UIApplication): void;
applicationDidFailToContinueUserActivityWithTypeError(application: UIApplication, userActivityType: string, error: NSError): void;
applicationDidFailToRegisterForRemoteNotificationsWithError(application: UIApplication, error: NSError): void;
applicationDidFinishLaunching(application: UIApplication): void;
applicationDidFinishLaunchingWithOptions(application: UIApplication, launchOptions: NSDictionary<string, any>): boolean;
applicationDidReceiveLocalNotification(application: UIApplication, notification: UILocalNotification): void;
applicationDidReceiveMemoryWarning(application: UIApplication): void;
applicationDidReceiveRemoteNotification(application: UIApplication, userInfo: NSDictionary<any, any>): void;
applicationDidReceiveRemoteNotificationFetchCompletionHandler(application: UIApplication, userInfo: NSDictionary<any, any>, completionHandler: (p1: UIBackgroundFetchResult) => void): void;
applicationDidRegisterForRemoteNotificationsWithDeviceToken(application: UIApplication, deviceToken: NSData): void;
applicationDidRegisterUserNotificationSettings(application: UIApplication, notificationSettings: UIUserNotificationSettings): void;
applicationDidUpdateUserActivity(application: UIApplication, userActivity: NSUserActivity): void;
applicationHandleActionWithIdentifierForLocalNotificationCompletionHandler(application: UIApplication, identifier: string, notification: UILocalNotification, completionHandler: () => void): void;
applicationHandleActionWithIdentifierForLocalNotificationWithResponseInfoCompletionHandler(application: UIApplication, identifier: string, notification: UILocalNotification, responseInfo: NSDictionary<any, any>, completionHandler: () => void): void;
applicationHandleActionWithIdentifierForRemoteNotificationCompletionHandler(application: UIApplication, identifier: string, userInfo: NSDictionary<any, any>, completionHandler: () => void): void;
applicationHandleActionWithIdentifierForRemoteNotificationWithResponseInfoCompletionHandler(application: UIApplication, identifier: string, userInfo: NSDictionary<any, any>, responseInfo: NSDictionary<any, any>, completionHandler: () => void): void;
applicationHandleEventsForBackgroundURLSessionCompletionHandler(application: UIApplication, identifier: string, completionHandler: () => void): void;
applicationHandleIntentCompletionHandler(application: UIApplication, intent: INIntent, completionHandler: (p1: INIntentResponse) => void): void;
applicationHandleOpenURL(application: UIApplication, url: NSURL): boolean;
applicationHandleWatchKitExtensionRequestReply(application: UIApplication, userInfo: NSDictionary<any, any>, reply: (p1: NSDictionary<any, any>) => void): void;
applicationHandlerForIntent(application: UIApplication, intent: INIntent): any;
applicationOpenOptions(application: UIApplication, url: NSURL, options: NSDictionary<string, any>): boolean;
applicationOpenURLOptions(app: UIApplication, url: NSURL, options: NSDictionary<string, any>): boolean;
applicationOpenURLSourceApplicationAnnotation(application: UIApplication, url: NSURL, sourceApplication: string, annotation: any): boolean;
applicationPerformActionForShortcutItemCompletionHandler(application: UIApplication, shortcutItem: UIApplicationShortcutItem, completionHandler: (p1: boolean) => void): void;
applicationPerformFetchWithCompletionHandler(application: UIApplication, completionHandler: (p1: UIBackgroundFetchResult) => void): void;
applicationProtectedDataDidBecomeAvailable(application: UIApplication): void;
applicationProtectedDataWillBecomeUnavailable(application: UIApplication): void;
applicationShouldAllowExtensionPointIdentifier(application: UIApplication, extensionPointIdentifier: string): boolean;
applicationShouldAutomaticallyLocalizeKeyCommands(application: UIApplication): boolean;
applicationShouldRequestHealthAuthorization(application: UIApplication): void;
applicationShouldRestoreApplicationState(application: UIApplication, coder: NSCoder): boolean;
applicationShouldRestoreSecureApplicationState(application: UIApplication, coder: NSCoder): boolean;
applicationShouldSaveApplicationState(application: UIApplication, coder: NSCoder): boolean;
applicationShouldSaveSecureApplicationState(application: UIApplication, coder: NSCoder): boolean;
applicationSignificantTimeChange(application: UIApplication): void;
applicationSupportedInterfaceOrientationsForWindow(application: UIApplication, window: UIWindow): UIInterfaceOrientationMask;
applicationUserDidAcceptCloudKitShareWithMetadata(application: UIApplication, cloudKitShareMetadata: CKShareMetadata): void;
applicationViewControllerWithRestorationIdentifierPathCoder(application: UIApplication, identifierComponents: NSArray<string> | string[], coder: NSCoder): UIViewController;
applicationWillChangeStatusBarFrame(application: UIApplication, newStatusBarFrame: CGRect): void;
applicationWillChangeStatusBarOrientationDuration(application: UIApplication, newStatusBarOrientation: UIInterfaceOrientation, duration: number): void;
applicationWillContinueUserActivityWithType(application: UIApplication, userActivityType: string): boolean;
applicationWillEncodeRestorableStateWithCoder(application: UIApplication, coder: NSCoder): void;
applicationWillEnterForeground(application: UIApplication): void;
applicationWillFinishLaunchingWithOptions(application: UIApplication, launchOptions: NSDictionary<string, any>): boolean;
applicationWillResignActive(application: UIApplication): void;
applicationWillTerminate(application: UIApplication): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
} | the_stack |
import { Component, State, Element, h } from '@stencil/core';
import Utils from '@visa/visa-charts-utils';
import '@visa/visa-charts-data-table';
import '@visa/keyboard-instructions';
const { findTagLevel } = Utils;
@Component({
tag: 'app-bar-chart',
styleUrl: 'app-bar-chart.scss'
})
export class AppBarChart {
@State() highestHeadingLevel: string | number = 'h3';
@State() data: any;
@State() stateTrigger: any = 0;
@State() width: number = 800;
@State() hoverElement: any = '';
@State() chartUpdates: string;
@State() barIntervalRatio = 0.15;
@State() padding: any = {
top: 20,
left: 60,
right: 30,
bottom: 40
};
@State() uniqueID: string = 'thisIsUnique';
@State() dataLabel: any = {
visible: true,
placement: 'left',
labelAccessor: 'value',
format: '0.0[a]',
collisionPlacement: 'left',
collisionHideOnly: true
};
@State() tooltipLabel: any = {
labelAccessor: ['region', 'country', 'value'],
labelTitle: ['', 'country', 'value'],
format: ['', '', '0,0[.0][a]']
};
@State() clickElement: any = [
// { country: 'Japan', otherValue: '24', value: '3', region: 'Asia', test: 'Group A', nonSense: 'test' }
];
@State() interactionState: any = ['region'];
@State() valueAccessor: any = 'value';
@State() groupAccessor: any = 'region';
@State() ordinalAccessor: any = 'country';
@State() hoverElementTest: any = '';
@State() clickElementTest: any = [];
@State() suppressEvents: boolean = false;
@State() animations: any = { disabled: false };
@State() accessibility: any = {
elementDescriptionAccessor: 'note', // see Indonesia above
longDescription:
'This is a bar chart that shows spending (in millions) on purchases in select market segments, across the top ten countries.',
contextExplanation: 'This chart is the output of filters involving market segment selection.',
executiveSummary:
'Indonesia has a massive spend per capita, second in volume only to the US at one hundred eleven million dollars.',
purpose:
'Looking at the top ten countries by spend on a market segment can help show outliers or emerging market leaders in this area.',
structureNotes: 'The bars are sorted in descending order and colored according to their regional grouping.',
statisticalNotes:
'Values here represent total spend in raw volume by market segment. These values are the sum of FY19 performance.',
onChangeFunc: d => {
this.onChangeFunc(d);
},
showSmallLabels: true,
hideDataTableButton: false,
elementsAreInterface: true,
disableValidation: false,
keyboardNavConfig: { disabled: false }
};
@State() annotations: any = [
{
note: {
label: '2018',
bgPadding: 0,
align: 'middle',
wrap: 210
},
accessibilityDescription: '2018 High Spend band total is 5,596',
x: '8%',
y: '40%',
disable: ['connector', 'subject'],
// dy: '-1%',
color: '#000000',
className: 'testing1 testing2 testing3',
collisionHideOnly: true
},
{
note: {
label: 'oasijfoiajsf',
bgPadding: 0,
align: 'middle',
wrap: 210
},
accessibilityDescription: '2018 High Spend band total is 5,596',
x: '8%',
y: '40%',
disable: ['connector', 'subject'],
// dy: '-1%',
color: '#000000',
className: 'testing1 testing2 testing3',
collisionHideOnly: false
}
// {
// note: {
// label: "China's Volume-per-capita is massively under market performance.",
// bgPadding: 20,
// title: 'Low Volume Per Capita',
// align: 'middle',
// wrap: 210
// },
// accessibilityDescription:
// 'This annotation is a callout to China, which only has 27 million volume but 1.3 billion people.',
// data: { country: 'China', value: '27', region: 'Asia' },
// dy: '-20%',
// color: 'categorical_blue'
// }
];
hoverStyle: any = {
color: '#979db7',
strokeWidth: 1.5
};
clickStyle: any = {
color: '#8fdcc7',
strokeWidth: 8
};
// colors: any = ['#2e3047', '#43455c', '#3c3f58'];
colors: any = ['#EDEEF3', '#A8AABB', '#6C6E86', '#3c3f58'];
// colors: any = ['#EBF4FA','#F2F2FF', '#FAFDF6'];
startData: any = [
{
country: 'China',
otherValue: '37',
value: '27',
region: 'Asia',
test: 'Group A',
tempDate: new Date(1986, 0, 2, 11, 39, 13),
nonSense: 'test'
},
{ country: 'Japan', otherValue: '24', value: '3', region: 'Asia', test: 'Group A', nonSense: 'test' },
{ country: 'Thailand', otherValue: '7', value: '52', region: 'Asia', test: 'Group A', nonSense: 'test' },
{
country: 'United States',
otherValue: '30',
value: '121',
region: 'North America',
test: 'Group A',
tempDate: new Date(2018, 0, 2, 11, 39, 13),
nonSense: 'test'
},
{ country: 'Canada', otherValue: '20', value: '24', test: 'Group A', region: 'North America', nonSense: 'test' },
{ country: 'India', otherValue: '37', value: '21', test: 'Group b', region: 'Asia', nonSense: 'test' },
{
country: 'Indonesia',
otherValue: '3',
value: '73',
test: 'Group b',
region: 'Asia',
note: 'The per capita ranking is 947% above the median',
nonSense: 'test'
},
{ country: 'Germany', otherValue: '16', value: '61', test: 'Group b', region: 'Europe', nonSense: 'test' },
{ country: 'Turkey', otherValue: '21', value: '28', test: 'Group b', region: 'Europe', nonSense: 'test' },
{ country: 'Italy', otherValue: '47', value: '7', test: 'Group b', region: 'Europe', nonSense: 'test' }
];
dataStorage: any = [
this.startData,
[
{
country: 'China',
otherValue: '37',
value: '27',
region: 'Asia',
test: 'Group A',
tempDate: new Date(1986, 0, 2, 11, 39, 13),
nonSense: 'test'
},
{ country: 'Japan', otherValue: '24', value: '5', region: 'Asia', test: 'Group A', nonSense: 'test' },
{ country: 'Thailand', otherValue: '7', value: '52', region: 'Asia', test: 'Group A', nonSense: 'test' },
{ country: 'India', otherValue: '37', value: '21', test: 'Group b', region: 'Asia', nonSense: 'test' },
{
country: 'Indonesia',
otherValue: '3',
value: '73',
test: 'Group b',
region: 'Asia',
note: 'The per capita ranking is 947% above the median',
nonSense: 'test'
}
],
[
{
country: 'China',
otherValue: '37',
value: '27',
region: 'Asia',
test: 'Group A',
tempDate: new Date(1986, 0, 2, 11, 39, 13),
nonSense: 'test'
},
{ country: 'Japan', otherValue: '24', value: '10', region: 'Asia', test: 'Group A', nonSense: 'test' },
{ country: 'Thailand', otherValue: '7', value: '52', region: 'Asia', test: 'Group A', nonSense: 'test' },
{
country: 'United States',
otherValue: '30',
value: '121',
region: 'North America',
test: 'Group A',
tempDate: new Date(2018, 0, 2, 11, 39, 13),
nonSense: 'test'
},
{ country: 'Canada', otherValue: '20', value: '24', test: 'Group A', region: 'North America', nonSense: 'test' },
{ country: 'India', otherValue: '37', value: '21', test: 'Group b', region: 'Asia', nonSense: 'test' },
{
country: 'Indonesia',
otherValue: '3',
value: '73',
test: 'Group b',
region: 'Asia',
note: 'The per capita ranking is 947% above the median.',
nonSense: 'test'
},
{ country: 'Germany', otherValue: '16', value: '61', test: 'Group b', region: 'Europe', nonSense: 'test' },
{ country: 'Turkey', otherValue: '21', value: '48', test: 'Group b', region: 'Europe', nonSense: 'test' },
{ country: 'Italy', otherValue: '47', value: '16', test: 'Group b', region: 'Europe', nonSense: 'test' }
],
this.startData,
[
{
country: 'China',
otherValue: '37',
value: '27',
region: 'Asia',
test: 'Group A',
tempDate: new Date(1986, 0, 2, 11, 39, 13),
nonSense: 'test'
},
{ country: 'Japan', otherValue: '24', value: '10', region: 'Asia', test: 'Group A', nonSense: 'test' },
{ country: 'Thailand', otherValue: '7', value: '52', region: 'Asia', test: 'Group A', nonSense: 'test' },
{
country: 'United States',
otherValue: '30',
value: '121',
region: 'North America',
test: 'Group A',
tempDate: new Date(2018, 0, 2, 11, 39, 13),
nonSense: 'test'
},
{ country: 'Canada', otherValue: '20', value: '24', test: 'Group A', region: 'North America', nonSense: 'test' },
{ country: 'India', otherValue: '37', value: '21', test: 'Group b', region: 'Asia', nonSense: 'test' },
{
country: 'Indonesia',
otherValue: '3',
value: '73',
test: 'Group b',
region: 'Asia',
note: 'The per capita ranking is 947% above the median.',
nonSense: 'test'
},
{ country: 'Germany', otherValue: '16', value: '61', test: 'Group b', region: 'Europe', nonSense: 'test' },
{ country: 'Turkey', otherValue: '21', value: '28', test: 'Group b', region: 'Europe', nonSense: 'test' },
{ country: 'Italy', otherValue: '47', value: '16', test: 'Group b', region: 'Europe', nonSense: 'test' }
],
[
{ country: 'China', value: '17', region: 'Asia' },
{ country: 'Japan', value: '10', region: 'Asia' },
{ country: 'Thailand', value: '30', region: 'Asia' },
{ country: 'United States', value: '114', region: 'North America' },
{ country: 'Canada', value: '24', region: 'North America' },
{ country: 'India', value: '21', region: 'Asia' },
{
country: 'Indonesia',
value: '111',
region: 'Asia',
note: 'The per capita ranking is 947% above the median.'
},
{ country: 'Germany', value: '38', region: 'Europe' },
{ country: 'Turkey', value: '28', region: 'Europe' },
{ country: 'Italy', value: '16', region: 'Europe' }
],
[
{ country: 'China', value: '17', region: 'Asia' },
{ country: 'Japan', value: '10', region: 'Asia' },
{ country: 'Thailand', value: '30', region: 'Asia' },
{ country: 'United States', value: '114', region: 'North America' },
{ country: 'Canada', value: '24', region: 'North America' },
{ country: 'India', value: '21', region: 'Asia' },
{
country: 'Indonesia',
value: '111',
region: 'Asia',
note: 'The per capita ranking is 947% above the median.'
},
{ country: 'Turkey', value: '28', region: 'Europe' },
{ country: 'Italy', value: '16', region: 'Europe' }
],
[
{ country: 'China', value: '17', region: 'Asia' },
{ country: 'S. Korea', value: '9', region: 'Asia' },
{ country: 'Japan', value: '10', region: 'Asia' },
{ country: 'Thailand', value: '30', region: 'Asia' },
{ country: 'United States', value: '114', region: 'North America' },
{ country: 'Canada', value: '24', region: 'North America' },
{ country: 'India', value: '21', region: 'Asia' },
{
country: 'Indonesia',
value: '111',
region: 'Asia',
note: 'The per capita ranking is 947% above the median.'
},
{ country: 'Turkey', value: '28', region: 'Europe' },
{ country: 'Italy', value: '16', region: 'Europe' }
],
[
{ country: 'China', value: '27', region: 'Asia' },
{ country: 'Japan', value: '10', region: 'Asia' },
{ country: 'Thailand', value: '30', region: 'Asia' },
{ country: 'United States', value: '114', region: 'North America' },
{ country: 'Canada', value: '24', region: 'North America' },
{ country: 'India', value: '21', region: 'Asia' },
{
country: 'Indonesia',
value: '111',
region: 'Asia',
note: 'The per capita ranking is 947% above the median.'
},
{ country: 'Germany', value: '38', region: 'Europe' },
{ country: 'Turkey', value: '28', region: 'Europe' },
{ country: 'Italy', value: '16', region: 'Europe' }
],
[
{ country: 'China', value: '27', region: 'Asia' },
{ country: 'Japan', value: '40', region: 'Asia' },
{ country: 'Thailand', value: '30', region: 'Asia' },
{ country: 'United States', value: '114', region: 'North America' },
{ country: 'Canada', value: '24', region: 'North America' },
{ country: 'India', value: '21', region: 'Asia' },
{
country: 'Indonesia',
value: '111',
region: 'Asia',
note: 'The per capita ranking is 947% above the median.'
},
{ country: 'Germany', value: '38', region: 'Europe' },
{ country: 'Turkey', value: '28', region: 'Europe' },
{ country: 'Italy', value: '16', region: 'Europe' }
],
this.startData
];
exampleData: any = [
{
name: 'Chris',
power: 'Can Fly',
role: 'Hero',
stat: 10
},
{
name: 'Akhil',
power: 'Can Change Time',
role: 'Hero',
stat: 3
},
{
name: 'Basav',
power: 'Can Change Time',
role: 'Wizard',
stat: 2
},
{
name: 'Frank',
power: 'Can Teleport',
role: 'Wizard',
stat: 2
},
{
name: 'Jaime',
power: 'Can Teleport',
role: 'Hero',
stat: 2
},
{
name: 'Layla',
power: 'Can Fly',
role: 'Wizard',
stat: 1
}
];
yAxis: any = {
gridVisible: true,
visible: true,
label: 'y axis',
format: '0.0[a]'
};
legend: any = { visible: true, interactive: true, labels: [] };
@Element()
appEl: HTMLElement;
componentWillLoad() {
this.data = this.dataStorage[this.stateTrigger];
}
onClickFunc(d) {
const index = this.clickElement.indexOf(d.detail);
const newClicks = [...this.clickElement];
if (index > -1) {
newClicks.splice(index, 1);
} else {
newClicks.push(d.detail);
}
this.clickElement = newClicks;
}
onHoverFunc(d) {
this.hoverElement = d.detail;
}
onMouseOut() {
this.hoverElement = '';
}
onChangeFunc(d) {
if (d.updated && (d.removed || d.added)) {
let updates = 'The bar chart has ';
if (d.removed) {
updates += 'removed ' + d.removed + ' bar' + (d.removed > 1 ? 's ' : ' ');
}
if (d.added) {
updates += (d.removed ? 'and ' : '') + 'added ' + d.added + (d.removed ? '' : d.added > 1 ? ' bars' : ' bar');
}
this.chartUpdates = updates;
} else if (d.updated) {
const newUpdate = "The chart's data has changed, but no bars were removed or added.";
this.chartUpdates =
newUpdate !== this.chartUpdates
? newUpdate
: "The chart's data has changed again, but no bars were removed or added.";
} else {
const newUpdate = "The chart's has updated, but no change to the data was made.";
this.chartUpdates =
newUpdate !== this.chartUpdates
? newUpdate
: "The chart's has updated again, but no change to the data was made.";
}
}
changeData() {
setTimeout(() => {
if (this.uniqueID !== 'POTENTIALLY_BUGGY_ID_CHANGE') {
this.uniqueID = 'POTENTIALLY_BUGGY_ID_CHANGE';
}
}, 10000);
this.stateTrigger = this.stateTrigger < this.dataStorage.length - 1 ? this.stateTrigger + 1 : 0;
this.data = this.dataStorage[this.stateTrigger];
}
changeDimension() {
this.padding =
this.padding.left === 60
? {
top: 20,
left: 150,
right: 180,
bottom: 40
}
: {
top: 20,
left: 60,
right: 30,
bottom: 40
};
this.width = this.width === 800 ? 700 : 800;
}
changeAccessElements() {
this.accessibility = {
...this.accessibility,
elementsAreInterface: !this.accessibility.elementsAreInterface
};
}
toggleAnimations() {
this.animations = { disabled: !this.animations.disabled };
}
changeExperimental() {
this.accessibility = {
...this.accessibility,
showExperimentalTextures: !this.accessibility.showExperimentalTextures
};
}
changeKeyNav() {
const keyboardNavConfig = {
disabled: !this.accessibility.keyboardNavConfig.disabled
};
this.accessibility = {
...this.accessibility,
keyboardNavConfig
};
}
contextExplanation() {
const newContextExplanation = this.accessibility.contextExplanation
? ''
: 'This chart is the output of filters involving market segment selection.';
this.accessibility = { ...this.accessibility, contextExplanation: newContextExplanation };
}
longDescription() {
const newLongDescription = this.accessibility.longDescription
? ''
: 'This is a bar chart that shows spending (in millions) on purchases in select market segments, across the top ten countries.';
this.accessibility = { ...this.accessibility, longDescription: newLongDescription };
}
changeLabels() {
this.dataLabel =
this.dataLabel.placement === 'top'
? {
visible: true, // !this.dataLabel.visible,
placement: 'bottom',
labelAccessor: 'value',
format: '0.0[a]'
}
: {
visible: true, // !this.dataLabel.visible,
placement: 'top',
labelAccessor: 'value',
format: '0.0[a]'
};
}
changeTooltip() {
this.tooltipLabel = { labelAccessor: ['value', 'test'], labelTitle: ['', ''], format: ['0,0[.0][a]', ''] };
}
changeInteraction() {
// this.valueAccessor !== 'value' ? (this.valueAccessor = 'value') : (this.valueAccessor = 'otherValue');
this.interactionState = this.interactionState[0] !== 'region' ? ['region'] : ['country'];
const shouldBeInteractive = this.interactionState[0] === 'region';
this.legend = { ...this.legend, interactive: shouldBeInteractive };
}
changeValueAccessor() {
// this.valueAccessor !== 'value' ? (this.valueAccessor = 'value') : (this.valueAccessor = 'otherValue');
this.valueAccessor = this.valueAccessor !== 'value' ? 'value' : 'otherValue';
}
changeOrdinalAccessor() {
// this.valueAccessor !== 'value' ? (this.valueAccessor = 'value') : (this.valueAccessor = 'otherValue');
this.ordinalAccessor = this.ordinalAccessor !== 'country' ? 'country' : 'value';
}
changeGroupAccessor() {
// this.valueAccessor !== 'value' ? (this.valueAccessor = 'value') : (this.valueAccessor = 'otherValue');
this.groupAccessor = this.groupAccessor !== 'region' ? 'region' : null;
}
toggleTextures() {
const newAccess = { ...this.accessibility };
newAccess.hideTextures = !newAccess.hideTextures;
this.accessibility = newAccess;
}
toggleStrokes() {
const newAccess = { ...this.accessibility };
newAccess.hideStrokes = !newAccess.hideStrokes;
this.accessibility = newAccess;
}
changeInterval() {
this.barIntervalRatio = this.barIntervalRatio === 0.05 ? 0.5 : 0.05;
}
toggleSuppress() {
this.suppressEvents = !this.suppressEvents;
}
toggleSmallLabels() {
const newAccess = { ...this.accessibility };
newAccess.showSmallLabels = !newAccess.showSmallLabels;
this.accessibility = newAccess;
}
onTestClickFunc(d) {
const index = this.clickElementTest.indexOf(d);
const newClicks = [...this.clickElementTest];
if (index > -1) {
newClicks.splice(index, 1);
} else {
newClicks.push(d);
}
this.clickElementTest = newClicks;
}
onTestHoverFunc(d) {
this.hoverElementTest = d;
}
onTestMouseOut() {
this.hoverElementTest = '';
}
handleInput = e => {
e.preventDefault();
this.highestHeadingLevel = e.target[0].value;
};
render() {
return (
<div>
{/* <div role="alert" aria-live="polite"> */}
<div>
<p>{this.chartUpdates}</p>
</div>
<bar-chart
data={this.data}
mainTitle={
'Heading prop received: ' +
this.highestHeadingLevel +
'. Highest becomes <' +
findTagLevel(this.highestHeadingLevel) +
'>. '
}
subTitle={
'Heading prop received: ' +
this.highestHeadingLevel +
'. Lowest becomes <' +
findTagLevel(this.highestHeadingLevel, 3) +
'>.'
}
height={400}
width={this.width}
animationConfig={this.animations}
yAxis={this.yAxis}
padding={this.padding}
suppressEvents={this.suppressEvents}
ordinalAccessor={this.ordinalAccessor}
valueAccessor={this.valueAccessor}
groupAccessor={this.groupAccessor}
// yAccessor={'region'}
// xAccessor={'value'}
layout={'horizontal'}
sortOrder="asc"
dataLabel={this.dataLabel}
tooltipLabel={this.tooltipLabel}
colorPalette={'sequential_grey'} // categorical // sequential_grey // diverging_GtoP // diverging_GtoP
// colors={this.colors}
legend={this.legend}
cursor={'pointer'}
barIntervalRatio={this.barIntervalRatio}
hoverOpacity={0.99999}
interactionKeys={this.interactionState}
// interactionKeys={['region']}
hoverHighlight={this.hoverElement}
clickHighlight={this.clickElement}
onClickFunc={d => this.onClickFunc(d)}
onHoverFunc={d => this.onHoverFunc(d)}
onMouseOutFunc={() => this.onMouseOut()}
hoverStyle={this.hoverStyle}
clickStyle={this.clickStyle}
accessibility={this.accessibility}
uniqueID={this.uniqueID}
// annotations={this.annotations}
highestHeadingLevel={this.highestHeadingLevel}
/>
<span>
<form onSubmit={this.handleInput}>
Type a heading level (1, 2, 3, h1, h4, div, p, span, etc)
<input style={{ padding: '10px' }} type="text" id="highestHeadingLevel" name="highestHeadingLevel" />
<input type="submit" value="Submit" />
</form>
</span>
<button
onClick={() => {
this.toggleAnimations();
}}
>
toggle animations
</button>
<button
onClick={() => {
this.changeAccessElements();
}}
>
change elementsAreInterface
</button>
<button
onClick={() => {
this.toggleSuppress();
}}
>
toggle event suppression
</button>
<button
onClick={() => {
this.changeKeyNav();
}}
>
toggle keyboard nav
</button>
<button
onClick={() => {
this.changeExperimental();
}}
>
toggle experimental textures
</button>
<button
onClick={() => {
this.longDescription();
}}
>
toggle longDescription
</button>
<button
onClick={() => {
this.contextExplanation();
}}
>
toggle contextExplanation
</button>
<button
onClick={() => {
this.changeData();
}}
>
change data
</button>
<button
onClick={() => {
this.toggleTextures();
}}
>
toggle textures
</button>
<button
onClick={() => {
this.toggleStrokes();
}}
>
toggle strokes
</button>
<button
onClick={() => {
this.toggleSmallLabels();
}}
>
toggle small labels
</button>
<button
onClick={() => {
this.changeInterval();
}}
>
change bar interval
</button>
<button
onClick={() => {
this.changeInteraction();
}}
>
change interaction key
</button>
<button
onClick={() => {
this.changeDimension();
}}
>
change dimension
</button>
<button
onClick={() => {
this.changeLabels();
}}
>
change labels
</button>
<button
onClick={() => {
this.changeValueAccessor();
}}
>
change value accessor
</button>
<button
onClick={() => {
this.changeOrdinalAccessor();
}}
>
change ordinal accessor
</button>
<button
onClick={() => {
this.changeGroupAccessor();
}}
>
change group accessor
</button>
<button
onClick={() => {
this.changeTooltip();
}}
>
change tooltip Label
</button>
{/* <bar-chart
data={this.exampleData}
mainTitle={'Test'}
subTitle={'example'}
height={400}
width={400}
yAxis={{
visible: true,
label: 'stat',
format: '0.0[a]'
}}
padding={{
top: 20,
left: 60,
right: 30,
bottom: 40
}}
ordinalAccessor={'name'}
valueAccessor={'stat'}
groupAccessor={'power'}
sortOrder="desc"
dataLabel={{ visible: true, placement: 'bottom', labelAccessor: 'stat', format: '0,0[.0][a]' }}
tooltipLabel={{
labelAccessor: ['name', 'stat', 'power', 'role'],
labelTitle: ['', '', '', ''],
format: ['', '0,0[.0][a]', '', '']
}}
colorPalette={'categorical'}
legend={{ visible: true, interactive: true }}
cursor={'pointer'}
hoverOpacity={0.2}
interactionKeys={['power', 'role']}
hoverHighlight={this.hoverElementTest}
clickHighlight={this.clickElementTest}
onClickFunc={d => this.onTestClickFunc(d)}
onHoverFunc={d => this.onTestHoverFunc(d)}
onMouseOutFunc={() => this.onTestMouseOut()}
accessibility={{
elementDescriptionAccessor: 'note', // see Indonesia above
longDescription:
'This is a bar chart that shows spending (in millions) on purchases in select market segments, across the top ten countries.',
contextExplanation: 'This chart is the output of filters involving market segment selection.',
executiveSummary:
'Indonesia has a massive spend per capita, second in volume only to the US at one hundred eleven million dollars.',
purpose:
'Looking at the top ten countries by spend on a market segment can help show outliers or emerging market leaders in this area.',
structureNotes: 'The bars are sorted in descending order and colored according to their regional grouping.',
statisticalNotes:
'Values here represent total spend in raw volume by market segment. These values are the sum of FY19 performance.',
onChangeFunc: () => {},
elementsAreInterface: false,
hideDataTableButton: true
}}
uniqueID={'test'}
/> */}
</div>
);
}
} | the_stack |
import { HttpEvent, HttpEventType } from '@angular/common/http';
import { NEVER, Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import {
ApiConfig,
ApiOptions,
NONE_PARSER,
Parser,
PathSegmentNames,
} from './types';
import { EDM_PARSERS } from './parsers/index';
import {
ODataSchema,
ODataEnumType,
ODataCallable,
ODataEntitySet,
ODataStructuredType,
} from './schema/index';
import { ODataModel, ODataCollection, ODataModelOptions } from './models/index';
import {
ODataBatchResource,
ODataMetadataResource,
ODataEntitySetResource,
ODataSingletonResource,
ODataFunctionResource,
ODataActionResource,
ODataEntityResource,
ODataPathSegments,
ODataSegment,
ODataQueryOptions,
ODataResponse,
ODataNavigationPropertyResource,
ODataRequest,
} from './resources/index';
import { ODataCache, ODataInMemoryCache } from './cache/index';
import { ODataApiOptions } from './options';
import { DEFAULT_VERSION } from './constants';
import { ODataEntityService } from './services/entity';
/**
* Api abstraction for consuming OData services.
*/
export class ODataApi {
requester?: (request: ODataRequest<any>) => Observable<any>;
serviceRootUrl: string;
metadataUrl: string;
name?: string;
version: string;
default: boolean;
creation: Date;
// Options
options: ODataApiOptions;
// Cache
cache!: ODataCache;
// Error Handler
errorHandler?: (error: any, caught: Observable<any>) => Observable<never>;
// Base Parsers
parsers: { [type: string]: Parser<any> };
// Schemas
schemas: ODataSchema[];
constructor(config: ApiConfig) {
this.serviceRootUrl = config.serviceRootUrl;
if (this.serviceRootUrl.indexOf('?') != -1)
throw new Error(
"The 'serviceRootUrl' should not contain query string. Please use 'params' to add extra parameters"
);
if (!this.serviceRootUrl.endsWith('/')) this.serviceRootUrl += '/';
this.metadataUrl = `${this.serviceRootUrl}$metadata`;
this.name = config.name;
this.version = config.version || DEFAULT_VERSION;
this.default = config.default || false;
this.creation = config.creation || new Date();
this.options = new ODataApiOptions(
Object.assign(<ApiOptions>{ version: this.version }, config.options || {})
);
this.cache = (config.cache as ODataCache) || new ODataInMemoryCache();
this.errorHandler = config.errorHandler;
this.parsers = config.parsers || EDM_PARSERS;
this.schemas = (config.schemas || []).map(
(schema) => new ODataSchema(schema, this)
);
}
configure(
settings: {
requester?: (request: ODataRequest<any>) => Observable<any>;
} = {}
) {
this.requester = settings.requester;
this.schemas.forEach((schema) => {
schema.configure({
parserForType: (type: string) => this.parserForType(type),
findOptionsForType: (type: string) => this.findOptionsForType(type),
});
});
}
fromJSON<P, R>(json: {
segments: ODataSegment[];
options: { [name: string]: any };
}): ODataActionResource<P, R> | ODataFunctionResource<P, R>;
fromJSON<E>(json: {
segments: ODataSegment[];
options: { [name: string]: any };
}):
| ODataEntityResource<E>
| ODataEntitySetResource<E>
| ODataNavigationPropertyResource<E>
| ODataSingletonResource<E>;
fromJSON(json: {
segments: ODataSegment[];
options: { [name: string]: any };
}) {
const segments = new ODataPathSegments(json.segments);
const query = new ODataQueryOptions(json.options);
switch (segments.last()?.name as PathSegmentNames) {
case PathSegmentNames.entitySet:
if (segments.last()?.hasKey()) {
return new ODataEntityResource(this, segments, query);
} else {
return new ODataEntitySetResource(this, segments, query);
}
case PathSegmentNames.navigationProperty:
return new ODataNavigationPropertyResource(this, segments, query);
case PathSegmentNames.singleton:
return new ODataSingletonResource(this, segments, query);
case PathSegmentNames.action:
return new ODataActionResource(this, segments, query);
case PathSegmentNames.function:
return new ODataFunctionResource(this, segments, query);
}
throw new Error('No Resource for json');
}
/**
* Build a metadata resource.
* @returns ODataMetadataResource
*/
metadata(): ODataMetadataResource {
return ODataMetadataResource.factory(this);
}
/**
* Build a batch resource.
* @returns ODataBatchResource
*/
batch(): ODataBatchResource {
return ODataBatchResource.factory(this);
}
/**
* Build a singleton resource.
* @param name Name of the singleton
* @returns
*/
singleton<T>(name: string) {
const type = this.findEntitySetByName(name)?.entityType;
return ODataSingletonResource.factory<T>(
this,
name,
type,
new ODataPathSegments(),
new ODataQueryOptions()
);
}
/**
* Build an entity set resource.
* @param name Name of the entity set
* @returns
*/
entitySet<T>(name: string): ODataEntitySetResource<T> {
const type = this.findEntitySetByName(name)?.entityType;
return ODataEntitySetResource.factory<T>(
this,
name,
type,
new ODataPathSegments(),
new ODataQueryOptions()
);
}
/**
* Unbound Action
* @param {string} name?
* @returns ODataActionResource
*/
action<P, R>(name: string): ODataActionResource<P, R> {
let type;
const callable = this.findCallableForType(name);
if (callable !== undefined) {
name = callable.path();
type = callable.type();
}
return ODataActionResource.factory<P, R>(
this,
name,
type,
new ODataPathSegments(),
new ODataQueryOptions()
);
}
/**
* Unbound Function
* @param {string} name?
* @returns ODataFunctionResource
*/
function<P, R>(name: string): ODataFunctionResource<P, R> {
let type;
const callable = this.findCallableForType(name);
if (callable !== undefined) {
name = callable.path();
type = callable.type();
}
return ODataFunctionResource.factory<P, R>(
this,
name,
type,
new ODataPathSegments(),
new ODataQueryOptions()
);
}
request(req: ODataRequest<any>): Observable<any> {
let res$ = this.requester !== undefined ? this.requester(req) : NEVER;
res$ = res$.pipe(
map((res: HttpEvent<any>) =>
res.type === HttpEventType.Response
? ODataResponse.fromHttpResponse<any>(req, res)
: res
)
);
if (this.errorHandler !== undefined)
res$ = res$.pipe(catchError(this.errorHandler));
return req.observe === 'response'
? this.cache.handleRequest(req, res$)
: res$;
}
//# region Find by Type
// Memoize
private memo: {
forType: {
enum: { [type: string]: ODataEnumType<any> | undefined };
structured: { [type: string]: ODataStructuredType<any> | undefined };
callable: { [key: string]: ODataCallable<any> | undefined };
entitySet: { [type: string]: ODataEntitySet | undefined };
parser: { [type: string]: Parser<any> };
options: { [type: string]: ODataModelOptions<any> | undefined };
};
byName: {
enum: { [type: string]: ODataEnumType<any> | undefined };
structured: { [type: string]: ODataStructuredType<any> | undefined };
callable: { [key: string]: ODataCallable<any> | undefined };
entitySet: { [type: string]: ODataEntitySet | undefined };
};
} = {
forType: {
enum: {},
structured: {},
callable: {},
entitySet: {},
parser: {},
options: {},
},
byName: { enum: {}, structured: {}, callable: {}, entitySet: {} },
};
private findSchemaForType(type: string) {
const schemas = this.schemas.filter((s) => s.isNamespaceOf(type));
if (schemas.length > 1)
return schemas
.sort((s1, s2) => s1.namespace.length - s2.namespace.length)
.pop();
if (schemas.length === 1) return schemas[0];
return undefined;
}
public findEnumTypeForType<T>(type: string) {
if (!(type in this.memo.forType.enum))
this.memo.forType.enum[type] =
this.findSchemaForType(type)?.findEnumTypeForType<T>(type);
return this.memo.forType.enum[type] as ODataEnumType<T> | undefined;
}
public findStructuredTypeForType<T>(type: string) {
if (!(type in this.memo.forType.structured))
this.memo.forType.structured[type] =
this.findSchemaForType(type)?.findStructuredTypeForType<T>(type);
return this.memo.forType.structured[type] as
| ODataStructuredType<T>
| undefined;
}
public findCallableForType<T>(type: string, bindingType?: string) {
const key = bindingType !== undefined ? `${bindingType}/${type}` : type;
if (!(key in this.memo.forType.callable))
this.memo.forType.callable[key] = this.findSchemaForType(
type
)?.findCallableForType<T>(type, bindingType);
return this.memo.forType.callable[key] as ODataCallable<T> | undefined;
}
public findEntitySetForType(type: string) {
if (!(type in this.memo.forType.entitySet))
this.memo.forType.entitySet[type] =
this.findSchemaForType(type)?.findEntitySetForType(type);
return this.memo.forType.entitySet[type] as ODataEntitySet | undefined;
}
public findModelForType(type: string) {
return this.findStructuredTypeForType<any>(type)?.model as
| typeof ODataModel
| undefined;
}
public modelForType(type?: string) {
return (type && this.findModelForType(type)) || ODataModel;
}
public findCollectionForType(type: string) {
return this.findStructuredTypeForType<any>(type)?.collection as
| typeof ODataCollection
| undefined;
}
public collectionForType(type?: string) {
return (type && this.findCollectionForType(type)) || ODataCollection;
}
public findServiceForType(type: string) {
return this.findEntitySetForType(type)?.service as
| typeof ODataEntityService
| undefined;
}
public findEntitySetForEntityType(entityType: string) {
if (!(entityType in this.memo.forType.entitySet))
this.memo.forType.entitySet[entityType] = this.schemas
.reduce(
(acc, schema) => [...acc, ...schema.entitySets],
<ODataEntitySet[]>[]
)
.find((e) => e.entityType === entityType);
return this.memo.forType.entitySet[entityType] as
| ODataEntitySet
| undefined;
}
public findServiceForEntityType(entityType: string) {
return this.findEntitySetForEntityType(entityType)?.service as
| typeof ODataEntityService
| undefined;
}
public findEnumTypeByName<T>(name: string) {
if (!(name in this.memo.byName.enum))
this.memo.byName.enum[name] = this.schemas
.reduce(
(acc, schema) => [...acc, ...schema.enums],
<ODataEnumType<T>[]>[]
)
.find((e) => e.name === name);
return this.memo.byName.enum[name] as ODataEnumType<T> | undefined;
}
public findStructuredTypeByName<T>(name: string) {
if (!(name in this.memo.byName.structured))
this.memo.byName.structured[name] = this.schemas
.reduce(
(acc, schema) => [...acc, ...schema.entities],
<ODataStructuredType<T>[]>[]
)
.find((e) => e.name === name);
return this.memo.byName.structured[name] as
| ODataStructuredType<T>
| undefined;
}
public findCallableByName<T>(name: string, bindingType?: string) {
const key = bindingType !== undefined ? `${bindingType}/${name}` : name;
if (!(key in this.memo.byName.callable))
this.memo.byName.callable[key] = this.schemas
.reduce(
(acc, schema) => [...acc, ...schema.callables],
<ODataCallable<T>[]>[]
)
.find(
(c) =>
c.name === name &&
(bindingType === undefined || c.binding()?.type === bindingType)
);
return this.memo.byName.callable[key] as ODataCallable<T> | undefined;
}
public findEntitySetByName(name: string) {
if (!(name in this.memo.byName.entitySet))
this.memo.byName.entitySet[name] = this.schemas
.reduce(
(acc, schema) => [...acc, ...schema.entitySets],
<ODataEntitySet[]>[]
)
.find((e) => e.name === name);
return this.memo.byName.entitySet[name] as ODataEntitySet | undefined;
}
public findModelByName(name: string) {
return this.findStructuredTypeByName<any>(name)?.model as
| typeof ODataModel
| undefined;
}
public findCollectionByName(name: string) {
return this.findStructuredTypeByName<any>(name)?.collection as
| typeof ODataCollection
| undefined;
}
public findServiceByName(name: string) {
return this.findEntitySetByName(name)?.service as
| typeof ODataEntityService
| undefined;
}
public parserForType<T>(type: string, bindingType?: string) {
const key = bindingType !== undefined ? `${bindingType}/${type}` : type;
if (!(key in this.memo.forType.parser)) {
if (type in this.parsers) {
// Edm, Base Parsers
this.memo.forType.parser[key] = this.parsers[type] as Parser<T>;
} else if (!type.startsWith('Edm.')) {
// EnumType, ComplexType and EntityType Parsers
let value =
this.findCallableForType<T>(type, bindingType) ||
this.findEnumTypeForType<T>(type) ||
this.findStructuredTypeForType<T>(type);
this.memo.forType.parser[key] = value?.parser as Parser<T>;
} else {
// None Parser
this.memo.forType.parser[key] = NONE_PARSER;
}
}
return this.memo.forType.parser[key] as Parser<T>;
}
public findOptionsForType<T>(type: string) {
// Strucutred Options
if (!(type in this.memo.forType.options)) {
let st = this.findStructuredTypeForType<T>(type);
this.memo.forType.options[type] =
st !== undefined && st.model !== undefined && st.model?.meta !== null
? st.model.meta
: undefined;
}
return this.memo.forType.options[type] as ODataModelOptions<T> | undefined;
}
} | the_stack |
import { injectable, inject, optional } from "inversify";
import { Bounds, Point } from "../utils/geometry";
import { Deferred } from "../utils/async";
import { ILogger } from "../utils/logging";
import { TYPES } from "../base/types";
import { Action } from "../base/actions/action";
import { ActionHandlerRegistry } from "../base/actions/action-handler";
import { IActionDispatcher } from "../base/actions/action-dispatcher";
import { findElement } from "../base/model/smodel-utils";
import { ViewerOptions } from "../base/views/viewer-options";
import { RequestModelAction, SetModelAction } from "../base/features/set-model";
import { SModelElementSchema, SModelIndex, SModelRootSchema } from "../base/model/smodel";
import { ComputedBoundsAction, RequestBoundsAction } from '../features/bounds/bounds-manipulation';
import { Match, applyMatches } from "../features/update/model-matching";
import { UpdateModelAction, UpdateModelCommand } from "../features/update/update-model";
import { RequestPopupModelAction, SetPopupModelAction } from "../features/hover/hover";
import { ModelSource } from "./model-source";
import { ExportSvgAction } from '../features/export/svg-exporter';
import { saveAs } from 'file-saver';
import { CollapseExpandAction, CollapseExpandAllAction } from '../features/expand/expand';
import { DiagramState, ExpansionState } from './diagram-state';
/**
* A model source that allows to set and modify the model through function calls.
* This class can be used as a facade over the action-based API of sprotty. It handles
* actions for bounds calculation and model updates.
*/
@injectable()
export class LocalModelSource extends ModelSource {
protected currentRoot: SModelRootSchema = {
type: 'NONE',
id: 'ROOT'
};
protected diagramState: DiagramState = {
expansionState: new ExpansionState(this.currentRoot)
};
/**
* The `type` property of the model root is used to determine whether a model update
* is a change of the previous model or a totally new one.
*/
protected lastSubmittedModelType: string;
/**
* When client layout is active, model updates are not applied immediately. Instead the
* model is rendered on a hidden canvas first to derive actual bounds. The promises listed
* here are resolved after the new bounds have been applied and the new model state has
* been actually applied to the visible canvas.
*/
protected pendingUpdates: Deferred<void>[] = [];
get model(): SModelRootSchema {
return this.currentRoot;
}
set model(root: SModelRootSchema) {
this.setModel(root);
}
constructor(@inject(TYPES.IActionDispatcher) actionDispatcher: IActionDispatcher,
@inject(TYPES.ActionHandlerRegistry) actionHandlerRegistry: ActionHandlerRegistry,
@inject(TYPES.ViewerOptions) viewerOptions: ViewerOptions,
@inject(TYPES.ILogger) protected readonly logger: ILogger,
@inject(TYPES.StateAwareModelProvider)@optional() protected modelProvider?: IStateAwareModelProvider,
@inject(TYPES.IPopupModelProvider)@optional() protected popupModelProvider?: IPopupModelProvider,
@inject(TYPES.IModelLayoutEngine)@optional() protected layoutEngine?: IModelLayoutEngine
) {
super(actionDispatcher, actionHandlerRegistry, viewerOptions);
}
protected initialize(registry: ActionHandlerRegistry): void {
super.initialize(registry);
// Register model manipulation commands
registry.registerCommand(UpdateModelCommand);
// Register this model source
registry.register(ComputedBoundsAction.KIND, this);
registry.register(RequestPopupModelAction.KIND, this);
registry.register(CollapseExpandAction.KIND, this);
registry.register(CollapseExpandAllAction.KIND, this);
}
/**
* Set the model without incremental update.
*/
setModel(newRoot: SModelRootSchema): Promise<void> {
this.currentRoot = newRoot;
this.diagramState = {
expansionState: new ExpansionState(newRoot)
};
return this.submitModel(newRoot, false);
}
/**
* Apply an incremental update to the model with an animation showing the transition to
* the new state. If `newRoot` is undefined, the current root is submitted; in that case
* it is assumed that it has been modified before.
*/
updateModel(newRoot?: SModelRootSchema): Promise<void> {
if (newRoot === undefined) {
return this.submitModel(this.currentRoot, true);
} else {
this.currentRoot = newRoot;
return this.submitModel(newRoot, true);
}
}
/**
* If client layout is active, run a `RequestBoundsAction` and wait for the resulting
* `ComputedBoundsAction`, otherwise call `doSubmitModel(…)` directly.
*/
protected submitModel(newRoot: SModelRootSchema, update: boolean | Match[]): Promise<void> {
if (this.viewerOptions.needsClientLayout) {
const deferred = new Deferred<void>();
this.pendingUpdates.push(deferred);
this.actionDispatcher.dispatch(new RequestBoundsAction(newRoot));
return deferred.promise;
} else {
return this.doSubmitModel(newRoot, update);
}
}
/**
* Submit the given model with an `UpdateModelAction` or a `SetModelAction` depending on the
* `update` argument. If available, the model layout engine is invoked first.
*/
protected async doSubmitModel(newRoot: SModelRootSchema, update: boolean | Match[], index?: SModelIndex<SModelElementSchema>): Promise<void> {
if (this.layoutEngine !== undefined) {
try {
const layoutResult = this.layoutEngine.layout(newRoot, index);
if (layoutResult instanceof Promise)
newRoot = await layoutResult;
else if (layoutResult !== undefined)
newRoot = layoutResult;
} catch (error) {
this.logger.error(this, error.toString(), error.stack);
}
}
const lastSubmittedModelType = this.lastSubmittedModelType;
this.lastSubmittedModelType = newRoot.type;
const updates = this.pendingUpdates;
this.pendingUpdates = [];
if (update && newRoot.type === lastSubmittedModelType) {
const input = Array.isArray(update) ? update : newRoot;
await this.actionDispatcher.dispatch(new UpdateModelAction(input));
} else {
await this.actionDispatcher.dispatch(new SetModelAction(newRoot));
}
updates.forEach(d => d.resolve());
}
/**
* Modify the current model with an array of matches.
*/
applyMatches(matches: Match[]): Promise<void> {
const root = this.currentRoot;
applyMatches(root, matches);
return this.submitModel(root, matches);
}
/**
* Modify the current model by adding new elements.
*/
addElements(elements: (SModelElementSchema | { element: SModelElementSchema, parentId: string })[]): Promise<void> {
const matches: Match[] = [];
for (const e of elements) {
const anye: any = e;
if (anye.element !== undefined && anye.parentId !== undefined) {
matches.push({
right: anye.element,
rightParentId: anye.parentId
});
} else if (anye.id !== undefined) {
matches.push({
right: anye,
rightParentId: this.currentRoot.id
});
}
}
return this.applyMatches(matches);
}
/**
* Modify the current model by removing elements.
*/
removeElements(elements: (string | { elementId: string, parentId: string })[]): Promise<void> {
const matches: Match[] = [];
const index = new SModelIndex();
index.add(this.currentRoot);
for (const e of elements) {
const anye: any = e;
if (anye.elementId !== undefined && anye.parentId !== undefined) {
const element = index.getById(anye.elementId);
if (element !== undefined) {
matches.push({
left: element,
leftParentId: anye.parentId
});
}
} else {
const element = index.getById(anye);
if (element !== undefined) {
matches.push({
left: element,
leftParentId: this.currentRoot.id
});
}
}
}
return this.applyMatches(matches);
}
// ----- Methods for handling incoming actions ----------------------------
handle(action: Action): void {
switch (action.kind) {
case RequestModelAction.KIND:
this.handleRequestModel(action as RequestModelAction);
break;
case ComputedBoundsAction.KIND:
this.handleComputedBounds(action as ComputedBoundsAction);
break;
case RequestPopupModelAction.KIND:
this.handleRequestPopupModel(action as RequestPopupModelAction);
break;
case ExportSvgAction.KIND:
this.handleExportSvgAction(action as ExportSvgAction);
break;
case CollapseExpandAction.KIND:
this.handleCollapseExpandAction(action as CollapseExpandAction);
break;
case CollapseExpandAllAction.KIND:
this.handleCollapseExpandAllAction(action as CollapseExpandAllAction);
break;
}
}
protected handleRequestModel(action: RequestModelAction): void {
if (this.modelProvider)
this.currentRoot = this.modelProvider.getModel(this.diagramState, this.currentRoot);
this.submitModel(this.currentRoot, false);
}
protected handleComputedBounds(action: ComputedBoundsAction): void {
const root = this.currentRoot;
const index = new SModelIndex();
index.add(root);
for (const b of action.bounds) {
const element = index.getById(b.elementId);
if (element !== undefined)
this.applyBounds(element, b.newBounds);
}
if (action.alignments !== undefined) {
for (const a of action.alignments) {
const element = index.getById(a.elementId);
if (element !== undefined)
this.applyAlignment(element, a.newAlignment);
}
}
this.doSubmitModel(root, true, index);
}
protected applyBounds(element: SModelElementSchema, newBounds: Bounds) {
const e = element as any;
e.position = { x: newBounds.x, y: newBounds.y };
e.size = { width: newBounds.width, height: newBounds.height };
}
protected applyAlignment(element: SModelElementSchema, newAlignment: Point) {
const e = element as any;
e.alignment = { x: newAlignment.x, y: newAlignment.y };
}
protected handleRequestPopupModel(action: RequestPopupModelAction): void {
if (this.popupModelProvider !== undefined) {
const element = findElement(this.currentRoot, action.elementId);
const popupRoot = this.popupModelProvider.getPopupModel(action, element);
if (popupRoot !== undefined) {
popupRoot.canvasBounds = action.bounds;
this.actionDispatcher.dispatch(new SetPopupModelAction(popupRoot));
}
}
}
protected handleExportSvgAction(action: ExportSvgAction): void {
const blob = new Blob([action.svg], {type: "text/plain;charset=utf-8"});
saveAs(blob, "diagram.svg");
}
protected handleCollapseExpandAction(action: CollapseExpandAction): void {
if (this.modelProvider !== undefined) {
this.diagramState.expansionState.apply(action);
const expandedModel = this.modelProvider.getModel(this.diagramState, this.currentRoot);
this.updateModel(expandedModel);
}
}
protected handleCollapseExpandAllAction(action: CollapseExpandAllAction): void {
if (this.modelProvider !== undefined) {
if (action.expand) {
// Expanding all elements locally is currently not supported
} else {
this.diagramState.expansionState.collapseAll();
}
const expandedModel = this.modelProvider.getModel(this.diagramState, this.currentRoot);
this.updateModel(expandedModel);
}
}
}
/**
* @deprecated Use IPopupModelProvider instead.
*/
export type PopupModelFactory = (request: RequestPopupModelAction, element?: SModelElementSchema)
=> SModelRootSchema | undefined;
export interface IPopupModelProvider {
getPopupModel(request: RequestPopupModelAction, element?: SModelElementSchema): SModelRootSchema | undefined;
}
export interface IStateAwareModelProvider {
getModel(diagramState: DiagramState, currentRoot?: SModelRootSchema): SModelRootSchema
}
export interface IModelLayoutEngine {
layout(model: SModelRootSchema, index?: SModelIndex<SModelElementSchema>): SModelRootSchema | Promise<SModelRootSchema>
} | the_stack |
import * as commandLineArgs from 'command-line-args';
import * as commandLineUsage from 'command-line-usage';
import * as fs from 'fs';
import * as mkdirp from 'mkdirp';
import * as pathLib from 'path';
import {Bundler} from '../bundler';
import {Analyzer, FsUrlLoader, MultiUrlLoader, MultiUrlResolver, PackageRelativeUrl, FsUrlResolver, RedirectResolver, ResolvedUrl, UrlLoader, UrlResolver} from 'polymer-analyzer';
import {DocumentCollection} from '../document-collection';
import {generateShellMergeStrategy, BundleManifest} from '../bundle-manifest';
import {ensureTrailingSlash, getFileUrl, resolvePath} from '../url-utils';
const prefixArgument = '{underline prefix}';
const pathArgument = '{underline path}';
const optionDefinitions = [
{name: 'help', type: Boolean, alias: 'h', description: 'Print this message'},
{
name: 'version',
type: Boolean,
alias: 'v',
description: 'Print version number'
},
{
name: 'exclude',
type: String,
multiple: true,
description:
'URL to exclude from inlining. Use multiple times to exclude multiple files and folders. HTML tags referencing excluded URLs are preserved.'
},
{
name: 'strip-comments',
type: Boolean,
description:
'Strips all HTML comments not containing an @license from the document'
},
{
name: 'inline-scripts',
type: Boolean,
description: 'Inline external scripts'
},
{
name: 'inline-css',
type: Boolean,
description: 'Inline external stylesheets'
},
{
name: 'out-file',
type: String,
typeLabel: pathArgument,
description: `If specified, output will be written to ${pathArgument}` +
' instead of stdout.'
},
{
name: 'manifest-out',
type: String,
typeLabel: pathArgument,
description: 'If specified, the bundle manifest will be written to ' +
`${pathArgument}.`
},
{
name: 'shell',
type: String,
typeLabel: pathArgument,
description: 'If specified, shared dependencies will be inlined into ' +
`${pathArgument}.`
},
{
name: 'out-dir',
type: String,
typeLabel: pathArgument,
description: 'If specified, all output files will be written to ' +
`${pathArgument}.`
},
{
name: 'in-file',
type: String,
typeLabel: pathArgument,
defaultOption: true,
multiple: true,
description:
'Input HTML (.html) and ES6 (.js) files. If not specified, will be ' +
'the last command line argument. Multiple input values allowable.'
},
{
name: 'redirect',
type: String,
typeLabel: `${prefixArgument}|${pathArgument}`,
multiple: true,
description: `Routes URLs with arbitrary ${prefixArgument}, possibly ` +
`including a protocol, hostname, and/or path prefix to a ` +
`${pathArgument} on local filesystem.For example ` +
`--redirect "myapp://|src" would route "myapp://main/home.html" to ` +
`"./src/main/home.html". Multiple redirects may be specified; the ` +
`earliest ones have the highest priority.`
},
{
name: 'rewrite-urls-in-templates',
type: Boolean,
description: 'Fix URLs found inside certain element attributes ' +
'(`action`, `assetpath`, `href`, `src`, and`style`) inside ' +
'`<template>` tags.'
},
{
name: 'sourcemaps',
type: Boolean,
description: 'Create and process sourcemaps for scripts.'
},
{
name: 'treeshake',
type: Boolean,
description:
'Use Rollup\'s treeshake feature to remove unused code from bundled output.'
},
{
name: 'root',
alias: 'r',
type: String,
typeLabel: pathArgument,
description:
'The root of the package/project being bundled. Defaults to the ' +
'current working folder.'
},
{
name: 'module-resolution',
description: 'Algorithm to use for resolving module specifiers in import ' +
'and export statements when rewriting them to be web-compatible. ' +
'Valid values are "none" and "node". "none" disables module specifier ' +
'rewriting. "node" uses Node.js resolution to find modules.',
type: String,
typeLabel: '"node|none"',
defaultValue: 'node',
}
];
const usage = [
{header: 'Usage', content: ['polymer-bundler [options...] <in-html>']},
{header: 'Options', optionList: optionDefinitions},
{
header: 'Examples',
content: [
{
desc:
'Inline the HTML Imports of \`target.html\` and print the resulting HTML to standard output.',
example: 'polymer-bundler target.html'
},
{
desc:
'Inline the HTML Imports of \`target.html\`, treat \`path/to/target/\` as the webroot of target.html, and make all URLs absolute to the provided webroot.',
example: 'polymer-bundler -p "path/to/target/" /target.html'
},
{
desc:
'Inline the HTML Imports of \`target.html\` that are not in the directory \`path/to/target/subpath\` nor \`path/to/target/subpath2\`.',
example:
'polymer-bundler --exclude "path/to/target/subpath/" --exclude "path/to/target/subpath2/" target.html'
},
{
desc:
'Inline scripts in \`target.html\` as well as HTML Imports. Exclude flags will apply to both Imports and Scripts.',
example: 'polymer-bundler --inline-scripts target.html'
},
{
desc: 'Route URLs starting with "myapp://" to folder "src/myapp".',
example: 'polymer-bundler --redirect="myapp://|src/myapp" target.html'
}
]
},
];
const options = commandLineArgs(optionDefinitions);
const projectRoot = resolvePath(ensureTrailingSlash(options.root || '.'));
const entrypoints: PackageRelativeUrl[] = options['in-file'];
function printHelp() {
console.log(commandLineUsage(usage));
}
const pkg = require('../../package.json');
function printVersion() {
console.log('polymer-bundler:', pkg.version);
}
if (options.version) {
printVersion();
process.exit(0);
}
if (options.help || !entrypoints) {
printHelp();
process.exit(0);
}
options.excludes = options.exclude || [];
options.stripComments = options['strip-comments'];
options.implicitStrip = !options['no-implicit-strip'];
options.inlineScripts = Boolean(options['inline-scripts']);
options.inlineCss = Boolean(options['inline-css']);
options.rewriteUrlsInTemplates = Boolean(options['rewrite-urls-in-templates']);
options.moduleResolution = options['module-resolution'];
options.treeshake = Boolean(options['treeshake']);
const {moduleResolution} = options;
const urlLoader = new FsUrlLoader(projectRoot);
const urlResolver = new FsUrlResolver(projectRoot);
const projectRootUrl = getFileUrl(projectRoot);
type Redirection = {
prefix: ResolvedUrl; path: ResolvedUrl;
};
if (options.redirect) {
const redirections: Redirection[] =
options.redirect
.map((redirect: string) => {
const [prefix, path] = redirect.split('|');
const resolvedPrefix = urlResolver.resolve(prefix as ResolvedUrl);
return {prefix: resolvedPrefix, path};
})
.filter((r: Redirection) => r.prefix && r.path);
const resolvers: UrlResolver[] = redirections.map(
(r: Redirection) =>
new RedirectResolver(projectRootUrl, r.prefix, getFileUrl(r.path)));
const loaders: UrlLoader[] = redirections.map(
(r: Redirection) => new FsUrlLoader(resolvePath(r.path)));
if (redirections.length > 0) {
options.analyzer = new Analyzer({
moduleResolution,
urlResolver: new MultiUrlResolver([...resolvers, urlResolver]),
urlLoader: new MultiUrlLoader([...loaders, urlLoader]),
});
}
}
if (!options.analyzer) {
options.analyzer = new Analyzer({moduleResolution, urlResolver, urlLoader});
}
if (options.shell) {
options.strategy =
generateShellMergeStrategy(options.analyzer.resolveUrl(options.shell), 2);
}
(async () => {
const bundler = new Bundler(options);
let documents: DocumentCollection;
let manifest: BundleManifest;
try {
const shell = options.shell;
if (shell) {
if (entrypoints.indexOf(shell) === -1) {
entrypoints.push(shell);
}
}
({documents, manifest} = await bundler.bundle(
await bundler.generateManifest(entrypoints.map((e) => {
const resolvedUrl = bundler.analyzer.resolveUrl(e);
if (!resolvedUrl) {
throw new Error(`Unable to resolve URL for entrypoint ${e}`);
}
return resolvedUrl;
}))));
} catch (err) {
console.log(err);
return;
}
if (options['manifest-out']) {
const manifestJson = manifest.toJson(bundler.analyzer.urlResolver);
const fd = fs.openSync(options['manifest-out'], 'w');
fs.writeSync(fd, JSON.stringify(manifestJson));
fs.closeSync(fd);
}
const outDir = options['out-dir'];
if (documents.size > 1 || outDir) {
if (!outDir) {
throw new Error(
'Must specify out-dir when bundling multiple entrypoints');
}
for (const [url, document] of documents) {
// When writing the output bundles to the filesystem, we need their paths
// to be package relative, since the destination is different than their
// original filesystem locations.
const out =
resolvePath(outDir, bundler.analyzer.urlResolver.relative(url));
const finalDir = pathLib.dirname(out);
mkdirp.sync(finalDir);
const fd = fs.openSync(out, 'w');
fs.writeSync(fd, document.content);
fs.closeSync(fd);
}
return;
}
const doc = documents.get(bundler.analyzer.resolveUrl(entrypoints[0])!);
if (!doc) {
return;
}
if (options['out-file']) {
const fd = fs.openSync(options['out-file'], 'w');
fs.writeSync(fd, doc.content);
fs.closeSync(fd);
} else {
process.stdout.write(doc.content);
}
})().catch((err) => {
console.log(err.stack);
process.stderr.write(require('util').inspect(err));
process.exit(1);
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/authorizationPoliciesMappers";
import * as Parameters from "../models/parameters";
import { CustomerInsightsManagementClientContext } from "../customerInsightsManagementClientContext";
/** Class representing a AuthorizationPolicies. */
export class AuthorizationPolicies {
private readonly client: CustomerInsightsManagementClientContext;
/**
* Create a AuthorizationPolicies.
* @param {CustomerInsightsManagementClientContext} client Reference to the service client.
*/
constructor(client: CustomerInsightsManagementClientContext) {
this.client = client;
}
/**
* Creates an authorization policy or updates an existing authorization policy.
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param parameters Parameters supplied to the CreateOrUpdate authorization policy operation.
* @param [options] The optional parameters
* @returns Promise<Models.AuthorizationPoliciesCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, hubName: string, authorizationPolicyName: string, parameters: Models.AuthorizationPolicyResourceFormat, options?: msRest.RequestOptionsBase): Promise<Models.AuthorizationPoliciesCreateOrUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param parameters Parameters supplied to the CreateOrUpdate authorization policy operation.
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, hubName: string, authorizationPolicyName: string, parameters: Models.AuthorizationPolicyResourceFormat, callback: msRest.ServiceCallback<Models.AuthorizationPolicyResourceFormat>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param parameters Parameters supplied to the CreateOrUpdate authorization policy operation.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, hubName: string, authorizationPolicyName: string, parameters: Models.AuthorizationPolicyResourceFormat, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AuthorizationPolicyResourceFormat>): void;
createOrUpdate(resourceGroupName: string, hubName: string, authorizationPolicyName: string, parameters: Models.AuthorizationPolicyResourceFormat, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AuthorizationPolicyResourceFormat>, callback?: msRest.ServiceCallback<Models.AuthorizationPolicyResourceFormat>): Promise<Models.AuthorizationPoliciesCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
hubName,
authorizationPolicyName,
parameters,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.AuthorizationPoliciesCreateOrUpdateResponse>;
}
/**
* Gets an authorization policy in the hub.
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param [options] The optional parameters
* @returns Promise<Models.AuthorizationPoliciesGetResponse>
*/
get(resourceGroupName: string, hubName: string, authorizationPolicyName: string, options?: msRest.RequestOptionsBase): Promise<Models.AuthorizationPoliciesGetResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param callback The callback
*/
get(resourceGroupName: string, hubName: string, authorizationPolicyName: string, callback: msRest.ServiceCallback<Models.AuthorizationPolicyResourceFormat>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, hubName: string, authorizationPolicyName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AuthorizationPolicyResourceFormat>): void;
get(resourceGroupName: string, hubName: string, authorizationPolicyName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AuthorizationPolicyResourceFormat>, callback?: msRest.ServiceCallback<Models.AuthorizationPolicyResourceFormat>): Promise<Models.AuthorizationPoliciesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
hubName,
authorizationPolicyName,
options
},
getOperationSpec,
callback) as Promise<Models.AuthorizationPoliciesGetResponse>;
}
/**
* Gets all the authorization policies in a specified hub.
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param [options] The optional parameters
* @returns Promise<Models.AuthorizationPoliciesListByHubResponse>
*/
listByHub(resourceGroupName: string, hubName: string, options?: msRest.RequestOptionsBase): Promise<Models.AuthorizationPoliciesListByHubResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param callback The callback
*/
listByHub(resourceGroupName: string, hubName: string, callback: msRest.ServiceCallback<Models.AuthorizationPolicyListResult>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param options The optional parameters
* @param callback The callback
*/
listByHub(resourceGroupName: string, hubName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AuthorizationPolicyListResult>): void;
listByHub(resourceGroupName: string, hubName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AuthorizationPolicyListResult>, callback?: msRest.ServiceCallback<Models.AuthorizationPolicyListResult>): Promise<Models.AuthorizationPoliciesListByHubResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
hubName,
options
},
listByHubOperationSpec,
callback) as Promise<Models.AuthorizationPoliciesListByHubResponse>;
}
/**
* Regenerates the primary policy key of the specified authorization policy.
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param [options] The optional parameters
* @returns Promise<Models.AuthorizationPoliciesRegeneratePrimaryKeyResponse>
*/
regeneratePrimaryKey(resourceGroupName: string, hubName: string, authorizationPolicyName: string, options?: msRest.RequestOptionsBase): Promise<Models.AuthorizationPoliciesRegeneratePrimaryKeyResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param callback The callback
*/
regeneratePrimaryKey(resourceGroupName: string, hubName: string, authorizationPolicyName: string, callback: msRest.ServiceCallback<Models.AuthorizationPolicy>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param options The optional parameters
* @param callback The callback
*/
regeneratePrimaryKey(resourceGroupName: string, hubName: string, authorizationPolicyName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AuthorizationPolicy>): void;
regeneratePrimaryKey(resourceGroupName: string, hubName: string, authorizationPolicyName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AuthorizationPolicy>, callback?: msRest.ServiceCallback<Models.AuthorizationPolicy>): Promise<Models.AuthorizationPoliciesRegeneratePrimaryKeyResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
hubName,
authorizationPolicyName,
options
},
regeneratePrimaryKeyOperationSpec,
callback) as Promise<Models.AuthorizationPoliciesRegeneratePrimaryKeyResponse>;
}
/**
* Regenerates the secondary policy key of the specified authorization policy.
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param [options] The optional parameters
* @returns Promise<Models.AuthorizationPoliciesRegenerateSecondaryKeyResponse>
*/
regenerateSecondaryKey(resourceGroupName: string, hubName: string, authorizationPolicyName: string, options?: msRest.RequestOptionsBase): Promise<Models.AuthorizationPoliciesRegenerateSecondaryKeyResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param callback The callback
*/
regenerateSecondaryKey(resourceGroupName: string, hubName: string, authorizationPolicyName: string, callback: msRest.ServiceCallback<Models.AuthorizationPolicy>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param options The optional parameters
* @param callback The callback
*/
regenerateSecondaryKey(resourceGroupName: string, hubName: string, authorizationPolicyName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AuthorizationPolicy>): void;
regenerateSecondaryKey(resourceGroupName: string, hubName: string, authorizationPolicyName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AuthorizationPolicy>, callback?: msRest.ServiceCallback<Models.AuthorizationPolicy>): Promise<Models.AuthorizationPoliciesRegenerateSecondaryKeyResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
hubName,
authorizationPolicyName,
options
},
regenerateSecondaryKeyOperationSpec,
callback) as Promise<Models.AuthorizationPoliciesRegenerateSecondaryKeyResponse>;
}
/**
* Gets all the authorization policies in a specified hub.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.AuthorizationPoliciesListByHubNextResponse>
*/
listByHubNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.AuthorizationPoliciesListByHubNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByHubNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.AuthorizationPolicyListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByHubNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AuthorizationPolicyListResult>): void;
listByHubNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AuthorizationPolicyListResult>, callback?: msRest.ServiceCallback<Models.AuthorizationPolicyListResult>): Promise<Models.AuthorizationPoliciesListByHubNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByHubNextOperationSpec,
callback) as Promise<Models.AuthorizationPoliciesListByHubNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/authorizationPolicies/{authorizationPolicyName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.hubName1,
Parameters.authorizationPolicyName0,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.AuthorizationPolicyResourceFormat,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.AuthorizationPolicyResourceFormat
},
201: {
bodyMapper: Mappers.AuthorizationPolicyResourceFormat
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/authorizationPolicies/{authorizationPolicyName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.hubName1,
Parameters.authorizationPolicyName1,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AuthorizationPolicyResourceFormat
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByHubOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/authorizationPolicies",
urlParameters: [
Parameters.resourceGroupName,
Parameters.hubName1,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AuthorizationPolicyListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const regeneratePrimaryKeyOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/authorizationPolicies/{authorizationPolicyName}/regeneratePrimaryKey",
urlParameters: [
Parameters.resourceGroupName,
Parameters.hubName1,
Parameters.authorizationPolicyName1,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AuthorizationPolicy
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const regenerateSecondaryKeyOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/authorizationPolicies/{authorizationPolicyName}/regenerateSecondaryKey",
urlParameters: [
Parameters.resourceGroupName,
Parameters.hubName1,
Parameters.authorizationPolicyName1,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AuthorizationPolicy
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByHubNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AuthorizationPolicyListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import { processCommaSep } from "string-process-comma-separated";
import checkForWhitespace from "./checkForWhitespace";
import { knownUnits } from "./constants";
import { isObj } from "./util";
import { ErrorObj } from "./commonTypes";
interface Opts {
type: "integer" | "rational";
whitelistValues: string[];
theOnlyGoodUnits: null | string[];
plusOK: boolean;
negativeOK: boolean;
zeroOK: boolean;
badUnits: string[];
enforceCount: null | number | "even" | "odd";
noUnitsIsFine: boolean;
canBeCommaSeparated: boolean;
customGenericValueError: null | string;
skipWhitespaceChecks: boolean;
customPxMessage: null | string;
maxValue: null | number;
}
const defaultOpts: Opts = {
type: "integer",
whitelistValues: [],
theOnlyGoodUnits: null,
plusOK: false,
negativeOK: false,
zeroOK: true,
badUnits: [],
enforceCount: null,
noUnitsIsFine: true,
canBeCommaSeparated: false,
customGenericValueError: null,
skipWhitespaceChecks: false,
customPxMessage: null,
maxValue: null,
};
interface InputObj {
str: string;
opts: Partial<Opts>;
charStart: number;
charEnd: number;
idxOffset: number;
errorArr: ErrorObj[];
}
function validateValue({
str,
opts,
charStart,
charEnd,
idxOffset,
errorArr,
}: InputObj) {
// the rule is for pattern digit(s) + unit, so start from checking, does it
// start with a digit
console.log(` `);
console.log(` `);
console.log(` `);
console.log(
`064 validateValue(): ${`\u001b[${32}m${`INCOMING`}\u001b[${39}m`} ${`\u001b[${33}m${`str`}\u001b[${39}m`} = ${JSON.stringify(
str,
null,
4
)}; ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify(
opts,
null,
4
)}`
);
console.log(
`075 validateValue(): INCOMING ${`\u001b[${33}m${`charStart`}\u001b[${39}m`} = ${charStart}; ${`\u001b[${33}m${`charEnd`}\u001b[${39}m`} = ${charEnd}`
);
// insurance
if (typeof str !== "string") {
return;
}
// applies to rational and integer types
if (str[charStart] === "0") {
if (charEnd === charStart + 1) {
// so length === 1
if (!opts.zeroOK) {
errorArr.push({
idxFrom: idxOffset + charStart,
idxTo: idxOffset + charEnd,
message: `Zero not allowed.`,
fix: null,
});
}
} else if ("0123456789".includes(str[charStart + 1])) {
// we have padded cases like 08
errorArr.push({
idxFrom: idxOffset + charStart,
idxTo: idxOffset + charEnd,
message: `Number padded with zero.`,
fix: null,
});
}
}
if (
!"0123456789".includes(str[charStart]) &&
!"0123456789".includes(str[charEnd - 1])
) {
console.log(
`111 validateValue(): no digits, PUSH [${idxOffset + charStart}, ${
idxOffset + charEnd
}]`
);
// calculate the message
let message = `Digits missing.`;
if (opts.customGenericValueError) {
message = opts.customGenericValueError;
} else if (
Array.isArray(opts.theOnlyGoodUnits) &&
!opts.theOnlyGoodUnits.length &&
opts.type === "integer"
) {
message = `Should be integer, no units.`;
}
errorArr.push({
idxFrom: idxOffset + charStart,
idxTo: idxOffset + charEnd,
message,
fix: null,
});
} else if (
"0123456789".includes(str[charStart]) &&
"0123456789".includes(str[charEnd - 1]) &&
(!opts.noUnitsIsFine ||
(opts.type === "integer" &&
opts.maxValue &&
str.slice(charStart, charEnd).match(/^\d+$/) &&
Number.parseInt(str.slice(charStart, charEnd), 10) > opts.maxValue))
) {
console.log(`143 validateValue(): inside digits-only clauses`);
if (!opts.noUnitsIsFine) {
console.log(
`146 validateValue(): units missing, PUSH [${idxOffset + charStart}, ${
idxOffset + charEnd
}]`
);
errorArr.push({
idxFrom: idxOffset + charStart,
idxTo: idxOffset + charEnd,
message: opts.customGenericValueError || `Units missing.`,
fix: null,
});
} else {
console.log(
`158 validateValue(): maximum exceeded, PUSH [${
idxOffset + charStart
}, ${idxOffset + charEnd}]`
);
errorArr.push({
idxFrom: idxOffset + charStart,
idxTo: idxOffset + charEnd,
message: `Maximum, ${opts.maxValue} exceeded.`,
fix: null,
});
}
} else {
console.log(
`171 validateValue(): separate digits from units, evaluate both`
);
for (let i = charStart; i < charEnd; i++) {
console.log(
`175 validateValue(): ${`\u001b[${36}m${`loop`}\u001b[${39}m`} ${`\u001b[${36}m${`str[${i}]`}\u001b[${39}m`} = ${JSON.stringify(
str[i],
null,
0
)}`
);
if (
!"0123456789".includes(str[i]) &&
(str[i] !== "." || opts.type !== "rational") &&
(str[i] !== "-" || !(opts.negativeOK && i === 0)) &&
(str[i] !== "+" || !(opts.plusOK && i === 0))
) {
// dash can be in the middle! For example, colspan="1-1"
const endPart = str.slice(i, charEnd);
console.log(
`190 ${`\u001b[${33}m${`endPart`}\u001b[${39}m`} = ${JSON.stringify(
endPart,
null,
4
)}`
);
if (
isObj(opts) &&
((Array.isArray(opts.theOnlyGoodUnits) &&
!opts.theOnlyGoodUnits.includes(endPart)) ||
(Array.isArray(opts.badUnits) && opts.badUnits.includes(endPart)))
) {
console.log(`202 recognised unit clauses`);
// special case for "px"
if (endPart === "px") {
const message = opts.customPxMessage
? opts.customPxMessage
: `Remove px.`;
errorArr.push({
idxFrom: idxOffset + i,
idxTo: idxOffset + charEnd,
message,
fix: opts.customPxMessage
? null
: {
ranges: [[idxOffset + i, idxOffset + charEnd]],
},
});
} else {
// validate against the known units and serve a separate
// message, depending on was it recognised
// calculate the message
let message = `Bad unit.`;
if (str.match(/-\s*-/g)) {
message = `Repeated minus.`;
} else if (str.match(/\+\s*\+/g)) {
message = `Repeated plus.`;
} else if (
Array.isArray(opts.theOnlyGoodUnits) &&
opts.theOnlyGoodUnits.length &&
opts.theOnlyGoodUnits.includes(endPart.trim())
) {
// if trimmed end part matches "good" units, it's the whitespace
message = "Rogue whitespace.";
} else if (opts.customGenericValueError) {
message = opts.customGenericValueError;
} else if (
Array.isArray(opts.theOnlyGoodUnits) &&
!opts.theOnlyGoodUnits.length &&
opts.type === "integer"
) {
message = `Should be integer, no units.`;
}
errorArr.push({
idxFrom: idxOffset + i,
idxTo: idxOffset + charEnd,
message,
fix: null,
});
}
} else if (!knownUnits.includes(endPart)) {
console.log(`252 unrecognised unit clauses`);
let message = "Unrecognised unit.";
if (/\d/.test(endPart)) {
message = "Messy value.";
} else if (knownUnits.includes(endPart.trim())) {
message = "Rogue whitespace.";
}
errorArr.push({
idxFrom: idxOffset + i,
idxTo: idxOffset + charEnd,
message,
fix: null,
});
}
// stop the loop
break;
}
}
}
}
// function below is used to validate attribute values which contain
// digits and a unit, for example, "100%" of an HTML attribute
// width="100%"
// or
// "100%" of CSS head style "width:100%;"
// it returns array of ready error objects, except without ruleId, something like:
//
// {
// idxFrom: 17,
// idxTo: 19,
// message: `Remove px.`,
// fix: {
// ranges: [[17, 19]]
// }
// }
//
// if it can't fix, key "fix" value is null
function validateDigitAndUnit(
str: string,
idxOffset: number,
originalOpts?: Partial<Opts>
): ErrorObj[] {
if (typeof str !== "string") {
console.log(
`299 ${`\u001b[${35}m${`validateDigitAndUnit() called`}\u001b[${39}m`} quick return, no content in the input`
);
return [];
}
const opts: Opts = { ...defaultOpts, ...originalOpts };
// we get trimmed string start and end positions, also an encountered errors array
let charStart = 0;
let charEnd = str.length;
let errorArr: ErrorObj[] = [];
if (!opts.skipWhitespaceChecks) {
const retrievedWhitespaceChecksObj = checkForWhitespace(str, idxOffset);
charStart = retrievedWhitespaceChecksObj.charStart as number;
charEnd = retrievedWhitespaceChecksObj.charEnd as number;
errorArr = retrievedWhitespaceChecksObj.errorArr;
}
console.log(
`320 validateDigitAndUnit(): ${`\u001b[${33}m${`charStart`}\u001b[${39}m`} = ${JSON.stringify(
charStart,
null,
4
)}`
);
console.log(
`327 validateDigitAndUnit(): ${`\u001b[${33}m${`charEnd`}\u001b[${39}m`} = ${JSON.stringify(
charEnd,
null,
4
)}`
);
// now that we know where non-whitespace chars are, evaluate them
if (Number.isInteger(charStart)) {
console.log(`336 validateDigitAndUnit(): it is integer.`);
if (opts.canBeCommaSeparated) {
console.log(
`339 validateDigitAndUnit(): opts.canBeCommaSeparated clauses`
);
// split by comma and process each
const extractedValues: string[] = [];
processCommaSep(str, {
offset: idxOffset,
oneSpaceAfterCommaOK: false,
leadingWhitespaceOK: true,
trailingWhitespaceOK: true,
cb: (idxFrom, idxTo) => {
console.log(
`351 cb(): ${`\u001b[${32}m${`INCOMING`}\u001b[${39}m`} idxFrom = ${idxFrom}; idxTo = ${idxTo}`
);
console.log(
`354 ██ EXTRACTED VALUE: ${JSON.stringify(
str.slice(idxFrom - idxOffset, idxTo - idxOffset),
null,
0
)}`
);
const extractedValue = str.slice(
idxFrom - idxOffset,
idxTo - idxOffset
);
// if the value is not whitelisted, evaluate it
if (
!Array.isArray(opts.whitelistValues) ||
!opts.whitelistValues.includes(extractedValue)
) {
validateValue({
str,
opts,
charStart: idxFrom - idxOffset,
charEnd: idxTo - idxOffset,
idxOffset,
errorArr,
});
}
extractedValues.push(extractedValue);
},
errCb: (ranges, message) => {
console.log(
`385 cb(): ${`\u001b[${32}m${`INCOMING`}\u001b[${39}m`} ranges = ${ranges}; message = ${message}`
);
errorArr.push({
idxFrom: ranges[0][0],
idxTo: ranges[ranges.length - 1][1],
message,
fix: {
ranges,
},
});
console.log(
`396 after errorArr push, ${`\u001b[${33}m${`errorArr`}\u001b[${39}m`} = ${JSON.stringify(
errorArr,
null,
4
)}`
);
},
});
// enforce the "extractedValues" count
console.log(
`407 validateDigitAndUnit(): ${`\u001b[${33}m${`extractedValues`}\u001b[${39}m`} = ${JSON.stringify(
extractedValues,
null,
4
)}`
);
if (
Number.isInteger(opts.enforceCount) &&
extractedValues.length !== opts.enforceCount
) {
errorArr.push({
idxFrom: charStart + idxOffset,
idxTo: charEnd + idxOffset,
message: `There should be ${opts.enforceCount} values.`,
fix: null,
});
console.log(
`425 after errorArr push, ${`\u001b[${33}m${`errorArr`}\u001b[${39}m`} = ${JSON.stringify(
errorArr,
null,
4
)}`
);
} else if (
typeof opts.enforceCount === "string" &&
["even", "odd"].includes(opts.enforceCount.toLowerCase())
) {
if (
opts.enforceCount.toLowerCase() === "even" &&
extractedValues.length % 2 !== 0
) {
errorArr.push({
idxFrom: charStart + idxOffset,
idxTo: charEnd + idxOffset,
message: `Should be an even number of values but found ${extractedValues.length}.`,
fix: null,
});
console.log(
`446 after errorArr push, ${`\u001b[${33}m${`errorArr`}\u001b[${39}m`} = ${JSON.stringify(
errorArr,
null,
4
)}`
);
} else if (
opts.enforceCount.toLowerCase() !== "even" &&
extractedValues.length % 2 === 0
) {
errorArr.push({
idxFrom: charStart + idxOffset,
idxTo: charEnd + idxOffset,
message: `Should be an odd number of values but found ${extractedValues.length}.`,
fix: null,
});
console.log(
`463 after errorArr push, ${`\u001b[${33}m${`errorArr`}\u001b[${39}m`} = ${JSON.stringify(
errorArr,
null,
4
)}`
);
}
}
} else {
console.log(
`473 validateDigitAndUnit(): opts.canBeCommaSeparated is off, process the whole`
);
// if the value is not whitelisted, evaluate it
if (
!Array.isArray(opts.whitelistValues) ||
!opts.whitelistValues.includes(str.slice(charStart, charEnd))
) {
validateValue({
str,
opts,
charStart,
charEnd,
idxOffset,
errorArr,
});
}
}
}
return errorArr;
}
export default validateDigitAndUnit; | the_stack |
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { defer, from, throwError } from 'rxjs';
import { share, catchError } from 'rxjs/operators';
import { CacheStorageService } from '../cache-storage/cache-storage.service';
import { StorageCacheItem } from '../../interfaces/cache-storage-item.interface';
import { errorMessages } from '../../constants/error-messages.constant';
import { isHttpResponse } from '../../helpers/is-http-response.helper';
import { convertBlobToBase64 } from '../../helpers/convert-blob-to-base64.helper';
import { decodeRawData } from '../../helpers/decode-raw-data.helper';
@Injectable()
export class CacheService {
private ttl: number = 60 * 60; // one hour
private cacheEnabled: boolean = true;
private invalidateOffline: boolean = false;
constructor(private cacheStorage: CacheStorageService) {
this.loadCache();
}
/**
* Disable or enable cache.
*/
public enableCache(enable: boolean = true): void {
this.cacheEnabled = enable;
}
/**
* Set if expired cache should be invalidated if device is offline.
*/
public setOfflineInvalidate(offlineInvalidate: boolean): void {
this.invalidateOffline = !offlineInvalidate;
}
/**
* Set default TTL.
* @param ttl TTL in seconds.
*/
public setDefaultTTL(ttl: number): number {
return (this.ttl = ttl);
}
/**
* Checks if the device is online.
*/
public isOnline(): boolean {
return navigator.onLine;
}
/**
* Saves an item to the cache storage with the provided options.
* @param key The unique key
* @param data The data to store
* @param groupKey The group key
* @param ttl The TTL in seconds
* @returns The saved data
*/
public saveItem(key: string, data: any, groupKey: string = 'none', ttl: number = this.ttl): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(errorMessages.notEnabled);
}
if (Blob.name === data.constructor.name) {
return this.saveBlobItem(key, data, groupKey, ttl);
}
const expires = new Date().getTime() + ttl * 1000;
const type = isHttpResponse(data) ? 'response' : typeof data;
const value = JSON.stringify(data);
return this.cacheStorage.set(key, {
value,
expires,
type,
groupKey
});
}
/**
* Deletes an item from the cache storage.
* @param key The unique key
* @returns A promise which will resolve when the item is removed.
*/
public removeItem(key: string): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(errorMessages.notEnabled);
}
return this.cacheStorage.remove(key);
}
/**
* Removes all items with a key that matches pattern.
* @returns A promise which will resolve when all the items are removed.
*/
public async removeItems(pattern: string): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(errorMessages.notEnabled);
}
const regex = new RegExp(`^${pattern.split('*').join('.*')}$`);
const items = await this.cacheStorage.all();
return Promise.all(
items
.map((item) => item.key)
.filter((key) => key && regex.test(key))
.map((key) => this.removeItem(key))
);
}
/**
* Gets item from cache without checking if it is expired.
* @param key The unique key
* @returns A promise which will resolve with the data from the cache.
*/
public async getRawItem(key: string): Promise<StorageCacheItem> {
if (!this.cacheEnabled) {
throw new Error(errorMessages.notEnabled);
}
try {
const data = await this.cacheStorage.get(key);
if (!!data) {
return data;
}
throw new Error('');
} catch (err) {
throw new Error(errorMessages.notFound + key);
}
}
/**
* Gets all items from the cache without checking if they are expired.
* @returns A promise which will resove with all the items in the cache.
*/
public getRawItems(): Promise<StorageCacheItem[]> {
return this.cacheStorage.all();
}
/**
* Check sif item exists in cache regardless if expired or not.
* @param key The unique key
* @returns A boolean which will be true the key if exists.
*/
public itemExists(key: string): Promise<boolean | string> {
if (!this.cacheEnabled) {
throw new Error(errorMessages.notEnabled);
}
return this.cacheStorage.exists(key);
}
/**
* Gets item from cache with expire check.
* @param key The unique key
* @returns The data from the cache
*/
public async getItem<T = any>(key: string): Promise<T> {
if (!this.cacheEnabled) {
throw new Error(errorMessages.notEnabled);
}
const data = await this.getRawItem(key);
if (data.expires < new Date().getTime() && (this.invalidateOffline || this.isOnline())) {
throw new Error(errorMessages.expired + key);
}
return decodeRawData(data);
}
/**
* Gets or sets an item in the cache storage
* @param key The unique key
* @param factory The factory to update the value with if it's not present.
* @param groupKey The group key
* @param ttl The TTL in seconds.
* @returns A promise which resolves with the data.
*/
public async getOrSetItem<T>(key: string, factory: () => Promise<T>, groupKey?: string, ttl?: number): Promise<T> {
let val: T;
try {
val = await this.getItem<T>(key);
} catch (error) {
val = await factory();
await this.saveItem(key, val, groupKey, ttl);
}
return val;
}
/**
* Loads an item from the cache, if it's not there it will use the provided observable to set the value and return it.
* @param key The unique key
* @param observable The observable to provide the data if it's not present in the cache.
* @param groupKey The group key
* @param ttl The TTL in seconds
* @returns An observable with the data from the cache or provided observable.
*/
public loadFromObservable<T = any>(key: string, observable: any, groupKey?: string, ttl?: number): Observable<T> {
if (!this.cacheEnabled) {
return observable;
}
observable = observable.pipe(share());
return defer(() => {
return from(this.getItem(key)).pipe(
catchError((e) => {
observable.subscribe(
(res) => {
return this.saveItem(key, res, groupKey, ttl);
},
(error) => {
return throwError(error);
}
);
return observable;
})
);
});
}
/**
* Loads an item from cache regardless of expiry.
* If the delay type is set to expired it will only get data from the observable when the item is expired.
* If the delay type is set to all it will always get data from the observable.
* @param key The unique key
* @param observable The observable with data.
* @param groupKey The group key
* @param ttl The TTL in seconds
* @param delayType The delay type, defaults to expired.
* @param metaKey The property on T to which to assign meta data.
* @returns An observable which will emit the data.
*/
public loadFromDelayedObservable<T = any>(
key: string,
observable: Observable<T>,
groupKey?: string,
ttl: number = this.ttl,
delayType: string = 'expired',
metaKey?: string
): Observable<T> {
if (!this.cacheEnabled) {
return observable;
}
const observableSubject = new Subject<T>();
observable = observable.pipe(share());
const subscribeOrigin = () => {
observable.subscribe(
(res) => {
this.saveItem(key, res, groupKey, ttl);
observableSubject.next(res);
observableSubject.complete();
},
(err) => {
observableSubject.error(err);
},
() => {
observableSubject.complete();
}
);
};
this.getItem<T>(key)
.then((data) => {
if (metaKey) {
data[metaKey] = data[metaKey] || {};
data[metaKey].fromCache = true;
}
observableSubject.next(data);
if (delayType === 'all') {
subscribeOrigin();
} else {
observableSubject.complete();
}
})
.catch((e) => {
this.getRawItem(key)
.then(async (res) => {
const result = await decodeRawData(res);
if (metaKey) {
result[metaKey] = result[metaKey] || {};
result[metaKey].fromCache = true;
}
observableSubject.next(result);
subscribeOrigin();
})
.catch(() => subscribeOrigin());
});
return observableSubject.asObservable();
}
/**
* Perform complete cache clear
* @returns A promise which resolves when the cache storage is cleared.
*/
public clearAll(): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(errorMessages.notEnabled);
}
return this.resetDatabase();
}
/**
* Removes all expired items from the cache.
* @param ignoreOnlineStatus Ignores the online status, defaults to false.
* @returns A promise which resolves when all expired items are cleared from cache storage.
*/
public async clearExpired(ignoreOnlineStatus = false): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(errorMessages.notEnabled);
}
if (!this.isOnline() && !ignoreOnlineStatus) {
throw new Error(errorMessages.browserOffline);
}
const items = await this.cacheStorage.all();
const datetime = new Date().getTime();
return Promise.all(items.filter((item) => item.expires < datetime).map((item) => this.removeItem(item.key)));
}
/**
* Removes all item with specified group
* @param groupKey The group key
* @returns A promise which resolves when all the items in the group have been cleared.
*/
async clearGroup(groupKey: string): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(errorMessages.notEnabled);
}
const items = await this.cacheStorage.all();
return Promise.all(items.filter((item) => item.groupKey === groupKey).map((item) => this.removeItem(item.key)));
}
/**
* Creates the cache storage.
* If it fails it will provide and error message.
*/
private async loadCache(): Promise<void> {
if (!this.cacheEnabled) {
return;
}
try {
await this.cacheStorage.create();
} catch (error) {
this.cacheEnabled = false;
console.error(errorMessages.initialization, error);
}
}
/**
* Resets the storage back to being empty.
*/
private async resetDatabase(): Promise<any> {
const items = await this.cacheStorage.all();
return Promise.all(items.map((item) => this.removeItem(item.key)));
}
/**
* Saves a blob item to the cache storage with the provided options.
* @param key The unique key
* @param blob The blob to store
* @param groupKey The group key
* @param ttl The TTL in seconds
* @returns The saved data
*/
private async saveBlobItem(
key: string,
blob: any,
groupKey: string = 'none',
ttl: number = this.ttl
): Promise<any> {
if (!this.cacheEnabled) {
throw new Error(errorMessages.notEnabled);
}
const expires = new Date().getTime() + ttl * 1000;
const type = blob.type;
try {
const base64data = await convertBlobToBase64(blob);
const value = JSON.stringify(base64data);
return this.cacheStorage.set(key, {
value,
expires,
type,
groupKey
});
} catch (error) {
throw new Error(error);
}
}
} | the_stack |
import { pathExists } from "fs-extra"
import { Buffer, BufferLayer, Commands, Configuration } from "oni-api"
import { warn } from "oni-core-logging"
import * as React from "react"
import { Transition } from "react-transition-group"
import { Position } from "vscode-languageserver-types"
import { LayerContextWithCursor } from "../../Editor/NeovimEditor/NeovimBufferLayersView"
import styled, { pixel, textOverflow, withProps } from "../../UI/components/common"
import { getTimeSince } from "../../Utility"
import { VersionControlProvider } from "./"
import { Blame as IBlame } from "./VersionControlProvider"
type TransitionStates = "entering" | "entered" | "exiting"
interface IBlamePosition {
top: number
left: number
hide: boolean
}
interface ICanFit {
canFit: boolean
message: string
position: IBlamePosition
}
interface ILineDetails {
nextSpacing: number
lastEmptyLine: number
}
export interface IProps extends LayerContextWithCursor {
getBlame: (lineOne: number, lineTwo: number) => Promise<IBlame>
timeout: number
cursorScreenLine: number
cursorBufferLine: number
currentLine: string
mode: "auto" | "manual"
fontFamily: string
setupCommand: (callback: () => void) => void
}
export interface IState {
blame: IBlame
showBlame: boolean
currentLineContent: string
currentCursorBufferLine: number
error: Error
}
interface IContainerProps {
height: number
top: number
left: number
fontFamily: string
hide: boolean
timeout: number
animationState: TransitionStates
}
const getOpacity = (state: TransitionStates) => {
const transitionStyles = {
entering: 0,
entered: 0.5,
exiting: 0,
}
return transitionStyles[state]
}
export const BlameContainer = withProps<IContainerProps>(styled.div).attrs({
style: ({ top, left }: IContainerProps) => ({
top: pixel(top),
left: pixel(left),
}),
})`
${p => p.hide && `visibility: hidden`};
width: auto;
box-sizing: border-box;
position: absolute;
font-style: italic;
font-family: ${p => p.fontFamily};
color: ${p => p.theme["menu.foreground"]};
opacity: ${p => getOpacity(p.animationState)};
transition: opacity ${p => p.timeout}ms ease-in-out;
height: ${p => pixel(p.height)};
line-height: ${p => pixel(p.height)};
right: 3em;
${textOverflow}
`
const BlameDetails = styled.span`
color: inherit;
width: 100%;
`
// CurrentLine - the string in the current line
// CursorLine - The 0 based position of the cursor in the file i.e. at line 30 this will be 29
// CursorBufferLine - The 1 based position of the cursor in the file i.e. at line 30 it will be 30
// CursorScreenLine - the position of the cursor within the visible lines so if line 30 is at the
// top of the viewport it will be 0
export class Blame extends React.PureComponent<IProps, IState> {
// Reset show blame to false when props change - do it here so it happens before rendering
// hide if the current line has changed or if the text of the line has changed
// aka input is in progress or if there is an empty line
public static getDerivedStateFromProps(nextProps: IProps, prevState: IState) {
const lineNumberChanged = nextProps.cursorBufferLine !== prevState.currentCursorBufferLine
const lineContentChanged = prevState.currentLineContent !== nextProps.currentLine
if (
(prevState.showBlame && (lineNumberChanged || lineContentChanged)) ||
!nextProps.currentLine
) {
return {
showBlame: false,
blame: prevState.blame,
currentLineContent: nextProps.currentLine,
currentCursorBufferLine: nextProps.cursorBufferLine,
}
}
return null
}
public state: IState = {
error: null,
blame: null,
showBlame: null,
currentLineContent: this.props.currentLine,
currentCursorBufferLine: this.props.cursorBufferLine,
}
private _timeout: any
private readonly DURATION = 300
private readonly LEFT_OFFSET = 4
public async componentDidMount() {
const { cursorBufferLine, mode } = this.props
await this.updateBlame(cursorBufferLine, cursorBufferLine)
if (mode === "auto") {
this.resetTimer()
}
this.props.setupCommand(() => {
const { showBlame } = this.state
this.setState({ showBlame: !showBlame })
})
}
public async componentDidUpdate(prevProps: IProps, prevState: IState) {
const { cursorBufferLine, currentLine, mode } = this.props
if (prevProps.cursorBufferLine !== cursorBufferLine && currentLine) {
await this.updateBlame(cursorBufferLine, cursorBufferLine)
if (mode === "auto") {
return this.resetTimer()
}
}
}
public componentWillUnmount() {
clearTimeout(this._timeout)
}
public componentDidCatch(error: Error) {
warn(`Oni VCS Blame layer failed because: ${error.message}`)
this.setState({ error })
}
public resetTimer = () => {
clearTimeout(this._timeout)
this._timeout = setTimeout(() => {
if (this.props.currentLine) {
this.setState({ showBlame: true })
}
}, this.props.timeout)
}
public getLastEmptyLine() {
const { cursorLine, visibleLines, topBufferLine } = this.props
const lineDetails: ILineDetails = {
lastEmptyLine: null,
nextSpacing: null,
}
for (
let currentBufferLine = cursorLine;
currentBufferLine >= topBufferLine;
currentBufferLine--
) {
const screenLine = currentBufferLine - topBufferLine
const line = visibleLines[screenLine]
if (!line.length) {
const nextLine = visibleLines[screenLine + 1]
lineDetails.lastEmptyLine = currentBufferLine
// search for index of first non-whitespace character which is equivalent
// to the whitespace count
lineDetails.nextSpacing = nextLine.search(/\S/)
break
}
}
return lineDetails
}
public calculatePosition(canFit: boolean) {
const { cursorLine, cursorScreenLine, visibleLines } = this.props
const currentLine = visibleLines[cursorScreenLine]
const character = currentLine && currentLine.length + this.LEFT_OFFSET
if (canFit) {
return this.getPosition({ line: cursorLine, character })
}
const { lastEmptyLine, nextSpacing } = this.getLastEmptyLine()
if (lastEmptyLine) {
return this.getPosition({ line: lastEmptyLine - 1, character: nextSpacing })
}
return this.getPosition()
}
// TODO: possibly add a caching strategy so a new call isn't made each time or
// get a blame for the entire file and store it
public updateBlame = async (lineOne: number, lineTwo: number) => {
const outOfBounds = this.isOutOfBounds(lineOne, lineTwo)
const blame = !outOfBounds ? await this.props.getBlame(lineOne, lineTwo) : null
this.setState({ blame })
}
public formatCommitDate(timestamp: string) {
return new Date(parseInt(timestamp, 10) * 1000)
}
public getPosition(positionToRender?: Position): IBlamePosition {
const emptyPosition: IBlamePosition = {
hide: true,
top: null,
left: null,
}
if (!positionToRender) {
return emptyPosition
}
const position = this.props.bufferToPixel(positionToRender)
if (!position) {
return emptyPosition
}
return {
hide: false,
top: position.pixelY,
left: position.pixelX,
}
}
public isOutOfBounds = (...lines: number[]) => {
return lines.some(
line => !line || line > this.props.bottomBufferLine || line < this.props.topBufferLine,
)
}
public getBlameText = (numberOfTruncations = 0) => {
const { blame } = this.state
if (!blame) {
return null
}
const { author, hash, committer_time } = blame
const formattedDate = this.formatCommitDate(committer_time)
const timeSince = `${getTimeSince(formattedDate)} ago`
const formattedHash = hash.slice(0, 4).toUpperCase()
const words = blame.summary.split(" ")
const message = words.slice(0, words.length - numberOfTruncations).join(" ")
const symbol = "…"
const summary = numberOfTruncations && words.length > 2 ? message.concat(symbol) : message
return words.length < 2
? `${author}, ${timeSince}`
: `${author}, ${timeSince}, ${summary} #${formattedHash}`
}
// Recursively calls get blame text if the message will not fit onto the screen up
// to a limit of 6 times each time removing one word from the blame message
// if after 6 attempts the message is still not small enougth then we render the popup
public canFit = (truncationAmount = 0): ICanFit => {
const { visibleLines, dimensions, cursorScreenLine } = this.props
const message = this.getBlameText(truncationAmount)
const currentLine = visibleLines[cursorScreenLine] || ""
const canFit = dimensions.width > currentLine.length + message.length + this.LEFT_OFFSET
if (!canFit && truncationAmount <= 6) {
return this.canFit(truncationAmount + 1)
}
const truncatedOrFullMessage = canFit ? message : this.getBlameText()
return {
canFit,
message: truncatedOrFullMessage,
position: this.calculatePosition(canFit),
}
}
public render() {
const { blame, showBlame, error } = this.state
if (!blame || !showBlame || error) {
return null
}
const { message, position } = this.canFit()
return (
<Transition in={blame && showBlame} timeout={this.DURATION}>
{(state: TransitionStates) => (
<BlameContainer
{...position}
data-id="vcs.blame"
timeout={this.DURATION}
animationState={state}
height={this.props.fontPixelHeight}
fontFamily={this.props.fontFamily}
>
<BlameDetails>{message}</BlameDetails>
</BlameContainer>
)}
</Transition>
)
}
}
export default class VersionControlBlameLayer implements BufferLayer {
constructor(
private _buffer: Buffer,
private _vcsProvider: VersionControlProvider,
private _configuration: Configuration,
private _commands: Commands.Api,
) {}
public getBlame = async (lineOne: number, lineTwo: number) => {
const fileExists = await pathExists(this._buffer.filePath)
return (
fileExists &&
this._vcsProvider.getBlame({ file: this._buffer.filePath, lineOne, lineTwo })
)
}
get id() {
return "vcs.blame"
}
public setupCommand = (callback: () => void) => {
this._commands.registerCommand({
command: "experimental.vcs.blame.toggleBlame",
name: null,
detail: null,
enabled: this._isActive,
execute: callback,
})
}
public getConfigOpts() {
const fontFamily = this._configuration.getValue<string>("editor.fontFamily")
const timeout = this._configuration.getValue<number>("experimental.vcs.blame.timeout")
const mode = this._configuration.getValue<"auto" | "manual">("experimental.vcs.blame.mode")
return { timeout, mode, fontFamily }
}
public render(context: LayerContextWithCursor) {
const cursorBufferLine = context.cursorLine + 1
const cursorScreenLine = cursorBufferLine - context.topBufferLine
const config = this.getConfigOpts()
const activated = this._isActive()
return (
activated && (
<Blame
{...context}
mode={config.mode}
timeout={config.timeout}
getBlame={this.getBlame}
fontFamily={config.fontFamily}
setupCommand={this.setupCommand}
cursorBufferLine={cursorBufferLine}
cursorScreenLine={cursorScreenLine}
currentLine={context.visibleLines[cursorScreenLine]}
/>
)
)
}
private _isActive() {
return this._vcsProvider && this._vcsProvider.isActivated
}
} | the_stack |
import { IRenderAtom } from '../render/atom';
import { IRenderBlock } from '../render/block';
import { IRenderDoc } from '../render/doc';
import { IRenderText } from '../render/text';
import { ITextService } from '../text/service';
import { ILayoutAtom, LayoutAtom } from './atom';
import { ILayoutBlock, LayoutBlock } from './block';
import { ILayoutDoc, LayoutDoc } from './doc';
import { ILayoutLine, LayoutLine } from './line';
import { ILayoutNode } from './node';
import { ILayoutPage, LayoutPage } from './page';
import { ILayoutText, LayoutText } from './text';
import { ILayoutWord, LayoutWord } from './word';
export interface ILayoutEngine {
updateDoc(doc: ILayoutDoc | null, renderDoc: IRenderDoc<any, any>): ILayoutDoc;
}
export class LayoutEngine implements ILayoutEngine {
constructor(protected textService: ITextService) {}
updateDoc(doc: ILayoutDoc | null, renderDoc: IRenderDoc<any, any>) {
if (!renderDoc.needLayout && doc) {
return doc;
}
const pages: ILayoutPage[] = [];
const childrenMap: { [key: string]: ILayoutNode[] } = {};
if (doc) {
doc.children.forEach((page) => {
pages.push(page as ILayoutPage);
page.children.forEach((child) => {
if (!child.renderId) {
throw new Error('Render ID missing on layout node.');
}
childrenMap[child.renderId] = childrenMap[child.renderId] || [];
childrenMap[child.renderId].push(child);
});
});
}
const newChildren: ILayoutNode[] = [];
renderDoc.children.forEach((child) => {
switch (child.type) {
case 'block':
newChildren.push(
...this.updateBlock(
(childrenMap[child.id] as ILayoutBlock[]) || [],
child as IRenderBlock<any, any>,
renderDoc.width - renderDoc.paddingLeft - renderDoc.paddingRight,
),
);
break;
default:
throw new Error(`Child type ${child.type} is invalid.`);
}
});
renderDoc.clearNeedLayout();
return this.buildDoc(
renderDoc,
this.reflowPages(
pages,
newChildren,
renderDoc.width,
renderDoc.height,
renderDoc.paddingTop,
renderDoc.paddingBottom,
renderDoc.paddingLeft,
renderDoc.paddingRight,
),
);
}
protected updateBlock(blocks: ILayoutBlock[], renderBlock: IRenderBlock<any, any>, width: number): ILayoutBlock[] {
if (!renderBlock.needLayout && blocks.length > 0) {
return blocks;
}
const lines: ILayoutLine[] = [];
const childrenMap: { [key: string]: ILayoutNode[] } = {};
for (const block of blocks) {
block.children.forEach((line) => {
lines.push(line as ILayoutLine);
line.children.forEach((child) => {
if (!child.renderId) {
throw new Error('Render ID missing on layout node.');
}
childrenMap[child.renderId] = childrenMap[child.renderId] || [];
childrenMap[child.renderId].push(child);
});
});
}
const newChildren: ILayoutNode[] = [];
renderBlock.children.forEach((renderChild) => {
switch (renderChild.type) {
case 'text':
newChildren.push(
...this.updateText(
(childrenMap[renderChild.id] as ILayoutText[]) || [],
renderChild as IRenderText<any, any>,
),
);
break;
case 'atom':
newChildren.push(
...this.updateAtom(
(childrenMap[renderChild.id] as ILayoutAtom[]) || [],
renderChild as IRenderAtom<any, any>,
),
);
break;
default:
throw new Error(`Child type ${renderChild.type} is invalid.`);
}
});
renderBlock.clearNeedLayout();
return [
this.buildBlock(
renderBlock,
this.reflowLines(
renderBlock.id,
lines,
newChildren,
width - renderBlock.paddingLeft - renderBlock.paddingRight,
),
width,
),
];
}
protected updateText(texts: ILayoutText[], renderText: IRenderText<any, any>): ILayoutText[] {
if (!renderText.needLayout && texts.length > 0) {
return texts;
}
const newChildren: ILayoutNode[] = [];
this.textService.breakIntoWords(renderText.text).forEach((word) => {
newChildren.push(
this.buildWord(
getNextId(
newChildren.length > 0 ? newChildren[newChildren.length - 1].id : null,
`${renderText.id}.word`,
),
renderText,
word.text,
word.whitespaceSize,
),
);
});
renderText.clearNeedLayout();
return [this.buildText(renderText, newChildren)];
}
protected updateAtom(atoms: ILayoutAtom[], renderAtom: IRenderAtom<any, any>): ILayoutAtom[] {
if (!renderAtom.needLayout && atoms.length > 0) {
return atoms;
}
renderAtom.clearNeedLayout();
return [this.buildAtom(renderAtom)];
}
protected buildDoc(renderDoc: IRenderDoc<any, any>, children: ILayoutNode[]) {
return new LayoutDoc(
renderDoc.id,
children,
renderDoc.width,
renderDoc.height,
renderDoc.paddingTop,
renderDoc.paddingBottom,
renderDoc.paddingLeft,
renderDoc.paddingRight,
);
}
protected buildBlock(renderBlock: IRenderBlock<any, any>, children: ILayoutNode[], width: number) {
if (renderBlock.type !== 'block') {
throw new Error('Expected block.');
}
return new LayoutBlock(
renderBlock.id,
children,
width,
renderBlock.paddingTop,
renderBlock.paddingBottom,
renderBlock.paddingLeft,
renderBlock.paddingRight,
);
}
protected buildText(renderText: IRenderText<any, any>, children: ILayoutNode[]) {
if (renderText.type !== 'text') {
throw new Error('Expected text.');
}
return new LayoutText(
renderText.id,
children,
renderText.paddingTop,
renderText.paddingBottom,
renderText.paddingLeft,
renderText.paddingRight,
renderText.font,
);
}
protected buildWord(id: string, renderText: IRenderText<any, any>, text: string, whitespaceSize: number) {
if (renderText.type !== 'text') {
throw new Error('Expected text.');
}
return new LayoutWord(renderText.id, text, whitespaceSize, renderText.font, this.textService);
}
protected buildAtom(renderAtom: IRenderAtom<any, any>) {
if (renderAtom.type !== 'atom') {
throw new Error('Expected atom.');
}
return new LayoutAtom(renderAtom.id, renderAtom.width, renderAtom.height);
}
protected reflowPages(
pages: ILayoutPage[],
nodes: ILayoutNode[],
width: number,
height: number,
paddingTop: number,
paddingBottom: number,
paddingLeft: number,
paddingRight: number,
) {
const innerHeight = height - paddingTop - paddingBottom;
nodes = nodes.slice();
const newPages: ILayoutNode[] = [];
while (nodes.length > 0) {
if (newPages.length < pages.length) {
const page = pages[newPages.length];
let reflowNeeded = false;
for (let n = 0, nn = page.children.length; n < nn; n++) {
const child = page.children.at(n);
if (child.id !== nodes[n].id || checkNeedsReflow(nodes[n])) {
reflowNeeded = true;
break;
}
}
if (!reflowNeeded) {
newPages.push(page);
nodes.splice(0, page.children.length);
continue;
}
}
const newChildren: ILayoutNode[] = [];
let currentHeight = 0;
// Push whole nodes to page until either no more node or no longer fit
let node = nodes.shift();
while (node && currentHeight + node.height <= innerHeight) {
clearNeedReflow(node);
newChildren.push(node);
currentHeight += node.height;
node = nodes.shift();
}
// If there is remainder node, try to push part of it to page
if (node) {
const nodeChildren: ILayoutNode[] = [];
for (let m = 0, mm = node.children.length; m < mm; m++) {
const nodeChild = node.children.at(m);
if (currentHeight + nodeChild.height + node.paddingVertical > innerHeight) {
break;
}
nodeChildren.push(nodeChild);
currentHeight += nodeChild.height;
}
if (nodeChildren.length > 0) {
clearNeedReflow(node);
switch (node.type) {
case 'block':
// Split block to two, one to push to this page, other goes back
// to list of nodes to process
const node1 = new LayoutBlock(
node.renderId!,
nodeChildren,
width,
node.paddingTop,
node.paddingBottom,
node.paddingLeft,
node.paddingRight,
);
newChildren.push(node1);
currentHeight += node1.height;
const node2 = new LayoutBlock(
node.renderId!,
node.children.slice(nodeChildren.length),
width,
node.paddingTop,
node.paddingBottom,
node.paddingLeft,
node.paddingRight,
);
nodes.unshift(node2);
break;
default:
throw new Error('Invalid node type encountered while reflowing page.');
}
} else {
nodes.unshift(node);
}
}
const newPage = new LayoutPage(
newChildren,
width,
height,
paddingTop,
paddingBottom,
paddingLeft,
paddingRight,
);
newPages.push(newPage);
}
return newPages;
}
protected reflowLines(parentId: string, lines: ILayoutLine[], nodes: ILayoutNode[], width: number) {
nodes = nodes.slice();
const newLines: ILayoutNode[] = [];
while (nodes.length > 0) {
if (newLines.length < newLines.length) {
const line = lines[newLines.length];
let reflowNeeded = false;
for (let n = 0, nn = line.children.length; n < nn; n++) {
const child = line.children.at(n);
if (child.id !== nodes[n].id || checkNeedsReflow(nodes[n])) {
reflowNeeded = true;
break;
}
}
if (!reflowNeeded) {
newLines.push(line);
nodes.splice(0, line.children.length);
continue;
}
}
const newChildren: ILayoutNode[] = [];
let currentWidth = 0;
// Push whole nodes to line until either no more node or no longer fit
let node = nodes.shift();
while (node && currentWidth + node.width <= width) {
clearNeedReflow(node);
newChildren.push(node);
currentWidth += node.width;
node = nodes.shift();
}
// If there is remainder node, try to push part of it to line
if (node) {
const nodeChildren = node.children.slice();
const newNodeChildren: ILayoutNode[] = [];
for (let m = 0; m < nodeChildren.length; m++) {
let nodeChild = nodeChildren[m];
if (nodeChild.type === 'word' && nodeChild.width > width) {
let breakAt = nodeChild.convertCoordinatesToPosition(width, 0);
if (nodeChild.resolveBoundingBoxes(breakAt, breakAt).boundingBoxes[0].left > width) {
breakAt--;
}
const [brokenNodeChild1, brokenNodeChild2] = (nodeChild as ILayoutWord).breakAt(breakAt);
nodeChild = brokenNodeChild1;
nodeChildren.splice(m, 1, brokenNodeChild1, brokenNodeChild2);
}
if (currentWidth + nodeChild.width > width) {
break;
}
newNodeChildren.push(nodeChild);
currentWidth += nodeChild.width;
}
if (newNodeChildren.length > 0) {
clearNeedReflow(node);
switch (node.type) {
case 'text':
// Split text to two, one to push to this line, other goes back
// to list of nodes to process
const text = node as ILayoutText;
const node1 = new LayoutText(
text.renderId,
newNodeChildren,
text.paddingTop,
text.paddingBottom,
text.paddingLeft,
text.paddingRight,
text.font,
);
newChildren.push(node1);
currentWidth += node1.width;
const node2 = new LayoutText(
text.renderId,
nodeChildren.slice(newNodeChildren.length),
text.paddingTop,
text.paddingBottom,
text.paddingLeft,
text.paddingRight,
text.font,
);
nodes.unshift(node2);
break;
case 'atom':
// If atom is wider than line and line is empty, push atom to line
// and let it clip
if (node.width > width && newChildren.length === 0) {
newChildren.push(node);
} else {
// Atom cannot be split, goes back to list of nodes to process
nodes.unshift(node);
}
break;
default:
throw new Error('Invalid node type encountered while reflowing page.');
}
} else {
nodes.unshift(node);
}
}
const newLine = new LayoutLine(newChildren, width);
newLines.push(newLine);
}
return newLines;
}
}
function getNextId(previousId: string | null, prefix: string) {
if (!previousId) {
return `${prefix}.0`;
}
const segments = previousId.split('.');
const counter = parseInt(segments[segments.length - 1], 36);
return `${prefix}.${(counter + 1).toString(36)}`;
}
function checkNeedsReflow(node: ILayoutNode) {
switch (node.type) {
case 'block':
return (node as ILayoutBlock).needReflow;
default:
return false;
}
}
function clearNeedReflow(node: ILayoutNode) {
switch (node.type) {
case 'block':
(node as ILayoutBlock).clearNeedReflow();
break;
}
} | the_stack |
import { mXparserConstants } from '../mXparserConstants';
import { javaemul } from 'j4ts/j4ts';
import { BinaryRelations } from './BinaryRelations';
import { Evaluate } from './Evaluate';
import { MathFunctions } from './MathFunctions';
import { Coefficients } from './Coefficients';
import { MathConstants } from './MathConstants';
/**
* SpecialFunctions - special (non-elementary functions).
*
* @author <b>Mariusz Gromada</b><br>
* <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br>
*
* @version 4.3.0
* @class
*/
export class SpecialFunctions {
/**
* Exponential integral function Ei(x)
* @param {number} x Point at which function will be evaluated.
* @return {number} Exponential integral function Ei(x)
*/
public static exponentialIntegralEi(x: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (x < -5.0)return SpecialFunctions.continuedFractionEi(x);
if (x === 0.0)return -javaemul.internal.DoubleHelper.MAX_VALUE;
if (x < 6.8)return SpecialFunctions.powerSeriesEi(x);
if (x < 50.0)return SpecialFunctions.argumentAdditionSeriesEi(x);
return SpecialFunctions.continuedFractionEi(x);
}
/**
* Constants for Exponential integral function Ei(x) calculation
*/
static EI_DBL_EPSILON: number; public static EI_DBL_EPSILON_$LI$(): number { if (SpecialFunctions.EI_DBL_EPSILON == null) { SpecialFunctions.EI_DBL_EPSILON = javaemul.internal.MathHelper.ulp(1.0); } return SpecialFunctions.EI_DBL_EPSILON; }
static EI_EPSILON: number; public static EI_EPSILON_$LI$(): number { if (SpecialFunctions.EI_EPSILON == null) { SpecialFunctions.EI_EPSILON = 10.0 * SpecialFunctions.EI_DBL_EPSILON_$LI$(); } return SpecialFunctions.EI_EPSILON; }
/**
* Supporting function
* while Exponential integral function Ei(x) calculation
* @param {number} x
* @return {number}
* @private
*/
/*private*/ static continuedFractionEi(x: number): number {
let Am1: number = 1.0;
let A0: number = 0.0;
let Bm1: number = 0.0;
let B0: number = 1.0;
let a: number = Math.exp(x);
let b: number = -x + 1.0;
let Ap1: number = b * A0 + a * Am1;
let Bp1: number = b * B0 + a * Bm1;
let j: number = 1;
a = 1.0;
while((Math.abs(Ap1 * B0 - A0 * Bp1) > SpecialFunctions.EI_EPSILON_$LI$() * Math.abs(A0 * Bp1))) {{
if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN;
if (Math.abs(Bp1) > 1.0){
Am1 = A0 / Bp1;
A0 = Ap1 / Bp1;
Bm1 = B0 / Bp1;
B0 = 1.0;
} else {
Am1 = A0;
A0 = Ap1;
Bm1 = B0;
B0 = Bp1;
}
a = -j * j;
b += 2.0;
Ap1 = b * A0 + a * Am1;
Bp1 = b * B0 + a * Bm1;
j += 1;
}};
return (-Ap1 / Bp1);
}
/**
* Supporting function
* while Exponential integral function Ei(x) calculation
* @param {number} x
* @return {number}
* @private
*/
/*private*/ static powerSeriesEi(x: number): number {
let xn: number = -x;
let Sn: number = -x;
let Sm1: number = 0.0;
let hsum: number = 1.0;
const g: number = MathConstants.EULER_MASCHERONI;
let y: number = 1.0;
let factorial: number = 1.0;
if (x === 0.0)return -javaemul.internal.DoubleHelper.MAX_VALUE;
while((Math.abs(Sn - Sm1) > SpecialFunctions.EI_EPSILON_$LI$() * Math.abs(Sm1))) {{
if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN;
Sm1 = Sn;
y += 1.0;
xn *= (-x);
factorial *= y;
hsum += (1.0 / y);
Sn += hsum * xn / factorial;
}};
return (g + Math.log(Math.abs(x)) - Math.exp(x) * Sn);
}
/**
* Supporting function
* while Exponential integral function Ei(x) calculation
* @param {number} x
* @return {number}
* @private
*/
/*private*/ static argumentAdditionSeriesEi(x: number): number {
const k: number = (<number>(x + 0.5)|0);
let j: number = 0;
const xx: number = k;
const dx: number = x - xx;
let xxj: number = xx;
const edx: number = Math.exp(dx);
let Sm: number = 1.0;
let Sn: number = (edx - 1.0) / xxj;
let term: number = javaemul.internal.DoubleHelper.MAX_VALUE;
let factorial: number = 1.0;
let dxj: number = 1.0;
while((Math.abs(term) > SpecialFunctions.EI_EPSILON_$LI$() * Math.abs(Sn))) {{
if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN;
j++;
factorial *= j;
xxj *= xx;
dxj *= (-dx);
Sm += (dxj / factorial);
term = (factorial * (edx * Sm - 1.0)) / xxj;
Sn += term;
}};
return Coefficients.EI_$LI$()[k - 7] + Sn * Math.exp(xx);
}
/**
* Logarithmic integral function li(x)
* @param {number} x Point at which function will be evaluated.
* @return {number} Logarithmic integral function li(x)
*/
public static logarithmicIntegralLi(x: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (x < 0)return javaemul.internal.DoubleHelper.NaN;
if (x === 0)return 0;
if (x === 2)return MathConstants.LI2;
return SpecialFunctions.exponentialIntegralEi(MathFunctions.ln(x));
}
/**
* Offset logarithmic integral function Li(x)
* @param {number} x Point at which function will be evaluated.
* @return {number} Offset logarithmic integral function Li(x)
*/
public static offsetLogarithmicIntegralLi(x: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (x < 0)return javaemul.internal.DoubleHelper.NaN;
if (x === 0)return -MathConstants.LI2;
return SpecialFunctions.logarithmicIntegralLi(x) - MathConstants.LI2;
}
/**
* Calculates the error function
* @param {number} x Point at which function will be evaluated.
* @return {number} Error function erf(x)
*/
public static erf(x: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (x === 0)return 0;
if (x === javaemul.internal.DoubleHelper.POSITIVE_INFINITY)return 1.0;
if (x === javaemul.internal.DoubleHelper.NEGATIVE_INFINITY)return -1.0;
return SpecialFunctions.erfImp(x, false);
}
/**
* Calculates the complementary error function.
* @param {number} x Point at which function will be evaluated.
* @return {number} Complementary error function erfc(x)
*/
public static erfc(x: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (x === 0)return 1;
if (x === javaemul.internal.DoubleHelper.POSITIVE_INFINITY)return 0.0;
if (x === javaemul.internal.DoubleHelper.NEGATIVE_INFINITY)return 2.0;
return SpecialFunctions.erfImp(x, true);
}
/**
* Calculates the inverse error function evaluated at x.
* @param {number} x Point at which function will be evaluated.
* @return {number} Inverse error function erfInv(x)
*/
public static erfInv(x: number): number {
if (x === 0.0)return 0;
if (x >= 1.0)return javaemul.internal.DoubleHelper.POSITIVE_INFINITY;
if (x <= -1.0)return javaemul.internal.DoubleHelper.NEGATIVE_INFINITY;
let p: number;
let q: number;
let s: number;
if (x < 0){
p = -x;
q = 1 - p;
s = -1;
} else {
p = x;
q = 1 - x;
s = 1;
}
return SpecialFunctions.erfInvImpl(p, q, s);
}
/**
* Calculates the inverse error function evaluated at x.
* @param x
* @param {boolean} invert
* @return
* @param {number} z
* @return {number}
* @private
*/
/*private*/ static erfImp(z: number, invert: boolean): number {
if (z < 0){
if (!invert)return -SpecialFunctions.erfImp(-z, false);
if (z < -0.5)return 2 - SpecialFunctions.erfImp(-z, true);
return 1 + SpecialFunctions.erfImp(-z, false);
}
let result: number;
if (z < 0.5){
if (z < 1.0E-10)result = (z * 1.125) + (z * 0.0033791670955125737); else result = (z * 1.125) + (z * Evaluate.polynomial(z, Coefficients.erfImpAn_$LI$()) / Evaluate.polynomial(z, Coefficients.erfImpAd_$LI$()));
} else if ((z < 110) || ((z < 110) && invert)){
invert = !invert;
let r: number;
let b: number;
if (z < 0.75){
r = Evaluate.polynomial(z - 0.5, Coefficients.erfImpBn_$LI$()) / Evaluate.polynomial(z - 0.5, Coefficients.erfImpBd_$LI$());
b = 0.3440242;
} else if (z < 1.25){
r = Evaluate.polynomial(z - 0.75, Coefficients.erfImpCn_$LI$()) / Evaluate.polynomial(z - 0.75, Coefficients.erfImpCd_$LI$());
b = 0.41999093;
} else if (z < 2.25){
r = Evaluate.polynomial(z - 1.25, Coefficients.erfImpDn_$LI$()) / Evaluate.polynomial(z - 1.25, Coefficients.erfImpDd_$LI$());
b = 0.4898625;
} else if (z < 3.5){
r = Evaluate.polynomial(z - 2.25, Coefficients.erfImpEn_$LI$()) / Evaluate.polynomial(z - 2.25, Coefficients.erfImpEd_$LI$());
b = 0.5317371;
} else if (z < 5.25){
r = Evaluate.polynomial(z - 3.5, Coefficients.erfImpFn_$LI$()) / Evaluate.polynomial(z - 3.5, Coefficients.erfImpFd_$LI$());
b = 0.54899734;
} else if (z < 8){
r = Evaluate.polynomial(z - 5.25, Coefficients.erfImpGn_$LI$()) / Evaluate.polynomial(z - 5.25, Coefficients.erfImpGd_$LI$());
b = 0.5571741;
} else if (z < 11.5){
r = Evaluate.polynomial(z - 8, Coefficients.erfImpHn_$LI$()) / Evaluate.polynomial(z - 8, Coefficients.erfImpHd_$LI$());
b = 0.5609808;
} else if (z < 17){
r = Evaluate.polynomial(z - 11.5, Coefficients.erfImpIn_$LI$()) / Evaluate.polynomial(z - 11.5, Coefficients.erfImpId_$LI$());
b = 0.56264937;
} else if (z < 24){
r = Evaluate.polynomial(z - 17, Coefficients.erfImpJn_$LI$()) / Evaluate.polynomial(z - 17, Coefficients.erfImpJd_$LI$());
b = 0.5634598;
} else if (z < 38){
r = Evaluate.polynomial(z - 24, Coefficients.erfImpKn_$LI$()) / Evaluate.polynomial(z - 24, Coefficients.erfImpKd_$LI$());
b = 0.5638478;
} else if (z < 60){
r = Evaluate.polynomial(z - 38, Coefficients.erfImpLn_$LI$()) / Evaluate.polynomial(z - 38, Coefficients.erfImpLd_$LI$());
b = 0.5640528;
} else if (z < 85){
r = Evaluate.polynomial(z - 60, Coefficients.erfImpMn_$LI$()) / Evaluate.polynomial(z - 60, Coefficients.erfImpMd_$LI$());
b = 0.5641309;
} else {
r = Evaluate.polynomial(z - 85, Coefficients.erfImpNn_$LI$()) / Evaluate.polynomial(z - 85, Coefficients.erfImpNd_$LI$());
b = 0.56415844;
}
const g: number = MathFunctions.exp(-z * z) / z;
result = (g * b) + (g * r);
} else {
result = 0;
invert = !invert;
}
if (invert)result = 1 - result;
return result;
}
/**
* Calculates the complementary inverse error function evaluated at x.
* @param {number} z Point at which function will be evaluated.
* @return {number} Inverse of complementary inverse error function erfcInv(x)
*/
public static erfcInv(z: number): number {
if (z <= 0.0)return javaemul.internal.DoubleHelper.POSITIVE_INFINITY;
if (z >= 2.0)return javaemul.internal.DoubleHelper.NEGATIVE_INFINITY;
let p: number;
let q: number;
let s: number;
if (z > 1){
q = 2 - z;
p = 1 - q;
s = -1;
} else {
p = 1 - z;
q = z;
s = 1;
}
return SpecialFunctions.erfInvImpl(p, q, s);
}
/**
* The implementation of the inverse error function.
* @param {number} p
* @param {number} q
* @param {number} s
* @return
* @return {number}
* @private
*/
/*private*/ static erfInvImpl(p: number, q: number, s: number): number {
let result: number;
if (p <= 0.5){
const y: number = 0.089131474;
const g: number = p * (p + 10);
const r: number = Evaluate.polynomial(p, Coefficients.ervInvImpAn_$LI$()) / Evaluate.polynomial(p, Coefficients.ervInvImpAd_$LI$());
result = (g * y) + (g * r);
} else if (q >= 0.25){
const y: number = 2.2494812;
const g: number = MathFunctions.sqrt(-2 * MathFunctions.ln(q));
const xs: number = q - 0.25;
const r: number = Evaluate.polynomial(xs, Coefficients.ervInvImpBn_$LI$()) / Evaluate.polynomial(xs, Coefficients.ervInvImpBd_$LI$());
result = g / (y + r);
} else {
const x: number = MathFunctions.sqrt(-MathFunctions.ln(q));
if (x < 3){
const y: number = 0.80722046;
const xs: number = x - 1.125;
const r: number = Evaluate.polynomial(xs, Coefficients.ervInvImpCn_$LI$()) / Evaluate.polynomial(xs, Coefficients.ervInvImpCd_$LI$());
result = (y * x) + (r * x);
} else if (x < 6){
const y: number = 0.9399557;
const xs: number = x - 3;
const r: number = Evaluate.polynomial(xs, Coefficients.ervInvImpDn_$LI$()) / Evaluate.polynomial(xs, Coefficients.ervInvImpDd_$LI$());
result = (y * x) + (r * x);
} else if (x < 18){
const y: number = 0.9836283;
const xs: number = x - 6;
const r: number = Evaluate.polynomial(xs, Coefficients.ervInvImpEn_$LI$()) / Evaluate.polynomial(xs, Coefficients.ervInvImpEd_$LI$());
result = (y * x) + (r * x);
} else if (x < 44){
const y: number = 0.99714565;
const xs: number = x - 18;
const r: number = Evaluate.polynomial(xs, Coefficients.ervInvImpFn_$LI$()) / Evaluate.polynomial(xs, Coefficients.ervInvImpFd_$LI$());
result = (y * x) + (r * x);
} else {
const y: number = 0.9994135;
const xs: number = x - 44;
const r: number = Evaluate.polynomial(xs, Coefficients.ervInvImpGn_$LI$()) / Evaluate.polynomial(xs, Coefficients.ervInvImpGd_$LI$());
result = (y * x) + (r * x);
}
}
return s * result;
}
/**
* Gamma function for the integers
* @param {number} n Integer number
* @return {number} Returns Gamma function for the integers.
* @private
*/
/*private*/ static gammaInt(n: number): number {
if (n === 0)return MathConstants.EULER_MASCHERONI;
if (n === 1)return 1;
if (n === 2)return 1;
if (n === 3)return 1.0 * 2.0;
if (n === 4)return 1.0 * 2.0 * 3.0;
if (n === 5)return 1.0 * 2.0 * 3.0 * 4.0;
if (n === 6)return 1.0 * 2.0 * 3.0 * 4.0 * 5.0;
if (n === 7)return 1.0 * 2.0 * 3.0 * 4.0 * 5.0 * 6.0;
if (n === 8)return 1.0 * 2.0 * 3.0 * 4.0 * 5.0 * 6.0 * 7.0;
if (n === 9)return 1.0 * 2.0 * 3.0 * 4.0 * 5.0 * 6.0 * 7.0 * 8.0;
if (n === 10)return 1.0 * 2.0 * 3.0 * 4.0 * 5.0 * 6.0 * 7.0 * 8.0 * 9.0;
if (n >= 11)return MathFunctions.factorial$double(n - 1);
if (n <= -1){
const r: number = -n;
const factr: number = MathFunctions.factorial$double(r);
let sign: number = -1;
if (r % 2 === 0)sign = 1;
return sign / (r * factr) - (1.0 / r) * SpecialFunctions.gammaInt(n + 1);
}
return javaemul.internal.DoubleHelper.NaN;
}
/**
* Real valued Gamma function
*
* @param {number} x Argument value
* @return {number} Returns gamma function value.
*/
public static gamma(x: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (x === javaemul.internal.DoubleHelper.POSITIVE_INFINITY)return javaemul.internal.DoubleHelper.POSITIVE_INFINITY;
if (x === javaemul.internal.DoubleHelper.NEGATIVE_INFINITY)return javaemul.internal.DoubleHelper.NaN;
const xabs: number = MathFunctions.abs(x);
const xint: number = Math.round(xabs);
if (MathFunctions.abs(xabs - xint) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON){
let n: number = (n => n<0?Math.ceil(n):Math.floor(n))(<number>xint);
if (x < 0)n = -n;
return SpecialFunctions.gammaInt(n);
}
return SpecialFunctions.lanchosGamma(x);
}
/**
* Gamma function implementation based on
* Lanchos approximation algorithm
*
* @param {number} x Function parameter
* @return {number} Gamma function value (Lanchos approx).
*/
public static lanchosGamma(x: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
const xabs: number = MathFunctions.abs(x);
const xint: number = Math.round(xabs);
if (x > BinaryRelations.DEFAULT_COMPARISON_EPSILON){
if (MathFunctions.abs(xabs - xint) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return MathFunctions.factorial$double(xint - 1);
} else if (x < -BinaryRelations.DEFAULT_COMPARISON_EPSILON){
if (MathFunctions.abs(xabs - xint) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return javaemul.internal.DoubleHelper.NaN;
} else return javaemul.internal.DoubleHelper.NaN;
if (x < 0.5)return MathConstants.PI / (Math.sin(MathConstants.PI * x) * SpecialFunctions.lanchosGamma(1 - x));
const g: number = 7;
x -= 1;
let a: number = Coefficients.lanchosGamma_$LI$()[0];
const t: number = x + g + 0.5;
for(let i: number = 1; i < Coefficients.lanchosGamma_$LI$().length; i++) {{
a += Coefficients.lanchosGamma_$LI$()[i] / (x + i);
};}
return Math.sqrt(2 * MathConstants.PI) * Math.pow(t, x + 0.5) * Math.exp(-t) * a;
}
/**
* Real valued log gamma function.
* @param {number} x Argument value
* @return {number} Returns log value from gamma function.
*/
public static logGamma(x: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (x === javaemul.internal.DoubleHelper.POSITIVE_INFINITY)return javaemul.internal.DoubleHelper.POSITIVE_INFINITY;
if (x === javaemul.internal.DoubleHelper.NEGATIVE_INFINITY)return javaemul.internal.DoubleHelper.NaN;
if (MathFunctions.isInteger(x)){
if (x >= 0)return Math.log(Math.abs(SpecialFunctions.gammaInt((n => n<0?Math.ceil(n):Math.floor(n))(<number>(Math.round(x)))))); else return Math.log(Math.abs(SpecialFunctions.gammaInt(-(n => n<0?Math.ceil(n):Math.floor(n))(<number>(Math.round(-x))))));
}
let p: number;
let q: number;
let w: number;
let z: number;
if (x < -34.0){
q = -x;
w = SpecialFunctions.logGamma(q);
p = Math.floor(q);
if (Math.abs(p - q) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return javaemul.internal.DoubleHelper.NaN;
z = q - p;
if (z > 0.5){
p += 1.0;
z = p - q;
}
z = q * Math.sin(Math.PI * z);
if (Math.abs(z) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return javaemul.internal.DoubleHelper.NaN;
z = MathConstants.LNPI_$LI$() - Math.log(z) - w;
return z;
}
if (x < 13.0){
z = 1.0;
while((x >= 3.0)) {{
x -= 1.0;
z *= x;
}};
while((x < 2.0)) {{
if (Math.abs(x) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return javaemul.internal.DoubleHelper.NaN;
z /= x;
x += 1.0;
}};
if (z < 0.0)z = -z;
if (x === 2.0)return Math.log(z);
x -= 2.0;
p = x * Evaluate.polevl(x, Coefficients.logGammaB_$LI$(), 5) / Evaluate.p1evl(x, Coefficients.logGammaC_$LI$(), 6);
return Math.log(z) + p;
}
if (x > 2.556348E305)return javaemul.internal.DoubleHelper.NaN;
q = (x - 0.5) * Math.log(x) - x + 0.9189385332046728;
if (x > 1.0E8)return q;
p = 1.0 / (x * x);
if (x >= 1000.0)q += ((7.936507936507937E-4 * p - 0.002777777777777778) * p + 0.08333333333333333) / x; else q += Evaluate.polevl(p, Coefficients.logGammaA_$LI$(), 4) / x;
return q;
}
/**
* Signum from the real valued gamma function.
* @param {number} x Argument value
* @return {number} Returns signum of the gamma(x)
*/
public static sgnGamma(x: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (x === javaemul.internal.DoubleHelper.POSITIVE_INFINITY)return 1;
if (x === javaemul.internal.DoubleHelper.NEGATIVE_INFINITY)return javaemul.internal.DoubleHelper.NaN;
if (x > 0)return 1;
if (MathFunctions.isInteger(x))return MathFunctions.sgn(SpecialFunctions.gammaInt(-(n => n<0?Math.ceil(n):Math.floor(n))(<number>(Math.round(-x)))));
x = -x;
const fx: number = Math.floor(x);
const div2remainder: number = Math.floor(fx % 2);
if (div2remainder === 0)return -1; else return 1;
}
/**
* Regularized lower gamma function 'P'
* @param {number} s Argument value
* @param {number} x Argument value
* @return {number} Value of the regularized lower gamma function 'P'.
*/
public static regularizedGammaLowerP(s: number, x: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (/* isNaN */isNaN(s))return javaemul.internal.DoubleHelper.NaN;
if (MathFunctions.almostEqual(x, 0))return 0;
if (MathFunctions.almostEqual(s, 0))return 1 + SpecialFunctions.exponentialIntegralEi(-x) / MathConstants.EULER_MASCHERONI;
if (MathFunctions.almostEqual(s, 1))return 1 - Math.exp(-x);
if (x < 0)return javaemul.internal.DoubleHelper.NaN;
if (s < 0)return SpecialFunctions.regularizedGammaLowerP(s + 1, x) + (Math.pow(x, s) * Math.exp(-x)) / (s * SpecialFunctions.gamma(s));
const epsilon: number = 1.0E-15;
const bigNumber: number = 4.503599627370496E15;
const bigNumberInverse: number = 2.220446049250313E-16;
const ax: number = (s * Math.log(x)) - x - SpecialFunctions.logGamma(s);
if (ax < -709.782712893384){
return 1;
}
if (x <= 1 || x <= s){
let r2: number = s;
let c2: number = 1;
let ans2: number = 1;
do {{
r2 = r2 + 1;
c2 = c2 * x / r2;
ans2 += c2;
}} while(((c2 / ans2) > epsilon));
return Math.exp(ax) * ans2 / s;
}
let c: number = 0;
let y: number = 1 - s;
let z: number = x + y + 1;
let p3: number = 1;
let q3: number = x;
let p2: number = x + 1;
let q2: number = z * x;
let ans: number = p2 / q2;
let error: number;
do {{
if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN;
c++;
y += 1;
z += 2;
const yc: number = y * c;
const p: number = (p2 * z) - (p3 * yc);
const q: number = (q2 * z) - (q3 * yc);
if (q !== 0){
const nextans: number = p / q;
error = Math.abs((ans - nextans) / nextans);
ans = nextans;
} else {
error = 1;
}
p3 = p2;
p2 = p;
q3 = q2;
q2 = q;
if (Math.abs(p) > bigNumber){
p3 *= bigNumberInverse;
p2 *= bigNumberInverse;
q3 *= bigNumberInverse;
q2 *= bigNumberInverse;
}
}} while((error > epsilon));
return 1 - (Math.exp(ax) * ans);
}
/**
* Incomplete lower gamma function
* @param {number} s Argument value
* @param {number} x Argument value
* @return {number} Value of the incomplete lower gamma function.
*/
public static incompleteGammaLower(s: number, x: number): number {
return SpecialFunctions.gamma(s) * SpecialFunctions.regularizedGammaLowerP(s, x);
}
/**
* Regularized upper gamma function 'Q'
* @param {number} s Argument value
* @param {number} x Argument value
* @return {number} Value of the regularized upper gamma function 'Q'.
*/
public static regularizedGammaUpperQ(s: number, x: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (/* isNaN */isNaN(s))return javaemul.internal.DoubleHelper.NaN;
if (MathFunctions.almostEqual(x, 0))return 1;
if (MathFunctions.almostEqual(s, 0))return -SpecialFunctions.exponentialIntegralEi(-x) / MathConstants.EULER_MASCHERONI;
if (MathFunctions.almostEqual(s, 1))return Math.exp(-x);
if (x < 0)return javaemul.internal.DoubleHelper.NaN;
if (s < 0)return SpecialFunctions.regularizedGammaUpperQ(s + 1, x) - (Math.pow(x, s) * Math.exp(-x)) / (s * SpecialFunctions.gamma(s));
let ax: number = s * Math.log(x) - x - SpecialFunctions.logGamma(s);
if (ax < -709.782712893384){
return 0;
}
let t: number;
const igammaepsilon: number = 1.0E-15;
const igammabignumber: number = 4.503599627370496E15;
const igammabignumberinv: number = 2.220446049250313 * 1.0E-16;
ax = Math.exp(ax);
let y: number = 1 - s;
let z: number = x + y + 1;
let c: number = 0;
let pkm2: number = 1;
let qkm2: number = x;
let pkm1: number = x + 1;
let qkm1: number = z * x;
let ans: number = pkm1 / qkm1;
do {{
if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN;
c = c + 1;
y = y + 1;
z = z + 2;
const yc: number = y * c;
const pk: number = pkm1 * z - pkm2 * yc;
const qk: number = qkm1 * z - qkm2 * yc;
if (qk !== 0){
const r: number = pk / qk;
t = Math.abs((ans - r) / r);
ans = r;
} else {
t = 1;
}
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if (Math.abs(pk) > igammabignumber){
pkm2 = pkm2 * igammabignumberinv;
pkm1 = pkm1 * igammabignumberinv;
qkm2 = qkm2 * igammabignumberinv;
qkm1 = qkm1 * igammabignumberinv;
}
}} while((t > igammaepsilon));
return ans * ax;
}
/**
* Incomplete upper gamma function
* @param {number} s Argument value
* @param {number} x Argument value
* @return {number} Value of the incomplete upper gamma function.
*/
public static incompleteGammaUpper(s: number, x: number): number {
return SpecialFunctions.gamma(s) * SpecialFunctions.regularizedGammaUpperQ(s, x);
}
/**
* Digamma function as the logarithmic derivative of the Gamma special function
* @param {number} x Argument value
* @return {number} Approximated value of the digamma function.
*/
public static diGamma(x: number): number {
const c: number = 12.0;
const d1: number = -0.5772156649015329;
const d2: number = 1.6449340668482264;
const s: number = 1.0E-6;
const s3: number = 1.0 / 12.0;
const s4: number = 1.0 / 120.0;
const s5: number = 1.0 / 252.0;
const s6: number = 1.0 / 240.0;
const s7: number = 1.0 / 132.0;
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (x === javaemul.internal.DoubleHelper.NEGATIVE_INFINITY)return javaemul.internal.DoubleHelper.NaN;
if (x <= 0)if (MathFunctions.isInteger(x))return javaemul.internal.DoubleHelper.NaN;
if (x < 0)return SpecialFunctions.diGamma(1.0 - x) + (MathConstants.PI / Math.tan(-Math.PI * x));
if (x <= s)return d1 - (1 / x) + (d2 * x);
let result: number = 0;
while((x < c)) {{
if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN;
result -= 1 / x;
x++;
}};
if (x >= c){
let r: number = 1 / x;
result += Math.log(x) - (0.5 * r);
r *= r;
result -= r * (s3 - (r * (s4 - (r * (s5 - (r * (s6 - (r * s7))))))));
}
return result;
}
static doubleWidth: number = 53;
static doublePrecision: number; public static doublePrecision_$LI$(): number { if (SpecialFunctions.doublePrecision == null) { SpecialFunctions.doublePrecision = Math.pow(2, -SpecialFunctions.doubleWidth); } return SpecialFunctions.doublePrecision; }
/**
* Log Beta special function
* @param {number} x Argument value
* @param {number} y Argument value
* @return {number} Return logBeta special function (for positive x and positive y)
*/
public static logBeta(x: number, y: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (/* isNaN */isNaN(y))return javaemul.internal.DoubleHelper.NaN;
if ((x <= 0) || (y <= 0))return javaemul.internal.DoubleHelper.NaN;
let lgx: number = SpecialFunctions.logGamma(x);
if (/* isNaN */isNaN(lgx))lgx = Math.log(Math.abs(SpecialFunctions.gamma(x)));
let lgy: number = SpecialFunctions.logGamma(y);
if (/* isNaN */isNaN(lgy))lgy = Math.log(Math.abs(SpecialFunctions.gamma(y)));
let lgxy: number = SpecialFunctions.logGamma(x + y);
if (/* isNaN */isNaN(lgy))lgxy = Math.log(Math.abs(SpecialFunctions.gamma(x + y)));
if ((!/* isNaN */isNaN(lgx)) && (!/* isNaN */isNaN(lgy)) && (!/* isNaN */isNaN(lgxy)))return (lgx + lgy - lgxy); else return javaemul.internal.DoubleHelper.NaN;
}
/**
* Beta special function
* @param {number} x Argument value
* @param {number} y Argument value
* @return {number} Return Beta special function (for positive x and positive y)
*/
public static beta(x: number, y: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (/* isNaN */isNaN(y))return javaemul.internal.DoubleHelper.NaN;
if ((x <= 0) || (y <= 0))return javaemul.internal.DoubleHelper.NaN;
if ((x > 99) || (y > 99))return Math.exp(SpecialFunctions.logBeta(x, y));
return SpecialFunctions.gamma(x) * SpecialFunctions.gamma(y) / SpecialFunctions.gamma(x + y);
}
/**
* Log Incomplete Beta special function
* @param {number} a Argument value
* @param {number} b Argument value
* @param {number} x Argument value
* @return {number} Return incomplete Beta special function
* for positive a and positive b and x between 0 and 1
*/
public static incompleteBeta(a: number, b: number, x: number): number {
if (/* isNaN */isNaN(a))return javaemul.internal.DoubleHelper.NaN;
if (/* isNaN */isNaN(b))return javaemul.internal.DoubleHelper.NaN;
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (x < -BinaryRelations.DEFAULT_COMPARISON_EPSILON)return javaemul.internal.DoubleHelper.NaN;
if (x > 1 + BinaryRelations.DEFAULT_COMPARISON_EPSILON)return javaemul.internal.DoubleHelper.NaN;
if ((a <= 0) || (b <= 0))return javaemul.internal.DoubleHelper.NaN;
if (MathFunctions.almostEqual(x, 0))return 0;
if (MathFunctions.almostEqual(x, 1))return SpecialFunctions.beta(a, b);
const aEq0: boolean = MathFunctions.almostEqual(a, 0);
const bEq0: boolean = MathFunctions.almostEqual(b, 0);
const aIsInt: boolean = MathFunctions.isInteger(a);
const bIsInt: boolean = MathFunctions.isInteger(b);
let aInt: number = 0;
let bInt: number = 0;
if (aIsInt)aInt = (n => n<0?Math.ceil(n):Math.floor(n))(<number>MathFunctions.integerPart(a));
if (bIsInt)bInt = (n => n<0?Math.ceil(n):Math.floor(n))(<number>MathFunctions.integerPart(b));
let n: number;
if (aEq0 && bEq0)return Math.log(x / (1 - x));
if (aEq0 && bIsInt){
n = bInt;
if (n >= 1){
if (n === 1)return Math.log(x);
if (n === 2)return Math.log(x) + x;
let v: number = Math.log(x);
for(let i: number = 1; i <= n - 1; i++) {v -= MathFunctions.binomCoeff$double$long(n - 1, i) * Math.pow(-1, i) * (Math.pow(x, i) / i);}
return v;
}
if (n <= -1){
if (n === -1)return Math.log(x / (1 - x)) + 1 / (1 - x) - 1;
if (n === -2)return Math.log(x / (1 - x)) - 1 / x - 1 / (2 * x * x);
let v: number = -Math.log(x / (1 - x));
for(let i: number = 1; i <= -n - 1; i++) {v -= Math.pow(x, -i) / i;}
return v;
}
}
if (aIsInt && bEq0){
n = aInt;
if (n >= 1){
if (n === 1)return -Math.log(1 - x);
if (n === 2)return -Math.log(1 - x) - x;
let v: number = -Math.log(1 - x);
for(let i: number = 1; i <= n - 1; i++) {v -= Math.pow(x, i) / i;}
return v;
}
if (n <= -1){
if (n === -1)return Math.log(x / (1 - x)) - 1 / x;
let v: number = -Math.log(x / (1 - x));
for(let i: number = 1; i <= -n; i++) {v += Math.pow(1 - x, -i) / i;}
for(let i: number = 1; i <= -n; i++) {v -= Math.pow(MathFunctions.factorial$double(i - 1), 2) / i;}
return v;
}
}
if (aIsInt){
n = aInt;
if (MathFunctions.almostEqual(b, 1)){
if (n <= -1)return -((n => n<0?Math.ceil(n):Math.floor(n))(1 / (-n))) * Math.pow(x, n);
}
}
return SpecialFunctions.regularizedBeta(a, b, x) * SpecialFunctions.beta(a, b);
}
/**
* Regularized incomplete Beta special function
* @param {number} a Argument value
* @param {number} b Argument value
* @param {number} x Argument value
* @return {number} Return incomplete Beta special function
* for positive a and positive b and x between 0 and 1
*/
public static regularizedBeta(a: number, b: number, x: number): number {
if (/* isNaN */isNaN(a))return javaemul.internal.DoubleHelper.NaN;
if (/* isNaN */isNaN(b))return javaemul.internal.DoubleHelper.NaN;
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if ((a <= 0) || (b <= 0))return javaemul.internal.DoubleHelper.NaN;
if (x < -BinaryRelations.DEFAULT_COMPARISON_EPSILON)return javaemul.internal.DoubleHelper.NaN;
if (x > 1 + BinaryRelations.DEFAULT_COMPARISON_EPSILON)return javaemul.internal.DoubleHelper.NaN;
if (MathFunctions.almostEqual(x, 0))return 0;
if (MathFunctions.almostEqual(x, 1))return 1;
const bt: number = (x === 0.0 || x === 1.0) ? 0.0 : Math.exp(SpecialFunctions.logGamma(a + b) - SpecialFunctions.logGamma(a) - SpecialFunctions.logGamma(b) + (a * Math.log(x)) + (b * Math.log(1.0 - x)));
const symmetryTransformation: boolean = x >= (a + 1.0) / (a + b + 2.0);
const eps: number = SpecialFunctions.doublePrecision_$LI$();
const fpmin: number = javaemul.internal.MathHelper.nextUp(0.0) / eps;
if (symmetryTransformation){
x = 1.0 - x;
const swap: number = a;
a = b;
b = swap;
}
const qab: number = a + b;
const qap: number = a + 1.0;
const qam: number = a - 1.0;
let c: number = 1.0;
let d: number = 1.0 - (qab * x / qap);
if (Math.abs(d) < fpmin){
d = fpmin;
}
d = 1.0 / d;
let h: number = d;
for(let m: number = 1, m2: number = 2; m <= 50000; m++, m2 += 2) {{
if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN;
let aa: number = m * (b - m) * x / ((qam + m2) * (a + m2));
d = 1.0 + (aa * d);
if (Math.abs(d) < fpmin){
d = fpmin;
}
c = 1.0 + (aa / c);
if (Math.abs(c) < fpmin){
c = fpmin;
}
d = 1.0 / d;
h *= d * c;
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
d = 1.0 + (aa * d);
if (Math.abs(d) < fpmin){
d = fpmin;
}
c = 1.0 + (aa / c);
if (Math.abs(c) < fpmin){
c = fpmin;
}
d = 1.0 / d;
const del: number = d * c;
h *= del;
if (Math.abs(del - 1.0) <= eps){
return symmetryTransformation ? 1.0 - (bt * h / a) : bt * h / a;
}
};}
return symmetryTransformation ? 1.0 - (bt * h / a) : bt * h / a;
}
static GSL_DBL_EPSILON: number = 2.220446049250313E-16;
/**
* Halley iteration used in Lambert-W approximation
* @param {number} x Point at which Halley iteration will be calculated
* @param {number} wInitial Starting point
* @param {number} maxIter Maximum number of iteration
* @return {number} Halley iteration value if succesfull, otherwise Double.NaN
* @private
*/
/*private*/ static halleyIteration(x: number, wInitial: number, maxIter: number): number {
let w: number = wInitial;
let tol: number = 1;
let t: number = 0;
let p: number;
let e: number;
for(let i: number = 0; i < maxIter; i++) {{
if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN;
e = Math.exp(w);
p = w + 1.0;
t = w * e - x;
if (w > 0)t = (t / p) / e; else t /= e * p - 0.5 * (p + 1.0) * t / p;
w -= t;
tol = SpecialFunctions.GSL_DBL_EPSILON * Math.max(Math.abs(w), 1.0 / (Math.abs(p) * e));
if (Math.abs(t) < tol)return w;
};}
const perc: number = Math.abs(t / tol);
if (perc >= 0.5 && perc <= 1.5)return w;
return javaemul.internal.DoubleHelper.NaN;
}
/**
* Private method used in Lambert-W approximation - near zero
* @param {number} r
* @return {number} Ner zero approximation
* @private
*/
/*private*/ static seriesEval(r: number): number {
const t8: number = Coefficients.lambertWqNearZero_$LI$()[8] + r * (Coefficients.lambertWqNearZero_$LI$()[9] + r * (Coefficients.lambertWqNearZero_$LI$()[10] + r * Coefficients.lambertWqNearZero_$LI$()[11]));
const t5: number = Coefficients.lambertWqNearZero_$LI$()[5] + r * (Coefficients.lambertWqNearZero_$LI$()[6] + r * (Coefficients.lambertWqNearZero_$LI$()[7] + r * t8));
const t1: number = Coefficients.lambertWqNearZero_$LI$()[1] + r * (Coefficients.lambertWqNearZero_$LI$()[2] + r * (Coefficients.lambertWqNearZero_$LI$()[3] + r * (Coefficients.lambertWqNearZero_$LI$()[4] + r * t5)));
return Coefficients.lambertWqNearZero_$LI$()[0] + r * t1;
}
/**
* W0 - Principal branch of Lambert-W function
* @param {number} x
* @return {number} Approximation of principal branch of Lambert-W function
* @private
*/
/*private*/ static lambertW0(x: number): number {
if (Math.abs(x) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return 0;
if (Math.abs(x + MathConstants.EXP_MINUS_1_$LI$()) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return -1;
if (Math.abs(x - 1) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return MathConstants.OMEGA;
if (Math.abs(x - MathConstants.E) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return 1;
if (Math.abs(x + MathConstants.LN_SQRT2_$LI$()) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return -2 * MathConstants.LN_SQRT2_$LI$();
if (x < -MathConstants.EXP_MINUS_1_$LI$())return javaemul.internal.DoubleHelper.NaN;
const q: number = x + MathConstants.EXP_MINUS_1_$LI$();
if (q < 0.001)return SpecialFunctions.seriesEval(Math.sqrt(q));
const MAX_ITER: number = 100;
let w: number;
if (x < 1){
const p: number = Math.sqrt(2.0 * MathConstants.E * q);
w = -1.0 + p * (1.0 + p * (-1.0 / 3.0 + p * 11.0 / 72.0));
} else {
w = Math.log(x);
if (x > 3.0)w -= Math.log(w);
}
return SpecialFunctions.halleyIteration(x, w, MAX_ITER);
}
/**
* Minus 1 branch of Lambert-W function
* Analytical approximations for real values of the Lambert W-function - D.A. Barry
* Mathematics and Computers in Simulation 53 (2000) 95–103
* @param {number} x
* @return {number} Approxmiation of minus 1 branch of Lambert-W function
* @private
*/
/*private*/ static lambertW1(x: number): number {
if (x >= -BinaryRelations.DEFAULT_COMPARISON_EPSILON)return javaemul.internal.DoubleHelper.NaN;
if (x < -MathConstants.EXP_MINUS_1_$LI$())return javaemul.internal.DoubleHelper.NaN;
if (Math.abs(x + MathConstants.EXP_MINUS_1_$LI$()) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return -1;
const M1: number = 0.3361;
const M2: number = -0.0042;
const M3: number = -0.0201;
const s: number = -1 - Math.log(-x);
return -1.0 - s - (2.0 / M1) * (1.0 - 1.0 / (1.0 + ((M1 * Math.sqrt(s / 2.0)) / (1.0 + M2 * s * Math.exp(M3 * Math.sqrt(s))))));
}
/**
* Real-valued Lambert-W function approximation.
* @param {number} x Point at which function will be approximated
* @param {number} branch Branch id, 0 for principal branch, -1 for the other branch
* @return {number} Principal branch for x greater or equal than -1/e, otherwise Double.NaN.
* Minus 1 branch for x greater or equal than -1/e and lower than 0, otherwise Double.NaN.
*/
public static lambertW(x: number, branch: number): number {
if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN;
if (/* isNaN */isNaN(branch))return javaemul.internal.DoubleHelper.NaN;
if (Math.abs(branch) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return SpecialFunctions.lambertW0(x);
if (Math.abs(branch + 1) <= BinaryRelations.DEFAULT_COMPARISON_EPSILON)return SpecialFunctions.lambertW1(x);
return javaemul.internal.DoubleHelper.NaN;
}
}
SpecialFunctions["__class"] = "org.mariuszgromada.math.mxparser.mathcollection.SpecialFunctions"; | the_stack |
import {yupResolver} from '@hookform/resolvers/yup'
import type {MutationEvent} from '@sanity/client'
import {Box, Button, Card, Flex, Stack, Tab, TabList, TabPanel, Text} from '@sanity/ui'
import {Asset, DialogAssetEdit as DialogAssetEdit, ReactSelectOption} from '@types'
import groq from 'groq'
import React, {FC, ReactNode, useEffect, useRef, useState} from 'react'
import {useForm} from 'react-hook-form'
import {useDispatch} from 'react-redux'
import {AspectRatio} from 'theme-ui'
import * as yup from 'yup'
import {client} from '../../client'
import {Z_INDEX_DIALOG} from '../../constants'
import useTypedSelector from '../../hooks/useTypedSelector'
import {assetsActions, selectAssetById} from '../../modules/assets'
import {dialogActions} from '../../modules/dialog'
import {selectTags, selectTagSelectOptions, tagsActions} from '../../modules/tags'
import getTagSelectOptions from '../../utils/getTagSelectOptions'
import imageDprUrl from '../../utils/imageDprUrl'
import sanitizeFormData from '../../utils/sanitizeFormData'
import {isFileAsset, isImageAsset} from '../../utils/typeGuards'
import AssetMetadata from '../AssetMetadata'
import Dialog from '../Dialog'
import DocumentList from '../DocumentList'
import FileAssetPreview from '../FileAssetPreview'
import FormFieldInputFilename from '../FormFieldInputFilename'
import FormFieldInputTags from '../FormFieldInputTags'
import FormFieldInputText from '../FormFieldInputText'
import FormFieldInputTextarea from '../FormFieldInputTextarea'
import FormSubmitButton from '../FormSubmitButton'
import Image from '../Image'
type Props = {
children: ReactNode
dialog: DialogAssetEdit
}
type FormData = yup.InferType<typeof formSchema>
const formSchema = yup.object().shape({
originalFilename: yup.string().required('Filename cannot be empty')
})
const getFilenameWithoutExtension = (asset?: Asset): string | undefined => {
const extensionIndex = asset?.originalFilename?.lastIndexOf(`.${asset.extension}`)
return asset?.originalFilename?.slice(0, extensionIndex)
}
const DialogAssetEdit: FC<Props> = (props: Props) => {
const {
children,
dialog: {assetId, id, lastCreatedTag, lastRemovedTagIds}
} = props
// Redux
const dispatch = useDispatch()
const assetItem = useTypedSelector(state => selectAssetById(state, String(assetId))) // TODO: check casting
const tags = useTypedSelector(selectTags)
// Refs
const isMounted = useRef(false)
// State
// - Generate a snapshot of the current asset
const [assetSnapshot, setAssetSnapshot] = useState(assetItem?.asset)
const [tabSection, setTabSection] = useState<'details' | 'references'>('details')
const currentAsset = assetItem ? assetItem?.asset : assetSnapshot
const allTagOptions = getTagSelectOptions(tags)
// Redux
const assetTagOptions = useTypedSelector(selectTagSelectOptions(currentAsset))
const generateDefaultValues = (asset?: Asset) => ({
altText: asset?.altText || '',
description: asset?.description || '',
originalFilename: asset ? getFilenameWithoutExtension(asset) : undefined,
opt: {media: {tags: assetTagOptions}},
title: asset?.title || ''
})
// Generate a string from all current tag labels
// This is used purely to determine tag updates to then update the form in real time
const currentTagLabels = assetTagOptions?.map(tag => tag.label).join(',')
// react-hook-form
const {
control,
// Read the formState before render to subscribe the form state through Proxy
formState: {errors, isDirty, isValid},
getValues,
handleSubmit,
register,
reset,
setValue
} = useForm({
defaultValues: generateDefaultValues(assetItem?.asset),
mode: 'onChange',
resolver: yupResolver(formSchema)
})
const formUpdating = !assetItem || assetItem?.updating
// Callbacks
const handleClose = () => {
dispatch(dialogActions.remove({id}))
}
const handleDelete = () => {
if (!assetItem?.asset) {
return
}
dispatch(
dialogActions.showConfirmDeleteAssets({
assets: [assetItem],
closeDialogId: assetItem?.asset._id
})
)
}
const handleAssetUpdate = (update: MutationEvent) => {
const {result, transition} = update
if (result && transition === 'update') {
// Regenerate asset snapshot
setAssetSnapshot(result as Asset)
// Reset react-hook-form
reset(generateDefaultValues(result as Asset))
}
}
const handleCreateTag = (tagName: string) => {
// Dispatch action to create new tag
dispatch(
tagsActions.createRequest({
assetId: currentAsset?._id,
name: tagName
})
)
}
// - submit react-hook-form
const onSubmit = async (formData: FormData) => {
if (!assetItem?.asset) {
return
}
const sanitizedFormData = sanitizeFormData(formData)
dispatch(
assetsActions.updateRequest({
asset: assetItem?.asset,
closeDialogId: assetItem?.asset._id,
formData: {
...sanitizedFormData,
// Map tags to sanity references
opt: {
media: {
...sanitizedFormData.opt.media,
tags:
sanitizedFormData.opt.media.tags?.map((tag: ReactSelectOption) => ({
_ref: tag.value,
_type: 'reference',
_weak: true
})) || null
}
},
// Append extension to filename
originalFilename: `${sanitizedFormData.originalFilename}.${assetItem?.asset.extension}`
}
})
)
}
// Effects
// - Listen for asset mutations and update snapshot
useEffect(() => {
if (!assetItem?.asset) {
return
}
// Remember that Sanity listeners ignore joins, order clauses and projections
const subscriptionAsset = client
.listen(groq`*[_id == $id]`, {id: assetItem?.asset._id})
.subscribe(handleAssetUpdate)
return () => {
subscriptionAsset?.unsubscribe()
}
}, [])
// - Partially reset form when current tags have changed (and after initial mount)
useEffect(() => {
if (isMounted.current) {
reset(
{
opt: {
media: {tags: assetTagOptions}
}
},
{
errors: true,
dirtyFields: true,
isDirty: true
}
)
}
// Mark as mounted
isMounted.current = true
}, [currentTagLabels])
// - Update tags form field (react-select) when a new _inline_ tag has been created
useEffect(() => {
if (lastCreatedTag) {
const existingTags = (getValues('opt.media.tags') as ReactSelectOption[]) || []
const updatedTags = existingTags.concat([lastCreatedTag])
setValue('opt.media.tags', updatedTags, {shouldDirty: true})
}
}, [lastCreatedTag])
// - Update tags form field (react-select) when an _inline_ tag has been removed elsewhere
useEffect(() => {
if (lastRemovedTagIds) {
const existingTags = (getValues('opt.media.tags') as ReactSelectOption[]) || []
const updatedTags = existingTags.filter(tag => {
return !lastRemovedTagIds.includes(tag.value)
})
setValue('opt.media.tags', updatedTags, {shouldDirty: true})
}
}, [lastRemovedTagIds])
const Footer = () => (
<Box padding={3}>
<Flex justify="space-between">
{/* Delete button */}
<Button
disabled={formUpdating}
fontSize={1}
mode="bleed"
onClick={handleDelete}
text="Delete"
tone="critical"
/>
{/* Submit button */}
<FormSubmitButton
disabled={formUpdating || !isDirty || !isValid}
isValid={isValid}
lastUpdated={currentAsset._updatedAt}
onClick={handleSubmit(onSubmit)}
/>
</Flex>
</Box>
)
if (!currentAsset) {
return null
}
return (
<Dialog
footer={<Footer />}
header="Asset details"
id={id}
onClose={handleClose}
width={3}
zOffset={Z_INDEX_DIALOG}
>
{/*
We reverse direction to ensure the download button doesn't appear (in the DOM) before other tabbable items.
This ensures that the dialog doesn't scroll down to the download button (which on smaller screens, can sometimes
be below the fold).
*/}
<Flex direction={['column-reverse', 'column-reverse', 'row-reverse']}>
<Box flex={1} marginTop={[5, 5, 0]} padding={4}>
{/* Tabs */}
<TabList space={2}>
<Tab
aria-controls="details-panel"
disabled={formUpdating}
id="details-tab"
label="Details"
onClick={() => setTabSection('details')}
selected={tabSection === 'details'}
size={2}
/>
<Tab
aria-controls="references-panel"
disabled={formUpdating}
id="references-tab"
label="References"
onClick={() => setTabSection('references')}
selected={tabSection === 'references'}
size={2}
/>
</TabList>
{/* Form fields */}
<Box as="form" marginTop={4} onSubmit={handleSubmit(onSubmit)}>
{/* Deleted notification */}
{!assetItem && (
<Card marginBottom={3} padding={3} radius={2} shadow={1} tone="critical">
<Text size={1}>This file cannot be found – it may have been deleted.</Text>
</Card>
)}
{/* Hidden button to enable enter key submissions */}
<button style={{display: 'none'}} tabIndex={-1} type="submit" />
{/* Panel: details */}
<TabPanel
aria-labelledby="details"
hidden={tabSection !== 'details'}
id="details-panel"
>
<Stack space={3}>
{/* Tags */}
<FormFieldInputTags
control={control}
disabled={formUpdating}
error={errors?.opt?.media?.tags}
label="Tags"
name="opt.media.tags"
onCreateTag={handleCreateTag}
options={allTagOptions}
placeholder="Select or create..."
value={assetTagOptions}
/>
{/* Filename */}
<FormFieldInputFilename
disabled={formUpdating}
error={errors?.originalFilename}
extension={currentAsset?.extension || ''}
label="Filename"
name="originalFilename"
ref={register}
value={getFilenameWithoutExtension(currentAsset)}
/>
{/* Title */}
<FormFieldInputText
disabled={formUpdating}
error={errors?.title}
label="Title"
name="title"
ref={register}
value={currentAsset?.title}
/>
{/* Alt text */}
<FormFieldInputText
disabled={formUpdating}
error={errors?.altText}
label="Alt Text"
name="altText"
ref={register}
value={currentAsset?.altText}
/>
{/* Description */}
<FormFieldInputTextarea
disabled={formUpdating}
error={errors?.description}
label="Description"
name="description"
ref={register}
rows={3}
value={currentAsset?.description}
/>
</Stack>
</TabPanel>
{/* Panel: References */}
<TabPanel
aria-labelledby="references"
hidden={tabSection !== 'references'}
id="references-panel"
>
<Box marginTop={5}>
{assetItem?.asset && <DocumentList assetId={assetItem?.asset._id} />}
</Box>
</TabPanel>
</Box>
</Box>
<Box flex={1} padding={4}>
<AspectRatio ratio={1}>
{/* File */}
{isFileAsset(currentAsset) && <FileAssetPreview asset={currentAsset} />}
{/* Image */}
{isImageAsset(currentAsset) && (
<Image
draggable={false}
showCheckerboard={!currentAsset?.metadata?.isOpaque}
src={imageDprUrl(currentAsset, {height: 600, width: 600})}
/>
)}
</AspectRatio>
{/* Metadata */}
{currentAsset && (
<Box marginTop={4}>
<AssetMetadata asset={currentAsset} item={assetItem} />
</Box>
)}
</Box>
</Flex>
{children}
</Dialog>
)
}
export default DialogAssetEdit | the_stack |
import { expect } from "chai";
import { BeDuration } from "@itwin/core-bentley";
import { ServerTimeoutError } from "@itwin/core-common";
import {
IModelApp, IModelTile, IModelTileContent, IModelTileTree, IpcApp, RenderGraphic, RenderMemory, SnapshotConnection, Tile, TileLoadStatus,
TileRequestChannel, Viewport,
} from "@itwin/core-frontend";
import { TestUtility } from "../../TestUtility";
import { TILE_DATA_2_0 } from "./data/TileIO.data.2.0";
import { fakeViewState } from "./TileIO.test";
describe("IModelTileRequestChannels", () => {
function getCloudStorageChannel(): TileRequestChannel {
const channels = IModelApp.tileAdmin.channels;
if (!channels.iModelChannels.cloudStorage) {
channels.enableCloudStorageCache();
expect(channels.iModelChannels.cloudStorage).not.to.be.undefined;
}
return channels.iModelChannels.cloudStorage!;
}
async function getTileForIModel(imodel: SnapshotConnection): Promise<IModelTile> {
await imodel.models.load("0x1c");
const model = imodel.models.getLoaded("0x1c")!.asGeometricModel!;
const view = fakeViewState(imodel);
const ref = model.createTileTreeReference(view);
const tree = (await ref.treeOwner.loadTree()) as IModelTileTree;
// The root tile marks itself as "ready" immediately. Make it "not loaded" instead.
tree.staticBranch.disposeContents();
return tree.staticBranch;
}
async function waitUntil(condition: () => boolean): Promise<void> {
await BeDuration.wait(1);
if (!condition())
return waitUntil(condition);
}
async function loadContent(tile: Tile): Promise<void> {
const viewport = {
viewportId: 12345,
iModel: tile.tree.iModel,
invalidateScene: () => { },
} as Viewport;
IModelApp.tileAdmin.requestTiles(viewport, new Set<Tile>([tile]));
IModelApp.tileAdmin.process();
return waitUntil(() => tile.loadStatus !== TileLoadStatus.Queued && tile.loadStatus !== TileLoadStatus.Loading);
}
describe("CloudStorageCacheChannel", () => {
let imodel: SnapshotConnection;
beforeEach(async () => {
await TestUtility.startFrontend();
imodel = await SnapshotConnection.openFile("test.bim");
});
afterEach(async () => {
await imodel.close();
await TestUtility.shutdownFrontend();
});
async function getTile() {
return getTileForIModel(imodel);
}
it("is not configured by default", async () => {
expect(IModelApp.tileAdmin.channels.iModelChannels.cloudStorage).to.be.undefined;
const tile = await getTile();
expect(tile.channel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
});
it("uses http concurrency", async () => {
const channel = getCloudStorageChannel();
expect(channel.concurrency).to.equal(IModelApp.tileAdmin.channels.httpConcurrency);
});
it("is used first if configured", async () => {
IModelApp.tileAdmin.channels.enableCloudStorageCache();
expect(IModelApp.tileAdmin.channels.iModelChannels.cloudStorage).not.to.be.undefined;
const tile = await getTile();
expect(tile.channel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.cloudStorage);
tile.channel.requestContent = async () => Promise.resolve(TILE_DATA_2_0.rectangle.bytes);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.Ready);
expect(tile.channel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.cloudStorage);
});
it("falls back to RPC if content is not found", async () => {
IModelApp.tileAdmin.channels.enableCloudStorageCache();
const tile = await getTile();
const channel = getCloudStorageChannel();
expect(tile.channel).to.equal(channel);
channel.requestContent = async () => Promise.resolve(undefined);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.NotLoaded);
expect(tile.channel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
tile.channel.requestContent = async () => Promise.resolve(TILE_DATA_2_0.rectangle.bytes);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.Ready);
});
it("is not used again after cache miss", async () => {
IModelApp.tileAdmin.channels.enableCloudStorageCache();
const tile = await getTile();
const channel = getCloudStorageChannel();
channel.requestContent = async () => { throw new ServerTimeoutError("..."); };
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.NotLoaded);
expect(tile.channel).to.equal(channel);
expect(tile.requestChannel).to.be.undefined;
channel.requestContent = async () => Promise.resolve(undefined);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.NotLoaded);
expect(tile.channel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
expect(tile.requestChannel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
tile.channel.requestContent = async () => Promise.resolve(TILE_DATA_2_0.rectangle.bytes);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.Ready);
tile.disposeContents();
expect(tile.loadStatus).to.equal(TileLoadStatus.NotLoaded);
expect(tile.requestChannel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
expect(tile.channel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
});
});
describe("Metadata cache channel", () => {
let imodel: SnapshotConnection;
beforeEach(async () => {
await TestUtility.startFrontend({ tileAdmin: { cacheTileMetadata: true } });
imodel = await SnapshotConnection.openFile("test.bim");
});
afterEach(async () => {
await imodel.close();
await TestUtility.shutdownFrontend();
});
async function getTile() {
return getTileForIModel(imodel);
}
function getChannel(): TileRequestChannel {
let channel: TileRequestChannel | undefined;
for (const ch of IModelApp.tileAdmin.channels) {
if (ch.name === "itwinjs-imodel-metadata-cache") {
channel = ch;
break;
}
}
expect(channel).not.to.be.undefined;
return channel!;
}
it("is configured if specified at startup", () => {
expect(getChannel()).not.to.be.undefined;
});
it("is highly concurrent", () => {
expect(getChannel().concurrency).to.equal(100);
});
it("is used first", async () => {
const tile = await getTile();
expect(tile.channel).to.equal(getChannel());
expect(tile.requestChannel).to.be.undefined;
tile.channel.requestContent = async () => Promise.resolve(TILE_DATA_2_0.rectangle.bytes);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.Ready);
expect(tile.channel).to.equal(getChannel());
expect(tile.requestChannel).to.be.undefined;
});
it("falls back to RPC if content is not found and cloud storage is not configured", async () => {
expect(IModelApp.tileAdmin.channels.iModelChannels.cloudStorage).to.be.undefined;
const tile = await getTile();
const channel = getChannel();
expect(tile.channel).to.equal(channel);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.NotLoaded);
expect(tile.channel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
tile.channel.requestContent = async () => Promise.resolve(TILE_DATA_2_0.rectangle.bytes);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.Ready);
});
it("falls back to cloud storage, then to RPC, if content is not found and cloud storage is configured", async () => {
IModelApp.tileAdmin.channels.enableCloudStorageCache();
const cloud = IModelApp.tileAdmin.channels.iModelChannels.cloudStorage!;
expect(cloud).not.to.be.undefined;
const tile = await getTile();
const channel = getChannel();
expect(tile.channel).to.equal(channel);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.NotLoaded);
expect(tile.channel).to.equal(cloud);
cloud.requestContent = async () => Promise.resolve(undefined);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.NotLoaded);
expect(tile.channel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
});
function expectEqualContent(a: IModelTileContent, b: IModelTileContent): void {
expect(a).not.to.be.undefined;
expect(a.sizeMultiplier).to.equal(b.sizeMultiplier);
expect(a.emptySubRangeMask).to.equal(b.emptySubRangeMask);
expect(a.isLeaf).to.equal(b.isLeaf);
if (undefined === a.contentRange)
expect(b.contentRange).to.be.undefined;
else
expect(a.contentRange.isAlmostEqual(b.contentRange!)).to.be.true;
expect(a.graphic).not.to.be.undefined;
expect(b.graphic).not.to.be.undefined;
}
function graphicSize(graphic: RenderGraphic): number {
const stats = new RenderMemory.Statistics();
graphic.collectStatistics(stats);
return stats.totalBytes;
}
it("caches metadata from RPC", async () => {
const tile = await getTile();
const channels = IModelApp.tileAdmin.channels.iModelChannels;
expect(channels.getCachedContent(tile)).to.be.undefined;
const channel = getChannel();
await loadContent(tile);
expect(tile.channel).to.equal(channels.rpc);
expect(channels.getCachedContent(tile)).to.be.undefined;
tile.channel.requestContent = async () => Promise.resolve(TILE_DATA_2_0.rectangle.bytes);
await loadContent(tile);
const content = channels.getCachedContent(tile)!;
expect(content).not.to.be.undefined;
const tileContent: IModelTileContent = {
graphic: tile.produceGraphics(),
emptySubRangeMask: tile.emptySubRangeMask,
contentRange: tile.contentRange,
sizeMultiplier: tile.sizeMultiplier,
isLeaf: tile.isLeaf,
};
if (!content.contentRange)
content.contentRange = tile.contentRange;
expectEqualContent(content, tileContent);
expect(graphicSize(content.graphic!)).to.equal(0);
expect(graphicSize(tile.produceGraphics()!)).least(1);
tile.disposeContents();
tile.requestChannel = undefined;
expect(tile.loadStatus).to.equal(TileLoadStatus.NotLoaded);
expect(tile.channel).to.equal(channel);
const newContent = await channel.requestContent(tile, () => false) as { content: IModelTileContent };
expect(newContent).not.to.be.undefined;
expect(newContent.content).not.to.be.undefined;
expectEqualContent(newContent.content, content);
expect(graphicSize(newContent.content.graphic!)).to.equal(0);
});
it("is not used again after cache miss", async () => {
const tile = await getTile();
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.NotLoaded);
expect(tile.channel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
tile.channel.requestContent = async () => Promise.resolve(TILE_DATA_2_0.rectangle.bytes);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.Ready);
tile.disposeContents();
expect(IModelApp.tileAdmin.channels.iModelChannels.cloudStorage).to.be.undefined;
expect(tile.loadStatus).to.equal(TileLoadStatus.NotLoaded);
expect(tile.requestChannel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
expect(tile.channel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
});
it("marks tile as failed if not content is produced", async () => {
const tile = await getTile();
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.NotLoaded);
expect(tile.channel).to.equal(IModelApp.tileAdmin.channels.iModelChannels.rpc);
tile.channel.requestContent = async () => Promise.resolve(undefined);
await loadContent(tile);
expect(tile.loadStatus).to.equal(TileLoadStatus.NotFound);
});
});
});
describe("RPC channels", () => {
before(async () => { await TestUtility.startFrontend(); });
after(async () => { await TestUtility.shutdownFrontend(); });
it("use http or rpc concurrency based on type of app", async () => {
const channels = IModelApp.tileAdmin.channels;
if (IpcApp.isValid)
expect(channels.rpcConcurrency).to.equal(await IpcApp.callIpcHost("queryConcurrency", "cpu"));
else
expect(channels.rpcConcurrency).to.equal(channels.httpConcurrency);
for (const channel of [channels.iModelChannels.rpc, channels.elementGraphicsRpc])
expect(channel.concurrency).to.equal(IpcApp.isValid ? channels.rpcConcurrency : channels.httpConcurrency);
});
}); | the_stack |
namespace PE.Battle.Moves {
/**
* in-battle secondary effect of a damaging move.
* @param attacker
* @param opponent
* @param move
*/
export function AdditionalEffect(attacker: Battler, opponent: Battler, move: Move) {
let sereneGrace = attacker.hasAbility(ABILITYDEX.SERENEGRACE) ? 1 : 2;
switch (move.id) {
case MOVEDEX.ACID:
case MOVEDEX.BUGBUZZ:
case MOVEDEX.EARTHPOWER:
case MOVEDEX.ENERGYBALL:
case MOVEDEX.FLASHCANNON:
case MOVEDEX.FOCUSBLAST:
case MOVEDEX.PSYCHIC:
if (Utils.chance(10 * sereneGrace) && opponent.canReduceStatStage(Stats.SpDef))
opponent.reduceStat(Stats.SpDef, 1, attacker, true);
break;
case MOVEDEX.ACIDSPRAY:
if (opponent.canReduceStatStage(Stats.SpDef))
opponent.reduceStat(Stats.SpDef, 2, attacker, false);
break;
case MOVEDEX.AIRSLASH:
case MOVEDEX.ASTONISH:
case MOVEDEX.BITE:
case MOVEDEX.HEADBUTT:
case MOVEDEX.HEARTSTAMP:
case MOVEDEX.ICICLECRASH:
case MOVEDEX.IRONHEAD:
case MOVEDEX.NEEDLEARM:
case MOVEDEX.ROCKSLIDE:
case MOVEDEX.ROLLINGKICK:
case MOVEDEX.SKYATTACK:
case MOVEDEX.SNORE:
case MOVEDEX.STEAMROLLER:
case MOVEDEX.STOMP:
case MOVEDEX.ZINGZAP:
// if (Utils.chance(30 * sereneGrace)) opponent.flinch();
break;
case MOVEDEX.ANCHORSHOT:
case MOVEDEX.SPIRITSHACKLE:
// if (Utils.chance(100)) opponent.traps(); //Traps the target.
break;
case MOVEDEX.ANCIENTPOWER:
case MOVEDEX.OMINOUSWIND:
case MOVEDEX.SILVERWIND:
if (Utils.chance(10 * sereneGrace)) {
if (attacker.canIncreaseStatStage(Stats.Attack)) attacker.increaseStat(Stats.Attack, 1, undefined, false);
if (attacker.canIncreaseStatStage(Stats.Defense)) attacker.increaseStat(Stats.Defense, 1, undefined, false);
if (attacker.canIncreaseStatStage(Stats.SpAtk)) attacker.increaseStat(Stats.SpAtk, 1, undefined, false);
if (attacker.canIncreaseStatStage(Stats.SpDef)) attacker.increaseStat(Stats.SpDef, 1, undefined, false);
if (attacker.canIncreaseStatStage(Stats.Speed)) attacker.increaseStat(Stats.Speed, 1, undefined, false);
}
break;
case MOVEDEX.AURORABEAM:
if (opponent.canReduceStatStage(Stats.Attack))
opponent.reduceStat(Stats.Attack, 1, attacker, true);
break;
case MOVEDEX.BLAZEKICK:
case MOVEDEX.EMBER:
case MOVEDEX.FIREBLAST:
case MOVEDEX.FIREPUNCH:
case MOVEDEX.HEATWAVE:
if (Utils.chance(10 * sereneGrace) && opponent.canBurn(attacker, false)) opponent.burn();
break;
case MOVEDEX.BLIZZARD:
case MOVEDEX.FREEZEDRY:
case MOVEDEX.ICEBEAM:
case MOVEDEX.ICEPUNCH:
case MOVEDEX.POWDERSNOW:
// if (Utils.chance(10 * sereneGrace) && opponent.canFreeze(attacker, false))
// opponent.freeze();
break;
case MOVEDEX.BLUEFLARE:
if (Utils.chance(20 * sereneGrace) && opponent.canBurn(attacker, false)) opponent.burn();
break;
case MOVEDEX.BODYSLAM:
case MOVEDEX.BOUNCE:
case MOVEDEX.DISCHARGE:
case MOVEDEX.DRAGONBREATH:
case MOVEDEX.FORCEPALM:
case MOVEDEX.FREEZESHOCK:
case MOVEDEX.LICK:
case MOVEDEX.SPARK:
case MOVEDEX.THUNDER:
if (Utils.chance(30 * sereneGrace) && opponent.canParalize(attacker, false)) opponent.paralize();
break;
case MOVEDEX.BOLTSTRIKE:
if (Utils.chance(20 * sereneGrace) && opponent.canParalize(attacker, false)) opponent.paralize();
break;
case MOVEDEX.BONECLUB:
case MOVEDEX.EXTRASENSORY:
case MOVEDEX.HYPERFANG:
// if (Utils.chance(10 * sereneGrace)) opponent.flinch();
break;
case MOVEDEX.BUBBLE:
case MOVEDEX.BUBBLEBEAM:
case MOVEDEX.CONSTRICT:
if (Utils.chance(10 * sereneGrace) && opponent.canReduceStatStage(Stats.Speed))
opponent.reduceStat(Stats.Speed, 1, attacker, true);
break;
case MOVEDEX.BULLDOZE:
case MOVEDEX.ELECTROWEB:
case MOVEDEX.GLACIATE:
case MOVEDEX.ICYWIND:
case MOVEDEX.LOWSWEEP:
case MOVEDEX.MUDSHOT:
case MOVEDEX.ROCKTOMB:
if (opponent.canReduceStatStage(Stats.Speed)) opponent.reduceStat(Stats.Speed, 1, attacker, true);
break;
case MOVEDEX.CHARGEBEAM:
if (Utils.chance(70 * sereneGrace) && attacker.canIncreaseStatStage(Stats.SpAtk))
attacker.increaseStat(Stats.SpAtk, 1, undefined, false);
break;
case MOVEDEX.CHATTER:
case MOVEDEX.DYNAMICPUNCH:
// if (opponent.canConfuse())
// opponent.confuse()
break;
case MOVEDEX.CLANGOROUSSOULBLAZE:
case MOVEDEX.POWERUPPUNCH:
if (attacker.canIncreaseStatStage(Stats.Attack)) attacker.increaseStat(Stats.Attack, 1, undefined, false);
if (attacker.canIncreaseStatStage(Stats.Defense)) attacker.increaseStat(Stats.Defense, 1, undefined, false);
if (attacker.canIncreaseStatStage(Stats.SpAtk)) attacker.increaseStat(Stats.SpAtk, 1, undefined, false);
if (attacker.canIncreaseStatStage(Stats.SpDef)) attacker.increaseStat(Stats.SpDef, 1, undefined, false);
if (attacker.canIncreaseStatStage(Stats.Speed)) attacker.increaseStat(Stats.Speed, 1, undefined, false);
break;
case MOVEDEX.CONFUSION:
case MOVEDEX.PSYBEAM:
case MOVEDEX.SIGNALBEAM:
// if (Utils.chance(10*sereneGraace) && opponent.canConfuse())
// opponent.confuse()
break;
case MOVEDEX.CROSSPOISON:
case MOVEDEX.POISONTAIL:
case MOVEDEX.SLUDGEWAVE:
if (Utils.chance(10 * sereneGrace) && opponent.canPoison(attacker, false)) opponent.poison();
break;
case MOVEDEX.CRUNCH:
case MOVEDEX.LIQUIDATION:
case MOVEDEX.SHADOWBONE:
if (Utils.chance(20 * sereneGrace) && opponent.canReduceStatStage(Stats.Defense))
opponent.reduceStat(Stats.Defense, 1, attacker, true);
break;
case MOVEDEX.CRUSHCLAW:
case MOVEDEX.RAZORSHELL:
case MOVEDEX.ROCKSMASH:
if (Utils.chance(50 * sereneGrace) && opponent.canReduceStatStage(Stats.Defense))
opponent.reduceStat(Stats.Defense, 1, attacker, true);
break;
case MOVEDEX.DARKPULSE:
case MOVEDEX.DRAGONRUSH:
case MOVEDEX.TWISTER:
case MOVEDEX.WATERPULSE:
case MOVEDEX.ZENHEADBUTT:
// if (Utils.chance(20 * sereneGrace)) opponent.flinch();
break;
case MOVEDEX.DIAMONDSTORM:
if (Utils.chance(50 * sereneGrace) && attacker.canIncreaseStatStage(Stats.Defense))
attacker.increaseStat(Stats.Defense, 1, undefined, false);
break;
case MOVEDEX.DIZZYPUNCH:
// if (Utils.chance(20*sereneGraace) && opponent.canConfuse())
// opponent.confuse()
break;
case MOVEDEX.FAKEOUT:
// opponent.flinch();
break;
case MOVEDEX.FIERYDANCE:
if (Utils.chance(50 * sereneGrace) && attacker.canIncreaseStatStage(Stats.SpAtk))
attacker.increaseStat(Stats.SpAtk, 1, undefined, false);
break;
case MOVEDEX.FIREFANG:
if (Utils.chance(10 * sereneGrace) && opponent.canBurn(attacker, false)) opponent.burn();
// else if (Utils.chance(10 * sereneGrace) && opponent.canParalize(attacker, false)) opponent.paralize();
break;
case MOVEDEX.FIRELASH:
if (attacker.canReduceStatStage(Stats.Defense)) attacker.reduceStat(Stats.Defense, 1, undefined, false);
break;
case MOVEDEX.GUNKSHOT:
case MOVEDEX.POISONJAB:
case MOVEDEX.POISONSTING:
case MOVEDEX.SLUDGE:
case MOVEDEX.SLUDGEBOMB:
if (Utils.chance(30 * sereneGrace) && opponent.canPoison(attacker, false)) opponent.poison();
break;
case MOVEDEX.HURRICANE:
// if (Utils.chance(30*sereneGraace) && opponent.canConfuse())
// opponent.confuse()
break;
case MOVEDEX.ICEBURN:
case MOVEDEX.LAVAPLUME:
case MOVEDEX.SCALD:
case MOVEDEX.SEARINGSHOT:
case MOVEDEX.STEAMERUPTION:
if (Utils.chance(30 * sereneGrace) && opponent.canBurn(attacker, false)) opponent.burn();
break;
case MOVEDEX.ICEFANG:
// if (Utils.chance(10 * sereneGrace) && opponent.canBurn(attacker, false)) opponent.burn();
// else if (Utils.chance(10 * sereneGrace) && opponent.canParalize(attacker, false)) opponent.paralize();
break;
case MOVEDEX.INFERNO:
if (opponent.canBurn(attacker, false)) opponent.burn();
break;
case MOVEDEX.IRONTAIL:
if (Utils.chance(10 * sereneGrace) && opponent.canReduceStatStage(Stats.Defense))
opponent.reduceStat(Stats.Defense, 1, attacker, true);
break;
case MOVEDEX.LEAFTORNADO:
case MOVEDEX.MIRRORSHOT:
case MOVEDEX.MUDBOMB:
case MOVEDEX.MUDDYWATER:
if (Utils.chance(30 * sereneGrace) && opponent.canReduceStatStage(Stats.Accuracy))
opponent.reduceStat(Stats.Accuracy, 1, attacker, true);
break;
case MOVEDEX.LUNGE:
case MOVEDEX.TROPKICK:
if (opponent.canReduceStatStage(Stats.Attack)) opponent.reduceStat(Stats.Attack, 1, attacker, true);
break;
case MOVEDEX.LUSTERPURGE:
if (Utils.chance(50 * sereneGrace) && opponent.canReduceStatStage(Stats.SpDef))
opponent.reduceStat(Stats.SpDef, 1, attacker, true);
break;
case MOVEDEX.METALCLAW:
case MOVEDEX.PLAYROUGH:
if (Utils.chance(10 * sereneGrace) && attacker.canReduceStatStage(Stats.Attack))
attacker.reduceStat(Stats.SpDef, 1, undefined, false);
break;
case MOVEDEX.METEORMASH:
if (Utils.chance(20 * sereneGrace) && attacker.canReduceStatStage(Stats.Attack))
attacker.reduceStat(Stats.SpDef, 1, undefined, false);
break;
case MOVEDEX.MISTBALL:
if (Utils.chance(50 * sereneGrace) && opponent.canReduceStatStage(Stats.SpAtk))
opponent.reduceStat(Stats.SpAtk, 1, attacker, true);
break;
case MOVEDEX.MOONBLAST:
if (Utils.chance(30 * sereneGrace) && opponent.canReduceStatStage(Stats.SpAtk))
opponent.reduceStat(Stats.SpAtk, 1, attacker, true);
break;
case MOVEDEX.MUDSLAP:
if (opponent.canReduceStatStage(Stats.Accuracy)) opponent.reduceStat(Stats.Accuracy, 1, attacker, true);
break;
case MOVEDEX.MYSTICALFIRE:
if (opponent.canReduceStatStage(Stats.SpAtk)) opponent.reduceStat(Stats.SpAtk, 1, attacker, true);
break;
case MOVEDEX.NIGHTDAZE:
if (Utils.chance(40 * sereneGrace) && opponent.canReduceStatStage(Stats.Accuracy))
opponent.reduceStat(Stats.Accuracy, 1, attacker, true);
break;
case MOVEDEX.NUZZLE:
case MOVEDEX.STOKEDSPARKSURFER:
case MOVEDEX.ZAPCANNON:
if (opponent.canParalize(attacker, false)) opponent.paralize();
break;
case MOVEDEX.OCTAZOOKA:
if (Utils.chance(50 * sereneGrace) && opponent.canReduceStatStage(Stats.Accuracy))
opponent.reduceStat(Stats.Accuracy, 1, attacker, true);
break;
case MOVEDEX.POISONFANG:
// if (Utils.chance(50 * sereneGrace) && opponent.canPoison(attacker, false)) opponent.toxic();
break;
case MOVEDEX.RELICSONG:
if (Utils.chance(10 * sereneGrace) && opponent.canSleep(attacker, false)) opponent.sleep();
break;
case MOVEDEX.ROCKCLIMB:
case MOVEDEX.WATERPULSE:
// if (Utils.chance(20*sereneGraace) && opponent.canConfuse())
// opponent.confuse()
break;
case MOVEDEX.SACREDFIRE:
if (Utils.chance(50 * sereneGrace) && opponent.canBurn(attacker, false)) opponent.burn();
break;
case MOVEDEX.SECRETPOWER:
if (Utils.chance(30 * sereneGrace)) {
if ($Battle.enviroment == Enviroments.Plain && opponent.canParalize()) opponent.paralize();
else if ($Battle.enviroment == Enviroments.Building && opponent.canParalize()) opponent.paralize();
else if ($Battle.enviroment == Enviroments.Sand && opponent.canReduceStatStage(Stats.Accuracy))
opponent.reduceStat(Stats.Accuracy, 1, attacker, true);
// else if ($Battle.enviroment == Enviroments.cave && opponent.canFlinch()) opponent.flinch();
// else if ($Battle.enviroment == Enviroments.rock && opponent.canConfuse()) opponent.confuse();
else if ($Battle.enviroment == Enviroments.TallGrass && opponent.canPoison(attacker, false)) opponent.poison();
else if ($Battle.enviroment == Enviroments.LongGrass && opponent.canSleep(attacker, false)) opponent.sleep();
else if ($Battle.enviroment == Enviroments.PondWater && opponent.canReduceStatStage(Stats.Speed))
opponent.reduceStat(Stats.Speed, 1, attacker, true);
else if ($Battle.enviroment == Enviroments.SeaWater && opponent.canReduceStatStage(Stats.Attack))
opponent.reduceStat(Stats.Attack, 1, attacker, true);
else if ($Battle.enviroment == Enviroments.UnderWater && opponent.canReduceStatStage(Stats.Defense))
opponent.reduceStat(Stats.Defense, 1, attacker, true);
}
break;
case MOVEDEX.SEEDFLARE:
if (Utils.chance(40 * sereneGrace) && opponent.canReduceStatStage(Stats.SpDef))
opponent.reduceStat(Stats.SpDef, 2, attacker, true);
break;
case MOVEDEX.SHADOWBALL:
if (Utils.chance(20 * sereneGrace) && opponent.canReduceStatStage(Stats.SpDef))
opponent.reduceStat(Stats.SpDef, 1, attacker, true);
break;
case MOVEDEX.SMOG:
if (Utils.chance(40 * sereneGrace) && opponent.canPoison(attacker, false)) opponent.poison();
break;
case MOVEDEX.SNARL:
case MOVEDEX.STRUGGLEBUG:
if (opponent.canReduceStatStage(Stats.SpAtk))
opponent.reduceStat(Stats.SpAtk, 1, attacker, true);
case MOVEDEX.STEELWING:
if (Utils.chance(10 * sereneGrace) && attacker.canIncreaseStatStage(Stats.Defense))
attacker.increaseStat(Stats.Defense, 1, undefined, false);
break;
case MOVEDEX.THUNDERFANG:
if (Utils.chance(10 * sereneGrace) && opponent.canParalize(attacker, false)) opponent.paralize();
// else if (Utils.chance(10 * sereneGrace) && opponent.canFiflnch(attacker, false)) opponent.burn();
break;
case MOVEDEX.THUNDERPUNCH:
case MOVEDEX.THUNDERSHOCK:
case MOVEDEX.THUNDERBOLT:
case MOVEDEX.VOLTTACKLE:
if (Utils.chance(10 * sereneGrace) && opponent.canParalize(attacker, false)) opponent.paralize();
case MOVEDEX.TRIATTACK:
if (Utils.chance(6.67 * sereneGrace) && opponent.canParalize(attacker, false)) opponent.paralize();
else if (Utils.chance(6.67 * sereneGrace) && opponent.canBurn(attacker, false)) opponent.burn();
// else if (Utils.chance(6.67 * sereneGrace) && opponent.canFreeze(attacker, false)) opponent.freeze();
break;
case MOVEDEX.TWINEEDLE:
if (Utils.chance(40 * sereneGrace) && opponent.canPoison(attacker, false)) opponent.poison();
break;
}
}
} | the_stack |
//============== NgZorro上传组件包装器===================
//Copyright 2019 何镇汐
//Licensed under the MIT license
//=======================================================
import { Component, Input, ViewChild, forwardRef, Optional, Output, EventEmitter, AfterViewInit } from '@angular/core';
import { NgModel, NgForm } from '@angular/forms';
import { Subscription } from 'rxjs';
import { NzUploadComponent, UploadFile, UploadFilter, UploadXHRArgs } from 'ng-zorro-antd';
import { MessageConfig as config } from '../config/message-config';
import { UploadService } from "../services/upload.service";
import { Util as util } from '../util';
/**
* NgZorro上传组件包装器
*/
@Component( {
selector: 'x-upload',
template: `
<nz-upload [nzName]="name" [(nzFileList)]="files" [nzListType]="listType"
[nzAction]="url" [nzData]="data" [nzHeaders]="headers"
[nzDisabled]="disabled" [nzShowButton]="isShowButton()" [nzAccept]="accept"
[nzFilter]="customFilters?customFilters:filters" [nzWithCredentials]="withCredentials"
[nzLimit]="limit" [nzSize]="size" [nzShowUploadList]="showUploadList"
[nzMultiple]="multiple" [nzDirectory]="directory"
[nzPreview]="getPreviewHandler()" [nzBeforeUpload]="beforeUpload"
[nzCustomRequest]="customRequest" [nzRemove]="remove"
(nzChange)="handleChange($event)" >
<button nz-button *ngIf="listType !== 'picture-card'" [disabled]="disabled">
<i nz-icon nzType="{{buttonIcon?buttonIcon:'upload'}}"></i>
<span>{{buttonText}}</span>
</button>
<ng-container *ngIf="listType === 'picture-card'">
<i nz-icon class="upload-icon" [nzType]="loading ? 'loading' : buttonIcon?buttonIcon:'plus'"></i>
<div class="upload-text">{{buttonText}}</div>
</ng-container>
</nz-upload>
<nz-modal [nzVisible]="previewVisible" [nzContent]="modalContent" [nzFooter]="null" (nzOnCancel)="previewVisible = false">
<ng-template #modalContent>
<img [src]="previewImage" [ngStyle]="{ width: '100%' }" />
</ng-template>
</nz-modal>
<nz-form-control [nzValidateStatus]="isValid()?'success':'error'">
<input nz-input style="display: none" [name]="validationId" #validationModel="ngModel" [(ngModel)]="validation" [required]="required" />
<nz-form-explain *ngIf="!isValid()">{{requiredMessage}}</nz-form-explain>
</nz-form-control>
`,
styles: [`
.upload-icon {
font-size: 32px;
color: #999;
}
.upload-text {
margin-top: 8px;
color: #666;
}
`]
} )
export class Upload implements AfterViewInit {
/**
* 加载状态
*/
loading;
/**
* 延迟
*/
timeout;
/**
* 已修改状态
*/
dirty;
/**
* 验证标识
*/
validationId;
/**
* 验证值
*/
validation;
/**
* 预览图片地址
*/
previewImage: string;
/**
* 预览图片可见状态
*/
previewVisible: boolean;
/**
* 上传文件列表
*/
files: UploadFile[];
/**
* 附件列表
*/
private items: any[];
/**
* 组件不添加到FormGroup,独立存在,这样也无法基于NgForm进行表单验证
*/
@Input() standalone: boolean;
/**
* 发到后台的文件参数名
*/
@Input() name: string;
/**
* 上传列表的内建样式,可选值:text, picture 和 picture-card
*/
@Input() listType: string;
/**
* 自定义过滤器
*/
@Input() customFilters: UploadFilter[];
/**
* 禁用
*/
@Input() disabled: boolean;
/**
* 限制文件大小
*/
@Input() size: number;
/**
* 单次最多上传数量
*/
@Input() limit: number;
/**
* 上传文件总数量限制
*/
@Input() totalLimit: number;
/**
* 接受上传的文件类型
*/
@Input() accept: string;
/**
* 是否显示按钮
*/
@Input() showButton: boolean;
/**
* 是否显示上传列表
*/
@Input() showUploadList: boolean | { showPreviewIcon?: boolean, showRemoveIcon?: boolean };
/**
* 是否允许多选
*/
@Input() multiple: boolean;
/**
* 允许上传文件夹
*/
@Input() directory: boolean;
/**
* 上传地址
*/
@Input() url: string;
/**
* 上传所需参数或返回上传参数的方法
*/
@Input() data;
/**
* 上传的请求头部
*/
@Input() headers;
/**
* 上传是否携带cookie
*/
@Input() withCredentials;
/**
* 按钮文本
*/
@Input() buttonText: string;
/**
* 按钮图标
*/
@Input() buttonIcon: string;
/**
* 必填项
*/
@Input() required: boolean;
/**
* 必填项验证消息
*/
@Input() requiredMessage: string;
/**
* 预览操作
*/
@Input() preview: ( file: UploadFile ) => void;
/**
* 移除文件操作
*/
@Input() remove: ( file: UploadFile ) => void;
/**
* 上传前操作
*/
@Input() beforeUpload: ( file: UploadFile, fileList: UploadFile[] ) => boolean;
/**
* 自定义上传操作
*/
@Input() customRequest: ( item: UploadXHRArgs ) => Subscription;
/**
* 模型
*/
@Input()
get model(): any[] {
return this.items;
}
set model( value ) {
if ( !value )
return;
this.items = value;
if ( !this.uploadService )
return;
if ( this.timeout )
clearTimeout( this.timeout );
this.timeout = setTimeout( () => {
this.files = this.items.map( item => this.uploadService.toFile( item ) );
this.loadValidate();
}, 500 );
}
/**
* 模型变更事件
*/
@Output() modelChange = new EventEmitter<any>();
/**
* 验证模型变更事件
*/
@Output() validateModelChange = new EventEmitter<any>();
/**
* 上传组件实例
*/
@ViewChild( forwardRef( () => NzUploadComponent ), { "static": false }) instance: NzUploadComponent;
/**
* 文本框组件模型,用于验证
*/
@ViewChild( forwardRef( () => NgModel ), { "static": false } ) controlModel: NgModel;
/**
* 初始化上传组件包装器
* @param uploadService 上传服务
* @param form 表单组件
*/
constructor( @Optional() public uploadService: UploadService, @Optional() public form: NgForm ) {
this.validationId = util.helper.uuid();
this.listType = "text";
this.buttonText = config.upload;
this.requiredMessage = config.uploadRequiredMessage;
this.showButton = true;
this.showUploadList = true;
}
/**
* 初始化
*/
ngAfterViewInit() {
this.addControl();
}
/**
* 将控件添加到FormGroup
*/
private addControl() {
if ( this.standalone )
return;
this.form && this.form.addControl( this.controlModel );
}
/**
* 组件销毁
*/
ngOnDestroy() {
this.removeControl();
}
/**
* 将控件移除FormGroup
*/
private removeControl() {
if ( this.standalone )
return;
this.form && this.form.removeControl( this.controlModel );
}
/**
* 获取预览处理器
*/
getPreviewHandler() {
if ( this.listType === 'text' )
return undefined;
if ( this.preview )
return this.preview;
return this.handlePreview;
}
/**
* 是否验证有效
*/
isValid() {
if ( !this.required )
return true;
if ( !this.dirty )
return true;
return this.validation;
}
/**
* 是否显示按钮
*/
isShowButton() {
if ( this.showButton === false )
return false;
if ( !this.totalLimit )
return this.showButton;
if ( !this.files )
return true;
return this.files.length < this.totalLimit;
}
/**
* 上传变更处理
* @param data 上传参数
*/
handleChange( data: { file, fileList, event, type } ) {
if ( !data || !data.file || !this.uploadService )
return;
switch ( data.file.status ) {
case 'uploading':
this.loading = true;
break;
case 'done':
this.loading = false;
if ( !data.file.response )
return;
let item = this.uploadService.resolve( data.file.response );
if ( !item )
return;
if ( data.type === 'success' ) {
this.model = [...( this.model || [] ), item];
this.modelChange.emit( this.model );
this.loadValidate();
}
break;
case 'removed':
this.loading = false;
this.uploadService.removeFromModel( this.model, data.file );
this.uploadService.removeFromFileList( this.files, data.file );
this.modelChange.emit( this.model );
this.loadValidate();
break;
case 'error':
this.loading = false;
break;
}
}
/**
* 加载验证值
*/
loadValidate() {
this.dirty = true;
if ( this.files && this.files.length > 0 ) {
this.validation = "1";
return;
}
this.validation = undefined;
}
/**
* 上传过滤器
*/
filters: UploadFilter[] = [
{
name: 'type',
fn: ( files: UploadFile[] ) => {
if ( !this.instance || !this.instance.nzAccept )
return files;
const accepts = ( <string>this.instance.nzAccept ).split( ',' );
let validFiles = files.filter( file => !file.name || ~accepts.indexOf( util.helper.getExtension( file.name ) ) );
let invalidFiles = util.helper.except( files, validFiles );
if ( invalidFiles && invalidFiles.length > 0 )
util.message.warn( this.getMessageByType( invalidFiles ) );
return validFiles;
}
},
{
name: 'size',
fn: ( files: UploadFile[] ) => {
if ( !this.instance || this.instance.nzSize === 0 )
return files;
let validFiles = files.filter( file => file.size / 1024 <= this.instance.nzSize );
let invalidFiles = util.helper.except( files, validFiles );
if ( invalidFiles && invalidFiles.length > 0 )
util.message.warn( this.getMessageBySize( invalidFiles ) );
return validFiles;
}
},
{
name: 'limit',
fn: ( files: UploadFile[] ) => {
if ( !this.instance || !this.instance.nzMultiple || this.instance.nzLimit === 0 )
return files;
let validFiles = files.slice( -this.instance.nzLimit );
let invalidFiles = util.helper.except( files, validFiles );
if ( invalidFiles && invalidFiles.length > 0 )
util.message.warn( this.getMessageByLimit( invalidFiles ) );
return validFiles;
}
}
];
/**
* 获取文件类型错误消息
*/
private getMessageByType( files: UploadFile[] ) {
return `${files.map( t => this.replace( config.fileTypeFilter, t.name ) + '<br/>' ).join( '' )}`;
}
/**
* 获取文件大小错误消息
*/
private getMessageBySize( files: UploadFile[] ) {
return `${files.map( t => this.replace( config.fileSizeFilter, t.name, this.instance.nzSize ) + '<br/>' ).join( '' )}`;
}
/**
* 获取文件数量错误消息
*/
private getMessageByLimit( files: UploadFile[] ) {
return `${files.map( t => this.replace( config.fileLimitFilter, this.instance.nzLimit ) + '<br/>' ).join( '' )}`;
}
/**
* 替换{0},{1}
*/
private replace( message, value1, value2 = null ) {
return message.replace( /\{0\}/, String( value1 ) ).replace( /\{1\}/, String( value2 ) );
}
/**
* 预览处理
*/
handlePreview = ( file: UploadFile ) => {
if ( !file )
return;
if ( !util.helper.isImage( file.url ) )
return;
this.previewImage = file.url || file.thumbUrl;
this.previewVisible = true;
};
} | the_stack |
/**
*
* @module Kiwi
* @submodule Geom
*/
module Kiwi.Geom {
/**
* Represents position, scale, rotation and rotationPoint of an Entity.
* - Values can be transformed with a 3x3 affine transformation matrix, which each transform is assigned.
* - A tranform can be assigned a parent, which may in turn have it's own parent, thereby creating a tranform inheritence heirarchy
* - A concatenated transformation matrix, representing the combined matrices of the transform and its ancestors.
*
* @class Transform
* @namespace Kiwi.Geom
* @constructor
* @param [x=0] {Number} X position of the transform.
* @param [y=0] {Number} Y position of the transform.
* @param [scaleX=1] {Number} X scaling of the transform.
* @param [scaleY=1] {Number} Y scaling of the transform.
* @param [rotation=0] {Number} Rotation of the transform in radians.
* @param [rotX=0] {Number} rotationPoint offset on X axis.
* @param [rotY=0] {Number} rotationPoint offset on Y axis.
* @return {Transform} This object.
*
*/
export class Transform {
constructor(x: number = 0, y: number = 0, scaleX: number = 1, scaleY: number = 1, rotation: number = 0, rotPointX: number = 0, rotPointY: number = 0) {
this.setTransform(x, y, scaleX, scaleY, rotation, rotPointX, rotPointY);
this._matrix = new Matrix();
this._cachedConcatenatedMatrix = new Matrix();
this._matrix.setFromOffsetTransform(this._x, this._y, this._scaleX, this._scaleY, this._rotation, this._rotPointX, this._rotPointY);
}
/**
* The type of this object.
* @method objType
* @return {String} "Transform"
* @public
*/
public objType() {
return "Transform";
}
/**
* X position of the transform
* @property _x
* @type Number
* @default 0
* @private
*/
private _x: number = 0;
/**
* Return the X value of the transform.
* @property x
* @type Number
* @public
*/
public set x(value: number) {
this._x = value;
this._dirty = true;
}
public get x():number {
return this._x;
}
/**
* Y position of the transform
* @property _y
* @type Number
* @default 0
* @private
*/
private _y: number = 0;
/**
* Return the Y value of the transform.
* @property y
* @type Number
* @public
*/
public set y(value: number) {
this._y = value;
this._dirty = true;
}
public get y(): number {
return this._y;
}
/**
* X scaleof the transform
* @property _scaleX
* @type Number
* @default 1
* @private
*/
private _scaleX: number = 1;
/**
* Return the X scale value of the transform.
* @property scaleX
* @type Number
* @public
*/
public set scaleX(value: number) {
this._scaleX = value;
this._dirty = true;
}
public get scaleX(): number {
return this._scaleX;
}
/**
* Y scale of the transform
* @property _scaleY
* @type Number
* @default 1
* @private
*/
private _scaleY: number = 1;
/**
* Return the Y scale value of the transform.
* @property scaleY
* @type Number
* @public
*/
public set scaleY(value: number) {
this._scaleY = value;
this._dirty = true;
}
public get scaleY():number {
return this._scaleY;
}
/**
* Rotation of the transform in radians.
* @property _rotation
* @type Number
* @default 0
* @private
*/
private _rotation: number = 0;
/**
* Return the rotation value of the transform in radians.
* @property rotation
* @type Number
* @public
*/
public set rotation(value: number) {
this._rotation = value;
this._dirty = true;
}
public get rotation():number {
return this._rotation;
}
/**
* Rotation offset on X axis.
* @property _rotPointX
* @type Number
* @default 0
* @private
*/
private _rotPointX: number = 0;
/**
* Return the rotation offset from the x axis.
* @property rotPointX
* @type Number
* @default 0
* @public
*/
public set rotPointX(value: number) {
this._rotPointX = value;
this._dirty = true;
}
public get rotPointX(): number {
return this._rotPointX;
}
/**
* Rotation offset on Y axis.
* @property _rotPointY
* @type Number
* @default 0
* @private
*/
private _rotPointY: number = 0;
/**
* Return the rotation offset from the y axis.
* @property rotPointY
* @type Number
* @public
*/
public set rotPointY(value: number) {
this._rotPointY = value;
this._dirty = true;
}
public get rotPointY(): number {
return this._rotPointY;
}
/**
* Return the anchor point value from the X axis. (Aliases to rotPointX.)
* @property anchorPointX
* @type Number
* @public
* @since 1.1.0
*/
public set anchorPointX(value: number) {
this.rotPointX = value;
}
public get anchorPointX(): number {
return( this.rotPointX );
}
/**
* Return the anchor point value from the Y axis. (Aliases to rotPointY.)
* @property anchorPointY
* @type Number
* @public
* @since 1.1.0
*/
public set anchorPointY(value: number) {
this.rotPointY = value;
}
public get anchorPointY(): number {
return( this.rotPointY );
}
/**
* A 3x3 transformation matrix object that can be use this tranform to manipulate points or the context transformation.
* @property _matrix
* @type Kiwi.Geom.Matrix
* @private
*/
private _matrix: Matrix;
/**
* Return the Matrix being used by this Transform
* @property matrix
* @type Kiwi.Geom.Matrix
* @readOnly
* @public
*/
public get matrix(): Matrix {
return this._matrix;
}
/**
* The most recently calculated matrix from getConcatenatedMatrix.
*
* @property _cachedConcatenatedMatrix
* @type Kiwi.Geom.Matrix
* @private
*/
private _cachedConcatenatedMatrix: Matrix;
/**
* Return the x of this transform translated to world space.
* @property worldX
* @type Number
* @readOnly
* @public
*/
public get worldX(): number {
return this.getConcatenatedMatrix().tx - this._rotPointX;
}
/**
* Return the y of this transform translated to world space.
* @property worldY
* @type Number
* @readOnly
* @public
*/
public get worldY(): number {
return this.getConcatenatedMatrix().ty - this._rotPointY;
}
/**
* The parent transform. If set to null there is no parent. Otherwise this is used by getConcatenatedMatrix to offset the current transforms by the another matrix
* @property _parent
* @type Kiwi.Geom.Transform
* @default null
* @private
*/
private _parent: Transform = null;
/**
* Return the parent Transform. If the transform does not have a parent this null is returned.
* @property parent
* @type Kiwi.Geom.Transform
* @default null
* @public
*/
public set parent(value: Transform) {
if(!this.checkAncestor(value)) {
this._parent = value;
this._dirty = true;
}
}
public get parent(): Transform {
return this._parent;
}
/**
* Private copy.
* Whether the Transform is locked. In locked mode, the Transform
* will not update its matrix, saving on computation.
* However, it will still follow its parent.
* @property _locked
* @type boolean
* @default false
* @private
* @since 1.2.0
*/
private _locked: boolean = false;
/**
* Whether the Transform is locked. In locked mode, the Transform
* will not update its matrix, saving on computation.
* However, it will still follow its parent.
* When locked is set to true, it will set the matrix according to
* current transform values.
* @property locked
* @type boolean
* @default false
* @public
* @since 1.2.0
*/
public set locked( value: boolean ) {
this._locked = value;
if ( this._locked ) {
this._matrix.setFromOffsetTransform(
this.x, this.y,
this.scaleX, this.scaleY,
this.rotation,
this.anchorPointX, this.anchorPointY );
}
}
public get locked(): boolean {
return this._locked;
}
/**
* Private copy.
* Whether to ignore its parent when concatenating matrices.
* If true, it won't compute parent matrices.
* This can save computation, but prevents it from following
* its parent's transforms.
* Use this to save some processor cycles if the transform isn't
* following a parent and the state does not transform.
* @property _ignoreParent
* @type boolean
* @default false
* @private
* @since 1.2.0
*/
private _ignoreParent: boolean = false;
/**
* Whether to ignore its parent when concatenating matrices.
* If true, it won't compute parent matrices.
* This can save computation, but prevents it from following
* its parent's transforms.
*
* Use this to save some processor cycles if the transform isn't
* following a parent and the state does not transform.
* @property ignoreParent
* @type boolean
* @default false
* @public
* @since 1.2.0
*/
public set ignoreParent( value: boolean ) {
this._ignoreParent = value;
}
public get ignoreParent(): boolean {
return this._ignoreParent;
}
/**
* Private copy.
* Whether to prevent children from acquiring this as a parent
* when concatenating matrices. This can save computation,
* but prevents it from passing any transform data to children.
*
* Use this to save some processor cycles if this is a Group
* that does not control its children, and the state does not
* transform.
*
* @property _ignoreChild
* @type boolean
* @default false
* @private
* @since 1.3.1
*/
private _ignoreChild: boolean = false;
/**
* Whether to prevent children from acquiring this as a parent
* when concatenating matrices. This can save computation,
* but prevents it from passing any transform data to children.
*
* Use this to save some processor cycles if this is a Group
* that does not control its children, and the state does not
* transform.
*
* @property ignoreChild
* @type boolean
* @default false
* @public
* @since 1.3.1
*/
public get ignoreChild(): boolean {
return this._ignoreChild;
}
public set ignoreChild( value: boolean ) {
this._ignoreChild = value;
}
/**
* Whether the transform has been altered since the last time
* it was used to create a matrix. Used to determine whether to rebuild
* the matrix or not.
*
* @property _dirty
* @type boolean
* @default true
* @private
* @since 1.3.1
*/
private _dirty: boolean = true;
/**
* Set the X and Y values of the transform.
* @method setPosition
* @param x {Number}
* @param y {Number}
* @return {Kiwi.Geom.Transform} This object.
* @public
*/
public setPosition(x: number, y: number): Transform {
this._x = x;
this._y = y;
this._dirty = true;
return this;
}
/**
* Set the X and Y values of the transform from a point.
* @method setPositionPoint
* @param point {Kiwi.Geom.Point} point.
* @return {Kiwi.Geom.Transform} This object.
* @public
*/
public setPositionFromPoint(point: Point): Transform {
this._x = point.x;
this._y = point.y;
this._dirty = true;
return this;
}
/**
* Translate the X and Y value of the transform by point components.
* @method translatePositionFromPoint
* @param point {Kiwi.Geom.Point} point.
* @return {Kiwi.Geom.Transform} This object.
* @public
*/
public translatePositionFromPoint(point: Point): Transform {
this._x += point.x;
this._y += point.y;
this._dirty = true;
return this;
}
/**
* Return a Point representing the X and Y values of the transform.
* If no point is given a new Point objected will be created.
*
* @method getPositionPoint
* @param [output] {Kiwi.Geom.Point} The Point to output the coordinates into. Creates a new Point if none given.
* @return {Kiwi.Geom.Point} A point representing the X and Y values of the transform.
* @public
*/
public getPositionPoint(output: Point = new Kiwi.Geom.Point): Point {
return output.setTo(this._x, this._y);
}
/**
* Set the X and Y scale value of the transform.
* This property is set only.
* In the future this will be looked into and updated as needed.
*
* @property scale
* @type Number
* @public
*/
public set scale(value:number) {
this._scaleX = value;
this._scaleY = value;
this._dirty = true;
}
/**
* Set the core properties of the transform.
*
* @method setTransform
* @param [x=0] {Number} X position of the transform.
* @param [y=0] {Number} Y position of the transform.
* @param [scaleX=1] {Number} X scaling of the transform.
* @param [scaleY=1] {Number} Y scaling of the transform.
* @param [rotation=0] {Number} Rotation of the transform in radians.
* @param [rotX=0] {Number} rotationPoint offset on X axis.
* @param [rotY=0] {Number} rotationPoint offset on Y axis.
* @return {Kiwi.Geom.Transform} This object.
* @public
*/
public setTransform(x: number = 0, y: number = 0, scaleX: number = 1, scaleY: number = 1, rotation: number = 0, rotPointX: number = 0, rotPointY: number = 0): Transform {
this._x = x;
this._y = y;
this._scaleX = scaleX;
this._scaleY = scaleY;
this._rotation = rotation;
this._rotPointX = rotPointX;
this._rotPointY = rotPointY;
this._dirty = true;
return this;
}
/**
* Return the parent matrix of the transform.
* If there is no parent then null is returned.
* @method getParentMatrix
* @return {Kiwi.Geom.Matrix} Parent transform matrix
* @public
*/
public getParentMatrix(): Matrix {
if (this._parent) {
return this._parent.getConcatenatedMatrix();
}
return null;
}
/**
* Return the transformation matrix that concatenates this transform
* with all ancestor transforms. If there is no parent then this will
* return a matrix the same as this transform's matrix.
* @method getConcatenatedMatrix
* @return {Kiwi.Geom.Matrix} The concatenated matrix.
* @public
*/
public getConcatenatedMatrix(): Matrix {
/*
Matrix caching
Potential cases:
- This dirty, parent dirty : Update matrix, build concat
- This dirty, parent clean : Update matrix, build concat
- This dirty, no parent : Update matrix
- This clean, parent dirty : Build concat
- This clean, parent clean : Use cachedConcatenated
- This clean, no parent : Use cachedConcatenated
Simplifies to four cases:
- This dirty, has parent : Update matrix, build concat
- This dirty, no parent : Update matrix
- This clean, parent dirty : Build concat
- Otherwise : Use cachedConcatenated
This has been further simplified because of some issues.
Now, the matrix is updated if it's dirty;
and the parent is applied if it exists.
Parent dirtiness is not considered, as this appeared to be
causing issues.
*/
// Set correct local matrix
if ( this._dirty && !this.locked ) {
this._matrix.setFromOffsetTransform(
this.x, this.y,
this.scaleX, this.scaleY,
this.rotation,
this.anchorPointX, this.anchorPointY) ;
}
// Get local matrix
this._cachedConcatenatedMatrix.copyFrom( this._matrix );
// Apply parent transform
if ( this._parent &&
!this._parent.ignoreChild &&
!this.ignoreParent ) {
this._cachedConcatenatedMatrix.tx -= this._parent.anchorPointX;
this._cachedConcatenatedMatrix.ty -= this._parent.anchorPointY;
this._cachedConcatenatedMatrix.prependMatrix(
this.getParentMatrix() );
}
this._dirty = false;
return this._cachedConcatenatedMatrix;
}
/**
* Apply this matrix to a an object with x and y properties representing a point and return the transformed point.
* @method transformPoint
* @param point {Kiwi.Geom.Point}
* @return {Kiwi.Geom.Point}
* @public
*/
public transformPoint(point: Point): Point {
var mat = this.getConcatenatedMatrix();
return mat.transformPoint(point);
}
/**
* Copy another transforms data to this transform. A clone of the source matrix is created for the matrix property.
* @method copyFrom
* @param transform {Kiwi.Geom.Transform} transform. The tranform to be copied from.
* @return {Kiwi.Geom.Transform} This object.
* @public
*/
public copyFrom(source: Transform): Transform {
this.setTransform(source.x, source.y, source.scaleX, source.scaleY, source.rotation, source.rotPointX, source.rotPointY);
this.parent = source.parent;
this._matrix = source.matrix.clone();
return this;
}
/**
* Copy this transforms data to the destination Transform.
* A clone of this transforms matrix is created in the destination Transform Matrix.
*
* @method copyTo
* @param destination {Kiwi.Geom.Transform} The tranform to copy to.
* @return {Kiwi.Geom.Transform} This object.
* @public
*/
public copyTo(destination: Transform): Transform {
destination.copyFrom(this);
return this;
}
/**
* Return a clone of this transform.
*
* @method clone
* @param [output] {Kiwi.Geom.Transform} A Transform to copy the clone in to. If none is given a new Transform object will be made.
* @return {Kiwi.Geom.Transform} A clone of this object.
* @public
*/
public clone(output: Transform = new Transform()): Transform {
output.copyFrom(this);
return output;
}
/**
* Recursively check that a transform does not appear as its own ancestor
* @method checkAncestor
* @param transform {Kiwi.Geom.Transform} The Transform to check.
* @return {boolean} Returns true if the given transform is the same as this or an ancestor, otherwise false.
* @public
*/
public checkAncestor(transform: Transform): boolean {
/*if (transform === this)
{
return true
}
if (transform.parent !== null)
{
return (this.checkAncestor(transform._parent))
}*/
return false;
}
/**
* Return a string represention of this object.
* @method toString
* @return {String} A string represention of this object.
* @public
*/
public get toString(): string {
return "[{Transform (x=" + this._x + " y=" + this._y + " scaleX=" + this._scaleX + " scaleY=" + this._scaleY + " rotation=" + this._rotation + " regX=" + this._rotPointX + " regY=" + this.rotPointY + " matrix=" + this._matrix + ")}]";
}
}
} | the_stack |
import { Toaster } from '@hospitalrun/components'
import {
act,
render,
screen,
waitFor,
waitForElementToBeRemoved,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import format from 'date-fns/format'
import { createMemoryHistory } from 'history'
import React from 'react'
import { Provider } from 'react-redux'
import { Router, Route } from 'react-router-dom'
import createMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as validateUtil from '../../labs/utils/validate-lab'
import { LabError } from '../../labs/utils/validate-lab'
import ViewLab from '../../labs/ViewLab'
import { ButtonBarProvider } from '../../page-header/button-toolbar/ButtonBarProvider'
import * as titleUtil from '../../page-header/title/TitleContext'
import LabRepository from '../../shared/db/LabRepository'
import PatientRepository from '../../shared/db/PatientRepository'
import Lab from '../../shared/model/Lab'
import Patient from '../../shared/model/Patient'
import Permissions from '../../shared/model/Permissions'
import { RootState } from '../../shared/store'
import { expectOneConsoleError } from '../test-utils/console.utils'
const mockStore = createMockStore<RootState, any>([thunk])
const mockPatient = { fullName: 'Full Name' }
const setup = (lab?: Partial<Lab>, permissions = [Permissions.ViewLab], error = {}) => {
const expectedDate = new Date()
let mockLab = {
...{
code: 'L-1234',
id: '12456',
status: 'requested',
patient: '1234',
type: 'lab type',
notes: [],
requestedOn: '2020-03-30T04:43:20.102Z',
},
...lab,
} as Lab
jest.resetAllMocks()
Date.now = jest.fn(() => expectedDate.valueOf())
jest.spyOn(PatientRepository, 'find').mockResolvedValue(mockPatient as Patient)
jest.spyOn(LabRepository, 'saveOrUpdate').mockImplementation(async (newOrUpdatedLab) => {
mockLab = newOrUpdatedLab
return mockLab
})
jest.spyOn(LabRepository, 'find').mockResolvedValue(mockLab)
const history = createMemoryHistory({ initialEntries: [`/labs/${mockLab.id}`] })
const store = mockStore({
user: {
permissions,
},
lab: {
mockLab,
patient: mockPatient,
error,
status: Object.keys(error).length > 0 ? 'error' : 'completed',
},
} as any)
return {
history,
mockLab,
expectedDate,
...render(
<ButtonBarProvider>
<Provider store={store}>
<Router history={history}>
<Route path="/labs/:id">
<titleUtil.TitleProvider>
<ViewLab />
</titleUtil.TitleProvider>
</Route>
</Router>
<Toaster draggable hideProgressBar />
</Provider>
</ButtonBarProvider>,
),
}
}
describe('View Lab', () => {
describe('page content', () => {
it("should display the patients' full name", async () => {
setup()
expect(await screen.findByRole('heading', { name: mockPatient.fullName })).toBeInTheDocument()
})
it('should display the lab-type', async () => {
const { mockLab } = setup({ type: 'expected type' })
expect(await screen.findByRole('heading', { name: mockLab.type })).toBeInTheDocument()
})
it('should display the requested on date', async () => {
const { mockLab } = setup({ requestedOn: '2020-03-30T04:43:20.102Z' })
expect(
await screen.findByRole('heading', {
name: format(new Date(mockLab.requestedOn), 'yyyy-MM-dd hh:mm a'),
}),
).toBeInTheDocument()
})
it('should not display the completed date if the lab is not completed', async () => {
const completedDate = new Date('2020-10-10T10:10:10.100') // We want a different date than the mocked date
setup({ completedOn: completedDate.toISOString() })
await waitForElementToBeRemoved(() => screen.queryByText(/loading/i))
expect(
screen.queryByText(format(completedDate, 'yyyy-MM-dd HH:mm a')),
).not.toBeInTheDocument()
})
it('should not display the cancelled date if the lab is not cancelled', async () => {
const cancelledDate = new Date('2020-10-10T10:10:10.100') // We want a different date than the mocked date
setup({ canceledOn: cancelledDate.toISOString() })
await waitForElementToBeRemoved(() => screen.queryByText(/loading/i))
expect(
screen.queryByText(format(cancelledDate, 'yyyy-MM-dd HH:mm a')),
).not.toBeInTheDocument()
})
it('should render a result text field', async () => {
const { mockLab } = setup({ result: 'expected results' })
expect(
await screen.findByRole('textbox', {
name: /labs\.lab\.result/i,
}),
).toHaveValue(mockLab.result)
})
it('should not display past notes if there is not', async () => {
setup({ notes: [] })
await waitForElementToBeRemoved(() => screen.queryByText(/loading/i))
expect(screen.queryAllByTestId('note')).toHaveLength(0)
})
it('should display the past notes that are not deleted', async () => {
const expectedNotes = {
id: 'test-note-id',
date: new Date().toISOString(),
text: 'expected notes',
deleted: false,
}
setup({ notes: [expectedNotes] })
expect(await screen.findByTestId('note')).toHaveTextContent(expectedNotes.text)
})
it('should not display the past notes that are deleted', async () => {
const deletedNote = {
id: 'test-note-id',
date: new Date().toISOString(),
text: 'deleted note',
deleted: true,
}
setup({ notes: [deletedNote] })
expect(await screen.queryByText('deleted note')).toBe(null)
})
it('should display the notes text field empty', async () => {
setup()
expect(await screen.findByLabelText('labs.lab.notes')).toHaveValue('')
})
it('should display errors', async () => {
const expectedError = { message: 'some message', result: 'some result feedback' } as LabError
setup({ status: 'requested' }, [Permissions.ViewLab, Permissions.CompleteLab])
expectOneConsoleError(expectedError)
jest.spyOn(validateUtil, 'validateLabComplete').mockReturnValue(expectedError)
userEvent.click(
await screen.findByRole('button', {
name: /labs\.requests\.complete/i,
}),
)
const alert = await screen.findByRole('alert')
expect(alert).toContainElement(screen.getByText(/states\.error/i))
expect(alert).toContainElement(screen.getByText(/some message/i))
expect(screen.getByLabelText(/labs\.lab\.result/i)).toHaveClass('is-invalid')
})
describe('requested lab request', () => {
it('should display a warning badge if the status is requested', async () => {
const { mockLab } = setup()
const status = await screen.findByText(mockLab.status)
expect(status.closest('span')).toHaveClass('badge-warning')
})
it('should display a update lab, complete lab, and cancel lab button if the lab is in a requested state', async () => {
setup({}, [Permissions.ViewLab, Permissions.CompleteLab, Permissions.CancelLab])
expect(await screen.findAllByRole('button')).toEqual(
expect.arrayContaining([
screen.getByText(/labs\.requests\.update/i),
screen.getByText(/labs\.requests\.complete/i),
screen.getByText(/labs\.requests\.cancel/i),
]),
)
})
})
describe('canceled lab request', () => {
it('should display a danger badge if the status is canceled', async () => {
const { mockLab } = setup({ status: 'canceled' })
const status = await screen.findByText(mockLab.status)
expect(status.closest('span')).toHaveClass('badge-danger')
})
it('should display the cancelled on date if the lab request has been cancelled', async () => {
const { mockLab } = setup({
status: 'canceled',
canceledOn: '2020-03-30T04:45:20.102Z',
})
expect(
await screen.findByRole('heading', {
name: format(new Date(mockLab.canceledOn as string), 'yyyy-MM-dd hh:mm a'),
}),
).toBeInTheDocument()
})
it('should not display update, complete, and cancel button if the lab is canceled', async () => {
setup(
{
status: 'canceled',
},
[Permissions.ViewLab, Permissions.CompleteLab, Permissions.CancelLab],
)
await waitForElementToBeRemoved(() => screen.queryByText(/loading/i))
expect(screen.queryByRole('button')).not.toBeInTheDocument()
})
it('should not display notes text field if the status is canceled', async () => {
setup({ status: 'canceled' })
expect(await screen.findByText(/labs\.lab\.notes/i)).toBeInTheDocument()
expect(screen.queryByLabelText(/labs\.lab\.notes/i)).not.toBeInTheDocument()
})
})
describe('completed lab request', () => {
it('should display a primary badge if the status is completed', async () => {
const { mockLab } = setup({ status: 'completed' })
const status = await screen.findByText(mockLab.status)
expect(status.closest('span')).toHaveClass('badge-primary')
})
it('should display the completed on date if the lab request has been completed', async () => {
const { mockLab } = setup({
status: 'completed',
completedOn: '2020-03-30T04:44:20.102Z',
})
expect(
await screen.findByText(
format(new Date(mockLab.completedOn as string), 'yyyy-MM-dd hh:mm a'),
),
).toBeInTheDocument()
})
it('should not display update, complete, and cancel buttons if the lab is completed', async () => {
setup(
{
status: 'completed',
},
[Permissions.ViewLab, Permissions.CompleteLab, Permissions.CancelLab],
)
await waitForElementToBeRemoved(() => screen.queryByText(/loading/i))
expect(screen.queryByRole('button')).not.toBeInTheDocument()
})
it('should not display notes text field if the status is completed', async () => {
setup(
{
status: 'completed',
},
[Permissions.ViewLab, Permissions.CompleteLab, Permissions.CancelLab],
)
expect(await screen.findByText(/labs\.lab\.notes/i)).toBeInTheDocument()
expect(screen.queryByLabelText(/labs\.lab\.notes/i)).not.toBeInTheDocument()
})
})
})
describe('on update', () => {
it('should update the lab with the new information', async () => {
const { history } = setup()
const expectedResult = 'expected result'
const newNotes = 'expected notes'
const resultTextField = await screen.findByLabelText(/labs\.lab\.result/i)
userEvent.type(resultTextField, expectedResult)
const notesTextField = screen.getByLabelText('labs.lab.notes')
userEvent.type(notesTextField, newNotes)
userEvent.click(
screen.getByRole('button', {
name: /labs\.requests\.update/i,
}),
)
await waitFor(() => {
expect(history.location.pathname).toEqual('/labs/12456')
})
expect(screen.getByLabelText(/labs\.lab\.result/i)).toHaveTextContent(expectedResult)
expect(screen.getByTestId('note')).toHaveTextContent(newNotes)
})
it('should be able delete an note from the lab', async () => {
const notes = [
{
id: 'earth-test-id',
date: new Date().toISOString(),
text: 'Hello earth, first note',
deleted: false,
},
{
id: 'mars-test-id',
date: new Date().toISOString(),
text: 'Hello mars, second note',
deleted: false,
},
]
setup({ notes })
expect(await screen.findByText(notes[0].text)).toBeInTheDocument()
expect(await screen.findByText(notes[1].text)).toBeInTheDocument()
act(() => userEvent.click(screen.getByTestId(`delete-note-${notes[1].id}`)))
expect(await screen.findByText(notes[0].text)).toBeInTheDocument()
expect(await screen.queryByText(notes[1].text)).not.toBeInTheDocument()
})
})
describe('on complete', () => {
it('should mark the status as completed and fill in the completed date with the current time', async () => {
const { history } = setup({}, [
Permissions.ViewLab,
Permissions.CompleteLab,
Permissions.CancelLab,
])
const expectedResult = 'expected result'
userEvent.type(await screen.findByLabelText(/labs\.lab\.result/i), expectedResult)
userEvent.click(
screen.getByRole('button', {
name: /labs\.requests\.complete/i,
}),
)
await waitFor(() => {
expect(history.location.pathname).toEqual('/labs/12456')
})
expect(await screen.findByRole('alert')).toBeInTheDocument()
expect(
within(screen.getByRole('alert')).getByText(/labs\.successfullyCompleted/i),
).toBeInTheDocument()
})
it('should disallow deleting notes', async () => {
const labNote = {
id: 'earth-test-id',
date: new Date().toISOString(),
text: 'A note from the lab!',
deleted: false,
}
setup(
{
notes: [labNote],
status: 'completed',
},
[Permissions.ViewLab, Permissions.CompleteLab, Permissions.CancelLab],
)
const notes = await screen.findAllByTestId('note')
expect(notes).toHaveLength(1)
expect(notes[0]).toHaveTextContent(labNote.text)
expect(screen.queryAllByRole('button', { name: 'Delete' })).toHaveLength(0)
})
})
describe('on cancel', () => {
// integration test candidate; after 'cancelled' route goes to <Labs />
// 'should mark the status as canceled and fill in the cancelled on date with the current time'
it('should mark the status as canceled and redirect to /labs', async () => {
const { history } = setup({}, [
Permissions.ViewLab,
Permissions.CompleteLab,
Permissions.CancelLab,
])
const expectedResult = 'expected result'
userEvent.type(await screen.findByLabelText(/labs\.lab\.result/i), expectedResult)
userEvent.click(
screen.getByRole('button', {
name: /labs\.requests\.cancel/i,
}),
)
await waitFor(() => {
expect(history.location.pathname).toEqual('/labs')
})
})
it('should disallow deleting notes', async () => {
const labNote = {
id: 'earth-test-id',
date: new Date().toISOString(),
text: 'A note from the lab!',
deleted: false,
}
setup(
{
notes: [labNote],
status: 'canceled',
},
[Permissions.ViewLab, Permissions.CompleteLab, Permissions.CancelLab],
)
const notes = await screen.findAllByTestId('note')
expect(notes).toHaveLength(1)
expect(notes[0]).toHaveTextContent(labNote.text)
expect(screen.queryAllByRole('button', { name: 'Delete' })).toHaveLength(0)
})
})
}) | the_stack |
/*
JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
Basic GUI blocking jpeg encoder
*/
import { Image } from "./image.ts";
function JPEGEncoder(quality: number) {
const ffloor = Math.floor;
const YTable = new Array(64);
const UVTable = new Array(64);
const fdtbl_Y = new Array(64);
const fdtbl_UV = new Array(64);
// @ts-ignore
let YDC_HT;
// @ts-ignore
let UVDC_HT;
// @ts-ignore
let YAC_HT;
// @ts-ignore
let UVAC_HT;
const bitcode = new Array(65535);
const category = new Array(65535);
const outputfDCTQuant = new Array(64);
const DU = new Array(64);
let byteout = [];
let bytenew = 0;
let bytepos = 7;
const YDU = new Array(64);
const UDU = new Array(64);
const VDU = new Array(64);
const clt = new Array(256);
const RGB_YUV_TABLE = new Array(2048);
// @ts-ignore
let currentQuality;
const ZigZag = [
0,
1,
5,
6,
14,
15,
27,
28,
2,
4,
7,
13,
16,
26,
29,
42,
3,
8,
12,
17,
25,
30,
41,
43,
9,
11,
18,
24,
31,
40,
44,
53,
10,
19,
23,
32,
39,
45,
52,
54,
20,
22,
33,
38,
46,
51,
55,
60,
21,
34,
37,
47,
50,
56,
59,
61,
35,
36,
48,
49,
57,
58,
62,
63,
];
const std_dc_luminance_nrcodes = [
0,
0,
1,
5,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
];
const std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const std_ac_luminance_nrcodes = [
0,
0,
2,
1,
3,
3,
2,
4,
3,
5,
5,
4,
4,
0,
0,
1,
0x7d,
];
const std_ac_luminance_values = [
0x01,
0x02,
0x03,
0x00,
0x04,
0x11,
0x05,
0x12,
0x21,
0x31,
0x41,
0x06,
0x13,
0x51,
0x61,
0x07,
0x22,
0x71,
0x14,
0x32,
0x81,
0x91,
0xa1,
0x08,
0x23,
0x42,
0xb1,
0xc1,
0x15,
0x52,
0xd1,
0xf0,
0x24,
0x33,
0x62,
0x72,
0x82,
0x09,
0x0a,
0x16,
0x17,
0x18,
0x19,
0x1a,
0x25,
0x26,
0x27,
0x28,
0x29,
0x2a,
0x34,
0x35,
0x36,
0x37,
0x38,
0x39,
0x3a,
0x43,
0x44,
0x45,
0x46,
0x47,
0x48,
0x49,
0x4a,
0x53,
0x54,
0x55,
0x56,
0x57,
0x58,
0x59,
0x5a,
0x63,
0x64,
0x65,
0x66,
0x67,
0x68,
0x69,
0x6a,
0x73,
0x74,
0x75,
0x76,
0x77,
0x78,
0x79,
0x7a,
0x83,
0x84,
0x85,
0x86,
0x87,
0x88,
0x89,
0x8a,
0x92,
0x93,
0x94,
0x95,
0x96,
0x97,
0x98,
0x99,
0x9a,
0xa2,
0xa3,
0xa4,
0xa5,
0xa6,
0xa7,
0xa8,
0xa9,
0xaa,
0xb2,
0xb3,
0xb4,
0xb5,
0xb6,
0xb7,
0xb8,
0xb9,
0xba,
0xc2,
0xc3,
0xc4,
0xc5,
0xc6,
0xc7,
0xc8,
0xc9,
0xca,
0xd2,
0xd3,
0xd4,
0xd5,
0xd6,
0xd7,
0xd8,
0xd9,
0xda,
0xe1,
0xe2,
0xe3,
0xe4,
0xe5,
0xe6,
0xe7,
0xe8,
0xe9,
0xea,
0xf1,
0xf2,
0xf3,
0xf4,
0xf5,
0xf6,
0xf7,
0xf8,
0xf9,
0xfa,
];
const std_dc_chrominance_nrcodes = [
0,
0,
3,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
];
const std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const std_ac_chrominance_nrcodes = [
0,
0,
2,
1,
2,
4,
4,
3,
4,
7,
5,
4,
4,
0,
1,
2,
0x77,
];
const std_ac_chrominance_values = [
0x00,
0x01,
0x02,
0x03,
0x11,
0x04,
0x05,
0x21,
0x31,
0x06,
0x12,
0x41,
0x51,
0x07,
0x61,
0x71,
0x13,
0x22,
0x32,
0x81,
0x08,
0x14,
0x42,
0x91,
0xa1,
0xb1,
0xc1,
0x09,
0x23,
0x33,
0x52,
0xf0,
0x15,
0x62,
0x72,
0xd1,
0x0a,
0x16,
0x24,
0x34,
0xe1,
0x25,
0xf1,
0x17,
0x18,
0x19,
0x1a,
0x26,
0x27,
0x28,
0x29,
0x2a,
0x35,
0x36,
0x37,
0x38,
0x39,
0x3a,
0x43,
0x44,
0x45,
0x46,
0x47,
0x48,
0x49,
0x4a,
0x53,
0x54,
0x55,
0x56,
0x57,
0x58,
0x59,
0x5a,
0x63,
0x64,
0x65,
0x66,
0x67,
0x68,
0x69,
0x6a,
0x73,
0x74,
0x75,
0x76,
0x77,
0x78,
0x79,
0x7a,
0x82,
0x83,
0x84,
0x85,
0x86,
0x87,
0x88,
0x89,
0x8a,
0x92,
0x93,
0x94,
0x95,
0x96,
0x97,
0x98,
0x99,
0x9a,
0xa2,
0xa3,
0xa4,
0xa5,
0xa6,
0xa7,
0xa8,
0xa9,
0xaa,
0xb2,
0xb3,
0xb4,
0xb5,
0xb6,
0xb7,
0xb8,
0xb9,
0xba,
0xc2,
0xc3,
0xc4,
0xc5,
0xc6,
0xc7,
0xc8,
0xc9,
0xca,
0xd2,
0xd3,
0xd4,
0xd5,
0xd6,
0xd7,
0xd8,
0xd9,
0xda,
0xe2,
0xe3,
0xe4,
0xe5,
0xe6,
0xe7,
0xe8,
0xe9,
0xea,
0xf2,
0xf3,
0xf4,
0xf5,
0xf6,
0xf7,
0xf8,
0xf9,
0xfa,
];
// @ts-ignore
function initQuantTables(sf) {
const YQT = [
16,
11,
10,
16,
24,
40,
51,
61,
12,
12,
14,
19,
26,
58,
60,
55,
14,
13,
16,
24,
40,
57,
69,
56,
14,
17,
22,
29,
51,
87,
80,
62,
18,
22,
37,
56,
68,
109,
103,
77,
24,
35,
55,
64,
81,
104,
113,
92,
49,
64,
78,
87,
103,
121,
120,
101,
72,
92,
95,
98,
112,
100,
103,
99,
];
for (let i = 0; i < 64; i++) {
let t = ffloor((YQT[i] * sf + 50) / 100);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
YTable[ZigZag[i]] = t;
}
const UVQT = [
17,
18,
24,
47,
99,
99,
99,
99,
18,
21,
26,
66,
99,
99,
99,
99,
24,
26,
56,
99,
99,
99,
99,
99,
47,
66,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
99,
];
for (let j = 0; j < 64; j++) {
let u = ffloor((UVQT[j] * sf + 50) / 100);
if (u < 1) {
u = 1;
} else if (u > 255) {
u = 255;
}
UVTable[ZigZag[j]] = u;
}
const aasf = [
1.0,
1.387039845,
1.306562965,
1.175875602,
1.0,
0.785694958,
0.541196100,
0.275899379,
];
let k = 0;
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
fdtbl_Y[k] = (1.0 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
fdtbl_UV[k] =
(1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
k++;
}
}
}
// @ts-ignore
function computeHuffmanTbl(nrcodes, std_table) {
let codevalue = 0;
let pos_in_table = 0;
const HT = new Array();
for (let k = 1; k <= 16; k++) {
for (let j = 1; j <= nrcodes[k]; j++) {
HT[std_table[pos_in_table]] = [];
HT[std_table[pos_in_table]][0] = codevalue;
HT[std_table[pos_in_table]][1] = k;
pos_in_table++;
codevalue++;
}
codevalue *= 2;
}
return HT;
}
function initHuffmanTbl() {
YDC_HT = computeHuffmanTbl(
std_dc_luminance_nrcodes,
std_dc_luminance_values,
);
UVDC_HT = computeHuffmanTbl(
std_dc_chrominance_nrcodes,
std_dc_chrominance_values,
);
YAC_HT = computeHuffmanTbl(
std_ac_luminance_nrcodes,
std_ac_luminance_values,
);
UVAC_HT = computeHuffmanTbl(
std_ac_chrominance_nrcodes,
std_ac_chrominance_values,
);
}
function initCategoryNumber() {
let nrlower = 1;
let nrupper = 2;
for (let cat = 1; cat <= 15; cat++) {
// Positive numbers
for (let nr = nrlower; nr < nrupper; nr++) {
category[32767 + nr] = cat;
bitcode[32767 + nr] = [];
bitcode[32767 + nr][1] = cat;
bitcode[32767 + nr][0] = nr;
}
// Negative numbers
for (let nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) {
category[32767 + nrneg] = cat;
bitcode[32767 + nrneg] = [];
bitcode[32767 + nrneg][1] = cat;
bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg;
}
nrlower <<= 1;
nrupper <<= 1;
}
}
function initRGBYUVTable() {
for (let i = 0; i < 256; i++) {
RGB_YUV_TABLE[i] = 19595 * i;
RGB_YUV_TABLE[(i + 256) >> 0] = 38470 * i;
RGB_YUV_TABLE[(i + 512) >> 0] = 7471 * i + 0x8000;
RGB_YUV_TABLE[(i + 768) >> 0] = -11059 * i;
RGB_YUV_TABLE[(i + 1024) >> 0] = -21709 * i;
RGB_YUV_TABLE[(i + 1280) >> 0] = 32768 * i + 0x807FFF;
RGB_YUV_TABLE[(i + 1536) >> 0] = -27439 * i;
RGB_YUV_TABLE[(i + 1792) >> 0] = -5329 * i;
}
}
// IO functions
// @ts-ignore
function writeBits(bs) {
const value = bs[0];
let posval = bs[1] - 1;
while (posval >= 0) {
if (value & (1 << posval)) {
bytenew |= (1 << bytepos);
}
posval--;
bytepos--;
if (bytepos < 0) {
if (bytenew === 0xFF) {
writeByte(0xFF);
writeByte(0);
} else {
writeByte(bytenew);
}
bytepos = 7;
bytenew = 0;
}
}
}
// @ts-ignore
function writeByte(value) {
// byteout.push(clt[value]); // write char directly instead of converting later
byteout.push(value);
}
// @ts-ignore
function writeWord(value) {
writeByte((value >> 8) & 0xFF);
writeByte((value) & 0xFF);
}
// DCT & quantization core
// @ts-ignore
function fDCTQuant(data, fdtbl) {
let d0, d1, d2, d3, d4, d5, d6, d7;
/* Pass 1: process rows. */
let dataOff = 0;
let i;
const I8 = 8;
const I64 = 64;
for (i = 0; i < I8; ++i) {
d0 = data[dataOff];
d1 = data[dataOff + 1];
d2 = data[dataOff + 2];
d3 = data[dataOff + 3];
d4 = data[dataOff + 4];
d5 = data[dataOff + 5];
d6 = data[dataOff + 6];
d7 = data[dataOff + 7];
const tmp0 = d0 + d7;
const tmp7 = d0 - d7;
const tmp1 = d1 + d6;
const tmp6 = d1 - d6;
const tmp2 = d2 + d5;
const tmp5 = d2 - d5;
const tmp3 = d3 + d4;
const tmp4 = d3 - d4;
/* Even part */
let tmp10 = tmp0 + tmp3; /* phase 2 */
const tmp13 = tmp0 - tmp3;
let tmp11 = tmp1 + tmp2;
let tmp12 = tmp1 - tmp2;
data[dataOff] = tmp10 + tmp11; /* phase 3 */
data[dataOff + 4] = tmp10 - tmp11;
const z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
data[dataOff + 2] = tmp13 + z1; /* phase 5 */
data[dataOff + 6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
const z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
const z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
const z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
const z3 = tmp11 * 0.707106781; /* c4 */
const z11 = tmp7 + z3; /* phase 5 */
const z13 = tmp7 - z3;
data[dataOff + 5] = z13 + z2; /* phase 6 */
data[dataOff + 3] = z13 - z2;
data[dataOff + 1] = z11 + z4;
data[dataOff + 7] = z11 - z4;
dataOff += 8; /* advance pointer to next row */
}
/* Pass 2: process columns. */
dataOff = 0;
for (i = 0; i < I8; ++i) {
d0 = data[dataOff];
d1 = data[dataOff + 8];
d2 = data[dataOff + 16];
d3 = data[dataOff + 24];
d4 = data[dataOff + 32];
d5 = data[dataOff + 40];
d6 = data[dataOff + 48];
d7 = data[dataOff + 56];
const tmp0p2 = d0 + d7;
const tmp7p2 = d0 - d7;
const tmp1p2 = d1 + d6;
const tmp6p2 = d1 - d6;
const tmp2p2 = d2 + d5;
const tmp5p2 = d2 - d5;
const tmp3p2 = d3 + d4;
const tmp4p2 = d3 - d4;
/* Even part */
let tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */
const tmp13p2 = tmp0p2 - tmp3p2;
let tmp11p2 = tmp1p2 + tmp2p2;
let tmp12p2 = tmp1p2 - tmp2p2;
data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */
data[dataOff + 32] = tmp10p2 - tmp11p2;
const z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */
data[dataOff + 16] = tmp13p2 + z1p2; /* phase 5 */
data[dataOff + 48] = tmp13p2 - z1p2;
/* Odd part */
tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */
tmp11p2 = tmp5p2 + tmp6p2;
tmp12p2 = tmp6p2 + tmp7p2;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
const z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */
const z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */
const z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */
const z3p2 = tmp11p2 * 0.707106781; /* c4 */
const z11p2 = tmp7p2 + z3p2; /* phase 5 */
const z13p2 = tmp7p2 - z3p2;
data[dataOff + 40] = z13p2 + z2p2; /* phase 6 */
data[dataOff + 24] = z13p2 - z2p2;
data[dataOff + 8] = z11p2 + z4p2;
data[dataOff + 56] = z11p2 - z4p2;
dataOff++; /* advance pointer to next column */
}
// Quantize/descale the coefficients
let fDCTQuant1;
for (i = 0; i < I64; ++i) {
// Apply the quantization and scaling factor & Round to nearest integer
fDCTQuant1 = data[i] * fdtbl[i];
outputfDCTQuant[i] = (fDCTQuant1 > 0.0)
? ((fDCTQuant1 + 0.5) | 0)
: ((fDCTQuant1 - 0.5) | 0);
}
return outputfDCTQuant;
}
function writeAPP0() {
writeWord(0xFFE0); // marker
writeWord(16); // length
writeByte(0x4A); // J
writeByte(0x46); // F
writeByte(0x49); // I
writeByte(0x46); // F
writeByte(0); // = "JFIF",'\0'
writeByte(1); // versionhi
writeByte(1); // versionlo
writeByte(0); // xyunits
writeWord(1); // xdensity
writeWord(1); // ydensity
writeByte(0); // thumbnwidth
writeByte(0); // thumbnheight
}
// @ts-ignore
function writeSOF0(width, height) {
writeWord(0xFFC0); // marker
writeWord(17); // length, truecolor YUV JPG
writeByte(8); // precision
writeWord(height);
writeWord(width);
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0x11); // HVY
writeByte(0); // QTY
writeByte(2); // IdU
writeByte(0x11); // HVU
writeByte(1); // QTU
writeByte(3); // IdV
writeByte(0x11); // HVV
writeByte(1); // QTV
}
function writeDQT() {
writeWord(0xFFDB); // marker
writeWord(132); // length
writeByte(0);
for (let i = 0; i < 64; i++) {
writeByte(YTable[i]);
}
writeByte(1);
for (let j = 0; j < 64; j++) {
writeByte(UVTable[j]);
}
}
function writeDHT() {
writeWord(0xFFC4); // marker
writeWord(0x01A2); // length
writeByte(0); // HTYDCinfo
for (let i = 0; i < 16; i++) {
writeByte(std_dc_luminance_nrcodes[i + 1]);
}
for (let j = 0; j <= 11; j++) {
writeByte(std_dc_luminance_values[j]);
}
writeByte(0x10); // HTYACinfo
for (let k = 0; k < 16; k++) {
writeByte(std_ac_luminance_nrcodes[k + 1]);
}
for (let l = 0; l <= 161; l++) {
writeByte(std_ac_luminance_values[l]);
}
writeByte(1); // HTUDCinfo
for (let m = 0; m < 16; m++) {
writeByte(std_dc_chrominance_nrcodes[m + 1]);
}
for (let n = 0; n <= 11; n++) {
writeByte(std_dc_chrominance_values[n]);
}
writeByte(0x11); // HTUACinfo
for (let o = 0; o < 16; o++) {
writeByte(std_ac_chrominance_nrcodes[o + 1]);
}
for (let p = 0; p <= 161; p++) {
writeByte(std_ac_chrominance_values[p]);
}
}
function writeSOS() {
writeWord(0xFFDA); // marker
writeWord(12); // length
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0); // HTY
writeByte(2); // IdU
writeByte(0x11); // HTU
writeByte(3); // IdV
writeByte(0x11); // HTV
writeByte(0); // Ss
writeByte(0x3f); // Se
writeByte(0); // Bf
}
// @ts-ignore
function processDU(CDU, fdtbl, DC, HTDC, HTAC) {
const EOB = HTAC[0x00];
const M16zeroes = HTAC[0xF0];
let pos;
const I16 = 16;
const I63 = 63;
const I64 = 64;
const DU_DCT = fDCTQuant(CDU, fdtbl);
// ZigZag reorder
for (let j = 0; j < I64; ++j) {
DU[ZigZag[j]] = DU_DCT[j];
}
const Diff = DU[0] - DC;
DC = DU[0];
// Encode DC
if (Diff === 0) {
writeBits(HTDC[0]); // Diff might be 0
} else {
pos = 32767 + Diff;
writeBits(HTDC[category[pos]]);
writeBits(bitcode[pos]);
}
// Encode ACs
let end0pos = 63; // was const... which is crazy
for (; (end0pos > 0) && (DU[end0pos] === 0); end0pos--) {}
// end0pos = first element in reverse order !=0
if (end0pos === 0) {
writeBits(EOB);
return DC;
}
let i = 1;
let lng;
while (i <= end0pos) {
const startpos = i;
for (; (DU[i] === 0) && (i <= end0pos); ++i) {}
let nrzeroes = i - startpos;
if (nrzeroes >= I16) {
lng = nrzeroes >> 4;
for (let nrmarker = 1; nrmarker <= lng; ++nrmarker) {
writeBits(M16zeroes);
}
nrzeroes = nrzeroes & 0xF;
}
pos = 32767 + DU[i];
writeBits(HTAC[(nrzeroes << 4) + category[pos]]);
writeBits(bitcode[pos]);
i++;
}
if (end0pos !== I63) {
writeBits(EOB);
}
return DC;
}
function initCharLookupTable() {
const sfcc = String.fromCharCode;
for (let i = 0; i < 256; i++) { ///// ACHTUNG // 255
clt[i] = sfcc(i);
}
}
// @ts-ignore
this.encode = function (image, q) {
if (q) { setQuality(q); }
// Initialize bit writer
byteout = new Array();
bytenew = 0;
bytepos = 7;
// Add JPEG headers
writeWord(0xFFD8); // SOI
writeAPP0();
writeDQT();
writeSOF0(image.width, image.height);
writeDHT();
writeSOS();
// Encode 8x8 macroblocks
let DCY = 0;
let DCU = 0;
let DCV = 0;
bytenew = 0;
bytepos = 7;
this.encode.displayName = "_encode_";
const imageData = image.data;
const width = image.width;
const height = image.height;
const quadWidth = width * 4;
let x, y = 0;
let r, g, b;
let start, p, col, row, pos;
while (y < height) {
x = 0;
while (x < quadWidth) {
start = quadWidth * y + x;
for (pos = 0; pos < 64; pos++) {
row = pos >> 3; // /8
col = (pos & 7) * 4; // %8
p = start + (row * quadWidth) + col;
if (y + row >= height) { // padding bottom
p -= (quadWidth * (y + 1 + row - height));
}
if (x + col >= quadWidth) { // padding right
p -= ((x + col) - quadWidth + 4);
}
r = imageData[p++];
g = imageData[p++];
b = imageData[p];
/* // calculate YUV values dynamically
YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
*/
// use lookup table (slightly faster)
YDU[pos] =
((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256) >> 0] +
RGB_YUV_TABLE[(b + 512) >> 0]) >> 16) - 128;
UDU[pos] =
((RGB_YUV_TABLE[(r + 768) >> 0] + RGB_YUV_TABLE[(g + 1024) >> 0] +
RGB_YUV_TABLE[(b + 1280) >> 0]) >> 16) - 128;
VDU[pos] =
((RGB_YUV_TABLE[(r + 1280) >> 0] + RGB_YUV_TABLE[(g + 1536) >> 0] +
RGB_YUV_TABLE[(b + 1792) >> 0]) >> 16) - 128;
}
// @ts-ignore
DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
// @ts-ignore
DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
// @ts-ignore
DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
x += 32;
}
y += 8;
}
////////////////////////////////////////////////////////////////
// Do the bit alignment of the EOI marker
if (bytepos >= 0) {
const fillbits = [];
fillbits[1] = bytepos + 1;
fillbits[0] = (1 << (bytepos + 1)) - 1;
writeBits(fillbits);
}
writeWord(0xFFD9); // EOI
return new Uint8Array(byteout);
};
// @ts-ignore
function setQuality(q) {
if (q <= 0) {
q = 1;
}
if (q > 100) {
q = 100;
}
// @ts-ignore
if (currentQuality === q) { return; } // don't recalc if unchanged
let sf = 0;
if (q < 50) {
sf = Math.floor(5000 / q);
} else {
sf = Math.floor(200 - q * 2);
}
initQuantTables(sf);
currentQuality = q;
}
function init() {
if (!quality) { quality = 50; }
// Create tables
initCharLookupTable();
initHuffmanTbl();
initCategoryNumber();
initRGBYUVTable();
setQuality(quality);
}
init();
}
export const encode = function (imgData: Image, qu: number = 50): Image {
// @ts-ignore
const encoder = new JPEGEncoder(qu);
const data = encoder.encode(imgData, qu);
const result = new Image();
result.data = data;
result.width = imgData.width;
result.height = imgData.height;
return result;
}; | the_stack |
import * as RxType from 'rxjs'
let Scheduler: import('./utils').Scheduler
let React: typeof import('react')
let ReactTestRenderer: typeof import('react-test-renderer')
let act: typeof import('react-test-renderer').act
let ObservableHooks: typeof import('../src')
let Rx: typeof import('rxjs')
describe('Concurrent Mode', () => {
beforeEach(() => {
jest.resetModules()
jest.mock('scheduler', () => require('scheduler/unstable_mock'))
jest.mock('react', () => require('experimental_react'))
jest.mock('react-dom', () => require('experimental_react-dom'))
jest.mock('react-test-renderer', () =>
require('experimental_react-test-renderer')
)
ObservableHooks = require('../src')
React = require('react')
ReactTestRenderer = require('react-test-renderer')
Scheduler = require('scheduler')
Rx = require('rxjs')
act = ReactTestRenderer.act
})
describe('useSubscription', () => {
it('should ignore emissions when the observable is changed but new subscription is not yet established', () => {
function Subscription({
source$
}: {
source$: RxType.Observable<string>
}) {
ObservableHooks.useSubscription(source$, value => {
Scheduler.unstable_yieldValue(value)
})
Scheduler.unstable_yieldValue('render')
return null
}
const observableA = new Rx.BehaviorSubject('a-0')
const observableB = new Rx.BehaviorSubject('b-0')
let renderer: ReturnType<typeof ReactTestRenderer.create>
act(() => {
renderer = ReactTestRenderer.create(
<Subscription source$={observableA} />,
{ unstable_isConcurrent: true } as any
)
})
expect(Scheduler).toHaveYielded(['render', 'a-0'])
act(() => {
renderer.update(<Subscription source$={observableB} />)
// Start React update, but don't finish
expect(Scheduler).toFlushAndYieldThrough(['render'])
observableA.next('a-1')
// observableA is ignored
expect(Scheduler).toFlushAndYield(['b-0'])
observableA.next('a-2')
observableB.next('b-2')
// observableA is still ignored
expect(Scheduler).toHaveYielded(['b-2'])
Scheduler.unstable_flushAllWithoutAsserting()
})
act(() => {
renderer.update(<Subscription source$={observableA} />)
// Start React update, but don't finish
expect(Scheduler).toFlushAndYieldThrough(['render'])
observableB.next('b-3')
observableB.error(new Error('oops'))
// observableB is ignored
expect(Scheduler).toFlushAndYield(['a-2'])
})
const observableC = new Rx.BehaviorSubject('c-0')
act(() => {
renderer.update(<Subscription source$={observableC} />)
// Start React update, but don't finish
expect(Scheduler).toFlushAndYieldThrough(['render'])
observableA.next('a-3')
observableA.complete()
// observableA is ignored
expect(Scheduler).toFlushAndYield(['c-0'])
})
expect(Scheduler).toFlushWithoutYielding()
})
})
describe('useLayoutSubscription', () => {
it('should ignore emissions when the observable is changed but new subscription is not yet established', () => {
function Subscription({
source$
}: {
source$: RxType.Observable<string>
}) {
ObservableHooks.useLayoutSubscription(source$, value => {
Scheduler.unstable_yieldValue(value)
})
Scheduler.unstable_yieldValue('render')
return null
}
const observableA = new Rx.BehaviorSubject('a-0')
const observableB = new Rx.BehaviorSubject('b-0')
let renderer: ReturnType<typeof ReactTestRenderer.create>
act(() => {
renderer = ReactTestRenderer.create(
<Subscription source$={observableA} />,
{ unstable_isConcurrent: true } as any
)
expect(Scheduler).toFlushAndYieldThrough(['render', 'a-0'])
})
act(() => {
renderer.update(<Subscription source$={observableB} />)
// useLayoutEffect runs synchronously
expect(Scheduler).toFlushAndYieldThrough(['render', 'b-0'])
observableA.next('a-1')
// observableA is ignored
expect(Scheduler).toFlushAndYield([])
observableA.next('a-2')
observableB.next('b-2')
// observableA is still ignored
expect(Scheduler).toHaveYielded(['b-2'])
Scheduler.unstable_flushAllWithoutAsserting()
})
act(() => {
renderer.update(<Subscription source$={observableA} />)
// useLayoutEffect runs synchronously
expect(Scheduler).toFlushAndYieldThrough(['render', 'a-2'])
observableB.next('b-3')
observableB.error(new Error('oops'))
// observableB is ignored
expect(Scheduler).toFlushAndYield([])
})
const observableC = new Rx.BehaviorSubject('c-0')
act(() => {
renderer.update(<Subscription source$={observableC} />)
// useLayoutEffect runs synchronously
expect(Scheduler).toFlushAndYieldThrough(['render', 'c-0'])
observableA.next('a-3')
observableA.complete()
// observableA is ignored
expect(Scheduler).toFlushAndYield([])
})
expect(Scheduler).toFlushWithoutYielding()
})
})
describe('useObservableState', () => {
it('should not tear if a mutation occurs during a concurrent update', () => {
jest.useFakeTimers()
const input$ = new Rx.Subject<string>()
const Subscriber = ({ id }: { id: string }) => {
const value = ObservableHooks.useObservableState(input$, 'A')
Scheduler.unstable_yieldValue(`render:${id}:${value}`)
return <>{value}</>
}
act(() => {
ReactTestRenderer.create(
<React.Fragment>
<Subscriber id="first" />
<Subscriber id="second" />
</React.Fragment>,
{ unstable_isConcurrent: true } as any
)
expect(Scheduler).toFlushAndYield(['render:first:A', 'render:second:A'])
// Update state "A" -> "B"
// This update will be eagerly evaluated,
// so the tearing case this test is guarding against would not happen.
input$.next('B')
expect(Scheduler).toFlushAndYield(['render:first:B', 'render:second:B'])
// No more pending updates
jest.runAllTimers()
// Partial update "B" -> "C"
// Interrupt with a second mutation "C" -> "D".
// This update will not be eagerly evaluated,
// but useObservableState() should eagerly close over the updated value to avoid tearing.
input$.next('C')
expect(Scheduler).toFlushAndYieldThrough(['render:first:C'])
input$.next('D')
expect(Scheduler).toFlushAndYield([
'render:second:C',
'render:first:D',
'render:second:D'
])
// No more pending updates
jest.runAllTimers()
})
})
})
describe('useObservableEagerState', () => {
it('should not tear if a mutation occurs during a concurrent update', () => {
jest.useFakeTimers()
const input$ = new Rx.BehaviorSubject('A')
const Subscriber = ({ id }: { id: string }) => {
const value = ObservableHooks.useObservableEagerState(input$)
Scheduler.unstable_yieldValue(`render:${id}:${value}`)
return <>{value}</>
}
act(() => {
ReactTestRenderer.create(
<React.Fragment>
<Subscriber id="first" />
<Subscriber id="second" />
</React.Fragment>,
{ unstable_isConcurrent: true } as any
)
expect(Scheduler).toFlushAndYield(['render:first:A', 'render:second:A'])
// Update state "A" -> "B"
// This update will be eagerly evaluated,
// so the tearing case this test is guarding against would not happen.
input$.next('B')
expect(Scheduler).toFlushAndYield(['render:first:B', 'render:second:B'])
// No more pending updates
jest.runAllTimers()
// Partial update "B" -> "C"
// Interrupt with a second mutation "C" -> "D".
// This update will not be eagerly evaluated,
// but useObservableState() should eagerly close over the updated value to avoid tearing.
input$.next('C')
expect(Scheduler).toFlushAndYieldThrough(['render:first:C'])
input$.next('D')
expect(Scheduler).toFlushAndYield([
'render:second:C',
'render:first:D',
'render:second:D'
])
// No more pending updates
jest.runAllTimers()
})
})
it('should ignore errors when the observable is changed but new subscription is not yet established', () => {
function Subscription({
source$
}: {
source$: RxType.Observable<string>
}) {
const state = ObservableHooks.useObservableEagerState(source$)
Scheduler.unstable_yieldValue(`render:${state}`)
return null
}
const observableA = new Rx.BehaviorSubject('a-0')
const observableB = new Rx.BehaviorSubject('b-0')
let renderer: ReturnType<typeof ReactTestRenderer.create>
act(() => {
renderer = ReactTestRenderer.create(
<Subscription source$={observableA} />,
{ unstable_isConcurrent: true } as any
)
})
expect(Scheduler).toHaveYielded(['render:a-0'])
act(() => {
renderer.update(<Subscription source$={observableB} />)
// Start React update, but don't finish
expect(Scheduler).toFlushAndYieldThrough(['render:a-0'])
observableA.next('a-1')
// observableA is ignored
expect(Scheduler).toFlushAndYield(['render:b-0'])
observableA.next('a-2')
observableB.next('b-2')
// observableA is still ignored
expect(Scheduler).toFlushAndYield(['render:b-2'])
})
act(() => {
renderer.update(<Subscription source$={observableA} />)
// Start React update, but don't finish
expect(Scheduler).toFlushAndYieldThrough(['render:b-2'])
observableB.next('b-3')
observableB.error(new Error('oops'))
// observableB is ignored
expect(Scheduler).toFlushAndYield(['render:a-2'])
})
})
})
describe('ObservableResource', () => {
it('should not tear if a mutation occurs during a concurrent update', () => {
jest.useFakeTimers()
const input$ = new Rx.BehaviorSubject<string>('A')
const resource = new ObservableHooks.ObservableResource(input$)
const Subscriber = ({ id }: { id: string }) => {
const value = ObservableHooks.useObservableSuspense(resource)
Scheduler.unstable_yieldValue(`render:${id}:${value}`)
return <>{value}</>
}
act(() => {
ReactTestRenderer.create(
<React.Fragment>
<Subscriber id="first" />
<Subscriber id="second" />
</React.Fragment>,
{ unstable_isConcurrent: true } as any
)
expect(Scheduler).toFlushAndYield(['render:first:A', 'render:second:A'])
// Update state "A" -> "B"
// This update will be eagerly evaluated,
// so the tearing case this test is guarding against would not happen.
input$.next('B')
expect(Scheduler).toFlushAndYield(['render:first:B', 'render:second:B'])
// No more pending updates
jest.runAllTimers()
// Partial update "B" -> "C"
// Interrupt with a second mutation "C" -> "D".
// This update will not be eagerly evaluated,
// but useObservableState() should eagerly close over the updated value to avoid tearing.
input$.next('C')
expect(Scheduler).toFlushAndYieldThrough(['render:first:C'])
input$.next('D')
expect(Scheduler).toFlushAndYield([
'render:second:C',
'render:first:D',
'render:second:D'
])
// No more pending updates
jest.runAllTimers()
})
})
})
}) | the_stack |
import HttpStatus from '@xpring-eng/http-status'
import * as request from 'supertest'
import 'mocha'
import App from '../../../../src/app'
import { adminApiVersions, payIdServerVersions } from '../../../../src/config'
import { AddressDetailsType } from '../../../../src/types/protocol'
import { appSetup, appCleanup } from '../../../helpers/helpers'
let app: App
const payIdApiVersion = adminApiVersions[0]
const payIdNextApiVersion = adminApiVersions[1]
const payIdProtocolVersion = payIdServerVersions[1]
const acceptPatch = 'application/merge-patch+json'
describe('E2E - adminApiRouter - PUT /users', function (): void {
before(async function () {
app = await appSetup()
})
it('Returns a 200 and updated user payload when updating an address', function (done): void {
// GIVEN a PayID known to resolve to an account on the PayID service
const payId = 'alice$xpring.money'
const updatedInformation = {
payId: 'alice$xpring.money',
addresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVZG1yJZf6QH85fPPRX1jswRYTZFg3H4um3Muu3S27SdJkr',
},
},
],
verifiedAddresses: [],
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${payId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN we expect back a 200-OK, with the updated user information
.expect(HttpStatus.OK, updatedInformation, done)
})
it('Returns a 200 and updated user payload when updating a verified address', function (done): void {
// GIVEN a PayID known to resolve to an account on the PayID service
const updatedInformation = {
payId: 'donaldduck$127.0.0.1',
addresses: [],
verifiedAddresses: [
{
paymentNetwork: 'XRPL',
environment: 'MAINNET',
details: {
address: 'rfvRiqhpZW1NURByu3iDsLVMT3zkzzMhJD',
},
identityKeySignature:
'bG9vayBhdCBtZSBJJ20gZW5jb2RpbiBnbW9yZSByYW5kb20gdHJhc2g=',
},
],
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${updatedInformation.payId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN we expect back a 200-OK, with the updated user information
.expect(HttpStatus.OK, updatedInformation, done)
})
it('Returns a 200 and updated user payload when updating a PayID', function (done): void {
// GIVEN a PayID known to resolve to an account on the PayID service
const payId = 'alice$xpring.money'
const updatedInformation = {
payId: 'charlie$xpring.money',
addresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVZG1yJZf6QH85fPPRX1jswRYTZFg3H4um3Muu3S27SdJkr',
},
},
],
verifiedAddresses: [],
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${payId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN we expect back a 200-OK, with the updated user information
.expect(HttpStatus.OK, updatedInformation, done)
})
it('Returns a 200 and updated user payload when removing all addresses', function (done): void {
// GIVEN a PayID known to resolve to an account on the PayID service
const payId = 'empty$xpring.money'
const updatedInformation = {
payId: 'empty$xpring.money',
addresses: [],
verifiedAddresses: [],
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${payId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect back a 200-OK, with the updated user information
.expect(HttpStatus.OK, updatedInformation, done)
})
it('Returns a 200 when updating a user with the canonical format', function (done): void {
// GIVEN a user with a PayID known to exist on the PayID service
const updatedInformation = {
payId: 'nextversion$127.0.0.1',
version: payIdProtocolVersion,
addresses: [
{
paymentNetwork: 'BTC',
environment: 'TESTNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: 'n4VQ5YdHf7hLQ2gWQYYrcxoE5B7nWuDFNF',
},
},
],
verifiedAddresses: [
{
payload: JSON.stringify({
payId: 'nextversion$127.0.0.1',
payIdAddress: {
paymentNetwork: 'XRPL',
environment: 'MAINNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: 'rBJwwXADHqbwsp6yhrqoyt2nmFx9FB83Th',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'eyJuYW1lIjoiaWRlbnRpdHlLZXkiLCJhbGciOiJFUzI1NksiLCJ0eXAiOiJKT1NFK0pTT04iLCJiNjQiOmZhbHNlLCJjcml0IjpbImI2NCIsIm5hbWUiXSwiandrIjp7ImNydiI6InNlY3AyNTZrMSIsIngiOiI2S0dtcEF6WUhWUm9qVmU5UEpfWTVyZHltQ21kTy1xaVRHem1Edl9waUlvIiwieSI6ImhxS3Vnc1g3Vjk3eFRNLThCMTBONUQxcW44MUZWMjItM1p0TURXaXZfSnciLCJrdHkiOiJFQyIsImtpZCI6Im4zNlhTc0M1TjRnNUtCVzRBWXJ5d1ZtRE1kUWNEV1BJX0RfNUR1UlNhNDAifX0',
signature:
'bG9vayBhdCBtZSBJIGp1c3QgdXBkYXRlZCB0aGlzIFBVVCBsZXRzIGdv',
},
],
},
],
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${updatedInformation.payId}`)
.set('PayID-API-Version', payIdNextApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect back a 200-OK, with the updated user information
// .expect(HttpStatus.OK, updatedInformation)
.end(function () {
request(app.adminApiExpress)
.get(`/users/${updatedInformation.payId}`)
.set('PayID-API-Version', payIdNextApiVersion)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN We expect back a 200 - OK, with the account information
.expect(HttpStatus.OK, updatedInformation, done)
})
})
it('Throws BadRequest error on invalid protected payload (identity key)', function (done): void {
// GIVEN a user with a PayID known to exist on the PayID service
const payId = 'johnwick$127.0.0.1'
const userInformation = {
payId,
addresses: [],
verifiedAddresses: [
{
payload: JSON.stringify({
payId,
payIdAddress: {
paymentNetwork: 'XRPL',
environment: 'TESTNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: 'rMwLfriHeWf5NMjcNKVMkqg58v1LYVRGnY',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'eiJKT1NFK0pTT04iLCJiNjQiOmZhbHNlLCJjcml0IjpbImI2NCIsIm5hbWUiXSwiandrIjp7ImNydiI6InNlY3AyNTZrMSIsIngiOiI2S0dtcEF6WUhWUm9qVmU5UEpfWTVyZHltQ21kTy1xaVRHem1Edl9waUlvIiwieSI6ImhxS3Vnc1g3Vjk3eFRNLThCMTBONUQxcW44MUZWMjItM1p0TURXaXZfSnciLCJrdHkiOiJFQyIsImtpZCI6Im4zNlhTc0M1TjRnNUtCVzRBWXJ5d1ZtRE1kUWNEV1BJX0RfNUR1UlNhNDAifX0',
signature: 'Z2V0IGxvdy4uIHdlaGVyIGV5b3UgZnJvbSBteSBib3kgYXNqZGFr',
},
],
},
],
}
// AND our expected error response
const expectedErrorResponse = {
statusCode: 400,
error: 'Bad Request',
message: 'Invalid JSON for protected payload (identity key).',
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${payId}`)
.set('PayID-API-Version', payIdNextApiVersion)
.send(userInformation)
.expect('Content-Type', /json/u)
// THEN We expect back a 400 - Bad Request, with the expected error response object
.expect(HttpStatus.BadRequest, expectedErrorResponse, done)
})
it('Throws BadRequest error on multiple identity keys per PayID', function (done): void {
// GIVEN a user with a PayID known to exist on the PayID service
const payId = 'johnwick$127.0.0.1'
const userInformation = {
payId,
addresses: [],
verifiedAddresses: [
{
payload: JSON.stringify({
payId,
payIdAddress: {
paymentNetwork: 'XRPL',
environment: 'TESTNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: 'rMwLfriHeWf5NMjcNKVMkqg58v1LYVRGnY',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'eyJuYW1lIjoiaWRlbnRpdHlLZXkiLCJhbGciOiJFUzI1NksiLCJ0eXAiOiJKT1NFK0pTT04iLCJiNjQiOmZhbHNlLCJjcml0IjpbImI2NCIsIm5hbWUiXSwiandrIjp7ImNydiI6InNlY3AyNTZrMSIsIngiOiI2S0dtcEF6WUhWUm9qVmU5UEpfWTVyZHltQ21kTy1xaVRHem1Edl9waUlvIiwieSI6ImhxS3Vnc1g3Vjk3eFRNLThCMTBONUQxcW44MUZWMjItM1p0TURXaXZfSnciLCJrdHkiOiJFQyIsImtpZCI6Im4zNlhTc0M1TjRnNUtCVzRBWXJ5d1ZtRE1kUWNEV1BJX0RfNUR1UlNhNDAifX0',
signature: 'Z2V0IGxvdy4uIHdlaGVyIGV5b3UgZnJvbSBteSBib3kgYXNqZGFr',
},
],
},
{
payload: JSON.stringify({
payId,
payIdAddress: {
paymentNetwork: 'XRPL',
environment: 'MAINNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: 'rsem3MPogcwLCD6iX34GQ4fAp4EC8kqMYM',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'eyJuYW1lIjoiaWRlbnRpdHlLZXkiLCJhbGciOiJFUzI1NksiLCJ0eXAiOiJKT1NFK0pTT04iLCJiNjQiOmZhbHNlLCJjcml0IjpbImI2NCIsIm5hbWUiXSwiandrIjp7ImNydiI6InNlY3AyNTZrMSIsIngiOiJKcXNXZk1QSmNsU1JISWRtS3U0cl84MktPRXdERjctOU1XeWFYcjNkSGl3IiwieSI6IkMxZm5sQndUMmZtNzN1OGxweEhlc0NiX0xobEx2aktoeTRGN05ZdWpDR0EiLCJrdHkiOiJFQyIsImtpZCI6IlRZSlNCb05FSDVHYzVDQ0hyc3pfMVM0RHhwNk9SZVhIWlQ5bmZiYXQ3YTAifX0',
signature: 'Z2V0IGxvdy4uIHdlaGVyIGV5b3UgZnJvbSBteSBib3kgYXNqZGFr',
},
],
},
],
}
// AND our expected error response
const expectedErrorResponse = {
statusCode: 400,
error: 'Bad Request',
message:
'More than one identity key detected. Only one identity key per PayID can be used.',
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${payId}`)
.set('PayID-API-Version', payIdNextApiVersion)
.send(userInformation)
.expect('Content-Type', /json/u)
// THEN We expect back a 400 - Bad Request, with the expected error response object
.expect(HttpStatus.BadRequest, expectedErrorResponse, done)
})
it('Throws BadRequest error on multiple identity keys per address', function (done): void {
// GIVEN a user with a PayID known to exist on the PayID service
const payId = 'verified$127.0.0.1'
const userInformation = {
payId,
addresses: [],
verifiedAddresses: [
{
payload: JSON.stringify({
payId,
payIdAddress: {
paymentNetwork: 'XRPL',
environment: 'TESTNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: 'rMwLfriHeWf5NMjcNKVMkqg58v1LYVRGnY',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'eyJuYW1lIjoiaWRlbnRpdHlLZXkiLCJhbGciOiJFUzI1NksiLCJ0eXAiOiJKT1NFK0pTT04iLCJiNjQiOmZhbHNlLCJjcml0IjpbImI2NCIsIm5hbWUiXSwiandrIjp7ImNydiI6InNlY3AyNTZrMSIsIngiOiI2S0dtcEF6WUhWUm9qVmU5UEpfWTVyZHltQ21kTy1xaVRHem1Edl9waUlvIiwieSI6ImhxS3Vnc1g3Vjk3eFRNLThCMTBONUQxcW44MUZWMjItM1p0TURXaXZfSnciLCJrdHkiOiJFQyIsImtpZCI6Im4zNlhTc0M1TjRnNUtCVzRBWXJ5d1ZtRE1kUWNEV1BJX0RfNUR1UlNhNDAifX0',
signature: 'Z2V0IGxvdy4uIHdlaGVyIGV5b3UgZnJvbSBteSBib3kgYXNqZGFr',
},
{
name: 'identityKey',
protected:
'eyJuYW1lIjoiaWRlbnRpdHlLZXkiLCJhbGciOiJFUzI1NksiLCJ0eXAiOiJKT1NFK0pTT04iLCJiNjQiOmZhbHNlLCJjcml0IjpbImI2NCIsIm5hbWUiXSwiandrIjp7ImNydiI6InNlY3AyNTZrMSIsIngiOiI2S0dtcEF6WUhWUm9qVmU5UEpfWTVyZHltQ21kTy1xaVRHem1Edl9waUlvIiwieSI6ImhxS3Vnc1g3Vjk3eFRNLThCMTBONUQxcW44MUZWMjItM1p0TURXaXZfSnciLCJrdHkiOiJFQyIsImtpZCI6Im4zNlhTc0M1TjRnNUtCVzRBWXJ5d1ZtRE1kUWNEV1BJX0RfNUR1UlNhNDAifX0',
signature: 'd2Fsa2luZyB0aG91Z2ggdGhlIHNyZWV3dCB3aWggbXkgdDQ0',
},
],
},
],
}
// AND our expected error response
const expectedErrorResponse = {
statusCode: 400,
error: 'Bad Request',
message:
'More than one identity key detected. Only one identity key per address can be used.',
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${payId}`)
.set('PayID-API-Version', payIdNextApiVersion)
.send(userInformation)
.expect('Content-Type', /json/u)
// THEN We expect back a 400 - Bad Request, with the expected error response object
.expect(HttpStatus.BadRequest, expectedErrorResponse, done)
})
it('Returns a 201 and inserted user payload for a Admin API PUT creating a new user', function (done): void {
// GIVEN a PayID known to not exist on the PayID service
const payId = 'notjohndoe$xpring.money'
const insertedInformation = {
payId: 'johndoe$xpring.money',
addresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVZG1yJZf6QH85fPPRX1jswRYTZFg3H4um3Muu3S27SdJkr',
},
},
],
verifiedAddresses: [],
}
// WHEN we make a PUT request to /users/ with the information to insert
request(app.adminApiExpress)
.put(`/users/${payId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(insertedInformation)
.expect('Content-Type', /json/u)
// THEN we expect the Location header to be set to the path of the created user resource
// Note that the PayID inserted is that of the request body, not the URL path
.expect('Location', `/users/${insertedInformation.payId}`)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// AND we expect back a 201 - CREATED, with the inserted user information
.expect(HttpStatus.Created, insertedInformation, done)
})
it('Returns a 201 and inserted user payload for a Admin API PUT creating a new user with an uppercase PayID provided', function (done): void {
// GIVEN a PayID known to not exist on the PayID service
const payId = 'notjohndoe$xpring.money'
const newPayId = 'johnsmith$xpring.money'
const insertedInformation = {
payId: newPayId.toUpperCase(),
addresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVZG1yJZf6QH85fPPRX1jswRYTZFg3H4um3Muu3S27SdJkr',
},
},
],
verifiedAddresses: [],
}
// WHEN we make a PUT request to /users/ with the information to insert
request(app.adminApiExpress)
.put(`/users/${payId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(insertedInformation)
.expect('Content-Type', /json/u)
// THEN we expect the Location header to be set to the path of the created user resource
// Note that the PayID inserted is that of the request body, not the URL path, and we expect a lowercase response
.expect('Location', `/users/${newPayId}`)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// AND we expect back a 201 - CREATED, with the inserted user information (but the PayID lowercased)
.expect(
HttpStatus.Created,
{ ...insertedInformation, ...{ payId: newPayId } },
done,
)
})
it('Returns a 201 when creating a new user with verifiedAddresses', function (done): void {
// GIVEN a user with a PayID known to not exist on the PayID service
const userInformation = {
payId: 'harrypotter$xpring.money',
addresses: [
{
paymentNetwork: 'BTC',
environment: 'TESTNET',
details: {
address: 'mxNEbRXokcdJtT6sbukr1CTGVx8Tkxk3DB',
},
},
],
verifiedAddresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVQWr6BhgBLW2jbFyqqufgq8T9eN7KresB684ZSHKQ3oDth',
},
identityKeySignature:
'd2hhdCBhbSBJIGNvZGluZyB3aGF0IGlzIGxpZmUgcGxlYXNlIGhlbHA=',
},
],
}
// WHEN we make a POST request to /users with that user information
request(app.adminApiExpress)
.put(`/users/${userInformation.payId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(userInformation)
// THEN we expect the Location header to be set to the path of the created user resource
.expect('Location', `/users/${userInformation.payId}`)
// THEN we expect back a 201 - CREATED
.expect(HttpStatus.Created)
.end(function () {
request(app.adminApiExpress)
.get(`/users/${userInformation.payId}`)
.set('PayID-API-Version', payIdApiVersion)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN We expect back a 200 - OK, with the account information
.expect(HttpStatus.OK, userInformation, done)
})
})
it('Returns a 400 - Bad Request with an error payload for a request with a malformed PayID', function (done): void {
// GIVEN a PayID known to be in a bad format (missing $) and an expected error response payload
const badPayId = 'alice.xpring.money'
const expectedErrorResponse = {
error: 'Bad Request',
message: 'Bad input. PayIDs must contain a "$"',
statusCode: 400,
}
const updatedInformation = {
payId: 'alice$xpring.money',
addresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVZG1yJZf6QH85fPPRX1jswRYTZFg3H4um3Muu3S27SdJkr',
},
},
],
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${badPayId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN we expect back a 400 - Bad Request, with the expected error payload response
.expect(HttpStatus.BadRequest, expectedErrorResponse, done)
})
it('Returns a 400 - Bad Request with an error payload for a request with an existing PayID with multiple "$"', function (done): void {
// GIVEN a PayID known to be in a bad format (multiple $) and an expected error response payload
const badPayId = 'alice$bob$xpring.money'
const expectedErrorResponse = {
error: 'Bad Request',
message: 'Bad input. PayIDs must contain only one "$"',
statusCode: 400,
}
const updatedInformation = {
payId: 'alice$xpring.money',
addresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVZG1yJZf6QH85fPPRX1jswRYTZFg3H4um3Muu3S27SdJkr',
},
},
],
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${badPayId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN we expect back a 400 - Bad Request, with the expected error payload response
.expect(HttpStatus.BadRequest, expectedErrorResponse, done)
})
it('Returns a 400 - Bad Request with an error payload for a request to update a PayID to a new value containing multiple "$"', function (done): void {
// GIVEN a PayID known to be in a bad format (missing $) and an expected error response payload
const badPayId = 'alice$xpring.money'
const expectedErrorResponse = {
error: 'Bad Request',
message: 'Bad input. PayIDs must contain only one "$"',
statusCode: 400,
}
const updatedInformation = {
payId: 'alice$bob$xpring.money',
addresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVZG1yJZf6QH85fPPRX1jswRYTZFg3H4um3Muu3S27SdJkr',
},
},
],
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${badPayId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN we expect back a 400 - Bad Request, with the expected error payload response
.expect(HttpStatus.BadRequest, expectedErrorResponse, done)
})
it('Returns a 409 - Conflict when attempting to update a user to a PayID that already exists', function (done): void {
// GIVEN a PayID known to resolve to an account on the PayID service
const payId = 'charlie$xpring.money'
const updatedInformation = {
// AND a request to update that PayID to one known to already exist on the PayID Service
payId: 'bob$xpring.money',
addresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVZG1yJZf6QH85fPPRX1jswRYTZFg3H4um3Muu3S27SdJkr',
},
},
],
}
// AND our expected error response
const expectedErrorResponse = {
statusCode: 409,
error: 'Conflict',
message: 'There already exists a user with the provided PayID',
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${payId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN we expect back a 409 - CONFLICT and our expected error response
.expect(HttpStatus.Conflict, expectedErrorResponse, done)
})
it('Returns a 409 - Conflict when attempting to PUT a new user to a PayID that already exists', function (done): void {
// GIVEN a PayID known to not resolve to an account on the PayID service
const payId = 'janedoe$xpring.money'
// AND a request to update that PayID to one known to already exist on the PayID Service
const updatedInformation = {
payId: 'bob$xpring.money',
addresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVZG1yJZf6QH85fPPRX1jswRYTZFg3H4um3Muu3S27SdJkr',
},
},
],
}
// AND our expected error response
const expectedErrorResponse = {
statusCode: 409,
error: 'Conflict',
message: 'There already exists a user with the provided PayID',
}
// WHEN we make a PUT request to /users/ with the new information to update
request(app.adminApiExpress)
.put(`/users/${payId}`)
.set('PayID-API-Version', payIdApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN we expect back a 409 - CONFLICT and our expected error response
.expect(HttpStatus.Conflict, expectedErrorResponse, done)
})
it('Returns a 415 - Unsupported Media Type when sending a wrong Content-Type header', function (done): void {
// GIVEN a PayID known to resolve to an account on the PayID service
const payId = 'alice$xpring.money'
// We need to send the body as a String if Content-Type is not application/json.
// Otherwise an error ERR_INVALID_ARG_TYPE will be thrown by Supertest in the send() method.
const updatedInformation = `{
payId: 'alice$xpring.money',
addresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVZG1yJZf6QH85fPPRX1jswRYTZFg3H4um3Muu3S27SdJkr',
},
},
],
}`
// AND our expected error response
const expectedErrorResponse = {
statusCode: 415,
error: 'Unsupported Media Type',
message:
"A 'Content-Type' header is required for this request: 'Content-Type: application/json'.",
}
// WHEN we make a PUT request to /users/:payId with that updated user information
request(app.adminApiExpress)
.put(`/users/${payId}`)
// WITH a wrong Content-Type
.set('Content-Type', 'application/xml')
.set('PayID-API-Version', payIdApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN we expect back a 415 - Unsupported Media Type and our expected error response
.expect(HttpStatus.UnsupportedMediaType, expectedErrorResponse, done)
})
it('Returns a 415 - Unsupported Media Type when Content-Type header is missing', function (done): void {
// GIVEN a PayID known to resolve to an account on the PayID service
const payId = 'alice$xpring.money'
// We need to send the body as a String if Content-Type is not sent.
// Otherwise Supertest will automatically add a "Content-Type: application/json" header.
const updatedInformation = `{
payId: 'alice$xpring.money',
addresses: [
{
paymentNetwork: 'XRPL',
environment: 'TESTNET',
details: {
address: 'TVZG1yJZf6QH85fPPRX1jswRYTZFg3H4um3Muu3S27SdJkr',
},
},
],
}`
// AND our expected error response
const expectedErrorResponse = {
statusCode: 415,
error: 'Unsupported Media Type',
message:
"A 'Content-Type' header is required for this request: 'Content-Type: application/json'.",
}
// WHEN we make a PUT request to /users/:payId with that updated user information
request(app.adminApiExpress)
.put(`/users/${payId}`)
// WITHOUT a Content-Type
.set('PayID-API-Version', payIdApiVersion)
.send(updatedInformation)
.expect('Content-Type', /json/u)
// THEN we expect to have an Accept-Patch header in the response
.expect('Accept-Patch', acceptPatch)
// THEN we expect back a 415 - Unsupported Media Type and our expected error response
.expect(HttpStatus.UnsupportedMediaType, expectedErrorResponse, done)
})
after(function () {
appCleanup(app)
})
}) | the_stack |
import { ISPListItems, ISPListItem } from './ISPList';
import { IWebPartContext } from '@microsoft/sp-webpart-base';
import { ISimplePollWebPartProps } from './ISimplePollWebPartProps';
import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions } from '@microsoft/sp-http';
import MockHttpClient from './MockHttpClient';
/**
* @interface
* Service interface definition
*/
export interface ISPSurveyService {
/**
* @function
* Gets the question from a SharePoint list
*/
getQuestions(libId: string): Promise<ISPListItems>;
getResults(surveyListId: string, question: string, choices: string[]): Promise<number[]>;
postVote(surveyListId: string, question: string, choice: string): Promise<boolean>;
}
/**
* @class
* Service implementation to get list & list items from current SharePoint site
*/
export class SPSurveyService implements ISPSurveyService {
private context: IWebPartContext;
private props: ISimplePollWebPartProps;
/**
* @function
* Service constructor
*/
constructor(_props: ISimplePollWebPartProps, pageContext: IWebPartContext){
this.props = _props;
this.context = pageContext;
}
public getResults(surveyListId: string, question: string, choices: string[]): Promise<number[]> {
var restUrl: string = this.context.pageContext.web.absoluteUrl;
restUrl += "/_api/Web/Lists(guid'";
restUrl += surveyListId;
restUrl += "')/items?$select=" + question + "&$top=9999";
return this.context.spHttpClient.get(restUrl, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
return response.json().then((responseFormated: any) => {
var res: number[] = [];
for (var c = 0; c < choices.length; c++)
res[c] = 0;
var collection = responseFormated.value;
for (var i = 0; i < collection.length; i++) {
var vote = collection[i][question];
var qIndex = choices.indexOf(vote);
res[qIndex]++;
}
return res;
});
}) as Promise<number[]>;
}
public postVote(surveyListId: string, question: string, choice: string): Promise<boolean> {
return this.getListName(surveyListId).then((listName: string) => {
var restUrl: string = this.context.pageContext.web.absoluteUrl;
restUrl += "/_api/Web/Lists(guid'";
restUrl += surveyListId;
restUrl += "')/items";
var item = {
"__metadata": { "type": this.getItemTypeForListName(listName) },
"Title": "newItemTitle"
};
item[question] = choice;
var options: ISPHttpClientOptions = {
headers: {
"odata-version": "3.0",
"Accept": "application/json"
},
body: JSON.stringify(item),
webUrl: this.context.pageContext.web.absoluteUrl
};
return this.context.spHttpClient.post(restUrl, SPHttpClient.configurations.v1, options).then((response: SPHttpClientResponse) => {
return response.json().then((responseFormated: any) => {
return true;
});
}) as Promise<boolean>;
}) as Promise<boolean>;
}
private getListName(listId: string): Promise<string> {
var restUrl: string = this.context.pageContext.web.absoluteUrl;
restUrl += "/_api/Web/Lists(guid'";
restUrl += listId;
restUrl += "')?$select=Title";
var options: ISPHttpClientOptions = {
headers: {
"odata-version": "3.0",
"Accept": "application/json"
}
};
return this.context.spHttpClient.get(restUrl, SPHttpClient.configurations.v1, options).then((response: SPHttpClientResponse) => {
return response.text().then((responseFormated: string) => {
var iTitle = responseFormated.indexOf("<d:Title>");
var newStr = responseFormated.slice(iTitle + 9, responseFormated.length);
newStr = newStr.slice(0, newStr.indexOf("</d:Title>"));
return newStr;
});
});
}
private getItemTypeForListName(name: string): string {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
public getVoteForUser(surveyListId: string, question: string, userEmail: string): Promise<ISPListItems> {
var restUrl: string = this.context.pageContext.web.absoluteUrl;
restUrl += "/_api/Web/Lists(guid'";
restUrl += surveyListId;
restUrl += "')/items?$expand=Author&$select=" + question + ",Author/EMail&$top=999";
return this.context.spHttpClient.get(restUrl, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
return response.json().then((responseFormated: any) => {
var formatedResponse: ISPListItems = { value: []};
//Fetchs the Json response to construct the final items list
responseFormated.value.map((object: any, i: number) => {
var authorEmail = object['Author'].EMail;
if (authorEmail == userEmail) {
var spListItem: ISPListItem = {
'ID': '',
'Title': object[question]
};
formatedResponse.value.push(spListItem);
}
});
return formatedResponse;
});
}) as Promise<ISPListItems>;
}
/**
* @function
* Gets the survey questions from a SharePoint list
*/
public getQuestions(surveyListId: string): Promise<ISPListItems> {
if (Environment.type === EnvironmentType.Local) {
//If the running environment is local, load the data from the mock
return this.getItemsFromMock('1');
}
else {
//Request the SharePoint web service
var restUrl: string = this.context.pageContext.web.absoluteUrl;
restUrl += "/_api/Web/Lists(guid'";
restUrl += surveyListId;
restUrl += "')/fields?$filter=(CanBeDeleted%20eq%20true)&$top=1";
return this.context.spHttpClient.get(restUrl, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
return response.json().then((responseFormated: any) => {
var formatedResponse: ISPListItems = { value: []};
//Fetchs the Json response to construct the final items list
responseFormated.value.map((object: any, i: number) => {
//Tests if the result is a file and not a folder
var spListItem: ISPListItem = {
'ID': object["ID"],
'Title': object['Title'],
'StaticName': object['StaticName'],
'TypeAsString': object['TypeAsString'],
'Choices': object['Choices']
};
formatedResponse.value.push(spListItem);
});
return formatedResponse;
});
}) as Promise<ISPListItems>;
}
}
/**
* @function
* Gets the pictures list from the mock. This function will return a
* different list of pics for the lib 1 & 2, and an empty list for the third.
*/
private getItemsFromMock(libId: string): Promise<ISPListItems> {
return MockHttpClient.getListsItems(this.context.pageContext.web.absoluteUrl).then(() => {
var listData: ISPListItems = { value: []};
if (libId == '1') {
listData = {
value:
[
{
"ID": "1", "Title": "Barton Dam, Ann Arbor, Michigan", "Description": ""
},
{
"ID": "2", "Title": "Building Atlanta, Georgia", "Description": ""
},
{
"ID": "3", "Title": "Nice day for a swim", "Description": ""
},
{
"ID": "4", "Title": "The plants that never die", "Description": ""
},
{
"ID": "5", "Title": "Downtown Atlanta, Georgia", "Description": ""
},
{
"ID": "6", "Title": "Atlanta traffic", "Description": ""
},
{
"ID": "7", "Title": "A pathetic dog", "Description": ""
},
{
"ID": "8", "Title": "Two happy dogs", "Description": ""
},
{
"ID": "9", "Title": "Antigua, Guatemala", "Description": ""
},
{
"ID": "10", "Title": "Iximche, Guatemala", "Description": ""
}
]
};
}
else if (libId == '2') {
listData = {
value:
[
{
"ID": "11", "Title": "Barton Dam, Ann Arbor, Michigan", "Description": ""
},
{
"ID": "12", "Title": "Building Atlanta, Georgia", "Description": ""
},
{
"ID": "13", "Title": "Nice day for a swim", "Description": ""
},
{
"ID": "14", "Title": "The plants that never die", "Description": ""
},
{
"ID": "15", "Title": "Downtown Atlanta, Georgia", "Description": ""
},
{
"ID": "16", "Title": "Atlanta traffic", "Description": ""
},
{
"ID": "17", "Title": "A pathetic dog", "Description": ""
},
{
"ID": "18", "Title": "Two happy dogs", "Description": ""
},
{
"ID": "19", "Title": "Antigua, Guatemala", "Description": ""
},
{
"ID": "20", "Title": "Iximche, Guatemala", "Description": ""
}
]
};
}
return listData;
}) as Promise<ISPListItems>;
}
} | the_stack |
import { Trans, DateFormat } from "@lingui/macro";
import classNames from "classnames";
import isEqual from "lodash.isequal";
import PropTypes from "prop-types";
import * as React from "react";
import { Link } from "react-router";
import { Tooltip } from "@dcos/ui-kit";
import { Icon } from "@dcos/ui-kit";
import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum";
import {
greyLightDarken1,
iconSizeXs,
} from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";
import CheckboxTable from "#SRC/js/components/CheckboxTable";
import CollapsingString from "#SRC/js/components/CollapsingString";
import ExpandingTable, { RowOptions } from "#SRC/js/components/ExpandingTable";
import TimeAgo from "#SRC/js/components/TimeAgo";
import Units from "#SRC/js/utils/Units";
import TableUtil from "#SRC/js/utils/TableUtil";
import DateUtil from "#SRC/js/utils/DateUtil";
import Pod from "../../structs/Pod";
import PodInstance from "../../structs/PodInstance";
import PodSpec from "../../structs/PodSpec";
import PodUtil from "../../utils/PodUtil";
import InstanceUtil from "../../utils/InstanceUtil";
import PodTableHeaderLabels from "../../constants/PodTableHeaderLabels";
const tableColumnClasses = {
checkbox: "task-table-column-checkbox",
name: "task-table-column-primary",
address: "task-table-column-host-address",
zone: "task-table-column-zone",
region: "task-table-column-region",
status: "task-table-column-status",
health: "task-table-column-health",
logs: "task-table-column-logs",
cpus: "task-table-column-cpus",
mem: "task-table-column-mem",
updated: "task-table-column-updated",
version: "task-table-column-version",
};
class PodInstancesTable extends React.Component<{
filterText: string;
instances: PodInstance[];
onSelectionChange: (a: {}) => void;
pod: Pod;
}> {
static defaultProps = {
filterText: "",
instances: null,
inverseStyle: false,
onSelectionChange() {},
pod: null,
};
static propTypes = {
filterText: PropTypes.string,
instances: PropTypes.instanceOf(Array),
inverseStyle: PropTypes.bool,
onSelectionChange: PropTypes.func,
pod: PropTypes.instanceOf(Pod).isRequired,
};
state = { checkedItems: {} };
UNSAFE_componentWillReceiveProps(nextProps) {
const { checkedItems } = this.state;
const prevInstances = this.props.instances;
const nextInstances = nextProps.instances;
// When the `instances` property is changed and we have selected
// items, re-trigger selection change in order to remove checked
// entries that are no longer present.
if (!isEqual(prevInstances, nextInstances)) {
this.triggerSelectionChange(checkedItems, nextProps.instances);
}
}
triggerSelectionChange(checkedItems: {}, instances: PodInstance[]) {
const checkedItemInstances = instances.filter(
(item) => checkedItems[item.getId()]
);
this.props.onSelectionChange(checkedItemInstances);
}
handleItemCheck = (idsChecked: number[]) => {
const checkedItems = {};
idsChecked.forEach((id) => {
checkedItems[id] = true;
});
this.setState({ checkedItems });
this.triggerSelectionChange(checkedItems, this.props.instances);
};
getColGroup = () => {
return (
<colgroup>
<col className={tableColumnClasses.checkbox} />
<col />
<col className={tableColumnClasses.address} />
<col className={tableColumnClasses.zone} />
<col className={tableColumnClasses.region} />
<col className={tableColumnClasses.status} />
<col className={tableColumnClasses.health} />
<col className={tableColumnClasses.logs} />
<col className={tableColumnClasses.cpus} />
<col className={tableColumnClasses.mem} />
<col className={tableColumnClasses.updated} />
<col className={tableColumnClasses.version} />
</colgroup>
);
};
getColumnHeading(prop, order, sortBy) {
const caretClassNames = classNames("caret", {
[`caret--${order}`]: order != null,
"caret--visible": prop === sortBy.prop,
});
return (
<span>
<Trans render="span" id={PodTableHeaderLabels[prop]} />
<span className={caretClassNames} />
</span>
);
}
getColumnClassName(prop, sortBy, row) {
return classNames(tableColumnClasses[prop], {
active: prop === sortBy.prop,
clickable: row == null,
});
}
getColumns() {
const sortTieBreaker = "name";
return [
{
className: this.getColumnClassName,
heading: this.getColumnHeading,
prop: "name",
render: this.renderColumnID,
sortable: true,
},
{
className: this.getColumnClassName,
heading: this.getColumnHeading,
prop: "address",
render: this.renderColumnAddress,
sortable: true,
},
{
className: this.getColumnClassName,
heading: this.getColumnHeading,
prop: "region",
render: this.renderRegion,
sortable: true,
sortFunction: TableUtil.getSortFunction(sortTieBreaker, (instance) =>
InstanceUtil.getRegionName(instance)
),
},
{
className: this.getColumnClassName,
heading: this.getColumnHeading,
prop: "zone",
render: this.renderZone,
sortable: true,
sortFunction: TableUtil.getSortFunction(sortTieBreaker, (instance) =>
InstanceUtil.getZoneName(instance)
),
},
{
className: this.getColumnClassName,
heading: this.getColumnHeading,
prop: "status",
render: this.renderColumnStatus,
sortable: true,
},
{
className: this.getColumnClassName,
heading: this.getColumnHeading,
prop: "health",
render: this.renderColumnHealth,
sortable: true,
},
{
className: this.getColumnClassName,
heading: this.getColumnHeading,
prop: "logs",
render: this.renderColumnLogs,
sortable: false,
},
{
className: this.getColumnClassName,
heading: this.getColumnHeading,
prop: "cpus",
render: this.renderColumnResource,
sortable: true,
},
{
className: this.getColumnClassName,
heading: this.getColumnHeading,
prop: "mem",
render: this.renderColumnResource,
sortable: true,
},
{
className: this.getColumnClassName,
heading: this.getColumnHeading,
prop: "updated",
render: this.renderColumnUpdated,
sortable: true,
},
{
className: this.getColumnClassName,
heading: this.getColumnHeading,
prop: "version",
render: this.renderColumnVersion,
sortable: true,
},
];
}
getContainersWithResources(podSpec: PodSpec, containers, agentAddress) {
return containers.map((container) => {
let containerResources = container.getResources();
// TODO: Remove the following 4 lines when DCOS-10098 is addressed
const containerSpec = podSpec
.getContainers()
.find(({ name }) => container.name === name);
containerResources = containerSpec?.resources ?? containerResources;
const addressComponents = container.getEndpoints().map((endpoint, i) => [
<a
className="text-muted"
href={`http://${agentAddress}:${endpoint.allocatedHostPort}`}
key={i}
target="_blank"
title="Open in a new window"
>
{endpoint.allocatedHostPort}
</a>,
" ",
]);
return {
id: container.getId(),
name: container.getName(),
status: container.getContainerStatus(),
address: addressComponents,
cpus: containerResources.cpus,
mem: containerResources.mem,
resourceLimits:
containerSpec?.resourceLimits || containerSpec?.resources || {},
updated: container.getLastUpdated(),
version: "",
isHistoricalInstance: container.isHistoricalInstance,
};
});
}
getDisabledItemsMap(instances) {
return instances.reduce((acc, instance) => {
if (!instance.isRunning()) {
acc[instance.getId()] = true;
}
return acc;
}, {});
}
getTableDataFor(instances: PodInstance[], filterText) {
const podSpec = this.props.pod.getSpec();
return instances.map((instance) => {
const containers = instance
.getContainers()
.filter((container) =>
PodUtil.isContainerMatchingText(container, filterText)
);
const children = this.getContainersWithResources(
podSpec,
containers,
instance.getAgentAddress()
);
const { cpus, mem } = instance.getResources();
return {
id: instance.getId(),
name: instance.getName(),
address: instance.getAgentAddress(),
agentId: instance.agentId,
cpus,
mem,
updated: instance.getLastUpdated(),
status: instance.getInstanceStatus(),
version: podSpec.getVersion(),
resourceLimits: { cpu: 0, mem: 0 },
children,
podSpec,
};
});
}
renderWithClickHandler(rowOptions: RowOptions, content, className?) {
return (
<div onClick={rowOptions.clickHandler} className={className}>
{content}
</div>
);
}
renderColumnID = (_prop, col, rowOptions: RowOptions) => {
const { id: taskID, name: taskName } = col;
if (!rowOptions.isParent) {
const id = encodeURIComponent(this.props.pod.getId());
return (
<div className="expanding-table-primary-cell-heading text-overflow">
<Link
className="table-cell-link-secondary text-overflow"
to={`/services/detail/${id}/tasks/${taskID}`}
title={taskName}
>
<CollapsingString string={taskName} />
</Link>
</div>
);
}
const classes = classNames("expanding-table-primary-cell is-expandable", {
"is-expanded": rowOptions.isExpanded,
});
return this.renderWithClickHandler(
rowOptions,
<CollapsingString string={taskID} />,
classes
);
};
renderColumnLogs = (_prop, row, rowOptions: RowOptions) => {
if (rowOptions.isParent) {
// Because elements are just stacked we need a spacer
return <span> </span>;
}
const id = encodeURIComponent(this.props.pod.getId());
const taskID = row.id;
return (
<Link to={`/services/detail/${id}/tasks/${taskID}/logs`} title={row.name}>
<Icon
color={greyLightDarken1}
shape={SystemIcons.PageDocument}
size={iconSizeXs}
/>
</Link>
);
};
renderColumnAddress = (_prop, row, rowOptions: RowOptions) => {
const { address } = row;
if (rowOptions.isParent) {
const { agentId } = row;
if (!agentId) {
return this.renderWithClickHandler(
rowOptions,
<CollapsingString string={address} />
);
}
return this.renderWithClickHandler(
rowOptions,
<Link
className="table-cell-link-secondary text-overflow"
to={`/nodes/${agentId}`}
title={address}
>
<CollapsingString string={address} />
</Link>
);
}
return this.renderWithClickHandler(rowOptions, address);
};
renderColumnStatus = (_prop, row, rowOptions: RowOptions) => {
const { status } = row;
return this.renderWithClickHandler(
rowOptions,
<Trans
id={status.displayName}
render="span"
className={`status-text ${status.textClassName}`}
/>
);
};
renderColumnHealth = (prop, row, rowOptions: RowOptions) => {
const { status } = row;
const { healthStatus } = status;
let tooltipContent = <Trans render="span">Healthy</Trans>;
if (healthStatus === "UNHEALTHY") {
tooltipContent = <Trans render="span">Unhealthy</Trans>;
}
if (healthStatus === "NA") {
tooltipContent = <Trans render="span">No health checks available</Trans>;
}
const trigger = (
<span className={classNames("flush", status.dotClassName)} />
);
return this.renderWithClickHandler(
rowOptions,
<div className="flex-box flex-box-align-vertical-center table-cell-flex-box flex-align-items-center flex-direction-top-to-bottom">
<div className="table-cell-icon">
<Tooltip id={row.id + prop} trigger={trigger}>
{tooltipContent}
</Tooltip>
</div>
</div>
);
};
// TODO rendering for pods
renderColumnResource = (prop, row, rowOptions: RowOptions) => {
if (rowOptions.isParent) {
const executorResource = row.podSpec?.executorResources?.[prop] ?? 0;
const childResources = row.children.filter(
(child) => !child.isHistoricalInstance
);
const requests = childResources.reduce(
(sum, current) => sum + (current[prop] || 0),
0
);
const limits = childResources.reduce(
(sum, current) =>
sum + (current.resourceLimits[prop] || current[prop] || 0),
0
);
const containerMsg =
requests === limits
? Units.formatResource(prop, requests)
: `${Units.formatResource(prop, requests)} guaranteed
with a limit of ${Units.formatResource(prop, limits)}`;
const trigger_ = Units.formatResources(
prop,
requests + executorResource,
limits + executorResource
);
return this.renderWithClickHandler(
rowOptions,
<Tooltip
id={row.id + prop}
trigger={trigger_}
preferredDirections={["top-right"]}
>
<Trans render="span">
Containers: {containerMsg}, Executor:{" "}
{Units.formatResource(prop, executorResource)}
</Trans>
</Tooltip>
);
}
const request = Units.formatResource(prop, row[prop]);
const limit = Units.formatResource(
prop,
row.resourceLimits[prop] || row[prop] || 0
);
if (request === limit) {
return this.renderWithClickHandler(rowOptions, request);
}
return this.renderWithClickHandler(
rowOptions,
<Tooltip
id={row.id + prop}
trigger={`${request} / ${limit}`}
preferredDirections={["top-right"]}
>
<Trans render="span">
{request} are guaranteed with a limit of {limit}
</Trans>
</Tooltip>
);
};
renderColumnUpdated = (_prop, row, rowOptions: RowOptions) => {
return this.renderWithClickHandler(
rowOptions,
<TimeAgo time={row.updated} />
);
};
renderColumnVersion = (_prop, row, rowOptions: RowOptions) => {
if (!row.version) {
return null;
}
const localeVersion = (
<DateFormat
value={new Date(row.version)}
format={DateUtil.getFormatOptions()}
/>
);
return this.renderWithClickHandler(
rowOptions,
<span>{localeVersion}</span>
);
};
renderRegion = (_prop, instance, rowOptions) => {
if (!rowOptions.isParent) {
return null;
}
return (
<div className="flex-box flex-box-align-vertical-center table-cell-flex-box">
<div className="table-cell-value flex-box flex-box-col">
{InstanceUtil.getRegionName(instance)}
</div>
</div>
);
};
renderZone = (_prop, instance, rowOptions) => {
if (!rowOptions.isParent) {
return null;
}
return (
<div className="flex-box flex-box-align-vertical-center table-cell-flex-box">
<div className="table-cell-value flex-box flex-box-col">
{InstanceUtil.getZoneName(instance)}
</div>
</div>
);
};
render() {
let { instances, pod, filterText } = this.props;
const { checkedItems } = this.state;
// If custom list of instances is not provided, use the default instances
// from the pod
if (instances == null) {
instances = pod.getInstanceList().getItems();
}
const disabledItemsMap = this.getDisabledItemsMap(instances);
return (
<ExpandingTable
allowMultipleSelect={true}
className="task-table expanding-table table table-hover table-flush table-borderless-outer table-borderless-inner-columns flush-bottom"
childRowClassName="expanding-table-child"
checkedItemsMap={checkedItems}
columns={this.getColumns()}
colGroup={this.getColGroup()}
data={this.getTableDataFor(instances, filterText)}
disabledItemsMap={disabledItemsMap}
inactiveItemsMap={disabledItemsMap}
expandAll={!!filterText}
getColGroup={this.getColGroup}
onCheckboxChange={this.handleItemCheck}
sortBy={{ prop: "name", order: "asc" }}
tableComponent={CheckboxTable}
uniqueProperty="id"
/>
);
}
}
export default PodInstancesTable; | the_stack |
import basem = require('./ClientApiBases');
import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces');
import TaskAgentInterfaces = require("./interfaces/TaskAgentInterfaces");
export interface ITaskAgentApiBase extends basem.ClientApiBase {
addAgentCloud(agentCloud: TaskAgentInterfaces.TaskAgentCloud): Promise<TaskAgentInterfaces.TaskAgentCloud>;
deleteAgentCloud(agentCloudId: number): Promise<TaskAgentInterfaces.TaskAgentCloud>;
getAgentCloud(agentCloudId: number): Promise<TaskAgentInterfaces.TaskAgentCloud>;
getAgentClouds(): Promise<TaskAgentInterfaces.TaskAgentCloud[]>;
getAgentCloudTypes(): Promise<TaskAgentInterfaces.TaskAgentCloudType[]>;
queueAgentRequest(request: TaskAgentInterfaces.TaskAgentJobRequest, queueId: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest>;
addAgent(agent: TaskAgentInterfaces.TaskAgent, poolId: number): Promise<TaskAgentInterfaces.TaskAgent>;
deleteAgent(poolId: number, agentId: number): Promise<void>;
getAgent(poolId: number, agentId: number, includeCapabilities?: boolean, includeAssignedRequest?: boolean, propertyFilters?: string[]): Promise<TaskAgentInterfaces.TaskAgent>;
getAgents(poolId: number, agentName?: string, includeCapabilities?: boolean, includeAssignedRequest?: boolean, propertyFilters?: string[], demands?: string[]): Promise<TaskAgentInterfaces.TaskAgent[]>;
replaceAgent(agent: TaskAgentInterfaces.TaskAgent, poolId: number, agentId: number): Promise<TaskAgentInterfaces.TaskAgent>;
updateAgent(agent: TaskAgentInterfaces.TaskAgent, poolId: number, agentId: number): Promise<TaskAgentInterfaces.TaskAgent>;
getAzureManagementGroups(): Promise<TaskAgentInterfaces.AzureManagementGroupQueryResult>;
getAzureSubscriptions(): Promise<TaskAgentInterfaces.AzureSubscriptionQueryResult>;
generateDeploymentGroupAccessToken(project: string, deploymentGroupId: number): Promise<string>;
addDeploymentGroup(deploymentGroup: TaskAgentInterfaces.DeploymentGroupCreateParameter, project: string): Promise<TaskAgentInterfaces.DeploymentGroup>;
deleteDeploymentGroup(project: string, deploymentGroupId: number): Promise<void>;
getDeploymentGroup(project: string, deploymentGroupId: number, actionFilter?: TaskAgentInterfaces.DeploymentGroupActionFilter, expand?: TaskAgentInterfaces.DeploymentGroupExpands): Promise<TaskAgentInterfaces.DeploymentGroup>;
getDeploymentGroups(project: string, name?: string, actionFilter?: TaskAgentInterfaces.DeploymentGroupActionFilter, expand?: TaskAgentInterfaces.DeploymentGroupExpands, continuationToken?: string, top?: number, ids?: number[]): Promise<TaskAgentInterfaces.DeploymentGroup[]>;
updateDeploymentGroup(deploymentGroup: TaskAgentInterfaces.DeploymentGroupUpdateParameter, project: string, deploymentGroupId: number): Promise<TaskAgentInterfaces.DeploymentGroup>;
getDeploymentGroupsMetrics(project: string, deploymentGroupName?: string, continuationToken?: string, top?: number): Promise<TaskAgentInterfaces.DeploymentGroupMetrics[]>;
getAgentRequestsForDeploymentMachine(project: string, deploymentGroupId: number, machineId: number, completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
getAgentRequestsForDeploymentMachines(project: string, deploymentGroupId: number, machineIds?: number[], completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
refreshDeploymentMachines(project: string, deploymentGroupId: number): Promise<void>;
generateDeploymentPoolAccessToken(poolId: number): Promise<string>;
getDeploymentPoolsSummary(poolName?: string, expands?: TaskAgentInterfaces.DeploymentPoolSummaryExpands): Promise<TaskAgentInterfaces.DeploymentPoolSummary[]>;
getAgentRequestsForDeploymentTarget(project: string, deploymentGroupId: number, targetId: number, completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
getAgentRequestsForDeploymentTargets(project: string, deploymentGroupId: number, targetIds?: number[], ownerId?: number, completedOn?: Date, completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
refreshDeploymentTargets(project: string, deploymentGroupId: number): Promise<void>;
queryEndpoint(endpoint: TaskAgentInterfaces.TaskDefinitionEndpoint): Promise<string[]>;
getServiceEndpointExecutionRecords(project: string, endpointId: string, top?: number): Promise<TaskAgentInterfaces.ServiceEndpointExecutionRecord[]>;
addServiceEndpointExecutionRecords(input: TaskAgentInterfaces.ServiceEndpointExecutionRecordsInput, project: string): Promise<TaskAgentInterfaces.ServiceEndpointExecutionRecord[]>;
getTaskHubLicenseDetails(hubName: string, includeEnterpriseUsersCount?: boolean, includeHostedAgentMinutesCount?: boolean): Promise<TaskAgentInterfaces.TaskHubLicenseDetails>;
updateTaskHubLicenseDetails(taskHubLicenseDetails: TaskAgentInterfaces.TaskHubLicenseDetails, hubName: string): Promise<TaskAgentInterfaces.TaskHubLicenseDetails>;
validateInputs(inputValidationRequest: TaskAgentInterfaces.InputValidationRequest): Promise<TaskAgentInterfaces.InputValidationRequest>;
deleteAgentRequest(poolId: number, requestId: number, lockToken: string, result?: TaskAgentInterfaces.TaskResult): Promise<void>;
getAgentRequest(poolId: number, requestId: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest>;
getAgentRequestsForAgent(poolId: number, agentId: number, completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
getAgentRequestsForAgents(poolId: number, agentIds?: number[], completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
getAgentRequestsForPlan(poolId: number, planId: string, jobId?: string): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
queueAgentRequestByPool(request: TaskAgentInterfaces.TaskAgentJobRequest, poolId: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest>;
updateAgentRequest(request: TaskAgentInterfaces.TaskAgentJobRequest, poolId: number, requestId: number, lockToken: string): Promise<TaskAgentInterfaces.TaskAgentJobRequest>;
generateDeploymentMachineGroupAccessToken(project: string, machineGroupId: number): Promise<string>;
addDeploymentMachineGroup(machineGroup: TaskAgentInterfaces.DeploymentMachineGroup, project: string): Promise<TaskAgentInterfaces.DeploymentMachineGroup>;
deleteDeploymentMachineGroup(project: string, machineGroupId: number): Promise<void>;
getDeploymentMachineGroup(project: string, machineGroupId: number, actionFilter?: TaskAgentInterfaces.MachineGroupActionFilter): Promise<TaskAgentInterfaces.DeploymentMachineGroup>;
getDeploymentMachineGroups(project: string, machineGroupName?: string, actionFilter?: TaskAgentInterfaces.MachineGroupActionFilter): Promise<TaskAgentInterfaces.DeploymentMachineGroup[]>;
updateDeploymentMachineGroup(machineGroup: TaskAgentInterfaces.DeploymentMachineGroup, project: string, machineGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachineGroup>;
getDeploymentMachineGroupMachines(project: string, machineGroupId: number, tagFilters?: string[]): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
updateDeploymentMachineGroupMachines(deploymentMachines: TaskAgentInterfaces.DeploymentMachine[], project: string, machineGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
addDeploymentMachine(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
deleteDeploymentMachine(project: string, deploymentGroupId: number, machineId: number): Promise<void>;
getDeploymentMachine(project: string, deploymentGroupId: number, machineId: number, expand?: TaskAgentInterfaces.DeploymentMachineExpands): Promise<TaskAgentInterfaces.DeploymentMachine>;
getDeploymentMachines(project: string, deploymentGroupId: number, tags?: string[], name?: string, expand?: TaskAgentInterfaces.DeploymentMachineExpands): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
replaceDeploymentMachine(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number, machineId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
updateDeploymentMachine(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number, machineId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
updateDeploymentMachines(machines: TaskAgentInterfaces.DeploymentMachine[], project: string, deploymentGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
createAgentPoolMaintenanceDefinition(definition: TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition, poolId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition>;
deleteAgentPoolMaintenanceDefinition(poolId: number, definitionId: number): Promise<void>;
getAgentPoolMaintenanceDefinition(poolId: number, definitionId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition>;
getAgentPoolMaintenanceDefinitions(poolId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition[]>;
updateAgentPoolMaintenanceDefinition(definition: TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition, poolId: number, definitionId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition>;
deleteAgentPoolMaintenanceJob(poolId: number, jobId: number): Promise<void>;
getAgentPoolMaintenanceJob(poolId: number, jobId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceJob>;
getAgentPoolMaintenanceJobLogs(poolId: number, jobId: number): Promise<NodeJS.ReadableStream>;
getAgentPoolMaintenanceJobs(poolId: number, definitionId?: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceJob[]>;
queueAgentPoolMaintenanceJob(job: TaskAgentInterfaces.TaskAgentPoolMaintenanceJob, poolId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceJob>;
updateAgentPoolMaintenanceJob(job: TaskAgentInterfaces.TaskAgentPoolMaintenanceJob, poolId: number, jobId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceJob>;
deleteMessage(poolId: number, messageId: number, sessionId: string): Promise<void>;
getMessage(poolId: number, sessionId: string, lastMessageId?: number): Promise<TaskAgentInterfaces.TaskAgentMessage>;
refreshAgent(poolId: number, agentId: number): Promise<void>;
refreshAgents(poolId: number): Promise<void>;
sendMessage(message: TaskAgentInterfaces.TaskAgentMessage, poolId: number, requestId: number): Promise<void>;
getPackage(packageType: string, platform: string, version: string): Promise<TaskAgentInterfaces.PackageMetadata>;
getPackages(packageType: string, platform?: string, top?: number): Promise<TaskAgentInterfaces.PackageMetadata[]>;
getAgentPoolMetadata(poolId: number): Promise<NodeJS.ReadableStream>;
addAgentPool(pool: TaskAgentInterfaces.TaskAgentPool): Promise<TaskAgentInterfaces.TaskAgentPool>;
deleteAgentPool(poolId: number): Promise<void>;
getAgentPool(poolId: number, properties?: string[], actionFilter?: TaskAgentInterfaces.TaskAgentPoolActionFilter): Promise<TaskAgentInterfaces.TaskAgentPool>;
getAgentPools(poolName?: string, properties?: string[], poolType?: TaskAgentInterfaces.TaskAgentPoolType, actionFilter?: TaskAgentInterfaces.TaskAgentPoolActionFilter): Promise<TaskAgentInterfaces.TaskAgentPool[]>;
updateAgentPool(pool: TaskAgentInterfaces.TaskAgentPool, poolId: number): Promise<TaskAgentInterfaces.TaskAgentPool>;
addAgentQueue(queue: TaskAgentInterfaces.TaskAgentQueue, project?: string): Promise<TaskAgentInterfaces.TaskAgentQueue>;
createTeamProject(project?: string): Promise<void>;
deleteAgentQueue(queueId: number, project?: string): Promise<void>;
getAgentQueue(queueId: number, project?: string, actionFilter?: TaskAgentInterfaces.TaskAgentQueueActionFilter): Promise<TaskAgentInterfaces.TaskAgentQueue>;
getAgentQueues(project?: string, queueName?: string, actionFilter?: TaskAgentInterfaces.TaskAgentQueueActionFilter): Promise<TaskAgentInterfaces.TaskAgentQueue[]>;
getAgentQueuesByIds(queueIds: number[], project?: string, actionFilter?: TaskAgentInterfaces.TaskAgentQueueActionFilter): Promise<TaskAgentInterfaces.TaskAgentQueue[]>;
getAgentQueuesByNames(queueNames: string[], project?: string, actionFilter?: TaskAgentInterfaces.TaskAgentQueueActionFilter): Promise<TaskAgentInterfaces.TaskAgentQueue[]>;
getAgentCloudRequests(agentCloudId: number): Promise<TaskAgentInterfaces.TaskAgentCloudRequest[]>;
getResourceLimits(): Promise<TaskAgentInterfaces.ResourceLimit[]>;
getResourceUsage(parallelismTag?: string, poolIsHosted?: boolean, includeRunningRequests?: boolean): Promise<TaskAgentInterfaces.ResourceUsage>;
getTaskGroupHistory(project: string, taskGroupId: string): Promise<TaskAgentInterfaces.TaskGroupRevision[]>;
deleteSecureFile(project: string, secureFileId: string): Promise<void>;
downloadSecureFile(project: string, secureFileId: string, ticket: string, download?: boolean): Promise<NodeJS.ReadableStream>;
getSecureFile(project: string, secureFileId: string, includeDownloadTicket?: boolean, actionFilter?: TaskAgentInterfaces.SecureFileActionFilter): Promise<TaskAgentInterfaces.SecureFile>;
getSecureFiles(project: string, namePattern?: string, includeDownloadTickets?: boolean, actionFilter?: TaskAgentInterfaces.SecureFileActionFilter): Promise<TaskAgentInterfaces.SecureFile[]>;
getSecureFilesByIds(project: string, secureFileIds: string[], includeDownloadTickets?: boolean, actionFilter?: TaskAgentInterfaces.SecureFileActionFilter): Promise<TaskAgentInterfaces.SecureFile[]>;
getSecureFilesByNames(project: string, secureFileNames: string[], includeDownloadTickets?: boolean, actionFilter?: TaskAgentInterfaces.SecureFileActionFilter): Promise<TaskAgentInterfaces.SecureFile[]>;
querySecureFilesByProperties(condition: string, project: string, namePattern?: string): Promise<TaskAgentInterfaces.SecureFile[]>;
updateSecureFile(secureFile: TaskAgentInterfaces.SecureFile, project: string, secureFileId: string): Promise<TaskAgentInterfaces.SecureFile>;
updateSecureFiles(secureFiles: TaskAgentInterfaces.SecureFile[], project: string): Promise<TaskAgentInterfaces.SecureFile[]>;
uploadSecureFile(customHeaders: any, contentStream: NodeJS.ReadableStream, project: string, name: string): Promise<TaskAgentInterfaces.SecureFile>;
executeServiceEndpointRequest(serviceEndpointRequest: TaskAgentInterfaces.ServiceEndpointRequest, project: string, endpointId: string): Promise<TaskAgentInterfaces.ServiceEndpointRequestResult>;
queryServiceEndpoint(binding: TaskAgentInterfaces.DataSourceBinding, project: string): Promise<string[]>;
createServiceEndpoint(endpoint: TaskAgentInterfaces.ServiceEndpoint, project: string): Promise<TaskAgentInterfaces.ServiceEndpoint>;
deleteServiceEndpoint(project: string, endpointId: string): Promise<void>;
getServiceEndpointDetails(project: string, endpointId: string): Promise<TaskAgentInterfaces.ServiceEndpoint>;
getServiceEndpoints(project: string, type?: string, authSchemes?: string[], endpointIds?: string[], includeFailed?: boolean): Promise<TaskAgentInterfaces.ServiceEndpoint[]>;
getServiceEndpointsByNames(project: string, endpointNames: string[], type?: string, authSchemes?: string[], includeFailed?: boolean): Promise<TaskAgentInterfaces.ServiceEndpoint[]>;
updateServiceEndpoint(endpoint: TaskAgentInterfaces.ServiceEndpoint, project: string, endpointId: string, operation?: string): Promise<TaskAgentInterfaces.ServiceEndpoint>;
updateServiceEndpoints(endpoints: TaskAgentInterfaces.ServiceEndpoint[], project: string): Promise<TaskAgentInterfaces.ServiceEndpoint[]>;
getServiceEndpointTypes(type?: string, scheme?: string): Promise<TaskAgentInterfaces.ServiceEndpointType[]>;
createAgentSession(session: TaskAgentInterfaces.TaskAgentSession, poolId: number): Promise<TaskAgentInterfaces.TaskAgentSession>;
deleteAgentSession(poolId: number, sessionId: string): Promise<void>;
addDeploymentTarget(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
deleteDeploymentTarget(project: string, deploymentGroupId: number, targetId: number): Promise<void>;
getDeploymentTarget(project: string, deploymentGroupId: number, targetId: number, expand?: TaskAgentInterfaces.DeploymentTargetExpands): Promise<TaskAgentInterfaces.DeploymentMachine>;
getDeploymentTargets(project: string, deploymentGroupId: number, tags?: string[], name?: string, partialNameMatch?: boolean, expand?: TaskAgentInterfaces.DeploymentTargetExpands, agentStatus?: TaskAgentInterfaces.TaskAgentStatusFilter, agentJobResult?: TaskAgentInterfaces.TaskAgentJobResultFilter, continuationToken?: string, top?: number, enabled?: boolean): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
replaceDeploymentTarget(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number, targetId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
updateDeploymentTarget(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number, targetId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
updateDeploymentTargets(machines: TaskAgentInterfaces.DeploymentTargetUpdateParameter[], project: string, deploymentGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
addTaskGroup(taskGroup: TaskAgentInterfaces.TaskGroupCreateParameter, project: string): Promise<TaskAgentInterfaces.TaskGroup>;
deleteTaskGroup(project: string, taskGroupId: string, comment?: string): Promise<void>;
getTaskGroup(project: string, taskGroupId: string, versionSpec: string, expand?: TaskAgentInterfaces.TaskGroupExpands): Promise<TaskAgentInterfaces.TaskGroup>;
getTaskGroupRevision(project: string, taskGroupId: string, revision: number): Promise<NodeJS.ReadableStream>;
getTaskGroups(project: string, taskGroupId?: string, expanded?: boolean, taskIdFilter?: string, deleted?: boolean, top?: number, continuationToken?: Date, queryOrder?: TaskAgentInterfaces.TaskGroupQueryOrder): Promise<TaskAgentInterfaces.TaskGroup[]>;
publishPreviewTaskGroup(taskGroup: TaskAgentInterfaces.TaskGroup, project: string, taskGroupId: string, disablePriorVersions?: boolean): Promise<TaskAgentInterfaces.TaskGroup[]>;
publishTaskGroup(taskGroupMetadata: TaskAgentInterfaces.PublishTaskGroupMetadata, project: string, parentTaskGroupId: string): Promise<TaskAgentInterfaces.TaskGroup[]>;
undeleteTaskGroup(taskGroup: TaskAgentInterfaces.TaskGroup, project: string): Promise<TaskAgentInterfaces.TaskGroup[]>;
updateTaskGroup(taskGroup: TaskAgentInterfaces.TaskGroupUpdateParameter, project: string, taskGroupId?: string): Promise<TaskAgentInterfaces.TaskGroup>;
deleteTaskDefinition(taskId: string): Promise<void>;
getTaskContentZip(taskId: string, versionString: string, visibility?: string[], scopeLocal?: boolean): Promise<NodeJS.ReadableStream>;
getTaskDefinition(taskId: string, versionString: string, visibility?: string[], scopeLocal?: boolean): Promise<TaskAgentInterfaces.TaskDefinition>;
getTaskDefinitions(taskId?: string, visibility?: string[], scopeLocal?: boolean): Promise<TaskAgentInterfaces.TaskDefinition[]>;
updateAgentUpdateState(poolId: number, agentId: number, currentState: string): Promise<TaskAgentInterfaces.TaskAgent>;
updateAgentUserCapabilities(userCapabilities: {
[key: string]: string;
}, poolId: number, agentId: number): Promise<TaskAgentInterfaces.TaskAgent>;
addVariableGroup(group: TaskAgentInterfaces.VariableGroupParameters, project: string): Promise<TaskAgentInterfaces.VariableGroup>;
deleteVariableGroup(project: string, groupId: number): Promise<void>;
getVariableGroup(project: string, groupId: number): Promise<TaskAgentInterfaces.VariableGroup>;
getVariableGroups(project: string, groupName?: string, actionFilter?: TaskAgentInterfaces.VariableGroupActionFilter, top?: number, continuationToken?: number, queryOrder?: TaskAgentInterfaces.VariableGroupQueryOrder): Promise<TaskAgentInterfaces.VariableGroup[]>;
getVariableGroupsById(project: string, groupIds: number[]): Promise<TaskAgentInterfaces.VariableGroup[]>;
updateVariableGroup(group: TaskAgentInterfaces.VariableGroupParameters, project: string, groupId: number): Promise<TaskAgentInterfaces.VariableGroup>;
acquireAccessToken(authenticationRequest: TaskAgentInterfaces.AadOauthTokenRequest): Promise<TaskAgentInterfaces.AadOauthTokenResult>;
createAadOAuthRequest(tenantId: string, redirectUri: string, promptOption?: TaskAgentInterfaces.AadLoginPromptOption, completeCallbackPayload?: string, completeCallbackByAuthCode?: boolean): Promise<string>;
getVstsAadTenantId(): Promise<string>;
}
export declare class TaskAgentApiBase extends basem.ClientApiBase implements ITaskAgentApiBase {
constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions);
static readonly RESOURCE_AREA_ID: string;
/**
* @param {TaskAgentInterfaces.TaskAgentCloud} agentCloud
*/
addAgentCloud(agentCloud: TaskAgentInterfaces.TaskAgentCloud): Promise<TaskAgentInterfaces.TaskAgentCloud>;
/**
* @param {number} agentCloudId
*/
deleteAgentCloud(agentCloudId: number): Promise<TaskAgentInterfaces.TaskAgentCloud>;
/**
* @param {number} agentCloudId
*/
getAgentCloud(agentCloudId: number): Promise<TaskAgentInterfaces.TaskAgentCloud>;
/**
*/
getAgentClouds(): Promise<TaskAgentInterfaces.TaskAgentCloud[]>;
/**
* Get agent cloud types.
*
*/
getAgentCloudTypes(): Promise<TaskAgentInterfaces.TaskAgentCloudType[]>;
/**
* @param {TaskAgentInterfaces.TaskAgentJobRequest} request
* @param {number} queueId
*/
queueAgentRequest(request: TaskAgentInterfaces.TaskAgentJobRequest, queueId: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest>;
/**
* @param {TaskAgentInterfaces.TaskAgent} agent
* @param {number} poolId
*/
addAgent(agent: TaskAgentInterfaces.TaskAgent, poolId: number): Promise<TaskAgentInterfaces.TaskAgent>;
/**
* @param {number} poolId
* @param {number} agentId
*/
deleteAgent(poolId: number, agentId: number): Promise<void>;
/**
* @param {number} poolId
* @param {number} agentId
* @param {boolean} includeCapabilities
* @param {boolean} includeAssignedRequest
* @param {string[]} propertyFilters
*/
getAgent(poolId: number, agentId: number, includeCapabilities?: boolean, includeAssignedRequest?: boolean, propertyFilters?: string[]): Promise<TaskAgentInterfaces.TaskAgent>;
/**
* @param {number} poolId
* @param {string} agentName
* @param {boolean} includeCapabilities
* @param {boolean} includeAssignedRequest
* @param {string[]} propertyFilters
* @param {string[]} demands
*/
getAgents(poolId: number, agentName?: string, includeCapabilities?: boolean, includeAssignedRequest?: boolean, propertyFilters?: string[], demands?: string[]): Promise<TaskAgentInterfaces.TaskAgent[]>;
/**
* @param {TaskAgentInterfaces.TaskAgent} agent
* @param {number} poolId
* @param {number} agentId
*/
replaceAgent(agent: TaskAgentInterfaces.TaskAgent, poolId: number, agentId: number): Promise<TaskAgentInterfaces.TaskAgent>;
/**
* @param {TaskAgentInterfaces.TaskAgent} agent
* @param {number} poolId
* @param {number} agentId
*/
updateAgent(agent: TaskAgentInterfaces.TaskAgent, poolId: number, agentId: number): Promise<TaskAgentInterfaces.TaskAgent>;
/**
* Returns list of azure subscriptions
*
*/
getAzureManagementGroups(): Promise<TaskAgentInterfaces.AzureManagementGroupQueryResult>;
/**
* Returns list of azure subscriptions
*
*/
getAzureSubscriptions(): Promise<TaskAgentInterfaces.AzureSubscriptionQueryResult>;
/**
* GET a PAT token for managing (configuring, removing, tagging) deployment targets in a deployment group.
*
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group in which deployment targets are managed.
*/
generateDeploymentGroupAccessToken(project: string, deploymentGroupId: number): Promise<string>;
/**
* Create a deployment group.
*
* @param {TaskAgentInterfaces.DeploymentGroupCreateParameter} deploymentGroup - Deployment group to create.
* @param {string} project - Project ID or project name
*/
addDeploymentGroup(deploymentGroup: TaskAgentInterfaces.DeploymentGroupCreateParameter, project: string): Promise<TaskAgentInterfaces.DeploymentGroup>;
/**
* Delete a deployment group.
*
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group to be deleted.
*/
deleteDeploymentGroup(project: string, deploymentGroupId: number): Promise<void>;
/**
* Get a deployment group by its ID.
*
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group.
* @param {TaskAgentInterfaces.DeploymentGroupActionFilter} actionFilter - Get the deployment group only if this action can be performed on it.
* @param {TaskAgentInterfaces.DeploymentGroupExpands} expand - Include these additional details in the returned object.
*/
getDeploymentGroup(project: string, deploymentGroupId: number, actionFilter?: TaskAgentInterfaces.DeploymentGroupActionFilter, expand?: TaskAgentInterfaces.DeploymentGroupExpands): Promise<TaskAgentInterfaces.DeploymentGroup>;
/**
* Get a list of deployment groups by name or IDs.
*
* @param {string} project - Project ID or project name
* @param {string} name - Name of the deployment group.
* @param {TaskAgentInterfaces.DeploymentGroupActionFilter} actionFilter - Get only deployment groups on which this action can be performed.
* @param {TaskAgentInterfaces.DeploymentGroupExpands} expand - Include these additional details in the returned objects.
* @param {string} continuationToken - Get deployment groups with names greater than this continuationToken lexicographically.
* @param {number} top - Maximum number of deployment groups to return. Default is **1000**.
* @param {number[]} ids - Comma separated list of IDs of the deployment groups.
*/
getDeploymentGroups(project: string, name?: string, actionFilter?: TaskAgentInterfaces.DeploymentGroupActionFilter, expand?: TaskAgentInterfaces.DeploymentGroupExpands, continuationToken?: string, top?: number, ids?: number[]): Promise<TaskAgentInterfaces.DeploymentGroup[]>;
/**
* Update a deployment group.
*
* @param {TaskAgentInterfaces.DeploymentGroupUpdateParameter} deploymentGroup - Deployment group to update.
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group.
*/
updateDeploymentGroup(deploymentGroup: TaskAgentInterfaces.DeploymentGroupUpdateParameter, project: string, deploymentGroupId: number): Promise<TaskAgentInterfaces.DeploymentGroup>;
/**
* Get a list of deployment group metrics.
*
* @param {string} project - Project ID or project name
* @param {string} deploymentGroupName - Name of the deployment group.
* @param {string} continuationToken - Get metrics for deployment groups with names greater than this continuationToken lexicographically.
* @param {number} top - Maximum number of deployment group metrics to return. Default is **50**.
*/
getDeploymentGroupsMetrics(project: string, deploymentGroupName?: string, continuationToken?: string, top?: number): Promise<TaskAgentInterfaces.DeploymentGroupMetrics[]>;
/**
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId
* @param {number} machineId
* @param {number} completedRequestCount
*/
getAgentRequestsForDeploymentMachine(project: string, deploymentGroupId: number, machineId: number, completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
/**
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId
* @param {number[]} machineIds
* @param {number} completedRequestCount
*/
getAgentRequestsForDeploymentMachines(project: string, deploymentGroupId: number, machineIds?: number[], completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
/**
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId
*/
refreshDeploymentMachines(project: string, deploymentGroupId: number): Promise<void>;
/**
* GET a PAT token for managing (configuring, removing, tagging) deployment agents in a deployment pool.
*
* @param {number} poolId - ID of the deployment pool in which deployment agents are managed.
*/
generateDeploymentPoolAccessToken(poolId: number): Promise<string>;
/**
* Get a list of deployment pool summaries.
*
* @param {string} poolName - Name of the deployment pool.
* @param {TaskAgentInterfaces.DeploymentPoolSummaryExpands} expands - Include these additional details in the returned objects.
*/
getDeploymentPoolsSummary(poolName?: string, expands?: TaskAgentInterfaces.DeploymentPoolSummaryExpands): Promise<TaskAgentInterfaces.DeploymentPoolSummary[]>;
/**
* Get agent requests for a deployment target.
*
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group to which the target belongs.
* @param {number} targetId - ID of the deployment target.
* @param {number} completedRequestCount - Maximum number of completed requests to return. Default is **50**
*/
getAgentRequestsForDeploymentTarget(project: string, deploymentGroupId: number, targetId: number, completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
/**
* Get agent requests for a list deployment targets.
*
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group to which the targets belong.
* @param {number[]} targetIds - Comma separated list of IDs of the deployment targets.
* @param {number} ownerId - Id of owner of agent job request.
* @param {Date} completedOn - Datetime to return request after this time.
* @param {number} completedRequestCount - Maximum number of completed requests to return for each target. Default is **50**
*/
getAgentRequestsForDeploymentTargets(project: string, deploymentGroupId: number, targetIds?: number[], ownerId?: number, completedOn?: Date, completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
/**
* Upgrade the deployment targets in a deployment group.
*
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group.
*/
refreshDeploymentTargets(project: string, deploymentGroupId: number): Promise<void>;
/**
* Proxy for a GET request defined by an 'endpoint'. The request is authorized using a service connection. The response is filtered using an XPath/Json based selector.
*
* @param {TaskAgentInterfaces.TaskDefinitionEndpoint} endpoint - Describes the URL to fetch.
*/
queryEndpoint(endpoint: TaskAgentInterfaces.TaskDefinitionEndpoint): Promise<string[]>;
/**
* @param {string} project - Project ID or project name
* @param {string} endpointId
* @param {number} top
*/
getServiceEndpointExecutionRecords(project: string, endpointId: string, top?: number): Promise<TaskAgentInterfaces.ServiceEndpointExecutionRecord[]>;
/**
* @param {TaskAgentInterfaces.ServiceEndpointExecutionRecordsInput} input
* @param {string} project - Project ID or project name
*/
addServiceEndpointExecutionRecords(input: TaskAgentInterfaces.ServiceEndpointExecutionRecordsInput, project: string): Promise<TaskAgentInterfaces.ServiceEndpointExecutionRecord[]>;
/**
* @param {string} hubName
* @param {boolean} includeEnterpriseUsersCount
* @param {boolean} includeHostedAgentMinutesCount
*/
getTaskHubLicenseDetails(hubName: string, includeEnterpriseUsersCount?: boolean, includeHostedAgentMinutesCount?: boolean): Promise<TaskAgentInterfaces.TaskHubLicenseDetails>;
/**
* @param {TaskAgentInterfaces.TaskHubLicenseDetails} taskHubLicenseDetails
* @param {string} hubName
*/
updateTaskHubLicenseDetails(taskHubLicenseDetails: TaskAgentInterfaces.TaskHubLicenseDetails, hubName: string): Promise<TaskAgentInterfaces.TaskHubLicenseDetails>;
/**
* @param {TaskAgentInterfaces.InputValidationRequest} inputValidationRequest
*/
validateInputs(inputValidationRequest: TaskAgentInterfaces.InputValidationRequest): Promise<TaskAgentInterfaces.InputValidationRequest>;
/**
* @param {number} poolId
* @param {number} requestId
* @param {string} lockToken
* @param {TaskAgentInterfaces.TaskResult} result
*/
deleteAgentRequest(poolId: number, requestId: number, lockToken: string, result?: TaskAgentInterfaces.TaskResult): Promise<void>;
/**
* @param {number} poolId
* @param {number} requestId
*/
getAgentRequest(poolId: number, requestId: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest>;
/**
* @param {number} poolId
* @param {number} agentId
* @param {number} completedRequestCount
*/
getAgentRequestsForAgent(poolId: number, agentId: number, completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
/**
* @param {number} poolId
* @param {number[]} agentIds
* @param {number} completedRequestCount
*/
getAgentRequestsForAgents(poolId: number, agentIds?: number[], completedRequestCount?: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
/**
* @param {number} poolId
* @param {string} planId
* @param {string} jobId
*/
getAgentRequestsForPlan(poolId: number, planId: string, jobId?: string): Promise<TaskAgentInterfaces.TaskAgentJobRequest[]>;
/**
* @param {TaskAgentInterfaces.TaskAgentJobRequest} request
* @param {number} poolId
*/
queueAgentRequestByPool(request: TaskAgentInterfaces.TaskAgentJobRequest, poolId: number): Promise<TaskAgentInterfaces.TaskAgentJobRequest>;
/**
* @param {TaskAgentInterfaces.TaskAgentJobRequest} request
* @param {number} poolId
* @param {number} requestId
* @param {string} lockToken
*/
updateAgentRequest(request: TaskAgentInterfaces.TaskAgentJobRequest, poolId: number, requestId: number, lockToken: string): Promise<TaskAgentInterfaces.TaskAgentJobRequest>;
/**
* @param {string} project - Project ID or project name
* @param {number} machineGroupId
*/
generateDeploymentMachineGroupAccessToken(project: string, machineGroupId: number): Promise<string>;
/**
* @param {TaskAgentInterfaces.DeploymentMachineGroup} machineGroup
* @param {string} project - Project ID or project name
*/
addDeploymentMachineGroup(machineGroup: TaskAgentInterfaces.DeploymentMachineGroup, project: string): Promise<TaskAgentInterfaces.DeploymentMachineGroup>;
/**
* @param {string} project - Project ID or project name
* @param {number} machineGroupId
*/
deleteDeploymentMachineGroup(project: string, machineGroupId: number): Promise<void>;
/**
* @param {string} project - Project ID or project name
* @param {number} machineGroupId
* @param {TaskAgentInterfaces.MachineGroupActionFilter} actionFilter
*/
getDeploymentMachineGroup(project: string, machineGroupId: number, actionFilter?: TaskAgentInterfaces.MachineGroupActionFilter): Promise<TaskAgentInterfaces.DeploymentMachineGroup>;
/**
* @param {string} project - Project ID or project name
* @param {string} machineGroupName
* @param {TaskAgentInterfaces.MachineGroupActionFilter} actionFilter
*/
getDeploymentMachineGroups(project: string, machineGroupName?: string, actionFilter?: TaskAgentInterfaces.MachineGroupActionFilter): Promise<TaskAgentInterfaces.DeploymentMachineGroup[]>;
/**
* @param {TaskAgentInterfaces.DeploymentMachineGroup} machineGroup
* @param {string} project - Project ID or project name
* @param {number} machineGroupId
*/
updateDeploymentMachineGroup(machineGroup: TaskAgentInterfaces.DeploymentMachineGroup, project: string, machineGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachineGroup>;
/**
* @param {string} project - Project ID or project name
* @param {number} machineGroupId
* @param {string[]} tagFilters
*/
getDeploymentMachineGroupMachines(project: string, machineGroupId: number, tagFilters?: string[]): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
/**
* @param {TaskAgentInterfaces.DeploymentMachine[]} deploymentMachines
* @param {string} project - Project ID or project name
* @param {number} machineGroupId
*/
updateDeploymentMachineGroupMachines(deploymentMachines: TaskAgentInterfaces.DeploymentMachine[], project: string, machineGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
/**
* @param {TaskAgentInterfaces.DeploymentMachine} machine
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId
*/
addDeploymentMachine(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
/**
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId
* @param {number} machineId
*/
deleteDeploymentMachine(project: string, deploymentGroupId: number, machineId: number): Promise<void>;
/**
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId
* @param {number} machineId
* @param {TaskAgentInterfaces.DeploymentMachineExpands} expand
*/
getDeploymentMachine(project: string, deploymentGroupId: number, machineId: number, expand?: TaskAgentInterfaces.DeploymentMachineExpands): Promise<TaskAgentInterfaces.DeploymentMachine>;
/**
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId
* @param {string[]} tags
* @param {string} name
* @param {TaskAgentInterfaces.DeploymentMachineExpands} expand
*/
getDeploymentMachines(project: string, deploymentGroupId: number, tags?: string[], name?: string, expand?: TaskAgentInterfaces.DeploymentMachineExpands): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
/**
* @param {TaskAgentInterfaces.DeploymentMachine} machine
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId
* @param {number} machineId
*/
replaceDeploymentMachine(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number, machineId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
/**
* @param {TaskAgentInterfaces.DeploymentMachine} machine
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId
* @param {number} machineId
*/
updateDeploymentMachine(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number, machineId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
/**
* @param {TaskAgentInterfaces.DeploymentMachine[]} machines
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId
*/
updateDeploymentMachines(machines: TaskAgentInterfaces.DeploymentMachine[], project: string, deploymentGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
/**
* @param {TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition} definition
* @param {number} poolId
*/
createAgentPoolMaintenanceDefinition(definition: TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition, poolId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition>;
/**
* @param {number} poolId
* @param {number} definitionId
*/
deleteAgentPoolMaintenanceDefinition(poolId: number, definitionId: number): Promise<void>;
/**
* @param {number} poolId
* @param {number} definitionId
*/
getAgentPoolMaintenanceDefinition(poolId: number, definitionId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition>;
/**
* @param {number} poolId
*/
getAgentPoolMaintenanceDefinitions(poolId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition[]>;
/**
* @param {TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition} definition
* @param {number} poolId
* @param {number} definitionId
*/
updateAgentPoolMaintenanceDefinition(definition: TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition, poolId: number, definitionId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceDefinition>;
/**
* @param {number} poolId
* @param {number} jobId
*/
deleteAgentPoolMaintenanceJob(poolId: number, jobId: number): Promise<void>;
/**
* @param {number} poolId
* @param {number} jobId
*/
getAgentPoolMaintenanceJob(poolId: number, jobId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceJob>;
/**
* @param {number} poolId
* @param {number} jobId
*/
getAgentPoolMaintenanceJobLogs(poolId: number, jobId: number): Promise<NodeJS.ReadableStream>;
/**
* @param {number} poolId
* @param {number} definitionId
*/
getAgentPoolMaintenanceJobs(poolId: number, definitionId?: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceJob[]>;
/**
* @param {TaskAgentInterfaces.TaskAgentPoolMaintenanceJob} job
* @param {number} poolId
*/
queueAgentPoolMaintenanceJob(job: TaskAgentInterfaces.TaskAgentPoolMaintenanceJob, poolId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceJob>;
/**
* @param {TaskAgentInterfaces.TaskAgentPoolMaintenanceJob} job
* @param {number} poolId
* @param {number} jobId
*/
updateAgentPoolMaintenanceJob(job: TaskAgentInterfaces.TaskAgentPoolMaintenanceJob, poolId: number, jobId: number): Promise<TaskAgentInterfaces.TaskAgentPoolMaintenanceJob>;
/**
* @param {number} poolId
* @param {number} messageId
* @param {string} sessionId
*/
deleteMessage(poolId: number, messageId: number, sessionId: string): Promise<void>;
/**
* @param {number} poolId
* @param {string} sessionId
* @param {number} lastMessageId
*/
getMessage(poolId: number, sessionId: string, lastMessageId?: number): Promise<TaskAgentInterfaces.TaskAgentMessage>;
/**
* @param {number} poolId
* @param {number} agentId
*/
refreshAgent(poolId: number, agentId: number): Promise<void>;
/**
* @param {number} poolId
*/
refreshAgents(poolId: number): Promise<void>;
/**
* @param {TaskAgentInterfaces.TaskAgentMessage} message
* @param {number} poolId
* @param {number} requestId
*/
sendMessage(message: TaskAgentInterfaces.TaskAgentMessage, poolId: number, requestId: number): Promise<void>;
/**
* @param {string} packageType
* @param {string} platform
* @param {string} version
*/
getPackage(packageType: string, platform: string, version: string): Promise<TaskAgentInterfaces.PackageMetadata>;
/**
* @param {string} packageType
* @param {string} platform
* @param {number} top
*/
getPackages(packageType: string, platform?: string, top?: number): Promise<TaskAgentInterfaces.PackageMetadata[]>;
/**
* @param {number} poolId
*/
getAgentPoolMetadata(poolId: number): Promise<NodeJS.ReadableStream>;
/**
* @param {TaskAgentInterfaces.TaskAgentPool} pool
*/
addAgentPool(pool: TaskAgentInterfaces.TaskAgentPool): Promise<TaskAgentInterfaces.TaskAgentPool>;
/**
* @param {number} poolId
*/
deleteAgentPool(poolId: number): Promise<void>;
/**
* @param {number} poolId
* @param {string[]} properties
* @param {TaskAgentInterfaces.TaskAgentPoolActionFilter} actionFilter
*/
getAgentPool(poolId: number, properties?: string[], actionFilter?: TaskAgentInterfaces.TaskAgentPoolActionFilter): Promise<TaskAgentInterfaces.TaskAgentPool>;
/**
* @param {string} poolName
* @param {string[]} properties
* @param {TaskAgentInterfaces.TaskAgentPoolType} poolType
* @param {TaskAgentInterfaces.TaskAgentPoolActionFilter} actionFilter
*/
getAgentPools(poolName?: string, properties?: string[], poolType?: TaskAgentInterfaces.TaskAgentPoolType, actionFilter?: TaskAgentInterfaces.TaskAgentPoolActionFilter): Promise<TaskAgentInterfaces.TaskAgentPool[]>;
/**
* @param {TaskAgentInterfaces.TaskAgentPool} pool
* @param {number} poolId
*/
updateAgentPool(pool: TaskAgentInterfaces.TaskAgentPool, poolId: number): Promise<TaskAgentInterfaces.TaskAgentPool>;
/**
* @param {TaskAgentInterfaces.TaskAgentQueue} queue
* @param {string} project - Project ID or project name
*/
addAgentQueue(queue: TaskAgentInterfaces.TaskAgentQueue, project?: string): Promise<TaskAgentInterfaces.TaskAgentQueue>;
/**
* @param {string} project - Project ID or project name
*/
createTeamProject(project?: string): Promise<void>;
/**
* @param {number} queueId
* @param {string} project - Project ID or project name
*/
deleteAgentQueue(queueId: number, project?: string): Promise<void>;
/**
* @param {number} queueId
* @param {string} project - Project ID or project name
* @param {TaskAgentInterfaces.TaskAgentQueueActionFilter} actionFilter
*/
getAgentQueue(queueId: number, project?: string, actionFilter?: TaskAgentInterfaces.TaskAgentQueueActionFilter): Promise<TaskAgentInterfaces.TaskAgentQueue>;
/**
* @param {string} project - Project ID or project name
* @param {string} queueName
* @param {TaskAgentInterfaces.TaskAgentQueueActionFilter} actionFilter
*/
getAgentQueues(project?: string, queueName?: string, actionFilter?: TaskAgentInterfaces.TaskAgentQueueActionFilter): Promise<TaskAgentInterfaces.TaskAgentQueue[]>;
/**
* @param {number[]} queueIds
* @param {string} project - Project ID or project name
* @param {TaskAgentInterfaces.TaskAgentQueueActionFilter} actionFilter
*/
getAgentQueuesByIds(queueIds: number[], project?: string, actionFilter?: TaskAgentInterfaces.TaskAgentQueueActionFilter): Promise<TaskAgentInterfaces.TaskAgentQueue[]>;
/**
* @param {string[]} queueNames
* @param {string} project - Project ID or project name
* @param {TaskAgentInterfaces.TaskAgentQueueActionFilter} actionFilter
*/
getAgentQueuesByNames(queueNames: string[], project?: string, actionFilter?: TaskAgentInterfaces.TaskAgentQueueActionFilter): Promise<TaskAgentInterfaces.TaskAgentQueue[]>;
/**
* @param {number} agentCloudId
*/
getAgentCloudRequests(agentCloudId: number): Promise<TaskAgentInterfaces.TaskAgentCloudRequest[]>;
/**
*/
getResourceLimits(): Promise<TaskAgentInterfaces.ResourceLimit[]>;
/**
* @param {string} parallelismTag
* @param {boolean} poolIsHosted
* @param {boolean} includeRunningRequests
*/
getResourceUsage(parallelismTag?: string, poolIsHosted?: boolean, includeRunningRequests?: boolean): Promise<TaskAgentInterfaces.ResourceUsage>;
/**
* @param {string} project - Project ID or project name
* @param {string} taskGroupId
*/
getTaskGroupHistory(project: string, taskGroupId: string): Promise<TaskAgentInterfaces.TaskGroupRevision[]>;
/**
* Delete a secure file
*
* @param {string} project - Project ID or project name
* @param {string} secureFileId - The unique secure file Id
*/
deleteSecureFile(project: string, secureFileId: string): Promise<void>;
/**
* Download a secure file by Id
*
* @param {string} project - Project ID or project name
* @param {string} secureFileId - The unique secure file Id
* @param {string} ticket - A valid download ticket
* @param {boolean} download - If download is true, the file is sent as attachement in the response body. If download is false, the response body contains the file stream.
*/
downloadSecureFile(project: string, secureFileId: string, ticket: string, download?: boolean): Promise<NodeJS.ReadableStream>;
/**
* Get a secure file
*
* @param {string} project - Project ID or project name
* @param {string} secureFileId - The unique secure file Id
* @param {boolean} includeDownloadTicket - If includeDownloadTicket is true and the caller has permissions, a download ticket is included in the response.
* @param {TaskAgentInterfaces.SecureFileActionFilter} actionFilter
*/
getSecureFile(project: string, secureFileId: string, includeDownloadTicket?: boolean, actionFilter?: TaskAgentInterfaces.SecureFileActionFilter): Promise<TaskAgentInterfaces.SecureFile>;
/**
* Get secure files
*
* @param {string} project - Project ID or project name
* @param {string} namePattern - Name of the secure file to match. Can include wildcards to match multiple files.
* @param {boolean} includeDownloadTickets - If includeDownloadTickets is true and the caller has permissions, a download ticket for each secure file is included in the response.
* @param {TaskAgentInterfaces.SecureFileActionFilter} actionFilter - Filter by secure file permissions for View, Manage or Use action. Defaults to View.
*/
getSecureFiles(project: string, namePattern?: string, includeDownloadTickets?: boolean, actionFilter?: TaskAgentInterfaces.SecureFileActionFilter): Promise<TaskAgentInterfaces.SecureFile[]>;
/**
* Get secure files
*
* @param {string} project - Project ID or project name
* @param {string[]} secureFileIds - A list of secure file Ids
* @param {boolean} includeDownloadTickets - If includeDownloadTickets is true and the caller has permissions, a download ticket for each secure file is included in the response.
* @param {TaskAgentInterfaces.SecureFileActionFilter} actionFilter
*/
getSecureFilesByIds(project: string, secureFileIds: string[], includeDownloadTickets?: boolean, actionFilter?: TaskAgentInterfaces.SecureFileActionFilter): Promise<TaskAgentInterfaces.SecureFile[]>;
/**
* Get secure files
*
* @param {string} project - Project ID or project name
* @param {string[]} secureFileNames - A list of secure file Ids
* @param {boolean} includeDownloadTickets - If includeDownloadTickets is true and the caller has permissions, a download ticket for each secure file is included in the response.
* @param {TaskAgentInterfaces.SecureFileActionFilter} actionFilter
*/
getSecureFilesByNames(project: string, secureFileNames: string[], includeDownloadTickets?: boolean, actionFilter?: TaskAgentInterfaces.SecureFileActionFilter): Promise<TaskAgentInterfaces.SecureFile[]>;
/**
* Query secure files using a name pattern and a condition on file properties.
*
* @param {string} condition - The main condition syntax is described [here](https://go.microsoft.com/fwlink/?linkid=842996). Use the *property('property-name')* function to access the value of the specified property of a secure file. It returns null if the property is not set. E.g. ``` and( eq( property('devices'), '2' ), in( property('provisioning profile type'), 'ad hoc', 'development' ) ) ```
* @param {string} project - Project ID or project name
* @param {string} namePattern - Name of the secure file to match. Can include wildcards to match multiple files.
*/
querySecureFilesByProperties(condition: string, project: string, namePattern?: string): Promise<TaskAgentInterfaces.SecureFile[]>;
/**
* Update the name or properties of an existing secure file
*
* @param {TaskAgentInterfaces.SecureFile} secureFile - The secure file with updated name and/or properties
* @param {string} project - Project ID or project name
* @param {string} secureFileId - The unique secure file Id
*/
updateSecureFile(secureFile: TaskAgentInterfaces.SecureFile, project: string, secureFileId: string): Promise<TaskAgentInterfaces.SecureFile>;
/**
* Update properties and/or names of a set of secure files. Files are identified by their IDs. Properties provided override the existing one entirely, i.e. do not merge.
*
* @param {TaskAgentInterfaces.SecureFile[]} secureFiles - A list of secure file objects. Only three field must be populated Id, Name, and Properties. The rest of fields in the object are ignored.
* @param {string} project - Project ID or project name
*/
updateSecureFiles(secureFiles: TaskAgentInterfaces.SecureFile[], project: string): Promise<TaskAgentInterfaces.SecureFile[]>;
/**
* Upload a secure file, include the file stream in the request body
*
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} project - Project ID or project name
* @param {string} name - Name of the file to upload
*/
uploadSecureFile(customHeaders: any, contentStream: NodeJS.ReadableStream, project: string, name: string): Promise<TaskAgentInterfaces.SecureFile>;
/**
* @param {TaskAgentInterfaces.ServiceEndpointRequest} serviceEndpointRequest
* @param {string} project - Project ID or project name
* @param {string} endpointId
*/
executeServiceEndpointRequest(serviceEndpointRequest: TaskAgentInterfaces.ServiceEndpointRequest, project: string, endpointId: string): Promise<TaskAgentInterfaces.ServiceEndpointRequestResult>;
/**
* Proxy for a GET request defined by an service endpoint. The request is authorized using a data source in service endpoint. The response is filtered using an XPath/Json based selector.
*
* @param {TaskAgentInterfaces.DataSourceBinding} binding - Describes the data source to fetch.
* @param {string} project - Project ID or project name
*/
queryServiceEndpoint(binding: TaskAgentInterfaces.DataSourceBinding, project: string): Promise<string[]>;
/**
* @param {TaskAgentInterfaces.ServiceEndpoint} endpoint
* @param {string} project - Project ID or project name
*/
createServiceEndpoint(endpoint: TaskAgentInterfaces.ServiceEndpoint, project: string): Promise<TaskAgentInterfaces.ServiceEndpoint>;
/**
* @param {string} project - Project ID or project name
* @param {string} endpointId
*/
deleteServiceEndpoint(project: string, endpointId: string): Promise<void>;
/**
* @param {string} project - Project ID or project name
* @param {string} endpointId
*/
getServiceEndpointDetails(project: string, endpointId: string): Promise<TaskAgentInterfaces.ServiceEndpoint>;
/**
* @param {string} project - Project ID or project name
* @param {string} type
* @param {string[]} authSchemes
* @param {string[]} endpointIds
* @param {boolean} includeFailed
*/
getServiceEndpoints(project: string, type?: string, authSchemes?: string[], endpointIds?: string[], includeFailed?: boolean): Promise<TaskAgentInterfaces.ServiceEndpoint[]>;
/**
* @param {string} project - Project ID or project name
* @param {string[]} endpointNames
* @param {string} type
* @param {string[]} authSchemes
* @param {boolean} includeFailed
*/
getServiceEndpointsByNames(project: string, endpointNames: string[], type?: string, authSchemes?: string[], includeFailed?: boolean): Promise<TaskAgentInterfaces.ServiceEndpoint[]>;
/**
* @param {TaskAgentInterfaces.ServiceEndpoint} endpoint
* @param {string} project - Project ID or project name
* @param {string} endpointId
* @param {string} operation
*/
updateServiceEndpoint(endpoint: TaskAgentInterfaces.ServiceEndpoint, project: string, endpointId: string, operation?: string): Promise<TaskAgentInterfaces.ServiceEndpoint>;
/**
* @param {TaskAgentInterfaces.ServiceEndpoint[]} endpoints
* @param {string} project - Project ID or project name
*/
updateServiceEndpoints(endpoints: TaskAgentInterfaces.ServiceEndpoint[], project: string): Promise<TaskAgentInterfaces.ServiceEndpoint[]>;
/**
* @param {string} type
* @param {string} scheme
*/
getServiceEndpointTypes(type?: string, scheme?: string): Promise<TaskAgentInterfaces.ServiceEndpointType[]>;
/**
* @param {TaskAgentInterfaces.TaskAgentSession} session
* @param {number} poolId
*/
createAgentSession(session: TaskAgentInterfaces.TaskAgentSession, poolId: number): Promise<TaskAgentInterfaces.TaskAgentSession>;
/**
* @param {number} poolId
* @param {string} sessionId
*/
deleteAgentSession(poolId: number, sessionId: string): Promise<void>;
/**
* Register a deployment target to a deployment group. Generally this is called by agent configuration tool.
*
* @param {TaskAgentInterfaces.DeploymentMachine} machine - Deployment target to register.
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group to which the deployment target is registered.
*/
addDeploymentTarget(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
/**
* Delete a deployment target in a deployment group. This deletes the agent from associated deployment pool too.
*
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group in which deployment target is deleted.
* @param {number} targetId - ID of the deployment target to delete.
*/
deleteDeploymentTarget(project: string, deploymentGroupId: number, targetId: number): Promise<void>;
/**
* Get a deployment target by its ID in a deployment group
*
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group to which deployment target belongs.
* @param {number} targetId - ID of the deployment target to return.
* @param {TaskAgentInterfaces.DeploymentTargetExpands} expand - Include these additional details in the returned objects.
*/
getDeploymentTarget(project: string, deploymentGroupId: number, targetId: number, expand?: TaskAgentInterfaces.DeploymentTargetExpands): Promise<TaskAgentInterfaces.DeploymentMachine>;
/**
* Get a list of deployment targets in a deployment group.
*
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group.
* @param {string[]} tags - Get only the deployment targets that contain all these comma separted list of tags.
* @param {string} name - Name pattern of the deployment targets to return.
* @param {boolean} partialNameMatch - When set to true, treats **name** as pattern. Else treats it as absolute match. Default is **false**.
* @param {TaskAgentInterfaces.DeploymentTargetExpands} expand - Include these additional details in the returned objects.
* @param {TaskAgentInterfaces.TaskAgentStatusFilter} agentStatus - Get only deployment targets that have this status.
* @param {TaskAgentInterfaces.TaskAgentJobResultFilter} agentJobResult - Get only deployment targets that have this last job result.
* @param {string} continuationToken - Get deployment targets with names greater than this continuationToken lexicographically.
* @param {number} top - Maximum number of deployment targets to return. Default is **1000**.
* @param {boolean} enabled - Get only deployment targets that are enabled or disabled. Default is 'null' which returns all the targets.
*/
getDeploymentTargets(project: string, deploymentGroupId: number, tags?: string[], name?: string, partialNameMatch?: boolean, expand?: TaskAgentInterfaces.DeploymentTargetExpands, agentStatus?: TaskAgentInterfaces.TaskAgentStatusFilter, agentJobResult?: TaskAgentInterfaces.TaskAgentJobResultFilter, continuationToken?: string, top?: number, enabled?: boolean): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
/**
* Replace a deployment target in a deployment group. Generally this is called by agent configuration tool.
*
* @param {TaskAgentInterfaces.DeploymentMachine} machine - New deployment target.
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group in which deployment target is replaced.
* @param {number} targetId - ID of the deployment target to replace.
*/
replaceDeploymentTarget(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number, targetId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
/**
* Update a deployment target and its agent properties in a deployment group. Generally this is called by agent configuration tool.
*
* @param {TaskAgentInterfaces.DeploymentMachine} machine - Deployment target to update.
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group in which deployment target is updated.
* @param {number} targetId - ID of the deployment target to update.
*/
updateDeploymentTarget(machine: TaskAgentInterfaces.DeploymentMachine, project: string, deploymentGroupId: number, targetId: number): Promise<TaskAgentInterfaces.DeploymentMachine>;
/**
* Update tags of a list of deployment targets in a deployment group.
*
* @param {TaskAgentInterfaces.DeploymentTargetUpdateParameter[]} machines - Deployment targets with tags to udpdate.
* @param {string} project - Project ID or project name
* @param {number} deploymentGroupId - ID of the deployment group in which deployment targets are updated.
*/
updateDeploymentTargets(machines: TaskAgentInterfaces.DeploymentTargetUpdateParameter[], project: string, deploymentGroupId: number): Promise<TaskAgentInterfaces.DeploymentMachine[]>;
/**
* Create a task group.
*
* @param {TaskAgentInterfaces.TaskGroupCreateParameter} taskGroup - Task group object to create.
* @param {string} project - Project ID or project name
*/
addTaskGroup(taskGroup: TaskAgentInterfaces.TaskGroupCreateParameter, project: string): Promise<TaskAgentInterfaces.TaskGroup>;
/**
* Delete a task group.
*
* @param {string} project - Project ID or project name
* @param {string} taskGroupId - Id of the task group to be deleted.
* @param {string} comment - Comments to delete.
*/
deleteTaskGroup(project: string, taskGroupId: string, comment?: string): Promise<void>;
/**
* Get task group.
*
* @param {string} project - Project ID or project name
* @param {string} taskGroupId - Id of the task group.
* @param {string} versionSpec - version specification of the task group. examples: 1, 1.0.
* @param {TaskAgentInterfaces.TaskGroupExpands} expand - The properties that should be expanded. example $expand=Tasks will expand nested task groups.
*/
getTaskGroup(project: string, taskGroupId: string, versionSpec: string, expand?: TaskAgentInterfaces.TaskGroupExpands): Promise<TaskAgentInterfaces.TaskGroup>;
/**
* @param {string} project - Project ID or project name
* @param {string} taskGroupId
* @param {number} revision
*/
getTaskGroupRevision(project: string, taskGroupId: string, revision: number): Promise<NodeJS.ReadableStream>;
/**
* List task groups.
*
* @param {string} project - Project ID or project name
* @param {string} taskGroupId - Id of the task group.
* @param {boolean} expanded - 'true' to recursively expand task groups. Default is 'false'.
* @param {string} taskIdFilter - Guid of the taskId to filter.
* @param {boolean} deleted - 'true'to include deleted task groups. Default is 'false'.
* @param {number} top - Number of task groups to get.
* @param {Date} continuationToken - Gets the task groups after the continuation token provided.
* @param {TaskAgentInterfaces.TaskGroupQueryOrder} queryOrder - Gets the results in the defined order. Default is 'CreatedOnDescending'.
*/
getTaskGroups(project: string, taskGroupId?: string, expanded?: boolean, taskIdFilter?: string, deleted?: boolean, top?: number, continuationToken?: Date, queryOrder?: TaskAgentInterfaces.TaskGroupQueryOrder): Promise<TaskAgentInterfaces.TaskGroup[]>;
/**
* @param {TaskAgentInterfaces.TaskGroup} taskGroup
* @param {string} project - Project ID or project name
* @param {string} taskGroupId
* @param {boolean} disablePriorVersions
*/
publishPreviewTaskGroup(taskGroup: TaskAgentInterfaces.TaskGroup, project: string, taskGroupId: string, disablePriorVersions?: boolean): Promise<TaskAgentInterfaces.TaskGroup[]>;
/**
* @param {TaskAgentInterfaces.PublishTaskGroupMetadata} taskGroupMetadata
* @param {string} project - Project ID or project name
* @param {string} parentTaskGroupId
*/
publishTaskGroup(taskGroupMetadata: TaskAgentInterfaces.PublishTaskGroupMetadata, project: string, parentTaskGroupId: string): Promise<TaskAgentInterfaces.TaskGroup[]>;
/**
* @param {TaskAgentInterfaces.TaskGroup} taskGroup
* @param {string} project - Project ID or project name
*/
undeleteTaskGroup(taskGroup: TaskAgentInterfaces.TaskGroup, project: string): Promise<TaskAgentInterfaces.TaskGroup[]>;
/**
* Update a task group.
*
* @param {TaskAgentInterfaces.TaskGroupUpdateParameter} taskGroup - Task group to update.
* @param {string} project - Project ID or project name
* @param {string} taskGroupId - Id of the task group to update.
*/
updateTaskGroup(taskGroup: TaskAgentInterfaces.TaskGroupUpdateParameter, project: string, taskGroupId?: string): Promise<TaskAgentInterfaces.TaskGroup>;
/**
* @param {string} taskId
*/
deleteTaskDefinition(taskId: string): Promise<void>;
/**
* @param {string} taskId
* @param {string} versionString
* @param {string[]} visibility
* @param {boolean} scopeLocal
*/
getTaskContentZip(taskId: string, versionString: string, visibility?: string[], scopeLocal?: boolean): Promise<NodeJS.ReadableStream>;
/**
* @param {string} taskId
* @param {string} versionString
* @param {string[]} visibility
* @param {boolean} scopeLocal
*/
getTaskDefinition(taskId: string, versionString: string, visibility?: string[], scopeLocal?: boolean): Promise<TaskAgentInterfaces.TaskDefinition>;
/**
* @param {string} taskId
* @param {string[]} visibility
* @param {boolean} scopeLocal
*/
getTaskDefinitions(taskId?: string, visibility?: string[], scopeLocal?: boolean): Promise<TaskAgentInterfaces.TaskDefinition[]>;
/**
* @param {number} poolId
* @param {number} agentId
* @param {string} currentState
*/
updateAgentUpdateState(poolId: number, agentId: number, currentState: string): Promise<TaskAgentInterfaces.TaskAgent>;
/**
* @param {{ [key: string] : string; }} userCapabilities
* @param {number} poolId
* @param {number} agentId
*/
updateAgentUserCapabilities(userCapabilities: {
[key: string]: string;
}, poolId: number, agentId: number): Promise<TaskAgentInterfaces.TaskAgent>;
/**
* Add a variable group.
*
* @param {TaskAgentInterfaces.VariableGroupParameters} group - Variable group to add.
* @param {string} project - Project ID or project name
*/
addVariableGroup(group: TaskAgentInterfaces.VariableGroupParameters, project: string): Promise<TaskAgentInterfaces.VariableGroup>;
/**
* Delete a variable group
*
* @param {string} project - Project ID or project name
* @param {number} groupId - Id of the variable group.
*/
deleteVariableGroup(project: string, groupId: number): Promise<void>;
/**
* Get a variable group.
*
* @param {string} project - Project ID or project name
* @param {number} groupId - Id of the variable group.
*/
getVariableGroup(project: string, groupId: number): Promise<TaskAgentInterfaces.VariableGroup>;
/**
* Get variable groups.
*
* @param {string} project - Project ID or project name
* @param {string} groupName - Name of variable group.
* @param {TaskAgentInterfaces.VariableGroupActionFilter} actionFilter - Action filter for the variable group. It specifies the action which can be performed on the variable groups.
* @param {number} top - Number of variable groups to get.
* @param {number} continuationToken - Gets the variable groups after the continuation token provided.
* @param {TaskAgentInterfaces.VariableGroupQueryOrder} queryOrder - Gets the results in the defined order. Default is 'IdDescending'.
*/
getVariableGroups(project: string, groupName?: string, actionFilter?: TaskAgentInterfaces.VariableGroupActionFilter, top?: number, continuationToken?: number, queryOrder?: TaskAgentInterfaces.VariableGroupQueryOrder): Promise<TaskAgentInterfaces.VariableGroup[]>;
/**
* Get variable groups by ids.
*
* @param {string} project - Project ID or project name
* @param {number[]} groupIds - Comma separated list of Ids of variable groups.
*/
getVariableGroupsById(project: string, groupIds: number[]): Promise<TaskAgentInterfaces.VariableGroup[]>;
/**
* Update a variable group.
*
* @param {TaskAgentInterfaces.VariableGroupParameters} group - Variable group to update.
* @param {string} project - Project ID or project name
* @param {number} groupId - Id of the variable group to update.
*/
updateVariableGroup(group: TaskAgentInterfaces.VariableGroupParameters, project: string, groupId: number): Promise<TaskAgentInterfaces.VariableGroup>;
/**
* @param {TaskAgentInterfaces.AadOauthTokenRequest} authenticationRequest
*/
acquireAccessToken(authenticationRequest: TaskAgentInterfaces.AadOauthTokenRequest): Promise<TaskAgentInterfaces.AadOauthTokenResult>;
/**
* @param {string} tenantId
* @param {string} redirectUri
* @param {TaskAgentInterfaces.AadLoginPromptOption} promptOption
* @param {string} completeCallbackPayload
* @param {boolean} completeCallbackByAuthCode
*/
createAadOAuthRequest(tenantId: string, redirectUri: string, promptOption?: TaskAgentInterfaces.AadLoginPromptOption, completeCallbackPayload?: string, completeCallbackByAuthCode?: boolean): Promise<string>;
/**
*/
getVstsAadTenantId(): Promise<string>;
} | the_stack |
import {Component, ComponentType} from 'react';
import * as PropTypes from 'prop-types';
import {v4} from 'uuid';
import {toast, ToastContainer} from 'react-toastify';
import {omit, pick} from 'lodash';
import {addFilesAction, FileIndexReducerType, removeFileAction, updateFileAction} from '../redux/fileIndexReducer';
import {GtoveDispatchProp} from '../redux/mainReducer';
import InputButton from '../presentation/inputButton';
import * as constants from '../util/constants';
import FileThumbnail from '../presentation/fileThumbnail';
import BreadCrumbs from '../presentation/breadCrumbs';
import {
AnyAppProperties,
AnyProperties,
anyPropertiesTooLong,
DriveMetadata,
isTabletopFileMetadata,
isWebLinkProperties,
} from '../util/googleDriveUtils';
import {FileAPIContext, OnProgressParams, splitFileName} from '../util/fileUtils';
import RenameFileEditor from '../presentation/renameFileEditor';
import {PromiseModalContext} from '../context/promiseModalContextBridge';
import {TextureLoaderContext} from '../util/driveTextureLoader';
import {DropDownMenuClickParams, DropDownMenuOption} from '../presentation/dropDownMenu';
import Spinner from '../presentation/spinner';
import InputField from '../presentation/inputField';
import SearchBar from '../presentation/searchBar';
import RubberBandGroup, {makeSelectableChildHOC} from '../presentation/rubberBandGroup';
import {updateFolderStackAction} from '../redux/folderStacksReducer';
const SelectableFileThumbnail = makeSelectableChildHOC(FileThumbnail);
export type BrowseFilesCallback<A extends AnyAppProperties, B extends AnyProperties, C> = (metadata: DriveMetadata<A, B>, parameters?: DropDownMenuClickParams) => C;
export type BrowseFilesComponentGlobalAction<A extends AnyAppProperties, B extends AnyProperties> = {
label: string;
createsFile: boolean;
onClick: (parents: string[]) => Promise<DriveMetadata<A, B> | undefined>;
hidden?: boolean;
};
interface BrowseFilesComponentFileOnClickOptionalResult<A extends AnyAppProperties, B extends AnyProperties> {
postAction: string;
metadata: DriveMetadata<A, B>
}
export type BrowseFilesComponentFileAction<A extends AnyAppProperties, B extends AnyProperties> = {
label: string;
onClick: 'edit' | 'delete' | 'select' | BrowseFilesCallback<A, B, void | Promise<void | BrowseFilesComponentFileOnClickOptionalResult<A, B>>>;
disabled?: BrowseFilesCallback<A, B, boolean>;
};
interface BrowseFilesComponentProps<A extends AnyAppProperties, B extends AnyProperties> extends GtoveDispatchProp {
files: FileIndexReducerType;
topDirectory: string;
folderStack: string[];
fileActions: BrowseFilesComponentFileAction<A, B>[];
fileIsNew?: BrowseFilesCallback<A, B, boolean>;
editorComponent: ComponentType<any>;
editorExtraProps?: {[key: string]: any};
onBack?: () => void;
allowMultiPick: boolean;
globalActions?: BrowseFilesComponentGlobalAction<A, B>[];
allowUploadAndWebLink: boolean;
screenInfo?: React.ReactElement<any> | ((directory: string, fileIds: string[], loading: boolean) => React.ReactElement<any>);
highlightMetadataId?: string;
jsonIcon?: string | BrowseFilesCallback<A, B, React.ReactElement<any>>;
showSearch: boolean;
}
interface BrowseFilesComponentState {
editMetadata?: DriveMetadata;
newFile: boolean;
uploadProgress: {[key: string]: number};
loading: boolean;
uploading: boolean;
showBusySpinner: boolean;
searchResult?: DriveMetadata[];
searchTerm?: string;
selectedMetadataIds?: {[metadataId: string]: boolean};
}
export default class BrowseFilesComponent<A extends AnyAppProperties, B extends AnyProperties> extends Component<BrowseFilesComponentProps<A, B>, BrowseFilesComponentState> {
static URL_REGEX = new RegExp('^[a-z][-a-z0-9+.]*:\\/\\/(%[0-9a-f][0-9a-f]|[-a-z0-9._~!$&\'()*+,;=:])*\\/');
static contextTypes = {
fileAPI: PropTypes.object,
textureLoader: PropTypes.object,
promiseModal: PropTypes.func
};
context: FileAPIContext & TextureLoaderContext & PromiseModalContext;
constructor(props: BrowseFilesComponentProps<A, B>) {
super(props);
this.onClickThumbnail = this.onClickThumbnail.bind(this);
this.onUploadInput = this.onUploadInput.bind(this);
this.onWebLinksPressed = this.onWebLinksPressed.bind(this);
this.onPaste = this.onPaste.bind(this);
this.showBusySpinner = this.showBusySpinner.bind(this);
this.onRubberBandSelectIds = this.onRubberBandSelectIds.bind(this);
this.state = {
editMetadata: undefined,
newFile: false,
uploadProgress: {},
loading: false,
uploading: false,
showBusySpinner: false
};
}
componentDidMount() {
this.loadCurrentDirectoryFiles();
// Register onPaste event manually, because user-select: none disables clipboard events in Chrome
document.addEventListener('paste', this.onPaste);
}
componentWillUnmount() {
document.removeEventListener('paste', this.onPaste);
}
componentDidUpdate(prevProps: BrowseFilesComponentProps<A, B>) {
if (prevProps.folderStack.length !== this.props.folderStack.length && !this.state.loading) {
this.loadCurrentDirectoryFiles();
}
}
async loadCurrentDirectoryFiles() {
const currentFolderId = this.props.folderStack[this.props.folderStack.length - 1];
const leftBehind = (this.props.files.children[currentFolderId] || []).reduce((all, fileId) => {
all[fileId] = true;
return all;
}, {});
this.setState({loading: true});
try {
await this.context.fileAPI.loadFilesInFolder(currentFolderId, (files: DriveMetadata[]) => {
this.props.dispatch(addFilesAction(files));
files.forEach((metadata) => {leftBehind[metadata.id] = false});
});
// Clean up any files that are no longer in directory
Object.keys(leftBehind)
.filter((fileId) => (leftBehind[fileId]))
.forEach((fileId) => {
this.props.dispatch(removeFileAction({id: fileId, parents: [currentFolderId]}));
});
} catch (err) {
console.log('Error getting contents of current folder', err);
}
this.setState({loading: false});
}
createPlaceholderFile(name: string, parents: string[]): DriveMetadata {
// Dispatch a placeholder file
const placeholder: DriveMetadata = {id: v4(), name, parents, trashed: false, appProperties: undefined, properties: undefined};
this.setState((prevState) => ({uploadProgress: {...prevState.uploadProgress, [placeholder.id]: 0}}), () => {
this.props.dispatch(addFilesAction([placeholder]));
});
return placeholder;
}
cleanUpPlaceholderFile(placeholder: DriveMetadata, driveMetadata: DriveMetadata | null) {
this.props.dispatch(removeFileAction(placeholder));
if (driveMetadata) {
this.props.dispatch(addFilesAction([driveMetadata]));
}
this.setState((prevState) => {
let uploadProgress = {...prevState.uploadProgress};
delete(uploadProgress[placeholder.id]);
return {uploadProgress};
});
return driveMetadata;
}
async uploadSingleFile(file: File, parents: string[], placeholderId: string): Promise<DriveMetadata> {
const driveMetadata = await this.context.fileAPI.uploadFile({name: file.name, parents}, file, (progress: OnProgressParams) => {
this.setState((prevState) => {
return {
uploadProgress: {
...prevState.uploadProgress,
[placeholderId]: progress.loaded / progress.total
}
}
});
});
await this.context.fileAPI.makeFileReadableToAll(driveMetadata);
return driveMetadata;
}
private isMetadataOwnedByMe(metadata: DriveMetadata) {
return metadata.owners && metadata.owners.reduce((me, owner) => (me || owner.me), false)
}
async uploadMultipleFiles(fileArray: File[]) {
const parents = this.props.folderStack.slice(this.props.folderStack.length - 1);
const placeholders = fileArray.map((file) => (this.createPlaceholderFile(file && file.name, parents)));
// Wait for the setState to finish before proceeding with upload.
await new Promise<void>((resolve) => {this.setState({uploading: true}, resolve)});
let metadata;
for (let index = 0; index < fileArray.length; ++index) {
const file = fileArray[index];
if (this.state.uploading && file) {
metadata = await this.uploadSingleFile(file, parents, placeholders[index].id);
this.cleanUpPlaceholderFile(placeholders[index], metadata);
}
}
if (metadata && fileArray.length === 1 && this.isMetadataOwnedByMe(metadata)) {
// For single file upload, automatically edit after creating if it's owned by me
this.setState({editMetadata: metadata, newFile: true});
}
this.setState({uploading: false});
}
onUploadInput(event?: React.ChangeEvent<HTMLInputElement>) {
if (event && event.target.files) {
this.uploadMultipleFiles(Array.from(event.target.files));
}
}
getFilenameFromUrl(url: string): string {
return url.split('#').shift()!.split('?').shift()!.split('/').pop()!;
}
uploadWebLinks(text: string) {
const webLinks = text.split(/\s+/)
.filter((text) => (text.toLowerCase().match(BrowseFilesComponent.URL_REGEX)));
if (webLinks.length > 0) {
const parents = this.props.folderStack.slice(this.props.folderStack.length - 1);
const placeholders = webLinks.map((link) => (this.createPlaceholderFile(this.getFilenameFromUrl(link), parents)));
this.setState({uploading: true}, () => {
webLinks
.reduce((promiseChain: Promise<null | DriveMetadata>, webLink, index) => (
promiseChain.then(() => {
const metadata: Partial<DriveMetadata> = {
name: this.getFilenameFromUrl(webLink),
parents: this.props.folderStack.slice(this.props.folderStack.length - 1),
properties: {webLink}
};
if (anyPropertiesTooLong(metadata.properties)) {
toast(`URL is too long: ${webLink}`);
return this.cleanUpPlaceholderFile(placeholders[index], null);
} else {
return this.context.fileAPI.uploadFileMetadata(metadata)
.then((driveMetadata: DriveMetadata) => {
return this.context.fileAPI.makeFileReadableToAll(driveMetadata)
.then(() => (this.cleanUpPlaceholderFile(placeholders[index], driveMetadata)));
})
}
})
), Promise.resolve(null))
.then((driveMetadata) => {
if (driveMetadata && webLinks.length === 1 && this.isMetadataOwnedByMe(driveMetadata)) {
// For single file upload, automatically edit after creating if it's owned by me
this.setState({editMetadata: driveMetadata, newFile: true});
}
this.setState({uploading: false})
});
});
}
}
async onWebLinksPressed() {
let textarea: HTMLTextAreaElement;
if (this.context.promiseModal?.isAvailable()) {
const result = await this.context.promiseModal({
className: 'webLinkModal',
children: (
<textarea
ref={(element: HTMLTextAreaElement) => {textarea = element}}
placeholder='Enter the URLs of one or more images, separated by spaces.'
/>
),
options: [
{label: 'Create links to images', value: () => (textarea.value)},
{label: 'Cancel', value: null}
]
});
if (result) {
this.uploadWebLinks(result);
}
}
}
onPaste(event: ClipboardEvent) {
// Only support paste on pages which allow upload.
if (this.props.allowUploadAndWebLink && event.clipboardData) {
if (event.clipboardData.files && event.clipboardData.files.length > 0) {
this.uploadMultipleFiles(Array.from(event.clipboardData.files));
} else {
this.uploadWebLinks(event.clipboardData.getData('text'));
}
}
}
async onGlobalAction(action: BrowseFilesComponentGlobalAction<A, B>) {
const parents = this.props.folderStack.slice(this.props.folderStack.length - 1);
const placeholder = action.createsFile ? this.createPlaceholderFile('', parents) : undefined;
const driveMetadata = await action.onClick(parents);
if (placeholder && driveMetadata) {
this.cleanUpPlaceholderFile(placeholder, driveMetadata);
if (this.isMetadataOwnedByMe(driveMetadata)) {
this.setState({editMetadata: driveMetadata, newFile: true});
}
}
}
onEditFile(metadata: DriveMetadata) {
this.setState({editMetadata: metadata, newFile: false});
}
async onDeleteFile(metadata: DriveMetadata) {
if (this.context.promiseModal?.isAvailable()) {
if (metadata.id === this.props.highlightMetadataId) {
await this.context.promiseModal({
children: 'Can\'t delete the currently selected file.'
});
} else {
const yesOption = 'Yes';
const response = await this.context.promiseModal({
children: `Are you sure you want to delete ${metadata.name}?`,
options: [yesOption, 'Cancel']
});
if (response === yesOption) {
this.props.dispatch(removeFileAction(metadata));
await this.context.fileAPI.deleteFile(metadata);
if (isTabletopFileMetadata(metadata)) {
// Also trash the private GM file.
await this.context.fileAPI.deleteFile({id: metadata.appProperties.gmFile});
}
}
}
}
}
onSelectFile(metadata: DriveMetadata) {
this.setState(({selectedMetadataIds}) => ({
selectedMetadataIds: selectedMetadataIds ? {...selectedMetadataIds, [metadata.id]: true} : {[metadata.id]: true}
}));
}
onRubberBandSelectIds(updatedIds: {[metadataId: string]: boolean}) {
const selectedMetadataIds = this.state.selectedMetadataIds;
if (selectedMetadataIds) {
const selected = Object.keys(updatedIds).reduce<undefined | {[key: string]: boolean}>((selected, metadataId) => {
if (selectedMetadataIds[metadataId]) {
// We need to explicitly test === false rather than using !updatedIds[metadataId] because the
// metadataId may not even be in updatedIds (if it's a file in a different directory) and !undefined
// is also true.
if (updatedIds[metadataId] === false) {
return omit(selected || selectedMetadataIds, metadataId);
}
} else if (updatedIds[metadataId]) {
if (!selected) {
selected = {...selectedMetadataIds};
}
selected[metadataId] = true;
}
return selected;
}, undefined);
if (selected) {
this.setState({selectedMetadataIds: Object.keys(selected).length > 0 ? selected : undefined});
}
} else {
const selectedIds = Object.keys(updatedIds).filter((metadataId) => (updatedIds[metadataId]));
if (Object.keys(selectedIds).length > 0) {
this.setState({selectedMetadataIds: pick(updatedIds, selectedIds)});
}
}
}
private showBusySpinner(show: boolean) {
this.setState({showBusySpinner: show});
}
onClickThumbnail(fileId: string) {
const metadata = this.props.files.driveMetadata[fileId] as DriveMetadata<A, B>;
const fileMenu = this.buildFileMenu(metadata);
// Perform the first enabled menu action
const firstItem = fileMenu.find((menuItem) => (!menuItem.disabled));
if (firstItem) {
firstItem.onClick({showBusySpinner: this.showBusySpinner});
}
}
async onAddFolder(prefix = ''): Promise<void> {
const promiseModal = this.context.promiseModal;
if (!promiseModal?.isAvailable()) {
return;
}
const okResponse = 'OK';
let name: string = 'New Folder';
const returnAction = () => {promiseModal.setResult(okResponse)};
const response = await promiseModal({
options: [okResponse, 'Cancel'],
children: (
<div>
{prefix + 'Please enter the name of the new folder.'}
<InputField type='text' initialValue={name} select={true} focus={true}
specialKeys={{Return: returnAction, Enter: returnAction}}
onChange={(value: string) => {name = value}}
/>
</div>
)
});
if (response === okResponse && name) {
// Check the name is unique
const currentFolder = this.props.folderStack[this.props.folderStack.length - 1];
const valid = (this.props.files.children[currentFolder] || []).reduce((valid, fileId) => {
return valid && (name.toLowerCase() !== this.props.files.driveMetadata[fileId].name.toLowerCase());
}, true);
if (valid) {
this.setState({loading: true});
const metadata = await this.context.fileAPI.createFolder(name, {parents:[currentFolder]});
this.props.dispatch(addFilesAction([metadata]));
this.setState({loading: false});
} else {
return this.onAddFolder('That name is already in use. ');
}
}
}
buildFileMenu(metadata: DriveMetadata<A, B>): DropDownMenuOption<BrowseFilesComponentFileOnClickOptionalResult<A, B>>[] {
const isFolder = (metadata.mimeType === constants.MIME_TYPE_DRIVE_FOLDER);
let fileActions: BrowseFilesComponentFileAction<A, B>[] = isFolder ? [
{label: 'Open', onClick: () => {
this.props.dispatch(updateFolderStackAction(this.props.topDirectory, [...this.props.folderStack, metadata.id]));
}},
{label: 'Rename', onClick: 'edit'},
{label: 'Select', onClick: 'select'},
{label: 'Delete', onClick: 'delete', disabled: () => (metadata.id === this.props.highlightMetadataId)}
] : this.props.fileActions;
if (this.state.searchResult) {
fileActions = [...fileActions, {
label: 'View in folder',
onClick: async () => {
this.setState({showBusySpinner: true});
// Need to build the breadcrumbs
const rootFolderId = this.props.files.roots[this.props.topDirectory];
const folderStack = [];
for (let folderId = metadata.parents[0]; folderId !== rootFolderId; folderId = this.props.files.driveMetadata[folderId].parents[0]) {
folderStack.push(folderId);
if (!this.props.files.driveMetadata[folderId]) {
this.props.dispatch(addFilesAction([await this.context.fileAPI.getFullMetadata(folderId)]));
}
}
folderStack.push(rootFolderId);
this.props.dispatch(updateFolderStackAction(this.props.topDirectory, folderStack.reverse()));
this.setState({showBusySpinner: false, searchTerm: undefined, searchResult: undefined});
}}];
}
return fileActions.map((fileAction) => {
let disabled = fileAction.disabled ? fileAction.disabled(metadata) : false;
const selected = this.state.selectedMetadataIds ? this.state.selectedMetadataIds[metadata.id] : false;
let onClick;
const fileActionOnClick = fileAction.onClick;
if (fileActionOnClick === 'edit') {
onClick = () => (this.onEditFile(metadata));
} else if (fileActionOnClick === 'delete') {
onClick = () => (this.onDeleteFile(metadata));
} else if (fileActionOnClick === 'select') {
onClick = () => (this.onSelectFile(metadata));
disabled = disabled || selected;
} else {
onClick = async (parameters: DropDownMenuClickParams) => {
const result = await fileActionOnClick(metadata, parameters);
if (result && result.postAction === 'edit') {
this.onEditFile(result.metadata);
}
};
}
return {
label: fileAction.label,
disabled,
onClick
};
});
}
renderFileThumbnail(metadata: DriveMetadata<A, B>, overrideOnClick?: (fileId: string) => void) {
const isFolder = (metadata.mimeType === constants.MIME_TYPE_DRIVE_FOLDER);
const isJson = (metadata.mimeType === constants.MIME_TYPE_JSON);
const name = (metadata.appProperties || metadata.properties) ? splitFileName(metadata.name).name : metadata.name;
const menuOptions = overrideOnClick ? undefined : this.buildFileMenu(metadata);
return (
<SelectableFileThumbnail
childId={metadata.id}
key={metadata.id}
fileId={metadata.id}
name={name}
isFolder={isFolder}
isIcon={isJson}
isNew={this.props.fileIsNew ? (!isFolder && !isJson && this.props.fileIsNew(metadata)) : false}
progress={this.state.uploadProgress[metadata.id]}
thumbnailLink={isWebLinkProperties(metadata.properties) ? metadata.properties.webLink : metadata.thumbnailLink}
onClick={overrideOnClick || this.onClickThumbnail}
highlight={this.props.highlightMetadataId === metadata.id || (this.state.selectedMetadataIds && this.state.selectedMetadataIds[metadata.id])}
menuOptions={menuOptions}
icon={(typeof(this.props.jsonIcon) === 'function') ? this.props.jsonIcon(metadata) : this.props.jsonIcon}
showBusySpinner={this.showBusySpinner}
fetchMissingThumbnail={async () => {
// video files can take a while to populate their thumbnailLink, so we need a mechanism to retry
const fullMetadata = await this.context.fileAPI.getFullMetadata(metadata.id);
const thumbnailLink = isWebLinkProperties(fullMetadata.properties) ? fullMetadata.properties.webLink : fullMetadata.thumbnailLink;
if (thumbnailLink) {
this.props.dispatch(updateFileAction(fullMetadata));
}
}}
/>
);
}
renderSearchResults() {
const searchResult = this.state.searchResult!;
return (
<div>
{
searchResult.length === 0 ? (
<p>
No matching results found. Note that the search will not find files which are marked as
<span className='material-icons' style={{color: 'green'}}>fiber_new</span> or folders.
</p>
) : (
searchResult.map((file) => (this.renderFileThumbnail(file as DriveMetadata<A, B>)))
)
}
</div>
);
}
sortMetadataIds(metadataIds: string[] = []): string[] {
return metadataIds.sort((id1, id2) => {
const file1 = this.props.files.driveMetadata[id1];
const file2 = this.props.files.driveMetadata[id2];
const isFolder1 = (file1.mimeType === constants.MIME_TYPE_DRIVE_FOLDER);
const isFolder2 = (file2.mimeType === constants.MIME_TYPE_DRIVE_FOLDER);
if (isFolder1 && !isFolder2) {
return -1;
} else if (!isFolder1 && isFolder2) {
return 1;
} else {
return file1.name < file2.name ? -1 : (file1.name === file2.name ? 0 : 1);
}
});
}
isMovingFolderAncestorOfFolder(movingFolderId: string, folderId: string) {
if (movingFolderId === folderId) {
return true;
}
const metadata = this.props.files.driveMetadata[folderId];
if (metadata && metadata.parents) {
for (let parent of metadata.parents) {
if (this.isMovingFolderAncestorOfFolder(movingFolderId, parent)) {
return true;
}
}
}
return false;
}
isSelectedMoveValidHere(currentFolder?: string) {
if (currentFolder === undefined) {
return false;
}
if (this.state.selectedMetadataIds) {
// Check if all selected metadata are already in this folder, or if any of them are ancestor folders.
let anyElsewhere = false;
for (let metadataId of Object.keys(this.state.selectedMetadataIds)) {
if (!this.state.selectedMetadataIds[metadataId]) {
// Ignore things that are no longer selected
continue;
}
const metadata = this.props.files.driveMetadata[metadataId];
if (!metadata) {
// If metadata is missing, we need to load it, but also return false in the interim.
this.context.fileAPI.getFullMetadata(metadataId)
.then((metadata) => {this.props.dispatch(addFilesAction([metadata]))});
return false;
}
if (metadata.parents.indexOf(currentFolder) < 0) {
anyElsewhere = true;
}
if (metadata.mimeType === constants.MIME_TYPE_DRIVE_FOLDER && this.isMovingFolderAncestorOfFolder(metadataId, currentFolder)) {
return false;
}
}
return anyElsewhere;
}
return true;
}
renderThumbnails(currentFolder: string) {
const sorted = this.sortMetadataIds(this.props.files.children[currentFolder]);
const folderDepth = this.props.folderStack.length;
return (
<div>
{
folderDepth === 1 ? null : (
<FileThumbnail
fileId={this.props.folderStack[folderDepth - 2]}
name={this.props.files.driveMetadata[this.props.folderStack[folderDepth - 2]].name}
isFolder={false}
isIcon={true}
icon='arrow_back'
isNew={false}
onClick={() => {
this.props.dispatch(updateFolderStackAction(this.props.topDirectory, this.props.folderStack.slice(0, folderDepth - 1)));
}}
showBusySpinner={this.showBusySpinner}
/>
)
}
{
sorted.map((fileId: string) => (
this.renderFileThumbnail(this.props.files.driveMetadata[fileId] as DriveMetadata<A, B>)
))
}
{
!this.state.uploading ? null : (
<InputButton type='button' onChange={() => {this.setState({uploading: false})}}>Cancel uploads</InputButton>
)
}
{
!this.state.loading ? null : (
<div className='fileThumbnail'><Spinner size={60}/></div>
)
}
{
!this.props.screenInfo ? null :
typeof(this.props.screenInfo) === 'function' ? this.props.screenInfo(currentFolder, sorted, this.state.loading) : this.props.screenInfo
}
</div>
);
}
renderSelectedFiles(currentFolder?: string) {
return !this.state.selectedMetadataIds ? null : (
<div className='selectedFiles'>
{
this.state.selectedMetadataIds === undefined ? null : (
<FileThumbnail
fileId={'cancel'} name={'Cancel select'} isFolder={false} isIcon={true} icon='close'
isNew={false} showBusySpinner={this.showBusySpinner} onClick={() => {
this.setState({selectedMetadataIds: undefined});
}}
/>
)
}
<FileThumbnail
fileId={'move'} name={'Move to this folder'} isFolder={false} isIcon={true} icon='arrow_downward'
disabled={!this.isSelectedMoveValidHere(currentFolder)} isNew={false} showBusySpinner={this.showBusySpinner}
onClick={async () => {
const {selectedMetadataIds} = this.state;
// Clear selected files and start loading spinner
this.setState({selectedMetadataIds: undefined, loading: true});
// update parents of selected metadataIds
for (let metadataId of Object.keys(selectedMetadataIds!)) {
const metadata = this.props.files.driveMetadata[metadataId];
if (metadata.parents && metadata.parents.indexOf(currentFolder!) < 0) {
const newMetadata = await this.context.fileAPI.uploadFileMetadata(metadata, [currentFolder!], metadata.parents);
this.props.dispatch(updateFileAction(newMetadata));
}
}
// Trigger refresh of this folder
await this.loadCurrentDirectoryFiles();
}}
/>
{
!this.props.allowMultiPick ? null : (
<FileThumbnail
fileId={'pick'} name={'Pick selected'} isFolder={false} isIcon={true} icon='touch_app'
disabled={Object.keys(this.state.selectedMetadataIds!).length === 0} isNew={false} showBusySpinner={this.showBusySpinner}
onClick={async () => {
const pickAction = this.props.fileActions[0].onClick;
if (pickAction === 'edit' || pickAction === 'select' || pickAction === 'delete') {
return;
}
this.showBusySpinner(true);
const isDisabled = this.props.fileActions[0].disabled;
for (let metadataId of Object.keys(this.state.selectedMetadataIds!)) {
const metadata = this.props.files.driveMetadata[metadataId] as DriveMetadata<A, B>;
if (!isDisabled || !isDisabled(metadata)) {
await pickAction(metadata);
}
}
this.showBusySpinner(false);
}}
/>
)
}
{
this.sortMetadataIds(Object.keys(this.state.selectedMetadataIds).filter((metadataId) => (this.state.selectedMetadataIds![metadataId])))
.map((metadataId) => (
this.renderFileThumbnail(this.props.files.driveMetadata[metadataId] as DriveMetadata<A, B>, (fileId) => {
const selectedMetadataIds = omit(this.state.selectedMetadataIds, fileId);
this.setState({selectedMetadataIds: Object.keys(selectedMetadataIds).length > 0 ? selectedMetadataIds : undefined});
}))
)
}
</div>
);
}
renderBrowseFiles() {
return (
<div className='fullHeight'>
<RubberBandGroup setSelectedIds={this.onRubberBandSelectIds}>
{
!this.props.onBack ? null : (
<InputButton type='button' onChange={this.props.onBack}>Finish</InputButton>
)
}
{
!this.state.searchResult ? null : (
<InputButton type='button' onChange={() => {this.setState({searchResult: undefined, searchTerm: undefined})}}>Clear Search</InputButton>
)
}
{
this.state.searchResult || !this.props.allowUploadAndWebLink ? null : (
<InputButton type='file' multiple={true} onChange={this.onUploadInput}>Upload</InputButton>
)
}
{
this.state.searchResult || !this.props.allowUploadAndWebLink ? null : (
<InputButton type='button' onChange={this.onWebLinksPressed}>Link to Images</InputButton>
)
}
{
this.state.searchResult || !this.props.globalActions ? null : (
this.props.globalActions
.filter((action) => (!action.hidden))
.map((action) => (
<InputButton type='button' key={action.label} onChange={() => (this.onGlobalAction(action))}>{action.label}</InputButton>
))
)
}
{
this.state.searchResult ? null : (
<InputButton type='button' onChange={() => this.onAddFolder()}>Add Folder</InputButton>
)
}
{
this.state.searchResult ? null : (
<InputButton type='button' onChange={() => this.loadCurrentDirectoryFiles()}>Refresh</InputButton>
)
}
{
!this.props.showSearch ? null : (
<SearchBar placeholder={'Search all ' + this.props.topDirectory}
initialValue={this.state.searchTerm || ''}
onSearch={async (searchTerm) => {
if (searchTerm) {
this.setState({showBusySpinner: true});
const matches = await this.context.fileAPI.findFilesContainingNameWithProperty(searchTerm, 'rootFolder', this.props.topDirectory);
this.setState({showBusySpinner: false});
matches.sort((f1, f2) => (f1.name < f2.name ? -1 : f1.name > f2.name ? 1 : 0));
this.setState({searchResult: matches, searchTerm});
this.props.dispatch(addFilesAction(matches));
} else {
this.setState({searchResult: undefined, searchTerm: undefined});
}
}}
/>
)
}
{
this.state.searchResult ? (
<div>{this.props.topDirectory} with names matching "{this.state.searchTerm}"</div>
) : (
<BreadCrumbs folders={this.props.folderStack} files={this.props.files} onChange={(folderStack: string[]) => {
this.props.dispatch(updateFolderStackAction(this.props.topDirectory, folderStack));
}}/>
)
}
{
this.state.searchResult ? this.renderSearchResults() : this.renderThumbnails(this.props.folderStack[this.props.folderStack.length - 1])
}
{
this.renderSelectedFiles(this.state.searchResult ? undefined : this.props.folderStack[this.props.folderStack.length - 1])
}
<ToastContainer className='toastContainer' position={toast.POSITION.BOTTOM_CENTER} hideProgressBar={true}/>
</RubberBandGroup>
</div>
);
}
render() {
if (this.state.editMetadata) {
const Editor = (this.state.editMetadata.mimeType === constants.MIME_TYPE_DRIVE_FOLDER) ? RenameFileEditor : this.props.editorComponent;
return (
<Editor
metadata={this.state.editMetadata}
onClose={() => {this.setState({editMetadata: undefined, newFile: false})}}
textureLoader={this.context.textureLoader}
newFile={this.state.newFile}
{...this.props.editorExtraProps}
/>
);
} else if (this.state.showBusySpinner) {
return (
<div className='fileThumbnail'><Spinner size={60}/></div>
);
} else {
return this.renderBrowseFiles();
}
}
} | the_stack |
import User from 'App/Models/User'
import Encryption from '@ioc:Adonis/Core/Encryption'
import { schema, rules } from '@ioc:Adonis/Core/Validator'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import NoLoginException from '../../Exceptions/NoLoginException'
import Env from '@ioc:Adonis/Core/Env'
import PasswordResetValidator from 'App/Validators/PasswordResetValidator'
import { DateTime } from 'luxon'
import Event from '@ioc:Adonis/Core/Event'
import Hash from '@ioc:Adonis/Core/Hash'
import PasswordChangeValidator from 'App/Validators/PasswordChangeValidator'
import AppRegistrationValidator from 'App/Validators/AppRegistrationValidator'
import UserServices, { randomUserByRole } from 'App/Services/UserServices'
import Role from 'App/Models/Role'
import Logger from '@ioc:Adonis/Core/Logger'
import { CACHE_TAGS } from 'Contracts/cache'
import CacheHelper from 'App/Helpers/CacheHelper'
import { IS_DEMO_MODE } from 'App/Helpers/utils'
import { ROLES } from 'Database/data/roles'
export default class AuthController {
public async register({ request, response, auth }: HttpContextContract) {
// Validate user details
const form = await request.validate(AppRegistrationValidator)
const {
email,
firstName,
middleName,
lastName,
newPassword,
phoneNumber,
address,
city,
stateId,
countryId,
} = form
// Get the CompanyAdmin role
let companyAdminRole
try {
companyAdminRole = await Role.findByOrFail('name', 'CompanyAdmin')
} catch (error) {
Logger.error('Role not found at AuthController.register:\n%o', error)
return response.abort({ message: 'Account could not be created' })
}
// Create a new user
const user = await User.create({
email,
password: newPassword,
isAccountActivated: true,
loginStatus: true,
accountActivatedAt: DateTime.now(),
roleId: companyAdminRole.id,
})
if (user) {
await user.related('profile').create({
firstName,
middleName,
lastName,
phoneNumber,
address,
city,
stateId,
countryId,
})
// Send verification email
Event.emit('auth::new-registration-verification', {
user,
})
const token = await auth.use('api').attempt(email, newPassword)
// Check if credentials are valid, else return error
if (!token)
throw new NoLoginException({ message: 'Email address or password is not correct.' })
/* Retrieve user with company information */
const userService = new UserServices({ email })
const cachedUser = await userService.getUserSummary()
/**
* Emit event to log login activity and
* persist login meta information to DB
* Also Clean up login code information
*/
const ip = request.ip()
Event.emit('auth::new-login', {
ip,
user,
})
return response.created({
message: 'Account was created successfully.',
token: token,
data: cachedUser,
})
} else {
Logger.error('User could not be created at AuthController.register')
return response.abort({ message: 'Account could not be created' })
}
}
public async newAccountEmailVerification({ request, response }: HttpContextContract) {
let { key } = request.body()
if (!key) {
return response.badRequest('Invalid request for password reset validation')
}
const decryptedKey: string = Encryption?.decrypt(key) ?? ''
if (!decryptedKey)
return response.badRequest({ message: 'Invalid request for password reset validation' })
else {
const userId = decryptedKey.split('email-verification-for-')[1]
let user: User
try {
user = await User.findOrFail(userId)
if (user.isEmailVerified) {
return response.ok({ message: 'Your email address is already verified' })
}
user.merge({ isEmailVerified: true, emailVerifiedAt: DateTime.now() })
await user.save()
// 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.ok({ message: 'Thank you! Your email address is verified' })
} catch (error) {
return response.notFound({
message:
'Email verification failed. This could be as a result of an expired or tampered link. Please proceed to Dashboard to request a new one',
})
}
}
}
public async requestEmailVerification({ response, auth }: HttpContextContract) {
const user = auth?.user ?? null
if (user) {
// Send verification email
Event.emit('auth::new-registration-verification', {
user,
})
return response.created({
message:
'Your verification email was sent. Please check your spam/junk folders too. Verification link is valid for 2 days.',
})
} else {
Logger.error('User not found at AuthController.requestEmailVerification')
return response.abort({ message: 'Account not found' })
}
}
public async login({ request, auth, response }: HttpContextContract) {
const { password, email } = request.body()
//const loginRecaptchaHelper = new LoginRecaptchaHelper(recaptchaResponseToken);
if (!IS_DEMO_MODE && !password) {
throw new NoLoginException({
message: 'Invalid credentials',
})
}
const userService = new UserServices({ email: email })
let user = await userService.getUserModel()
if (!user) throw new NoLoginException({ message: 'Log in not allowed' })
else {
// Check if user can log in.
// Get login status
const loginStatus = Boolean(user.loginStatus)
if (!loginStatus) {
throw new NoLoginException({
message: 'Log in is not permitted for this account!',
})
}
// Get activation status
const activationStatus = Boolean(user.isAccountActivated)
if (!activationStatus) {
throw new NoLoginException({
message:
'Your account is not activated. Please activate your account with the activation link sent to you via email.',
})
}
let token
if (IS_DEMO_MODE) {
token = await auth.use('api').login(user)
} else {
token = await auth.use('api').attempt(email, password)
}
// Check if credentials are valid, else return error
if (!token)
throw new NoLoginException({ message: 'Email address or password is not correct.' })
/* Retrieve user with company information */
const cachedUser = await userService.getUserSummary()
//console.log(user)
/**
* Emit event to log login activity and
* persist login meta information to DB
* Also Clean up login code information
*/
const ip = request.ip()
Event.emit('auth::new-login', {
ip,
user,
})
return response.created({
message: 'Login successful.',
token: token,
data: cachedUser,
})
}
}
public async authProfile({ auth, response }: HttpContextContract) {
/* Retrieve user with company information */
const email = auth.user?.email!
const userService = new UserServices({ email: email })
const cachedUser = await userService.getUserSummary()
return response.ok({
data: cachedUser,
})
}
public async requestPasswordReset({ request, response }: HttpContextContract) {
const { email } = request.body()
let user: User
try {
user = await User.findByOrFail('email', email)
} catch (error) {
return response.notFound({ message: 'This email was not found' })
}
// Check if user can log in.
// Get login status
const loginStatus = Boolean(user.loginStatus)
if (!loginStatus) {
throw new NoLoginException({
message: 'Log in is not permitted for this account!',
})
}
// Get activation status
const activationStatus = Boolean(user.isAccountActivated)
if (!activationStatus) {
throw new NoLoginException({
message:
'Your account is not activated. Please activate your account with the activation link sent to you via email.',
})
}
// Get email verification status
const emailVerificationStatus = Boolean(user.isEmailVerified)
if (!emailVerificationStatus) {
throw new NoLoginException({
message:
'Your email address is not verified. Please check your email inbox for a verification sent to you or request for a new verification email from your Church admin. If you are a Church admin, please contact us for assistance.',
})
}
// Step 1: generate encrypted string to be used for email
// This is not meant for storing in var(255) column as
// it is over 255 characters. 282 characters, actually
// Storing as text is not an option too due to indexing cost
// Best bet is to make this stateless
// So encrypted key will be embed in URL is sent via email without storing
const key = Encryption.encrypt(`password-reset-for-${user.id}`, '2 hours', undefined)
const FORGET_PASSWORD_URI = Env.get('FORGET_PASSWORD_URI', 'auth/reset-password')
const FRONTEND_URL = Env.get('FRONTEND_URL')
const passwordResetLink = `${FRONTEND_URL}${FORGET_PASSWORD_URI}/${key}`
console.info(
'\n\n==============\n',
'Use this link to reset your password:\n',
passwordResetLink,
'\n=============='
)
return response.ok({ id: user.email })
}
public async verifyPasswordReset({ request, response }: HttpContextContract) {
let { key } = request.body()
if (!key) {
return response.badRequest('Invalid request for password reset validation')
}
const decryptedKey: string = Encryption?.decrypt(key) ?? ''
if (!decryptedKey) return response.badRequest('Invalid request for password reset validation')
else {
const userId = decryptedKey.split('password-reset-for-')[1]
let user: User
try {
user = await User.findOrFail(userId)
} catch (error) {
return response.notFound({ message: 'Invalid user for password reset validation' })
}
return response.ok({ data: user.email })
}
}
/**
* Reset password via the auth page password reset flow
* @param ctx {HttpContextContract} The HTTP context
* @returns {Promise<void>}
*/
public async ResetPassword({ request, response, auth }: HttpContextContract) {
let { email, newPassword } = await request.validate(PasswordResetValidator)
let user: User
try {
user = await User.findByOrFail('email', email)
} catch (error) {
return response.notFound({ message: 'Invalid user for password reset' })
}
// Verify 'newPassword' against user's old passwords on
// the password_histories table.
await user.load('passwordHistories')
const passwordHistories = user.passwordHistories
for (const history of passwordHistories) {
if (await Hash.verify(history.oldPassword, newPassword)) {
return response.badRequest({
message:
'The password you submitted was already used by you! Please try again with a unique password.',
})
}
}
/**
* If all is green, update password on users table and store old password
* on the password_histories table.
*/
await user.related('passwordHistories').create({
oldPassword: user.password,
})
user.merge({ password: newPassword })
await user.save()
const token = await auth.use('api').attempt(email, newPassword)
// Check if credentials are valid, else return error
if (!token) throw new NoLoginException({ message: 'Email address or password is not correct.' })
/* Retrieve user with company information */
const cachedUser = new UserServices({ email: email }).getUserSummary()
return response.created({
message: 'Password change was successful.',
token: token,
data: cachedUser,
})
}
public async confirmCurrentPassword({ request, response, auth }: HttpContextContract) {
let { currentPassword } = request.body()
if (!currentPassword) {
return response.badRequest('Invalid request. No current password provided!')
}
const user = auth.user
const userEmail = user?.email!
try {
// Check if credentials are valid, else throw an error
await auth.use('api').verifyCredentials(userEmail, currentPassword)
} catch (error) {
return response.badRequest({ message: 'Current password is not valid' })
}
// Create or update password change record for the user
// Most fields are auto-created/auto-updated in the PasswordChange model
// via the beforeSave hooks
await user?.related('passwordChange').updateOrCreate({ userId: user.id }, {})
// reload passwordChange relationship
await user?.load('passwordChange')
const passwordChange = user?.passwordChange
/**
* Fire event and send verification email
*/
Event.emit('auth::send-code', { user: user ?? null, type: 'password_change_code' })
return response.ok({
message:
'Current password is verified. Please check your email address for a confirmation code. Code is valid for only 2 hours.',
data: { secret: passwordChange?.secret },
})
}
public async confirmPasswordCode({ request, response, auth }: HttpContextContract) {
// Validate request
const validationSchema = schema.create({
code: schema.number([rules.required(), rules.unsigned(), rules.range(100000, 999999)]),
secret: schema.string({ trim: true }, [rules.uuid({ version: 5 }), rules.required()]),
})
const validationMessages = {
'code.required': 'Code is required!',
'code.unsigned': 'Code is invalid',
'code.range': 'Code is out of range',
'secret.uuid': 'Secret is invalid',
'secret.required': 'Secret is required',
}
let { code, secret } = await request.validate({
schema: validationSchema,
messages: validationMessages,
})
const user = auth.user!
await user.load('passwordChange')
const passwordChange = user.passwordChange
if (!passwordChange) {
return response.badRequest({ message: 'Password change has not been initiated' })
}
if (passwordChange.verificationCode !== Number(code) || passwordChange.secret !== secret) {
return response.badRequest({ message: 'Invalid data provided' })
}
const NOW = DateTime.now()
const THEN = passwordChange.verificationCodeExpiresAt
if (THEN > NOW.plus({ hours: 2 })) {
return response.badRequest({
message: 'Verification code has expired. Please restart the process',
})
}
return response.ok({
message: 'Everything is green. Please reset your password',
})
}
public async submitNewPassword({ request, response, auth }: HttpContextContract) {
let { newPassword, secret } = await request.validate(PasswordChangeValidator)
const user = auth.user!
await user.load('passwordChange')
const passwordChange = user.passwordChange
if (!passwordChange) {
return response.badRequest({ message: 'Password change has not been initiated' })
}
if (passwordChange.secret !== secret) {
return response.badRequest({ message: 'Invalid password-change session!' })
}
// Verify 'newPassword' against user's old passwords on
// the password_histories table.
await user.load('passwordHistories')
const passwordHistories = user.passwordHistories
for (const history of passwordHistories) {
if (await Hash.verify(history.oldPassword, newPassword)) {
return response.badRequest({
message:
'New password has been used already on Akpoho Software! Please try again with a unique password.',
})
}
}
/**
* If all is green, update password on users table and store old password
* on the password_histories table.
*/
await user.related('passwordHistories').create({
oldPassword: user.password,
})
/**
* `newPassword` is not hashed here because hashing will be handled
* by the `beforeSave` hook on the User model.
*/
user.merge({ password: newPassword })
await user.save()
// Future: flush user cache after this
Event.emit('auth::send-success-emails', { user, type: 'password_change_success' })
return response.created({
message: 'Your password was updated successfully. You can now login with it subsequently.',
})
}
public async demoLoginCredentials({ response }: HttpContextContract) {
if (!IS_DEMO_MODE) return response.ok({ data: {} })
const randomCompanyAdmin = await randomUserByRole(ROLES.COMPANY_ADMIN)
const randomCompanyEditor = await randomUserByRole(ROLES.COMPANY_EDITOR)
const randomCompanyStaff = await randomUserByRole(ROLES.COMPANY_STAFF)
const data = {
admin: randomCompanyAdmin?.[0]?.email ?? '',
editor: randomCompanyEditor?.[0]?.email ?? '',
staff: randomCompanyStaff?.[0]?.email ?? '',
}
return response.ok({
data,
})
}
} | the_stack |
import { ContextLevel } from '@/core/constants';
import { Injectable } from '@angular/core';
import { CoreSyncBaseProvider } from '@classes/base-sync';
import { CoreNetworkError } from '@classes/errors/network-error';
import { CoreApp } from '@services/app';
import { CoreSites } from '@services/sites';
import { CoreTextUtils } from '@services/utils/text';
import { CoreUtils } from '@services/utils/utils';
import { makeSingleton } from '@singletons';
import { CoreEvents } from '@singletons/events';
import { CoreRating } from './rating';
import { CoreRatingItemSet, CoreRatingOffline } from './rating-offline';
/**
* Service to sync ratings.
*/
@Injectable( { providedIn: 'root' })
export class CoreRatingSyncProvider extends CoreSyncBaseProvider<CoreRatingSyncItem> {
static readonly SYNCED_EVENT = 'core_rating_synced';
constructor() {
super('CoreRatingSyncProvider');
}
/**
* Try to synchronize all the ratings of a certain component, instance or item set.
*
* This function should be called from the sync provider of activities with ratings.
*
* @param component Component. Example: "mod_forum".
* @param ratingArea Rating Area. Example: "post".
* @param contextLevel Context level: course, module, user, etc.
* @param instanceId Context instance id.
* @param itemSetId Item set id.
* @param force Wether to force sync not depending on last execution.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected if sync fails.
*/
async syncRatings(
component: string,
ratingArea: string,
contextLevel?: ContextLevel,
instanceId?: number,
itemSetId?: number,
force?: boolean,
siteId?: string,
): Promise<CoreRatingSyncItemResult[]> {
siteId = siteId || CoreSites.getCurrentSiteId();
const itemSets = await CoreRatingOffline.getItemSets(component, ratingArea, contextLevel, instanceId, itemSetId, siteId);
const results: CoreRatingSyncItemResult[] = [];
await Promise.all(itemSets.map(async (itemSet) => {
const result = force
? await this.syncItemSet(
component,
ratingArea,
itemSet.contextLevel,
itemSet.instanceId,
itemSet.itemSetId,
siteId,
)
: await this.syncItemSetIfNeeded(
component,
ratingArea,
itemSet.contextLevel,
itemSet.instanceId,
itemSet.itemSetId,
siteId,
);
if (result) {
if (result.updated) {
// Sync successful, send event.
CoreEvents.trigger(CoreRatingSyncProvider.SYNCED_EVENT, {
...itemSet,
warnings: result.warnings,
}, siteId);
}
results.push(
{
itemSet,
...result,
},
);
}
}));
return results;
}
/**
* Sync ratings of an item set only if a certain time has passed since the last time.
*
* @param component Component. Example: "mod_forum".
* @param ratingArea Rating Area. Example: "post".
* @param contextLevel Context level: course, module, user, etc.
* @param instanceId Context instance id.
* @param itemSetId Item set id. Example: forum discussion id.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when ratings are synced or if it doesn't need to be synced.
*/
protected async syncItemSetIfNeeded(
component: string,
ratingArea: string,
contextLevel: ContextLevel,
instanceId: number,
itemSetId: number,
siteId?: string,
): Promise<CoreRatingSyncItem | undefined> {
siteId = siteId || CoreSites.getCurrentSiteId();
const syncId = this.getItemSetSyncId(component, ratingArea, contextLevel, instanceId, itemSetId);
const needed = await this.isSyncNeeded(syncId, siteId);
if (needed) {
return this.syncItemSet(component, ratingArea, contextLevel, instanceId, itemSetId, siteId);
}
}
/**
* Synchronize all offline ratings of an item set.
*
* @param component Component. Example: "mod_forum".
* @param ratingArea Rating Area. Example: "post".
* @param contextLevel Context level: course, module, user, etc.
* @param instanceId Context instance id.
* @param itemSetId Item set id. Example: forum discussion id.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
protected syncItemSet(
component: string,
ratingArea: string,
contextLevel: ContextLevel,
instanceId: number,
itemSetId: number,
siteId?: string,
): Promise<CoreRatingSyncItem> {
siteId = siteId || CoreSites.getCurrentSiteId();
const syncId = this.getItemSetSyncId(component, ratingArea, contextLevel, instanceId, itemSetId);
const currentSyncPromise = this.getOngoingSync(syncId, siteId);
if (currentSyncPromise) {
// There's already a sync ongoing for this item set, return the promise.
return currentSyncPromise;
}
this.logger.debug(`Try to sync ratings of component '${component}' rating area '${ratingArea}'` +
` context level '${contextLevel}' instance ${instanceId} item set ${itemSetId}`);
// Get offline events.
const syncPromise = this.performSyncItemSet(component, ratingArea, contextLevel, instanceId, itemSetId, siteId);
return this.addOngoingSync(syncId, syncPromise, siteId);
}
/**
* Synchronize all offline ratings of an item set.
*
* @param component Component. Example: "mod_forum".
* @param ratingArea Rating Area. Example: "post".
* @param contextLevel Context level: course, module, user, etc.
* @param instanceId Context instance id.
* @param itemSetId Item set id. Example: forum discussion id.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
protected async performSyncItemSet(
component: string,
ratingArea: string,
contextLevel: ContextLevel,
instanceId: number,
itemSetId: number,
siteId: string,
): Promise<CoreRatingSyncItem> {
const result: CoreRatingSyncItem = {
updated: [],
warnings: [],
};
const ratings = await CoreRatingOffline.getRatings(component, ratingArea, contextLevel, instanceId, itemSetId, siteId);
if (!ratings.length) {
// Nothing to sync.
return result;
}
if (!CoreApp.isOnline()) {
// Cannot sync in offline.
throw new CoreNetworkError();
}
const promises = ratings.map(async (rating) => {
try {
await CoreRating.addRatingOnline(
component,
ratingArea,
rating.contextlevel,
rating.instanceid,
rating.itemid,
rating.scaleid,
rating.rating,
rating.rateduserid,
rating.aggregation,
siteId,
);
} catch (error) {
if (!CoreUtils.isWebServiceError(error)) {
// Couldn't connect to server, reject.
throw error;
}
const warning = CoreTextUtils.getErrorMessageFromError(error);
if (warning) {
result.warnings.push(warning);
}
}
result.updated.push(rating.itemid);
try {
return CoreRatingOffline.deleteRating(
component,
ratingArea,
rating.contextlevel,
rating.instanceid,
rating.itemid,
siteId,
);
} finally {
await CoreRating.invalidateRatingItems(
rating.contextlevel,
rating.instanceid,
component,
ratingArea,
rating.itemid,
rating.scaleid,
undefined,
siteId,
);
}
});
await Promise.all(promises);
// All done, return the result.
return result;
}
/**
* Get the sync id of an item set.
*
* @param component Component. Example: "mod_forum".
* @param ratingArea Rating Area. Example: "post".
* @param contextLevel Context level: course, module, user, etc.
* @param instanceId Context instance id.
* @param itemSetId Item set id. Example: forum discussion id.
* @return Sync id.
*/
protected getItemSetSyncId(
component: string,
ratingArea: string,
contextLevel: ContextLevel,
instanceId: number,
itemSetId: number,
): string {
return `itemSet#${component}#${ratingArea}#${contextLevel}#${instanceId}#${itemSetId}`;
}
}
export const CoreRatingSync = makeSingleton(CoreRatingSyncProvider);
declare module '@singletons/events' {
/**
* Augment CoreEventsData interface with events specific to this service.
*
* @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
*/
export interface CoreEventsData {
[CoreRatingSyncProvider.SYNCED_EVENT]: CoreRatingSyncEventData;
}
}
export type CoreRatingSyncItem = {
warnings: string[];
updated: number[];
};
export type CoreRatingSyncItemResult = CoreRatingSyncItem & {
itemSet: CoreRatingItemSet;
};
/**
* Data passed to SYNCED_EVENT event.
*/
export type CoreRatingSyncEventData = CoreRatingItemSet & {
warnings: string[];
}; | the_stack |
import BigNumber from 'bignumber.js'
import { abi as FactoryV2ABI } from '@uniswap/v2-periphery/build/IUniswapV2Factory.json'
import { abi as RouterV2ABI } from '@uniswap/v2-periphery/build/IUniswapV2Router02.json'
import { abi as PairV2ABI } from '@uniswap/v2-periphery/build/IUniswapV2Pair.json'
import ethLikeHelper from 'common/helpers/ethLikeHelper'
import constants from 'common/helpers/constants'
import utils from 'common/utils'
import erc20Like from 'common/erc20Like'
import actions from 'redux/actions'
const ABIS = {
factory: FactoryV2ABI,
router: RouterV2ABI,
pair: PairV2ABI,
}
enum SwapMethods {
swapExactETHForTokens = 'swapExactETHForTokens',
swapExactTokensForETH = 'swapExactTokensForETH',
swapExactTokensForTokens = 'swapExactTokensForTokens',
swapTokensForExactTokens = 'swapTokensForExactTokens',
swapExactETHForTokensSupportingFeeOnTransferTokens = 'swapExactETHForTokensSupportingFeeOnTransferTokens',
swapExactTokensForETHSupportingFeeOnTransferTokens = 'swapExactTokensForETHSupportingFeeOnTransferTokens',
swapExactTokensForTokensSupportingFeeOnTransferTokens = 'swapExactTokensForTokensSupportingFeeOnTransferTokens',
}
enum LiquidityMethods {
addLiquidity = 'addLiquidity',
addLiquidityETH = 'addLiquidityETH',
removeLiquidity = 'removeLiquidity',
removeLiquidityETH = 'removeLiquidityETH',
}
type GetContractParams = {
name: 'factory' | 'router' | 'pair'
address: string
baseCurrency: string
}
const wrapCurrency = (chainId: number, currencyAddress: string) => {
const { WrapperCurrency, EVM_COIN_ADDRESS } = constants.ADDRESSES
return currencyAddress === EVM_COIN_ADDRESS ? WrapperCurrency[chainId] : currencyAddress
}
const getContract = (params: GetContractParams) => {
const { name, address, baseCurrency } = params
return ethLikeHelper[baseCurrency?.toLowerCase()]?.getContract({
abi: ABIS[name],
address,
})
}
const getDeadline = async (provider, deadlinePeriod): Promise<string> => {
const latestBlockNumber = await provider.eth.getBlockNumber()
const latestBlock = await provider.eth.getBlock(latestBlockNumber)
const timestamp = latestBlock.timestamp
return utils.amount.toHexNumber(new BigNumber(timestamp).plus(deadlinePeriod))
}
const getSlippageRange = (slippagePercent, amount) => {
const MAX_PERCENT = 100
return new BigNumber(amount).div(MAX_PERCENT).times(slippagePercent).toNumber()
}
const getMinAmount = (amount, range) => {
return new BigNumber(amount).minus(range).integerValue(BigNumber.ROUND_CEIL)
}
const getPairAddress = async (params) => {
const { factoryAddress, baseCurrency, chainId } = params
let { tokenA, tokenB } = params
const factory = getContract({
name: 'factory',
address: factoryAddress,
baseCurrency,
})
tokenA = wrapCurrency(chainId, tokenA)
tokenB = wrapCurrency(chainId, tokenB)
try {
return await factory?.methods.getPair(tokenA, tokenB).call()
} catch (error) {
return error
}
}
const getAmountOut = async (params) => {
const {
routerAddress,
baseCurrency,
chainId,
tokenA,
tokenADecimals,
tokenB,
tokenBDecimals,
amountIn,
} = params
const router = getContract({ name: 'router', address: routerAddress, baseCurrency })
const unitAmountIn = utils.amount.formatWithDecimals(amountIn, tokenADecimals)
const path = [wrapCurrency(chainId, tokenA), wrapCurrency(chainId, tokenB)]
try {
// use getAmountsOut instead of getAmountOut, because we don't need
// to request pair reserves manually for the second method arguments
const amounts = await router?.methods
.getAmountsOut(utils.amount.toHexNumber(unitAmountIn), path)
.call()
return utils.amount.formatWithoutDecimals(amounts[1], tokenBDecimals)
} catch (error) {
return error
}
}
const getLiquidityAmountForAssetB = async (params) => {
const {
chainId,
pairAddress,
routerAddress,
baseCurrency,
amountADesired,
tokenADecimals,
tokenBDecimals,
} = params
let { tokenA } = params
tokenA = wrapCurrency(chainId, tokenA)
const router = getContract({ name: 'router', address: routerAddress, baseCurrency })
const pair = getContract({ name: 'pair', address: pairAddress, baseCurrency })
try {
const token1 = await pair.methods.token1().call()
const { reserve0, reserve1 } = await pair.methods.getReserves().call()
const unitAmountA = utils.amount.formatWithDecimals(amountADesired, tokenADecimals)
const reservesOrder =
tokenA.toLowerCase() === token1.toLowerCase() ? [reserve1, reserve0] : [reserve0, reserve1]
const tokenBAmount = await router.methods.quote(unitAmountA, ...reservesOrder).call()
return utils.amount.formatWithoutDecimals(tokenBAmount, tokenBDecimals)
} catch (error) {
return error
}
}
const returnSwapDataByMethod = async (
params
): Promise<{
args: any[]
value?: string
}> => {
let {
chainId,
provider,
method,
fromToken,
fromTokenDecimals,
toToken,
toTokenDecimals,
owner,
deadlinePeriod,
slippage,
sellAmount,
buyAmount,
} = params
if (!SwapMethods[method]) throw new Error('Wrong method')
const chainNumber = Number(chainId)
// Swaps available only for tokens. Replace native currency with a wrapped one
fromToken = wrapCurrency(chainNumber, fromToken)
toToken = wrapCurrency(chainNumber, toToken)
const path = [fromToken, toToken]
const deadline = await getDeadline(provider, deadlinePeriod)
const weiSellAmount = utils.amount.formatWithDecimals(sellAmount, fromTokenDecimals)
const weiBuyAmount = utils.amount.formatWithDecimals(buyAmount, toTokenDecimals)
const buySlilppageRange = getSlippageRange(slippage, weiBuyAmount)
// the minimum amount of the purchased asset to be received
const intOutMin = getMinAmount(weiBuyAmount, buySlilppageRange)
const amountOutMin = utils.amount.toHexNumber(intOutMin)
const amountIn = weiSellAmount
switch (method) {
case SwapMethods.swapExactETHForTokensSupportingFeeOnTransferTokens:
case SwapMethods.swapExactETHForTokens:
return {
args: [amountOutMin, path, owner, deadline],
// without decimals and not in hex format, because we do it in the actions
value: sellAmount,
}
case SwapMethods.swapExactTokensForTokensSupportingFeeOnTransferTokens:
case SwapMethods.swapExactTokensForETHSupportingFeeOnTransferTokens:
case SwapMethods.swapExactTokensForETH:
case SwapMethods.swapExactTokensForTokens:
return {
args: [amountIn, amountOutMin, path, owner, deadline],
}
}
return { args: [] }
}
const returnSwapMethod = (params) => {
const { fromToken, toToken, useFeeOnTransfer } = params
if (
fromToken.toLowerCase() === constants.ADDRESSES.EVM_COIN_ADDRESS &&
toToken.toLowerCase() === constants.ADDRESSES.EVM_COIN_ADDRESS
) {
throw new Error('Swap between two native coins')
}
if (fromToken.toLowerCase() === constants.ADDRESSES.EVM_COIN_ADDRESS) {
return useFeeOnTransfer
? SwapMethods.swapExactETHForTokensSupportingFeeOnTransferTokens
: SwapMethods.swapExactETHForTokens
} else if (toToken.toLowerCase() === constants.ADDRESSES.EVM_COIN_ADDRESS) {
return useFeeOnTransfer
? SwapMethods.swapExactTokensForETHSupportingFeeOnTransferTokens
: SwapMethods.swapExactTokensForETH
} else {
return useFeeOnTransfer
? SwapMethods.swapExactTokensForTokensSupportingFeeOnTransferTokens
: SwapMethods.swapExactTokensForTokens
}
}
const checkAndApproveToken = async (params) => {
const { standard, token, owner, decimals, spender, amount, tokenName } = params
const allowance = await erc20Like[standard].checkAllowance({
contract: token,
decimals,
spender,
owner,
})
return new Promise(async (res, rej) => {
if (new BigNumber(amount).isGreaterThan(allowance)) {
const result = await actions[standard].approve({
name: tokenName,
to: spender,
amount,
})
return result instanceof Error ? rej(result) : res(result)
}
res(true)
})
}
const swapCallback = async (params) => {
const {
routerAddress,
baseCurrency,
owner,
fromToken,
fromTokenDecimals,
toToken,
toTokenDecimals,
deadlinePeriod,
slippage,
sellAmount,
buyAmount,
waitReceipt = false,
useFeeOnTransfer,
} = params
try {
const provider = actions[baseCurrency.toLowerCase()].getWeb3()
const router = getContract({ name: 'router', address: routerAddress, baseCurrency })
const method = returnSwapMethod({ fromToken, toToken, useFeeOnTransfer })
const swapData = await returnSwapDataByMethod({
chainId: actions[baseCurrency.toLowerCase()].chainId,
slippage,
provider,
method,
fromToken,
fromTokenDecimals,
toToken,
toTokenDecimals,
owner,
deadlinePeriod,
sellAmount,
buyAmount,
})
const txData = router.methods[method](...swapData.args).encodeABI()
return actions[baseCurrency.toLowerCase()].send({
to: routerAddress,
data: txData,
waitReceipt,
amount: swapData.value ?? 0,
})
} catch (error) {
return error
}
}
const returnAddLiquidityData = async (params) => {
const {
provider,
slippage,
tokenA,
tokenADecimals,
amountADesired,
tokenB,
tokenBDecimals,
amountBDesired,
owner,
deadlinePeriod,
} = params
const lowerTokenA = tokenA.toLowerCase()
const lowerTokenB = tokenB.toLowerCase()
let method: string
let args: (string | number)[]
let value: number | null
if (
lowerTokenA === constants.ADDRESSES.EVM_COIN_ADDRESS &&
lowerTokenB === constants.ADDRESSES.EVM_COIN_ADDRESS
) {
throw new Error('Two native coins')
}
const { formatWithDecimals, toHexNumber } = utils.amount
const deadline = await getDeadline(provider, deadlinePeriod)
const unitAmountADesired = formatWithDecimals(amountADesired, tokenADecimals)
const unitAmountBDesired = formatWithDecimals(amountBDesired, tokenBDecimals)
const amountASlippageRange = getSlippageRange(
slippage,
formatWithDecimals(amountADesired, tokenADecimals)
)
const amountBSlippageRange = getSlippageRange(
slippage,
formatWithDecimals(amountBDesired, tokenBDecimals)
)
const amountAMin = getMinAmount(unitAmountADesired, amountASlippageRange)
const amountBMin = getMinAmount(unitAmountBDesired, amountBSlippageRange)
const hexAmountADesired = toHexNumber(unitAmountADesired)
const hexAmountBDesired = toHexNumber(unitAmountBDesired)
const hexAmountAMin = toHexNumber(amountAMin)
const hexAmountBMin = toHexNumber(amountBMin)
if (
lowerTokenA === constants.ADDRESSES.EVM_COIN_ADDRESS ||
lowerTokenB === constants.ADDRESSES.EVM_COIN_ADDRESS
) {
const tokenAIsNative = lowerTokenA === constants.ADDRESSES.EVM_COIN_ADDRESS
method = LiquidityMethods.addLiquidityETH
value = tokenAIsNative ? amountADesired : amountBDesired
args = [
tokenAIsNative ? tokenB : tokenA,
tokenAIsNative ? hexAmountBDesired : hexAmountADesired,
tokenAIsNative ? hexAmountBMin : hexAmountAMin,
tokenAIsNative ? hexAmountAMin : hexAmountBMin,
owner,
deadline,
]
} else {
method = LiquidityMethods.addLiquidity
value = null
args = [
tokenA,
tokenB,
hexAmountADesired,
hexAmountBDesired,
hexAmountBMin,
hexAmountBMin,
owner,
deadline,
]
}
return {
method,
args,
value,
}
}
const addLiquidityCallback = async (params) => {
const {
routerAddress,
baseCurrency,
waitReceipt = false,
tokenA,
tokenADecimals,
amountADesired,
tokenB,
tokenBDecimals,
amountBDesired,
owner,
deadlinePeriod,
} = params
let { slippage } = params
const provider = actions[baseCurrency.toLowerCase()].getWeb3()
const { method, args, value } = await returnAddLiquidityData({
provider,
tokenA,
tokenADecimals,
amountADesired,
slippage,
tokenB,
tokenBDecimals,
amountBDesired,
owner,
deadlinePeriod,
})
const router = getContract({ name: 'router', address: routerAddress, baseCurrency })
const txData = router.methods[method](...args).encodeABI()
try {
return actions[baseCurrency.toLowerCase()].send({
to: routerAddress,
data: txData,
waitReceipt,
amount: value ?? 0,
})
} catch (error) {
return error
}
}
export default {
getContract,
getPairAddress,
getAmountOut,
getLiquidityAmountForAssetB,
swapCallback,
addLiquidityCallback,
} | the_stack |
import React from 'react'
import HtmlParser from 'react-html-parser'
import { useMutation } from 'react-apollo'
import gql from 'graphql-tag'
import { Formik, Form, Field } from 'formik'
import * as Yup from 'yup'
import {
Box,
Tiles,
Stack,
ButtonDeprecated as Button,
Typography,
} from '@island.is/island-ui/core'
import { useI18n } from '@island.is/gjafakort-web/i18n'
import { Company } from '@island.is/gjafakort-web/graphql/schema'
import {
FieldCheckbox,
FieldInput,
FieldNumberInput,
FieldPolarQuestion,
FieldSelect,
FormLayout,
} from '@island.is/gjafakort-web/components'
interface PropTypes {
company: Company
handleSubmission: (_: boolean) => void
}
const CreateCompanyApplicationMutation = gql`
mutation CreateCompanyApplicationMutation(
$input: CreateCompanyApplicationInput!
) {
createCompanyApplication(input: $input) {
application {
id
state
}
}
}
`
const urlRegex = /[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}/gi
function Signup({ company, handleSubmission }: PropTypes) {
const {
t: {
company: { signup: t },
validation,
},
} = useI18n()
const [createCompanyApplication] = useMutation(
CreateCompanyApplicationMutation,
)
const companyOperations = t.form.operation.options
const onSubmit = async (
{
operations,
serviceCategory,
gotPublicHelpAmount,
gotPublicHelp,
...values
},
{ setSubmitting },
) => {
setSubmitting(true)
if (operations.noneOfTheAbove) {
setSubmitting(false)
return handleSubmission(false)
}
await createCompanyApplication({
variables: {
input: {
...values,
...operations,
serviceCategory: serviceCategory.label,
publicHelpAmount: parseInt(
gotPublicHelp ? gotPublicHelpAmount || 0 : 0,
),
noneOfTheAbove: undefined,
},
},
})
setSubmitting(false)
return handleSubmission(true)
}
return (
<FormLayout>
<Box marginBottom={2}>
<Typography variant="h1" as="h1">
{company.name}
</Typography>
</Box>
<Box marginBottom={6}>
<Typography variant="intro">{t.intro}</Typography>
</Box>
<Formik
initialValues={{
companySSN: company.ssn,
companyName: company.name,
companyDisplayName:
company.application?.companyDisplayName ?? company.name,
serviceCategory: company.application?.serviceCategory,
name: company.application?.name ?? '',
email: company.application?.email ?? '',
generalEmail: company.application?.generalEmail ?? '',
webpage: company.application?.webpage ?? '',
phoneNumber: company.application?.phoneNumber.replace(/-/g, '') ?? '',
operations: companyOperations.reduce((acc, o) => {
acc[o.name] = false
return acc
}, {}),
noneOfTheAbove: false,
operationsTrouble: undefined,
gotPublicHelp: undefined,
gotPublicHelpAmount: '',
}}
validate={(values) => {
const errors = {}
const noOperations = companyOperations.every(
(o) => !values.operations[o.name],
)
if (!values.noneOfTheAbove && noOperations) {
errors['operations'] = {}
companyOperations.forEach((o) => {
errors['operations'][o.name] = t.form.validation.operations
})
}
return errors
}}
validationSchema={Yup.object().shape({
companyDisplayName: Yup.string().required(validation.required),
serviceCategory: Yup.object()
.nullable()
.required(validation.required),
name: Yup.string().required(validation.required),
email: Yup.string()
.email(validation.email)
.required(validation.required),
generalEmail: Yup.string()
.email(validation.email)
.required(validation.required),
phoneNumber: Yup.string()
.length(7, validation.phoneNumber)
.required(validation.required),
operationsTrouble: Yup.bool().required(
t.form.validation.operationsTrouble,
),
gotPublicHelp: Yup.bool().required(
t.form.validation.operationsTrouble,
),
gotPublicHelpAmount: Yup.number().when(
'gotPublicHelp',
(gotPublicHelp, gotPublicHelpAmount) =>
gotPublicHelp
? gotPublicHelpAmount.required(validation.required)
: gotPublicHelpAmount,
),
webpage: Yup.string()
.matches(urlRegex, validation.webpage)
.required(validation.required),
})}
onSubmit={onSubmit}
enableReinitialize
>
{({ values, setFieldValue, isSubmitting }) => (
<Form>
<Box marginBottom={6}>
<Tiles columns={[1, 1, 2]} space={3}>
<Field
component={FieldInput}
label={t.form.companyName.label}
name="companyName"
disabled
/>
<Field
component={FieldNumberInput}
label={t.form.companySSN.label}
disabled
name="companySSN"
format="######-####"
/>
<Field
component={FieldInput}
label={t.form.companyDisplayName.label}
name="companyDisplayName"
tooltip={t.form.companyDisplayName.tooltip}
/>
<Field
component={FieldSelect}
name="serviceCategory"
label={t.form.serviceCategory.label}
placeholder={t.form.serviceCategory.placeholder}
options={t.form.serviceCategory.options}
/>
</Tiles>
</Box>
<Box marginBottom={6}>
<Box marginBottom={1}>
<Typography variant="h4" as="h2">
{t.form.operation.label}
</Typography>
</Box>
<Stack space={5}>
{t.form.operation.instructions.map((instruction, index) => (
<Typography variant="p" key={index}>
{HtmlParser(instruction)}
</Typography>
))}
{companyOperations.map((operation) => (
<Field
key={operation.name}
component={FieldCheckbox}
name={`operations.${operation.name}`}
tooltip={operation.tooltip}
label={operation.label}
disabled={
operation.name !== 'noneOfTheAbove' &&
values.operations.noneOfTheAbove
}
onChange={() => {
if (operation.name === 'noneOfTheAbove') {
// we want this to run in the next render cycle
// so "noneOfTheAbove" is true before we uncheck all operations
setTimeout(() => {
companyOperations.forEach((o) => {
if (values.operations[o.name]) {
setFieldValue(`operations.${o.name}`, false)
}
})
}, 0)
}
}}
/>
))}
</Stack>
</Box>
<Box marginBottom={5}>
<Stack space={5}>
<Field
component={FieldPolarQuestion}
name="operationsTrouble"
positiveLabel={t.form.operationsTrouble.positiveLabel}
negativeLabel={t.form.operationsTrouble.negativeLabel}
label={t.form.operationsTrouble.label}
tooltip={t.form.operationsTrouble.tooltip}
reverse
/>
<Field
component={FieldPolarQuestion}
name="gotPublicHelp"
positiveLabel={t.form.gotPublicHelp.positiveLabel}
negativeLabel={t.form.gotPublicHelp.negativeLabel}
label={t.form.gotPublicHelp.label}
tooltip={t.form.gotPublicHelp.tooltip}
reverse
/>
{values.gotPublicHelp && (
<Field
component={FieldNumberInput}
label={t.form.gotPublicHelpAmount}
decimalSeparator=","
thousandSeparator="."
suffix=" kr."
name="gotPublicHelpAmount"
/>
)}
</Stack>
</Box>
<Box marginBottom={5}>
<Stack space={3}>
<Typography variant="h4" as="h2">
{t.form.contact.label}
</Typography>
<Field
component={FieldInput}
label={t.form.contact.name}
name="name"
/>
<Field
component={FieldInput}
label={t.form.contact.email}
name="email"
/>
<Field
component={FieldInput}
label={t.form.contact.generalEmail}
name="generalEmail"
/>
<Field
component={FieldInput}
label={t.form.contact.webpage}
name="webpage"
/>
<Field
component={FieldNumberInput}
label={t.form.contact.phoneNumber}
name="phoneNumber"
format="### ####"
/>
</Stack>
</Box>
<Button htmlType="submit" disabled={isSubmitting}>
{t.form.submit}
</Button>
</Form>
)}
</Formik>
</FormLayout>
)
}
export default Signup | the_stack |
import { PhysXPhysics } from "./PhysXPhysics";
import { Quaternion, Vector3 } from "oasis-engine";
import { IDynamicCollider } from "@oasis-engine/design";
import { PhysXCollider } from "./PhysXCollider";
/** The collision detection mode constants used for PhysXDynamicCollider.collisionDetectionMode. */
export enum CollisionDetectionMode {
/** Continuous collision detection is off for this dynamic collider. */
Discrete,
/** Continuous collision detection is on for colliding with static mesh geometry. */
Continuous,
/** Continuous collision detection is on for colliding with static and dynamic geometry. */
ContinuousDynamic,
/** Speculative continuous collision detection is on for static and dynamic geometries */
ContinuousSpeculative
}
/** Use these flags to constrain motion of dynamic collider. */
export enum DynamicColliderConstraints {
/** Freeze motion along the X-axis. */
FreezePositionX,
/** Freeze motion along the Y-axis. */
FreezePositionY,
/** Freeze motion along the Z-axis. */
FreezePositionZ,
/** Freeze rotation along the X-axis. */
FreezeRotationX,
/** Freeze rotation along the Y-axis. */
FreezeRotationY,
/** Freeze rotation along the Z-axis. */
FreezeRotationZ,
/** Freeze motion along all axes. */
FreezePosition,
/** Freeze rotation along all axes. */
FreezeRotation,
/** Freeze rotation and motion along all axes. */
FreezeAll
}
/**
* A dynamic collider can act with self-defined movement or physical force
*/
export class PhysXDynamicCollider extends PhysXCollider implements IDynamicCollider {
/** The linear damping of the dynamic collider. */
private _drag: number;
/** The angular damping of the dynamic collider. */
private _angularDrag: number;
/** The linear velocity vector of the dynamic collider measured in world unit per second. */
private _velocity: Vector3;
/** The angular velocity vector of the dynamic collider measured in radians per second. */
private _angularVelocity: Vector3;
/** The mass of the dynamic collider. */
private _mass: number;
private _centerOfMass: Vector3;
private _inertiaTensor: Vector3;
private _maxAngularVelocity: number;
private _maxDepenetrationVelocity: number;
private _sleepThreshold: number;
private _solverIterations: number;
private _collisionDetectionMode: CollisionDetectionMode;
/** Controls whether physics affects the dynamic collider. */
private _isKinematic: boolean;
private _constraints: DynamicColliderConstraints;
private _freezeRotation: boolean;
/**
* The drag of the object.
*/
get linearDamping(): number {
return this._drag;
}
set linearDamping(value: number) {
this._drag = value;
this._pxActor.setLinearDamping(value);
}
/**
* The angular drag of the object.
*/
get angularDamping(): number {
return this._angularDrag;
}
set angularDamping(value: number) {
this._angularDrag = value;
this._pxActor.setAngularDamping(value);
}
/**
* The velocity vector of the collider. It represents the rate of change of collider position.
*/
get linearVelocity(): Vector3 {
return this._velocity;
}
set linearVelocity(value: Vector3) {
this._velocity = value;
const vel = { x: value.x, y: value.y, z: value.z };
this._pxActor.setLinearVelocity(vel, true);
}
/**
* The angular velocity vector of the collider measured in radians per second.
*/
get angularVelocity(): Vector3 {
return this._angularVelocity;
}
set angularVelocity(value: Vector3) {
this._angularVelocity = value;
this._pxActor.setAngularVelocity({ x: value.x, y: value.y, z: value.z }, true);
}
/**
* The mass of the collider.
*/
get mass(): number {
return this._mass;
}
set mass(value: number) {
this._mass = value;
this._pxActor.setMass(value);
}
/**
* The center of mass relative to the transform's origin.
*/
get centerOfMass(): Vector3 {
return this._centerOfMass;
}
set centerOfMass(value: Vector3) {
this._centerOfMass = value;
const transform = {
translation: {
x: value.x,
y: value.y,
z: value.z
},
rotation: {
w: 1,
x: 0,
y: 0,
z: 0
}
};
this._pxActor.setCMassLocalPose(transform);
}
/**
* The diagonal inertia tensor of mass relative to the center of mass.
*/
get inertiaTensor(): Vector3 {
return this._inertiaTensor;
}
set inertiaTensor(value: Vector3) {
this._inertiaTensor = value;
this._pxActor.setMassSpaceInertiaTensor({ x: value.x, y: value.y, z: value.z });
}
/**
* The maximum angular velocity of the collider measured in radians per second. (Default 7) range { 0, infinity }.
*/
get maxAngularVelocity(): number {
return this._maxAngularVelocity;
}
set maxAngularVelocity(value: number) {
this._maxAngularVelocity = value;
this._pxActor.setMaxAngularVelocity(value);
}
/**
* Maximum velocity of a collider when moving out of penetrating state.
*/
get maxDepenetrationVelocity(): number {
return this._maxDepenetrationVelocity;
}
set maxDepenetrationVelocity(value: number) {
this._maxDepenetrationVelocity = value;
this._pxActor.setMaxDepenetrationVelocity(value);
}
/**
* The mass-normalized energy threshold, below which objects start going to sleep.
*/
get sleepThreshold(): number {
return this._sleepThreshold;
}
set sleepThreshold(value: number) {
this._sleepThreshold = value;
this._pxActor.setSleepThreshold(value);
}
/**
* The solverIterations determines how accurately collider joints and collision contacts are resolved.
* Overrides Physics.defaultSolverIterations. Must be positive.
*/
get solverIterations(): number {
return this._solverIterations;
}
set solverIterations(value: number) {
this._solverIterations = value;
this._pxActor.setSolverIterationCounts(value, 1);
}
/**
* The colliders' collision detection mode.
*/
get collisionDetectionMode(): CollisionDetectionMode {
return this._collisionDetectionMode;
}
set collisionDetectionMode(value: CollisionDetectionMode) {
this._collisionDetectionMode = value;
switch (value) {
case CollisionDetectionMode.Continuous:
this._pxActor.setRigidBodyFlag(PhysXPhysics._physX.PxRigidBodyFlag.eENABLE_CCD, true);
break;
case CollisionDetectionMode.ContinuousDynamic:
this._pxActor.setRigidBodyFlag(PhysXPhysics._physX.PxRigidBodyFlag.eENABLE_CCD_FRICTION, true);
break;
case CollisionDetectionMode.ContinuousSpeculative:
this._pxActor.setRigidBodyFlag(PhysXPhysics._physX.PxRigidBodyFlag.eENABLE_SPECULATIVE_CCD, true);
break;
case CollisionDetectionMode.Discrete:
this._pxActor.setRigidBodyFlag(PhysXPhysics._physX.PxRigidBodyFlag.eENABLE_CCD, false);
this._pxActor.setRigidBodyFlag(PhysXPhysics._physX.PxRigidBodyFlag.eENABLE_CCD_FRICTION, false);
this._pxActor.setRigidBodyFlag(PhysXPhysics._physX.PxRigidBodyFlag.eENABLE_SPECULATIVE_CCD, false);
break;
}
}
/**
* Controls whether physics affects the collider.
*/
get isKinematic(): boolean {
return this._isKinematic;
}
set isKinematic(value: boolean) {
this._isKinematic = value;
if (value) {
this._pxActor.setRigidBodyFlag(PhysXPhysics._physX.PxRigidBodyFlag.eKINEMATIC, true);
} else {
this._pxActor.setRigidBodyFlag(PhysXPhysics._physX.PxRigidBodyFlag.eKINEMATIC, false);
}
}
/**
* Controls which degrees of freedom are allowed for the simulation of this collider.
*/
get constraints(): DynamicColliderConstraints {
return this._constraints;
}
/**
* Controls whether physics will change the rotation of the object.
*/
get freezeRotation(): boolean {
return this._freezeRotation;
}
set freezeRotation(value: boolean) {
this._freezeRotation = value;
this.setConstraints(DynamicColliderConstraints.FreezeRotation, value);
}
constructor(position: Vector3, rotation: Quaternion) {
super();
const transform = this._transform(position, rotation);
this._pxActor = PhysXPhysics._pxPhysics.createRigidDynamic(transform);
}
/**
* Set constraint flags
* @param flag Collider Constraint
* @param value true or false
*/
setConstraints(flag: DynamicColliderConstraints, value: boolean) {
if (value) this._constraints = this._constraints | flag;
else this._constraints = this._constraints & ~flag;
switch (flag) {
case DynamicColliderConstraints.FreezePositionX:
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_LINEAR_X, value);
break;
case DynamicColliderConstraints.FreezePositionY:
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_LINEAR_Y, value);
break;
case DynamicColliderConstraints.FreezePositionZ:
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_LINEAR_Y, value);
break;
case DynamicColliderConstraints.FreezeRotationX:
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_ANGULAR_X, value);
break;
case DynamicColliderConstraints.FreezeRotationY:
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_ANGULAR_Y, value);
break;
case DynamicColliderConstraints.FreezeRotationZ:
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_ANGULAR_Z, value);
break;
case DynamicColliderConstraints.FreezeAll:
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_LINEAR_X, value);
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_LINEAR_Y, value);
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_LINEAR_Y, value);
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_ANGULAR_X, value);
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_ANGULAR_Y, value);
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_ANGULAR_Z, value);
break;
case DynamicColliderConstraints.FreezePosition:
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_LINEAR_X, value);
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_LINEAR_Y, value);
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_LINEAR_Y, value);
break;
case DynamicColliderConstraints.FreezeRotation:
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_ANGULAR_X, value);
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_ANGULAR_Y, value);
this._pxActor.setRigidDynamicLockFlag(PhysXPhysics._physX.PxRigidDynamicLockFlag.eLOCK_ANGULAR_Z, value);
break;
}
}
/**
* {@inheritDoc IDynamicCollider.addForce }
*/
addForce(force: Vector3) {
this._pxActor.addForce({ x: force.x, y: force.y, z: force.z });
}
/**
* {@inheritDoc IDynamicCollider.addTorque }
*/
addTorque(torque: Vector3) {
this._pxActor.addTorque({ x: torque.x, y: torque.y, z: torque.z });
}
/**
* Applies force at position. As a result this will apply a torque and force on the object.
* @param force Force vector in world coordinates.
* @param pos Position in world coordinates.
*/
addForceAtPosition(force: Vector3, pos: Vector3) {
this._pxActor.addForceAtPos({ x: force.x, y: force.y, z: force.z }, { x: pos.x, y: pos.y, z: pos.z });
}
/**
* The velocity of the collider at the point worldPoint in global space.
* @param pos The point in global space.
*/
getPointVelocity(pos: Vector3): Vector3 {
const vel = this._pxActor.getVelocityAtPos({ x: pos.x, y: pos.y, z: pos.z });
return new Vector3(vel.x, vel.y, vel.z);
}
/**
* The velocity relative to the collider at the point relativePoint.
* @param pos The relative point
*/
getRelativePointVelocity(pos: Vector3): Vector3 {
const vel = this._pxActor.getLocalVelocityAtLocalPos({ x: pos.x, y: pos.y, z: pos.z });
return new Vector3(vel.x, vel.y, vel.z);
}
/**
* Moves the kinematic collider towards position.
* @param value Provides the new position for the collider object.
*/
MovePosition(value: Vector3) {
const transform = {
translation: {
x: value.x,
y: value.y,
z: value.z
},
rotation: {
w: 1,
x: 0,
y: 0,
z: 0
}
};
this._pxActor.setKinematicTarget(transform);
}
/**
* Rotates the collider to rotation.
* @param value The new rotation for the collider.
*/
MoveRotation(value: Quaternion) {
const transform = {
translation: {
x: 0,
y: 0,
z: 0
},
rotation: {
w: value.w,
x: value.x,
y: value.y,
z: value.z
}
};
this._pxActor.setKinematicTarget(transform);
}
/**
* Is the collider sleeping?
*/
isSleeping(): boolean {
return this._pxActor.isSleeping();
}
/**
* Forces a collider to sleep at least one frame.
*/
sleep() {
return this._pxActor.putToSleep();
}
/**
* Forces a collider to wake up.
*/
wakeUp() {
return this._pxActor.wakeUp();
}
} | the_stack |
import { createEvent, fireEvent, render } from '@testing-library/react'
import React from 'react'
import { DndProvider, useDrop } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import { LocaleContext } from '../../../i18n'
import enUS from '../../../i18n/locales/en-US'
import { KeyMapping } from './types/KeyMapping'
import { FilterDraggable, FilterDraggableProps } from './FilterDraggable'
type Pet = {
name: string
}
const origin = 'keys_avaible'
const petKeyMapping = new Map<keyof Pet, KeyMapping>([['name', { keyName: 'Name' }]])
const keyState: Array<keyof Pet> = ['name']
const key: keyof Pet = keyState[0]
const keys = new Map<keyof Pet, string[]>([['name', ['Bebel', 'Foguete', 'Scooby-Doo']]])
const createFilterComponent = (props: Partial<FilterDraggableProps<Pet>> = {}) => (
<LocaleContext.Provider value={enUS}>
<FilterDraggable<Pet>
key={key}
name={key}
type={'test'}
onDragEnd={() => {}}
onKeyNav={() => {}}
value={petKeyMapping.get(key).keyName}
origin={origin}
selectedItems={new Set<string>()}
filterItems={keys.get(key)}
onFilterUpdate={() => {}}
{...props}
/>
</LocaleContext.Provider>
)
export function DropableDiv(props: any) {
const [, drag] = useDrop({
accept: props.type,
drop() {
return { result: 'drop' }
},
collect: (monitor) => ({
canDrop: !!monitor.canDrop(),
isOver: monitor.isOver(),
}),
})
return (
<div ref={drag} className='dropable'>
{props.children}
</div>
)
}
describe('FilterDraggable', () => {
describe('render', () => {
it('should render correctly with no values of selectedItems', () => {
const { container } = render(createFilterComponent())
expect(container).toMatchSnapshot()
})
it('should render correctly with all values of selectedItems', () => {
const { container } = render(createFilterComponent({ selectedItems: new Set<string>(keys.get(key)) }))
expect(container).toMatchSnapshot()
})
it('should render correctly with some values of selectedItems', () => {
const { container } = render(
createFilterComponent({ selectedItems: new Set<string>(['Bebel']) })
)
expect(container).toMatchSnapshot()
})
})
it('should throw an error when the prop filterItems is empty', () => {
expect(() => {
render(createFilterComponent({ filterItems: [] }))
}).toThrowError()
})
it('should throw an error when the prop selectedItems contains an item that does not belong to the filterItems', () => {
expect(() => {
render(createFilterComponent({ selectedItems: new Set<string>('Mel') }))
}).toThrowError()
})
it('should show the drop down menu when the user clicks on component', () => {
const { getByRole, getAllByRole, getByText } = render(createFilterComponent())
const button = getByRole('button')
fireEvent.click(button)
expect(button.getAttribute('aria-expanded')).toBeTruthy()
expect(getAllByRole('menuitem')).toHaveLength(5) // Search + All items + Bebel + Foguete + Scooby-Doo
expect(getByText('All items')).toBeDefined()
expect(getByText('Bebel')).toBeDefined()
expect(getByText('Foguete')).toBeDefined()
expect(getByText('Scooby-Doo')).toBeDefined()
})
it('should close the dropdown menu when the user clicks on the component when it is open', () => {
const { getByRole, getAllByRole } = render(createFilterComponent())
const button = getByRole('button')
fireEvent.click(button) // open
expect(getAllByRole('checkbox')).toHaveLength(4) // options + all items
fireEvent.click(button) // close
expect(() => {
getAllByRole('checkbox')
}).toThrowError()
})
describe('handleKeyDown', () => {
it('should call the onKeyNav with direction as up when the user press the ArrowUp key', () => {
const keyNav = jest.fn()
const { getByRole } = render(createFilterComponent({ onKeyNav: keyNav }))
fireEvent.keyDown(getByRole('button'), { key: 'ArrowUp', code: 'ArrowUp' })
expect(keyNav).toBeCalledWith('up', origin, 'name')
})
it('should call the onKeyNav with direction as down when the user press the ArrowDown key', () => {
const keyNav = jest.fn()
const { getByRole } = render(createFilterComponent({ onKeyNav: keyNav }))
fireEvent.keyDown(getByRole('button'), { key: 'ArrowDown', code: 'ArrowDown' })
expect(keyNav).toBeCalledWith('down', origin, 'name')
})
it('should call the onKeyNav with direction as left when the user press the ArrowLeft key', () => {
const keyNav = jest.fn()
const { getByRole } = render(createFilterComponent({ onKeyNav: keyNav }))
fireEvent.keyDown(getByRole('button'), { key: 'ArrowLeft', code: 'ArrowLeft' })
expect(keyNav).toBeCalledWith('left', origin, 'name')
})
it('should call the onKeyNav with direction as right when the user press the ArrowRight key', () => {
const keyNav = jest.fn()
const { getByRole } = render(createFilterComponent({ onKeyNav: keyNav }))
fireEvent.keyDown(getByRole('button'), { key: 'ArrowRight', code: 'ArrowRight' })
expect(keyNav).toBeCalledWith('right', origin, 'name')
})
it('should call the onKeyNav with null when the user press a non-arrow key', () => {
const keyNav = jest.fn()
const { getByRole } = render(createFilterComponent({ onKeyNav: keyNav }))
fireEvent.keyDown(getByRole('button'), { key: 'Enter', code: 'Enter' })
expect(keyNav).toBeCalledWith(null, origin, 'name')
})
})
describe('handleFilterUpdate', () => {
describe('handleSelectAll', () => {
it('should pass a empty set when the user uncheck "all items" checkbox', () => {
const onFilterUpdate = jest.fn()
const { getByRole, getAllByRole } = render(
createFilterComponent({ onFilterUpdate: onFilterUpdate, selectedItems: new Set<string>(keys.get(key)) })
)
const button = getByRole('button')
fireEvent.click(button)
const allItemsCheckbox = getAllByRole('checkbox')[0]
fireEvent.click(allItemsCheckbox)
expect(onFilterUpdate).toBeCalledWith('name', new Set<string>(new Set<string>()))
})
it('should pass all values in a set when the user check "all items" checkbox', () => {
const onFilterUpdate = jest.fn()
const { getByRole, getAllByRole } = render(createFilterComponent({ onFilterUpdate: onFilterUpdate }))
const button = getByRole('button')
fireEvent.click(button)
const allItemsCheckbox = getAllByRole('checkbox')[0]
fireEvent.click(allItemsCheckbox)
expect(onFilterUpdate).toBeCalledWith(
'name',
new Set<string>(['Bebel', 'Foguete', 'Scooby-Doo'])
)
})
})
describe('handleSelect', () => {
it('should return a set with "Bebel" when the user check its checkbox', () => {
const onFilterUpdate = jest.fn()
const { getByRole, getAllByRole } = render(createFilterComponent({ onFilterUpdate: onFilterUpdate }))
const button = getByRole('button')
fireEvent.click(button)
const checkbox = getAllByRole('checkbox')[1]
fireEvent.click(checkbox)
expect(onFilterUpdate).toBeCalledWith(
'name',
new Set<string>(['Bebel'])
)
})
it('should return an empty set when the user uncheck "Bebel" checkbox', () => {
const onFilterUpdate = jest.fn()
const { getByRole, getAllByRole } = render(
createFilterComponent({
onFilterUpdate: onFilterUpdate,
selectedItems: new Set<string>(['Bebel']),
})
)
const button = getByRole('button')
fireEvent.click(button)
const checkbox = getAllByRole('checkbox')[1]
fireEvent.click(checkbox)
expect(onFilterUpdate).toBeCalledWith('name', new Set<string>())
})
it('should return all options when the user check the "Foguete" checkbox', () => {
const onFilterUpdate = jest.fn()
const { getByRole, getAllByRole } = render(
createFilterComponent({
onFilterUpdate: onFilterUpdate,
selectedItems: new Set<string>(['Bebel', 'Scooby-Doo']),
})
)
const button = getByRole('button')
fireEvent.click(button)
const checkbox = getAllByRole('checkbox')[2]
fireEvent.click(checkbox)
expect(onFilterUpdate).toBeCalledWith('name', new Set<string>(keys.get(key)))
})
})
})
describe('handleSearch', () => {
it('should show only Scooby-Doo checkbox when the user types "Sco" ', () => {
const { getByRole, getByPlaceholderText, getAllByRole } = render(createFilterComponent())
const button = getByRole('button')
fireEvent.click(button)
const input = getByPlaceholderText('Search')
fireEvent.change(input, { target: { value: 'Sco' } })
expect(getByRole('checkbox').title).toEqual('Scooby-Doo')
expect(getAllByRole('checkbox')).toHaveLength(1)
})
it('should show an empty list when the user types "Mel" ', () => {
const { getByRole, getByPlaceholderText, getAllByRole } = render(createFilterComponent())
const button = getByRole('button')
fireEvent.click(button)
const input = getByPlaceholderText('Search')
fireEvent.change(input, { target: { value: 'Mel' } })
expect(() => {
getAllByRole('checkbox')
}).toThrowError()
})
})
describe('events', () => {
it('should prevent and not propagate the mouse down event when the user make this event on checkbox', () => {
const { getByRole, getAllByRole } = render(createFilterComponent())
const button = getByRole('button')
fireEvent.click(button)
const checkbox = getAllByRole('checkbox')[1]
const mouseDownEvent = createEvent.mouseDown(checkbox)
const spy = spyOn(mouseDownEvent, 'stopPropagation')
fireEvent(checkbox, mouseDownEvent)
expect(mouseDownEvent.defaultPrevented).toBeTruthy()
expect(spy).toBeCalled()
})
it('should not propagate the blur event when the user remove the focus on drop down area', () => {
const { getByRole } = render(createFilterComponent())
const button = getByRole('button')
fireEvent.click(button)
const dropDownArea = getByRole('menu').firstChild
fireEvent.focus(dropDownArea)
const blurEvent = createEvent.blur(dropDownArea)
const spy = spyOn(blurEvent, 'stopPropagation')
fireEvent(dropDownArea, blurEvent)
expect(spy).toBeCalled()
})
})
it('should not show invalid values on drop down menu', () => {
const { getByRole, getAllByRole } = render(
createFilterComponent({ filterItems: new Array<string>(undefined, '', null) })
)
const button = getByRole('button')
fireEvent.click(button)
expect(getAllByRole('checkbox')).toHaveLength(1) // only the 'All items' checkbox
})
describe('Drag and drop', () => {
it('should call onDragEnd when the drag event ends', () => {
const onDragEnd = jest.fn()
const { container } = render(
<DndProvider backend={HTML5Backend}>
<DropableDiv type={'test'}>{createFilterComponent({ onDragEnd: onDragEnd })}</DropableDiv>
<DropableDiv type={'test'} />
</DndProvider>
)
const dragabble = container.querySelectorAll('div[class*=dropable]')[0].firstChild
const secondDiv = container.querySelectorAll('div[class*=dropable]')[1]
fireEvent.dragStart(dragabble)
fireEvent.dragEnter(secondDiv)
fireEvent.dragOver(secondDiv)
fireEvent.drop(secondDiv)
fireEvent.dragEnd(dragabble)
expect(onDragEnd).toHaveBeenCalled()
})
})
}) | the_stack |
namespace ts {
export type TscCompileSystem = fakes.System & {
writtenFiles: Set<Path>;
baseLine(): { file: string; text: string; };
disableUseFileVersionAsSignature?: boolean;
storeFilesChangingSignatureDuringEmit?: boolean;
};
export const noChangeRun: TestTscEdit = {
subScenario: "no-change-run",
modifyFs: noop
};
export const noChangeWithExportsDiscrepancyRun: TestTscEdit = {
...noChangeRun,
discrepancyExplanation: () => [
"Incremental build did not emit and has .ts as signature so exports has all imported modules/referenced files",
"Clean build always uses d.ts for signature for testing thus does not contain non exported modules/referenced files that arent needed"
]
};
export const noChangeOnlyRuns = [noChangeRun];
export const noChangeWithExportsDiscrepancyOnlyRuns = [noChangeWithExportsDiscrepancyRun];
export interface TestTscCompile extends TestTscCompileLikeBase {
baselineSourceMap?: boolean;
baselineReadFileCalls?: boolean;
baselinePrograms?: boolean;
baselineDependencies?: boolean;
}
export type CommandLineProgram = [Program, BuilderProgram?];
export interface CommandLineCallbacks {
cb: ExecuteCommandLineCallbacks;
getPrograms: () => readonly CommandLineProgram[];
}
function isAnyProgram(program: Program | BuilderProgram | ParsedCommandLine): program is Program | BuilderProgram {
return !!(program as Program | BuilderProgram).getCompilerOptions;
}
export function commandLineCallbacks(
sys: TscCompileSystem | tscWatch.WatchedSystem,
originalReadCall?: System["readFile"],
): CommandLineCallbacks {
let programs: CommandLineProgram[] | undefined;
return {
cb: program => {
if (isAnyProgram(program)) {
baselineBuildInfo(program.getCompilerOptions(), sys, originalReadCall);
(programs || (programs = [])).push(isBuilderProgram(program) ?
[program.getProgram(), program] :
[program]
);
}
else {
baselineBuildInfo(program.options, sys, originalReadCall);
}
},
getPrograms: () => {
const result = programs || emptyArray;
programs = undefined;
return result;
}
};
}
export interface TestTscCompileLikeBase extends VerifyTscCompileLike {
diffWithInitial?: boolean;
modifyFs?: (fs: vfs.FileSystem) => void;
disableUseFileVersionAsSignature?: boolean;
environmentVariables?: Record<string, string>;
}
export interface TestTscCompileLike extends TestTscCompileLikeBase {
compile: (sys: TscCompileSystem) => void;
additionalBaseline?: (sys: TscCompileSystem) => void;
}
/**
* Initialize FS, run compile function and save baseline
*/
export function testTscCompileLike(input: TestTscCompileLike) {
const initialFs = input.fs();
const inputFs = initialFs.shadow();
const {
scenario, subScenario, diffWithInitial,
commandLineArgs, modifyFs,
environmentVariables,
compile: worker, additionalBaseline,
} = input;
if (modifyFs) modifyFs(inputFs);
inputFs.makeReadonly();
const fs = inputFs.shadow();
// Create system
const sys = new fakes.System(fs, { executingFilePath: "/lib/tsc", env: environmentVariables }) as TscCompileSystem;
if (input.disableUseFileVersionAsSignature) sys.disableUseFileVersionAsSignature = true;
sys.storeFilesChangingSignatureDuringEmit = true;
sys.write(`${sys.getExecutingFilePath()} ${commandLineArgs.join(" ")}\n`);
sys.exit = exitCode => sys.exitCode = exitCode;
worker(sys);
sys.write(`exitCode:: ExitStatus.${ExitStatus[sys.exitCode as ExitStatus]}\n`);
additionalBaseline?.(sys);
fs.makeReadonly();
sys.baseLine = () => {
const baseFsPatch = diffWithInitial ?
inputFs.diff(initialFs, { includeChangedFileWithSameContent: true }) :
inputFs.diff(/*base*/ undefined, { baseIsNotShadowRoot: true });
const patch = fs.diff(inputFs, { includeChangedFileWithSameContent: true });
return {
file: `${isBuild(commandLineArgs) ? "tsbuild" : "tsc"}/${scenario}/${subScenario.split(" ").join("-")}.js`,
text: `Input::
${baseFsPatch ? vfs.formatPatch(baseFsPatch) : ""}
Output::
${sys.output.join("")}
${patch ? vfs.formatPatch(patch) : ""}`
};
};
return sys;
}
function makeSystemReadyForBaseline(sys: TscCompileSystem, versionToWrite?: string) {
if (versionToWrite) {
fakes.patchHostForBuildInfoWrite(sys, versionToWrite);
}
else {
fakes.patchHostForBuildInfoReadWrite(sys);
}
const writtenFiles = sys.writtenFiles = new Set();
const originalWriteFile = sys.writeFile;
sys.writeFile = (fileName, content, writeByteOrderMark) => {
const path = toPathWithSystem(sys, fileName);
// When buildinfo is same for two projects,
// it gives error and doesnt write buildinfo but because buildInfo is written for one project,
// readable baseline will be written two times for those two projects with same contents and is ok
Debug.assert(!writtenFiles.has(path) || endsWith(path, "baseline.txt"));
writtenFiles.add(path);
return originalWriteFile.call(sys, fileName, content, writeByteOrderMark);
};
}
export function createSolutionBuilderHostForBaseline(
sys: TscCompileSystem | tscWatch.WatchedSystem,
versionToWrite?: string,
originalRead?: (TscCompileSystem | tscWatch.WatchedSystem)["readFile"]
) {
if (sys instanceof fakes.System) makeSystemReadyForBaseline(sys, versionToWrite);
const { cb } = commandLineCallbacks(sys, originalRead);
const host = createSolutionBuilderHost(sys,
/*createProgram*/ undefined,
createDiagnosticReporter(sys, /*pretty*/ true),
createBuilderStatusReporter(sys, /*pretty*/ true),
);
host.afterProgramEmitAndDiagnostics = cb;
host.afterEmitBundle = cb;
return host;
}
/**
* Initialize Fs, execute command line and save baseline
*/
export function testTscCompile(input: TestTscCompile) {
let actualReadFileMap: MapLike<number> | undefined;
let getPrograms: CommandLineCallbacks["getPrograms"] | undefined;
return testTscCompileLike({
...input,
compile: commandLineCompile,
additionalBaseline
});
function commandLineCompile(sys: TscCompileSystem) {
makeSystemReadyForBaseline(sys);
actualReadFileMap = {};
const originalReadFile = sys.readFile;
sys.readFile = path => {
// Dont record libs
if (path.startsWith("/src/")) {
actualReadFileMap![path] = (getProperty(actualReadFileMap!, path) || 0) + 1;
}
return originalReadFile.call(sys, path);
};
const result = commandLineCallbacks(sys, originalReadFile);
executeCommandLine(
sys,
result.cb,
input.commandLineArgs,
);
sys.readFile = originalReadFile;
getPrograms = result.getPrograms;
}
function additionalBaseline(sys: TscCompileSystem) {
const { baselineSourceMap, baselineReadFileCalls, baselinePrograms, baselineDependencies } = input;
if (baselinePrograms) {
const baseline: string[] = [];
tscWatch.baselinePrograms(baseline, getPrograms!, emptyArray, baselineDependencies);
sys.write(baseline.join("\n"));
}
if (baselineReadFileCalls) {
sys.write(`readFiles:: ${JSON.stringify(actualReadFileMap, /*replacer*/ undefined, " ")} `);
}
if (baselineSourceMap) generateSourceMapBaselineFiles(sys);
actualReadFileMap = undefined;
getPrograms = undefined;
}
}
export function verifyTscBaseline(sys: () => { baseLine: TscCompileSystem["baseLine"]; }) {
it(`Generates files matching the baseline`, () => {
const { file, text } = sys().baseLine();
Harness.Baseline.runBaseline(file, text);
});
}
export interface VerifyTscCompileLike {
scenario: string;
subScenario: string;
commandLineArgs: readonly string[];
fs: () => vfs.FileSystem;
}
/**
* Verify by baselining after initializing FS and custom compile
*/
export function verifyTscCompileLike<T extends VerifyTscCompileLike>(verifier: (input: T) => { baseLine: TscCompileSystem["baseLine"]; }, input: T) {
describe(`tsc ${input.commandLineArgs.join(" ")} ${input.scenario}:: ${input.subScenario}`, () => {
describe(input.scenario, () => {
describe(input.subScenario, () => {
verifyTscBaseline(() => verifier({
...input,
fs: () => input.fs().makeReadonly()
}));
});
});
});
}
/**
* Verify by baselining after initializing FS and command line compile
*/
export function verifyTsc(input: TestTscCompile) {
verifyTscCompileLike(testTscCompile, input);
}
} | the_stack |
import type * as Common from '../../core/common/common.js';
import * as Platform from '../../core/platform/platform.js';
import * as ARIAUtils from './ARIAUtils.js';
import type {ItemsReplacedEvent, ListModel} from './ListModel.js';
import {Events as ListModelEvents} from './ListModel.js';
import {measurePreferredSize} from './UIUtils.js';
export interface ListDelegate<T> {
createElementForItem(item: T): Element;
/**
* This method is not called in NonViewport mode.
* Return zero to make list measure the item (only works in SameHeight mode).
*/
heightForItem(item: T): number;
isItemSelectable(item: T): boolean;
selectedItemChanged(from: T|null, to: T|null, fromElement: HTMLElement|null, toElement: HTMLElement|null): void;
updateSelectedItemARIA(fromElement: Element|null, toElement: Element|null): boolean;
}
// TODO(crbug.com/1167717): Make this a const enum again
// eslint-disable-next-line rulesdir/const_enum
export enum ListMode {
NonViewport = 'UI.ListMode.NonViewport',
EqualHeightItems = 'UI.ListMode.EqualHeightItems',
VariousHeightItems = 'UI.ListMode.VariousHeightItems',
}
export class ListControl<T> {
element: HTMLDivElement;
private topElement: HTMLElement;
private bottomElement: HTMLElement;
private firstIndex: number;
private lastIndex: number;
private renderedHeight: number;
private topHeight: number;
private bottomHeight: number;
private model: ListModel<T>;
private itemToElement: Map<T, Element>;
private selectedIndexInternal: number;
private selectedItemInternal: T|null;
private delegate: ListDelegate<T>;
private readonly mode: ListMode;
private fixedHeight: number;
private variableOffsets: Int32Array;
constructor(model: ListModel<T>, delegate: ListDelegate<T>, mode?: ListMode) {
this.element = document.createElement('div');
this.element.style.overflowY = 'auto';
this.topElement = this.element.createChild('div');
this.bottomElement = this.element.createChild('div');
this.firstIndex = 0;
this.lastIndex = 0;
this.renderedHeight = 0;
this.topHeight = 0;
this.bottomHeight = 0;
this.model = model;
this.model.addEventListener(ListModelEvents.ItemsReplaced, this.replacedItemsInRange, this);
this.itemToElement = new Map();
this.selectedIndexInternal = -1;
this.selectedItemInternal = null;
this.element.tabIndex = -1;
this.element.addEventListener('click', this.onClick.bind(this), false);
this.element.addEventListener('keydown', this.onKeyDown.bind(this), false);
ARIAUtils.markAsListBox(this.element);
this.delegate = delegate;
this.mode = mode || ListMode.EqualHeightItems;
this.fixedHeight = 0;
this.variableOffsets = new Int32Array(0);
this.clearContents();
if (this.mode !== ListMode.NonViewport) {
this.element.addEventListener('scroll', () => {
this.updateViewport(this.element.scrollTop, this.element.offsetHeight);
}, false);
}
}
setModel(model: ListModel<T>): void {
this.itemToElement.clear();
const length = this.model.length;
this.model.removeEventListener(ListModelEvents.ItemsReplaced, this.replacedItemsInRange, this);
this.model = model;
this.model.addEventListener(ListModelEvents.ItemsReplaced, this.replacedItemsInRange, this);
this.invalidateRange(0, length);
}
private replacedItemsInRange(event: Common.EventTarget.EventTargetEvent<ItemsReplacedEvent<T>>): void {
const data = event.data;
const from = data.index;
const to = from + data.removed.length;
const keepSelectedIndex = data.keepSelectedIndex;
const oldSelectedItem = this.selectedItemInternal;
const oldSelectedElement = oldSelectedItem ? (this.itemToElement.get(oldSelectedItem) || null) : null;
for (let i = 0; i < data.removed.length; i++) {
this.itemToElement.delete(data.removed[i]);
}
this.invalidate(from, to, data.inserted);
if (this.selectedIndexInternal >= to) {
this.selectedIndexInternal += data.inserted - (to - from);
this.selectedItemInternal = this.model.at(this.selectedIndexInternal);
} else if (this.selectedIndexInternal >= from) {
const selectableIndex = keepSelectedIndex ? from : from + data.inserted;
let index = this.findFirstSelectable(selectableIndex, +1, false);
if (index === -1) {
const alternativeSelectableIndex = keepSelectedIndex ? from : from - 1;
index = this.findFirstSelectable(alternativeSelectableIndex, -1, false);
}
this.select(index, oldSelectedItem, oldSelectedElement);
}
}
refreshItem(item: T): void {
const index = this.model.indexOf(item);
if (index === -1) {
console.error('Item to refresh is not present');
return;
}
this.refreshItemByIndex(index);
}
refreshItemByIndex(index: number): void {
const item = this.model.at(index);
this.itemToElement.delete(item);
this.invalidateRange(index, index + 1);
if (this.selectedIndexInternal !== -1) {
this.select(this.selectedIndexInternal, null, null);
}
}
refreshAllItems(): void {
this.itemToElement.clear();
this.invalidateRange(0, this.model.length);
if (this.selectedIndexInternal !== -1) {
this.select(this.selectedIndexInternal, null, null);
}
}
invalidateRange(from: number, to: number): void {
this.invalidate(from, to, to - from);
}
viewportResized(): void {
if (this.mode === ListMode.NonViewport) {
return;
}
// TODO(dgozman): try to keep visible scrollTop the same.
const scrollTop = this.element.scrollTop;
const viewportHeight = this.element.offsetHeight;
this.clearViewport();
this.updateViewport(
Platform.NumberUtilities.clamp(scrollTop, 0, this.totalHeight() - viewportHeight), viewportHeight);
}
invalidateItemHeight(): void {
if (this.mode !== ListMode.EqualHeightItems) {
console.error('Only supported in equal height items mode');
return;
}
this.fixedHeight = 0;
if (this.model.length) {
this.itemToElement.clear();
this.invalidate(0, this.model.length, this.model.length);
}
}
itemForNode(node: Node|null): T|null {
while (node && node.parentNodeOrShadowHost() !== this.element) {
node = node.parentNodeOrShadowHost();
}
if (!node) {
return null;
}
const element = (node as Element);
const index = this.model.findIndex(item => this.itemToElement.get(item) === element);
return index !== -1 ? this.model.at(index) : null;
}
scrollItemIntoView(item: T, center?: boolean): void {
const index = this.model.indexOf(item);
if (index === -1) {
console.error('Attempt to scroll onto missing item');
return;
}
this.scrollIntoView(index, center);
}
selectedItem(): T|null {
return this.selectedItemInternal;
}
selectedIndex(): number {
return this.selectedIndexInternal;
}
selectItem(item: T|null, center?: boolean, dontScroll?: boolean): void {
let index = -1;
if (item !== null) {
index = this.model.indexOf(item);
if (index === -1) {
console.error('Attempt to select missing item');
return;
}
if (!this.delegate.isItemSelectable(item)) {
console.error('Attempt to select non-selectable item');
return;
}
}
// Scrolling the item before selection ensures it is in the DOM.
if (index !== -1 && !dontScroll) {
this.scrollIntoView(index, center);
}
if (this.selectedIndexInternal !== index) {
this.select(index);
}
}
selectPreviousItem(canWrap?: boolean, center?: boolean): boolean {
if (this.selectedIndexInternal === -1 && !canWrap) {
return false;
}
let index: number = this.selectedIndexInternal === -1 ? this.model.length - 1 : this.selectedIndexInternal - 1;
index = this.findFirstSelectable(index, -1, Boolean(canWrap));
if (index !== -1) {
this.scrollIntoView(index, center);
this.select(index);
return true;
}
return false;
}
selectNextItem(canWrap?: boolean, center?: boolean): boolean {
if (this.selectedIndexInternal === -1 && !canWrap) {
return false;
}
let index: number = this.selectedIndexInternal === -1 ? 0 : this.selectedIndexInternal + 1;
index = this.findFirstSelectable(index, +1, Boolean(canWrap));
if (index !== -1) {
this.scrollIntoView(index, center);
this.select(index);
return true;
}
return false;
}
selectItemPreviousPage(center?: boolean): boolean {
if (this.mode === ListMode.NonViewport) {
return false;
}
let index: number = this.selectedIndexInternal === -1 ? this.model.length - 1 : this.selectedIndexInternal;
index = this.findPageSelectable(index, -1);
if (index !== -1) {
this.scrollIntoView(index, center);
this.select(index);
return true;
}
return false;
}
selectItemNextPage(center?: boolean): boolean {
if (this.mode === ListMode.NonViewport) {
return false;
}
let index: number = this.selectedIndexInternal === -1 ? 0 : this.selectedIndexInternal;
index = this.findPageSelectable(index, +1);
if (index !== -1) {
this.scrollIntoView(index, center);
this.select(index);
return true;
}
return false;
}
private scrollIntoView(index: number, center?: boolean): void {
if (this.mode === ListMode.NonViewport) {
this.elementAtIndex(index).scrollIntoViewIfNeeded(Boolean(center));
return;
}
const top = this.offsetAtIndex(index);
const bottom = this.offsetAtIndex(index + 1);
const viewportHeight = this.element.offsetHeight;
if (center) {
const scrollTo = (top + bottom) / 2 - viewportHeight / 2;
this.updateViewport(
Platform.NumberUtilities.clamp(scrollTo, 0, this.totalHeight() - viewportHeight), viewportHeight);
return;
}
const scrollTop = this.element.scrollTop;
if (top < scrollTop) {
this.updateViewport(top, viewportHeight);
} else if (bottom > scrollTop + viewportHeight) {
this.updateViewport(bottom - viewportHeight, viewportHeight);
}
}
private onClick(event: Event): void {
const item = this.itemForNode((event.target as Node | null));
if (item && this.delegate.isItemSelectable(item)) {
this.selectItem(item);
}
}
private onKeyDown(ev: Event): void {
const event = (ev as KeyboardEvent);
let selected = false;
switch (event.key) {
case 'ArrowUp':
selected = this.selectPreviousItem(true, false);
break;
case 'ArrowDown':
selected = this.selectNextItem(true, false);
break;
case 'PageUp':
selected = this.selectItemPreviousPage(false);
break;
case 'PageDown':
selected = this.selectItemNextPage(false);
break;
}
if (selected) {
event.consume(true);
}
}
private totalHeight(): number {
return this.offsetAtIndex(this.model.length);
}
private indexAtOffset(offset: number): number {
if (this.mode === ListMode.NonViewport) {
throw 'There should be no offset conversions in non-viewport mode';
}
if (!this.model.length || offset < 0) {
return 0;
}
if (this.mode === ListMode.VariousHeightItems) {
return Math.min(
this.model.length - 1,
Platform.ArrayUtilities.lowerBound(
this.variableOffsets, offset, Platform.ArrayUtilities.DEFAULT_COMPARATOR, 0, this.model.length));
}
if (!this.fixedHeight) {
this.measureHeight();
}
return Math.min(this.model.length - 1, Math.floor(offset / this.fixedHeight));
}
private elementAtIndex(index: number): Element {
const item = this.model.at(index);
let element = this.itemToElement.get(item);
if (!element) {
element = this.delegate.createElementForItem(item);
this.itemToElement.set(item, element);
this.updateElementARIA(element, index);
}
return element;
}
private refreshARIA(): void {
for (let index = this.firstIndex; index <= this.lastIndex; index++) {
const item = this.model.at(index);
const element = this.itemToElement.get(item);
if (element) {
this.updateElementARIA(element, index);
}
}
}
private updateElementARIA(element: Element, index: number): void {
if (!ARIAUtils.hasRole(element)) {
ARIAUtils.markAsOption(element);
}
ARIAUtils.setSetSize(element, this.model.length);
ARIAUtils.setPositionInSet(element, index + 1);
}
private offsetAtIndex(index: number): number {
if (this.mode === ListMode.NonViewport) {
throw new Error('There should be no offset conversions in non-viewport mode');
}
if (!this.model.length) {
return 0;
}
if (this.mode === ListMode.VariousHeightItems) {
return this.variableOffsets[index];
}
if (!this.fixedHeight) {
this.measureHeight();
}
return index * this.fixedHeight;
}
private measureHeight(): void {
this.fixedHeight = this.delegate.heightForItem(this.model.at(0));
if (!this.fixedHeight) {
this.fixedHeight = measurePreferredSize(this.elementAtIndex(0), this.element).height;
}
}
private select(index: number, oldItem?: T|null, oldElement?: Element|null): void {
if (oldItem === undefined) {
oldItem = this.selectedItemInternal;
}
if (oldElement === undefined) {
oldElement = this.itemToElement.get((oldItem as T)) || null;
}
this.selectedIndexInternal = index;
this.selectedItemInternal = index === -1 ? null : this.model.at(index);
const newItem = this.selectedItemInternal;
const newElement = this.selectedIndexInternal !== -1 ? this.elementAtIndex(index) : null;
this.delegate.selectedItemChanged(
oldItem, newItem, (oldElement as HTMLElement | null), (newElement as HTMLElement | null));
if (!this.delegate.updateSelectedItemARIA((oldElement as Element | null), newElement)) {
if (oldElement) {
ARIAUtils.setSelected(oldElement, false);
}
if (newElement) {
ARIAUtils.setSelected(newElement, true);
}
ARIAUtils.setActiveDescendant(this.element, newElement);
}
}
private findFirstSelectable(index: number, direction: number, canWrap: boolean): number {
const length = this.model.length;
if (!length) {
return -1;
}
for (let step = 0; step <= length; step++) {
if (index < 0 || index >= length) {
if (!canWrap) {
return -1;
}
index = (index + length) % length;
}
if (this.delegate.isItemSelectable(this.model.at(index))) {
return index;
}
index += direction;
}
return -1;
}
private findPageSelectable(index: number, direction: number): number {
let lastSelectable = -1;
const startOffset = this.offsetAtIndex(index);
// Compensate for zoom rounding errors with -1.
const viewportHeight = this.element.offsetHeight - 1;
while (index >= 0 && index < this.model.length) {
if (this.delegate.isItemSelectable(this.model.at(index))) {
if (Math.abs(this.offsetAtIndex(index) - startOffset) >= viewportHeight) {
return index;
}
lastSelectable = index;
}
index += direction;
}
return lastSelectable;
}
private reallocateVariableOffsets(length: number, copyTo: number): void {
if (this.variableOffsets.length < length) {
const variableOffsets = new Int32Array(Math.max(length, this.variableOffsets.length * 2));
variableOffsets.set(this.variableOffsets.slice(0, copyTo), 0);
this.variableOffsets = variableOffsets;
} else if (this.variableOffsets.length >= 2 * length) {
const variableOffsets = new Int32Array(length);
variableOffsets.set(this.variableOffsets.slice(0, copyTo), 0);
this.variableOffsets = variableOffsets;
}
}
private invalidate(from: number, to: number, inserted: number): void {
if (this.mode === ListMode.NonViewport) {
this.invalidateNonViewportMode(from, to - from, inserted);
return;
}
if (this.mode === ListMode.VariousHeightItems) {
this.reallocateVariableOffsets(this.model.length + 1, from + 1);
for (let i = from + 1; i <= this.model.length; i++) {
this.variableOffsets[i] = this.variableOffsets[i - 1] + this.delegate.heightForItem(this.model.at(i - 1));
}
}
const viewportHeight = this.element.offsetHeight;
const totalHeight = this.totalHeight();
const scrollTop = this.element.scrollTop;
if (this.renderedHeight < viewportHeight || totalHeight < viewportHeight) {
this.clearViewport();
this.updateViewport(Platform.NumberUtilities.clamp(scrollTop, 0, totalHeight - viewportHeight), viewportHeight);
return;
}
const heightDelta = totalHeight - this.renderedHeight;
if (to <= this.firstIndex) {
const topHeight = this.topHeight + heightDelta;
this.topElement.style.height = topHeight + 'px';
this.element.scrollTop = scrollTop + heightDelta;
this.topHeight = topHeight;
this.renderedHeight = totalHeight;
const indexDelta = inserted - (to - from);
this.firstIndex += indexDelta;
this.lastIndex += indexDelta;
return;
}
if (from >= this.lastIndex) {
const bottomHeight = this.bottomHeight + heightDelta;
this.bottomElement.style.height = bottomHeight + 'px';
this.bottomHeight = bottomHeight;
this.renderedHeight = totalHeight;
return;
}
// TODO(dgozman): try to keep visible scrollTop the same
// when invalidating after firstIndex but before first visible element.
this.clearViewport();
this.updateViewport(Platform.NumberUtilities.clamp(scrollTop, 0, totalHeight - viewportHeight), viewportHeight);
this.refreshARIA();
}
private invalidateNonViewportMode(start: number, remove: number, add: number): void {
let startElement: HTMLElement = this.topElement;
for (let index = 0; index < start; index++) {
startElement = (startElement.nextElementSibling as HTMLElement);
}
while (remove--) {
(startElement.nextElementSibling as HTMLElement).remove();
}
while (add--) {
this.element.insertBefore(this.elementAtIndex(start + add), startElement.nextElementSibling);
}
}
private clearViewport(): void {
if (this.mode === ListMode.NonViewport) {
console.error('There should be no viewport updates in non-viewport mode');
return;
}
this.firstIndex = 0;
this.lastIndex = 0;
this.renderedHeight = 0;
this.topHeight = 0;
this.bottomHeight = 0;
this.clearContents();
}
private clearContents(): void {
// Note: this method should not force layout. Be careful.
this.topElement.style.height = '0';
this.bottomElement.style.height = '0';
this.element.removeChildren();
this.element.appendChild(this.topElement);
this.element.appendChild(this.bottomElement);
}
private updateViewport(scrollTop: number, viewportHeight: number): void {
// Note: this method should not force layout. Be careful.
if (this.mode === ListMode.NonViewport) {
console.error('There should be no viewport updates in non-viewport mode');
return;
}
const totalHeight = this.totalHeight();
if (!totalHeight) {
this.firstIndex = 0;
this.lastIndex = 0;
this.topHeight = 0;
this.bottomHeight = 0;
this.renderedHeight = 0;
this.topElement.style.height = '0';
this.bottomElement.style.height = '0';
return;
}
const firstIndex = this.indexAtOffset(scrollTop - viewportHeight);
const lastIndex = this.indexAtOffset(scrollTop + 2 * viewportHeight) + 1;
while (this.firstIndex < Math.min(firstIndex, this.lastIndex)) {
this.elementAtIndex(this.firstIndex).remove();
this.firstIndex++;
}
while (this.lastIndex > Math.max(lastIndex, this.firstIndex)) {
this.elementAtIndex(this.lastIndex - 1).remove();
this.lastIndex--;
}
this.firstIndex = Math.min(this.firstIndex, lastIndex);
this.lastIndex = Math.max(this.lastIndex, firstIndex);
for (let index = this.firstIndex - 1; index >= firstIndex; index--) {
const element = this.elementAtIndex(index);
this.element.insertBefore(element, this.topElement.nextSibling);
}
for (let index = this.lastIndex; index < lastIndex; index++) {
const element = this.elementAtIndex(index);
this.element.insertBefore(element, this.bottomElement);
}
this.firstIndex = firstIndex;
this.lastIndex = lastIndex;
this.topHeight = this.offsetAtIndex(firstIndex);
this.topElement.style.height = this.topHeight + 'px';
this.bottomHeight = totalHeight - this.offsetAtIndex(lastIndex);
this.bottomElement.style.height = this.bottomHeight + 'px';
this.renderedHeight = totalHeight;
this.element.scrollTop = scrollTop;
}
} | the_stack |
/// <reference types="jquery" />
declare interface Ui5Logger {
//Allows to add a new LogListener that will be notified for new log entries.
addLogListener(oListener: any): void;
//Creates a new debug-level entry in the log with the given message, details and calling component.
debug(sMessage: string, sDetails?: string, sComponent?: string): void;
//Creates a new error-level entry in the log with the given message, details and calling component.
error(sMessage: string, sDetails?: string, sComponent?: string): void;
//Creates a new fatal-level entry in the log with the given message, details and calling component.
fatal(sMessage: string, sDetails?: string, sComponent?: string): void;
//Returns the log level currently effective for the given component.
getLevel(sComponent?: string): void;
//Returns the logged entries recorded so far as an array.
getLogEntries(): void;
//Returns a jQuery.sap.log.Logger for the given component.
getLogger(sComponent: string, iDefaultLogLevel?: any): void;
//Creates a new info-level entry in the log with the given message, details and calling component.
info(sMessage: string, sDetails?: string, sComponent?: string): void;
//Checks whether logging is enabled for the given log level, depending on the currently effective log level for the given component.
isLoggable(iLevel?: any, sComponent?: string): void;
//Allows to remove a registered LogListener.
removeLogListener(oListener: any): void;
//Defines the maximum jQuery.sap.log.Level of log entries that will be recorded.
setLevel(iLogLevel: any, sComponent?: string): void;
//Creates a new trace-level entry in the log with the given message, details and calling component.
trace(sMessage: string, sDetails?: string, sComponent?: string): void;
//Creates a new warning-level entry in the log with the given message, details and calling component.
warning(sMessage: string, sDetails?: string, sComponent?: string): void;
}
declare interface JquerySap {
log: Ui5Logger
// Adds a whitelist entry for URL valiadtion
addUrlWhitelist(protocol: any, host: any, port: any, path: any): void;
// Calculate delta of old list and new list This implements the algorithm described in "A Technique for Isolating Differences Between Files" (Commun.
arrayDiff(aOld: any, aNew: any, fnCompare?: any, bUniqueEntries?: any): void;
// A simple assertion mechanism that logs a message when a given condition is not met.
assert(bResult: any, sMessage: any): void;
// Binds all events for listening with the given callback function.
bindAnyEvent(fnCallback: any): void;
// Shortcut for jQuery("#" + id) with additionally the id being escaped properly.
byId(sId: any, oContext: any): void;
// Transforms a hyphen separated string to an camel case string.
camelCase(sString: any): void;
// Converts a character of the string to upper case.
charToUpperCase(sString: any, iPos: any): void;
// Checks a given mouseover or mouseout event whether it is equivalent to a mouseenter or mousleave event regarding the given DOM reference.
checkMouseEnterOrLeave(oEvent: any, oDomRef: any): void;
// Stops the delayed call.
clearDelayedCall(sDelayedCallId: any): void;
// Stops the interval call.
clearIntervalCall(sIntervalCallId: any): void;
// clears the whitelist for URL valiadtion
clearUrlWhitelist(): void;
// Returns whether oDomRefChild is oDomRefContainer or is contained in oDomRefContainer.
containsOrEquals(oDomRefContainer: any, oDomRefChild: any): void;
// Declares a module as existing.
declare(sModuleName: any, bCreateNamespace?: any): void;
// Calls a method after a given delay and returns an id for this timer
delayedCall(iDelay: any, oObject: any, method: any, aParameters?: any): void;
// For the given scroll position measured from the "beginning" of a container (the right edge in RTL mode) this method returns the scrollLeft value as understood by the current browser in RTL mode.
denormalizeScrollBeginRTL(iNormalizedScrollBegin: any, oDomRef: any): void;
// For the given scrollLeft value this method returns the scrollLeft value as understood by the current browser in RTL mode.
denormalizeScrollLeftRTL(iNormalizedScrollLeft: any, oDomRef: any): void;
// Disable touch to mouse handling
disableTouchToMouseHandling(): void;
// Shortcut for document.getElementById(), including a bug fix for older IE versions.
domById(sId: any, oWindow?: any): void;
// Encode the string for inclusion into CSS string literals or identifiers
encodeCSS(sString: any): void;
// Encode the string for inclusion into HTML content/attribute
encodeHTML(sString: any): void;
// Encode the string for inclusion into a JS string literal
encodeJS(sString: any): void;
// Encode the string for inclusion into an URL parameter
encodeURL(sString: any): void;
// Encode a map of parameters into a combined URL parameter string
encodeURLParameters(mParams: any): void;
// Encode the string for inclusion into XML content/attribute
encodeXML(sString: any): void;
// Checks whether a given sString ends with sEndString respecting the case of the strings.
endsWith(sString: any, sEndString: any): void;
// Checks whether a given sString ends with sEndString ignoring the case of the strings.
endsWithIgnoreCase(sString: any, sEndString: any): void;
// Compares the two given values for equality, especially takes care not to compare arrays and objects by reference: any, but compares their content.
equal(a: any, b: any, maxDepth?: any, contains?: any): void;
// This function escapes the reserved letters in Regular Expression
escapeRegExp(sString: any): void;
// Returns a new constructor function that creates objects with the given prototype.
factory(oPrototype: any): void;
// Calls focus() on the given DOM element, but catches and ignores any errors that occur when doing so.
focus(oDomRef: any): void;
// Creates a string from a pattern by replacing placeholders with concrete values.
formatMessage(sPattern: any, aValues?: any): void;
// Returns the names of all declared modules.
getAllDeclaredModules(): void;
// Constructs an URL to load the module with the given name and file type (suffix).
getModulePath(sModuleName: any, sSuffix: any): void;
// Returns a JavaScript object which is identified by a sequence of names.
getObject(sName: any, iNoCreates?: any, oContext?: any): void;
// Determines the URL for a resource given its unified resource name.
getResourcePath(sResourceName: any): void;
// Returns a new function that returns the given oValue (using its closure).
getter(oValue: any): void;
// Creates and returns a new instance of jQuery.sap.util.UriParameters.
getUriParameters(sUri: any): void;
// Gets the whitelist for URL valiadtion
getUrlWhitelist(): void;
// Executes an 'eval' for its arguments in the global context (without closure variables).
globalEval(): void;
// Transforms a camel case string into a hyphen separated string.
hyphen(sString: any): void;
// Includes the script (via <script>-tag) into the head for the specified sUrl and optional sId.
includeScript(sUrl: any, sId?: any, fnLoadCallback?: any, fnErrorCallback?: any): void;
// Includes the specified stylesheet via a <link>-tag in the head of the current document.
includeStyleSheet(sUrl: any, sId?: any, fnLoadCallback?: any, fnErrorCallback?: any): void;
// Does some basic modifications to the HTML page that make it more suitable for mobile apps.
initMobile(options?: any): void;
// Calls a method after a given interval and returns an id for this interval.
intervalCall(iInterval: any, oObject: any, method: any, aParameters?: any): void;
// Check whether a given module has been loaded / declared already.
isDeclared(sModuleName: any, bIncludePreloaded?: any): void;
// Returns a new object which has the given oPrototype as its prototype.
newObject(oPrototype: any): void;
// Returns the window reference for a DomRef
ownerWindow(oDomRef: any): void;
// Pads a string on the left side until is has the given length.
padLeft(sString: any, sPadChar: any, iLength: any): void;
// Pads a string on the right side until is has the given length.
padRight(sString: any, sPadChar: any, iLength: any): void;
// Parses the specified XML formatted string text using native parsing function of the browser and returns a valid XML document.
parseXML(sXMLText: any): void;
// Creates and returns a new instance of jQuery.sap.util.Properties.
properties(mParams?: any): void;
// Registers an URL prefix for a module name prefix.
registerModulePath(sModuleName: any, vUrlPrefix: any): void;
// Registers an URL prefix for a resource name prefix.
registerResourcePath(sResourceNamePrefix: any, vUrlPrefix: any): void;
// Removes a whitelist entry for URL valiadtion
removeUrlWhitelist(iIndex: any): void;
// Ensures that the given module is loaded and executed before execution of the current script continues.
require(vModuleName: any): void;
// Creates and returns a new instance of jQuery.sap.util.ResourceBundle using the given URL and locale to determine what to load.
resources(mParams?: any): void;
// Returns the size (width of the vertical / height of the horizontal) native browser scrollbars.
scrollbarSize(sClasses?: any, bForce?: any): void;
// Serializes the specified XML document into a string representation.
serializeXML(oXMLDocument: any): void;
// Sets the bookmark icon for desktop browsers and the icon to be displayed on the home screen of iOS devices after the user does "add to home screen".
setIcons(oIcons: any): void;
// Sets the "apple-mobile-web-app-capable" and "mobile-web-app-capable" meta information which defines whether the application is loaded in full screen mode (browser address bar and toolbar are hidden) after the user does "add to home screen" on mobile devices.
setMobileWebAppCapable(bValue: any): void;
// Sets an object property to a given value, where the property is identified by a sequence of names (path: any).
setObject(sName: any, vValue: any, oContext?: any): void;
// Convenience wrapper around jQuery.ajax() that avoids the need for callback functions when synchronous calls are made.
sjax(oOrigSettings: any): void;
// Checks whether a given sString starts with sStartString respecting the case of the strings.
startsWith(sString: any, sStartString: any): void;
// Checks whether a given sString starts with sStartString ignoring the case of the strings.
startsWithIgnoreCase(sString: any, sStartString: any): void;
// Convenience wrapper for jQuery.sap.sjax that enforeces the Http method GET and defaults the data type of the result to 'text'.
syncGet(sUrl: any, data: any, sDataType?: any): void;
// Convenience wrapper for jQuery.sap.sjax that enforces the Http method GET and the data type 'json'.
syncGetJSON(sUrl: any, data: any, fallback?: any): void;
// Convenience wrapper for jQuery.sap.sjax that enforces the Http method GET and the data type 'text'.
syncGetText(sUrl: any, data: any, fallback?: any): void;
// Convenience wrapper for jQuery.sap.sjax that enforces the Http method POST and defaults the data type of the result to 'text'.
syncPost(sUrl: any, data: any, sDataType?: any): void;
// Search ancestors of the given source DOM element for the specified CSS class name.
syncStyleClass(sStyleClass: any, vSource: any, vDestination: any): void;
// Creates and returns a pseudo-unique id.
uid(): void;
// Unbinds all events for listening with the given callback function.
unbindAnyEvent(fnCallback: any): void;
// Sorts the given array in-place and removes any duplicates (identified by "===").
unique(a: any): void;
// Validates an URL.
validateUrl(sUrl: any): void;
}
declare interface JQueryStatic {
sap: JquerySap
} | the_stack |
import debounce from 'lodash/debounce';
import isEqual from 'lodash/isEqual';
import React from 'react';
import mapState, {
ActiveMarkers,
MapInfo,
MARKER_SET_KEYS,
} from 'src/components/map-utils/map-state';
import { MARKER_TYPES } from 'src/data';
import * as firebase from 'src/data/firebase';
import { Filter, Page } from 'src/state';
import { isDefined } from 'src/util';
import styled, { LARGE_DEVICES } from '../styling';
import AddInstructions from './add-information';
import { AppContext } from './context';
import { createGoogleMap, haversineDistance } from './map-utils/google-maps';
import infoWindowContent from './map-utils/info-window';
import { debouncedUpdateQueryStringMapLocation } from './map-utils/query-string';
type MarkerInfo = firebase.MarkerInfo;
interface MarkerData {
firebase: Map<string, MarkerIdAndInfo>;
}
type DataSet = keyof MarkerData;
const MARKER_DATA_ID = 'id';
const MARKER_DATA_CIRCLE = 'circle';
const INITIAL_NUMBER_OF_RESULTS = 20;
export interface MarkerId {
set: DataSet;
id: string;
}
export interface MarkerIdAndInfo {
id: MarkerId;
info: MarkerInfo;
}
/**
* Either the current or next set of results in the results pane
*/
export interface ResultsSet {
/**
* How were these results calculated? E.g. were they from a cluster, or the
* current zoom for the whole map.
*/
context: {
/**
* The bounds of the map at the time the results were calculated
*/
bounds: google.maps.LatLngBounds | null;
};
results: MarkerIdAndInfo[];
/**
* How many rows from the results should be shown in the pane?
* (used to limit how many dom elements we have)
*/
showRows: number;
}
const getMarkerId = (marker: google.maps.Marker): MarkerId =>
marker.get(MARKER_DATA_ID);
interface Props {
className?: string;
filter: Filter;
results: ResultsSet | null;
setResults: (results: ResultsSet, openResults?: boolean) => void;
nextResults: ResultsSet | null;
setNextResults: (nextResults: ResultsSet) => void;
selectedResult: MarkerIdAndInfo | null;
setSelectedResult: (selectedResult: MarkerIdAndInfo | null) => void;
/**
* Call this
*/
setUpdateResultsCallback: (callback: (() => void) | null) => void;
page: Page;
setPage: (page: Page) => void;
resultsOpen: boolean;
}
interface State {
/**
* Shall we display service areas?
* Can be disabled when the device has decreased performance
*/
displayServiceAreas: boolean;
}
class MapComponent extends React.Component<Props, State> {
private readonly data: MarkerData = {
firebase: new Map(),
};
private addInfoMapClickedListener:
| ((evt: google.maps.MouseEvent) => void)
| null = null;
private infoWindow: google.maps.InfoWindow | null = null;
public constructor(props: Props) {
super(props);
this.state = {
displayServiceAreas: true,
};
}
public componentDidMount() {
const { setUpdateResultsCallback } = this.props;
setUpdateResultsCallback(this.updateResults);
firebase.addInformationListener(this.informationUpdated);
firebase.loadInitialData();
}
public componentDidUpdate(prevProps: Props) {
const { map } = mapState();
const { filter, results, nextResults, selectedResult } = this.props;
// Update filter if changed
if (map && !isEqual(filter, map.currentFilter)) {
this.updateMarkersVisibilityUsingFilter(filter);
map.currentFilter = filter;
}
if (nextResults && !results) {
// If we have next results queued up, but no results yet, set the results
this.updateResults();
}
// Update selected point if changed
if (selectedResult !== prevProps.selectedResult) {
if (map && selectedResult) {
// Center selected result
// selectedResult.info.loc.
map.map.panTo({
lat: selectedResult.info.loc.latlng.latitude,
lng: selectedResult.info.loc.latlng.longitude,
});
}
this.updateInfoWindow();
}
}
public componentWillUnmount() {
const { setUpdateResultsCallback } = this.props;
setUpdateResultsCallback(null);
firebase.removeInformationListener(this.informationUpdated);
}
private updateMarkersVisibilityUsingFilter = (filter: Filter) => {
const { map } = mapState();
if (map) {
for (const set of MARKER_SET_KEYS) {
map.activeMarkers[set].forEach(marker => {
const info = this.getMarkerInfo(marker);
const validType =
!filter.type || info?.info.type.type === filter.type;
const validVisibility = !!(
!filter.visibility ||
filter.visibility === 'any' ||
(filter.visibility === 'hidden' && !info?.info.visible) ||
(filter.visibility === 'visible' && info?.info.visible)
);
const visible = validType && validVisibility;
marker.setVisible(visible);
});
}
// Ensure that the results are updated given the filter has changed
mapState().updateResultsOnNextBoundsChange = true;
// Trigger reclustering
map.markerClusterer.repaint();
// Trigger recomputation of results
this.updateResultsBasedOnViewport();
}
};
private setAddInfoMapClickedListener = (
listener: ((evt: google.maps.MouseEvent) => void) | null,
) => {
this.addInfoMapClickedListener = listener;
};
/**
* Return true if the usual behaviour for clicking should be supressed
*/
private mapClicked = (evt: google.maps.MouseEvent): boolean => {
if (this.addInfoMapClickedListener) {
this.addInfoMapClickedListener(evt);
return true;
}
return false;
};
private getMarkerInfo = (
marker: google.maps.Marker,
): MarkerIdAndInfo | null => {
const id = getMarkerId(marker);
const info = this.data[id.set].get(id.id);
return info || null;
};
private createMarker = (
activeMarkers: ActiveMarkers,
set: DataSet,
id: string,
info: MarkerInfo,
) => {
const marker = new window.google.maps.Marker({
position: {
lat: info.loc.latlng.latitude,
lng: info.loc.latlng.longitude,
},
title: info.contentTitle,
});
const idData: MarkerId = { set, id };
marker.set(MARKER_DATA_ID, idData);
activeMarkers[set].set(id, marker);
// Add marker listeners
marker.addListener('click', event => {
const { setSelectedResult } = this.props;
if (!this.mapClicked(event)) {
const i = this.getMarkerInfo(marker);
if (i) {
setSelectedResult(i);
}
}
});
return marker;
};
private informationUpdated: firebase.InformationListener = update => {
// Update existing markers, add new markers and delete removed markers
this.data.firebase = new Map();
for (const entry of update.markers.entries()) {
this.data.firebase.set(entry[0], {
id: { set: 'firebase', id: entry[0] },
info: entry[1],
});
}
const { map } = mapState();
if (map) {
// Update existing markers and add new markers
const newMarkers: google.maps.Marker[] = [];
for (const [id, info] of update.markers.entries()) {
const marker = map.activeMarkers.firebase.get(id);
if (marker) {
// Update info
marker.setPosition({
lat: info.loc.latlng.latitude,
lng: info.loc.latlng.longitude,
});
marker.setTitle(info.contentTitle);
} else {
newMarkers.push(
this.createMarker(map.activeMarkers, 'firebase', id, info),
);
}
}
map.markerClusterer.addMarkers(newMarkers, true);
// Delete removed markers
const removedMarkers: google.maps.Marker[] = [];
for (const [id, marker] of map.activeMarkers.firebase.entries()) {
if (!update.markers.has(id)) {
removedMarkers.push(marker);
map.activeMarkers.firebase.delete(id);
// const circle: google.maps.Circle = marker.get(MARKER_DATA_CIRCLE);
// if (circle) {
// circle.setMap(null);
// }
}
}
map.markerClusterer.removeMarkers(removedMarkers, true);
this.updateMarkersVisibilityUsingFilter(map.currentFilter);
}
};
// eslint-disable-next-line react/sort-comp
private updateResultsBasedOnViewport = debounce(() => {
const { map } = mapState();
if (map) {
const bounds = map.map.getBounds() || null;
const nextResults: ResultsSet = {
context: {
bounds,
},
results: [],
showRows: INITIAL_NUMBER_OF_RESULTS,
};
// Go through every marker, and add to results if it is within the bounds
// of the map, and visible
for (const set of MARKER_SET_KEYS) {
for (const markerIdAndInfo of this.data[set].values()) {
if (
!bounds ||
bounds.contains({
lat: markerIdAndInfo.info.loc.latlng.latitude,
lng: markerIdAndInfo.info.loc.latlng.longitude,
})
) {
const marker = map.activeMarkers[set].get(markerIdAndInfo.id.id);
if (marker && marker.getVisible()) {
nextResults.results.push(markerIdAndInfo);
}
}
}
}
const {
results,
setNextResults,
resultsOpen,
selectedResult,
setResults,
} = this.props;
setNextResults(nextResults);
if (
// If we need to update on next clustering
mapState().updateResultsOnNextBoundsChange ||
// If the location hasn't changed (i.e. filter or results themselves)
(nextResults.context.bounds &&
results?.context.bounds?.equals(nextResults.context.bounds)) ||
// If the results panel is currently closed, update the results
// (so that the count display is fresh)
(!resultsOpen && !selectedResult)
) {
mapState().updateResultsOnNextBoundsChange = false;
setResults(nextResults, false);
}
}
}, 50);
private updateGoogleMapRef = (ref: HTMLDivElement | null) => {
const { filter } = this.props;
if (!ref) {
return;
}
const map = createGoogleMap(ref);
const activeMarkers: ActiveMarkers = {
firebase: new Map(),
};
// Create initial markers
for (const set of MARKER_SET_KEYS) {
const data = this.data[set];
for (const [id, info] of data) {
this.createMarker(activeMarkers, set, id, info.info);
}
}
const allMarkers = MARKER_SET_KEYS.map(s => [
...activeMarkers[s].values(),
]).flat();
// Add a marker clusterer to manage the markers.
const markerClusterer = new MarkerClusterer(map, allMarkers, {
imagePath:
'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
ignoreHidden: true,
zoomOnClick: false,
minimumClusterSize: 6,
});
const m: MapInfo = {
map,
activeMarkers,
currentFilter: filter,
markerClusterer,
};
mapState().map = m;
this.updateMarkersVisibilityUsingFilter(filter);
map.addListener('bounds_changed', () => {
if ('replaceState' in window.history) {
debouncedUpdateQueryStringMapLocation(map);
}
this.updateResultsBasedOnViewport();
});
const drawMarkerServiceArea = (marker: google.maps.Marker) => {
const info = this.getMarkerInfo(marker);
if (!info) {
return;
}
const { color } = MARKER_TYPES[info.info.type.type];
const mapBoundingBox = map.getBounds();
if (mapBoundingBox) {
const topRight = mapBoundingBox.getNorthEast();
const bottomLeft = mapBoundingBox.getSouthWest();
const markerPosition = marker.getPosition();
const radius = info.info.loc.serviceRadius;
if (!radius) {
return;
}
// Now compare the distance from the marker to corners of the box;
if (markerPosition) {
const distanceToTopRight = haversineDistance(
markerPosition,
topRight,
);
const distanceToBottomLeft = haversineDistance(
markerPosition,
bottomLeft,
);
let circle: google.maps.Circle = marker.get(MARKER_DATA_CIRCLE);
if (distanceToBottomLeft > radius || distanceToTopRight > radius) {
if (!circle) {
circle = new window.google.maps.Circle({
strokeColor: color,
strokeOpacity: 0.3,
strokeWeight: 1,
fillColor: color,
fillOpacity: 0.15,
map,
center: marker.getPosition() || undefined,
radius,
// If we change this, we need to ensure that we make appropriate
// changes to the marker placement when adding new data so that
// the circle can be clicked to place a marker at the cursor
clickable: false,
});
marker.set(MARKER_DATA_CIRCLE, circle);
}
circle.setVisible(true);
} else if (circle) {
circle.setVisible(false);
}
}
}
};
markerClusterer.addListener('click', (cluster: MarkerClusterer) => {
// Immidiately change the result list to the cluster instead
// Don't update nextResults as we want that to still be for the current
// viewport
const { setResults, setSelectedResult } = this.props;
setSelectedResult(null);
setResults(
{
context: {
bounds: map.getBounds() || null,
},
results: cluster
.getMarkers()
.map(marker => this.getMarkerInfo(marker))
.filter(isDefined),
showRows: INITIAL_NUMBER_OF_RESULTS,
},
true,
);
});
// The clusters have been computed so we can
markerClusterer.addListener(
'clusteringend',
(newClusterParent: MarkerClusterer) => {
const { displayServiceAreas } = this.state;
m.clustering = {
clusterMarkers: new Map(),
};
const markersWithAreaDrawn = new Set<google.maps.Marker>();
for (const cluster of newClusterParent.getClusters()) {
let maxMarker: {
marker: google.maps.Marker;
serviceRadius: number;
} | null = null;
const center = cluster.getCenter();
const clusterMarkers = cluster.getMarkers();
// Figure out which marker in each cluster will generate a circle.
for (const marker of clusterMarkers) {
// Update maxMarker to higher value if found.
const info = this.getMarkerInfo(marker);
if (info) {
if (
info.info.loc.serviceRadius &&
(!maxMarker ||
maxMarker.serviceRadius < info.info.loc.serviceRadius)
) {
maxMarker = {
marker,
serviceRadius: info.info.loc.serviceRadius,
};
}
if (clusterMarkers.length > 1) {
m.clustering.clusterMarkers.set(marker, center);
}
}
}
// Draw a circle for the marker with the largest radius for each cluster (even clusters with 1 marker)
if (displayServiceAreas && maxMarker) {
markersWithAreaDrawn.add(maxMarker.marker);
drawMarkerServiceArea(maxMarker.marker);
}
}
if (displayServiceAreas) {
// Iterate through ALL markers (including hidden ones) to hide all
// service areas we don't want to be visible
MARKER_SET_KEYS.forEach(s =>
m.activeMarkers[s].forEach(marker => {
if (!markersWithAreaDrawn.has(marker)) {
const circle: google.maps.Circle | undefined = marker.get(
MARKER_DATA_CIRCLE,
);
if (circle) {
circle.setVisible(false);
}
}
}),
);
}
// Update tooltip position if neccesary
// (marker may be newly in or out of cluster)
this.updateInfoWindow();
},
);
};
private updateResults = () => {
const { map } = mapState();
const { results, nextResults, setResults } = this.props;
if (map && nextResults && results !== nextResults) {
setResults(nextResults, false);
}
};
/**
* Open the tooltip for the currently selected marker, or close it if none is
* selected. And return the coordinates that were used to place the tooltip.
*/
private updateInfoWindow = (): google.maps.LatLng | undefined => {
const { map } = mapState();
const { selectedResult, setSelectedResult } = this.props;
if (!map) {
return;
}
const marker =
selectedResult &&
map.activeMarkers[selectedResult.id.set].get(selectedResult.id.id);
if (selectedResult && marker) {
const clusterCenter = map.clustering?.clusterMarkers.get(marker);
const contentString = infoWindowContent(selectedResult.info);
if (!this.infoWindow) {
this.infoWindow = new window.google.maps.InfoWindow({
content: contentString,
disableAutoPan: true,
});
this.infoWindow.addListener('closeclick', () =>
setSelectedResult(null),
);
}
this.infoWindow.setContent(contentString);
if (clusterCenter) {
this.infoWindow.open(map.map);
this.infoWindow.setPosition(clusterCenter);
return clusterCenter;
}
this.infoWindow.open(map.map, marker);
return marker.getPosition() || undefined;
}
if (this.infoWindow) {
this.infoWindow.close();
}
};
public render() {
const { map } = mapState();
const { className, page, setPage } = this.props;
return (
<AppContext.Consumer>
{({ lang }) => (
<div className={className}>
<div className="map" ref={this.updateGoogleMapRef} />
{page.page === 'add-information' && (
<AddInstructions
lang={lang}
map={(map && map.map) || null}
addInfoStep={page.step}
setPage={setPage}
setAddInfoMapClickedListener={this.setAddInfoMapClickedListener}
/>
)}
</div>
)}
</AppContext.Consumer>
);
}
}
export default styled(MapComponent)`
height: 100%;
position: relative;
> .map {
height: 100%;
}
> .search {
position: absolute;
max-width: 500px;
top: ${p => p.theme.spacingPx}px;
left: ${p => p.theme.spacingPx}px;
right: 40px;
${LARGE_DEVICES} {
top: ${p => p.theme.spacingPx + p.theme.secondaryHeaderSizePx}px;
}
}
`; | the_stack |
import { EventEmitter } from 'events'
import NetworkRecorder from 'lighthouse/lighthouse-core/lib/network-recorder'
import NetworkMonitor from 'lighthouse/lighthouse-core/gather/driver/network-monitor'
import ProtocolSession from 'lighthouse/lighthouse-core/fraggle-rock/gather/session'
import { waitForFullyLoaded } from 'lighthouse/lighthouse-core/gather/driver/wait-for-condition'
import logger from '@wdio/logger'
import type Protocol from 'devtools-protocol'
import type { TraceEvent, TraceEventArgs } from '@tracerbench/trace-event'
import type { HTTPRequest } from 'puppeteer-core/lib/cjs/puppeteer/common/HTTPRequest'
import type { CDPSession } from 'puppeteer-core/lib/cjs/puppeteer/common/Connection'
import type { Page } from 'puppeteer-core/lib/cjs/puppeteer/common/Page'
import registerPerformanceObserverInPage from '../scripts/registerPerformanceObserverInPage'
import {
FRAME_LOAD_START_TIMEOUT, TRACING_TIMEOUT, MAX_TRACE_WAIT_TIME,
CLICK_TRANSITION, NETWORK_RECORDER_EVENTS
} from '../constants'
import { isSupportedUrl } from '../utils'
import type { GathererDriver } from '../types'
const log = logger('@wdio/devtools-service:TraceGatherer')
export interface Trace {
traceEvents: TraceEvent[]
frameId?: string
loaderId?: string
pageUrl?: string
traceStart?: number
traceEnd?: number
}
interface StartedInBrowserEvent extends TraceEventArgs {
data: {
frames: {
parent: any
processId: number
}[]
}
}
interface NavigationStartEvent extends TraceEventArgs {
data: {
isLoadingMainFrame: boolean
}
}
export interface WaitPromise {
promise: Promise<any>
cancel: Function
}
export default class TraceGatherer extends EventEmitter {
private _failingFrameLoadIds: string[] = []
private _pageLoadDetected = false
private _networkListeners: Record<string, (params: any) => void> = {}
private _frameId?: string
private _loaderId?: string
private _pageUrl?: string
private _networkStatusMonitor: typeof NetworkRecorder
private _networkMonitor: typeof NetworkMonitor
private _protocolSession: typeof ProtocolSession
private _trace?: Trace
private _traceStart?: number
private _clickTraceTimeout?: NodeJS.Timeout
private _waitConditionPromises: Promise<void>[] = []
constructor (private _session: CDPSession, private _page: Page, private _driver: GathererDriver) {
super()
NETWORK_RECORDER_EVENTS.forEach((method) => {
this._networkListeners[method] = (params) => this._networkStatusMonitor.dispatch({ method, params })
})
this._protocolSession = new ProtocolSession(_session)
this._networkMonitor = new NetworkMonitor(_session)
}
async startTracing (url: string) {
/**
* delete old trace
*/
delete this._trace
/**
* register listener for network status monitoring
*/
this._networkStatusMonitor = new NetworkRecorder()
NETWORK_RECORDER_EVENTS.forEach((method) => {
this._session.on(method, this._networkListeners[method])
})
this._traceStart = Date.now()
log.info(`Start tracing frame with url ${url}`)
await this._driver.beginTrace()
/**
* if this tracing was started from a click transition
* then we want to discard page trace if no load detected
*/
if (url === CLICK_TRANSITION) {
log.info('Start checking for page load for click')
this._clickTraceTimeout = setTimeout(async () => {
log.info('No page load detected, canceling trace')
return this.finishTracing()
}, FRAME_LOAD_START_TIMEOUT)
}
/**
* register performance observer
*/
await this._page.evaluateOnNewDocument(registerPerformanceObserverInPage)
this._waitConditionPromises.push(
waitForFullyLoaded(this._protocolSession, this._networkMonitor, { timedOut: 1 })
)
}
/**
* store frame id of frames that are being traced
*/
async onFrameNavigated (msgObj: Protocol.Page.FrameNavigatedEvent) {
if (!this.isTracing) {
return
}
/**
* page load failed, cancel tracing
*/
if (this._failingFrameLoadIds.includes(msgObj.frame.id)) {
delete this._traceStart
this._waitConditionPromises = []
this._frameId = '"unsuccessful loaded frame"'
this.finishTracing()
this.emit('tracingError', new Error(`Page with url "${msgObj.frame.url}" failed to load`))
if (this._clickTraceTimeout) {
clearTimeout(this._clickTraceTimeout)
}
}
/**
* ignore event if
*/
if (
// we already detected a frameId before
this._frameId ||
// the event was thrown for a sub frame (e.g. iframe)
msgObj.frame.parentId ||
// we don't support the url of given frame
!isSupportedUrl(msgObj.frame.url)
) {
log.info(`Ignore navigated frame with url ${msgObj.frame.url}`)
return
}
this._frameId = msgObj.frame.id
this._loaderId = msgObj.frame.loaderId
this._pageUrl = msgObj.frame.url
log.info(`Page load detected: ${this._pageUrl}, set frameId ${this._frameId}, set loaderId ${this._loaderId}`)
/**
* clear click tracing timeout if it's still waiting
*
* the reason we have to tie this to Page.frameNavigated instead of Page.frameStartedLoading
* is because the latter can sometimes occur without the former, which will cause a hang
* e.g. with duolingo's sign-in button
*/
if (this._clickTraceTimeout && !this._pageLoadDetected) {
log.info('Page load detected for click, clearing click trace timeout}')
this._pageLoadDetected = true
clearTimeout(this._clickTraceTimeout)
}
this.emit('tracingStarted', msgObj.frame.id)
}
/**
* once the page load event has fired, we can grab some performance
* metrics and timing
*/
async onLoadEventFired () {
if (!this.isTracing) {
return
}
/**
* Ensure that page is fully loaded and all metrics can be calculated.
*/
const loadPromise = Promise.all(this._waitConditionPromises).then(() => async () => {
/**
* ensure that we trace at least for 5s to ensure that we can
* calculate "interactive"
*/
const minTraceTime = TRACING_TIMEOUT - (Date.now() - (this._traceStart || 0))
if (minTraceTime > 0) {
log.info(`page load happen to quick, waiting ${minTraceTime}ms more`)
await new Promise((resolve) => setTimeout(resolve, minTraceTime))
}
return this.completeTracing()
})
const cleanupFn = await Promise.race([
loadPromise,
this.waitForMaxTimeout()
])
this._waitConditionPromises = []
return cleanupFn()
}
onFrameLoadFail (request: HTTPRequest) {
const frame = request.frame()
if (frame) {
this._failingFrameLoadIds.push(frame._id)
}
}
get isTracing () {
return typeof this._traceStart === 'number'
}
/**
* once tracing has finished capture trace logs into memory
*/
async completeTracing () {
const traceDuration = Date.now() - (this._traceStart || 0)
log.info(`Tracing completed after ${traceDuration}ms, capturing performance data for frame ${this._frameId}`)
/**
* download all tracing data
* in case it fails, continue without capturing any data
*/
try {
const traceEvents = await this._driver.endTrace()
/**
* modify pid of renderer frame to be the same as where tracing was started
* possibly related to https://github.com/GoogleChrome/lighthouse/issues/6968
*/
const startedInBrowserEvt = traceEvents.traceEvents.find(e => e.name === 'TracingStartedInBrowser')
const mainFrame = (
startedInBrowserEvt &&
startedInBrowserEvt.args &&
(startedInBrowserEvt.args as StartedInBrowserEvent)['data']['frames'] &&
(startedInBrowserEvt.args as StartedInBrowserEvent)['data']['frames'].find((frame: any) => !frame.parent)
)
if (mainFrame && mainFrame.processId) {
const threadNameEvt = traceEvents.traceEvents.find(e => e.ph === 'R' &&
e.cat === 'blink.user_timing' && e.name === 'navigationStart' && (e.args as NavigationStartEvent).data.isLoadingMainFrame)
if (threadNameEvt) {
log.info(`Replace mainFrame process id ${mainFrame.processId} with actual thread process id ${threadNameEvt.pid}`)
mainFrame.processId = threadNameEvt.pid
} else {
log.info(`Couldn't replace mainFrame process id ${mainFrame.processId} with actual thread process id`)
}
}
this._trace = {
...traceEvents,
frameId: this._frameId,
loaderId: this._loaderId,
pageUrl: this._pageUrl,
traceStart: this._traceStart,
traceEnd: Date.now()
}
this.emit('tracingComplete', this._trace)
this.finishTracing()
} catch (err: any) {
log.error(`Error capturing tracing logs: ${err.stack}`)
this.emit('tracingError', err)
return this.finishTracing()
}
}
/**
* clear tracing states and emit tracingFinished
*/
finishTracing () {
log.info(`Tracing for ${this._frameId} completed`)
this._pageLoadDetected = false
/**
* clean up the listeners
*/
NETWORK_RECORDER_EVENTS.forEach(
(method) => this._session.off(method, this._networkListeners[method]))
delete this._networkStatusMonitor
delete this._traceStart
delete this._frameId
delete this._loaderId
delete this._pageUrl
this._failingFrameLoadIds = []
this._waitConditionPromises = []
this.emit('tracingFinished')
}
waitForMaxTimeout (maxWaitForLoadedMs = MAX_TRACE_WAIT_TIME) {
return new Promise(
(resolve) => setTimeout(resolve, maxWaitForLoadedMs)
).then(() => async () => {
log.error('Neither network nor CPU idle time could be detected within timeout, wrapping up tracing')
return this.completeTracing()
})
}
} | the_stack |
import * as React from 'react'
import { render, screen } from '@testing-library/react'
import { runSpaceTests } from '../test-helpers'
import { Columns, Column, ColumnWidth } from './'
import { axe } from 'jest-axe'
const columnWidths: Array<ColumnWidth> = [
'1/2',
'1/3',
'1/4',
'1/5',
'2/3',
'2/5',
'3/4',
'3/5',
'4/5',
'auto',
'content',
]
describe('Columns', () => {
it('can be rendered as any HTML element', () => {
render(<Columns data-testid="container" as="label" />)
expect(screen.getByTestId('container').tagName).toBe('LABEL')
})
it('renders its child Column elements as its content', () => {
render(
<Columns data-testid="container">
{columnWidths.map((width) => (
<Column key={width} width={width}>
{width}
</Column>
))}
</Columns>,
)
expect(screen.getByTestId('container').childNodes).toHaveLength(columnWidths.length)
expect(screen.getByTestId('container')).toHaveTextContent(columnWidths.join(''))
})
it('does not acknowledge the className prop, but exceptionallySetClassName instead', () => {
render(
<Columns
data-testid="container"
// @ts-expect-error
className="wrong"
exceptionallySetClassName="right"
/>,
)
expect(screen.getByTestId('container')).not.toHaveClass('wrong')
expect(screen.getByTestId('container')).toHaveClass('right')
})
it('renders as a flex row container', () => {
render(<Columns data-testid="container" />)
expect(screen.getByTestId('container')).toHaveClass('display-flex', 'flexDirection-row')
})
it('applies some extra class names corresponding to other layout-related props', () => {
render(
<Columns
data-testid="container"
maxWidth="large"
minWidth="small"
padding="medium"
border="primary"
borderRadius="standard"
background="highlight"
/>,
)
expect(screen.getByTestId('container')).toHaveClass(
'box',
'minWidth-small',
'maxWidth-large',
'paddingTop-medium',
'paddingRight-medium',
'paddingBottom-medium',
'paddingLeft-medium',
'bg-highlight',
'borderRadius-standard',
'border-primary',
)
})
describe('align', () => {
it('sets the columns horizontal alignment', () => {
// test with no explicit alignment first
const { rerender } = render(<Columns data-testid="container" />)
expect(screen.getByTestId('container')).toHaveClass('justifyContent-flexStart')
// left-aligned horizontally
rerender(<Columns data-testid="container" align="left" />)
expect(screen.getByTestId('container')).toHaveClass('justifyContent-flexStart')
// centered horizontally
rerender(<Columns data-testid="container" align="center" />)
expect(screen.getByTestId('container')).toHaveClass('justifyContent-center')
// right-aligned horizontally
rerender(<Columns data-testid="container" align="right" />)
expect(screen.getByTestId('container')).toHaveClass('justifyContent-flexEnd')
})
it('supports specifying a responsive value', () => {
render(
<Columns
data-testid="container"
align={{ mobile: 'left', tablet: 'center', desktop: 'right' }}
/>,
)
expect(screen.getByTestId('container')).toHaveClass(
'justifyContent-flexStart',
'tablet-justifyContent-center',
'desktop-justifyContent-flexEnd',
)
})
})
describe('alignY', () => {
it('sets the columns vertical alignment', () => {
// test with no explicit alignment first
const { rerender } = render(<Columns data-testid="container" />)
expect(screen.getByTestId('container')).toHaveClass('alignItems-flexStart')
// top-aligned vertically
rerender(<Columns data-testid="container" alignY="top" />)
expect(screen.getByTestId('container')).toHaveClass('alignItems-flexStart')
// centered vertically
rerender(<Columns data-testid="container" alignY="center" />)
expect(screen.getByTestId('container')).toHaveClass('alignItems-center')
// bottom-aligned vertically
rerender(<Columns data-testid="container" alignY="bottom" />)
expect(screen.getByTestId('container')).toHaveClass('alignItems-flexEnd')
})
it('supports specifying a responsive value', () => {
render(
<Columns
data-testid="container"
alignY={{ mobile: 'top', tablet: 'center', desktop: 'bottom' }}
/>,
)
expect(screen.getByTestId('container')).toHaveClass(
'alignItems-flexStart',
'tablet-alignItems-center',
'desktop-alignItems-flexEnd',
)
})
})
describe('collapseBellow', () => {
it('is set to render stacked when instructed to collapse below a certain responsive viewport width', () => {
const { rerender } = render(<Columns data-testid="container" />)
const container = screen.getByTestId('container')
// never collapses by default
expect(container).toHaveClass('display-flex', 'flexDirection-row')
expect(container).not.toHaveClass('flexDirection-column')
expect(container).not.toHaveClass('tablet-flexDirection-row')
expect(container).not.toHaveClass('tablet-flexDirection-column')
expect(container).not.toHaveClass('desktop-flexDirection-row')
expect(container).not.toHaveClass('desktop-flexDirection-column')
// collapses on screens of tablet-like sizes or smaller
rerender(<Columns data-testid="container" collapseBelow="tablet" />)
expect(container).toHaveClass(
'display-flex',
'flexDirection-column',
'tablet-flexDirection-row',
)
expect(container).not.toHaveClass('flexDirection-row')
expect(container).not.toHaveClass('tablet-flexDirection-column')
expect(container).not.toHaveClass('desktop-flexDirection-row')
expect(container).not.toHaveClass('desktop-flexDirection-column')
// collapses on screens of tablet-like sizes or smaller
rerender(<Columns data-testid="container" collapseBelow="desktop" />)
expect(container).toHaveClass(
'display-flex',
'flexDirection-column',
'tablet-flexDirection-column',
'desktop-flexDirection-row',
)
expect(container).not.toHaveClass('flexDirection-row')
expect(container).not.toHaveClass('tablet-flexDirection-row')
expect(container).not.toHaveClass('desktop-flexDirection-column')
})
})
runSpaceTests(Columns)
describe('a11y', () => {
it('renders with no a11y violations', async () => {
const { container } = render(<Columns />)
const results = await axe(container)
expect(results).toHaveNoViolations()
})
})
})
describe('Column', () => {
it('renders its children as its content', () => {
render(
<Columns>
<Column data-testid="column">
Hello <strong>world</strong>!
</Column>
</Columns>,
)
expect(screen.getByTestId('column').innerHTML).toMatchInlineSnapshot(
`"Hello <strong>world</strong>!"`,
)
})
it('can be rendered as any HTML element', () => {
render(
<Columns>
<Column data-testid="column" as="li" />
</Columns>,
)
expect(screen.getByTestId('column').tagName).toBe('LI')
})
it('does not acknowledge the className prop, but exceptionallySetClassName instead', () => {
render(
<Columns>
<Column
data-testid="column"
// @ts-expect-error
className="bad"
exceptionallySetClassName="good"
/>
</Columns>,
)
expect(screen.getByTestId('column')).not.toHaveClass('bad')
expect(screen.getByTestId('column')).toHaveClass('good')
})
it('is set to width auto by default', () => {
render(
<Columns>
<Column data-testid="column" />
</Columns>,
)
const column = screen.getByTestId('column')
expect(column).toHaveClass('columnWidth-auto')
for (const width of columnWidths) {
if (width === 'auto') continue
expect(column).not.toHaveClass(`columnWidth-${width.replace('/', '-')}`)
}
})
it('is set to zero mininum width regardless of the width prop value', () => {
const { rerender } = render(
<Columns>
<Column data-testid="column" width="content" />
</Columns>,
)
const column = screen.getByTestId('column')
for (const width of columnWidths) {
rerender(
<Columns>
<Column data-testid="column" width={width} />
</Columns>,
)
expect(column).toHaveClass('minWidth-0')
}
})
it('is set to the specified width', () => {
const { rerender } = render(
<Columns>
<Column data-testid="column" width="content" />
</Columns>,
)
const column = screen.getByTestId('column')
// for width="content" no css class is added
for (const width of columnWidths) {
expect(column).not.toHaveClass(`columnWidth-${width.replace('/', '-')}`)
}
// for all non-content widths, a single corresponding css class is added
for (const actualWidth of columnWidths) {
if (actualWidth === 'content') continue
rerender(
<Columns>
<Column data-testid="column" width={actualWidth} />
</Columns>,
)
for (const width of columnWidths) {
if (width === actualWidth) continue
expect(column).not.toHaveClass(`columnWidth-${width.replace('/', '-')}`)
}
expect(column).toHaveClass(`columnWidth-${actualWidth.replace('/', '-')}`)
}
})
it('is set to fill the available width unless width="content"', () => {
const { rerender } = render(
<Columns>
<Column data-testid="column" width="content" />
</Columns>,
)
const column = screen.getByTestId('column')
expect(column).not.toHaveClass('width-full')
for (const width of columnWidths) {
if (width === 'content') continue
rerender(
<Columns>
<Column data-testid="column" width={width} />
</Columns>,
)
expect(column).toHaveClass('width-full')
}
})
it('is set to shrink only if width="content"', () => {
const { rerender } = render(
<Columns>
<Column data-testid="column" width="content" />
</Columns>,
)
const column = screen.getByTestId('column')
expect(column).toHaveClass('flexShrink-0')
for (const width of columnWidths) {
if (width === 'content') continue
rerender(
<Columns>
<Column data-testid="column" width={width} />
</Columns>,
)
expect(column).not.toHaveClass('flexShrink-0')
}
})
describe('a11y', () => {
it('renders with no a11y violations', async () => {
const { container } = render(
<Columns>
<Column>Test</Column>
</Columns>,
)
const results = await axe(container)
expect(results).toHaveNoViolations()
})
})
}) | the_stack |
import { FormTemplate } from './@types/form-design/form-template';
const _formTemplates: Array<FormTemplate> = [
{
code: 'pc_00',
title: '空模板',
description: '标准空模板。',
deviceType: 'pc',
library: 'ant-design',
controls: [],
script: `return {
data: {
},
methods: {
test() {
}
},
created() {
}
}`,
style: ``
}, {
code: 'pc_01',
title: '标准流程模板',
description: '戈吉网络标准流程模板。',
deviceType: 'pc',
library: 'ant-design',
controls: [
{
id: "", name: "divider", events: [], propertys: [],
control: { control: "a-divider", slot: {}, propAttrs: {}, events: {}, attrs: { text: "基本信息", remark: "基本信息" } }
}, {
id: "", name: "row", icon: "", childrenSlot: ".ant-col", propertys: [], events: [],
children: [
[ {
id: "", name: "custom", events: [], propertys: [],
control: { control: 'antd-form-design-control-custom', attrs: { label: "申请人", remark: "申请人", renderFn: "me.applicationData.applicantUserName" }, events: {}, propAttrs: {}, slot: {} }
} ], [ {
id: "", name: "custom", events: [], propertys: [],
control: { control: 'antd-form-design-control-custom', attrs: { label: "申请时间", remark: "申请时间", renderFn: "me.applicationData.requestTime" }, events: {}, propAttrs: {}, slot: {} }
} ]
],
control: {
control: "antd-form-design-control-row",
slot: {}, propAttrs: {}, events: {}, attrs: { options: [ { span: 12, offset: 0 }, { span: 12, offset: 0 } ], remark: "基本信息" }
}
}, {
id: "", name: "row", icon: "", childrenSlot: ".ant-col", propertys: [], events: [],
children: [
[ {
id: "", name: "custom", events: [], propertys: [],
control: { control: 'antd-form-design-control-custom', attrs: { label: "所属部门", remark: "所属部门", renderFn: "me.applicationData.applicantDepartment" }, events: {}, propAttrs: {}, slot: {} }
} ], [ {
id: "", name: "custom", events: [], propertys: [],
control: { control: 'antd-form-design-control-custom', attrs: { label: "申请单号", remark: "申请单号", renderFn: "me.applicationData.snNumber" }, events: {}, propAttrs: {}, slot: {} }
} ]
],
control: {
control: "antd-form-design-control-row",
slot: {}, propAttrs: {}, events: {}, attrs: { options: [ { span: 12, offset: 0 }, { span: 12, offset: 0 } ], remark: "基本信息" }
}
}, {
id: "", name: "row", icon: "", childrenSlot: ".ant-col", propertys: [], events: [],
children: [
[ {
id: "", name: "custom", events: [], propertys: [],
control: { control: 'antd-form-design-control-custom', attrs: { label: "公司信息", remark: "公司信息", renderFn: "me.applicationData.company" }, events: {}, propAttrs: {}, slot: {} }
} ], [ {
id: "", name: "custom", events: [], propertys: [],
control: { control: 'antd-form-design-control-custom', attrs: { label: "成本中心", remark: "成本中心", renderFn: "me.applicationData.costcenter" }, events: {}, propAttrs: {}, slot: {} }
} ]
],
control: {
control: "antd-form-design-control-row",
slot: {}, propAttrs: {}, events: {}, attrs: { options: [ { span: 12, offset: 0 }, { span: 12, offset: 0 } ], remark: "基本信息" }
}
}, {
id: "", name: "divider", events: [], propertys: [],
control: { control: "a-divider", slot: {}, propAttrs: {}, events: {}, attrs: { text: "详细信息", remark: "详细信息" } }
}
],
script: `return {
data: {
/** 流程数据 */
taskData: {
/** 流程编号 */
nodeCode: '',
/** 草稿id */
draftId: '',
/** 任务创建时间 */
createTime: '',
/** 审批id */
procId: '',
/** 下一步审批id */
nextProcId: '',
/** 审批状态 */
procStatus: '',
/** 任务id */
taskId: '',
/** 按钮id */
actionId: '',
/** 按钮描述 */
action: '',
/** 审批备注 */
comments: '',
/** 是否为开始节点 */
isStartStep: false,
/** 是否为自动测试 */
isAutoTest: false,
/** 企业id */
enterpriseId: '',
/** 任务状态 */
taskStatus: '',
/** 表单是否为只读 */
isReadOnly: false,
/** 是否结束 */
isEnd: false,
/** 转发/询问/加签时选中的账号 */
assignToUserAccount: ''
},
/** 全局数据 */
applicationData: {
/** 公司名称 */
company: '',
/** 成本中心名称 */
costcenter: '',
/** 表单发起时间 */
requestTime: '',
/** 业务流水号 */
snNumber: '',
/** 表单打开时的登录账号 */
openFormUserAccount: '',
/** 审批人Id */
procUserId: '',
/** 当前用户姓名 */
currentUserName: '',
/** 当前用户账号 */
currentUserAccount: '',
/** 申请人UserId */
applicantUserId: '',
/** 申请人是否有效 */
applicantActive: '',
/** 申请人姓名 */
applicantUserName: '',
/** 申请人邮箱 */
applicantEMail: '',
/** 申请人部门 */
applicantDepartment: '',
/** 发起人Id */
initiatorUserId: '',
/** 发起人姓名 */
initiatorUserName: '',
/** 发起人邮箱 */
initiatorEMail: '',
/** 发起人部门 */
initiatorDepartment: '',
},
/** 表单数据 */
formData: {
}
},
methods: {
/** 获取控件 */
getControl(controlId) {
let _el = null;
const _cb = el => {
if (el.$children.length && !_el) {
for (let i = 0; i < el.$children.length; i++) {
if (el.$children[i].controlId == id) {
_el = el.$children[i].$el;
return;
} else {
_cb(el.$children[i]);
}
}
}
}
_cb(this);
return _el;
},
/** 测试函数 */
fn(numA, numB) {
if (numA && numB) {
return numA + numB;
} else {
return 0;
}
}
},
created() {
}
}`,
style: ``,
api: [
{ name: 'uploadFile', type: 'POST', address: 'http://file.bpm.gejinet.com/api/File/UploadFile', remark: '文件上传接口' }
]
}, {
code: 'mobile_00',
title: 'Vant空模板',
description: '标准空模板。',
deviceType: 'mobile',
library: 'vant',
controls: [],
script: `return {
data: {
},
methods: {
test() {
}
},
created() {
}
}`,
style: ``
}, {
code: 'pc_02',
title: '调试模板',
description: '戈吉网络调试模板。',
deviceType: 'pc',
library: 'ant-design',
controls: [],
script: `return {
data: {
/** 流程数据 */
taskData: {
/** 流程编号 */
nodeCode: '',
/** 草稿id */
draftId: '',
/** 任务创建时间 */
createTime: '',
/** 审批id */
procId: '',
/** 下一步审批id */
nextProcId: '',
/** 审批状态 */
procStatus: '',
/** 任务id */
taskId: '',
/** 按钮id */
actionId: '',
/** 按钮描述 */
action: '',
/** 审批备注 */
comments: '',
/** 是否为开始节点 */
isStartStep: false,
/** 是否为自动测试 */
isAutoTest: false,
/** 企业id */
enterpriseId: '',
/** 任务状态 */
taskStatus: '',
/** 表单是否为只读 */
isReadOnly: false,
/** 是否结束 */
isEnd: false,
/** 转发/询问/加签时选中的账号 */
assignToUserAccount: ''
},
/** 全局数据 */
applicationData: {
/** 公司名称 */
company: '{{公司名称}}',
/** 成本中心名称 */
costcenter: '{{成本中心}}',
/** 表单发起时间 */
requestTime: '{{申请时间}}',
/** 业务流水号 */
snNumber: '{{申请单号}}',
/** 表单打开时的登录账号 */
openFormUserAccount: '',
/** 审批人Id */
procUserId: '',
/** 当前用户姓名 */
currentUserName: '',
/** 当前用户账号 */
currentUserAccount: '',
/** 申请人UserId */
applicantUserId: '',
/** 申请人是否有效 */
applicantActive: '',
/** 申请人姓名 */
applicantUserName: '{{申请人姓名}}',
/** 申请人邮箱 */
applicantEMail: '{{申请人邮箱}}',
/** 申请人部门 */
applicantDepartment: '{{所属部门}}',
/** 发起人Id */
initiatorUserId: '',
/** 发起人姓名 */
initiatorUserName: '',
/** 发起人邮箱 */
initiatorEMail: '',
/** 发起人部门 */
initiatorDepartment: '',
},
/** 表单数据 */
formData: {
}
},
methods: {
/** 获取控件 */
getControl(controlId) {
let _el = null;
const _cb = el => {
if (el.$children.length && !_el) {
for (let i = 0; i < el.$children.length; i++) {
if (el.$children[i].controlId == id) {
_el = el.$children[i].$el;
return;
} else {
_cb(el.$children[i]);
}
}
}
}
_cb(this);
return _el;
}
},
created() {
}
}`,
style: ``,
api: [
{ name: 'uploadFile', type: 'POST', address: 'http://file.bpm.gejinet.com/api/File/UploadFile', remark: '文件上传接口' }
]
}
// {
// code: 'miniapp_01',
// title: 'Uni空模板',
// description: '标准空模板。',
// deviceType: 'mobile',
// library: 'uni',
// controls: [],
// variables: ``,
// functions: ``
// },
];
export default function() {
return _formTemplates;
}; | the_stack |
import React, { useState } from "react";
import CustomScrollArea from "react-perfect-scrollbar";
import {
Box,
Button,
Dialog,
Flex,
Form as FluentUIForm,
ProviderConsumer as FluentUIThemeConsumer,
SiteVariablesPrepared,
} from "@fluentui/react-northstar";
import { getText, TTextObject } from "../../translations";
import { TeamsTheme } from "../../themes";
import { Surface } from "../../types/types";
import { SignifiedOverflow } from "../../lib/SignifiedOverflow";
import { FormTheme } from "./FormTheme";
import {
FormContent,
MaxWidth,
ISection,
IInlineInputsBlock,
setInitialValue,
TInputBlock,
} from "./FormContent";
/**
* A collection of input values, keyed by input ID. If the input is a block of checkboxes or a
* dropdown with multiple selection, the value will be an array of option IDs.
* @public
*/
export interface IFormState {
[inputId: string]: string | string[];
}
/**
* A collection of error messages associated with inputs, keyed by input ID.
* @public
*/
export type TFormErrors = { [inputId: string]: TTextObject };
/**
* An interaction event emitted by the Form component. The payload always contains the Form’s state,
* which contains the values of all the Form’s inputs.
* @public
*/
export type TFormInteraction = {
event: "submit" | "cancel" | "back";
target: "form";
formState: IFormState;
};
/**
* The Form component can be used to render an interactive Form. Designs for this component are
* available in the [Forms page of the Microsoft Teams UI Kit](https://www.figma.com/file/EOsbapNvZgEwcA1mShswfh/Microsoft-Teams-UI-Kit-Community?node-id=5271%3A221958).
* @public
*/
export interface IFormProps {
/**
* A section rendered at the top of the Form, which uses an `h1` for the section’s title. Any
* input groups are ignored.
*/
headerSection?: ISection;
/**
* Form section, each of which can have a title (rendered as an `h2`) and a preface for any
* descriptions or coaching text, which is rendered before any inputs or input groups.
*/
sections: ISection[];
/**
* A collection of error messages associated with inputs, keyed by input ID.
*/
errors?: TFormErrors;
/**
* An error to render at the top of the Form, in case it isn’t relevant to a specific input.
*/
topError?: TTextObject;
/**
* The text content of the submit button.
*/
submit: TTextObject;
/**
* The text content of the cancel button, if relevant. The button is not rendered if this is
* absent.
*/
cancel?: TTextObject;
/**
* An interaction handler for the Form. Interactions are triggered when the user clicks 'submit',
* 'cancel', or 'back' (only in Wizard components).
*/
onInteraction?: (interaction: TFormInteraction) => void;
}
export interface IFormDialogProps extends IFormProps {
/**
* A trigger element for a form dialog.
* @internal
*/
trigger: JSX.Element;
}
/**
* A Form which is a step in a Wizard has the same inputs as Form with an additional option to
* override the text of the Wizard’s back button for the current step.
* @public
*/
export interface IFormWizardStepProps extends IFormProps {
back?: TTextObject;
}
/**
* @internal
*/
export interface IFormWizardStepDialogProps extends IFormWizardStepProps {
trigger: JSX.Element;
}
const dialogStyles = {
minWidth: "320px",
};
const initialFormState = (sections: ISection[]) => {
return sections.reduce(
(acc_i: IFormState, { inputBlocks }) =>
inputBlocks
? inputBlocks.reduce((acc_j: IFormState, inputGroup) => {
if (!inputGroup) return acc_j;
switch (inputGroup.type) {
case "inline-inputs":
return (inputGroup as IInlineInputsBlock).fields.reduce(
setInitialValue,
acc_j
);
default:
return setInitialValue(acc_j, inputGroup as TInputBlock);
}
}, acc_i)
: acc_i,
{}
);
};
/**
* @public
*/
export const Form = ({
cancel,
errors,
headerSection,
sections,
submit,
topError,
onInteraction,
}: IFormProps) => {
const [formState, setFormState] = useState<IFormState>(() =>
initialFormState(sections)
);
return (
<FluentUIThemeConsumer
render={(globalTheme) => {
const { t } = globalTheme.siteVariables;
return (
<FormTheme globalTheme={globalTheme} surface={Surface.base}>
<FluentUIForm
styles={{
display: "block",
"& > *:not(:last-child)": { marginBottom: 0 },
"& > :last-child": { marginTop: 0 },
backgroundColor: "var(--surface-background)",
}}
{...(onInteraction && {
onSubmit: () =>
onInteraction({
event: "submit",
target: "form",
formState,
}),
})}
>
<SignifiedOverflow
body={
<FormContent
{...{
headerSection,
sections,
topError,
errors,
t,
formState,
setFormState,
}}
/>
}
footer={
<MaxWidth
styles={{
display: "flex",
justifyContent: "flex-end",
padding: "1.25rem 2rem",
}}
>
{cancel && (
<Button
content={getText(t.locale, cancel)}
styles={{ marginRight: ".5rem" }}
{...(onInteraction && {
onClick: (e) => {
e.preventDefault();
onInteraction({
event: "cancel",
target: "form",
formState,
});
},
})}
/>
)}
<Button
primary
type="submit"
content={getText(t.locale, submit)}
/>
</MaxWidth>
}
/>
</FluentUIForm>
</FormTheme>
);
}}
/>
);
};
/**
* @internal
*/
export const FormDialog = ({
cancel,
errors,
headerSection,
sections,
submit,
topError,
trigger,
onInteraction,
}: IFormDialogProps) => {
const [formState, setFormState] = useState<IFormState>(
initialFormState(sections)
);
return (
<Dialog
trigger={trigger}
trapFocus
content={
<FluentUIThemeConsumer
render={(globalTheme) => {
const { t } = globalTheme.siteVariables;
return (
<FormTheme globalTheme={globalTheme} surface={Surface.raised}>
<FluentUIForm
styles={{
display: "block",
backgroundColor: "var(--surface-background)",
}}
>
<FormContent
flush
{...{
headerSection,
sections,
topError,
errors,
t,
formState,
setFormState,
breakpointOffset: 28,
}}
/>
</FluentUIForm>
</FormTheme>
);
}}
/>
}
confirmButton={{
content: submit,
...(onInteraction && {
onClick: () =>
onInteraction({
event: "submit",
target: "form",
formState,
}),
}),
}}
cancelButton={{
content: cancel,
...(onInteraction && {
onClick: (e) => {
e.preventDefault();
onInteraction({
event: "cancel",
target: "form",
formState,
});
},
}),
}}
styles={dialogStyles}
/>
);
};
export const FormWizardStep = ({
headerSection,
sections,
topError,
errors,
cancel,
submit,
back,
onInteraction,
}: IFormWizardStepProps) => {
const [formState, setFormState] = useState<IFormState>(
initialFormState(sections)
);
return (
<FluentUIThemeConsumer
render={(globalTheme) => {
const { t } = globalTheme.siteVariables;
return (
<CustomScrollArea style={{ height: "calc(100% - 6rem)" }}>
<FormTheme globalTheme={globalTheme} surface={Surface.base}>
<FluentUIForm
styles={{
display: "block",
"& > *:not(:last-child)": { marginBottom: 0 },
"& > :last-child": { marginTop: 0 },
backgroundColor: "var(--surface-background)",
"@media screen and (min-width: 34rem)": {
paddingLeft: "14rem",
},
}}
{...(onInteraction && {
onSubmit: () =>
onInteraction({
event: "submit",
target: "form",
formState,
}),
})}
>
<FormContent
{...{
headerSection,
sections,
topError,
errors,
t,
formState,
setFormState,
align: "left",
breakpointOffset: 14,
}}
/>
<Box
styles={{
display: "flex",
flexWrap: "wrap",
justifyContent: "flex-end",
backgroundColor: "var(--overlay-background)",
position: "fixed",
bottom: 0,
left: 0,
right: 0,
padding: "1.5rem 2rem 2rem 2.5rem",
zIndex: 2,
"@media screen and (min-width: 34rem)": {
left: "14rem",
},
borderTopStyle: "solid",
}}
variables={({
colorScheme,
theme,
}: SiteVariablesPrepared) => ({
elevation: colorScheme.elevations[16],
borderColor: colorScheme.default.foreground,
borderWidth: `${
theme === TeamsTheme.HighContrast ? "1px" : 0
} 0 0 0`,
})}
>
{cancel && (
<Button
content={getText(t.locale, cancel)}
styles={{ marginRight: ".5rem", marginTop: ".5rem" }}
{...(onInteraction && {
onClick: (e) => {
e.preventDefault();
onInteraction({
event: "cancel",
target: "form",
formState,
});
},
})}
/>
)}
<Box role="none" styles={{ flex: "1 0 0", height: "1px" }} />
{back && (
<Button
content={getText(t.locale, back)}
styles={{ marginRight: ".5rem", marginTop: ".5rem" }}
{...(onInteraction && {
onClick: (e) => {
e.preventDefault();
onInteraction({
event: "back",
target: "form",
formState,
});
},
})}
/>
)}
<Button
primary
type="submit"
content={getText(t.locale, submit)}
styles={{ marginRight: ".5rem", marginTop: ".5rem" }}
/>
</Box>
</FluentUIForm>
</FormTheme>
</CustomScrollArea>
);
}}
/>
);
};
export const FormWizardStepDialog = ({
cancel,
back,
errors,
headerSection,
sections,
submit,
topError,
trigger,
onInteraction,
}: IFormWizardStepDialogProps) => {
const [formState, setFormState] = useState<IFormState>(
initialFormState(sections)
);
return (
<FluentUIThemeConsumer
render={(globalTheme) => {
const { t } = globalTheme.siteVariables;
return (
<Dialog
trigger={trigger}
trapFocus
content={
<FormTheme
globalTheme={globalTheme}
surface={Surface.raised}
styles={{ marginRight: "-1rem" }}
>
<CustomScrollArea
options={{ suppressScrollX: true }}
style={{ maxHeight: "74vh" }}
>
<FluentUIForm
styles={{
display: "block",
backgroundColor: "var(--surface-background)",
paddingRight: "1rem",
}}
>
<FormContent
flush
{...{
headerSection,
sections,
topError,
errors,
t,
formState,
setFormState,
breakpointOffset: 28,
}}
/>
</FluentUIForm>
</CustomScrollArea>
</FormTheme>
}
footer={{
children: (Component, { styles, ...props }) => {
return (
<Flex {...{ styles }}>
<Button
content={getText(t.locale, cancel)}
{...(onInteraction && {
onClick: () => {
onInteraction({
event: "cancel",
target: "form",
formState,
});
},
})}
/>
<Box styles={{ flex: "1 0 0" }} />
{back && (
<Button
content={getText(t.locale, back)}
{...(onInteraction && {
onClick: () => {
onInteraction({
event: "back",
target: "form",
formState,
});
},
styles: { marginRight: ".5rem" },
})}
/>
)}
<Button
primary
content={getText(t.locale, submit)}
{...(onInteraction && {
onClick: () => {
onInteraction({
event: "submit",
target: "form",
formState,
});
},
styles: { marginRight: ".5rem" },
})}
/>
</Flex>
);
},
}}
styles={dialogStyles}
/>
);
}}
/>
);
}; | the_stack |
import { invariant } from '@algomart/shared/utils'
import type { Account, Algodv2, Transaction } from 'algosdk'
import { accountInformation } from './account'
import {
DEFAULT_ADDITIONAL_ROUNDS,
DEFAULT_DAPP_NAME,
MAX_NFT_COUNT,
} from './constants'
import { encodeNote, NoteTypes } from './note'
import { loadSDK, TransactionList } from './utils'
import { encodeTransaction, WalletTransaction } from './wallet'
/**
* Configuration for a single NFT
*/
export type NewNFT = {
assetName: string
unitName: string
assetURL: string
assetMetadataHash: Uint8Array
edition: number
totalEditions: number
}
/**
* Options for creating NFTs
*/
export type NFTOptions = {
algod: Algodv2
creatorAccount: Account
dappName?: string
additionalRounds?: number
enforcerAppID?: number
nfts: NewNFT[]
reference?: string
}
/**
* Create transactions to create NFTs according to the ARC-3 and (optionally) ARC-18 specs. May create up to 16 NFTs at a time.
* @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0003.md
* @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0018.md
* @param options Options for creating NFTs
* @param options.algod Initialized Algodv2 client to get suggested params
* @param options.creatorAccount The account that will create the NFTs
* @param options.dappName Optional dApp name to use for the txn notes
* @param options.additionalRounds Optional additional rounds these transactions are valid for
* @param options.enforcerAppID Optional app ID of the enforcer app to set as manager, freeze, etc
* @param options.nfts The NFTs to create
* @param options.reference Optional reference to include in the txn notes
* @returns Signed transactions to be submitted to the network
*/
export async function createNewNFTsTransactions({
algod,
creatorAccount,
nfts,
enforcerAppID,
reference,
additionalRounds = DEFAULT_ADDITIONAL_ROUNDS,
dappName = DEFAULT_DAPP_NAME,
}: NFTOptions): Promise<TransactionList> {
const {
makeAssetCreateTxnWithSuggestedParamsFromObject,
AtomicTransactionComposer,
makeBasicAccountTransactionSigner,
getApplicationAddress,
} = await loadSDK()
const creatorSigner = makeBasicAccountTransactionSigner(creatorAccount)
const suggestedParams = await algod.getTransactionParams().do()
suggestedParams.lastRound += additionalRounds
const targetAddress = enforcerAppID
? getApplicationAddress(enforcerAppID)
: creatorAccount.addr
invariant(nfts.length > 0, 'No NFTs provided')
invariant(
nfts.length <= MAX_NFT_COUNT,
`Cannot create more than ${MAX_NFT_COUNT} NFTs at once`
)
const atc = new AtomicTransactionComposer()
for (const nft of nfts) {
atc.addTransaction({
signer: creatorSigner,
txn: makeAssetCreateTxnWithSuggestedParamsFromObject({
assetMetadataHash: nft.assetMetadataHash,
assetName: nft.assetName,
assetURL: nft.assetURL,
clawback: targetAddress,
decimals: 0,
defaultFrozen: true,
freeze: targetAddress,
from: creatorAccount.addr,
manager: targetAddress,
note: encodeNote(dappName, {
t: NoteTypes.NonFungibleTokenCreate,
e: nft.edition,
n: nft.totalEditions,
r: reference,
s: ['arc2', 'arc3'].concat(enforcerAppID ? ['arc18'] : []),
}),
// TODO: should this be used for something else?
reserve: targetAddress,
suggestedParams,
total: 1,
unitName: nft.unitName,
}),
})
}
// Build transactions
const group = atc.buildGroup()
// Sign transactions
const signedTxns = await atc.gatherSignatures()
return {
groupID: group[0].txn.group?.toString('base64'),
signedTxns,
txns: group.map((g) => g.txn),
txIDs: group.map((g) => g.txn.txID()),
}
}
/**
* Options for clawback transaction
*/
export type ClawbackNFTOptions = {
algod: Algodv2
additionalRounds?: number
dappName?: string
currentOwnerAddress: string
recipientAccount?: Account
clawbackAccount: Account
fundingAccount?: Account
recipientAddress: string
assetIndex: number
reference?: string
skipOptIn?: boolean
}
/**
* Trigger a clawback transfer of an NFT to a custodial account.
* @param options Options for the clawback transfer
* @param options.additionalRounds Optional additional rounds these transactions are valid for
* @param options.algod Initialized Algodv2 client
* @param options.assetIndex Index of the asset to clawback
* @param options.clawbackAccount Account that is set as the clawback on the NFT
* @param options.currentOwnerAddress Address of the current owner of the NFT
* @param options.dappName Optional name of the dApp
* @param options.fundingAccount Optional account that can fund the NFT opt-in
* @param options.recipientAccount Optional account that needs to opt-in to the NFT
* @param options.recipientAddress Address of the recipient of the NFT
* @param options.reference Optional reference for the clawback
* @param options.skipOptIn Optional flag to skip the opt-in process
* @returns Signed transactions to be submitted to the network
*/
export async function createClawbackNFTTransactions({
additionalRounds = DEFAULT_ADDITIONAL_ROUNDS,
algod,
assetIndex,
clawbackAccount,
currentOwnerAddress,
dappName = DEFAULT_DAPP_NAME,
fundingAccount,
recipientAccount,
recipientAddress,
reference,
skipOptIn,
}: ClawbackNFTOptions): Promise<TransactionList> {
const {
makeBasicAccountTransactionSigner,
makePaymentTxnWithSuggestedParamsFromObject,
makeAssetTransferTxnWithSuggestedParamsFromObject,
AtomicTransactionComposer,
} = await loadSDK()
const suggestedParams = await algod.getTransactionParams().do()
suggestedParams.lastRound += additionalRounds
const clawbackSigner = makeBasicAccountTransactionSigner(clawbackAccount)
const atc = new AtomicTransactionComposer()
if (!skipOptIn) {
invariant(
fundingAccount && recipientAccount,
'Must provide funding and recipient accounts while opting in to NFT'
)
// Send enough money to recipient to cover the "opt-in" transaction and the minimum balance increase
const fundingSigner = makeBasicAccountTransactionSigner(fundingAccount)
atc.addTransaction({
signer: fundingSigner,
txn: makePaymentTxnWithSuggestedParamsFromObject({
suggestedParams,
amount:
100_000 /* minimum balance increase */ + 1000 /* opt-in txn fee */,
from: fundingAccount.addr,
to: recipientAccount.addr,
note: encodeNote(dappName, {
t: NoteTypes.ClawbackTransferPayFunds,
r: reference,
a: assetIndex,
s: ['arc2'],
}),
}),
})
// Recipient needs to "opt-in" to the asset by using a "zero-balance" transaction
const recipientSigner = makeBasicAccountTransactionSigner(recipientAccount)
atc.addTransaction({
signer: recipientSigner,
txn: makeAssetTransferTxnWithSuggestedParamsFromObject({
suggestedParams,
amount: 0,
assetIndex,
from: recipientAccount.addr,
to: recipientAccount.addr,
note: encodeNote(dappName, {
t: NoteTypes.ClawbackTransferOptIn,
r: reference,
s: ['arc2'],
}),
}),
})
}
// Use a clawback to "revoke" ownership from current owner to the recipient.
atc.addTransaction({
signer: clawbackSigner,
txn: makeAssetTransferTxnWithSuggestedParamsFromObject({
suggestedParams,
amount: 1,
assetIndex,
// Who is issuing the transaction
from: clawbackAccount.addr,
to: recipientAddress,
// Who the asset is being revoked from
revocationTarget: currentOwnerAddress,
note: encodeNote(dappName, {
t: NoteTypes.ClawbackTransferTxn,
r: reference,
s: ['arc2'],
}),
}),
})
// Build transactions
const group = atc.buildGroup()
// Sign transactions
const signedTxns = await atc.gatherSignatures()
return {
groupID: group[0].txn.group?.toString('base64'),
signedTxns,
txns: group.map((g) => g.txn),
txIDs: group.map((g) => g.txn.txID()),
}
}
/**
* Metadata structure for ARC3 specification
* @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0003.md#json-metadata-file-schema
*/
export type ARC3Metadata = {
animation_url_integrity?: string
animation_url_mimetype?: string
animation_url?: string
background_color?: string
decimals?: number
description?: string
external_url_integrity?: string
external_url_mimetype?: string
external_url?: string
image_integrity?: string
image_mimetype?: string
image?: string
name?: string
properties?: Record<string, unknown>
extra_metadata?: string
localization?: {
uri: string
default: string
locales: string[]
integrity?: Record<string, string>
}
}
/**
* Helper class to build a metadata structure compliant with ARC3 using a fluent API.
* @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0003.md#json-metadata-file-schema
*/
class MetadataBuilder {
private _metadata: ARC3Metadata = {}
build(): ARC3Metadata {
return Object.freeze(Object.assign({}, this._metadata))
}
toJSON(): string {
return JSON.stringify(this.build())
}
/**
* Set animation URL fields.
* @param url URL to the animation
* @param mimetype Animation content type
* @param integrity Animation integrity hash (SHA256)
* @returns The builder
*/
animation(url: string, mimetype?: string, integrity?: string) {
this._metadata.animation_url = url
this._metadata.animation_url_mimetype = mimetype
this._metadata.animation_url_integrity = integrity
return this
}
/**
* Sets the decimals field.
* @param decimals Number of decimals
* @returns The builder
*/
decimals(decimals: number) {
this._metadata.decimals = decimals
return this
}
/**
* Sets the name field.
* @param name Name of the NFT.
* @returns The builder
*/
name(name: string) {
this._metadata.name = name
return this
}
/**
* Sets the description field.
* @param description Description of the NFT.
* @returns The builder
*/
description(description: string) {
this._metadata.description = description
return this
}
/**
* Sets the image fields.
* @param url URL to the image
* @param mimetype Image content type
* @param integrity Image integrity hash (SHA256)
* @returns The builder
*/
image(url: string, mimetype?: string, integrity?: string) {
this._metadata.image = url
this._metadata.image_mimetype = mimetype
this._metadata.image_integrity = integrity
return this
}
/**
* Sets the background color field.
* @param color Hex color code
* @returns The builder
*/
backgroundColor(color: string) {
this._metadata.background_color = color
return this
}
/**
* Sets the external URL fields.
* @param url URL to the external resource
* @param mimetype Content type of the external resource
* @param integrity Integrity hash of the external resource (SHA256)
* @returns The builder
*/
external(url: string, mimetype?: string, integrity?: string) {
this._metadata.external_url = url
this._metadata.external_url_mimetype = mimetype
this._metadata.external_url_integrity = integrity
return this
}
/**
* Sets a property on the properties field.
* @param key Property key
* @param value Property value
* @returns The builder
*/
property(key: string, value: unknown) {
this._metadata.properties = this._metadata.properties || {}
this._metadata.properties[key] = value
return this
}
/**
* Sets all properties on the properties field. Overrides any existing properties.
* @param properties Properties to set
* @returns The builder
*/
properties(properties: Record<string, unknown>) {
this._metadata.properties = properties
return this
}
/**
* Sets the extra metadata field.
* @param extraMetadata Extra metadata to include, base64 encoded
* @returns The builder
*/
extraMetadata(extraMetadata: string) {
this._metadata.extra_metadata = extraMetadata
return this
}
/**
* Sets the localization fields.
* @param uri URI to the localization file
* @param defaultLocale Default locale used in this metadata JSON file
* @param locales All available locales
* @param integrity Integrity object with hashes for each localized metadata file
* @returns The builder
*/
localization(
uri: string,
defaultLocale: string,
locales: string[],
integrity?: Record<string, string>
) {
this._metadata.localization = {
uri,
default: defaultLocale,
locales,
integrity,
}
return this
}
}
/**
* Create a new MetadataBuilder instance to create ARC3 compliant metadata.
* @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0003.md#json-metadata-file-schema
* @returns A builder to construct ARC3 compliant metadata
*/
export function buildMetadata() {
return new MetadataBuilder()
}
export type ExportNFTOptions = {
additionalRounds?: number
algod: Algodv2
assetIndex: number
clawbackAddress: string
dappName?: string
fromAddress: string
fundingAddress: string
reference?: string
toAddress: string
}
/**
* Creates NFT export transactions for the given asset index.
* @note This should not be used once the Enforcer contract is implemented.
* @param options Options for the export
* @param options.additionalRounds Optional additional rounds these transactions are valid for
* @param options.algod Initialized Algodv2 client
* @param options.assetIndex Index of the asset to export
* @param options.clawbackAddress Address that can perform clawback on the NFT
* @param options.dappName Optional name of the dapp
* @param options.fromAddress Address of the current NFT holder
* @param options.fundingAddress Address to fund the transactions
* @param options.reference Optional reference for the transaction
* @param options.toAddress Address to transfer the NFT to
* @returns Encoded unsigned transactions
*/
export async function createExportNFTTransactions({
additionalRounds = DEFAULT_ADDITIONAL_ROUNDS,
algod,
assetIndex,
clawbackAddress,
dappName = DEFAULT_DAPP_NAME,
fromAddress,
fundingAddress,
reference,
toAddress,
}: ExportNFTOptions): Promise<WalletTransaction[]> {
const {
makePaymentTxnWithSuggestedParamsFromObject,
makeAssetTransferTxnWithSuggestedParamsFromObject,
assignGroupID,
} = await loadSDK()
const suggestedParams = await algod.getTransactionParams().do()
suggestedParams.lastRound += additionalRounds
// Send funds to cover asset transfer transaction
// Signed by funding account
const fundsTxn = makePaymentTxnWithSuggestedParamsFromObject({
suggestedParams,
amount: 2000,
from: fundingAddress,
to: fromAddress,
note: encodeNote(dappName, {
t: NoteTypes.ExportTransferPayFunds,
r: reference,
s: ['arc2'],
}),
})
// Opt-in to asset in recipient's non-custodial wallet
// Signed by non-custodial wallet recipient
const optInTxn = makeAssetTransferTxnWithSuggestedParamsFromObject({
suggestedParams,
amount: 0,
assetIndex,
from: toAddress,
to: toAddress,
note: encodeNote(dappName, {
t: NoteTypes.ExportTransferOptIn,
r: reference,
s: ['arc2'],
}),
})
// Transfer asset to recipient and remove opt-in from sender
// Signed by the user's custodial wallet
const transferAssetTxn = makeAssetTransferTxnWithSuggestedParamsFromObject({
suggestedParams,
assetIndex,
from: clawbackAddress,
to: toAddress,
amount: 1,
revocationTarget: fromAddress,
note: encodeNote(dappName, {
t: NoteTypes.ExportTransferAsset,
r: reference,
s: ['arc2'],
}),
})
const optOutAssetTxn = makeAssetTransferTxnWithSuggestedParamsFromObject({
suggestedParams,
assetIndex,
from: fromAddress,
to: toAddress,
amount: 0,
closeRemainderTo: toAddress,
note: encodeNote(dappName, {
t: NoteTypes.ExportTransferAsset,
r: reference,
s: ['arc2'],
}),
})
// Return min balance funds to funding account
// Signed by the user's custodial wallet
const returnFundsTxn = makePaymentTxnWithSuggestedParamsFromObject({
suggestedParams,
from: fromAddress,
to: fundingAddress,
amount: 100_000,
note: encodeNote(dappName, {
t: NoteTypes.ExportTransferReturnFunds,
r: reference,
s: ['arc2'],
}),
})
const transactions = [
fundsTxn,
optInTxn,
transferAssetTxn,
optOutAssetTxn,
returnFundsTxn,
]
const signers = [
fundingAddress,
toAddress,
clawbackAddress,
fromAddress,
fromAddress,
]
assignGroupID(transactions)
return Promise.all(
transactions.map((txn, index) => {
return encodeTransaction(txn, [signers[index]])
})
)
}
export type ImportNFTOptions = {
additionalRounds?: number
algod: Algodv2
assetIndex: number
clawbackAddress: string
dappName?: string
fromAddress: string
fundingAddress: string
reference?: string
toAddress: string
}
/**
* Create NFT import transactions for the given asset index.
* @param options Options for the import
* @param options.additionalRounds Optional additional rounds these transactions are valid for
* @param options.algod Initialized Algodv2 client
* @param options.assetIndex Index of the asset to import
* @param options.clawbackAddress Address that can perform clawback on the NFT
* @param options.dappName Optional name of the dapp
* @param options.fromAddress Address of the current NFT holder
* @param options.fundingAddress Address to fund the transactions
* @param options.reference Optional reference for the transaction
* @param options.toAddress Address to transfer the NFT to
* @returns Encoded unsigned transactions
*/
export async function createImportNFTTransactions({
algod,
assetIndex,
clawbackAddress,
fromAddress,
fundingAddress,
toAddress,
additionalRounds = DEFAULT_ADDITIONAL_ROUNDS,
dappName = DEFAULT_DAPP_NAME,
reference,
}: ImportNFTOptions) {
const accountInfo = await accountInformation(algod, toAddress)
const transactions: Transaction[] = []
const {
makePaymentTxnWithSuggestedParamsFromObject,
makeAssetTransferTxnWithSuggestedParamsFromObject,
assignGroupID,
} = await loadSDK()
const suggestedParams = await algod.getTransactionParams().do()
suggestedParams.lastRound += additionalRounds
const signers: string[] = []
if (!accountInfo.assets?.some((asset) => asset.assetIndex === assetIndex)) {
// This account has not opted in to this asset
// 0.1 Algo for opt-in, 1000 microAlgos for txn fee
let minBalanceIncrease = 100_000 + 1000
if (accountInfo.amount === 0) {
// this is a brand new account, need to send additional funds
minBalanceIncrease += 100_000
}
// Send funds to cover asset min balance increase
// Signed by the funding account
const fundsTxn = makePaymentTxnWithSuggestedParamsFromObject({
suggestedParams,
amount: minBalanceIncrease,
from: fundingAddress,
to: toAddress,
note: encodeNote(dappName, {
t: NoteTypes.ImportTransferPayFunds,
r: reference,
s: ['arc2'],
}),
})
// Opt-in to asset
// Signed by the user's custodial account
const optInAssetTxn = makeAssetTransferTxnWithSuggestedParamsFromObject({
suggestedParams,
assetIndex,
from: toAddress,
to: toAddress,
amount: 0,
note: encodeNote(dappName, {
t: NoteTypes.ImportTransferOptIn,
r: reference,
s: ['arc2'],
}),
})
signers.push(fundingAddress, toAddress)
transactions.push(fundsTxn, optInAssetTxn)
}
// Transfer asset to recipient and remove opt-in from sender
const transferAssetTxn = makeAssetTransferTxnWithSuggestedParamsFromObject({
suggestedParams,
assetIndex,
from: clawbackAddress,
to: toAddress,
amount: 1,
revocationTarget: fromAddress,
note: encodeNote(dappName, {
t: NoteTypes.ImportTransferAsset,
r: reference,
s: ['arc2'],
}),
})
// Opt out of the asset
// This transaction will be signed by the non-custodial account
const optOutAssetTxn = makeAssetTransferTxnWithSuggestedParamsFromObject({
suggestedParams,
assetIndex,
from: fromAddress,
to: toAddress,
amount: 0,
closeRemainderTo: toAddress,
note: encodeNote(dappName, {
t: NoteTypes.ImportTransferOptOut,
r: reference,
s: ['arc2'],
}),
})
signers.push(clawbackAddress, fromAddress)
transactions.push(transferAssetTxn, optOutAssetTxn)
assignGroupID(transactions)
return Promise.all(
transactions.map((txn, index) => {
return encodeTransaction(txn, [signers[index]])
})
)
} | the_stack |
import { Color, IColor } from '../color/Color';
import { Cell } from '../cell/Cell';
import { ICanvasOptions } from './CanvasOptions';
import { IDisplayOptions } from '../cell/DisplayOptions';
import { WriteStream } from 'tty';
import { encodeToVT100 } from '../encodeToVT100';
/**
* Canvas implements low-level API to terminal control codes.
*
* @see http://www.termsys.demon.co.uk/vtansi.htm
* @see http://misc.flogisoft.com/bash/tip_colors_and_formatting
* @see http://man7.org/linux/man-pages/man4/console_codes.4.html
* @see http://www.x.org/docs/xterm/ctlseqs.pdf
* @see http://wiki.bash-hackers.org/scripting/terminalcodes
* @since 1.0.0
*/
export class Canvas implements ICanvasOptions {
public readonly cells: Cell[];
public lastFrame: string[];
public stream: WriteStream = process.stdout;
public width: number;
public height: number;
public cursorX = 0;
public cursorY = 0;
public cursorBackground: IColor = { r: -1, g: -1, b: -1 };
public cursorForeground: IColor = { r: -1, g: -1, b: -1 };
public cursorDisplay: IDisplayOptions = {
blink: false,
bold: false,
dim: false,
hidden: false,
reverse: false,
underlined: false,
};
/**
* Creates canvas that writes direct to `stdout` by default.
* You can override destination stream with another Writable stream.
* Also, you can specify custom width and height of viewport where cursor will render the frame.
*
* @constructor
* @param {Object} [options]
* @param {Stream} [options.stream=process.stdout] Writable stream
* @param {Number} [options.width=stream.columns] Number of columns (width)
* @param {Number} [options.height=stream.rows] Number of rows (height)
* @example
* Canvas.create({stream: fs.createWriteStream(), width: 20, height: 20});
*/
public constructor (options?: Partial<ICanvasOptions>) {
if (typeof options?.stream !== 'undefined') {
this.stream = options.stream;
}
this.width = this.stream.columns;
if (typeof options?.width !== 'undefined') {
this.width = options.width;
}
this.height = this.stream.rows;
if (typeof options?.height !== 'undefined') {
this.height = options.height;
}
this.cells = Array
.from<Cell>({ length: this.width * this.height })
.map((_, index) => new Cell(' ', { x: this.getXYFromPointer(index)[0], y: this.getXYFromPointer(index)[1] }));
this.lastFrame = Array.from<string>({ length: this.width * this.height }).fill('');
}
/**
* Wrapper around `new Canvas()`.
*
* @static
* @returns {Canvas}
*/
public static create (options?: Partial<ICanvasOptions>): Canvas {
return new this(options);
}
/**
* Write to the buffer.
* It doesn't apply immediately, but stores in virtual terminal that represented as array of {@link Cell} instances.
* For applying changes, you need to call {@link flush} method.
*
* @param {String} data Data to write to the terminal
* @returns {Canvas}
* @example
* canvas.write('Hello, world').flush();
*/
public write (data: string): Canvas {
const { width, height } = this;
const background = this.cursorBackground;
const foreground = this.cursorForeground;
const display = this.cursorDisplay;
for (const char of data) {
const x = this.cursorX;
const y = this.cursorY;
const pointer = this.getPointerFromXY(x, y);
if (x >= 0 && x < width && y >= 0 && y < height) {
const cell = this.cells[pointer];
cell.setChar(char);
cell.setX(x);
cell.setY(y);
cell.setBackground(background.r, background.g, background.b);
cell.setForeground(foreground.r, foreground.g, foreground.b);
cell.setDisplay(display);
cell.isModified = true;
}
this.cursorX += 1;
}
return this;
}
/**
* Flush changes to the real terminal, taking only modified cells.
* Firstly, we get modified cells that have been affected by {@link write} method.
* Secondly, we compare these modified cells with the last frame.
* If cell has changes that doesn't equal to the cell from the last frame - write to the stream.
*
* @returns {Canvas}
*/
public flush (): Canvas {
let payload = '';
for (let i = 0; i < this.cells.length; i += 1) {
const cell = this.cells[i];
if (cell.isModified) {
cell.isModified = false;
const cellSeq = cell.toString();
if (cellSeq !== this.lastFrame[i]) {
this.lastFrame[i] = cellSeq;
payload += cellSeq;
}
}
}
this.stream.write(payload);
return this;
}
/**
* Get index of the virtual terminal representation from (x, y) coordinates.
*
* @param {Number} [x] X coordinate on the terminal
* @param {Number} [y] Y coordinate on the terminal
* @returns {Number} Returns index in the buffer array
* @example
* canvas.getPointerFromXY(0, 0); // returns 0
* canvas.getPointerFromXY(); // x and y in this case is current position of the cursor
*/
public getPointerFromXY (x: number = this.cursorX, y: number = this.cursorY): number {
return y * this.width + x;
}
/**
* Get (x, y) coordinate from the virtual terminal pointer.
*
* @param {Number} index Index in the buffer
* @returns {Array} Returns an array [x, y]
* @example
* canvas.getXYFromPointer(0); // returns [0, 0]
*/
public getXYFromPointer (index: number): [number, number] {
return [index - Math.floor(index / this.width) * this.width, Math.floor(index / this.width)];
}
/**
* Move the cursor up.
*
* @param {Number} [y=1]
* @returns {Canvas}
* @example
* canvas.up(); // moves cursor up by one cell
* canvas.up(5); // moves cursor up by five cells
*/
public up (y = 1): Canvas {
this.cursorY -= Math.floor(y);
return this;
}
/**
* Move the cursor down.
*
* @param {Number} [y=1]
* @returns {Canvas}
* @example
* canvas.down(); // moves cursor down by one cell
* canvas.down(5); // moves cursor down by five cells
*/
public down (y = 1): Canvas {
this.cursorY += Math.floor(y);
return this;
}
/**
* Move the cursor right.
*
* @param {Number} [x=1]
* @returns {Canvas}
* @example
* canvas.right(); // moves cursor right by one cell
* canvas.right(5); // moves cursor right by five cells
*/
public right (x = 1): Canvas {
this.cursorX += Math.floor(x);
return this;
}
/**
* Move the cursor left.
*
* @param {Number} [x=1]
* @returns {Canvas}
* @example
* canvas.left(); // moves cursor left by one cell
* canvas.left(5); // moves cursor left by five cells
*/
public left (x = 1): Canvas {
this.cursorX -= Math.floor(x);
return this;
}
/**
* Move the cursor position relative to the current coordinates.
*
* @param {Number} x Offset by X coordinate
* @param {Number} y Offset by Y coordinate
* @returns {Canvas}
* @example
* canvas.moveBy(5, 5); // moves cursor to the right and down by five cells
*/
public moveBy (x: number, y: number): Canvas {
if (x < 0) this.left(-x);
if (x > 0) this.right(x);
if (y < 0) this.up(-y);
if (y > 0) this.down(y);
return this;
}
/**
* Set the cursor position by absolute coordinates.
*
* @param {Number} x X coordinate
* @param {Number} y Y coordinate
* @returns {Canvas}
* @example
* canvas.moveTo(10, 10); // moves cursor to the (10, 10) coordinate
*/
public moveTo (x: number, y: number): Canvas {
this.cursorX = Math.floor(x);
this.cursorY = Math.floor(y);
return this;
}
/**
* Set the foreground color.
* This color is used when text is rendering.
*
* @param {String} color Color name, rgb, hex or none if you want to disable foreground filling
* @returns {Canvas}
* @example
* canvas.foreground('white');
* canvas.foreground('#000000');
* canvas.foreground('rgb(255, 255, 255)');
* canvas.foreground('none'); // disables foreground filling (will be used default filling)
*/
public foreground (color: string): Canvas {
this.cursorForeground = color === 'none' ? { r: -1, g: -1, b: -1 } : Color.create(color).toRgb();
return this;
}
/**
* Set the background color.
* This color is used for filling the whole cell in the TTY.
*
* @param {String} color Color name, rgb, hex or none if you want to disable background filling
* @returns {Canvas}
* @example
* canvas.background('white');
* canvas.background('#000000');
* canvas.background('rgb(255, 255, 255)');
* canvas.background('none'); // disables background filling (will be used default filling)
*/
public background (color: string): Canvas {
this.cursorBackground = color === 'none' ? { r: -1, g: -1, b: -1 } : Color.create(color).toRgb();
return this;
}
/**
* Toggle bold display mode.
*
* @param {Boolean} [isBold=true] If false, disables bold mode
* @returns {Canvas}
* @example
* canvas.bold(); // enable bold mode
* canvas.bold(false); // disable bold mode
*/
public bold (isBold = true): Canvas {
this.cursorDisplay.bold = isBold;
return this;
}
/**
* Toggle dim display mode.
*
* @param {Boolean} [isDim=true] If false, disables dim mode
* @returns {Canvas}
* @example
* canvas.dim(); // enable dim mode
* canvas.dim(false); // disable dim mode
*/
public dim (isDim = true): Canvas {
this.cursorDisplay.dim = isDim;
return this;
}
/**
* Toggle underlined display mode.
*
* @param {Boolean} [isUnderlined=true] If false, disables underlined mode
* @returns {Canvas}
* @example
* canvas.underlined(); // enable underlined mode
* canvas.underlined(false); // disable underlined mode
*/
public underlined (isUnderlined = true): Canvas {
this.cursorDisplay.underlined = isUnderlined;
return this;
}
/**
* Toggle blink display mode.
*
* @param {Boolean} [isBlink=true] If false, disables blink mode
* @returns {Canvas}
* @example
* canvas.blink(); // enable blink mode
* canvas.blink(false); // disable blink mode
*/
public blink (isBlink = true): Canvas {
this.cursorDisplay.blink = isBlink;
return this;
}
/**
* Toggle reverse display mode.
*
* @param {Boolean} [isReverse=true] If false, disables reverse display mode
* @returns {Canvas}
* @example
* canvas.reverse(); // enable reverse mode
* canvas.reverse(false); // disable reverse mode
*/
public reverse (isReverse = true): Canvas {
this.cursorDisplay.reverse = isReverse;
return this;
}
/**
* Toggle hidden display mode.
*
* @param {Boolean} [isHidden=true] If false, disables hidden display mode
* @returns {Canvas}
* @example
* canvas.hidden(); // enable hidden mode
* canvas.hidden(false); // disable hidden mode
*/
public hidden (isHidden = true): Canvas {
this.cursorDisplay.hidden = isHidden;
return this;
}
/**
* Erase the specified region.
* The region describes the rectangle shape which need to erase.
*
* @param {Number} x1
* @param {Number} y1
* @param {Number} x2
* @param {Number} y2
* @returns {Canvas}
* @example
* canvas.erase(0, 0, 5, 5);
*/
public erase (x1: number, y1: number, x2: number, y2: number): Canvas {
for (let y = y1; y <= y2; y += 1) {
for (let x = x1; x <= x2; x += 1) {
const pointer = this.getPointerFromXY(x, y);
this.cells[pointer]?.reset();
}
}
return this;
}
/**
* Erase from current position to end of the line.
*
* @returns {Canvas}
* @example
* canvas.eraseToEnd();
*/
public eraseToEnd (): Canvas {
return this.erase(this.cursorX, this.cursorY, this.width - 1, this.cursorY);
}
/**
* Erase from current position to start of the line.
*
* @returns {Canvas}
* @example
* canvas.eraseToStart();
*/
public eraseToStart (): Canvas {
return this.erase(0, this.cursorY, this.cursorX, this.cursorY);
}
/**
* Erase from current line to down.
*
* @returns {Canvas}
* @example
* canvas.eraseToDown();
*/
public eraseToDown (): Canvas {
return this.erase(0, this.cursorY, this.width - 1, this.height - 1);
}
/**
* Erase from current line to up.
*
* @returns {Canvas}
* @example
* canvas.eraseToUp();
*/
public eraseToUp (): Canvas {
return this.erase(0, 0, this.width - 1, this.cursorY);
}
/**
* Erase current line.
*
* @returns {Canvas}
* @example
* canvas.eraseLine();
*/
public eraseLine (): Canvas {
return this.erase(0, this.cursorY, this.width - 1, this.cursorY);
}
/**
* Erase the entire screen.
*
* @returns {Canvas}
* @example
* canvas.eraseScreen();
*/
public eraseScreen (): Canvas {
return this.erase(0, 0, this.width - 1, this.height - 1);
}
/**
* Save current terminal state into the buffer.
* Applies immediately without calling {@link flush} method.
*
* @returns {Canvas}
* @example
* canvas.saveScreen();
*/
public saveScreen (): Canvas {
this.stream.write(encodeToVT100('[?47h'));
return this;
}
/**
* Restore terminal state from the buffer.
* Applies immediately without calling {@link flush}.
*
* @returns {Canvas}
* @example
* canvas.restoreScreen();
*/
public restoreScreen (): Canvas {
this.stream.write(encodeToVT100('[?47l'));
return this;
}
/**
* Set the terminal cursor invisible.
* Applies immediately without calling {@link flush}.
*
* @returns {Canvas}
* @example
* canvas.hideCursor();
*/
public hideCursor (): Canvas {
this.stream.write(encodeToVT100('[?25l'));
return this;
}
/**
* Set the terminal cursor visible.
* Applies immediately without calling {@link flush}.
*
* @returns {Canvas}
* @example
* canvas.showCursor();
*/
public showCursor (): Canvas {
this.stream.write(encodeToVT100('[?25h'));
return this;
}
/**
* Reset all terminal settings.
* Applies immediately without calling {@link flush}.
*
* @returns {Canvas}
* @example
* canvas.reset();
*/
public reset (): Canvas {
this.stream.write(encodeToVT100('c'));
return this;
}
} | the_stack |
module Supler {
interface RenderAnyValueField {
(fieldData:FieldData, options:any, compact:boolean): string
}
interface RenderPossibleValuesField {
(fieldData:FieldData,
possibleValues:SelectValue[],
containerOptions:any,
elementOptions:any,
compact:boolean): string
}
export interface RenderOptions {
// main field rendering entry points
// basic types
renderTextField: RenderAnyValueField
renderHiddenField: RenderAnyValueField
renderTextareaField: RenderAnyValueField
renderDateField: RenderAnyValueField
renderMultiChoiceCheckboxField: RenderPossibleValuesField
renderMultiChoiceSelectField: RenderPossibleValuesField
renderSingleChoiceRadioField: RenderPossibleValuesField
renderSingleChoiceSelectField: RenderPossibleValuesField
renderActionField: (fieldData:FieldData, options:any, compact:boolean) => string
// templates
// [label] [input] [validation]
renderField: (input:string, fieldData:FieldData, compact:boolean) => string
renderLabel: (forId:string, label:string) => string
renderDescription: (description:string) => string
renderValidation: (validationId:string) => string
renderRow: (fields: string) => string
renderForm: (rows: string) => string
renderStaticField: (label:string, id:string, validationId:string, value:any, compact:boolean) => string
renderStaticText: (text:string) => string
renderSubformDecoration: (subform:string, label:string, id:string, name:string) => string
renderSubformListElement: (subformElement:string, options:any) => string;
renderSubformTable: (tableHeaders:string[], cells:string[][], elementOptions:any) => string;
// html form elements
renderHtmlInput: (inputType:string, value:any, options:any) => string
renderHtmlSelect: (value:number, possibleValues:SelectValue[], options:any) => string
renderHtmlRadios: (value:any, possibleValues:SelectValue[], containerOptions:any, elementOptions:any) => string
renderHtmlCheckboxes: (value:any, possibleValues:SelectValue[], containerOptions:any, elementOptions:any) => string
renderHtmlTextarea: (value:string, options:any) => string
renderHtmlButton: (label:string, options:any) => string
// misc
additionalFieldOptions: () => any
inputTypeFor: (fieldData:FieldData) => string
}
export class Bootstrap3RenderOptions implements RenderOptions {
constructor() {
}
renderForm(rows:string):string {
return HtmlUtil.renderTag('div', {'class': 'container-fluid'}, rows);
}
renderRow(fields:string):string {
return HtmlUtil.renderTag('div', {'class': 'row'}, fields);
}
renderTextField(fieldData, options, compact) {
var inputType = this.inputTypeFor(fieldData);
return this.renderField(this.renderHtmlInput(inputType, fieldData.value, options), fieldData, compact);
}
renderDateField(fieldData, options, compact) {
var optionsWithDatepicker = this.addDatePickerOptions(options);
return this.renderTextField(fieldData, optionsWithDatepicker, compact);
}
private addDatePickerOptions(fieldOptions) {
var options = fieldOptions;
if (!options) {
options = {};
}
if (!options['class']) {
options['class'] = 'datepicker';
} else {
options['class'] += ' datepicker';
}
options['data-date-format'] = 'yyyy-mm-dd';
options['data-provide'] = 'datepicker';
return options;
}
renderHiddenField(fieldData, options, compact) {
return this.renderHiddenFormGroup(this.renderHtmlInput('hidden', fieldData.value, options));
}
renderTextareaField(fieldData, options, compact) {
return this.renderField(this.renderHtmlTextarea(fieldData.value, options), fieldData, compact);
}
renderStaticField(fieldData, compact) {
return this.renderField(this.renderStaticText(fieldData.value), fieldData, compact);
}
renderStaticText(text) {
return HtmlUtil.renderTagEscaped('div', {'class': 'form-control-static'}, text);
}
renderMultiChoiceCheckboxField(fieldData, possibleValues, containerOptions, elementOptions, compact) {
return this.renderField(this.renderHtmlCheckboxes(fieldData.value, possibleValues, containerOptions, elementOptions), fieldData, compact);
}
renderMultiChoiceSelectField(fieldData, possibleValues, containerOptions, elementOptions, compact) {
return '';
}
renderSingleChoiceRadioField(fieldData, possibleValues, containerOptions, elementOptions, compact) {
return this.renderField(this.renderHtmlRadios(fieldData.value, possibleValues, containerOptions, elementOptions), fieldData, compact);
}
renderSingleChoiceSelectField(fieldData, possibleValues, containerOptions, elementOptions, compact) {
return this.renderField(this.renderHtmlSelect(fieldData.value, possibleValues, elementOptions), fieldData, compact);
}
renderActionField(fieldData, options, compact) {
var fieldDataNoLabel = Util.copyObject(fieldData);
fieldDataNoLabel.label = '';
return this.renderField(this.renderHtmlButton(fieldData.label, options), fieldDataNoLabel, compact);
}
//
renderField(input, fieldData, compact) {
var labelPart;
var descriptionPart;
if (compact) {
labelPart = '';
descriptionPart = '';
} else {
labelPart = this.renderLabel(fieldData.id, fieldData.label);
descriptionPart = this.renderDescription(fieldData.description);
}
var divBody = labelPart +
'\n' +
input +
'\n' +
descriptionPart +
'\n' +
this.renderValidation(fieldData.validationId) +
'\n';
return HtmlUtil.renderTag('div', {'class': 'form-group'+this.addColumnWidthClass(fieldData)}, divBody);
}
private addColumnWidthClass(fieldData: FieldData) {
if (fieldData.fieldsPerRow > 0) {
return ' col-md-' + (fieldData.fieldsPerRow >= 12 ? 1 : 12 / fieldData.fieldsPerRow);
} else {
return '';
}
}
renderHiddenFormGroup(input) {
return HtmlUtil.renderTag('span', {
'class': 'hidden-form-group',
'style': 'visibility: hidden; display: none'
}, input);
}
renderLabel(forId, label) {
return HtmlUtil.renderTagEscaped('label', {'for': forId}, label);
}
renderDescription(description) {
if (description) {
return HtmlUtil.renderTagEscaped('p', {'class': 'help-block'}, description);
} else return '';
}
renderValidation(validationId) {
return HtmlUtil.renderTagEscaped('div', {'class': 'text-danger', 'id': validationId});
}
renderSubformDecoration(subform, label, id, name) {
var fieldsetBody = '\n';
fieldsetBody += HtmlUtil.renderTagEscaped('legend', {}, label);
fieldsetBody += subform;
return HtmlUtil.renderTag('fieldset', {'id': id}, fieldsetBody);
}
renderSubformListElement(subformElement, options) {
var optionsWithClass = Util.copyProperties({'class': 'well'}, options);
return HtmlUtil.renderTag('div', optionsWithClass, subformElement);
}
renderSubformTable(tableHeaders, cells, elementOptions) {
var tableBody = this.renderSubformTableHeader(tableHeaders);
tableBody += this.renderSubformTableBody(cells, elementOptions);
return HtmlUtil.renderTag('table', {'class': 'table'}, tableBody);
}
private renderSubformTableHeader(tableHeaders) {
var trBody = '';
tableHeaders.forEach((header) => trBody += HtmlUtil.renderTagEscaped('th', {}, header));
return HtmlUtil.renderTag('tr', {}, trBody);
}
private renderSubformTableBody(cells, elementOptions) {
var html = '';
for (var i = 0; i < cells.length; i++) {
var row = cells[i];
var trBody = '';
for (var j = 0; j < row.length; j++) {
trBody += HtmlUtil.renderTag('td', {}, row[j]);
}
html += HtmlUtil.renderTag('tr', elementOptions, trBody) + '\n';
}
return html;
}
//
renderHtmlInput(inputType, value, options) {
var inputOptions = Util.copyProperties({'type': inputType, 'value': value}, options);
return HtmlUtil.renderTag('input', inputOptions);
}
renderHtmlSelect(value, possibleValues, options) {
var selectBody = '';
Util.foreach(possibleValues, (i, v) => {
var optionOptions = {'value': v.id};
if (v.id === value) {
optionOptions['selected'] = 'selected';
}
selectBody += HtmlUtil.renderTagEscaped('option', optionOptions, v.label);
});
var html = HtmlUtil.renderTag('select', options, selectBody);
html += '\n';
return html;
}
renderHtmlRadios(value, possibleValues, containerOptions, elementOptions) {
return this.renderCheckable('radio', possibleValues, containerOptions, elementOptions,
(v) => {
return v.id === value;
});
}
renderHtmlCheckboxes(value, possibleValues, containerOptions, elementOptions) {
return this.renderCheckable('checkbox', possibleValues, containerOptions, elementOptions,
(v) => {
return value.indexOf(v.id) >= 0;
});
}
renderHtmlTextarea(value, options) {
return HtmlUtil.renderTagEscaped('textarea', options, value);
}
renderHtmlButton(label, options) {
var allOptions = Util.copyProperties({'type': 'button'}, options);
allOptions['class'] = allOptions['class'].replace('form-control', 'btn btn-default');
return HtmlUtil.renderTagEscaped('button', allOptions, label);
}
private renderCheckable(inputType:string, possibleValues:SelectValue[],
containerOptions:any, elementOptions:any, isChecked:(SelectValue) => boolean) {
var html = '';
Util.foreach(possibleValues, (i, v) => {
var checkableOptions = Util.copyProperties({}, elementOptions);
// for checkables we need to remove the form-control default class or they look ugly
checkableOptions['class'] = checkableOptions['class'].replace('form-control', '');
if (isChecked(v)) {
checkableOptions['checked'] = 'checked';
}
checkableOptions['id'] = containerOptions['id'] + '.' + v.id;
var labelBody = this.renderHtmlInput(inputType, v.id, checkableOptions);
labelBody += HtmlUtil.renderTagEscaped('span', {}, v.label);
var divBody = HtmlUtil.renderTag('label', {}, labelBody);
html += HtmlUtil.renderTag('div', {'class': inputType}, divBody);
});
return HtmlUtil.renderTag('span', containerOptions, html);
}
//
additionalFieldOptions() {
return {'class': 'form-control'};
}
inputTypeFor(fieldData:FieldData):string {
switch (fieldData.type) {
case FieldTypes.INTEGER:
return 'number';
case FieldTypes.FLOAT:
return 'number';
}
switch (fieldData.getRenderHintName()) {
case 'password':
return 'password';
}
return 'text';
}
}
} | the_stack |
import {getComponentClass, getComponentId} from './ComponentId';
import {Class} from '../utils/Class';
import {Signal} from '../utils/Signal';
import {isTag, Tag} from './Tag';
import {ILinkedComponent, isLinkedComponent} from './LinkedComponent';
import {LinkedComponentList} from './LinkedComponentList';
/**
* Entity readonly interface
*/
export interface ReadonlyEntity {
/**
* The signal dispatches if new component or tag was added to the entity
*/
readonly onComponentAdded: Signal<ComponentUpdateHandler>;
/**
* The signal dispatches if component was removed from the entity
*/
readonly onComponentRemoved: Signal<ComponentUpdateHandler>;
/**
* Returns components map, where key is component identifier, and value is a component itself
* @see {@link getComponentId}, {@link Entity.getComponents}
*/
readonly components: Readonly<Record<number, unknown>>;
/**
* Returns set of tags applied to the entity
* @see getComponentId
*/
readonly tags: ReadonlySet<Tag>;
/**
* Returns value indicating whether entity has a specific component or tag
*
* @param {Class | Tag} componentClassOrTag
* @example
* ```ts
* const BERSERK = 10091;
* if (!entity.has(Immobile) || entity.has(BERSERK)) {
* const position = entity.get(Position)!;
* position.x += 1;
* }
* ```
*/
has<T>(componentClassOrTag: Class<T> | Tag): boolean;
/**
* Returns value indicating whether entity contains a component instance.
* If the component is an instance of ILinkedComponent then all components of its type will be checked for equality.
*
* @param {T} component
* @param {Class<K>} resolveClass
* @example
* ```ts
* const boon = new Boon(BoonType.HEAL);
* entity
* .append(new Boon(BoonType.PROTECTION));
* .append(boon);
*
* if (entity.contains(boon)) {
* logger.info('Ah, sweet. We have not only protection but heal as well!');
* }
* ```
*/
contains<T extends K, K>(component: T, resolveClass?: Class<K>): boolean
/**
* Returns value indicating whether entity has a specific component
*
* @param component
* @example
* ```
* if (!entity.hasComponent(Immobile)) {
* const position = entity.get(Position)!;
* position.x += 1;
* }
* ```
*/
hasComponent<T>(component: Class<T>): boolean;
/**
* Returns value indicating whether entity has a specific tag
*
* @param tag
* @example
* ```ts
* const BERSERK = "berserk";
* let damage = initialDamage;
* if (entity.hasTag(BERSERK)) {
* damage *= 1.2;
* }
* ```
*/
hasTag(tag: Tag): boolean;
/**
* Returns value indicating whether entity have any of specified components/tags
*
* @param {Class<unknown> | Tag} componentClassOrTag
* @returns {boolean}
* @example
* ```ts
* const IMMORTAL = "immortal";
* if (!entity.hasAny(Destroy, Destroying, IMMORTAL)) {
* entity.add(new Destroy());
* }
* ```
*/
hasAny(...componentClassOrTag: Array<Class<unknown> | Tag>): boolean;
/**
* Returns value indicating whether entity have all of specified components/tags
*
* @param {Class<unknown> | Tag} componentClassOrTag
* @returns {boolean}
* @example
* ```ts
* const I_LOVE_GRAVITY = "no-i-don't";
* if (entity.hasAll(Position, Acceleration, I_LOVE_GRAVITY)) {
* entity.get(Position)!.y += entity.get(Acceleration)!.y * dt;
* }
* ```
*/
hasAll(...componentClassOrTag: Array<Class<unknown> | Tag>): boolean
/**
* Returns an array of entity components
*
* @returns {unknown[]}
*/
getComponents(): unknown[];
/**
* Returns an array of tags applied to the entity
*/
getTags(): Tag[];
/**
* Gets a component instance if it's exists in the entity, otherwise returns `undefined`
* - If you want to check presence of the tag then use {@link has} instead.
*
* @param componentClass Specific component class
*/
get<T>(componentClass: Class<T>): T | undefined;
/**
* Iterates over instances of linked component appended to the Entity and performs the action over each.<br>
* Works and for standard components (action will be called for a single instance in this case).
*
* @param {Class<T>} componentClass Component`s class
* @param {(component: T) => void} action Action to perform over every component instance.
* @example
* ```ts
* class Boon extends LinkedComponent {
* public constructor(
* public type: BoonType,
* public duration: number
* ) { super(); }
* }
* const entity = new Entity()
* .append(new Boon(BoonType.HEAL, 2))
* .append(new Boon(BoonType.PROTECTION, 3);
*
* // Let's decrease every boon duration and remove them if they are expired.
* entity.iterate(Boon, (boon) => {
* if (--boon.duration <= 0) {
* entity.pick(boon);
* }
* });
* ```
*/
iterate<T>(componentClass: Class<T>, action: (component: T) => void): void;
/**
* Returns generator with all instances of specified linked component class
*
* @param {Class<T>} componentClass Component`s class
* @example
* ```ts
* for (const damage of entity.linkedComponents(Damage)) {
* if (damage.value < 0) {
* throw new Error('Damage value can't be less than zero');
* }
* ```
*/
getAll<T>(componentClass: Class<T>): Generator<T, void, T>;
/**
* Searches a component instance of specified linked component class.
* Works and for standard components (predicate will be called for a single instance in this case).
*
* @param {Class<T>} componentClass
* @param {(component: T) => boolean} predicate
* @return {T | undefined}
*/
find<T>(componentClass: Class<T>, predicate: (component: T) => boolean): T | undefined;
/**
* Returns number of components of specified class.
*
* @param {Class<T>} componentClass
* @return {number}
*/
lengthOf<T>(componentClass: Class<T>): number;
}
/**
* Entity is a general purpose object, which can be marked with tags and can contain different components.
* So it is just a container, that can represent any in-game entity, like enemy, bomb, configuration, game state, etc.
*
* @example
* ```ts
* // Here we can see structure of the component "Position", it's just a data that can be attached to the Entity
* // There is no limits for component`s structure.
* // Components mustn't hold the reference to the entity that it attached to.
*
* class Position {
* public x:number;
* public y:number;
*
* public constructor(x:number = 0, y:number = 0) {
* this.x = x;
* this.y = y;
* }
* }
*
* // We can mark an entity with the tag OBSTACLE. Tag can be represented as a number or string.
* const OBSTACLE = 10100;
*
* const entity = new Entity()
* .add(OBSTACLE)
* .add(new Position(10, 5));
* ```
*/
export class Entity implements ReadonlyEntity {
/**
* The signal dispatches if new component or tag was added to the entity. Works for every linked component as well.
*/
public readonly onComponentAdded: Signal<ComponentUpdateHandler> = new Signal();
/**
* The signal dispatches if component was removed from the entity. Works for every linked component as well.
*/
public readonly onComponentRemoved: Signal<ComponentUpdateHandler> = new Signal();
/**
* The signal dispatches that invalidation requested for this entity.
* Which means that if the entity attached to the engine — its queries will be updated.
*
* Use {@link Entity.invalidate} method in case if in query test function is using component properties or complex
* logic.
*
* Only adding/removing components and tags are tracked by Engine. So you need to request queries invalidation
* manually, if some of your queries depends on logic or component`s properties.
*/
public readonly onInvalidationRequested: Signal<(entity: Entity) => void> = new Signal();
/**
* Unique id identifier
*/
public readonly id = entityId++;
private _components: Record<number, unknown> = {};
private _linkedComponents: Record<number, LinkedComponentList<ILinkedComponent>> = {};
private _tags: Set<Tag> = new Set();
/**
* Returns components map, where key is component identifier, and value is a component itself
* @see {@link getComponentId}, {@link Entity.getComponents}
*/
public get components(): Readonly<Record<number, unknown>> {
return this._components;
}
/**
* Returns set of tags applied to the entity
* @see getComponentId
*/
public get tags(): ReadonlySet<Tag> {
return this._tags;
}
/**
* Adds a component or tag to the entity.
* It's a unified shorthand for {@link addComponent} and {@link addTag}.
*
* - If a component of the same type already exists in entity, it will be replaced by the passed one (only if
* component itself is not the same, in this case - no actions will be done).
* - If the tag is already present in the entity - no actions will be done.
* - During components replacement {@link onComponentRemoved} and {@link onComponentAdded} are will be triggered
* sequentially.
* - If there is no component of the same type, or the tag is not present in the entity - then only
* - If the passed component is an instance of ILinkedComponent then all existing instances will be removed, and the
* passed instance will be added to the Entity. {@link onComponentRemoved} will be triggered for every removed
* instance and {@link onComponentAdded} will be triggered for the passed component.
* - Linked component always replaces all existing instances. Even if the passed instance already exists in the
* Entity - all existing linked components will be removed anyway, and replaced with the passed one.
*
* @throws Throws error if component is null or undefined, or if component is not an instance of the class as well
* @param {T | Tag} componentOrTag Component instance or Tag
* @param {K} resolveClass Class that should be used as resolving class.
* Passed class always should be an ancestor of Component's class.
* It has sense only if component instance is passed, but not the Tag.
* @returns {Entity} Reference to the entity itself. It helps to build chain of calls.
* @see {@link addComponent, appendComponent}, {@link addTag}
* @example
* ```ts
* const BULLET = 1;
* const EXPLOSIVE = "explosive";
* const entity = new Entity()
* .add(new Position())
* .add(new View())
* .add(new Velocity())
* .add(BULLET)
* .add(EXPLOSIVE);
* ```
*/
public add<T extends K, K extends unknown>(componentOrTag: NonNullable<T> | Tag, resolveClass?: Class<K>): Entity {
if (isTag(componentOrTag)) {
this.addTag(componentOrTag);
} else {
this.addComponent(componentOrTag, resolveClass);
}
return this;
}
/**
* Appends a linked component to the entity.
*
* - If linked component is not exists, then it will be added to the Entity and {@link onComponentAdded}
* will be triggered.
* - If component already exists in the entity, then passed one will be appended to the tail. {@link onComponentAdded}
* will be triggered as well.
*
* It's a shorthand to {@link appendComponent}
*
* @throws Throws error if component is null or undefined, or if component is not an instance of the class as well
* @param {T | Tag} component ILinkedComponent instance
* @param {K} resolveClass Class that should be used as resolving class.
* Passed class always should be an ancestor of Component's class.
*
* @returns {Entity} Reference to the entity itself. It helps to build chain of calls.
* @see {@link addComponent}
* @see {@link appendComponent}
* @example
* ```ts
* const damage = new Damage();
* const entity = new Entity()
* .append(new Damage(1))
* .append(new Damage(2))
*
* const damage = entity.get(Damage);
* while (entity.has(Damage)) {
* const entity = entity.withdraw(Damage);
* print(damage.value);
* }
* ```
*/
public append<T extends K, K extends ILinkedComponent>(component: NonNullable<T>, resolveClass?: Class<K>): Entity {
return this.appendComponent(component, resolveClass);
}
/**
* Removes first appended linked component instance of the specified type.
* Unlike {@link remove} and {@link removeComponent} remaining linked components stays in the Entity.
*
* - If linked component exists in the Entity, then it will be removed from Entity and {@link onComponentRemoved}
* will be triggered.
*
* @param {Class<T>} componentClass
* @return {T | undefined} Component instance if any of the specified type exists in the entity, otherwise undefined
* @example
* ```ts
* const entity = new Entity()
* .append(new Damage(1))
* .append(new Damage(2))
* .append(new Damage(3));
*
* entity.withdraw(Damage);
* entity.iterate(Damage, (damage) => {
* print('Remaining damage: ' + damage.value);
* });
*
* // Remaining damage: 2
* // Remaining damage: 3
* ```
*/
public withdraw<T>(componentClass: Class<T>): T | undefined {
const component = this.get(componentClass);
if (component !== undefined) {
return this.withdrawComponent(component as NonNullable<T>, componentClass);
}
return undefined;
}
/**
* Removes particular linked component instance from the Entity.
*
* - If linked component instance exists in the Entity, then it will be removed from Entity and
* {@link onComponentRemoved} will be triggered.
*
* @param {NonNullable<T>} component Linked component instance
* @param {Class<K>} resolveClass Resolve class
* @return {T | undefined} Component instance if it exists in the entity, otherwise undefined
*/
public pick<T>(component: NonNullable<T>, resolveClass?: Class<T>): T | undefined {
return this.withdrawComponent(component, resolveClass);
}
/**
* Adds a component to the entity.
*
* - If a component of the same type already exists in entity, it will be replaced by the passed one (only if
* component itself is not the same, in this case - no actions will be done).
* - During components replacement {@link onComponentRemoved} and {@link onComponentAdded} are will be triggered
* sequentially.
* - If there is no component of the same type - then only {@link onComponentAdded} will be triggered.
*
* @throws Throws error if component is null or undefined, or if component is not an instance of the class as well
* @param {T} component Component instance
* @param {K} resolveClass Class that should be used as resolving class.
* Passed class always should be an ancestor of Component's class.
* @returns {Entity} Reference to the entity itself. It helps to build chain of calls.
* @see {@link add}, {@link addTag}
* @example
* ```ts
* const BULLET = 1;
* const entity = new Entity()
* .addComponent(new Position())
* .addComponent(new View())
* .add(BULLET);
* ```
*/
public addComponent<T extends K, K extends unknown>(component: NonNullable<T>, resolveClass?: Class<K>): void {
const componentClass = getComponentClass(component, resolveClass);
const id = getComponentId(componentClass, true)!;
const linkedComponent = isLinkedComponent(component);
if (this._components[id] !== undefined) {
if (!linkedComponent && component === this._components[id]) {
return;
}
this.remove(componentClass);
}
if (linkedComponent) {
this.append(component as ILinkedComponent, resolveClass as Class<ILinkedComponent>);
} else {
this._components[id] = component;
this.dispatchOnComponentAdded(component);
}
}
/**
* Appends a linked component to the entity.
*
* - If linked component is not exists, then it will be added via `addComponent` method and {@link onComponentAdded}
* will be triggered.
* - If component already exists in the entity, then passed one will be appended to the tail. {@link
* onComponentAdded} wont be triggered.
*
* @throws Throws error if component is null or undefined, or if component is not an instance of the class as well
* @param {T | Tag} component ILinkedComponent instance
* @param {K} resolveClass Class that should be used as resolving class.
* Passed class always should be an ancestor of Component's class.
*
* @returns {Entity} Reference to the entity itself. It helps to build chain of calls.
* @see {@link append}
* @see {@link addComponent}
* @example
* ```ts
* const damage = new Damage();
* const entity = new Entity()
* .append(new Damage())
* .append(new Damage())
*
* const damage = entity.get(Damage);
* while (damage !== undefined) {
* print(damage.value);
* damage = damage.next;
* }
* ```
*/
public appendComponent<T extends K, K extends ILinkedComponent>(component: NonNullable<T>, resolveClass?: Class<K>): Entity {
const componentClass = getComponentClass(component, resolveClass);
const componentId = getComponentId(componentClass, true)!;
const componentList = this.getLinkedComponentList(componentId)!;
componentList.add(component);
if (this._components[componentId] === undefined) {
this._components[componentId] = componentList.head;
}
this.dispatchOnComponentAdded(component);
return this;
}
/**
* Adds a tag to the entity.
*
* - If the tag is already present in the entity - no actions will be done.
* - If there is such tag in the entity then {@link onComponentAdded} will be triggered.
*
* @param {Tag} tag Tag
* @returns {Entity} Reference to the entity itself. It helps to build chain of calls.
* @see {@link add}, {@link addComponent}
* @example
* ```ts
* const DEVELOPER = "developer;
* const EXHAUSTED = 2;
* const = "game-over";
* const entity = new Entity()
* .addTag(DEVELOPER)
* .add(EXHAUSTED)
* ```
*/
public addTag(tag: Tag): void {
if (!this._tags.has(tag)) {
this._tags.add(tag);
this.dispatchOnComponentAdded(tag);
}
}
/**
* Returns componentClassOrTag indicating whether entity has a specific component or tag
*
* @param componentClassOrTag
* @example
* ```ts
* const BERSERK = 10091;
* if (!entity.has(Immobile) || entity.has(BERSERK)) {
* const position = entity.get(Position)!;
* position.x += 1;
* }
* ```
*/
public has<T>(componentClassOrTag: Class<T> | Tag): boolean {
if (isTag(componentClassOrTag)) {
return this.hasTag(componentClassOrTag);
}
return this.hasComponent(componentClassOrTag);
}
/**
* Returns value indicating whether entity contains a component instance.
* If the component is an instance of ILinkedComponent then all components of its type will be checked for equality.
*
* @param {NonNullable<T>} component
* @param {Class<K>} resolveClass
* @example
* ```ts
* const boon = new Boon(BoonType.HEAL);
* entity
* .append(new Boon(BoonType.PROTECTION));
* .append(boon);
*
* if (entity.contains(boon)) {
* logger.info('Ah, sweet. We have not only protection but heal as well!');
* }
* ```
*/
public contains<T extends K, K>(component: NonNullable<T>, resolveClass?: Class<K>): boolean {
const componentClass = getComponentClass(component, resolveClass);
if (isLinkedComponent(component)) {
return this.find(componentClass, (value) => value === component) !== undefined;
}
return this.get(componentClass) === component;
}
/**
* Returns value indicating whether entity has a specific component
*
* @param component
* @example
* ```
* if (!entity.hasComponent(Immobile)) {
* const position = entity.get(Position)!;
* position.x += 1;
* }
* ```
*/
public hasComponent<T>(component: Class<T>): boolean {
const id = getComponentId(component);
if (id === undefined) return false;
return this._components[id] !== undefined;
}
/**
* Returns value indicating whether entity has a specific tag
*
* @param tag
* @example
* ```ts
* const BERSERK = "berserk";
* let damage = initialDamage;
* if (entity.hasTag(BERSERK)) {
* damage *= 1.2;
* }
* ```
*/
public hasTag(tag: Tag): boolean {
return this._tags.has(tag);
}
/**
* Returns value indicating whether entity have any of specified components/tags
*
* @param {Class<unknown> | Tag} componentClassOrTag
* @returns {boolean}
* @example
* ```ts
* const IMMORTAL = "immortal";
* if (!entity.hasAny(Destroy, Destroying, IMMORTAL)) {
* entity.add(new Destroy());
* }
* ```
*/
public hasAny(...componentClassOrTag: Array<Class<unknown> | Tag>): boolean {
return componentClassOrTag.some(value => this.has(value));
}
/**
* Returns value indicating whether entity have all of specified components/tags
*
* @param {Class<unknown> | Tag} componentClassOrTag
* @returns {boolean}
* @example
* ```ts
* const I_LOVE_GRAVITY = "no-i-don't";
* if (entity.hasAll(Position, Acceleration, I_LOVE_GRAVITY)) {
* entity.get(Position)!.y += entity.get(Acceleration)!.y * dt;
* }
* ```
*/
public hasAll(...componentClassOrTag: Array<Class<unknown> | Tag>): boolean {
return componentClassOrTag.every(value => this.has(value));
}
/**
* Gets a component instance if it's exists in the entity, otherwise returns `undefined`
* - If you want to check presence of the tag then use {@link has} instead.
*
* @param componentClass Specific component class
*/
public get<T>(componentClass: Class<T>): T | undefined {
const id = getComponentId(componentClass);
if (id === undefined) return undefined;
return this._components[id] as T;
}
/**
* Returns an array of entity components
*
* @returns {unknown[]}
*/
public getComponents(): unknown[] {
return Array.from(Object.values(this._components));
}
/**
* Returns an array of tags applied to the entity
*/
public getTags(): Tag[] {
return Array.from(this._tags);
}
/**
* Removes a component or tag from the entity.
* In case if the component or tag is present - then {@link onComponentRemoved} will be
* dispatched after removing it from the entity.
*
* If linked component type provided:
* - For each instance of linked component {@link onComponentRemoved} will be called
* - Only head of the linked list will be returned.
*
* If you need to get all instances use {@link withdraw} or {@link pick} instead, or check {@link iterate},
* {@link getAll}
*
* It's a shorthand for {@link removeComponent}
*
* @param componentClassOrTag Specific component class or tag
* @returns Component instance or `undefined` if it doesn't exists in the entity, or tag was removed
* @see {@link withdraw}
* @see {@link pick}
*/
public remove<T>(componentClassOrTag: Class<T> | Tag): T | undefined {
if (isTag(componentClassOrTag)) {
this.removeTag(componentClassOrTag);
return undefined;
}
return this.removeComponent(componentClassOrTag);
}
/**
* Removes a component from the entity.
* In case if the component or tag is present - then {@link onComponentRemoved} will be
* dispatched after removing it from the entity.
*
* If linked component type provided:
* - For each instance of linked component {@link onComponentRemoved} will be called
* - Only head of the linked list will be returned.
*
* If you need to get all instances use {@link withdraw} or {@link pick} instead, or check {@link iterate},
* {@link getAll}
*
* @param componentClassOrTag Specific component class
* @returns Component instance or `undefined` if it doesn't exists in the entity
*/
public removeComponent<T>(componentClassOrTag: Class<T>): T | undefined {
const id = getComponentId(componentClassOrTag);
if (id === undefined || this._components[id] === undefined) {
return undefined;
}
let value = this._components[id];
if (isLinkedComponent(value)) {
const list = this.getLinkedComponentList(componentClassOrTag)!;
while (!list.isEmpty) {
this.withdraw(componentClassOrTag);
}
} else {
delete this._components[id];
this.dispatchOnComponentRemoved(value);
}
return value as T;
}
/**
* Removes a tag from the entity.
* In case if the component tag is present - then {@link onComponentRemoved} will be
* dispatched after removing it from the entity
*
* @param {Tag} tag Specific tag
* @returns {void}
*/
public removeTag(tag: Tag): void {
if (this._tags.has(tag)) {
this._tags.delete(tag);
this.dispatchOnComponentRemoved(tag);
}
}
/**
* Removes all components and tags from entity
*/
public clear(): void {
this._components = {};
this._linkedComponents = {};
this._tags.clear();
}
/**
* Copies content from entity to itself.
* Linked components structure will be copied by the link, because we can't duplicate linked list order without
* cloning components itself. So modifying linked components in the copy will affect linked components in copy
* source.
*
* @param {Entity} entity
* @return {this}
*/
public copyFrom(entity: Entity): this {
this._components = Object.assign({}, entity._components);
this._linkedComponents = Object.assign({}, entity._linkedComponents);
this._tags = new Set(entity._tags);
return this;
}
/**
* Iterates over instances of linked component appended to the Entity and performs the action over each.<br>
* Works and for standard components (action will be called for a single instance in this case).
*
* @param {Class<T>} componentClass Component`s class
* @param {(component: T) => void} action Action to perform over every component instance.
* @example
* ```ts
* class Boon extends LinkedComponent {
* public constructor(
* public type: BoonType,
* public duration: number
* ) { super(); }
* }
* const entity = new Entity()
* .append(new Boon(BoonType.HEAL, 2))
* .append(new Boon(BoonType.PROTECTION, 3);
*
* // Let's decrease every boon duration and remove them if they are expired.
* entity.iterate(Boon, (boon) => {
* if (--boon.duration <= 0) {
* entity.pick(boon);
* }
* });
* ```
*/
public iterate<T>(componentClass: Class<T>, action: (component: T) => void): void {
if (!this.hasComponent(componentClass)) return;
this.getLinkedComponentList(componentClass)?.iterate(action);
}
/**
* Returns generator with all instances of specified linked component class
*
* @param {Class<T>} componentClass Component`s class
* @example
* ```ts
* for (const damage of entity.linkedComponents(Damage)) {
* if (damage.value < 0) {
* throw new Error('Damage value can't be less than zero');
* }
* ```
*/
public* getAll<T>(componentClass: Class<T>): Generator<T, void, T | undefined> {
if (!this.hasComponent(componentClass)) return;
const list = this.getLinkedComponentList(componentClass, false);
if (list === undefined) return undefined;
yield* list.nodes();
}
/**
* Searches a component instance of specified linked component class.
* Works and for standard components (predicate will be called for a single instance in this case).
*
* @param {Class<T>} componentClass
* @param {(component: T) => boolean} predicate
* @return {T | undefined}
*/
public find<T>(componentClass: Class<T>, predicate: (component: T) => boolean): T | undefined {
const componentIdToFind = getComponentId(componentClass, false);
if (componentIdToFind === undefined) return undefined;
const component = this._components[componentIdToFind];
if (component === undefined) return undefined;
if (isLinkedComponent(component)) {
let linkedComponent: ILinkedComponent | undefined = component;
while (linkedComponent !== undefined) {
if (predicate(linkedComponent as T)) return linkedComponent as T;
linkedComponent = linkedComponent.next;
}
} else return predicate(component as T) ? component as T : undefined;
}
/**
* Returns number of components of specified class.
*
* @param {Class<T>} componentClass
* @return {number}
*/
public lengthOf<T>(componentClass: Class<T>): number {
let result = 0;
this.iterate(componentClass, () => {
result++;
});
return result;
}
/**
* Use this method to dispatch that entity component properties were changed, in case if
* queries predicates are depends on them.
* Components properties are not tracking by Engine itself, because it's too expensive.
*/
public invalidate(): void {
this.onInvalidationRequested.emit(this);
}
/**
* @internal
* @param {EntitySnapshot} result
* @param {T} changedComponentOrTag
* @param {Class<T>} resolveClass
*/
public takeSnapshot<T>(result: EntitySnapshot, changedComponentOrTag?: T, resolveClass?: Class<T>): void {
const previousState = result.previous as Entity;
if (result.current !== this) {
result.current = this;
previousState.copyFrom(this);
}
if (changedComponentOrTag === undefined) {
return;
}
if (isTag(changedComponentOrTag)) {
const previousTags = previousState._tags;
if (this.has(changedComponentOrTag)) {
previousTags.delete(changedComponentOrTag);
} else {
previousTags.add(changedComponentOrTag);
}
} else {
const componentClass = resolveClass ?? Object.getPrototypeOf(changedComponentOrTag).constructor;
const componentId = getComponentId(componentClass!, true)!;
const previousComponents = previousState._components;
if (this.has(componentClass)) {
delete previousComponents[componentId];
} else {
previousComponents[componentId] = changedComponentOrTag;
}
}
}
/**
* @internal
*/
public getLinkedComponentList(componentClassOrId: number | Class<any>, createIfNotExists = true): LinkedComponentList<any> | undefined {
if (typeof componentClassOrId !== 'number') {
componentClassOrId = getComponentId(componentClassOrId)!;
}
if (this._linkedComponents[componentClassOrId] !== undefined || !createIfNotExists) {
return this._linkedComponents[componentClassOrId];
} else {
return this._linkedComponents[componentClassOrId] = new LinkedComponentList<ILinkedComponent>();
}
}
private withdrawComponent<T extends K, K extends ILinkedComponent>(component: NonNullable<T>, resolveClass?: Class<K>): T | undefined {
const componentClass = getComponentClass(component, resolveClass);
if (!isLinkedComponent(component)) {
return this.remove(componentClass);
}
const componentList = this.getLinkedComponentList(componentClass, false);
if (!this.hasComponent(componentClass) || componentList === undefined) return undefined;
const result = componentList.remove(component) ? component : undefined;
const componentId = getComponentId(componentClass, true)!;
if (componentList.isEmpty) {
delete this._components[componentId];
delete this._linkedComponents[componentId];
} else {
this._components[componentId] = componentList.head;
}
if (result !== undefined) {
this.dispatchOnComponentRemoved(result);
}
return result;
}
private dispatchOnComponentAdded<T>(component: NonNullable<T>): void {
if (this.onComponentAdded.hasHandlers) {
this.onComponentAdded.emit(this, component);
}
}
private dispatchOnComponentRemoved<T>(value: NonNullable<T>): void {
if (this.onComponentRemoved.hasHandlers) {
this.onComponentRemoved.emit(this, value);
}
}
}
/**
* EntitySnapshot is a content container that displays the difference between the current state of Entity and its
* previous state.
*
* The {@link EntitySnapshot.current} property always reflects the current state, and {@link EntitySnapshot.previous} -
* previous one. So you can understand which components have been added and which have been removed.
*
* <p>It is important to note that changes in the data of the same entity components will not be reflected in the
* snapshot, even if a manual invalidation of the entity has been triggered.</p>
*/
export class EntitySnapshot {
private _current?: Entity;
private _previous: ReadonlyEntity = new Entity();
/**
* Gets an instance of the actual entity
* @returns {Entity}
*/
public get current(): Entity {
return this._current!;
}
/**
* @internal
*/
public set current(value: Entity) {
this._current = value;
}
/**
* Gets an instance of the previous state of entity
*/
public get previous(): ReadonlyEntity {
return this._previous;
}
}
/**
* Component update handler type.
* @see {@link Entity.onComponentAdded}
* @see {@link Entity.onComponentRemoved}
*/
export type ComponentUpdateHandler = (entity: Entity, componentOrTag: unknown, componentClass?: Class<unknown>) => void;
/**
* Entity ids enumerator
*/
let entityId: number = 1; | the_stack |
import { ArrayParser } from '@/parsers/ArrayParser';
import { TestParser, Scope } from '../../lib/TestParser';
describe('parsers/ArrayParser', () => {
TestParser.Case({
case: '0',
given: {
parser: new ArrayParser({
schema: { type: 'array' },
model: []
})
},
expected: {
parser: {
kind: 'array',
items: [],
additionalItems: undefined,
max: -2,
count: 0,
model: [],
rawValue: [],
limit: 0,
children: [],
field: {
sortable: false,
minItems: 0,
maxItems: Number.MAX_SAFE_INTEGER,
pushButton: {
disabled: true,
trigger: ({ value }: Scope) => expect(value).toBeInstanceOf(Function)
},
addItemValue: ({ value }: Scope) => expect(value).toBeInstanceOf(Function)
}
}
}
});
TestParser.Case({
case: '1.0',
given: {
parser: new ArrayParser({
schema: { type: 'array' },
model: undefined
})
},
expected: {
parser: {
initialValue: [],
model: [],
rawValue: []
}
}
});
TestParser.Case({
case: '1.1',
given: {
parser: new ArrayParser({
schema: {
type: 'array',
items: { type: 'string' },
default: [ 'arya' ]
},
model: undefined
})
},
expected: {
parser: {
initialValue: [ 'arya' ],
model: [ 'arya' ],
rawValue: [ 'arya' ],
field: {
sortable: true
}
}
}
});
TestParser.Case({
case: '1.2',
given: {
parser: new ArrayParser({
schema: {
type: 'array',
items: { type: 'string', default: 'tyrion' },
minItems: 1
},
model: undefined
})
},
expected: {
parser: {
initialValue: [],
model: [ 'tyrion' ],
rawValue: [ 'tyrion' ]
}
}
});
TestParser.Case({
case: '1.3',
given: {
parser: new ArrayParser({
schema: {
type: 'array',
items: { type: 'string' }
},
model: undefined,
required: true
})
},
expected: {
parser: {
initialValue: [],
model: [],
rawValue: [ undefined ]
}
}
});
TestParser.Case({
case: '2.0',
given: {
parser: new ArrayParser({
schema: { type: 'array' },
model: [ 12 ]
})
},
expected: {
parser: {
items: [],
additionalItems: undefined,
max: -2,
get count() {
return this.rawValue.length;
},
model: [ 12 ],
rawValue: [ 12 ],
limit: 0,
children: [],
field: {
uniqueItems: undefined,
minItems: 0,
maxItems: Number.MAX_SAFE_INTEGER,
pushButton: {
disabled: true
}
}
}
}
});
TestParser.Case({
case: '2.1',
description: 'field.getField()',
given: {
parser: new ArrayParser({
schema: {
type: 'array',
items: {
type: 'string'
}
},
model: [ 'Stark', 'Targaryen' ]
})
},
expected: {
parser: {
field: {
getField({ value, field }: Scope) {
expect(value('.[]')).toBeNull();
expect(value('.[0]')).toBe(field.children[0]);
expect(value('.[1]')).toBe(field.children[1]);
expect(value('.[3]')).toBeNull();
}
}
}
}
});
TestParser.Case({
case: '2.2',
description: 'field.getField()',
given: {
parser: new ArrayParser({
schema: {
type: 'array',
items: {
type: 'string'
}
},
model: []
})
},
expected: {
parser: {
field: {
getField({ value, field }: Scope) {
expect(value('')).toBe(field);
expect(value('.')).toBe(field);
expect(value('.unexsisting')).toBeNull();
expect(value('.[0]')).toBeNull();
}
}
}
}
});
TestParser.Case({
case: '3.0',
description: 'with options.required === true',
given: {
parser: new ArrayParser({
schema: {
type: 'array',
items: [
{ type: 'string' }
]
},
model: [],
required: true
})
},
expected: {
parser: {
items: [ { type: 'string' } ],
additionalItems: undefined,
max: 1,
count: 1,
model: [],
rawValue: [ undefined ],
limit: 1,
children({ value }: Scope) {
expect(value.length).toBe(this.limit);
},
field: {
required: true,
uniqueItems: undefined,
sortable: false,
minItems: 1,
maxItems: Number.MAX_SAFE_INTEGER,
pushButton: {
disabled: true
}
}
}
}
});
const options4: any = {
schema: {
type: 'array',
items: { type: 'string' },
minItems: 1,
maxItems: 2,
uniqueItems: true
},
model: []
};
TestParser.Case({
case: '4.0',
given: {
parser: new ArrayParser(options4)
},
expected: {
parser: {
items: [
{ type: 'string' }
],
additionalItems: undefined,
get max() {
return this.field.maxItems;
},
count: 1,
model: [],
rawValue: [ undefined ],
get limit() {
return this.count;
},
children({ value }: Scope) {
expect(value.length).toBe(this.limit);
},
field: {
uniqueItems: undefined,
minItems: 1,
maxItems: 2,
pushButton: {
disabled: false
}
}
}
}
});
TestParser.Case({
case: '4.1',
given: {
parser() {
const parser = new ArrayParser(options4);
parser.parse();
parser.field.pushButton.trigger();
return parser;
}
},
expected: {
parser: {
count: 2,
model: [],
rawValue: [ undefined, undefined ],
get limit() {
return this.count;
},
children({ value }: Scope) {
expect(value.length).toBe(this.limit);
},
field: {
pushButton: {
disabled: true
}
}
}
}
});
TestParser.Case({
case: '4.2',
description: 'field.pushButton.trigger()',
given: {
parser() {
const parser = new ArrayParser(options4);
parser.parse();
// call field.pushButton.trigger() twice
parser.field.pushButton.trigger();
parser.field.pushButton.trigger();
return parser;
}
},
expected: {
parser: {
count: 2,
model: [],
rawValue: [ undefined, undefined ],
get limit() {
return this.count;
},
children({ value }: Scope) {
expect(value.length).toBe(this.limit);
},
field: {
pushButton: {
disabled: true
}
}
}
}
});
const options5: any = {
schema: {
type: 'array',
items: { type: 'string', enum: [ 'a', 'b', 'c', 'd' ] },
uniqueItems: true
},
model: [ 'b', 'd' ]
};
TestParser.Case({
case: '5.0',
description: 'with array enums (checkbox)',
given: {
parser: new ArrayParser(options5)
},
expected: {
parser: {
items: [
{ type: 'string', default: 'a', title: 'a' },
{ type: 'string', default: 'b', title: 'b' },
{ type: 'string', default: 'c', title: 'c' },
{ type: 'string', default: 'd', title: 'd' }
],
additionalItems: undefined,
max: 4,
count: 4,
model: [ 'b', 'd' ],
rawValue: [ undefined, 'b', undefined, 'd' ],
limit: 4,
children: ({ value }: Scope) => expect(value.length).toBe(4),
field: {
required: false,
uniqueItems: true,
children: ({ value: [ field0 ] }: Scope) => {
// expect(field0.descriptor.kind).toBe('checkbox');
expect(field0.attrs.type).toBe('checkbox');
},
minItems: 0,
maxItems: 4,
pushButton: {
disabled: true
}
}
},
descriptor: {
kind: 'array'
}
}
});
// TestParser.Case({
// case: '5.1',
// description: 'with custom descriptor',
// parser: new ArrayParser({
// ...options5,
// descriptor: {
// items: [
// {
// label: 'label-a',
// helper: 'description-a'
// },
// {
// label: 'label-b',
// helper: 'description-b'
// },
// {
// label: 'label-c',
// helper: 'description-c'
// },
// {
// label: 'label-d',
// helper: 'description-d'
// }
// ]
// }
// }),
// expected: {
// children: (fields: ArrayField[]) => fields.forEach(({ descriptor }: ArrayField, i) => {
// const label = `label-${options5.schema.items.enum[i]}`;
// const description = `description-${options5.schema.items.enum[i]}`;
// expect(descriptor.label).toBe(label);
// expect(descriptor.helper).toBe(description);
// })
// }
// });
TestParser.Case({
case: '5.2',
description: 'with updated checkbox input',
given: {
parser() {
const parser = new ArrayParser(options5);
parser.parse();
parser.field.fields[0].setValue(true);
return parser;
}
},
expected: {
parser: {
model: [ 'a', 'b', 'd' ],
rawValue: [ 'a', 'b', undefined, 'd' ]
}
}
});
TestParser.Case({
case: '6',
description: 'with min/max and default model',
given: {
parser: new ArrayParser({
schema: {
type: 'array',
items: { type: 'string' },
minItems: 3,
maxItems: 4
},
model: [ 'a', 'd' ]
})
},
expected: {
parser: {
items: [
{ type: 'string' }
],
additionalItems: undefined,
max: 4,
count: 3,
model: [ 'a', 'd' ],
rawValue: [ 'a', 'd', undefined ],
limit({ value }: Scope) {
expect(value).toBe(this.count);
},
children: ({ value }: Scope) => expect(value.length).toBe(3),
field: {
uniqueItems: undefined,
minItems: 3,
maxItems: 4,
pushButton: {
disabled: false
}
}
}
}
});
TestParser.Case({
case: '7.0',
description: 'with additional items',
given: {
parser: new ArrayParser({
schema: {
type: 'array',
items: [
{ type: 'string' }
],
additionalItems: { type: 'number' }
},
model: [ 'a', 12 ]
})
},
expected: {
parser: {
items: [
{ type: 'string' }
],
additionalItems: { type: 'number' },
max: -1,
count() {
return this.rawValue.length;
},
model: [ 'a', 12 ],
rawValue: [ 'a', 12 ],
limit({ value }: Scope) {
expect(value).toBe(this.items.length);
},
children({ value }: Scope) {
expect(value.length).toBe(this.rawValue.length);
},
field: {
required: false,
uniqueItems: undefined,
minItems: 0,
maxItems: Number.MAX_SAFE_INTEGER,
pushButton: {
disabled: false
}
}
}
}
});
TestParser.Case({
case: '7.1',
description: 'with an undefined schema type',
given: {
parser: new ArrayParser({
schema: {
type: 'array',
items: [
{ type: 'string' }
],
additionalItems: { type: undefined } as any
},
model: [ 'a', 12 ]
})
},
expected: {
parser: {
items: [
{ type: 'string' }
],
additionalItems: { type: undefined },
children({ value }: Scope) {
expect(value.length).toBe(this.items.length);
}
}
}
});
const options8: any = (bracketedObjectInputNameValue: boolean) => ({
name: 'array',
schema: {
type: 'array',
items: { type: 'string' }
},
model: [ 'a', 12 ],
bracketedObjectInputName: bracketedObjectInputNameValue
});
TestParser.Case({
case: '8.0',
description: 'with name and bracketedObjectInputName === true',
given: {
parser: new ArrayParser(options8(true))
},
expected: {
parser: {
children({ value: items }: Scope) {
expect(items.length).toBe(2);
items.forEach(({ name }: any, index: number) => expect(name).toBe(`array[${index}]`));
}
}
}
});
TestParser.Case({
case: '8.1',
description: 'with name and bracketedObjectInputName === false',
given: {
parser: new ArrayParser(options8(false))
},
expected: {
parser: {
children({ value: items }: Scope) {
items.forEach(({ name }: any) => expect(name).toBe('array'));
}
}
}
});
TestParser.Case({
case: '9.0',
description: 'isEmpty() with an empty array',
given: {
parser: new ArrayParser({
schema: { type: 'array' }
})
},
expected: {
parser: {
isEmpty: ({ parser }: Scope) => expect(parser.isEmpty([])).toBeTruthy()
}
}
});
TestParser.Case({
case: '9.1',
description: 'isEmpty() with a non empty array',
given: {
parser: new ArrayParser({
schema: { type: 'array' }
})
},
expected: {
parser: {
isEmpty: ({ parser }: Scope) => expect(parser.isEmpty([ 1 ])).toBeFalsy()
}
}
});
TestParser.Case({
case: '9.2',
description: 'isEmpty() with default value',
given: {
parser: new ArrayParser({
schema: { type: 'array', default: [ 2 ] }
})
},
expected: {
parser: {
isEmpty: ({ parser }: Scope) => expect(parser.isEmpty()).toBeFalsy()
}
}
});
TestParser.Case({
case: '10',
description: 'field.deep validation',
given: {
parser: new ArrayParser(options8(true))
},
expected: {
parser: {
field: {
deep: ({ value }: Scope) => expect(value).toBe(0),
children({ value }: Scope) {
value.forEach(({ deep }: any) => expect(deep).toBe(1));
}
}
}
}
});
TestParser.Case({
case: '11.0',
description: 'parser.reset()',
given: {
parser() {
const model = [ 'arya' ];
const onChange = jest.fn();
const parser = new ArrayParser({ ...options4, model, onChange });
parser.parse();
return parser;
}
},
expected: {
parser: {
reset({ parser }: Scope) {
const onChange = parser.options.onChange;
const expected = [
[ 'arya' ],
[ 'jon' ]
];
expect(parser.rawValue).toEqual([ 'arya' ]);
expect(parser.model).toEqual([ 'arya' ]);
expect(onChange.mock.calls.length).toBe(1);
expect(onChange.mock.calls[0][0]).toEqual(expected[0]);
parser.field.children[0].setValue('jon');
expect(onChange.mock.calls.length).toBe(2);
expect(onChange.mock.calls[1][0]).toEqual(expected[1]);
expect(parser.rawValue).toEqual([ 'jon' ]);
expect(parser.model).toEqual([ 'jon' ]);
parser.reset(); // reset without calling onChange
expect(onChange.mock.calls.length).toBe(2);
expect(parser.initialValue).toEqual([ 'arya' ]);
expect(parser.rawValue).toEqual([ 'arya' ]);
expect(parser.model).toEqual([ 'arya' ]);
parser.field.reset(); // reset with calling onChange
expect(onChange.mock.calls.length).toBe(3);
expect(onChange.mock.calls[2][0]).toEqual(expected[0]);
}
}
}
});
TestParser.Case({
case: '12.0',
description: 'parser.clear()',
given: {
parser() {
const model = [ 'arya' ];
const onChange = jest.fn();
const parser = new ArrayParser({ ...options4, model, onChange });
parser.parse();
return parser;
}
},
expected: {
parser: {
clear({ parser }: Scope) {
const onChange = parser.options.onChange;
const expected = [
[ 'arya' ],
[ 'jon' ]
];
expect(parser.rawValue).toEqual([ 'arya' ]);
expect(parser.model).toEqual([ 'arya' ]);
expect(onChange.mock.calls.length).toBe(1);
expect(onChange.mock.calls[0][0]).toEqual(expected[0]);
parser.field.children[0].setValue('jon');
expect(onChange.mock.calls.length).toBe(2);
expect(onChange.mock.calls[1][0]).toEqual(expected[1]);
expect(parser.rawValue).toEqual([ 'jon' ]);
expect(parser.model).toEqual([ 'jon' ]);
parser.clear(); // clear without calling onChange
expect(onChange.mock.calls.length).toBe(2);
expect(parser.initialValue).toEqual([ 'arya' ]);
expect(parser.rawValue).toEqual([ undefined ]);
expect(parser.model).toEqual([]);
parser.field.clear(); // clear with calling onChange
expect(onChange.mock.calls.length).toBe(3);
expect(onChange.mock.calls[2][0]).toEqual([]);
}
}
}
});
TestParser.Case({
case: '13.0',
description: 'field.addItemValue()',
given: {
parser: new ArrayParser({
schema: {
type: 'array',
maxItems: 1,
items: { type: 'string', default: 'arya' }
},
model: []
})
},
expected: {
parser: {
field: {
addItemValue: ({ value: addItemValue, field }: Scope) => {
/**
* scenario: successfully add a new item
*/
expect(field.value).toEqual([]);
addItemValue('jon');
expect(field.value).toEqual([ 'jon' ]);
/**
* scenario: failed to add a new item when the push button is disabled
*/
expect(field.pushButton.disabled).toBeTruthy();
addItemValue('baryon');
expect(field.value).toEqual([ 'jon' ]);
}
}
}
}
});
}); | the_stack |
* @description 全局工具函数
* @author shuxiaokai
* @create 2021-06-15 22:55
*/
import { nanoid } from "nanoid/non-secure"
import type { ApidocHttpRequestMethod, ApidocProperty, ApidocPropertyType, ApidocDetail } from "@@/global"
import lodashIsEqual from "lodash/isEqual";
import lodashCloneDeep from "lodash/cloneDeep";
import lodashDebounce from "lodash/debounce";
import lodashThrottle from "lodash/throttle";
import dayjs from "dayjs";
import mitt from "mitt"
import tips from "./tips"
import Mock from "@/server/mock"
import { store } from "@/store/index"
type Data = Record<string, unknown>
/**
* 对象对比
*/
export const isEqual = lodashIsEqual;
/**
* 深拷贝
*/
export const cloneDeep = lodashCloneDeep;
/**
* 防抖函数
*/
export const debounce = lodashDebounce;
/**
* 节流函数
*/
export const throttle = lodashThrottle;
/**
* 全局事件订阅发布
*/
const emitter = mitt()
export const event = emitter;
/**
* @description 返回uuid
* @author shuxiaokai
* @create 2021-01-20 22:52
* @return {string} 返回uuid
*/
export function uuid(): string {
return nanoid();
}
/**
@description 返回变量类型
@author shuxiaokai
@create 2019-10-29 16:32"
@param {any} variable
@return 小写对象类型(null,number,string,boolean,symbol,function,object,array,regexp)
*/
export function getType(variable: unknown): string {
return Object.prototype.toString.call(variable).slice(8, -1).toLocaleLowerCase();
}
type ForestData = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[propName: string]: any,
}
/**
* @description 遍历森林(深度优先)
* @author shuxiaokai
* @create 2020-03-02 10:17
* @param {array} arrData 数组数据
* @param {function} fn 每次遍历执行得函数
* @param {string} childrenKey children对应字段
*/
export function forEachForest<T extends ForestData>(forest: T[], fn: (arg: T) => void, options?: { childrenKey?: string }): void {
if (!Array.isArray(forest)) {
throw new Error("第一个参数必须为数组类型");
}
const childrenKey = options?.childrenKey || "children";
const foo = (forestData: T[], hook: (arg: T) => void) => {
for (let i = 0; i < forestData.length; i += 1) {
const currentData = forestData[i];
hook(currentData);
if (!currentData[childrenKey]) {
// eslint-disable-next-line no-continue
continue;
}
if (!Array.isArray(currentData[childrenKey])) {
// eslint-disable-next-line no-continue
continue;
}
if ((currentData[childrenKey] as T[]).length > 0) {
foo(currentData[childrenKey] as T[], hook);
}
}
};
foo(forest, fn);
}
/**
* 根据id查询父元素
*/
export function findParentById<T extends ForestData>(forest: T[], id: string, options?: { childrenKey?: string, idKey?: string }): T | null {
if (!Array.isArray(forest)) {
throw new Error("第一个参数必须为数组类型");
}
const childrenKey = options?.childrenKey || "children";
const idKey = options?.idKey || "id";
let pNode: T | null = null;
let hasPNode = false;
const foo = (forestData: ForestData, deep: number) => {
for (let i = 0; i < forestData.length; i += 1) {
const currentData = forestData[i];
if (currentData[idKey] === id && deep !== 0) {
hasPNode = true;
break;
}
if (currentData[childrenKey] && currentData[childrenKey].length > 0) {
pNode = currentData;
foo(currentData[childrenKey], deep + 1);
}
}
};
foo(forest, 0);
if (hasPNode) {
return pNode;
}
return null;
}
/**
* 根据id查询下一个兄弟节点
*/
export function findNextSiblingById<T extends ForestData>(forest: T[], id: string, options?: { childrenKey?: string, idKey?: string }): T | null {
if (!Array.isArray(forest)) {
throw new Error("第一个参数必须为数组类型");
}
const childrenKey = options?.childrenKey || "children";
const idKey = options?.idKey || "id";
let nextSibling: T | null = null;
const foo = (forestData: ForestData) => {
for (let i = 0; i < forestData.length; i += 1) {
const currentData = forestData[i];
if (currentData[idKey] === id) {
nextSibling = forestData[i + 1]
break;
}
if (currentData[childrenKey] && currentData[childrenKey].length > 0) {
foo(currentData[childrenKey]);
}
}
};
foo(forest);
return nextSibling;
}
/**
* 根据id查询上一个兄弟节点
*/
export function findPreviousSiblingById<T extends ForestData>(forest: T[], id: string, options?: { childrenKey?: string, idKey?: string }): T | null {
if (!Array.isArray(forest)) {
throw new Error("第一个参数必须为数组类型");
}
const childrenKey = options?.childrenKey || "children";
const idKey = options?.idKey || "id";
let previousSibling: T | null = null;
const foo = (forestData: ForestData) => {
for (let i = 0; i < forestData.length; i += 1) {
const currentData = forestData[i];
if (currentData[idKey] === id) {
previousSibling = forestData[i - 1]
break;
}
if (currentData[childrenKey] && currentData[childrenKey].length > 0) {
foo(currentData[childrenKey]);
}
}
};
foo(forest);
return previousSibling;
}
/**
* 根据id查询元素
*/
export function findNodeById<T extends ForestData>(forest: T[], id: string, options?: { childrenKey?: string, idKey?: string }): T | null {
if (!Array.isArray(forest)) {
throw new Error("第一个参数必须为数组类型");
}
let result = null;
const childrenKey = options?.childrenKey || "children";
const idKey = options?.idKey || "id";
const foo = (forestData: ForestData) => {
for (let i = 0; i < forestData.length; i += 1) {
const currentData = forestData[i];
if (currentData[idKey] === id) {
result = currentData;
break;
}
if (currentData[childrenKey] && currentData[childrenKey].length > 0) {
foo(currentData[childrenKey]);
}
}
};
foo(forest);
return result;
}
type TreeNode<T> = {
children: T[],
};
/**
* 将树形数据所有节点转换为一维数组,数据会进行深拷贝
*/
export function flatTree<T extends TreeNode<T>>(root: T): T[] {
const result: T[] = [];
const foo = (nodes: T[]): void => {
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
const itemCopy = cloneDeep(item);
itemCopy.children = [];
result.push(itemCopy);
if (item.children && item.children.length > 0) {
foo(item.children);
}
}
}
foo([root]);
return result;
}
/**
* 获取字符串宽度
*/
export function getTextWidth(text: string, font: string): number {
let canvas: HTMLCanvasElement | null = document.createElement("canvas");
const context = canvas.getContext("2d");
(context as CanvasRenderingContext2D).font = font;
const metrics = (context as CanvasRenderingContext2D).measureText(text);
canvas = null;
return metrics.width;
}
/**
* 获取提示信息
*/
export function randomTip(): string {
const len = tips.length;
const randomIndex = Math.ceil(Math.random() * len) - 1;
return tips[randomIndex];
}
/**
* 格式化时间
*/
export function formatDate(date: string | number | Date | dayjs.Dayjs | undefined, rule?: string): string {
const realRule = rule || "YYYY-MM-DD HH:mm"
const result = dayjs(date).format(realRule);
return result;
}
/**
@description 将数组对象[{id: 1}]根据指定的key值进行去重,key值对应的数组元素不存在则直接过滤掉,若不传入id则默认按照set形式进行去重。
@create 2019-11-20 22:40
@update 2019-11-20 22:42
@param {array} array 需要处理的数组
@param {string?} key 指定对象数组的去重依据
@return {Array} 返回一个去重后的新数组,不会改变原数组
@example
unique([{id: 1}, {id: 2}, {id: 1}], "id") => [{id: 1}, {id: 2}]
unique([{id: 1}, {id: 2}, {id: 1}]) => [{id: 1}, {id: 2}, {id: 1}]
unique([{id: 1}, {}, {id: 1}]) => [{id: 1}, {id: 2}, {id: 1}]
unique([1, 2, 3, 4, 3, 3]) => [1, 2, 3, 4]
*/
export function uniqueByKey<T extends Data, K extends keyof T>(data: T[], key: K): T[] {
const result: T[] = [];
for (let i = 0, len = data.length; i < len; i += 1) {
const isInResult = result.find((val) => val[key] === data[i][key]);
if (data[i][key] != null && !isInResult) {
result.push(data[i]);
}
}
return result;
}
/**
* 获取请求方法
*/
export function getRequestMethodEnum(): ApidocHttpRequestMethod[] {
return ["GET", "POST", "PUT", "DELETE", "TRACE", "OPTIONS", "PATCH", "HEAD"];
}
/**
* 生成一条接口参数
*/
export function apidocGenerateProperty<T extends ApidocPropertyType = "string">(type?: T): ApidocProperty<T> {
const result = {
_id: uuid(),
key: "",
type: type || "string",
description: "",
value: "",
required: true,
select: true,
children: [],
editor: "",
editorId: "",
};
return result as ApidocProperty<T>;
}
/*
|--------------------------------------------------------------------------
|--------------------------------------------------------------------------
|
*/
type Properties = ApidocProperty<ApidocPropertyType>[]
type PropertyValueHook = (value: ApidocProperty) => string | number | boolean;
// eslint-disable-next-line no-use-before-define
type JSON = string | number | boolean | null | JsonObj | JsonArr
type JsonConvertHook = (property: ApidocProperty<ApidocPropertyType>, itemData: JSON) => void;
type JsonArr = JSON[]
type JsonObj = {
[x: string]: JSON
}
type JsonValueType = "string" | "number" | "boolean" | "array" | "object"
type ConvertToObjectOptions = {
result: Record<string, JSON> | JSON[],
valueHook?: PropertyValueHook,
jumpChecked?: boolean,
parent: ApidocProperty<ApidocPropertyType>
}
/**
* @description apidoc转换value值
* @author shuxiaokai
* @create 2021-8-26 21:56
* @param {string} value - 需要转换的值
* @return {String} 返回转换后的字符串
* @remark 这个方法具有强耦合性
*/
export function apidocConvertValue(value: string): string {
const matchdVariable = value.toString().match(/\{\{\s*([^} ]+)\s*\}\}/);
const allVariables = store.state["apidoc/baseInfo"].variables;
if (value.toString().startsWith("@")) {
return Mock.mock(value);
}
if (matchdVariable) {
const varInfo = allVariables.find((v) => v.name === matchdVariable[1]);
return varInfo?.value || value;
}
return value;
}
function convertToJson(properties: Properties, options: ConvertToObjectOptions): void {
const { result, parent, jumpChecked, valueHook } = options;
for (let i = 0; i < properties.length; i += 1) {
const property = properties[i];
const { type, value, key, children } = property;
const isParentArray = (parent && parent.type === "array");
const isComplex = (type === "object" || type === "array" || type === "file");
const keyValIsEmpty = key === "" && value === ""
if (jumpChecked && !property.select) { //过滤掉_select属性为false的值
continue;
}
if (!isParentArray && !isComplex && (key === "")) { //父元素不为数组并且也不是复杂数据类型
continue
}
if (!isParentArray && isComplex && (key === "")) { //对象下面对象必须具备key
continue
}
if (isParentArray && keyValIsEmpty && type === "number") { //数组下面为数字
continue
}
if (isParentArray && keyValIsEmpty && type === "boolean") { //数组下面为布尔值
continue
}
const convertValue = valueHook ? valueHook(property) : apidocConvertValue(value);
if (isParentArray) { //父元素为数组
if (type === "boolean") {
(result as JSON[]).push(convertValue === "true");
} else if (type === "string") {
(result as JSON[]).push(convertValue);
} else if (type === "number") {
const isNumber = !Number.isNaN(Number(convertValue));
if (isNumber) {
(result as JSON[]).push(Number(convertValue));
} else {
console.warn("参数无法被转换为数字类型,默认为0");
(result as JSON[]).push(0);
}
} else if (type === "file") {
console.warn("不允许为file类型");
(result as JSON[]).push(convertValue);
} else if (type === "object") {
const pushData = {};
(result as JSON[]).push(pushData);
convertToJson(children, {
result: pushData,
valueHook,
jumpChecked,
parent: property
})
} else if (type === "array") {
const pushData: JSON[] = [];
(result as JSON[]).push(pushData);
convertToJson(children, {
result: pushData,
valueHook,
jumpChecked,
parent: property
})
}
} else { //父元素为对象
if (type === "boolean") {
(result as Record<string, JSON>)[key] = convertValue === "true";
} else if (type === "string") {
(result as Record<string, JSON>)[key] = convertValue;
} else if (type === "number") {
const isNumber = !Number.isNaN(Number(convertValue));
if (isNumber) {
(result as Record<string, JSON>)[key] = Number(convertValue);
} else {
console.warn("参数无法被转换为数字类型,默认为0");
(result as Record<string, JSON>)[key] = 0;
}
} else if (type === "file") {
console.warn("不允许为file类型");
(result as Record<string, JSON>)[key] = convertValue;
} else if (type === "object") {
(result as Record<string, JSON>)[key] = {};
convertToJson(children, {
result: (result as Record<string, JSON>)[key] as Record<string, JSON>,
valueHook,
jumpChecked,
parent: property
})
} else if (type === "array") {
(result as Record<string, JSON>)[key] = [];
convertToJson(children, {
result: (result as Record<string, JSON>)[key] as JSON[],
valueHook,
jumpChecked,
parent: property
})
}
}
}
}
/**
* @description 获取property字段类型
* @author shuxiaokai
* @create 2021-8-29 13:38
* @param {any} value - 任意类型变量
* @return {string} 返回参数类型
*/
function getJsonValueType(value: unknown): JsonValueType {
let result: JsonValueType = "string";
if (typeof value === "string") {
result = "string"
} else if (typeof value === "number") { //NaN
result = "number"
} else if (typeof value === "boolean") {
result = "boolean"
} else if (Array.isArray(value)) {
result = "array"
} else if (typeof value === "object" && value !== null) {
result = "object"
} else { // undefined ...
result = "string"
}
return result;
}
/**
* 将录入参数转换为json参数
*/
export function apidocConvertParamsToJsonData(properties: Properties, jumpChecked?: boolean, valueHook?: PropertyValueHook): JSON {
if (properties.length === 0) {
console.warn("无任何参数值")
return null;
}
const rootType = properties[0].type;
const rootValue = properties[0].value;
if (rootType === "boolean") {
return rootValue === "true";
}
if (rootType === "string") {
return rootValue;
}
if (rootType === "number") {
const isNumber = !Number.isNaN(Number(rootValue));
if (isNumber) {
return Number(rootValue);
}
console.warn("参数无法被转换为数字类型,默认为0");
return 0;
}
if (rootType === "file") {
console.warn("根元素不允许为file");
return null;
}
if (rootType === "object") {
const resultJson = {};
const data = properties[0].children;
if (data.every((p) => !p.key)) {
return null;
}
convertToJson(properties[0].children, {
result: resultJson,
valueHook,
jumpChecked,
parent: properties[0]
});
return resultJson
}
if (rootType === "array") {
const resultJson: JSON[] = [];
const data = properties[0].children;
if (data.every((p) => ((p.type === "number" && p.value === "") || (p.type === "boolean" && p.value === "")))) {
return null;
}
convertToJson(properties[0].children, {
result: resultJson,
valueHook,
jumpChecked,
parent: properties[0]
});
return resultJson
}
return {};
}
/**
* 将json类型数据转换为moyu类型参数
*/
export function apidocConvertJsonDataToParams(jsonData: JSON, hook?: PropertyValueHook): Properties {
const globalResult = [];
const rootType = getJsonValueType(jsonData);
if (rootType === "object" || rootType === "array") {
const rootProperty = apidocGenerateProperty(rootType);
globalResult.push(rootProperty);
// eslint-disable-next-line no-shadow
const foo = (obj: JSON, { result, deep, hook }: { result: Properties, deep: number, hook?: JsonConvertHook }) => {
if (getJsonValueType(obj) === "object") {
Object.keys(obj as JsonObj).forEach((key) => {
const itemValue = (obj as JsonObj)[key];
const itemType = getJsonValueType(itemValue);
if (itemType === "string" || itemType === "number" || itemType === "boolean") {
const property = apidocGenerateProperty(itemType);
property.key = key;
property.value = itemValue == null ? "null" : itemValue.toString();
if (hook) {
hook(property, itemValue);
}
result.push(property);
} else if (itemType === "object") {
const property = apidocGenerateProperty(itemType);
property.key = key;
if (hook) {
hook(property, itemValue);
}
result.push(property);
foo(itemValue, {
result: property.children,
deep: deep + 1,
hook,
});
} else if (itemType === "array") {
// eslint-disable-next-line no-shadow
const itemValue = (obj as JsonObj)[key] as JsonArr
const property = apidocGenerateProperty(itemType);
property.key = key;
if (hook) {
hook(property, itemValue);
}
result.push(property);
if (getJsonValueType(itemValue[0]) === "object") {
const property2 = apidocGenerateProperty("object");
property.children.push(property2)
foo(itemValue[0], {
result: property.children[0].children,
deep: deep + 1,
hook,
});
} else {
foo(itemValue[0], {
result: property.children,
deep: deep + 1,
hook,
});
}
}
});
} else {
const valueType = getJsonValueType(obj);
const property = apidocGenerateProperty(valueType);
result.push(property)
}
}
foo(jsonData, {
result: rootProperty.children,
deep: 1,
hook,
});
} else {
const rootProperty = apidocGenerateProperty(rootType);
globalResult.push(rootProperty);
}
return globalResult;
}
/**
* @description 生成一份apidoc默认值
* @author shuxiaokai
* @create 2021-09-07 22:35
*/
export function apidocGenerateApidoc(): ApidocDetail {
return {
_id: "",
pid: "",
projectId: "",
isFolder: false,
sort: 0,
info: {
name: "",
description: "",
version: "",
type: "api",
tag: {
_id: "",
name: "",
color: "",
},
creator: "",
maintainer: "",
deletePerson: "",
spendTime: 0,
},
item: {
method: "GET",
url: {
host: "",
path: "",
},
paths: [],
queryParams: [],
requestBody: {
mode: "json",
json: [],
formdata: [],
urlencoded: [],
raw: {
data: "",
dataType: "text/plain"
},
file: {
src: "",
},
},
responseParams: [{
title: "成功返回",
statusCode: 200,
value: {
file: {
url: "",
raw: ""
},
json: [],
dataType: "application/json",
text: ""
}
}],
headers: [],
contentType: "",
},
}
}
/**
* @description 将byte转换为易读单位
* @author shuxiaokai
* @create 2020-10-26 21:56
* @param {number} byteNum - 字节数量
* @return {String} 返回字符串
*/
export function formatBytes(byteNum: number): string {
let result = "";
if (!byteNum) {
return "";
}
if (byteNum > 0 && byteNum < 1024) {
//b
result = `${byteNum}B`;
} else if (byteNum >= 1024 && byteNum < 1024 * 1024) {
//KB
result = `${(byteNum / 1024).toFixed(2)}KB`;
} else if (byteNum >= 1024 * 1024 && byteNum < 1024 * 1024 * 1024) {
//MB
result = `${(byteNum / 1024 / 1024).toFixed(2)}MB`;
} else if (byteNum >= 1024 * 1024 * 1024 && byteNum < 1024 * 1024 * 1024 * 1024) {
//GB
result = `${(byteNum / 1024 / 1024 / 1024).toFixed(2)}GB`;
}
return result;
}
/**
* @description 将毫秒转换为易读单位
* @author shuxiaokai
* @create 2020-10-26 21:56
* @param {number} ms - 毫秒
* @return {String} 返回字符串
*/
export function formatMs(ms: number): string {
let result = "";
if (!ms) {
return "";
}
if (ms > 0 && ms < 1000) { //毫秒
result = `${ms}ms`;
} else if (ms >= 1000 && ms < 1000 * 60) { //秒
result = `${(ms / 1000).toFixed(2)}s`;
} else if (ms >= 1000 * 60) { //分钟
result = `${(ms / 1000 / 60).toFixed(2)}m`;
}
return result;
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [access-analyzer](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiamaccessanalyzer.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class AccessAnalyzer extends PolicyStatement {
public servicePrefix = 'access-analyzer';
/**
* Statement provider for service [access-analyzer](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiamaccessanalyzer.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 apply an archive rule
*
* Access Level: Write
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_ApplyArchiveRule.html
*/
public toApplyArchiveRule() {
return this.to('ApplyArchiveRule');
}
/**
* Grants permission to cancel a policy generation
*
* Access Level: Write
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_CancelPolicyGeneration.html
*/
public toCancelPolicyGeneration() {
return this.to('CancelPolicyGeneration');
}
/**
* Grants permission to create an access preview for the specified analyzer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_CreateAccessPreview.html
*/
public toCreateAccessPreview() {
return this.to('CreateAccessPreview');
}
/**
* Grants permission to create an analyzer
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* Dependent actions:
* - iam:CreateServiceLinkedRole
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_CreateAnalyzer.html
*/
public toCreateAnalyzer() {
return this.to('CreateAnalyzer');
}
/**
* Grants permission to create an archive rule for the specified analyzer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_CreateArchiveRule.html
*/
public toCreateArchiveRule() {
return this.to('CreateArchiveRule');
}
/**
* Grants permission to delete the specified analyzer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_DeleteAnalyzer.html
*/
public toDeleteAnalyzer() {
return this.to('DeleteAnalyzer');
}
/**
* Grants permission to delete archive rules for the specified analyzer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_DeleteArchiveRule.html
*/
public toDeleteArchiveRule() {
return this.to('DeleteArchiveRule');
}
/**
* Grants permission to retrieve information about an access preview
*
* Access Level: Read
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_GetAccessPreview.html
*/
public toGetAccessPreview() {
return this.to('GetAccessPreview');
}
/**
* Grants permission to retrieve information about an analyzed resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_GetAnalyzedResource.html
*/
public toGetAnalyzedResource() {
return this.to('GetAnalyzedResource');
}
/**
* Grants permission to retrieve information about analyzers
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_GetAnalyzer.html
*/
public toGetAnalyzer() {
return this.to('GetAnalyzer');
}
/**
* Grants permission to retrieve information about archive rules for the specified analyzer
*
* Access Level: Read
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_GetArchiveRule.html
*/
public toGetArchiveRule() {
return this.to('GetArchiveRule');
}
/**
* Grants permission to retrieve findings
*
* Access Level: Read
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_GetFinding.html
*/
public toGetFinding() {
return this.to('GetFinding');
}
/**
* Grants permission to retrieve a policy that was generated using StartPolicyGeneration
*
* Access Level: Read
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_GetGeneratedPolicy.html
*/
public toGetGeneratedPolicy() {
return this.to('GetGeneratedPolicy');
}
/**
* Grants permission to retrieve a list of findings from an access preview
*
* Access Level: Read
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_ListAccessPreviewFindings.html
*/
public toListAccessPreviewFindings() {
return this.to('ListAccessPreviewFindings');
}
/**
* Grants permission to retrieve a list of access previews
*
* Access Level: List
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_ListAccessPreviews.html
*/
public toListAccessPreviews() {
return this.to('ListAccessPreviews');
}
/**
* Grants permission to retrieve a list of resources that have been analyzed
*
* Access Level: Read
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_ListAnalyzedResources.html
*/
public toListAnalyzedResources() {
return this.to('ListAnalyzedResources');
}
/**
* Grants permission to retrieves a list of analyzers
*
* Access Level: List
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_ListAnalyzers.html
*/
public toListAnalyzers() {
return this.to('ListAnalyzers');
}
/**
* Grants permission to retrieve a list of archive rules from an analyzer
*
* Access Level: List
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_ListArchiveRules.html
*/
public toListArchiveRules() {
return this.to('ListArchiveRules');
}
/**
* Grants permission to retrieve a list of findings from an analyzer
*
* Access Level: Read
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_ListFindings.html
*/
public toListFindings() {
return this.to('ListFindings');
}
/**
* Grants permission to list all the recently started policy generations
*
* Access Level: Read
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_ListPolicyGenerations.html
*/
public toListPolicyGenerations() {
return this.to('ListPolicyGenerations');
}
/**
* Grants permission to retrieve a list of tags applied to a resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to start a policy generation
*
* Access Level: Write
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_StartPolicyGeneration.html
*/
public toStartPolicyGeneration() {
return this.to('StartPolicyGeneration');
}
/**
* Grants permission to start a scan of the policies applied to a resource
*
* Access Level: Write
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_StartResourceScan.html
*/
public toStartResourceScan() {
return this.to('StartResourceScan');
}
/**
* Grants permission to add a tag to a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to remove a tag from a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to modify an archive rule
*
* Access Level: Write
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_UpdateArchiveRule.html
*/
public toUpdateArchiveRule() {
return this.to('UpdateArchiveRule');
}
/**
* Grants permission to modify findings
*
* Access Level: Write
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_UpdateFindings.html
*/
public toUpdateFindings() {
return this.to('UpdateFindings');
}
/**
* Grants permission to validate a policy
*
* Access Level: Read
*
* https://docs.aws.amazon.com/access-analyzer/latest/APIReference/API_ValidatePolicy.html
*/
public toValidatePolicy() {
return this.to('ValidatePolicy');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"ApplyArchiveRule",
"CancelPolicyGeneration",
"CreateAccessPreview",
"CreateAnalyzer",
"CreateArchiveRule",
"DeleteAnalyzer",
"DeleteArchiveRule",
"StartPolicyGeneration",
"StartResourceScan",
"UpdateArchiveRule",
"UpdateFindings"
],
"Read": [
"GetAccessPreview",
"GetAnalyzedResource",
"GetAnalyzer",
"GetArchiveRule",
"GetFinding",
"GetGeneratedPolicy",
"ListAccessPreviewFindings",
"ListAnalyzedResources",
"ListFindings",
"ListPolicyGenerations",
"ListTagsForResource",
"ValidatePolicy"
],
"List": [
"ListAccessPreviews",
"ListAnalyzers",
"ListArchiveRules"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type Analyzer to the statement
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-getting-started.html#permission-resources
*
* @param analyzerName - Identifier for the analyzerName.
* @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 onAnalyzer(analyzerName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}';
arn = arn.replace('${AnalyzerName}', analyzerName);
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 ArchiveRule to the statement
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-getting-started.html#permission-resources
*
* @param analyzerName - Identifier for the analyzerName.
* @param ruleName - Identifier for the ruleName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onArchiveRule(analyzerName: string, ruleName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}';
arn = arn.replace('${AnalyzerName}', analyzerName);
arn = arn.replace('${RuleName}', ruleName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import { Array } from "@siteimprove/alfa-array";
import { Equatable } from "@siteimprove/alfa-equatable";
import { Future } from "@siteimprove/alfa-future";
import { Iterable } from "@siteimprove/alfa-iterable";
import { List } from "@siteimprove/alfa-list";
import { None, Option } from "@siteimprove/alfa-option";
import { Record } from "@siteimprove/alfa-record";
import { Result } from "@siteimprove/alfa-result";
import { Sequence } from "@siteimprove/alfa-sequence";
import * as earl from "@siteimprove/alfa-earl";
import * as json from "@siteimprove/alfa-json";
import * as sarif from "@siteimprove/alfa-sarif";
import { Cache } from "./cache";
import { Diagnostic } from "./diagnostic";
import { Interview } from "./interview";
import { Oracle } from "./oracle";
import { Outcome } from "./outcome";
import { Requirement } from "./requirement";
import { Tag } from "./tag";
const { flatMap, flatten, reduce } = Iterable;
/**
* @public
*/
export abstract class Rule<I = unknown, T = unknown, Q = never, S = T>
implements
Equatable,
json.Serializable<Rule.JSON>,
earl.Serializable<Rule.EARL>,
sarif.Serializable<sarif.ReportingDescriptor>
{
protected readonly _uri: string;
protected readonly _requirements: Array<Requirement>;
protected readonly _tags: Array<Tag>;
protected readonly _evaluate: Rule.Evaluate<I, T, Q, S>;
protected constructor(
uri: string,
requirements: Array<Requirement>,
tags: Array<Tag>,
evaluator: Rule.Evaluate<I, T, Q, S>
) {
this._uri = uri;
this._requirements = requirements;
this._tags = tags;
this._evaluate = evaluator;
}
public get uri(): string {
return this._uri;
}
public get requirements(): ReadonlyArray<Requirement> {
return this._requirements;
}
public get tags(): ReadonlyArray<Tag> {
return this._tags;
}
public hasRequirement(requirement: Requirement): boolean {
return Array.includes(this._requirements, requirement);
}
public hasTag(tag: Tag): boolean {
return Array.includes(this._tags, tag);
}
public evaluate(
input: I,
oracle: Oracle<I, T, Q, S> = () => Future.now(None),
outcomes: Cache = Cache.empty()
): Future<Iterable<Outcome<I, T, Q, S>>> {
return this._evaluate(input, oracle, outcomes);
}
public equals<I, T, Q, S>(value: Rule<I, T, Q, S>): boolean;
public equals(value: unknown): value is this;
public equals(value: unknown): boolean {
return value instanceof Rule && value._uri === this._uri;
}
public abstract toJSON(): Rule.JSON;
public toEARL(): Rule.EARL {
return {
"@context": {
earl: "http://www.w3.org/ns/earl#",
dct: "http://purl.org/dc/terms/",
},
"@type": ["earl:TestCriterion", "earl:TestCase"],
"@id": this._uri,
"dct:isPartOf": {
"@set": this._requirements.map((requirement) => requirement.toEARL()),
},
};
}
public toSARIF(): sarif.ReportingDescriptor {
return {
id: this._uri,
helpUri: this._uri,
};
}
}
/**
* @public
*/
export namespace Rule {
export interface JSON {
[key: string]: json.JSON;
type: string;
uri: string;
requirements: Array<Requirement.JSON>;
tags: Array<Tag.JSON>;
}
export interface EARL extends earl.EARL {
"@context": {
earl: "http://www.w3.org/ns/earl#";
dct: "http://purl.org/dc/terms/";
};
"@type": ["earl:TestCriterion", "earl:TestCase"];
"@id": string;
"dct:isPartOf": {
"@set": Array<Requirement.EARL>;
};
}
export type Input<R> = R extends Rule<infer I, any, any, any> ? I : never;
export type Target<R> = R extends Rule<any, infer T, any, any> ? T : never;
export type Question<R> = R extends Rule<any, any, infer Q, any> ? Q : never;
export type Subject<R> = R extends Rule<any, any, any, infer S> ? S : never;
export function isRule<I, T, Q, S>(
value: unknown
): value is Rule<I, T, Q, S> {
return value instanceof Rule;
}
/**
* @remarks
* We use a short-lived cache during audits for rules to store their outcomes.
* It effectively acts as a memoization layer on top of each rule evaluation
* procedure, which comes in handy when dealing with composite rules that are
* dependant on the outcomes of other rules. There are several ways in which
* audits of such rules can be performed:
*
* 1. Put the onus on the caller to construct an audit with dependency-ordered
* rules. This is just crazy.
*
* 2. Topologically sort rules based on their dependencies before performing
* an audit. This requires graph operations.
*
* 3. Disregard order entirely and simply run rule evaluation procedures as
* their outcomes are needed, thereby risking repeating some of these
* procedures. This requires nothing.
*
* Given that 3. is the simpler, and non-crazy, approach, we can use this
* approach in combination with memoization to avoid the risk of repeating
* rule evaluation procedures.
*/
export interface Evaluate<I, T, Q, S> {
(input: Readonly<I>, oracle: Oracle<I, T, Q, S>, outcomes: Cache): Future<
Iterable<Outcome<I, T, Q, S>>
>;
}
export class Atomic<I = unknown, T = unknown, Q = never, S = T> extends Rule<
I,
T,
Q,
S
> {
public static of<I, T = unknown, Q = never, S = T>(properties: {
uri: string;
requirements?: Iterable<Requirement>;
tags?: Iterable<Tag>;
evaluate: Atomic.Evaluate<I, T, Q, S>;
}): Atomic<I, T, Q, S> {
return new Atomic(
properties.uri,
Array.from(properties.requirements ?? []),
Array.from(properties.tags ?? []),
properties.evaluate
);
}
private constructor(
uri: string,
requirements: Array<Requirement>,
tags: Array<Tag>,
evaluate: Atomic.Evaluate<I, T, Q, S>
) {
super(uri, requirements, tags, (input, oracle, outcomes) =>
outcomes.get(this, () => {
const { applicability, expectations } = evaluate(input);
return Future.traverse(applicability(), (interview) =>
Interview.conduct(interview, this, oracle).map((target) =>
target.flatMap((target) =>
Option.isOption(target) ? target : Option.of(target)
)
)
)
.map((targets) => Sequence.from(flatten<T>(targets)))
.flatMap<Iterable<Outcome<I, T, Q, S>>>((targets) => {
if (targets.isEmpty()) {
return Future.now([Outcome.Inapplicable.of(this)]);
}
return Future.traverse(targets, (target) =>
resolve(target, Record.of(expectations(target)), this, oracle)
);
});
})
);
}
public toJSON(): Atomic.JSON {
return {
type: "atomic",
uri: this._uri,
requirements: this._requirements.map((requirement) =>
requirement.toJSON()
),
tags: this._tags.map((tag) => tag.toJSON()),
};
}
}
export namespace Atomic {
export interface JSON extends Rule.JSON {
type: "atomic";
}
export interface Evaluate<I, T, Q, S> {
(input: I): {
applicability(): Iterable<Interview<Q, S, T, Option.Maybe<T>>>;
expectations(target: T): {
[key: string]: Interview<Q, S, T, Option.Maybe<Result<Diagnostic>>>;
};
};
}
}
export function isAtomic<I, T, Q, S>(
value: Rule<I, T, Q, S>
): value is Atomic<I, T, Q, S>;
export function isAtomic<I, T, Q, S>(
value: unknown
): value is Atomic<I, T, Q, S>;
export function isAtomic<I, T, Q, S>(
value: unknown
): value is Atomic<I, T, Q, S> {
return value instanceof Atomic;
}
export class Composite<
I = unknown,
T = unknown,
Q = never,
S = T
> extends Rule<I, T, Q, S> {
public static of<I, T = unknown, Q = never, S = T>(properties: {
uri: string;
requirements?: Iterable<Requirement>;
tags?: Iterable<Tag>;
composes: Iterable<Rule<I, T, Q, S>>;
evaluate: Composite.Evaluate<I, T, Q, S>;
}): Composite<I, T, Q, S> {
return new Composite(
properties.uri,
Array.from(properties.requirements ?? []),
Array.from(properties.tags ?? []),
Array.from(properties.composes),
properties.evaluate
);
}
private readonly _composes: Array<Rule<I, T, Q, S>>;
private constructor(
uri: string,
requirements: Array<Requirement>,
tags: Array<Tag>,
composes: Array<Rule<I, T, Q, S>>,
evaluate: Composite.Evaluate<I, T, Q, S>
) {
super(uri, requirements, tags, (input, oracle, outcomes) =>
outcomes.get(this, () =>
Future.traverse(this._composes, (rule) =>
rule.evaluate(input, oracle, outcomes)
)
.map((outcomes) =>
Sequence.from(
flatMap(outcomes, function* (outcomes) {
for (const outcome of outcomes) {
if (Outcome.isApplicable(outcome)) {
yield outcome;
}
}
})
)
)
.flatMap<Iterable<Outcome<I, T, Q, S>>>((targets) => {
if (targets.isEmpty()) {
return Future.now([Outcome.Inapplicable.of(this)]);
}
const { expectations } = evaluate(input);
return Future.traverse(
targets.groupBy((outcome) => outcome.target),
([target, outcomes]) =>
resolve(
target,
Record.of(expectations(outcomes)),
this,
oracle
)
);
})
)
);
this._composes = composes;
}
public get composes(): ReadonlyArray<Rule<I, T, Q, S>> {
return this._composes;
}
public toJSON(): Composite.JSON {
return {
type: "composite",
uri: this._uri,
requirements: this._requirements.map((requirement) =>
requirement.toJSON()
),
tags: this._tags.map((tag) => tag.toJSON()),
composes: this._composes.map((rule) => rule.toJSON()),
};
}
}
export namespace Composite {
export interface JSON extends Rule.JSON {
type: "composite";
uri: string;
composes: Array<Rule.JSON>;
}
export interface Evaluate<I, T, Q, S> {
(input: I): {
expectations(outcomes: Sequence<Outcome.Applicable<I, T, Q, S>>): {
[key: string]: Interview<Q, S, T, Option.Maybe<Result<Diagnostic>>>;
};
};
}
}
export function isComposite<I, T, Q>(
value: Rule<I, T, Q>
): value is Composite<I, T, Q>;
export function isComposite<I, T, Q>(
value: unknown
): value is Composite<I, T, Q>;
export function isComposite<I, T, Q>(
value: unknown
): value is Composite<I, T, Q> {
return value instanceof Composite;
}
}
function resolve<I, T, Q, S>(
target: T,
expectations: Record<{
[key: string]: Interview<Q, S, T, Option.Maybe<Result<Diagnostic>>>;
}>,
rule: Rule<I, T, Q, S>,
oracle: Oracle<I, T, Q, S>
): Future<Outcome.Applicable<I, T, Q, S>> {
return Future.traverse(expectations, ([id, interview]) =>
Interview.conduct(interview, rule, oracle).map(
(expectation) => [id, expectation] as const
)
).map((expectations) =>
reduce(
expectations,
(expectations, [id, expectation]) =>
expectations.flatMap((expectations) =>
expectation.map((expectation) =>
expectations.append([
id,
Option.isOption(expectation)
? expectation
: Option.of(expectation),
])
)
),
Option.of(List.empty<[string, Option<Result<Diagnostic>>]>())
)
.map((expectations) => {
return Outcome.from(rule, target, Record.from(expectations));
})
.getOrElse(() => {
return Outcome.CantTell.of(rule, target);
})
);
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.